import { existsSync, readdirSync, readFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' /** * Language rules (template from the `dev` skill): all code is English. * - server and shared code are ASCII-only (Portuguese text lives only in the client); * - names of files, classes, functions, types, variables, routes and tRPC procedures * contain no Portuguese words, in any folder (client included). * Grow PORTUGUESE_WORDS when a new word slips through. */ const ROOT = process.cwd() const SOURCE_ROOT = path.join(ROOT, 'src') const CLIENT = path.join(SOURCE_ROOT, 'client') const ASCII_ONLY_DIRS = ['shared', 'server'].map((dir) => path.join(SOURCE_ROOT, dir)) const CODE_DIRS = [CLIENT, ...ASCII_ONLY_DIRS] const IGNORED_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', '.git']) /** Portuguese words that are not also English words (so `data`, `total`, `do` are absent on purpose). */ const PORTUGUESE_WORDS = new Set([ 'usuario', 'usuarios', 'processo', 'processos', 'cliente', 'clientes', 'pedido', 'pedidos', 'nome', 'nomes', 'valor', 'valores', 'lista', 'listar', 'cadastro', 'cadastrar', 'pessoa', 'pessoas', 'empresa', 'empresas', 'endereco', 'telefone', 'senha', 'conta', 'contas', 'pagamento', 'pagamentos', 'contrato', 'contratos', 'proposta', 'propostas', 'tarefa', 'tarefas', 'arquivo', 'arquivos', 'relatorio', 'relatorios', 'configuracao', 'configuracoes', 'novo', 'nova', 'editar', 'excluir', 'salvar', 'buscar', 'criar', 'atualizar', 'remover', 'enviar', 'gerar', 'calcular', 'validar', 'obter', 'inicio', 'tela', 'telas', 'botao', 'campo', 'campos', 'formulario', 'pagina', 'mensagem', 'mensagens', 'erro', 'erros', 'sucesso', 'ativo', 'inativo', 'quantidade', 'preco', 'dados', 'hora', 'dia', 'mes', 'ano', 'semana', 'cobranca', 'perito', 'peritos', 'documento', 'documentos', 'assinatura', 'juros', 'taxa', 'taxas', 'saldo', 'credito', 'debito', 'vencimento', 'parcela', 'parcelas', 'venda', 'vendas', 'compra', 'compras', 'produto', 'produtos', 'estoque', 'pelo', 'pela', 'para', ]) const DECLARATION_PATTERN = /\b(?:class|interface|type|enum|function|const|let|var)\s+([A-Za-z_$][\w$]*)/g const ROUTE_PATTERN = /\bpath\s*[:=]\s*\{?\s*['"`]([^'"`]+)['"`]/g const PROCEDURE_PATTERN = /\b([A-Za-z_$][\w$]*)\s*:\s*(?:\w*[pP]rocedure\b|\w*[rR]outer\b|router\s*\()/g function walk(dir: string): string[] { if (!existsSync(dir)) return [] return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { if (IGNORED_DIRS.has(entry.name)) return [] const full = path.join(dir, entry.name) return entry.isDirectory() ? [full, ...walk(full)] : [full] }) } const isCode = (file: string) => /\.tsx?$/.test(file) const rel = (file: string) => path.relative(ROOT, file) /** Splits camelCase, PascalCase, kebab-case, snake_case and route paths into lowercase words. */ function wordsOf(name: string): string[] { return name .replace(/([a-z0-9])([A-Z])/g, '$1 $2') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') .split(/[^A-Za-z0-9]+/) .map((word) => word.toLowerCase()) .filter(Boolean) } function namesIn(file: string): string[] { const content = readFileSync(file, 'utf8') return [DECLARATION_PATTERN, ROUTE_PATTERN, PROCEDURE_PATTERN].flatMap((pattern) => [...content.matchAll(pattern)].map((match) => match[1] ?? ''), ) } const portugueseWords = (name: string) => wordsOf(name).filter((word) => PORTUGUESE_WORDS.has(word)) describe('language', () => { it('keeps server and shared code ASCII-only', () => { const violations = ASCII_ONLY_DIRS.flatMap(walk) .filter(isCode) .flatMap((file) => readFileSync(file, 'utf8') .split('\n') .flatMap((line, index) => (/[^\x00-\x7F]/.test(line) ? [`${rel(file)}:${index + 1}`] : [])), ) expect(violations).toEqual([]) }) it('names files and folders in English', () => { const violations = CODE_DIRS.flatMap(walk) .map((file) => path.basename(file)) .filter((name) => portugueseWords(name).length > 0 || /[^\x00-\x7F]/.test(name)) expect([...new Set(violations)].sort()).toEqual([]) }) it('names classes, functions, types, variables, routes and procedures in English', () => { const violations = CODE_DIRS.flatMap(walk) .filter(isCode) .flatMap((file) => namesIn(file) .filter((name) => portugueseWords(name).length > 0 || /[^\x00-\x7F]/.test(name)) .map((name) => `${rel(file)}: ${name}`), ) expect(violations).toEqual([]) }) })