@mks2508/better-logger 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/dist/chunks/{Logger-Cbi1f10o.js → Logger-CKqzXDh3.js} +2 -2
  2. package/dist/chunks/{Logger-Cbi1f10o.js.map → Logger-CKqzXDh3.js.map} +1 -1
  3. package/dist/chunks/{Logger-BZ7B7OXE.js → Logger-D_vuKP4l.js} +2 -2
  4. package/dist/chunks/{Logger-BZ7B7OXE.js.map → Logger-D_vuKP4l.js.map} +1 -1
  5. package/dist/chunks/cli-module-B-njrTWb.js +2 -0
  6. package/dist/chunks/cli-module-B-njrTWb.js.map +1 -0
  7. package/dist/chunks/{cli-module-ClIJmaT8.js → cli-module-Cx7qotPY.js} +16 -9
  8. package/dist/chunks/cli-module-Cx7qotPY.js.map +1 -0
  9. package/dist/cli.cjs +1 -1
  10. package/dist/cli.js +1 -1
  11. package/dist/exports.cjs +1 -1
  12. package/dist/exports.js +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +3 -3
  15. package/dist/styling.cjs +1 -1
  16. package/dist/styling.js +2 -2
  17. package/dist/terminal/formatter.d.ts.map +1 -1
  18. package/package.json +5 -1
  19. package/.claude/settings.local.json +0 -48
  20. package/.github/workflows/ci-quality.yml +0 -357
  21. package/.github/workflows/docs-demo.yml +0 -119
  22. package/.github/workflows/releases-core.yml +0 -512
  23. package/.github/workflows/releases-full.yml +0 -582
  24. package/.github/workflows-backup/ci.yml +0 -221
  25. package/.github/workflows-backup/nightly.yml +0 -196
  26. package/.github/workflows-backup/release-optimized.yml +0 -373
  27. package/.github/workflows-backup/release.yml +0 -269
  28. package/.release-notes-0.2.0.md +0 -129
  29. package/.yamllint +0 -28
  30. package/CHANGELOG.json +0 -1076
  31. package/CHANGELOG.md +0 -209
  32. package/CLAUDE.md +0 -217
  33. package/bun.lock +0 -333
  34. package/demo.html +0 -847
  35. package/dist/chunks/cli-module-CadqgZ1Z.js +0 -2
  36. package/dist/chunks/cli-module-CadqgZ1Z.js.map +0 -1
  37. package/dist/chunks/cli-module-ClIJmaT8.js.map +0 -1
  38. package/docs/API.md +0 -918
  39. package/docs/CORE.md +0 -264
  40. package/docs/DEVELOPMENT.md +0 -731
  41. package/docs/EXPORTS.md +0 -467
  42. package/docs/PACKAGES.md +0 -244
  43. package/docs/STYLING.md +0 -405
  44. package/docs/_config.yml +0 -36
  45. package/docs/index.md +0 -179
  46. package/examples/README.md +0 -208
  47. package/examples/basic-logging.js +0 -75
  48. package/examples/data-export.js +0 -234
  49. package/examples/package.json +0 -16
  50. package/examples/performance-timing.js +0 -170
  51. package/examples/simplified-api.js +0 -124
  52. package/examples/styling-themes.js +0 -207
  53. package/index.html +0 -358
  54. package/packages/core/package.json +0 -57
  55. package/packages/exports/package.json +0 -41
  56. package/packages/nodejs-opentui/README.md +0 -232
  57. package/packages/nodejs-opentui/package.json +0 -72
  58. package/packages/nodejs-opentui/src/LogRenderer.ts +0 -171
  59. package/packages/nodejs-opentui/src/OpenTUILogHandler.ts +0 -178
  60. package/packages/nodejs-opentui/src/components/LogBadge.tsx +0 -131
  61. package/packages/nodejs-opentui/src/index.ts +0 -133
  62. package/packages/nodejs-opentui/src/types.ts +0 -158
  63. package/packages/nodejs-opentui/tsconfig.json +0 -20
  64. package/packages/styling/package.json +0 -41
  65. package/playground/demo-all.ts +0 -95
  66. package/playground/demo-box.ts +0 -85
  67. package/playground/demo-levels.ts +0 -56
  68. package/playground/demo-real-world.ts +0 -98
  69. package/playground/demo-spinner.ts +0 -77
  70. package/playground/demo-steps.ts +0 -72
  71. package/playground/demo-table.ts +0 -83
  72. package/project-utils/README.md +0 -172
  73. package/project-utils/auto-release-gemini.ts +0 -1193
  74. package/project-utils/auto-release-ui.ts +0 -1329
  75. package/project-utils/commit-generator.ts +0 -1385
  76. package/project-utils/commit-ui.ts +0 -264
  77. package/project-utils/git-utils.ts +0 -199
  78. package/project-utils/github-release-manager.ts +0 -466
  79. package/project-utils/project-config.ts +0 -260
  80. package/project-utils/prompt-templates.js +0 -345
  81. package/project-utils/prompt-templates.ts +0 -422
  82. package/project-utils/version-manager.ts +0 -1078
  83. package/public/vite.svg +0 -1
  84. package/src/Logger.ts +0 -1858
  85. package/src/ScopedLogger.ts +0 -256
  86. package/src/cli/CommandProcessor.ts +0 -248
  87. package/src/cli/commands/ConfigCommand.ts +0 -93
  88. package/src/cli/commands/ExportCommand.ts +0 -276
  89. package/src/cli/commands/HistoryCommand.ts +0 -117
  90. package/src/cli/commands/StatusCommand.ts +0 -112
  91. package/src/cli/commands/ThemeCommand.ts +0 -88
  92. package/src/cli/help.ts +0 -127
  93. package/src/cli/index.ts +0 -71
  94. package/src/cli-module.ts +0 -21
  95. package/src/cli-primitives/box.ts +0 -86
  96. package/src/cli-primitives/cli-table.ts +0 -62
  97. package/src/cli-primitives/divider.ts +0 -17
  98. package/src/cli-primitives/header.ts +0 -18
  99. package/src/cli-primitives/index.ts +0 -13
  100. package/src/cli-primitives/server-fallback.ts +0 -54
  101. package/src/cli-primitives/spinner.ts +0 -133
  102. package/src/cli-primitives/step.ts +0 -22
  103. package/src/constants.ts +0 -313
  104. package/src/core.ts +0 -397
  105. package/src/example.ts +0 -210
  106. package/src/exports-module.ts +0 -311
  107. package/src/handlers/AnalyticsLogHandler.ts +0 -22
  108. package/src/handlers/ExportLogHandler.ts +0 -610
  109. package/src/handlers/FileLogHandler.ts +0 -169
  110. package/src/handlers/RemoteLogHandler.ts +0 -42
  111. package/src/handlers/index.ts +0 -8
  112. package/src/hooks/HookManager.ts +0 -177
  113. package/src/hooks/index.ts +0 -1
  114. package/src/index.ts +0 -395
  115. package/src/main.ts +0 -196
  116. package/src/serializers/SerializerRegistry.ts +0 -173
  117. package/src/serializers/index.ts +0 -1
  118. package/src/style.css +0 -96
  119. package/src/styling/LogStyleBuilder.ts +0 -355
  120. package/src/styling/SemanticStyles.ts +0 -380
  121. package/src/styling/SmartPresets.ts +0 -288
  122. package/src/styling/StyleBuilder.ts +0 -319
  123. package/src/styling/StyleCache.ts +0 -131
  124. package/src/styling/banners.ts +0 -168
  125. package/src/styling/index.ts +0 -27
  126. package/src/styling/themes.ts +0 -235
  127. package/src/styling-module.ts +0 -244
  128. package/src/terminal/color-converter.ts +0 -315
  129. package/src/terminal/formatter.ts +0 -236
  130. package/src/terminal/terminal-renderer.ts +0 -342
  131. package/src/transports/ConsoleTransport.ts +0 -28
  132. package/src/transports/FileTransport.ts +0 -53
  133. package/src/transports/HttpTransport.ts +0 -56
  134. package/src/transports/TransportManager.ts +0 -130
  135. package/src/transports/index.ts +0 -4
  136. package/src/types/core.ts +0 -417
  137. package/src/types/handlers.ts +0 -95
  138. package/src/types/hooks.ts +0 -45
  139. package/src/types/index.ts +0 -83
  140. package/src/types/serializers.ts +0 -30
  141. package/src/types/transports.ts +0 -52
  142. package/src/typescript.svg +0 -1
  143. package/src/utils/adapter.ts +0 -291
  144. package/src/utils/ansi-colors.ts +0 -333
  145. package/src/utils/environment-detector.ts +0 -170
  146. package/src/utils/environment.ts +0 -94
  147. package/src/utils/formatting.ts +0 -332
  148. package/src/utils/index.ts +0 -33
  149. package/src/utils/opentui-detection.ts +0 -138
  150. package/src/utils/output.ts +0 -227
  151. package/src/utils/stackTrace.ts +0 -144
  152. package/src/utils/timestamps.ts +0 -80
  153. package/src/vite-env.d.ts +0 -1
  154. package/src/writers/BufferWriter.ts +0 -157
  155. package/src/writers/index.ts +0 -6
  156. package/test-core-browser.html +0 -237
  157. package/test-core-node.js +0 -63
  158. package/tests/test-conflict-resolution.ts +0 -391
  159. package/tests/validate-workflows.sh +0 -131
  160. package/tests/yaml-autofix.sh +0 -146
  161. package/tsconfig.json +0 -50
  162. package/vite.config.ts +0 -256
