Merge pull request 'feat: migrate-to-TS' (#15) from feat/migrate-to-TS into main

Reviewed-on: #15
Reviewed-by: blas <me@blassanto.me>
This commit was merged in pull request #15.
This commit is contained in:
2026-03-23 16:32:54 +00:00
8 changed files with 968 additions and 173 deletions

7
.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"tabWidth": 2,
"semi": true
}

View File

@@ -112,9 +112,9 @@ import { USER_USE_CASES } from '@/domain/use-cases/user/user.use-cases.contract'
}) })
export class UsersComponent { export class UsersComponent {
#userUseCases = inject(USER_USE_CASES); #userUseCases = inject(USER_USE_CASES);
ngOnInit() { ngOnInit() {
this.#userUseCases.getUsers().subscribe(users => { this.#userUseCases.getUsers().subscribe((users) => {
console.log(users); console.log(users);
}); });
} }
@@ -126,6 +126,7 @@ export class UsersComponent {
### ❌ Error: openapi-generator-cli: command not found ### ❌ Error: openapi-generator-cli: command not found
**Solución:** **Solución:**
```bash ```bash
npm install -g @openapitools/openapi-generator-cli npm install -g @openapitools/openapi-generator-cli
``` ```
@@ -133,6 +134,7 @@ npm install -g @openapitools/openapi-generator-cli
### ❌ Error: Cannot find module 'commander' ### ❌ Error: Cannot find module 'commander'
**Solución:** **Solución:**
```bash ```bash
npm install npm install
``` ```
@@ -140,6 +142,7 @@ npm install
### ❌ Los archivos no se generan ### ❌ Los archivos no se generan
**Solución:** Verifica que el directorio de salida existe o usa `--dry-run` para ver qué pasaría: **Solución:** Verifica que el directorio de salida existe o usa `--dry-run` para ver qué pasaría:
```bash ```bash
node generate.js --dry-run node generate.js --dry-run
``` ```

View File

@@ -23,13 +23,20 @@ npm run setup
### Comando básico ### Comando básico
```bash ```bash
node generate.js -i swagger.yaml # Versión compilada
npm run generate -- -i swagger.yaml
# Versión desarrollo (ts-node)
npm run generate:dev -- -i swagger.yaml
# Versión link global (si hiciste npm link)
generate-clean-arch -i swagger.yaml
``` ```
### Opciones disponibles ### Opciones disponibles
```bash ```bash
node generate.js [opciones] npm run generate -- [opciones]
Opciones: Opciones:
-V, --version Mostrar versión -V, --version Mostrar versión
@@ -45,16 +52,16 @@ Opciones:
```bash ```bash
# Generar desde swagger.yaml en src/app # Generar desde swagger.yaml en src/app
node generate.js -i swagger.yaml -o ./src/app npm run generate -- -i swagger.yaml -o ./src/app
# Usar templates personalizados # Usar templates personalizados
node generate.js -i api.yaml -t ./mis-templates npm run generate -- -i api.yaml -t ./mis-templates
# Modo de prueba (no genera archivos) # Modo de prueba (no genera archivos)
node generate.js -i swagger.yaml --dry-run npm run generate -- -i swagger.yaml --dry-run
# Especificar todos los parámetros # Especificar todos los parámetros
node generate.js -i ./docs/api.yaml -o ./frontend/src/app -t ./custom-templates npm run generate -- -i ./docs/api.yaml -o ./frontend/src/app -t ./custom-templates
``` ```
## 📁 Estructura Generada ## 📁 Estructura Generada
@@ -117,6 +124,7 @@ src/app/
Los templates están en la carpeta `templates/`. Cada archivo `.mustache` define cómo se genera un tipo de archivo. Los templates están en la carpeta `templates/`. Cada archivo `.mustache` define cómo se genera un tipo de archivo.
Templates disponibles: Templates disponibles:
- `model.mustache` - DTOs - `model.mustache` - DTOs
- `model-entity.mustache` - Entidades del modelo - `model-entity.mustache` - Entidades del modelo
- `mapper.mustache` - Mappers - `mapper.mustache` - Mappers
@@ -183,7 +191,7 @@ cp ../docs/api.yaml ./swagger.yaml
### 3. Generar código ### 3. Generar código
```bash ```bash
node generate.js npm run generate -- -i swagger.yaml
``` ```
### 4. Registrar providers en Angular ### 4. Registrar providers en Angular
@@ -201,7 +209,7 @@ import { NodeUseCasesProvider } from '@/di/use-cases/node.use-cases.provider';
NodeRepositoryProvider, NodeRepositoryProvider,
OrderTypeRepositoryProvider, OrderTypeRepositoryProvider,
SupplyModeRepositoryProvider, SupplyModeRepositoryProvider,
// Use Cases // Use Cases
NodeUseCasesProvider, NodeUseCasesProvider,
OrderTypeUseCasesProvider, OrderTypeUseCasesProvider,
@@ -223,9 +231,9 @@ import { NODE_USE_CASES, NodeUseCases } from '@/domain/use-cases/node/node.use-c
}) })
export class NodesComponent { export class NodesComponent {
#nodeUseCases = inject(NODE_USE_CASES); #nodeUseCases = inject(NODE_USE_CASES);
loadNodes() { loadNodes() {
this.#nodeUseCases.getNodes('TI').subscribe(nodes => { this.#nodeUseCases.getNodes('TI').subscribe((nodes) => {
console.log(nodes); console.log(nodes);
}); });
} }
@@ -245,8 +253,9 @@ npm run setup
### Error: Archivo swagger.yaml no encontrado ### Error: Archivo swagger.yaml no encontrado
Asegúrate de especificar la ruta correcta: Asegúrate de especificar la ruta correcta:
```bash ```bash
node generate.js -i ./ruta/a/tu/swagger.yaml npm run generate -- -i ./ruta/a/tu/swagger.yaml
``` ```
### Los imports no se resuelven (@/ no funciona) ### Los imports no se resuelven (@/ no funciona)

523
dist/generate.js vendored Normal file
View File

