mirror of
https://github.com/lissy93/networking-toolbox.git
synced 2026-11-25 15:15:27 +03:00
Creates lang switching functionality
This commit is contained in:
1 parent
f76f3d0bea
commit
68e09fbbaf
222 files changed
+42553
-50
No files matched your search
@@ -0,0 +1,309 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Translation Validation Script
|
||||
*
|
||||
* Validates translation files by:
|
||||
* - Checking for missing keys compared to English (source)
|
||||
* - Detecting extra keys that don't exist in source
|
||||
* - Finding empty translation values
|
||||
* - Reporting coverage statistics
|
||||
*
|
||||
* Usage:
|
||||
* npm run check-translations
|
||||
* npm run check-translations -- --verbose
|
||||
* npm run check-translations -- --lang=de
|
||||
*/
|
||||
|
||||
import { readFileSync, readdirSync, existsSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const TRANSLATIONS_DIR = join(__dirname, '../src/lib/i18n/translations');
|
||||
const SOURCE_LANG = 'en';
|
||||
|
||||
interface TranslationObject {
|
||||
[key: string]: string | TranslationObject;
|
||||
}
|
||||
|
||||
interface ValidationResult {
|
||||
lang: string;
|
||||
namespace: string;
|
||||
missing: string[];
|
||||
extra: string[];
|
||||
empty: string[];
|
||||
total: number;
|
||||
translated: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively flatten nested object into dot-notation keys
|
||||
*/
|
||||
function flattenKeys(obj: TranslationObject, prefix = ''): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const fullKey = prefix ? `${prefix}.${key}` : key;
|
||||
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
Object.assign(result, flattenKeys(value, fullKey));
|
||||
} else {
|
||||
result[fullKey] = String(value);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and parse a translation file
|
||||
*/
|
||||
function loadTranslation(lang: string, namespace: string): Record<string, string> | null {
|
||||
const filePath = join(TRANSLATIONS_DIR, lang, `${namespace}.json`);
|
||||
|
||||
if (!existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
return flattenKeys(parsed);
|
||||
} catch (error) {
|
||||
console.error(`Error parsing ${filePath}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all available namespaces from source language
|
||||
*/
|
||||
function getNamespaces(): string[] {
|
||||
const sourcePath = join(TRANSLATIONS_DIR, SOURCE_LANG);
|
||||
|
||||
if (!existsSync(sourcePath)) {
|
||||
throw new Error(`Source language directory not found: ${sourcePath}`);
|
||||
}
|
||||
|
||||
return readdirSync(sourcePath)
|
||||
.filter(file => file.endsWith('.json'))
|
||||
.map(file => file.replace('.json', ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all available languages
|
||||
*/
|
||||
function getLanguages(): string[] {
|
||||
if (!existsSync(TRANSLATIONS_DIR)) {
|
||||
throw new Error(`Translations directory not found: ${TRANSLATIONS_DIR}`);
|
||||
}
|
||||
|
||||
return readdirSync(TRANSLATIONS_DIR, { withFileTypes: true })
|
||||
.filter(dirent => dirent.isDirectory())
|
||||
.map(dirent => dirent.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single language namespace against source
|
||||
*/
|
||||
function validateNamespace(lang: string, namespace: string): ValidationResult {
|
||||
const source = loadTranslation(SOURCE_LANG, namespace);
|
||||
const target = loadTranslation(lang, namespace);
|
||||
|
||||
if (!source) {
|
||||
throw new Error(`Source translation not found: ${SOURCE_LANG}/${namespace}.json`);
|
||||
}
|
||||
|
||||
const result: ValidationResult = {
|
||||
lang,
|
||||
namespace,
|
||||
missing: [],
|
||||
extra: [],
|
||||
empty: [],
|
||||
total: Object.keys(source).length,
|
||||
translated: 0,
|
||||
};
|
||||
|
||||
if (!target) {
|
||||
// Entire namespace is missing
|
||||
result.missing = Object.keys(source);
|
||||
return result;
|
||||
}
|
||||
|
||||
const sourceKeys = new Set(Object.keys(source));
|
||||
const targetKeys = new Set(Object.keys(target));
|
||||
|
||||
// Find missing keys
|
||||
for (const key of sourceKeys) {
|
||||
if (!targetKeys.has(key)) {
|
||||
result.missing.push(key);
|
||||
} else if (target[key].trim() === '') {
|
||||
result.empty.push(key);
|
||||
} else {
|
||||
result.translated++;
|
||||
}
|
||||
}
|
||||
|
||||
// Find extra keys
|
||||
for (const key of targetKeys) {
|
||||
if (!sourceKeys.has(key)) {
|
||||
result.extra.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format validation results
|
||||
*/
|
||||
function formatResults(results: ValidationResult[], verbose: boolean): string {
|
||||
let output = '';
|
||||
|
||||
// Group by language
|
||||
const byLang = results.reduce((acc, r) => {
|
||||
if (!acc[r.lang]) acc[r.lang] = [];
|
||||
acc[r.lang].push(r);
|
||||
return acc;
|
||||
}, {} as Record<string, ValidationResult[]>);
|
||||
|
||||
for (const [lang, langResults] of Object.entries(byLang)) {
|
||||
const totalKeys = langResults.reduce((sum, r) => sum + r.total, 0);
|
||||
const translatedKeys = langResults.reduce((sum, r) => sum + r.translated, 0);
|
||||
const missingKeys = langResults.reduce((sum, r) => sum + r.missing.length, 0);
|
||||
const emptyKeys = langResults.reduce((sum, r) => sum + r.empty.length, 0);
|
||||
const extraKeys = langResults.reduce((sum, r) => sum + r.extra.length, 0);
|
||||
const coverage = totalKeys > 0 ? ((translatedKeys / totalKeys) * 100).toFixed(1) : '0.0';
|
||||
|
||||
output += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
output += `📝 Language: ${lang.toUpperCase()}\n`;
|
||||
output += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
output += `Coverage: ${coverage}% (${translatedKeys}/${totalKeys} keys)\n`;
|
||||
|
||||
if (missingKeys > 0) {
|
||||
output += `❌ Missing: ${missingKeys} keys\n`;
|
||||
}
|
||||
if (emptyKeys > 0) {
|
||||
output += `⚠️ Empty: ${emptyKeys} keys\n`;
|
||||
}
|
||||
if (extraKeys > 0) {
|
||||
output += `🔍 Extra: ${extraKeys} keys\n`;
|
||||
}
|
||||
|
||||
if (missingKeys === 0 && emptyKeys === 0 && extraKeys === 0) {
|
||||
output += `✅ All translations complete!\n`;
|
||||
}
|
||||
|
||||
// Detailed breakdown by namespace
|
||||
if (verbose) {
|
||||
output += `\nNamespaces:\n`;
|
||||
for (const result of langResults) {
|
||||
const nsCoverage = result.total > 0
|
||||
? ((result.translated / result.total) * 100).toFixed(1)
|
||||
: '0.0';
|
||||
|
||||
output += ` ${result.namespace}: ${nsCoverage}% (${result.translated}/${result.total})`;
|
||||
|
||||
if (result.missing.length > 0) {
|
||||
output += ` - Missing: ${result.missing.length}`;
|
||||
}
|
||||
if (result.empty.length > 0) {
|
||||
output += ` - Empty: ${result.empty.length}`;
|
||||
}
|
||||
if (result.extra.length > 0) {
|
||||
output += ` - Extra: ${result.extra.length}`;
|
||||
}
|
||||
|
||||
output += '\n';
|
||||
|
||||
// Show missing keys
|
||||
if (result.missing.length > 0 && result.missing.length <= 10) {
|
||||
output += ` Missing keys:\n`;
|
||||
for (const key of result.missing) {
|
||||
output += ` - ${key}\n`;
|
||||
}
|
||||
} else if (result.missing.length > 10) {
|
||||
output += ` Missing keys (first 10):\n`;
|
||||
for (const key of result.missing.slice(0, 10)) {
|
||||
output += ` - ${key}\n`;
|
||||
}
|
||||
output += ` ... and ${result.missing.length - 10} more\n`;
|
||||
}
|
||||
|
||||
// Show empty keys
|
||||
if (result.empty.length > 0) {
|
||||
output += ` Empty values:\n`;
|
||||
for (const key of result.empty) {
|
||||
output += ` - ${key}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
// Show extra keys
|
||||
if (result.extra.length > 0) {
|
||||
output += ` Extra keys (not in source):\n`;
|
||||
for (const key of result.extra) {
|
||||
output += ` - ${key}\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const verbose = args.includes('--verbose') || args.includes('-v');
|
||||
const langFilter = args.find(arg => arg.startsWith('--lang='))?.split('=')[1];
|
||||
|
||||
console.log('🌍 Translation Validation Script\n');
|
||||
console.log(`Source language: ${SOURCE_LANG}`);
|
||||
console.log(`Translations directory: ${TRANSLATIONS_DIR}\n`);
|
||||
|
||||
try {
|
||||
const namespaces = getNamespaces();
|
||||
const languages = getLanguages().filter(lang => lang !== SOURCE_LANG);
|
||||
|
||||
if (languages.length === 0) {
|
||||
console.log('No translation languages found.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${namespaces.length} namespaces: ${namespaces.join(', ')}`);
|
||||
console.log(`Found ${languages.length} languages: ${languages.join(', ')}\n`);
|
||||
|
||||
const results: ValidationResult[] = [];
|
||||
|
||||
for (const lang of languages) {
|
||||
if (langFilter && lang !== langFilter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const namespace of namespaces) {
|
||||
const result = validateNamespace(lang, namespace);
|
||||
results.push(result);
|
||||
}
|
||||
}
|
||||
|
||||
const output = formatResults(results, verbose);
|
||||
console.log(output);
|
||||
|
||||
// Exit with error if there are missing translations
|
||||
const hasMissing = results.some(r => r.missing.length > 0 || r.empty.length > 0);
|
||||
if (hasMissing) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Hardcoded Text Finder
|
||||
*
|
||||
* Scans Svelte files for hardcoded English text that should be moved to translation files.
|
||||
* Helps identify strings that need internationalization.
|
||||
*
|
||||
* Usage:
|
||||
* npm run find-hardcoded
|
||||
* npm run find-hardcoded -- --path=src/routes/settings
|
||||
* npm run find-hardcoded -- --min-length=10
|
||||
*/
|
||||
|
||||
import { readFileSync, readdirSync, statSync } from 'fs';
|
||||
import { join, relative, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const PROJECT_ROOT = join(__dirname, '..');
|
||||
const DEFAULT_SCAN_PATH = join(PROJECT_ROOT, 'src');
|
||||
|
||||
interface HardcodedText {
|
||||
file: string;
|
||||
line: number;
|
||||
text: string;
|
||||
context: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Patterns to detect hardcoded text in Svelte files
|
||||
*/
|
||||
const TEXT_PATTERNS = [
|
||||
// HTML text content: >Text<
|
||||
/>([A-Z][^<>{}\n]{3,})</g,
|
||||
|
||||
// Attribute values: title="Text", placeholder="Text", etc.
|
||||
/(?:title|placeholder|aria-label|alt|label)=["']([A-Z][^"']{3,})["']/g,
|
||||
|
||||
// String literals in script: 'Text' or "Text"
|
||||
/['"]([A-Z][A-Za-z\s]{4,})["']/g,
|
||||
];
|
||||
|
||||
/**
|
||||
* Patterns to exclude (these are likely not user-facing text)
|
||||
*/
|
||||
const EXCLUDE_PATTERNS = [
|
||||
/^\d+$/, // Just numbers
|
||||
/^[A-Z]+$/, // All caps (likely constants)
|
||||
/^[a-z-]+$/, // kebab-case (likely CSS/HTML)
|
||||
/^[A-Z][a-z]+$/, // Single word capitalized (might be component names)
|
||||
/^\$[a-z]/, // Svelte store references
|
||||
/^var\(/, // CSS variables
|
||||
/^#[0-9a-fA-F]{3,6}$/, // Color codes
|
||||
/^\//, // Paths
|
||||
/^http/, // URLs
|
||||
/\{.*\}/, // Template expressions
|
||||
/^\w+\(/, // Function calls
|
||||
/^[A-Z][a-z]+[A-Z]/, // PascalCase (component names)
|
||||
];
|
||||
|
||||
/**
|
||||
* Check if text should be excluded
|
||||
*/
|
||||
function shouldExclude(text: string): boolean {
|
||||
const trimmed = text.trim();
|
||||
|
||||
if (trimmed.length < 3) return true;
|
||||
if (trimmed.length > 100) return true; // Too long, likely not a translation
|
||||
|
||||
return EXCLUDE_PATTERNS.some(pattern => pattern.test(trimmed));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract hardcoded text from file content
|
||||
*/
|
||||
function findHardcodedText(filePath: string, content: string): HardcodedText[] {
|
||||
const results: HardcodedText[] = [];
|
||||
const lines = content.split('\n');
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const lineNumber = i + 1;
|
||||
|
||||
// Skip script/style blocks content (rough heuristic)
|
||||
if (line.includes('<script') || line.includes('<style')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip lines with translation helpers
|
||||
if (line.includes('$t(') || line.includes('t(')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip comments
|
||||
if (line.trim().startsWith('//') || line.trim().startsWith('/*') || line.trim().startsWith('*')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const pattern of TEXT_PATTERNS) {
|
||||
let match;
|
||||
while ((match = pattern.exec(line)) !== null) {
|
||||
const text = match[1];
|
||||
|
||||
if (!shouldExclude(text)) {
|
||||
results.push({
|
||||
file: relative(PROJECT_ROOT, filePath),
|
||||
line: lineNumber,
|
||||
text: text.trim(),
|
||||
context: line.trim().substring(0, 80),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively scan directory for Svelte files
|
||||
*/
|
||||
function scanDirectory(dirPath: string): HardcodedText[] {
|
||||
let results: HardcodedText[] = [];
|
||||
|
||||
try {
|
||||
const entries = readdirSync(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = join(dirPath, entry.name);
|
||||
|
||||
// Skip node_modules, .svelte-kit, etc.
|
||||
if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'build') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
results = results.concat(scanDirectory(fullPath));
|
||||
} else if (entry.isFile() && entry.name.endsWith('.svelte')) {
|
||||
try {
|
||||
const content = readFileSync(fullPath, 'utf-8');
|
||||
const found = findHardcodedText(fullPath, content);
|
||||
results = results.concat(found);
|
||||
} catch (error) {
|
||||
console.error(`Error reading ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error scanning ${dirPath}:`, error);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group results by file
|
||||
*/
|
||||
function groupByFile(results: HardcodedText[]): Map<string, HardcodedText[]> {
|
||||
const grouped = new Map<string, HardcodedText[]>();
|
||||
|
||||
for (const result of results) {
|
||||
if (!grouped.has(result.file)) {
|
||||
grouped.set(result.file, []);
|
||||
}
|
||||
grouped.get(result.file)!.push(result);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format results for display
|
||||
*/
|
||||
function formatResults(results: HardcodedText[], minLength: number): string {
|
||||
const filtered = results.filter(r => r.text.length >= minLength);
|
||||
const grouped = groupByFile(filtered);
|
||||
|
||||
let output = '';
|
||||
|
||||
output += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
output += `📝 Hardcoded Text Finder\n`;
|
||||
output += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
output += `Found ${filtered.length} potential hardcoded strings in ${grouped.size} files\n`;
|
||||
output += `Minimum length: ${minLength} characters\n\n`;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
output += `✅ No hardcoded text found!\n`;
|
||||
return output;
|
||||
}
|
||||
|
||||
// Sort files by number of issues
|
||||
const sortedFiles = Array.from(grouped.entries())
|
||||
.sort((a, b) => b[1].length - a[1].length);
|
||||
|
||||
for (const [file, items] of sortedFiles) {
|
||||
output += `\n📄 ${file} (${items.length} items)\n`;
|
||||
output += `${'─'.repeat(60)}\n`;
|
||||
|
||||
for (const item of items) {
|
||||
output += ` Line ${item.line}: "${item.text}"\n`;
|
||||
output += ` Context: ${item.context}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
output += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
output += `Summary: ${filtered.length} strings need translation\n`;
|
||||
output += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const pathArg = args.find(arg => arg.startsWith('--path='))?.split('=')[1];
|
||||
const minLengthArg = args.find(arg => arg.startsWith('--min-length='))?.split('=')[1];
|
||||
|
||||
const scanPath = pathArg ? join(PROJECT_ROOT, pathArg) : DEFAULT_SCAN_PATH;
|
||||
const minLength = minLengthArg ? parseInt(minLengthArg, 10) : 3;
|
||||
|
||||
console.log('🔍 Scanning for hardcoded text...\n');
|
||||
console.log(`Path: ${relative(PROJECT_ROOT, scanPath)}`);
|
||||
console.log(`Min length: ${minLength}\n`);
|
||||
|
||||
try {
|
||||
const results = scanDirectory(scanPath);
|
||||
const output = formatResults(results, minLength);
|
||||
console.log(output);
|
||||
|
||||
// Exit with warning if hardcoded text found
|
||||
if (results.length > 0) {
|
||||
console.log('\n💡 Tip: Move these strings to translation files in src/lib/i18n/translations/');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in new issue
Block a user