@@ -1,1193 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Auto-Release Manager con Integración Gemini para Better Logger
5
- * Sistema avanzado que usa AI para generar documentación y commits inteligentes
6
- */
7
-
8
- import { spawn } from 'child_process';
9
- import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'fs';
10
- import { join, dirname } from 'path';
11
- import { createReleasePrompt, BETTER_LOGGER_PROJECT_CONFIG, type GeminiPromptConfig } from './prompt-templates';
12
-
13
- interface ChangelogData {
14
- current_version: string;
15
- versions: Array<{
16
- version: string;
17
- date: string;
18
- type: string;
19
- title: string;
20
- changes: Array<{
21
- type: string;
22
- title: string;
23
- description: string;
24
- }>;
25
- technical_notes: string;
26
- breaking_changes: string[];
27
- commit_hash: string;
28
- prefix?: string;
29
- }>;
30
- }
31
-
32
- interface ReleaseInfo {
33
- version: string;
34
- prefix: string;
35
- major: number;
36
- minor: number;
37
- patch: number;
38
- }
39
-
40
- class AutoReleaseManagerAI {
41
- private projectRoot: string;
42
- private releaseDir: string;
43
- private changelogPath: string;
44
- private tempDir: string;
45
- private forceMode: boolean;
46
- private useAI: boolean;
47
- private noGitHub: boolean;
48
-
49
- // Parámetros de contexto mejorados
50
- private focusArea: string;
51
- private targetPlatform: string;
52
- private urgency: string;
53
- private targetAudience: string;
54
- private dependencies: string;
55
-
56
- // Nuevos parámetros para version manager y commit generator
57
- private versionType: string;
58
- private versionPrefix: string;
59
- private workType: string;
60
- private affectedComponents: string;
61
- private context: string;
62
- private performanceImpact: string;
63
- private publishNpm: boolean;
64
- private publishGithub: boolean;
65
- private dryRun: boolean;
66
- private autoApprove: boolean;
67
- private autoCommit: boolean;
68
-
69
- constructor() {
70
- this.projectRoot = process.cwd();
71
- this.releaseDir = join(this.projectRoot, 'dist');
72
- this.changelogPath = join(this.projectRoot, 'CHANGELOG.json');
73
- this.tempDir = join(this.projectRoot, 'project-utils/.temp');
74
- this.forceMode = process.argv.includes('--force');
75
- this.useAI = process.argv.includes('--ai') || !process.argv.includes('--no-ai');
76
- this.noGitHub = process.argv.includes('--no-github');
77
-
78
- // Parsear parámetros de contexto mejorados
79
- this.focusArea = this.getArgValue('--focus') || '';
80
- this.targetPlatform = this.getArgValue('--target-platform') || 'universal';
81
- this.urgency = this.getArgValue('--urgency') || 'normal';
82
- this.targetAudience = this.getArgValue('--audience') || 'public';
83
- this.dependencies = this.getArgValue('--dependencies') || 'both';
84
-
85
- // Nuevos parámetros
86
- this.versionType = this.getArgValue('--type') || 'patch';
87
- this.versionPrefix = this.getArgValue('--prefix') || '';
88
- this.workType = this.getArgValue('--work-type') || 'feature';
89
- this.affectedComponents = this.getArgValue('--affected-components') || '';
90
- this.context = this.getArgValue('--context') || '';
91
- this.performanceImpact = this.getArgValue('--performance-impact') || 'none';
92
- this.publishNpm = process.argv.includes('--publish-npm');
93
- this.publishGithub = process.argv.includes('--publish-github');
94
- this.dryRun = process.argv.includes('--dry-run');
95
- this.autoApprove = process.argv.includes('--auto-approve');
96
- this.autoCommit = process.argv.includes('--auto-commit') || this.autoApprove;
97
-
98
- // Crear directorio temporal si no existe
99
- if (!existsSync(this.tempDir)) {
100
- mkdirSync(this.tempDir, { recursive: true });
101
- }
102
- }
103
-
104
- /**
105
- * Obtiene valor de un argumento específico
106
- */
107
- private getArgValue(argName: string): string | undefined {
108
- const args = process.argv;
109
- const argIndex = args.indexOf(argName);
110
- if (argIndex > -1 && args[argIndex + 1] && !args[argIndex + 1].startsWith('--')) {
111
- return args[argIndex + 1];
112
- }
113
- return undefined;
114
- }
115
-
116
- async run(): Promise<void> {
117
- console.log('🚀 Auto-Release Manager AI iniciado...\n');
118
- if (this.useAI) {
119
- console.log('🤖 Modo AI activado - Generación inteligente habilitada');
120
- } else {
121
- console.log('📝 Modo básico - Sin generación AI');
122
- }
123
-
124
- try {
125
- // Paso 0: Detectar y manejar cambios no commiteados
126
- await this.handleUncommittedChanges();
127
-
128
- // Paso 1: Detectar cambios remotos y hacer pull
129
- await this.pullRemoteChanges();
130
-
131
- // Paso 2: Instalar dependencias
132
- await this.installNodeDependencies();
133
-
134
- // Paso 3: Generar nueva versión usando version-manager
135
- await this.generateNewVersion();
136
-
137
- // Paso 4: Verificar versión actual del changelog (actualizada)
138
- const currentVersion = this.getCurrentVersion();
139
- console.log(`📋 Versión generada: ${currentVersion}`);
140
-
141
- // Paso 5: Verificar última release existente
142
- const latestRelease = this.getLatestRelease();
143
- console.log(`📦 Última release: ${latestRelease || 'ninguna'}`);
144
-
145
- // Paso 6: Comparar versiones
146
- if (latestRelease === currentVersion && !this.forceMode) {
147
- console.log('✅ No hay nueva versión para compilar. Release ya existe.');
148
- console.log('💡 Usa --force para forzar la recompilación.');
149
- return;
150
- }
151
-
152
- if (this.forceMode && latestRelease === currentVersion) {
153
- console.log('🔧 Modo forzado activado. Regenerando release existente...');
154
- } else {
155
- console.log(`🆕 Nueva versión generada: ${currentVersion}`);
156
- }
157
-
158
- console.log('⚡ Iniciando proceso de compilación y release...\n');
159
-
160
- // Paso 7: Compilar aplicación
161
- await this.buildApplication();
162
-
163
- // Paso 8: Crear estructura de release
164
- const releaseInfo = this.parseVersion(currentVersion);
165
- await this.createReleaseStructure(releaseInfo);
166
-
167
- // Paso 9: Copiar archivos de distribución
168
- await this.copyDistFiles(releaseInfo);
169
-
170
- // Paso 10: Generar documentación (con AI si está disponible)
171
- await this.generateReleaseDocumentation(releaseInfo);
172
-
173
- // Paso 11: Commit y push con AI
174
- await this.commitAndPushReleaseAI(releaseInfo);
175
-
176
- // Paso 12: Crear GitHub Release (si está configurado)
177
- await this.createGitHubRelease(releaseInfo);
178
-
179
- // Paso 13: Publicar en registros NPM (si está habilitado)
180
- await this.publishToNPMRegistries(releaseInfo);
181
-
182
- // Paso 14: Actualizar sistema OTA
183
- await this.updateOTASystem(currentVersion);
184
-
185
- console.log('\n✅ Auto-release AI completado exitosamente!');
186
-
187
- } catch (error) {
188
- console.error('❌ Error en auto-release:', error);
189
- process.exit(1);
190
- }
191
- }
192
-
193
- private async pullRemoteChanges(): Promise<void> {
194
- console.log('🔄 Verificando cambios remotos...');
195
-
196
- try {
197
- await this.runCommand('git', ['fetch', 'origin']);
198
- // Detectar rama principal remota
199
- const currentBranchResult = await this.runCommand('git', ['branch', '--show-current']);
200
- const currentBranch = currentBranchResult.stdout.trim();
201
- const remoteBranch = `origin/${currentBranch}`;
202
- const result = await this.runCommand('git', ['log', `HEAD..${remoteBranch}`, '--oneline']);
203
-
204
- if (result.stdout.trim()) {
205
- console.log('📥 Cambios remotos detectados. Actualizando...');
206
-
207
- const statusResult = await this.runCommand('git', ['status', '--porcelain']);
208
- if (statusResult.stdout.trim()) {
209
- console.log('💾 Guardando cambios locales...');
210
- await this.runCommand('git', ['stash', 'push', '-m', 'auto-release-stash']);
211
- }
212
-
213
- await this.runCommand('git', ['pull', 'origin', currentBranch]);
214
- console.log('✅ Actualización completa');
215
- } else {
216
- console.log('✅ Repositorio actualizado');
217
- }
218
- } catch (error) {
219
- throw new Error(`Error al actualizar repositorio: ${error}`);
220
- }
221
- }
222
-
223
- /**
224
- * Detecta cambios no commiteados y los maneja según la configuración
225
- */
226
- private async handleUncommittedChanges(): Promise<void> {
227
- console.log('🔍 Verificando cambios no commiteados...');
228
-
229
- try {
230
- const statusResult = await this.runCommand('git', ['status', '--porcelain']);
231
- const uncommittedChanges = statusResult.stdout.trim();
232
-
233
- if (!uncommittedChanges) {
234
- console.log('✅ Repositorio limpio, no hay cambios pendientes');
235
- return;
236
- }
237
-
238
- console.log('⚠️ Se detectaron cambios no commiteados:');
239
- console.log(uncommittedChanges.split('\n').map(line => ` ${line}`).join('\n'));
240
-
241
- if (this.dryRun) {
242
- console.log('🔍 [DRY RUN] Se commitearían los cambios automáticamente');
243
- return;
244
- }
245
-
246
- if (this.autoCommit || this.autoApprove) {
247
- console.log('🤖 Modo auto-commit activado, commiteando cambios...');
248
- await this.autoCommitChanges();
249
- } else {
250
- // Prompt interactivo
251
- const shouldCommit = await this.promptUserForCommit(uncommittedChanges);
252
- if (shouldCommit) {
253
- await this.autoCommitChanges();
254
- } else {
255
- console.log('❌ Release cancelado. Commitea tus cambios manualmente y vuelve a intentar.');
256
- process.exit(1);
257
- }
258
- }
259
-
260
- } catch (error) {
261
- throw new Error(`Error verificando estado del repositorio: ${error}`);
262
- }
263
- }
264
-
265
- /**
266
- * Realiza commit automático con mensaje inteligente y [skip ci]
267
- */
268
- private async autoCommitChanges(): Promise<void> {
269
- console.log('📝 Generando commit automático...');
270
-
271
- try {
272
- // Añadir todos los archivos modificados
273
- await this.runCommand('git', ['add', '.']);
274
-
275
- // Generar mensaje de commit inteligente
276
- const commitMessage = await this.generateAutoCommitMessage();
277
-
278
- // Hacer commit con [skip ci] para evitar workflows recursivos
279
- const skipCiMessage = `${commitMessage}\n\n[skip ci] Auto-commit antes de release`;
280
- await this.runCommand('git', ['commit', '-m', skipCiMessage]);
281
-
282
- console.log('✅ Cambios commiteados automáticamente');
283
- console.log(`📋 Mensaje: ${commitMessage}`);
284
-
285
- } catch (error) {
286
- throw new Error(`Error en auto-commit: ${error}`);
287
- }
288
- }
289
-
290
- /**
291
- * Genera mensaje de commit inteligente basado en los archivos modificados
292
- */
293
- private async generateAutoCommitMessage(): Promise<string> {
294
- try {
295
- // Obtener archivos modificados
296
- const statusResult = await this.runCommand('git', ['status', '--porcelain']);
297
- const files = statusResult.stdout.trim().split('\n').filter(line => line.trim());
298
-
299
- const modifiedFiles = files.map(line => {
300
- const status = line.substring(0, 2).trim();
301
- const filePath = line.substring(3);
302
- return { status, filePath };
303
- });
304
-
305
- // Analizar tipos de cambios
306
- const hasPackageJson = modifiedFiles.some(f => f.filePath.includes('package.json'));
307
- const hasSourceFiles = modifiedFiles.some(f => f.filePath.match(/\.(ts|js|tsx|jsx)$/));
308
- const hasConfigFiles = modifiedFiles.some(f => f.filePath.match(/\.(json|yml|yaml|toml|md)$/));
309
- const hasDocFiles = modifiedFiles.some(f => f.filePath.includes('docs/') || f.filePath.includes('README'));
310
-
311
- let commitType = 'chore';
312
- let scope = '';
313
- let description = 'cambios automáticos pre-release';
314
-
315
- if (hasPackageJson && hasSourceFiles) {
316
- commitType = 'feat';
317
- scope = 'core';
318
- description = 'mejoras y actualizaciones automáticas';
319
- } else if (hasSourceFiles) {
320
- commitType = 'feat';
321
- scope = 'core';
322
- description = 'actualizaciones de funcionalidad';
323
- } else if (hasDocFiles) {
324
- commitType = 'docs';
325
- scope = 'readme';
326
- description = 'actualización de documentación';
327
- } else if (hasConfigFiles) {
328
- commitType = 'chore';
329
- scope = 'config';
330
- description = 'actualizaciones de configuración';
331
- }
332
-
333
- const scopePrefix = scope ? `(${scope})` : '';
334
- return `${commitType}${scopePrefix}: ${description}`;
335
-
336
- } catch (error) {
337
- console.warn('⚠️ Error generando mensaje inteligente, usando mensaje genérico');
338
- return 'chore: cambios automáticos pre-release';
339
- }
340
- }
341
-
342
- /**
343
- * Prompt interactivo para confirmar commit
344
- */
345
- private async promptUserForCommit(changes: string): Promise<boolean> {
346
- console.log('\n🤔 ¿Qué deseas hacer con estos cambios?');
347
- console.log('1. Commitear automáticamente y continuar');
348
- console.log('2. Cancelar release y commitear manualmente');
349
- console.log('\nEscribe "1" para auto-commit o "2" para cancelar:');
350
-
351
- return new Promise((resolve) => {
352
- const stdin = process.stdin;
353
- stdin.setRawMode(true);
354
- stdin.resume();
355
- stdin.setEncoding('utf8');
356
-
357
- stdin.on('data', (key) => {
358
- if (key === '1') {
359
- stdin.setRawMode(false);
360
- stdin.pause();
361
- console.log('✅ Continuando con auto-commit...');
362
- resolve(true);
363
- } else if (key === '2') {
364
- stdin.setRawMode(false);
365
- stdin.pause();
366
- console.log('❌ Cancelando release...');
367
- resolve(false);
368
- } else if (key === '\u0003') { // Ctrl+C
369
- stdin.setRawMode(false);
370
- stdin.pause();
371
- console.log('\n❌ Release cancelado por usuario');
372
- process.exit(0);
373
- } else {
374
- console.log('⚠️ Opción inválida. Escribe "1" o "2"');
375
- }
376
- });
377
- });
378
- }
379
-
380
- private async installNodeDependencies(): Promise<void> {
381
- console.log('📦 Verificando dependencias...');
382
-
383
- try {
384
- const result = await this.runCommand('npm', ['install']);
385
- if (result.stdout.includes('up to date')) {
386
- console.log('✅ Dependencias actualizadas');
387
- } else {
388
- console.log('✅ Dependencias instaladas/actualizadas');
389
- }
390
- } catch (error) {
391
- throw new Error(`Error instalando dependencias: ${error}`);
392
- }
393
- }
394
-
395
- /**
396
- * Genera nueva versión usando version-manager.ts con parámetros
397
- */
398
- private async generateNewVersion(): Promise<void> {
399
- console.log('🔢 Generando nueva versión...');
400
-
401
- if (this.dryRun) {
402
- console.log('🔍 [DRY RUN] Se generaría versión con:');
403
- console.log(` - Tipo: ${this.versionType}`);
404
- console.log(` - Prefijo: ${this.versionPrefix || 'stable'}`);
405
- return;
406
- }
407
-
408
- try {
409
- const versionArgs = [
410
- 'project-utils/version-manager.ts',
411
- '--auto-approve'
412
- ];
413
-
414
- if (this.versionType && this.versionType !== 'auto') {
415
- versionArgs.push('--type', this.versionType);
416
- }
417
-
418
- if (this.versionPrefix) {
419
- versionArgs.push('--prefix', this.versionPrefix);
420
- }
421
-
422
- console.log(`📋 Ejecutando: bun ${versionArgs.join(' ')}`);
423
- const result = await this.runCommand('bun', versionArgs);
424
-
425
- console.log('✅ Nueva versión generada exitosamente');
426
- } catch (error) {
427
- throw new Error(`Error generando versión: ${error}`);
428
- }
429
- }
430
-
431
- private getCurrentVersion(): string {
432
- try {
433
- const changelog: ChangelogData = JSON.parse(readFileSync(this.changelogPath, 'utf8'));
434
- return changelog.current_version;
435
- } catch (error) {
436
- throw new Error(`Error leyendo changelog: ${error}`);
437
- }
438
- }
439
-
440
- private getLatestRelease(): string | null {
441
- if (!existsSync(this.releaseDir)) {
442
- return null;
443
- }
444
-
445
- const prefixes = readdirSync(this.releaseDir);
446
- let latestVersion = null;
447
- let latestDate = new Date(0);
448
-
449
- for (const prefix of prefixes) {
450
- const prefixDir = join(this.releaseDir, prefix);
451
- if (!statSync(prefixDir).isDirectory()) continue;
452
-
453
- const versions = readdirSync(prefixDir);
454
- for (const version of versions) {
455
- const versionDir = join(prefixDir, version);
456
- if (!statSync(versionDir).isDirectory()) continue;
457
-
458
- const stat = statSync(versionDir);
459
- const modDate = stat.mtime;
460
-
461
- if (modDate > latestDate) {
462
- latestDate = modDate;
463
- latestVersion = `${prefix}-${version}`;
464
- }
465
- }
466
- }
467
-
468
- return latestVersion;
469
- }
470
-
471
- private parseVersion(version: string): ReleaseInfo {
472
- // Formatos soportados: 0.3.1, 0.4.0-alpha.1, alpha-0.4.0, etc.
473
- let match = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+)(?:\.(\d+))?)?$/);
474
- let major: string, minor: string, patch: string, prefix: string | undefined;
475
-
476
- if (match) {
477
- // Formato: X.Y.Z-prefix
478
- [, major, minor, patch, prefix] = match;
479
- } else {
480
- // Intentar formato: prefix-X.Y.Z
481
- match = version.match(/^(\w+)-(\d+)\.(\d+)\.(\d+)$/);
482
- if (match) {
483
- [, prefix, major, minor, patch] = match;
484
- } else {
485
- throw new Error(`Formato de versión inválido: ${version}. Formatos esperados: X.Y.Z, X.Y.Z-alpha, o alpha-X.Y.Z`);
486
- }
487
- }
488
-
489
- return {
490
- version: version,
491
- prefix: prefix || 'stable',
492
- major: parseInt(major),
493
- minor: parseInt(minor),
494
- patch: parseInt(patch)
495
- };
496
- }
497
-
498
- private async buildApplication(): Promise<void> {
499
- console.log('🔨 Compilando biblioteca...');
500
-
501
- if (this.dryRun) {
502
- console.log('🔍 [DRY RUN] Se ejecutaría: npm run build:all');
503
- return;
504
- }
505
-
506
- try {
507
- // Limpiar compilaciones previas
508
- await this.runCommand('npm', ['run', 'clean']);
509
-
510
- // Build completo de todos los módulos
511
- await this.runCommand('npm', ['run', 'build:all']);
512
-
513
- console.log('✅ Compilación exitosa (todos los módulos)');
514
-
515
- } catch (error) {
516
- throw new Error(`Error en compilación: ${error}`);
517
- }
518
- }
519
-
520
- private async createReleaseStructure(releaseInfo: ReleaseInfo): Promise<void> {
521
- const releaseDir = join(this.releaseDir, releaseInfo.prefix, `${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch}`);
522
-
523
- console.log(`📁 Creando estructura: ${releaseDir}`);
524
-
525
- if (!existsSync(releaseDir)) {
526
- mkdirSync(releaseDir, { recursive: true });
527
- }
528
- }
529
-
530
- private async copyDistFiles(releaseInfo: ReleaseInfo): Promise<void> {
531
- const releaseDir = join(this.releaseDir, releaseInfo.prefix, `${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch}`);
532
- const distDir = join(this.projectRoot, 'dist');
533
-
534
- console.log('📋 Copiando archivos de distribución...');
535
-
536
- if (this.dryRun) {
537
- console.log('🔍 [DRY RUN] Se copiarían archivos desde dist/ al release');
538
- return;
539
- }
540
-
541
- try {
542
- if (!existsSync(distDir)) {
543
- console.log('⚠️ Directorio dist/ no existe, omitiendo copia de archivos');
544
- return;
545
- }
546
-
547
- const files = readdirSync(distDir);
548
- const filesToCopy = files.filter(file => {
549
- const sourceFile = join(distDir, file);
550
- const stat = statSync(sourceFile);
551
- return stat.isFile(); // Solo copiar archivos, no directorios
552
- });
553
-
554
- if (filesToCopy.length === 0) {
555
- console.log('⚠️ No hay archivos para copiar en dist/');
556
- return;
557
- }
558
-
559
- for (const file of filesToCopy) {
560
- const sourceFile = join(distDir, file);
561
- const destFile = join(releaseDir, file);
562
- await this.runCommand('cp', [sourceFile, destFile]);
563
- }
564
-
565
- console.log(`✅ ${filesToCopy.length} archivos de distribución copiados`);
566
-
567
- } catch (error) {
568
- throw new Error(`Error copiando archivos de distribución: ${error}`);
569
- }
570
- }
571
-
572
- private async generateReleaseDocumentation(releaseInfo: ReleaseInfo): Promise<void> {
573
- console.log('📝 Generando documentación de release...');
574
-
575
- if (this.useAI) {
576
- await this.generateAIDocumentation(releaseInfo);
577
- } else {
578
- await this.generateBasicREADME(releaseInfo);
579
- }
580
- }
581
-
582
- private async generateAIDocumentation(releaseInfo: ReleaseInfo): Promise<void> {
583
- const releaseDir = join(this.releaseDir, releaseInfo.prefix, `${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch}`);
584
-
585
- console.log('🤖 Generando documentación con AI...');
586
-
587
- try {
588
- // Leer información del changelog
589
- const changelog: ChangelogData = JSON.parse(readFileSync(this.changelogPath, 'utf8'));
590
- const versionInfo = changelog.versions.find(v => v.version === releaseInfo.version);
591
-
592
- if (!versionInfo) {
593
- throw new Error(`No se encontró información para la versión ${releaseInfo.version}`);
594
- }
595
-
596
- // Obtener información de archivos generados
597
- const files = readdirSync(releaseDir);
598
- const fileInfo = this.getFileInfo(releaseDir, files);
599
-
600
- // Crear prompt para Gemini
601
- const prompt = this.createDocumentationPrompt(releaseInfo, versionInfo, fileInfo);
602
-
603
- // Guardar el prompt
604
- const promptPath = join(this.tempDir, 'release-doc-prompt.txt');
605
- writeFileSync(promptPath, prompt);
606
-
607
- try {
608
- console.log('🚀 Consultando Gemini AI...');
609
- const { spawn } = await import('child_process');
610
- const geminiProcess = spawn('gemini', [], {
611
- cwd: this.projectRoot,
612
- stdio: ['pipe', 'pipe', 'pipe']
613
- });
614
-
615
- geminiProcess.stdin?.write(prompt);
616
- geminiProcess.stdin?.end();
617
-
618
- let aiResponse = '';
619
- let errorOutput = '';
620
-
621
- geminiProcess.stdout?.on('data', (data) => {
622
- aiResponse += data.toString();
623
- });
624
-
625
- geminiProcess.stderr?.on('data', (data) => {
626
- errorOutput += data.toString();
627
- });
628
-
629
- const exitCode = await new Promise((resolve) => {
630
- geminiProcess.on('exit', resolve);
631
- });
632
-
633
- if (exitCode !== 0) {
634
- throw new Error(`Gemini CLI error: ${errorOutput || 'Gemini CLI failed'}`);
635
- }
636
-
637
- // Guardar respuesta AI
638
- const responsePath = join(this.tempDir, 'release-doc-response.md');
639
- writeFileSync(responsePath, aiResponse);
640
-
641
- // Procesar y usar la respuesta de AI
642
- const processedREADME = this.processAIResponse(aiResponse, releaseInfo, versionInfo, fileInfo);
643
-
644
- const readmePath = join(releaseDir, 'README.md');
645
- writeFileSync(readmePath, processedREADME, 'utf8');
646
-
647
- // Generar documentación adicional si AI lo sugiere
648
- await this.generateAdditionalDocs(aiResponse, releaseDir, releaseInfo);
649
-
650
- console.log('✅ Documentación AI generada exitosamente');
651
-
652
- } catch (aiError) {
653
- console.warn('⚠️ Error con AI, usando generación básica:', aiError);
654
- console.log('📝 Prompt guardado en:', promptPath);
655
- await this.generateBasicREADME(releaseInfo);
656
- }
657
-
658
- } catch (error) {
659
- throw new Error(`Error generando documentación AI: ${error}`);
660
- }
661
- }
662
-
663
- private createDocumentationPrompt(releaseInfo: ReleaseInfo, versionInfo: any, fileInfo: any): string {
664
- const config: GeminiPromptConfig = {
665
- projectContext: {
666
- name: BETTER_LOGGER_PROJECT_CONFIG.name,
667
- description: BETTER_LOGGER_PROJECT_CONFIG.description,
668
- version: releaseInfo.version,
669
- techStack: [...BETTER_LOGGER_PROJECT_CONFIG.techStack],
670
- targetPlatform: BETTER_LOGGER_PROJECT_CONFIG.targetPlatform,
671
- },
672
- analysisType: 'release',
673
- specificContext: `Release ${releaseInfo.version} (${releaseInfo.prefix})`,
674
- data: {
675
- releaseInfo,
676
- versionInfo,
677
- fileInfo,
678
- date: new Date().toISOString().split('T')[0]
679
- }
680
- };
681
-
682
- return createReleasePrompt(config);
683
-
684
- }
685
-
686
- private getFileInfo(releaseDir: string, files: string[]): Record<string, string> {
687
- const fileInfo: Record<string, string> = {};
688
-
689
- for (const file of files) {
690
- if (file !== 'README.md') { // No incluir README que estamos generando
691
- const filePath = join(releaseDir, file);
692
- const stats = statSync(filePath);
693
- const sizeMB = (stats.size / (1024 * 1024)).toFixed(1);
694
- fileInfo[file] = `${sizeMB}MB`;
695
- }
696
- }
697
-
698
- return fileInfo;
699
- }
700
-
701
- private processAIResponse(aiResponse: string, releaseInfo: ReleaseInfo, versionInfo: any, fileInfo: any): string {
702
- // Usar directamente la respuesta de AI como README
703
- // En el futuro se puede añadir más procesamiento si es necesario
704
- return aiResponse;
705
- }
706
-
707
- private async generateAdditionalDocs(aiResponse: string, releaseDir: string, releaseInfo: ReleaseInfo): Promise<void> {
708
- // Placeholder para generar documentación adicional basada en respuesta AI
709
- // Por ahora no genera documentación adicional
710
- return Promise.resolve();
711
- }
712
-
713
- private async generateBasicREADME(releaseInfo: ReleaseInfo): Promise<void> {
714
- // Fallback a generación básica si AI no está disponible
715
- const releaseDir = join(this.releaseDir, releaseInfo.prefix, `${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch}`);
716
- const changelog: ChangelogData = JSON.parse(readFileSync(this.changelogPath, 'utf8'));
717
- const versionInfo = changelog.versions.find(v => v.version === releaseInfo.version);
718
-
719
- const date = new Date().toISOString().split('T')[0];
720
- const files = readdirSync(releaseDir);
721
- const fileInfo = this.getFileInfo(releaseDir, files);
722
-
723
- const readme = `# EL Haido TPV - ${releaseInfo.prefix.charAt(0).toUpperCase() + releaseInfo.prefix.slice(1)} ${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch} - ARM64 Release
724
-
725
- ## Información de la Release
726
-
727
- - **Versión**: ${releaseInfo.version}
728
- - **Fecha**: ${date}
729
- - **Arquitectura**: ARM64 (aarch64)
730
- - **Plataforma objetivo**: Raspberry Pi 3B+
731
- - **Tipo de release**: ${versionInfo?.type} (${versionInfo?.title.toLowerCase()})
732
-
733
- ## Archivos incluidos
734
-
735
- ${Object.entries(fileInfo).map(([file, size]) => `- \`${file}\` - ${size}`).join('\n')}
736
-
737
- ## Instalación Rápida
738
-
739
- \`\`\`bash
740
- sudo dpkg -i "EL Haido TPV_${releaseInfo.major}.${releaseInfo.minor}.${releaseInfo.patch}_arm64.deb"
741
- sudo apt-get install -f
742
- \`\`\`
743
-
744
- ---
745
-
746
- *Release generada automáticamente el ${date}*
747
- `;
748
-
749
- const readmePath = join(releaseDir, 'README.md');
750
- writeFileSync(readmePath, readme, 'utf8');
751
- console.log('✅ README básico generado');
752
- }
753
-
754
- private async commitAndPushReleaseAI(releaseInfo: ReleaseInfo): Promise<void> {
755
- console.log('📤 Realizando commit y push con AI...');
756
-
757
- if (this.dryRun) {
758
- console.log('🔍 [DRY RUN] Se haría commit con AI y push de cambios');
759
- return;
760
- }
761
-
762
- try {
763
- // Configurar git si es necesario
764
- try {
765
- await this.runCommand('git', ['config', 'user.name']);
766
- } catch {
767
- await this.runCommand('git', ['config', 'user.email', 'auto-release@build.local']);
768
- await this.runCommand('git', ['config', 'user.name', 'Auto-Release AI System']);
769
- }
770
-
771
- // Solo añadir archivos que no estén en gitignore
772
- // Añadir cambios en CHANGELOG.json y package.json (actualizados por version-manager)
773
- const filesToAdd = [
774
- 'CHANGELOG.json',
775
- 'package.json'
776
- ];
777
-
778
- // Añadir archivos específicos de packages
779
- const packageFiles = [
780
- 'packages/core/package.json',
781
- 'packages/styling/package.json',
782
- 'packages/exports/package.json'
783
- ];
784
-
785
- for (const filePattern of [...filesToAdd, ...packageFiles]) {
786
- try {
787
- if (existsSync(join(this.projectRoot, filePattern))) {
788
- await this.runCommand('git', ['add', filePattern]);
789
- }
790
- } catch (error) {
791
- // Ignorar errores si el archivo no existe
792
- }
793
- }
794
-
795
- // Verificar si hay algo que commitear
796
- const statusResult = await this.runCommand('git', ['status', '--porcelain']);
797
- if (!statusResult.stdout.trim()) {
798
- console.log('⚠️ No hay cambios para commitear.');
799
- return;
800
- }
801
-
802
- if (this.useAI) {
803
- // Usar commit-generator con contexto AI mejorado
804
- console.log('🤖 Generando commit automático con AI avanzado...');
805
-
806
- const commitArgs = [
807
- 'project-utils/commit-generator.ts',
808
- '--auto-approve'
809
- ];
810
-
811
- if (this.workType) commitArgs.push('--work-type', this.workType);
812
- if (this.affectedComponents) commitArgs.push('--affected-components', this.affectedComponents);
813
- if (this.context) commitArgs.push('--context', this.context);
814
- if (this.performanceImpact) commitArgs.push('--performance-impact', this.performanceImpact);
815
-
816
- // Contexto adicional para releases
817
- const extraContext = this.createCommitContext(releaseInfo);
818
- if (extraContext) commitArgs.push('--extra', extraContext);
819
-
820
- try {
821
- console.log(`📋 Ejecutando: bun ${commitArgs.join(' ')}`);
822
- await this.runCommand('bun', commitArgs);
823
-
824
- console.log('✅ Commit AI generado exitosamente');
825
- } catch (error) {
826
- console.warn('⚠️ Error con commit AI, usando manual...');
827
- const commitMessage = this.generateCommitMessage(releaseInfo);
828
- await this.runCommand('git', ['commit', '-m', commitMessage]);
829
- }
830
- } else {
831
- // Commit manual
832
- const commitMessage = this.generateCommitMessage(releaseInfo);
833
- await this.runCommand('git', ['commit', '-m', commitMessage]);
834
- }
835
-
836
- // Push (detectar rama actual)
837
- const currentBranchResult = await this.runCommand('git', ['branch', '--show-current']);
838
- const currentBranch = currentBranchResult.stdout.trim();
839
- await this.runCommand('git', ['push', 'origin', currentBranch]);
840
- console.log('✅ Push completado');
841
-
842
- } catch (error) {
843
- throw new Error(`Error en commit/push: ${error}`);
844
- }
845
- }
846
-
847
- private createCommitContext(releaseInfo: ReleaseInfo): string {
848
- const changelog: ChangelogData = JSON.parse(readFileSync(this.changelogPath, 'utf8'));
849
- const versionInfo = changelog.versions.find(v => v.version === releaseInfo.version);
850
-
851
- return `AUTO-RELEASE CONTEXT - Version ${releaseInfo.version}
852
-
853
- Esto es un auto-release generado automáticamente para la versión ${releaseInfo.version}.
854
- Se han compilado y añadido binarios ARM64 optimizados para Raspberry Pi 3B+.
855
-
856
- ARCHIVOS INCLUIDOS:
857
- - Binario ejecutable nativo ARM64
858
- - Paquete Debian (.deb) para fácil instalación
859
- - Paquete RPM (.rpm) para distribuciones basadas en RPM
860
- - README detallado ${this.useAI ? 'generado con AI' : 'básico'}
861
- ${this.useAI ? '- Documentación adicional generada por AI' : ''}
862
-
863
- CARACTERÍSTICAS DE ESTA VERSIÓN:
864
- ${versionInfo?.changes.slice(0, 5).map(c => `- ${c.type}: ${c.title}`).join('\n') || '- Versión de mantenimiento'}
865
-
866
- NOTAS TÉCNICAS:
867
- - Compilado nativamente en ARM64 con optimizaciones específicas
868
- - OpenSSL configurado para cross-compilation
869
- - Todos los tests pasaron exitosamente
870
- ${this.useAI ? '- Documentación mejorada con inteligencia artificial' : ''}
871
-
872
- Por favor genera un commit tipo 'release(${releaseInfo.version})' que refleje adecuadamente:
873
- 1. Que es un auto-release automatizado
874
- 2. Las características principales de esta versión
875
- 3. Que incluye binarios optimizados para RPi
876
- 4. ${this.useAI ? 'Que usa AI para documentación mejorada' : 'Documentación estándar incluida'}
877
-
878
- Mantén el mensaje profesional pero informativo.`;
879
- }
880
-
881
- private generateCommitMessage(releaseInfo: ReleaseInfo): string {
882
- const changelog: ChangelogData = JSON.parse(readFileSync(this.changelogPath, 'utf8'));
883
- const versionInfo = changelog.versions.find(v => v.version === releaseInfo.version);
884
-
885
- const features = versionInfo?.changes
886
- .filter(c => c.type === 'feature')
887
- .slice(0, 3)
888
- .map(c => `✨ ${c.title}`)
889
- .join('\n') || '';
890
-
891
- const improvements = versionInfo?.changes
892
- .filter(c => c.type === 'improvement')
893
- .slice(0, 2)
894
- .map(c => `⚙️ ${c.title}`)
895
- .join('\n') || '';
896
-
897
- return `release(${releaseInfo.version}): auto-release ARM64 ${this.useAI ? 'con AI' : 'binarios'}
898
-
899
- - Binario ejecutable principal
900
- - Paquete Debian (.deb)
901
- - Paquete RPM (.rpm)
902
- - README ${this.useAI ? 'generado con AI' : 'automático'}
903
- ${this.useAI ? '- Documentación adicional AI' : ''}
904
-
905
- ${features ? 'Nuevas características:\n' + features : ''}
906
- ${improvements ? '\nMejoras:\n' + improvements : ''}
907
-
908
- ${this.useAI ? 'Generado por Auto-Release Manager AI con Gemini.' : 'Generado por Auto-Release Manager.'}
909
- Compilado nativamente en ARM64 para RPi3+ con optimizaciones.`;
910
- }
911
-
912
- /**
913
- * Crea GitHub Release usando el GitHub Release Manager
914
- */
915
- private async createGitHubRelease(releaseInfo: ReleaseInfo): Promise<void> {
916
- if (this.noGitHub) {
917
- console.log('⏭️ GitHub Release deshabilitado por --no-github');
918
- return;
919
- }
920
-
921
- console.log(`🚀 Creando GitHub Release ${this.useAI ? 'con documentación AI' : 'con documentación básica'}...`);
922
-
923
- if (this.dryRun) {
924
- console.log('🔍 [DRY RUN] Se crearía GitHub Release con github-release-manager.ts');
925
- return;
926
- }
927
-
928
- try {
929
- // Verificar que GitHub CLI esté disponible
930
- await this.runCommand('gh', ['--version']);
931
-
932
- // Ejecutar GitHub Release Manager con configuraciones apropiadas
933
- const ghArgs = ['project-utils/github-release-manager.ts'];
934
- if (process.argv.includes('--force')) ghArgs.push('--force');
935
- if (this.autoApprove) ghArgs.push('--auto-approve');
936
-
937
- await this.runCommand('bun', ghArgs);
938
-
939
- console.log(`✅ GitHub Release creado exitosamente ${this.useAI ? '(con mejoras AI)' : ''}`);
940
-
941
- } catch (error) {
942
- console.warn('⚠️ No se pudo crear GitHub Release:', error);
943
- console.log('💡 Verifica que gh CLI esté instalado y autenticado');
944
- console.log('💡 O usa --no-github para deshabilitar GitHub releases');
945
- }
946
- }
947
-
948
- /**
949
- * Publica el paquete en registros NPM (público y GitHub)
950
- */
951
- private async publishToNPMRegistries(releaseInfo: ReleaseInfo): Promise<void> {
952
- if (!this.publishNpm && !this.publishGithub) {
953
- console.log('⏭️ Publicación NPM deshabilitada (usa --publish-npm o --publish-github)');
954
- return;
955
- }
956
-
957
- console.log('📦 Iniciando publicación NPM...');
958
-
959
- if (this.dryRun) {
960
- console.log('🔍 [DRY RUN] Se publicaría en:');
961
- if (this.publishNpm) console.log(' - NPM Registry (público)');
962
- if (this.publishGithub) console.log(' - GitHub Packages');
963
- return;
964
- }
965
-
966
- try {
967
- // Verificar que el build esté completo
968
- const distPath = join(this.projectRoot, 'dist');
969
- if (!existsSync(distPath)) {
970
- throw new Error('Directorio dist/ no encontrado. Ejecuta npm run build primero.');
971
- }
972
-
973
- // Publicar en NPM público
974
- if (this.publishNpm) {
975
- console.log('🌐 Publicando en NPM Registry (público)...');
976
- try {
977
- // Determinar tag basado en el prefijo de la versión
978
- const npmTag = this.determineNPMTag(releaseInfo.version);
979
- const npmArgs = ['publish', '--access', 'public', '--ignore-scripts'];
980
- if (npmTag !== 'latest') {
981
- npmArgs.push('--tag', npmTag);
982
- }
983
-
984
- await this.runCommand('npm', npmArgs);
985
- console.log(`✅ Publicado exitosamente en NPM público con tag: ${npmTag}`);
986
- } catch (error) {
987
- console.error('❌ Error publicando en NPM público:', error);
988
- throw error;
989
- }
990
- }
991
-
992
- // Publicar en GitHub Packages
993
- if (this.publishGithub) {
994
- console.log('🐈 Publicando en GitHub Packages...');
995
- try {
996
- // Determinar tag basado en el prefijo de la versión
997
- const npmTag = this.determineNPMTag(releaseInfo.version);
998
- const githubArgs = [
999
- 'publish',
1000
- '--registry=https://npm.pkg.github.com',
1001
- '--access', 'public',
1002
- '--ignore-scripts'
1003
- ];
1004
- if (npmTag !== 'latest') {
1005
- githubArgs.push('--tag', npmTag);
1006
- }
1007
-
1008
- await this.runCommand('npm', githubArgs);
1009
- console.log(`✅ Publicado exitosamente en GitHub Packages con tag: ${npmTag}`);
1010
- } catch (error) {
1011
- console.error('❌ Error publicando en GitHub Packages:', error);
1012
- console.log('💡 Verifica que tengas permisos write:packages y estés autenticado');
1013
- throw error;
1014
- }
1015
- }
1016
-
1017
- console.log('✅ Publicación NPM completada exitosamente');
1018
-
1019
- // Mostrar comandos de instalación
1020
- console.log('\n📦 Comandos de instalación:');
1021
- if (this.publishNpm) {
1022
- console.log(` npm install @mks2508/better-logger@${releaseInfo.version}`);
1023
- }
1024
- if (this.publishGithub) {
1025
- console.log(` npm install @mks2508/better-logger@${releaseInfo.version} --registry=https://npm.pkg.github.com`);
1026
- }
1027
-
1028
- } catch (error) {
1029
- console.error('❌ Error en publicación NPM:', error);
1030
- console.log('💡 Verifica autenticación: npm whoami');
1031
- throw error;
1032
- }
1033
- }
1034
-
1035
- /**
1036
- * Determina el tag NPM apropiado basado en el formato de versión
1037
- */
1038
- private determineNPMTag(version: string): string {
1039
- const releaseInfo = this.parseVersion(version);
1040
-
1041
- // Si no hay prefijo, es una versión estable (latest)
1042
- if (!releaseInfo.prefix || releaseInfo.prefix === 'stable') {
1043
- return 'latest';
1044
- }
1045
-
1046
- // Mapear prefijos a tags NPM
1047
- switch (releaseInfo.prefix) {
1048
- case 'alpha':
1049
- case 'pre-alpha':
1050
- return 'alpha';
1051
- case 'beta':
1052
- return 'beta';
1053
- case 'rc':
1054
- return 'next'; // tag común para release candidates
1055
- default:
1056
- return releaseInfo.prefix; // usar el prefijo como tag
1057
- }
1058
- }
1059
-
1060
- /**
1061
- * Actualiza el sistema OTA después de un release exitoso
1062
- * Sincroniza la nueva versión con los canales OTA apropiados
1063
- */
1064
- private async updateOTASystem(version: string): Promise<void> {
1065
- console.log(`🔄 Actualizando sistema OTA para versión ${version}...`);
1066
-
1067
- try {
1068
- // El version-manager.ts ya sincroniza automáticamente con OTA,
1069
- // pero podemos hacer validaciones adicionales aquí
1070
-
1071
- // Verificar que package.json fue actualizado correctamente
1072
- const packagePath = join(this.projectRoot, 'package.json');
1073
- if (!existsSync(packagePath)) {
1074
- console.warn('⚠️ package.json no existe');
1075
- return;
1076
- }
1077
-
1078
- const packageData = JSON.parse(readFileSync(packagePath, 'utf-8'));
1079
-
1080
- if (packageData.version === version) {
1081
- console.log(`✅ package.json actualizado correctamente: ${version}`);
1082
- } else {
1083
- console.warn(`⚠️ Posible desincronización en package.json:`);
1084
- console.warn(` Esperado: ${version}`);
1085
- console.warn(` Actual: ${packageData.version || 'N/A'}`);
1086
- }
1087
-
1088
- } catch (error) {
1089
- console.warn(`⚠️ Error verificando package.json: ${error}`);
1090
- console.warn('El release continuará sin verificación');
1091
- }
1092
- }
1093
-
1094
- private async runCommand(command: string, args: string[] = [], options: any = {}): Promise<any> {
1095
- return new Promise((resolve, reject) => {
1096
- const proc = spawn(command, args, {
1097
- cwd: options.cwd || this.projectRoot,
1098
- env: options.env || process.env,
1099
- stdio: ['pipe', 'pipe', 'pipe']
1100
- });
1101
-
1102
- let stdout = '';
1103
- let stderr = '';
1104
-
1105
- proc.stdout?.on('data', (data) => {
1106
- stdout += data.toString();
1107
- });
1108
-
1109
- proc.stderr?.on('data', (data) => {
1110
- stderr += data.toString();
1111
- });
1112
-
1113
- proc.on('exit', (code) => {
1114
- if (code !== 0) {
1115
- reject(new Error(`Command failed: ${command} ${args.join(' ')}\n${stderr}`));
1116
- } else {
1117
- resolve({ stdout, stderr });
1118
- }
1119
- });
1120
-
1121
- proc.on('error', (error) => {
1122
- reject(error);
1123
- });
1124
- });
1125
- }
1126
- }
1127
-
1128
- // Ejecutar si se llama directamente
1129
- if (import.meta.main) {
1130
- const args = process.argv.slice(2);
1131
-
1132
- if (args.includes('--help') || args.includes('-h')) {
1133
- console.log(`
1134
- 🚀 Auto-Release Manager AI para Better Logger
1135
-
1136
- Automatiza el proceso completo: versión, build, commit, GitHub release y publicación NPM.
1137
-
1138
- Uso:
1139
- bun project-utils/auto-release-gemini.ts [opciones]
1140
-
1141
- Opciones Principales:
1142
- --ai Activar generación con AI (por defecto)
1143
- --no-ai Deshabilitar AI, usar generación básica
1144
- --force Forzar recompilación aunque la release ya exista
1145
- --dry-run Solo mostrar qué haría, sin ejecutar
1146
- --auto-approve No pedir confirmación (para CI/CD)
1147
- --auto-commit Auto-commitear cambios pendientes
1148
- (se activa automáticamente con --auto-approve)
1149
-
1150
- Version Manager:
1151
- --type <tipo> Tipo de versión: major|minor|patch (default: patch)
1152
- --prefix <prefijo> Prefijo: alpha|beta|rc|'' (default: stable)
1153
-
1154
- Commit Generator (AI):
1155
- --work-type <tipo> Tipo: feature|fix|refactor|docs|test
1156
- --affected-components <lista> Componentes afectados: "core,styling,exports"
1157
- --context <descripción> Contexto del trabajo realizado
1158
- --performance-impact <tipo> Impacto: none|minor|major
1159
-
1160
- Publicación NPM:
1161
- --publish-npm Publicar en NPM Registry (público)
1162
- --publish-github Publicar en GitHub Packages
1163
-
1164
- Otras opciones:
1165
- --no-github Deshabilitar creación de GitHub releases
1166
- --help, -h Mostrar esta ayuda
1167
-
1168
- Ejemplos:
1169
- # Release alpha básica
1170
- bun project-utils/auto-release-gemini.ts --type minor --prefix alpha
1171
-
1172
- # Release completa con AI y publicación dual
1173
- bun project-utils/auto-release-gemini.ts --ai --auto-approve \\
1174
- --type minor --prefix alpha \\
1175
- --work-type feature --affected-components "exports,handlers" \\
1176
- --context "enhanced export functionality" \\
1177
- --publish-npm --publish-github
1178
-
1179
- # Solo mostrar qué haría
1180
- bun project-utils/auto-release-gemini.ts --dry-run --type patch --publish-npm
1181
-
1182
- # Para CI/CD
1183
- bun project-utils/auto-release-gemini.ts --auto-approve --ai \\
1184
- --type patch --publish-npm --publish-github
1185
- `);
1186
- process.exit(0);
1187
- }
1188
-
1189
- const manager = new AutoReleaseManagerAI();
1190
- await manager.run();
1191
- }
1192
-
1193
- export { AutoReleaseManagerAI };