@@ -0,0 +1,523 @@
#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const mustache_1 = __importDefault(require("mustache"));
const commander_1 = require("commander");
// Desactivar escape HTML para que los literales < y > generen tipos genéricos válidos de TS.
mustache_1.default.escape = function (text) {
return text;
};
// Colores para console (sin dependencias externas)
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
green: '\x1b[32m',
blue: '\x1b[34m',
yellow: '\x1b[33m',
red: '\x1b[31m',
cyan: '\x1b[36m'
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function logSuccess(message) {
log(`${message}`, 'green');
}
function logInfo(message) {
log(` ${message}`, 'blue');
}
function logWarning(message) {
log(`⚠️ ${message}`, 'yellow');
}
function logError(message) {
log(`${message}`, 'red');
}
function logStep(message) {
log(`\n🚀 ${message}`, 'cyan');
}
// Configuración del CLI
commander_1.program
.name('generate-clean-arch')
.description('Generador de código Angular con Clean Architecture desde OpenAPI/Swagger')
.version('1.0.0')
.option('-i, --input <file>', 'Archivo OpenAPI/Swagger (yaml o json)', 'swagger.yaml')
.option('-o, --output <dir>', 'Directorio de salida', './src/app')
.option('-t, --templates <dir>', 'Directorio de templates personalizados', './templates')
.option('--skip-install', 'No instalar dependencias')
.option('--dry-run', 'Simular sin generar archivos')
.parse(process.argv);
const options = commander_1.program.opts();
// Validar que existe openapi-generator-cli
function checkOpenApiGenerator() {
try {
(0, child_process_1.execSync)('openapi-generator-cli version', { stdio: 'ignore' });
return true;
}
catch (_error) {
return false;
}
}
// Instalar openapi-generator-cli
function installOpenApiGenerator() {
logStep('Instalando @openapitools/openapi-generator-cli...');
try {
(0, child_process_1.execSync)('npm install -g @openapitools/openapi-generator-cli', { stdio: 'inherit' });
logSuccess('OpenAPI Generator CLI instalado correctamente');
}
catch (_error) {
logError('Error al instalar OpenAPI Generator CLI');
process.exit(1);
}
}
// Crear estructura de directorios
function createDirectoryStructure(baseDir) {
const dirs = [
path_1.default.join(baseDir, 'data/dtos'),
path_1.default.join(baseDir, 'data/repositories'),
path_1.default.join(baseDir, 'data/mappers'),
path_1.default.join(baseDir, 'domain/repositories'),
path_1.default.join(baseDir, 'domain/use-cases'),
path_1.default.join(baseDir, 'di/repositories'),
path_1.default.join(baseDir, 'di/use-cases'),
path_1.default.join(baseDir, 'entities/models')
];
dirs.forEach((dir) => {
fs_extra_1.default.ensureDirSync(dir);
});
logSuccess('Estructura de directorios creada');
}
// Analizar el swagger para extraer tags y dominios
function analyzeSwagger(swaggerFile) {
logStep('Analizando archivo OpenAPI...');
try {
const fileContent = fs_extra_1.default.readFileSync(swaggerFile, 'utf8');
const swagger = js_yaml_1.default.load(fileContent);
const tags = Array.isArray(swagger.tags) ? swagger.tags : [];
const paths = swagger.paths || {};
logInfo(`Encontrados ${tags.length} tags en el API`);
logInfo(`Encontrados ${Object.keys(paths).length} endpoints`);
tags.forEach((tag) => {
const t = tag;
logInfo(` - ${t.name}: ${t.description || 'Sin descripción'}`);
});
return { tags, paths, swagger };
}
catch (error) {
const err = error;
logError(`Error al leer el archivo Swagger: ${err.message}`);
process.exit(1);
}
}
// Generar código con OpenAPI Generator
function generateCode(swaggerFile, templatesDir) {
logStep('Generando código desde OpenAPI...');
const tempDir = path_1.default.join(process.cwd(), '.temp-generated');
// Limpiar directorio temporal
if (fs_extra_1.default.existsSync(tempDir)) {
fs_extra_1.default.removeSync(tempDir);
}
try {
const command = `openapi-generator-cli generate \
-i "${swaggerFile}" \
-g typescript-angular \
--global-property models \
-t "${templatesDir}" \
-o "${tempDir}" \
--additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto`;
(0, child_process_1.execSync)(command, { stdio: 'inherit' });
logSuccess('Código generado correctamente');
return tempDir;
}
catch (_error) {
logError('Error al generar código');
if (fs_extra_1.default.existsSync(tempDir)) {
fs_extra_1.default.removeSync(tempDir);
}
process.exit(1);
}
}
// Organizar archivos según Clean Architecture (DTOs)
function organizeFiles(tempDir, outputDir) {
logStep('Organizando archivos DTO generados...');
const sourceDir = path_1.default.join(tempDir, 'model');
const destDir = path_1.default.join(outputDir, 'data/dtos');
let filesMoved = 0;
if (fs_extra_1.default.existsSync(sourceDir)) {
fs_extra_1.default.ensureDirSync(destDir);
const files = fs_extra_1.default.readdirSync(sourceDir).filter((file) => file.endsWith('.dto.ts'));
files.forEach((file) => {
const sourcePath = path_1.default.join(sourceDir, file);
const destPath = path_1.default.join(destDir, file);
fs_extra_1.default.copySync(sourcePath, destPath);
filesMoved++;
logInfo(` ${file}${path_1.default.relative(process.cwd(), destPath)}`);
});
}
logSuccess(`${filesMoved} DTOs movidos correctamente`);
}
// Utilidad para mapear tipos OpenAPI elementales a TypeScript
function mapSwaggerTypeToTs(type) {
if (!type)
return 'unknown';
const typeMap = {
integer: 'number',
string: 'string',
boolean: 'boolean',
number: 'number',
array: 'Array<unknown>',
object: 'unknown'
};
return typeMap[type] || 'unknown';
}
// Generar Clean Architecture con Mustache
function generateCleanArchitecture(analysis, outputDir, templatesDir) {
logStep('Generando artefactos de Clean Architecture usando Mustache...');
const generatedCount = {
models: 0,
repositories: 0,
mappers: 0,
useCases: 0,
providers: 0
};
const schemas = analysis.swagger.components
?.schemas || {};
// 1. Generar Modelos, Entidades y Mappers a partir de Schemas
Object.keys(schemas).forEach((schemaName) => {
// Sanitizar nombres base para que coincidan con cómo OpenAPI los emite (sin Dto duplicado)
const baseName = schemaName.replace(/Dto$/, '');
// variables para model
const schemaObj = schemas[schemaName];
const rawProperties = schemaObj.properties || {};
const requiredProps = schemaObj.required || [];
const varsMap = Object.keys(rawProperties).map((k) => {
let tsType = mapSwaggerTypeToTs(rawProperties[k].type);
if (rawProperties[k].$ref) {
// Simple extración del tipo de la ref
tsType = rawProperties[k].$ref.split('/').pop() || 'unknown';
}
else if (rawProperties[k].type === 'array' && rawProperties[k].items?.$ref) {
tsType = `Array<${rawProperties[k].items.$ref.split('/').pop()}>`;
}
return {
name: k,
dataType: tsType,
description: rawProperties[k].description || '',
required: requiredProps.includes(k)
};
});
const modelViewData = {
models: [
{
model: {
classname: baseName,
classFilename: baseName.toLowerCase(),
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
description: schemaObj.description || '',
vars: varsMap
}
}
],
// Para plantillas que esperan allModels o importaciones (mapper)
allModels: [{ model: { vars: varsMap } }]
};
// Y para mapper.mustache, que además pide apiInfo
const mapperViewData = {
...modelViewData,
apiInfo: {
apis: [
{
operations: {
classname: baseName,
classFilename: baseName.toLowerCase(),
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1)
}
}
]
}
};
// Model (Entities)
const modelTemplatePath = path_1.default.join(templatesDir, 'model-entity.mustache');
if (fs_extra_1.default.existsSync(modelTemplatePath)) {
const template = fs_extra_1.default.readFileSync(modelTemplatePath, 'utf8');
const output = mustache_1.default.render(template, modelViewData);
const destPath = path_1.default.join(outputDir, 'entities/models', `${baseName.toLowerCase()}.model.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.models++;
logInfo(` ${baseName.toLowerCase()}.model.ts → ${path_1.default.relative(process.cwd(), destPath)}`);
}
// Mapper
const mapperTemplatePath = path_1.default.join(templatesDir, 'mapper.mustache');
if (fs_extra_1.default.existsSync(mapperTemplatePath)) {
const template = fs_extra_1.default.readFileSync(mapperTemplatePath, 'utf8');
const output = mustache_1.default.render(template, mapperViewData);
const destPath = path_1.default.join(outputDir, 'data/mappers', `${baseName.toLowerCase()}.mapper.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.mappers++;
}
});
// 2. Generar Casos de Uso y Repositorios a partir de Paths/Tags
const tagsMap = {};
// Agrupar operaciones por Tag
Object.keys(analysis.paths).forEach((pathKey) => {
const pathObj = analysis.paths[pathKey];
Object.keys(pathObj).forEach((method) => {
const op = pathObj[method];
if (op.tags && op.tags.length > 0) {
const tag = op.tags[0]; // Usamos el primer tag
if (!tagsMap[tag])
tagsMap[tag] = [];
// Parsear parámetros
const allParams = (op.parameters || []).map((p) => ({
paramName: p.name,
dataType: mapSwaggerTypeToTs(p.schema?.type || ''),
description: p.description || '',
required: p.required
}));
// Añadir body como parámetro si existe
if (op.requestBody) {
let bodyType = 'unknown';
const content = op.requestBody.content?.['application/json']?.schema;
if (content) {
if (content.$ref)
bodyType = content.$ref.split('/').pop() || 'unknown';
else if (content.type)
bodyType = mapSwaggerTypeToTs(content.type);
}
allParams.push({
paramName: 'body',
dataType: bodyType,
description: op.requestBody.description || '',
required: true
});
}
// Parsear respuestas
let returnType = 'void';
let returnBaseType = 'void';
let isListContainer = false;
const responseSchema = op.responses?.['200']?.content?.['application/json']?.schema;
if (responseSchema) {
if (responseSchema.$ref) {
returnType = responseSchema.$ref.split('/').pop() || 'unknown';
returnBaseType = returnType;
}
else if (responseSchema.type === 'array' && responseSchema.items?.$ref) {
returnBaseType = responseSchema.items.$ref.split('/').pop() || 'unknown';
returnType = `Array<${returnBaseType}>`;
isListContainer = true;
}
}
tagsMap[tag].push({
nickname: op.operationId || `${method}${pathKey.replace(/\//g, '_')}`,
summary: op.summary || '',
notes: op.description || '',
httpMethod: method.toLowerCase(),
path: pathKey,
allParams: allParams.map((p, i) => ({ ...p, '-last': i === allParams.length - 1 })),
hasQueryParams: (op.parameters || []).some((p) => p.in === 'query'),
queryParams: (op.parameters || [])
.filter((p) => p.in === 'query')
.map((p, i, arr) => ({
paramName: p.name,
'-last': i === arr.length - 1
})),
hasBodyParam: !!op.requestBody,
bodyParam: 'body',
returnType: returnType !== 'void' ? returnType : false,
returnBaseType: returnBaseType !== 'void' ? returnBaseType : false,
isListContainer: isListContainer,
vendorExtensions: {}
});
}
});
});
// Generar por cada Tag
Object.keys(tagsMap).forEach((tag) => {
// Buscar si ese tag cruza con alguna entidad para importarla
const imports = [];
Object.keys(schemas).forEach((s) => {
// Import heurístico burdo
if (tagsMap[tag].some((op) => op.returnType === s || op.returnType === `Array<${s}>`)) {
imports.push({
classname: s,
classFilename: s.toLowerCase(),
classVarName: s.charAt(0).toLowerCase() + s.slice(1)
});
}
});
const apiViewData = {
apiInfo: {
apis: [
{
operations: {
classname: tag,
classFilename: tag.toLowerCase(),
constantName: tag.toUpperCase().replace(/[^A-Z0-9]/g, '_'),
operation: tagsMap[tag],
imports: imports
}
}
]
}
};
// Use Case Contract
const ucContractPath = path_1.default.join(templatesDir, 'api.use-cases.contract.mustache');
if (fs_extra_1.default.existsSync(ucContractPath)) {
const template = fs_extra_1.default.readFileSync(ucContractPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.contract.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.useCases++;
}
// Use Case Impl
const ucImplPath = path_1.default.join(templatesDir, 'api.use-cases.impl.mustache');
if (fs_extra_1.default.existsSync(ucImplPath)) {
const template = fs_extra_1.default.readFileSync(ucImplPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.impl.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.useCases++;
}
// Repository Contract
const repoContractPath = path_1.default.join(templatesDir, 'api.repository.contract.mustache');
if (fs_extra_1.default.existsSync(repoContractPath)) {
const template = fs_extra_1.default.readFileSync(repoContractPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'domain/repositories', `${tag.toLowerCase()}.repository.contract.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.repositories++;
}
// Repository Impl
const repoImplPath = path_1.default.join(templatesDir, 'api.repository.impl.mustache');
if (fs_extra_1.default.existsSync(repoImplPath)) {
const template = fs_extra_1.default.readFileSync(repoImplPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'data/repositories', `${tag.toLowerCase()}.repository.impl.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.repositories++;
}
// Use Case Provider
const ucProviderPath = path_1.default.join(templatesDir, 'use-cases.provider.mustache');
if (fs_extra_1.default.existsSync(ucProviderPath)) {
const template = fs_extra_1.default.readFileSync(ucProviderPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'di/use-cases', `${tag.toLowerCase()}.use-cases.provider.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.providers++;
}
// Repository Provider
const repoProviderPath = path_1.default.join(templatesDir, 'repository.provider.mustache');
if (fs_extra_1.default.existsSync(repoProviderPath)) {
const template = fs_extra_1.default.readFileSync(repoProviderPath, 'utf8');
const output = mustache_1.default.render(template, apiViewData);
const destPath = path_1.default.join(outputDir, 'di/repositories', `${tag.toLowerCase()}.repository.provider.ts`);
fs_extra_1.default.writeFileSync(destPath, output);
generatedCount.providers++;
}
});
logSuccess(`${generatedCount.models} Models, ${generatedCount.repositories} Repos, ${generatedCount.useCases} Use Cases, ${generatedCount.mappers} Mappers, ${generatedCount.providers} Providers generados con Mustache`);
return generatedCount;
}
// Limpiar directorio temporal
function cleanup(tempDir) {
if (fs_extra_1.default.existsSync(tempDir)) {
fs_extra_1.default.removeSync(tempDir);
logInfo('Archivos temporales eliminados');
}
}
// Generar reporte
function generateReport(outputDir, analysis) {
logStep('Generando reporte de generación...');
const report = {
timestamp: new Date().toISOString(),
tags: analysis.tags.length,
endpoints: Object.keys(analysis.paths).length,
outputDirectory: outputDir,
structure: {
dtos: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'data/dtos')).length,
repositories: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'data/repositories')).length,
mappers: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'data/mappers')).length,
useCases: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'domain/use-cases')).length,
providers: fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/repositories')).length +
fs_extra_1.default.readdirSync(path_1.default.join(outputDir, 'di/use-cases')).length
}
};
const reportPath = path_1.default.join(process.cwd(), 'generation-report.json');
fs_extra_1.default.writeJsonSync(reportPath, report, { spaces: 2 });
logSuccess(`Reporte guardado en: ${reportPath}`);
return report;
}
// Función principal
async function main() {
console.log('\n' + '='.repeat(60));
log(' OpenAPI Clean Architecture Generator', 'bright');
log(' Angular + Clean Architecture Code Generator', 'cyan');
console.log('='.repeat(60) + '\n');
// Validar archivo de entrada
if (!fs_extra_1.default.existsSync(options.input)) {
logError(`Archivo no encontrado: ${options.input}`);
process.exit(1);
}
logInfo(`Archivo de entrada: ${options.input}`);
logInfo(`Directorio de salida: ${options.output}`);
logInfo(`Templates: ${options.templates}`);
if (options.dryRun) {
logWarning('Modo DRY RUN - No se generarán archivos');
}
// Verificar/Instalar OpenAPI Generator
if (!checkOpenApiGenerator()) {
logWarning('OpenAPI Generator CLI no encontrado');
if (!options.skipInstall) {
installOpenApiGenerator();
}
else {
logError('Instala openapi-generator-cli con: npm install -g @openapitools/openapi-generator-cli');
process.exit(1);
}
}
else {
logSuccess('OpenAPI Generator CLI encontrado');
}
// Analizar Swagger
const analysis = analyzeSwagger(options.input);
if (options.dryRun) {
logInfo('Finalizando en modo DRY RUN');
return;
}
// Crear estructura de directorios
createDirectoryStructure(options.output);
// Generar código
const tempDir = generateCode(options.input, options.templates);
// Organizar archivos
organizeFiles(tempDir, options.output);
// Crear componentes Clean Architecture con nuestro script de Mustache
generateCleanArchitecture(analysis, options.output, options.templates);
// Limpiar
cleanup(tempDir);
// Generar reporte
const report = generateReport(options.output, analysis);
// Resumen final
console.log('\n' + '='.repeat(60));
log(' ✨ Generación completada con éxito', 'green');
console.log('='.repeat(60));
console.log(`\n📊 Resumen:`);
console.log(` - DTOs generados: ${report.structure.dtos}`);
console.log(` - Repositories: ${report.structure.repositories}`);
console.log(` - Mappers: ${report.structure.mappers}`);
console.log(` - Use Cases: ${report.structure.useCases}`);
console.log(` - Providers: ${report.structure.providers}`);
console.log(`\n📁 Archivos generados en: ${colors.cyan}${options.output}${colors.reset}\n`);
}
// Ejecutar
main().catch((error) => {
const err = error;
logError(`Error fatal: ${err.message}`);
console.error(error);
process.exit(1);
});

30
eslint.config.js Normal file
View File

@@ -0,0 +1,30 @@
const eslint = require('@eslint/js');
const tseslint = require('typescript-eslint');
const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');
module.exports = tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname
}
},
rules: {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-function-return-type': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { 'argsIgnorePattern': '^_', 'varsIgnorePattern': '^_', 'caughtErrorsIgnorePattern': '^_' }]
}
},
{
ignores: ['dist/', 'node_modules/', 'eslint.config.js']
}
);

View File

@@ -1,14 +1,16 @@
#!/usr/bin/env node #!/usr/bin/env node
const { execSync } = require('child_process'); import { execSync } from 'child_process';
const fs = require('fs-extra'); import fs from 'fs-extra';
const path = require('path'); import path from 'path';
const yaml = require('js-yaml'); import yaml from 'js-yaml';
const mustache = require('mustache'); import mustache from 'mustache';
const { program } = require('commander'); import { program } from 'commander';
// Desactivar escape HTML para que los literales < y > generen tipos genéricos válidos de TS. // Desactivar escape HTML para que los literales < y > generen tipos genéricos válidos de TS.
mustache.escape = function(text) { return text; }; (mustache as { escape: (text: string) => string }).escape = function (text: string): string {
return text;
};
// Colores para console (sin dependencias externas) // Colores para console (sin dependencias externas)
const colors = { const colors = {
@@ -21,27 +23,29 @@ const colors = {
cyan: '\x1b[36m' cyan: '\x1b[36m'
}; };
function log(message, color = 'reset') { type Color = keyof typeof colors;
function log(message: string, color: Color = 'reset'): void {
console.log(`${colors[color]}${message}${colors.reset}`); console.log(`${colors[color]}${message}${colors.reset}`);
} }
function logSuccess(message) { function logSuccess(message: string): void {
log(`${message}`, 'green'); log(`${message}`, 'green');
} }
function logInfo(message) { function logInfo(message: string): void {
log(` ${message}`, 'blue'); log(` ${message}`, 'blue');
} }
function logWarning(message) { function logWarning(message: string): void {
log(`⚠️ ${message}`, 'yellow'); log(`⚠️ ${message}`, 'yellow');
} }
function logError(message) { function logError(message: string): void {
log(`${message}`, 'red'); log(`${message}`, 'red');
} }
function logStep(message) { function logStep(message: string): void {
log(`\n🚀 ${message}`, 'cyan'); log(`\n🚀 ${message}`, 'cyan');
} }
@@ -57,32 +61,40 @@ program
.option('--dry-run', 'Simular sin generar archivos') .option('--dry-run', 'Simular sin generar archivos')
.parse(process.argv); .parse(process.argv);
export interface CliOptions {
input: string;
output: string;
templates: string;
skipInstall?: boolean;
dryRun?: boolean;
}
const options = program.opts(); const options = program.opts();
// Validar que existe openapi-generator-cli // Validar que existe openapi-generator-cli
function checkOpenApiGenerator() { function checkOpenApiGenerator(): boolean {
try { try {
execSync('openapi-generator-cli version', { stdio: 'ignore' }); execSync('openapi-generator-cli version', { stdio: 'ignore' });
return true; return true;
} catch (error) { } catch (_error) {
return false; return false;
} }
} }
// Instalar openapi-generator-cli // Instalar openapi-generator-cli
function installOpenApiGenerator() { function installOpenApiGenerator(): void {
logStep('Instalando @openapitools/openapi-generator-cli...'); logStep('Instalando @openapitools/openapi-generator-cli...');
try { try {
execSync('npm install -g @openapitools/openapi-generator-cli', { stdio: 'inherit' }); execSync('npm install -g @openapitools/openapi-generator-cli', { stdio: 'inherit' });
logSuccess('OpenAPI Generator CLI instalado correctamente'); logSuccess('OpenAPI Generator CLI instalado correctamente');
} catch (error) { } catch (_error) {
logError('Error al instalar OpenAPI Generator CLI'); logError('Error al instalar OpenAPI Generator CLI');
process.exit(1); process.exit(1);
} }
} }
// Crear estructura de directorios // Crear estructura de directorios
function createDirectoryStructure(baseDir) { function createDirectoryStructure(baseDir: string): void {
const dirs = [ const dirs = [
path.join(baseDir, 'data/dtos'), path.join(baseDir, 'data/dtos'),
path.join(baseDir, 'data/repositories'), path.join(baseDir, 'data/repositories'),
@@ -94,49 +106,57 @@ function createDirectoryStructure(baseDir) {
path.join(baseDir, 'entities/models') path.join(baseDir, 'entities/models')
]; ];
dirs.forEach(dir => { dirs.forEach((dir) => {
fs.ensureDirSync(dir); fs.ensureDirSync(dir);
}); });
logSuccess('Estructura de directorios creada'); logSuccess('Estructura de directorios creada');
} }
interface SwaggerAnalysis {
tags: unknown[];
paths: Record<string, unknown>;
swagger: unknown;
}
// Analizar el swagger para extraer tags y dominios // Analizar el swagger para extraer tags y dominios
function analyzeSwagger(swaggerFile) { function analyzeSwagger(swaggerFile: string): SwaggerAnalysis {
logStep('Analizando archivo OpenAPI...'); logStep('Analizando archivo OpenAPI...');
try { try {
const fileContent = fs.readFileSync(swaggerFile, 'utf8'); const fileContent = fs.readFileSync(swaggerFile, 'utf8');
const swagger = yaml.load(fileContent); const swagger = yaml.load(fileContent) as Record<string, unknown>;
const tags = swagger.tags || []; const tags = Array.isArray(swagger.tags) ? swagger.tags : [];
const paths = swagger.paths || {}; const paths = (swagger.paths as Record<string, unknown>) || {};
logInfo(`Encontrados ${tags.length} tags en el API`); logInfo(`Encontrados ${tags.length} tags en el API`);
logInfo(`Encontrados ${Object.keys(paths).length} endpoints`); logInfo(`Encontrados ${Object.keys(paths).length} endpoints`);
tags.forEach(tag => { tags.forEach((tag: unknown) => {
logInfo(` - ${tag.name}: ${tag.description || 'Sin descripción'}`); const t = tag as { name: string; description?: string };
logInfo(` - ${t.name}: ${t.description || 'Sin descripción'}`);
}); });
return { tags, paths, swagger }; return { tags, paths, swagger };
} catch (error) { } catch (error: unknown) {
logError(`Error al leer el archivo Swagger: ${error.message}`); const err = error as Error;
logError(`Error al leer el archivo Swagger: ${err.message}`);
process.exit(1); process.exit(1);
} }
} }
// Generar código con OpenAPI Generator // Generar código con OpenAPI Generator
function generateCode(swaggerFile, templatesDir) { function generateCode(swaggerFile: string, templatesDir: string): string {
logStep('Generando código desde OpenAPI...'); logStep('Generando código desde OpenAPI...');
const tempDir = path.join(process.cwd(), '.temp-generated'); const tempDir = path.join(process.cwd(), '.temp-generated');
// Limpiar directorio temporal // Limpiar directorio temporal
if (fs.existsSync(tempDir)) { if (fs.existsSync(tempDir)) {
fs.removeSync(tempDir); fs.removeSync(tempDir);
} }
try { try {
const command = `openapi-generator-cli generate \ const command = `openapi-generator-cli generate \
-i "${swaggerFile}" \ -i "${swaggerFile}" \
@@ -145,12 +165,12 @@ function generateCode(swaggerFile, templatesDir) {
-t "${templatesDir}" \ -t "${templatesDir}" \
-o "${tempDir}" \ -o "${tempDir}" \
--additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto`; --additional-properties=ngVersion=17.0.0,modelFileSuffix=.dto`;
execSync(command, { stdio: 'inherit' }); execSync(command, { stdio: 'inherit' });
logSuccess('Código generado correctamente'); logSuccess('Código generado correctamente');
return tempDir; return tempDir;
} catch (error) { } catch (_error) {
logError('Error al generar código'); logError('Error al generar código');
if (fs.existsSync(tempDir)) { if (fs.existsSync(tempDir)) {
fs.removeSync(tempDir); fs.removeSync(tempDir);
@@ -160,70 +180,166 @@ function generateCode(swaggerFile, templatesDir) {
} }
// Organizar archivos según Clean Architecture (DTOs) // Organizar archivos según Clean Architecture (DTOs)
function organizeFiles(tempDir, outputDir) { function organizeFiles(tempDir: string, outputDir: string): void {
logStep('Organizando archivos DTO generados...'); logStep('Organizando archivos DTO generados...');
const sourceDir = path.join(tempDir, 'model'); const sourceDir = path.join(tempDir, 'model');
const destDir = path.join(outputDir, 'data/dtos'); const destDir = path.join(outputDir, 'data/dtos');
let filesMoved = 0; let filesMoved = 0;
if (fs.existsSync(sourceDir)) { if (fs.existsSync(sourceDir)) {
fs.ensureDirSync(destDir); fs.ensureDirSync(destDir);
const files = fs.readdirSync(sourceDir).filter(file => file.endsWith('.dto.ts')); const files = fs.readdirSync(sourceDir).filter((file) => file.endsWith('.dto.ts'));
files.forEach(file => { files.forEach((file) => {
const sourcePath = path.join(sourceDir, file); const sourcePath = path.join(sourceDir, file);
const destPath = path.join(destDir, file); const destPath = path.join(destDir, file);
fs.copySync(sourcePath, destPath); fs.copySync(sourcePath, destPath);
filesMoved++; filesMoved++;
logInfo(` ${file}${path.relative(process.cwd(), destPath)}`); logInfo(` ${file}${path.relative(process.cwd(), destPath)}`);
}); });
} }
logSuccess(`${filesMoved} DTOs movidos correctamente`); logSuccess(`${filesMoved} DTOs movidos correctamente`);
} }
// Utilidad para mapear tipos OpenAPI elementales a TypeScript // Utilidad para mapear tipos OpenAPI elementales a TypeScript
function mapSwaggerTypeToTs(type) { function mapSwaggerTypeToTs(type?: string): string {
const typeMap = { if (!type) return 'unknown';
'integer': 'number',
'string': 'string', const typeMap: Record<string, string> = {
'boolean': 'boolean', integer: 'number',
'number': 'number', string: 'string',
'array': 'Array<any>', boolean: 'boolean',
'object': 'any' number: 'number',
array: 'Array<unknown>',
object: 'unknown'
}; };
return typeMap[type] || 'any'; return typeMap[type] || 'unknown';
}
interface GeneratedCount {
models: number;
repositories: number;
mappers: number;
useCases: number;
providers: number;
}
export interface OpenApiSchema {
properties?: Record<
string,
{
type?: string;
description?: string;
$ref?: string;
items?: { $ref?: string };
}
>;
required?: string[];
description?: string;
}
export interface OpenApiOperation {
tags?: string[];
operationId?: string;
summary?: string;
description?: string;
parameters?: Array<{
name: string;
in: string;
required: boolean;
description?: string;
schema?: { type?: string };
}>;
requestBody?: {
description?: string;
content?: Record<
string,
{
schema?: {
$ref?: string;
type?: string;
};
}
>;
};
responses?: Record<
string,
{
content?: Record<
string,
{
schema?: {
$ref?: string;
type?: string;
items?: { $ref?: string };
};
}
>;
}
>;
}
export interface TagOperation {
nickname: string;
summary: string;
notes: string;
httpMethod: string;
path: string;
allParams: unknown[];
hasQueryParams: boolean;
queryParams: unknown[];
hasBodyParam: boolean;
bodyParam: string;
returnType: string | boolean;
returnBaseType: string | boolean;
isListContainer: boolean;
vendorExtensions: Record<string, unknown>;
} }
// Generar Clean Architecture con Mustache // Generar Clean Architecture con Mustache
function generateCleanArchitecture(analysis, outputDir, templatesDir) { function generateCleanArchitecture(
analysis: SwaggerAnalysis,
outputDir: string,
templatesDir: string
): GeneratedCount {
logStep('Generando artefactos de Clean Architecture usando Mustache...'); logStep('Generando artefactos de Clean Architecture usando Mustache...');
let generatedCount = { models: 0, repositories: 0, mappers: 0, useCases: 0, providers: 0 }; const generatedCount: GeneratedCount = {
models: 0,
repositories: 0,
mappers: 0,
useCases: 0,
providers: 0
};
const schemas =
(analysis.swagger as { components?: { schemas?: Record<string, unknown> } }).components
?.schemas || {};
const schemas = analysis.swagger.components?.schemas || {};
// 1. Generar Modelos, Entidades y Mappers a partir de Schemas // 1. Generar Modelos, Entidades y Mappers a partir de Schemas
Object.keys(schemas).forEach(schemaName => { Object.keys(schemas).forEach((schemaName) => {
// Sanitizar nombres base para que coincidan con cómo OpenAPI los emite (sin Dto duplicado) // Sanitizar nombres base para que coincidan con cómo OpenAPI los emite (sin Dto duplicado)
const baseName = schemaName.replace(/Dto$/, ''); const baseName = schemaName.replace(/Dto$/, '');
// variables para model // variables para model
const rawProperties = schemas[schemaName].properties || {};
const requiredProps = schemas[schemaName].required || []; const schemaObj = schemas[schemaName] as OpenApiSchema;
const rawProperties = schemaObj.properties || {};
const varsMap = Object.keys(rawProperties).map(k => { const requiredProps: string[] = schemaObj.required || [];
const varsMap = Object.keys(rawProperties).map((k) => {
let tsType = mapSwaggerTypeToTs(rawProperties[k].type); let tsType = mapSwaggerTypeToTs(rawProperties[k].type);
if (rawProperties[k].$ref) { if (rawProperties[k].$ref) {
// Simple extración del tipo de la ref // Simple extración del tipo de la ref
tsType = rawProperties[k].$ref.split('/').pop(); tsType = rawProperties[k].$ref.split('/').pop() || 'unknown';
} else if (rawProperties[k].type === 'array' && rawProperties[k].items?.$ref) { } else if (rawProperties[k].type === 'array' && rawProperties[k].items?.$ref) {
tsType = `Array<${rawProperties[k].items.$ref.split('/').pop()}>`; tsType = `Array<${rawProperties[k].items.$ref.split('/').pop()}>`;
} }
return { return {
name: k, name: k,
dataType: tsType, dataType: tsType,
description: rawProperties[k].description || '', description: rawProperties[k].description || '',
required: requiredProps.includes(k) required: requiredProps.includes(k)
@@ -231,15 +347,17 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
}); });
const modelViewData = { const modelViewData = {
models: [{ models: [
model: { {
classname: baseName, model: {
classFilename: baseName.toLowerCase(), classname: baseName,
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1), classFilename: baseName.toLowerCase(),
description: schemas[schemaName].description || '', classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1),
vars: varsMap description: schemaObj.description || '',
vars: varsMap
}
} }
}], ],
// Para plantillas que esperan allModels o importaciones (mapper) // Para plantillas que esperan allModels o importaciones (mapper)
allModels: [{ model: { vars: varsMap } }] allModels: [{ model: { vars: varsMap } }]
}; };
@@ -247,14 +365,16 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
// Y para mapper.mustache, que además pide apiInfo // Y para mapper.mustache, que además pide apiInfo
const mapperViewData = { const mapperViewData = {
...modelViewData, ...modelViewData,
apiInfo: { apiInfo: {
apis: [{ apis: [
operations: { {
classname: baseName, operations: {
classFilename: baseName.toLowerCase(), classname: baseName,
classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1), classFilename: baseName.toLowerCase(),
} classVarName: baseName.charAt(0).toLowerCase() + baseName.slice(1)
}] }
}
]
} }
}; };
@@ -263,7 +383,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(modelTemplatePath)) { if (fs.existsSync(modelTemplatePath)) {
const template = fs.readFileSync(modelTemplatePath, 'utf8'); const template = fs.readFileSync(modelTemplatePath, 'utf8');
const output = mustache.render(template, modelViewData); const output = mustache.render(template, modelViewData);
const destPath = path.join(outputDir, 'entities/models', `${baseName.toLowerCase()}.model.ts`); const destPath = path.join(
outputDir,
'entities/models',
`${baseName.toLowerCase()}.model.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.models++; generatedCount.models++;
logInfo(` ${baseName.toLowerCase()}.model.ts → ${path.relative(process.cwd(), destPath)}`); logInfo(` ${baseName.toLowerCase()}.model.ts → ${path.relative(process.cwd(), destPath)}`);
@@ -281,32 +405,32 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
}); });
// 2. Generar Casos de Uso y Repositorios a partir de Paths/Tags // 2. Generar Casos de Uso y Repositorios a partir de Paths/Tags
const tagsMap = {}; const tagsMap: Record<string, TagOperation[]> = {};
// Agrupar operaciones por Tag // Agrupar operaciones por Tag
Object.keys(analysis.paths).forEach(pathKey => { Object.keys(analysis.paths).forEach((pathKey) => {
const pathObj = analysis.paths[pathKey]; const pathObj = analysis.paths[pathKey] as Record<string, unknown>;
Object.keys(pathObj).forEach(method => { Object.keys(pathObj).forEach((method) => {
const op = pathObj[method]; const op = pathObj[method] as OpenApiOperation;
if (op.tags && op.tags.length > 0) { if (op.tags && op.tags.length > 0) {
const tag = op.tags[0]; // Usamos el primer tag const tag = op.tags[0]; // Usamos el primer tag
if (!tagsMap[tag]) tagsMap[tag] = []; if (!tagsMap[tag]) tagsMap[tag] = [];
// Parsear parámetros // Parsear parámetros
const allParams = (op.parameters || []).map(p => ({ const allParams = (op.parameters || []).map((p) => ({
paramName: p.name, paramName: p.name,
dataType: mapSwaggerTypeToTs(p.schema?.type), dataType: mapSwaggerTypeToTs(p.schema?.type || ''),
description: p.description || '', description: p.description || '',
required: p.required required: p.required
})); }));
// Añadir body como parámetro si existe // Añadir body como parámetro si existe
if (op.requestBody) { if (op.requestBody) {
let bodyType = 'any'; let bodyType = 'unknown';
const content = op.requestBody.content?.['application/json']?.schema; const content = op.requestBody.content?.['application/json']?.schema;
if (content) { if (content) {
if (content.$ref) bodyType = content.$ref.split('/').pop(); if (content.$ref) bodyType = content.$ref.split('/').pop() || 'unknown';
else if (content.type) bodyType = mapSwaggerTypeToTs(content.type); else if (content.type) bodyType = mapSwaggerTypeToTs(content.type);
} }
allParams.push({ allParams.push({
paramName: 'body', paramName: 'body',
@@ -315,21 +439,21 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
required: true required: true
}); });
} }
// Parsear respuestas // Parsear respuestas
let returnType = 'void'; let returnType = 'void';
let returnBaseType = 'void'; let returnBaseType = 'void';
let isListContainer = false; let isListContainer = false;
const responseSchema = op.responses?.['200']?.content?.['application/json']?.schema; const responseSchema = op.responses?.['200']?.content?.['application/json']?.schema;
if (responseSchema) { if (responseSchema) {
if (responseSchema.$ref) { if (responseSchema.$ref) {
returnType = responseSchema.$ref.split('/').pop(); returnType = responseSchema.$ref.split('/').pop() || 'unknown';
returnBaseType = returnType; returnBaseType = returnType;
} else if (responseSchema.type === 'array' && responseSchema.items?.$ref) { } else if (responseSchema.type === 'array' && responseSchema.items?.$ref) {
returnBaseType = responseSchema.items.$ref.split('/').pop(); returnBaseType = responseSchema.items.$ref.split('/').pop() || 'unknown';
returnType = `Array<${returnBaseType}>`; returnType = `Array<${returnBaseType}>`;
isListContainer = true; isListContainer = true;
} }
} }
tagsMap[tag].push({ tagsMap[tag].push({
@@ -338,9 +462,17 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
notes: op.description || '', notes: op.description || '',
httpMethod: method.toLowerCase(), httpMethod: method.toLowerCase(),
path: pathKey, path: pathKey,
allParams: allParams.map((p, i) => ({ ...p, '-last': i === allParams.length - 1 })), allParams: allParams.map((p, i: number) => ({
hasQueryParams: (op.parameters || []).some(p => p.in === 'query'), ...p,
queryParams: (op.parameters || []).filter(p => p.in === 'query').map((p, i, arr) => ({ paramName: p.name, '-last': i === arr.length - 1 })), '-last': i === allParams.length - 1
})),
hasQueryParams: (op.parameters || []).some((p) => p.in === 'query'),
queryParams: (op.parameters || [])
.filter((p) => p.in === 'query')
.map((p, i: number, arr: unknown[]) => ({
paramName: p.name,
'-last': i === arr.length - 1
})),
hasBodyParam: !!op.requestBody, hasBodyParam: !!op.requestBody,
bodyParam: 'body', bodyParam: 'body',
returnType: returnType !== 'void' ? returnType : false, returnType: returnType !== 'void' ? returnType : false,
@@ -353,27 +485,33 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
}); });
// Generar por cada Tag // Generar por cada Tag
Object.keys(tagsMap).forEach(tag => { Object.keys(tagsMap).forEach((tag) => {
// Buscar si ese tag cruza con alguna entidad para importarla // Buscar si ese tag cruza con alguna entidad para importarla
const imports = []; const imports: { classname: string; classFilename: string; classVarName: string }[] = [];
Object.keys(schemas).forEach(s => { Object.keys(schemas).forEach((s) => {
// Import heurístico burdo // Import heurístico burdo
if (tagsMap[tag].some(op => op.returnType === s || op.returnType === `Array<${s}>`)) { if (tagsMap[tag].some((op) => op.returnType === s || op.returnType === `Array<${s}>`)) {
imports.push({ classname: s, classFilename: s.toLowerCase(), classVarName: s.charAt(0).toLowerCase() + s.slice(1) }); imports.push({
classname: s,
classFilename: s.toLowerCase(),
classVarName: s.charAt(0).toLowerCase() + s.slice(1)
});
} }
}); });
const apiViewData = { const apiViewData = {
apiInfo: { apiInfo: {
apis: [{ apis: [
operations: { {
classname: tag, operations: {
classFilename: tag.toLowerCase(), classname: tag,
constantName: tag.toUpperCase().replace(/[^A-Z0-9]/g, '_'), classFilename: tag.toLowerCase(),
operation: tagsMap[tag], constantName: tag.toUpperCase().replace(/[^A-Z0-9]/g, '_'),
imports: imports operation: tagsMap[tag],
imports: imports
}
} }
}] ]
} }
}; };
@@ -382,7 +520,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(ucContractPath)) { if (fs.existsSync(ucContractPath)) {
const template = fs.readFileSync(ucContractPath, 'utf8'); const template = fs.readFileSync(ucContractPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.contract.ts`); const destPath = path.join(
outputDir,
'domain/use-cases',
`${tag.toLowerCase()}.use-cases.contract.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.useCases++; generatedCount.useCases++;
} }
@@ -392,7 +534,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(ucImplPath)) { if (fs.existsSync(ucImplPath)) {
const template = fs.readFileSync(ucImplPath, 'utf8'); const template = fs.readFileSync(ucImplPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'domain/use-cases', `${tag.toLowerCase()}.use-cases.impl.ts`); const destPath = path.join(
outputDir,
'domain/use-cases',
`${tag.toLowerCase()}.use-cases.impl.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.useCases++; generatedCount.useCases++;
} }
@@ -402,7 +548,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(repoContractPath)) { if (fs.existsSync(repoContractPath)) {
const template = fs.readFileSync(repoContractPath, 'utf8'); const template = fs.readFileSync(repoContractPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'domain/repositories', `${tag.toLowerCase()}.repository.contract.ts`); const destPath = path.join(
outputDir,
'domain/repositories',
`${tag.toLowerCase()}.repository.contract.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.repositories++; generatedCount.repositories++;
} }
@@ -412,7 +562,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(repoImplPath)) { if (fs.existsSync(repoImplPath)) {
const template = fs.readFileSync(repoImplPath, 'utf8'); const template = fs.readFileSync(repoImplPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'data/repositories', `${tag.toLowerCase()}.repository.impl.ts`); const destPath = path.join(
outputDir,
'data/repositories',
`${tag.toLowerCase()}.repository.impl.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.repositories++; generatedCount.repositories++;
} }
@@ -422,7 +576,11 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(ucProviderPath)) { if (fs.existsSync(ucProviderPath)) {
const template = fs.readFileSync(ucProviderPath, 'utf8'); const template = fs.readFileSync(ucProviderPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'di/use-cases', `${tag.toLowerCase()}.use-cases.provider.ts`); const destPath = path.join(
outputDir,
'di/use-cases',
`${tag.toLowerCase()}.use-cases.provider.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.providers++; generatedCount.providers++;
} }
@@ -432,29 +590,49 @@ function generateCleanArchitecture(analysis, outputDir, templatesDir) {
if (fs.existsSync(repoProviderPath)) { if (fs.existsSync(repoProviderPath)) {
const template = fs.readFileSync(repoProviderPath, 'utf8'); const template = fs.readFileSync(repoProviderPath, 'utf8');
const output = mustache.render(template, apiViewData); const output = mustache.render(template, apiViewData);
const destPath = path.join(outputDir, 'di/repositories', `${tag.toLowerCase()}.repository.provider.ts`); const destPath = path.join(
outputDir,
'di/repositories',
`${tag.toLowerCase()}.repository.provider.ts`
);
fs.writeFileSync(destPath, output); fs.writeFileSync(destPath, output);
generatedCount.providers++; generatedCount.providers++;
} }
}); });
logSuccess(`${generatedCount.models} Models, ${generatedCount.repositories} Repos, ${generatedCount.useCases} Use Cases, ${generatedCount.mappers} Mappers, ${generatedCount.providers} Providers generados con Mustache`); logSuccess(
`${generatedCount.models} Models, ${generatedCount.repositories} Repos, ${generatedCount.useCases} Use Cases, ${generatedCount.mappers} Mappers, ${generatedCount.providers} Providers generados con Mustache`
);
return generatedCount; return generatedCount;
} }
// Limpiar directorio temporal // Limpiar directorio temporal
function cleanup(tempDir) { function cleanup(tempDir: string): void {
if (fs.existsSync(tempDir)) { if (fs.existsSync(tempDir)) {
fs.removeSync(tempDir); fs.removeSync(tempDir);
logInfo('Archivos temporales eliminados'); logInfo('Archivos temporales eliminados');
} }
} }
interface GenerationReport {
timestamp: string;
tags: number;
endpoints: number;
outputDirectory: string;
structure: {
dtos: number;
repositories: number;
mappers: number;
useCases: number;
providers: number;
};
}
// Generar reporte // Generar reporte
function generateReport(outputDir, analysis) { function generateReport(outputDir: string, analysis: SwaggerAnalysis): GenerationReport {
logStep('Generando reporte de generación...'); logStep('Generando reporte de generación...');
const report = { const report: GenerationReport = {
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
tags: analysis.tags.length, tags: analysis.tags.length,
endpoints: Object.keys(analysis.paths).length, endpoints: Object.keys(analysis.paths).length,
@@ -464,78 +642,82 @@ function generateReport(outputDir, analysis) {
repositories: fs.readdirSync(path.join(outputDir, 'data/repositories')).length, repositories: fs.readdirSync(path.join(outputDir, 'data/repositories')).length,
mappers: fs.readdirSync(path.join(outputDir, 'data/mappers')).length, mappers: fs.readdirSync(path.join(outputDir, 'data/mappers')).length,
useCases: fs.readdirSync(path.join(outputDir, 'domain/use-cases')).length, useCases: fs.readdirSync(path.join(outputDir, 'domain/use-cases')).length,
providers: fs.readdirSync(path.join(outputDir, 'di/repositories')).length + fs.readdirSync(path.join(outputDir, 'di/use-cases')).length providers:
fs.readdirSync(path.join(outputDir, 'di/repositories')).length +
fs.readdirSync(path.join(outputDir, 'di/use-cases')).length
} }
}; };
const reportPath = path.join(process.cwd(), 'generation-report.json'); const reportPath = path.join(process.cwd(), 'generation-report.json');
fs.writeJsonSync(reportPath, report, { spaces: 2 }); fs.writeJsonSync(reportPath, report, { spaces: 2 });
logSuccess(`Reporte guardado en: ${reportPath}`); logSuccess(`Reporte guardado en: ${reportPath}`);
return report; return report;
} }
// Función principal // Función principal
async function main() { async function main(): Promise<void> {
console.log('\n' + '='.repeat(60)); console.log('\n' + '='.repeat(60));
log(' OpenAPI Clean Architecture Generator', 'bright'); log(' OpenAPI Clean Architecture Generator', 'bright');
log(' Angular + Clean Architecture Code Generator', 'cyan'); log(' Angular + Clean Architecture Code Generator', 'cyan');
console.log('='.repeat(60) + '\n'); console.log('='.repeat(60) + '\n');
// Validar archivo de entrada // Validar archivo de entrada
if (!fs.existsSync(options.input)) { if (!fs.existsSync(options.input)) {
logError(`Archivo no encontrado: ${options.input}`); logError(`Archivo no encontrado: ${options.input}`);
process.exit(1); process.exit(1);
} }
logInfo(`Archivo de entrada: ${options.input}`); logInfo(`Archivo de entrada: ${options.input}`);
logInfo(`Directorio de salida: ${options.output}`); logInfo(`Directorio de salida: ${options.output}`);
logInfo(`Templates: ${options.templates}`); logInfo(`Templates: ${options.templates}`);
if (options.dryRun) { if (options.dryRun) {
logWarning('Modo DRY RUN - No se generarán archivos'); logWarning('Modo DRY RUN - No se generarán archivos');
} }
// Verificar/Instalar OpenAPI Generator // Verificar/Instalar OpenAPI Generator
if (!checkOpenApiGenerator()) { if (!checkOpenApiGenerator()) {
logWarning('OpenAPI Generator CLI no encontrado'); logWarning('OpenAPI Generator CLI no encontrado');
if (!options.skipInstall) { if (!options.skipInstall) {
installOpenApiGenerator(); installOpenApiGenerator();
} else { } else {
logError('Instala openapi-generator-cli con: npm install -g @openapitools/openapi-generator-cli'); logError(
'Instala openapi-generator-cli con: npm install -g @openapitools/openapi-generator-cli'
);
process.exit(1); process.exit(1);
} }
} else { } else {
logSuccess('OpenAPI Generator CLI encontrado'); logSuccess('OpenAPI Generator CLI encontrado');
} }
// Analizar Swagger // Analizar Swagger
const analysis = analyzeSwagger(options.input); const analysis = analyzeSwagger(options.input);
if (options.dryRun) { if (options.dryRun) {
logInfo('Finalizando en modo DRY RUN'); logInfo('Finalizando en modo DRY RUN');
return; return;
} }
// Crear estructura de directorios // Crear estructura de directorios
createDirectoryStructure(options.output); createDirectoryStructure(options.output);
// Generar código // Generar código
const tempDir = generateCode(options.input, options.templates); const tempDir = generateCode(options.input, options.templates);
// Organizar archivos // Organizar archivos
organizeFiles(tempDir, options.output); organizeFiles(tempDir, options.output);
// Crear componentes Clean Architecture con nuestro script de Mustache // Crear componentes Clean Architecture con nuestro script de Mustache
generateCleanArchitecture(analysis, options.output, options.templates); generateCleanArchitecture(analysis, options.output, options.templates);
// Limpiar // Limpiar
cleanup(tempDir); cleanup(tempDir);
// Generar reporte // Generar reporte
const report = generateReport(options.output, analysis); const report = generateReport(options.output, analysis);
// Resumen final // Resumen final
console.log('\n' + '='.repeat(60)); console.log('\n' + '='.repeat(60));
log(' ✨ Generación completada con éxito', 'green'); log(' ✨ Generación completada con éxito', 'green');
@@ -550,8 +732,9 @@ async function main() {
} }
// Ejecutar // Ejecutar
main().catch(error => { main().catch((error: unknown) => {
logError(`Error fatal: ${error.message}`); const err = error as Error;
logError(`Error fatal: ${err.message}`);
console.error(error); console.error(error);
process.exit(1); process.exit(1);
}); });

View File

@@ -2,12 +2,18 @@
"name": "openapi-clean-arch-generator", "name": "openapi-clean-arch-generator",
"version": "1.0.0", "version": "1.0.0",
"description": "Generador de código Angular con Clean Architecture desde OpenAPI/Swagger", "description": "Generador de código Angular con Clean Architecture desde OpenAPI/Swagger",
"main": "generate.js", "main": "dist/generate.js",
"bin": { "bin": {
"generate-clean-arch": "./generate.js" "generate-clean-arch": "./dist/generate.js"
}, },
"scripts": { "scripts": {
"generate": "node generate.js", "build": "tsc",
"prepublishOnly": "npm run build",
"generate": "node dist/generate.js",
"generate:dev": "ts-node main.ts",
"lint": "eslint 'main.ts' -f unix",
"lint:fix": "eslint 'main.ts' --fix -f unix",
"format": "prettier --write .",
"setup": "npm install -g @openapitools/openapi-generator-cli" "setup": "npm install -g @openapitools/openapi-generator-cli"
}, },
"keywords": [ "keywords": [
@@ -28,5 +34,22 @@
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/fs-extra": "^11.0.4",
"@types/js-yaml": "^4.0.9",
"@types/mustache": "^4.2.6",
"@types/node": "^25.5.0",
"@typescript-eslint/eslint-plugin": "^8.57.1",
"@typescript-eslint/parser": "^8.57.1",
"eslint": "^10.1.0",
"eslint-config-prettier": "^10.1.8",
"eslint-formatter-unix": "^9.0.1",
"eslint-plugin-prettier": "^5.5.5",
"prettier": "^3.8.1",
"ts-node": "^10.9.2",
"typescript": "^5.9.3",
"typescript-eslint": "^8.57.1"
} }
} }

17
tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true
},
"include": ["main.ts"],
"exclude": ["node_modules", "dist"]
}