@saulwade/swl-ses 1.4.0 → 1.4.1

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.
@@ -0,0 +1,392 @@
1
+ // Adaptado de temp/ultraship-main/tools/migration-checker.mjs bajo MIT License
2
+ // Fuente: Houseofmvps/ultraship (https://github.com/Houseofmvps/ultraship)
3
+ 'use strict';
4
+
5
+ const { readFileSync, existsSync, readdirSync, statSync } = require('fs');
6
+ const { join, relative, resolve } = require('path');
7
+ const { outputJSON, outputError } = require('./lib/output');
8
+
9
+ /**
10
+ * Detecta el ORM de un directorio revisando package.json o archivos Python.
11
+ * @param {string} dir
12
+ * @returns {string|null}
13
+ */
14
+ function detectOrm(dir) {
15
+ // Verificar primero ORM de Python (Alembic)
16
+ const alembicDetected = (
17
+ existsSync(join(dir, 'alembic.ini')) ||
18
+ (existsSync(join(dir, 'alembic')) && existsSync(join(dir, 'alembic', 'versions')))
19
+ );
20
+ if (alembicDetected) return 'alembic';
21
+
22
+ // Verificar requirements.txt / pyproject.toml para alembic
23
+ const reqPath = join(dir, 'requirements.txt');
24
+ if (existsSync(reqPath)) {
25
+ const content = readFileSync(reqPath, 'utf8').toLowerCase();
26
+ if (content.includes('alembic')) return 'alembic';
27
+ }
28
+ const pyprojectPath = join(dir, 'pyproject.toml');
29
+ if (existsSync(pyprojectPath)) {
30
+ const content = readFileSync(pyprojectPath, 'utf8').toLowerCase();
31
+ if (content.includes('alembic')) return 'alembic';
32
+ }
33
+
34
+ // ORM de Node.js desde package.json
35
+ const pkgPath = join(dir, 'package.json');
36
+ if (!existsSync(pkgPath)) return null;
37
+
38
+ let pkg;
39
+ try {
40
+ pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
41
+ } catch {
42
+ return null;
43
+ }
44
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
45
+
46
+ if (allDeps['drizzle-orm'] || allDeps['drizzle-kit']) return 'drizzle';
47
+ if (allDeps['prisma'] || allDeps['@prisma/client']) return 'prisma';
48
+ if (allDeps['knex']) return 'knex';
49
+ if (allDeps['typeorm']) return 'typeorm';
50
+ if (allDeps['sequelize']) return 'sequelize';
51
+ if (allDeps['mongoose']) return 'mongoose';
52
+ return null;
53
+ }
54
+
55
+ /**
56
+ * Revisa migraciones de Drizzle ORM.
57
+ * @param {string} dir
58
+ * @returns {object}
59
+ */
60
+ function checkDrizzle(dir) {
61
+ const findings = [];
62
+ const info = { orm: 'drizzle', migration_dir: null, schema_files: [], migrations: [] };
63
+
64
+ // Buscar config de Drizzle
65
+ const configNames = ['drizzle.config.ts', 'drizzle.config.js', 'drizzle.config.mjs'];
66
+ let configPath = null;
67
+ for (const name of configNames) {
68
+ const p = join(dir, name);
69
+ if (existsSync(p)) { configPath = p; break; }
70
+ }
71
+
72
+ if (!configPath) {
73
+ findings.push({ severity: 'high', message: 'No se encontró drizzle.config — las migraciones podrían no estar configuradas' });
74
+ } else {
75
+ const config = readFileSync(configPath, 'utf8');
76
+ const outMatch = config.match(/out\s*:\s*['"]([^'"]+)['"]/);
77
+ if (outMatch) info.migration_dir = outMatch[1];
78
+ }
79
+
80
+ // Buscar directorio de migraciones
81
+ const migrationDirs = [info.migration_dir, 'drizzle', 'migrations', 'db/migrations'].filter(Boolean);
82
+ let migDir = null;
83
+ for (const d of migrationDirs) {
84
+ const p = join(dir, d);
85
+ try {
86
+ if (existsSync(p) && statSync(p).isDirectory()) { migDir = p; info.migration_dir = d; break; }
87
+ } catch { /* skip */ }
88
+ }
89
+
90
+ if (migDir) {
91
+ const files = readdirSync(migDir).filter(f => f.endsWith('.sql') || f.endsWith('.ts') || f.endsWith('.js'));
92
+ info.migrations = files.map(f => {
93
+ try {
94
+ const s = statSync(join(migDir, f));
95
+ return { name: f, modified: s.mtime.toISOString().split('T')[0] };
96
+ } catch { return { name: f }; }
97
+ });
98
+ info.migration_count = files.length;
99
+
100
+ // Verificar journal (Drizzle registra migraciones aplicadas)
101
+ const journalPath = join(migDir, 'meta', '_journal.json');
102
+ if (existsSync(journalPath)) {
103
+ try {
104
+ const journal = JSON.parse(readFileSync(journalPath, 'utf8'));
105
+ info.applied_count = journal.entries ? journal.entries.length : 0;
106
+ if (info.migration_count > info.applied_count) {
107
+ findings.push({
108
+ severity: 'critical',
109
+ message: `${info.migration_count - info.applied_count} migración(es) pendiente(s) sin aplicar — ejecutar: npx drizzle-kit push`,
110
+ });
111
+ }
112
+ } catch { /* ignorar */ }
113
+ }
114
+ } else {
115
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx drizzle-kit generate' });
116
+ }
117
+
118
+ // Buscar archivos de schema
119
+ const schemaPatterns = ['schema.ts', 'schema.js', 'db/schema.ts', 'src/db/schema.ts', 'src/schema.ts'];
120
+ for (const pattern of schemaPatterns) {
121
+ if (existsSync(join(dir, pattern))) info.schema_files.push(pattern);
122
+ }
123
+ const schemaDirs = ['src/db', 'db', 'src/schema'];
124
+ for (const d of schemaDirs) {
125
+ const p = join(dir, d);
126
+ try {
127
+ if (existsSync(p) && statSync(p).isDirectory()) {
128
+ const files = readdirSync(p).filter(f => f.includes('schema') && (f.endsWith('.ts') || f.endsWith('.js')));
129
+ for (const f of files) info.schema_files.push(join(d, f));
130
+ }
131
+ } catch { /* skip */ }
132
+ }
133
+
134
+ if (info.schema_files.length === 0) {
135
+ findings.push({ severity: 'high', message: 'No se encontraron archivos de schema — Drizzle ORM requiere definiciones de schema' });
136
+ }
137
+
138
+ return { ...info, findings };
139
+ }
140
+
141
+ /**
142
+ * Revisa migraciones de Prisma.
143
+ * @param {string} dir
144
+ * @returns {object}
145
+ */
146
+ function checkPrisma(dir) {
147
+ const findings = [];
148
+ const info = { orm: 'prisma', schema_file: null, migrations: [] };
149
+
150
+ const schemaPaths = ['prisma/schema.prisma', 'schema.prisma'];
151
+ for (const p of schemaPaths) {
152
+ if (existsSync(join(dir, p))) { info.schema_file = p; break; }
153
+ }
154
+
155
+ if (!info.schema_file) {
156
+ findings.push({ severity: 'critical', message: 'No se encontró prisma/schema.prisma' });
157
+ return { ...info, findings };
158
+ }
159
+
160
+ const migDir = join(dir, 'prisma/migrations');
161
+ try {
162
+ if (existsSync(migDir) && statSync(migDir).isDirectory()) {
163
+ const dirs = readdirSync(migDir).filter(f => {
164
+ try {
165
+ const p = join(migDir, f);
166
+ return statSync(p).isDirectory() && f !== '_lock';
167
+ } catch { return false; }
168
+ });
169
+ info.migrations = dirs.map(d => ({ name: d }));
170
+ info.migration_count = dirs.length;
171
+ } else {
172
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones de Prisma — ejecutar: npx prisma migrate dev' });
173
+ }
174
+ } catch { /* skip */ }
175
+
176
+ const nodeModulesPrisma = join(dir, 'node_modules/.prisma/client');
177
+ if (!existsSync(nodeModulesPrisma)) {
178
+ findings.push({ severity: 'high', message: 'Cliente de Prisma no generado — ejecutar: npx prisma generate' });
179
+ }
180
+
181
+ return { ...info, findings };
182
+ }
183
+
184
+ /**
185
+ * Revisa migraciones de Knex.
186
+ * @param {string} dir
187
+ * @returns {object}
188
+ */
189
+ function checkKnex(dir) {
190
+ const findings = [];
191
+ const info = { orm: 'knex', migration_dir: null, migrations: [] };
192
+
193
+ const knexfileNames = ['knexfile.js', 'knexfile.ts', 'knexfile.mjs'];
194
+ let found = false;
195
+ for (const name of knexfileNames) {
196
+ if (existsSync(join(dir, name))) { found = true; break; }
197
+ }
198
+
199
+ if (!found) {
200
+ findings.push({ severity: 'medium', message: 'No se encontró knexfile — la configuración de migraciones podría estar inline' });
201
+ }
202
+
203
+ const migDirs = ['migrations', 'db/migrations', 'src/migrations'];
204
+ for (const d of migDirs) {
205
+ const p = join(dir, d);
206
+ try {
207
+ if (existsSync(p) && statSync(p).isDirectory()) {
208
+ info.migration_dir = d;
209
+ const files = readdirSync(p).filter(f => f.endsWith('.js') || f.endsWith('.ts'));
210
+ info.migrations = files.map(f => ({ name: f }));
211
+ info.migration_count = files.length;
212
+ break;
213
+ }
214
+ } catch { /* skip */ }
215
+ }
216
+
217
+ if (!info.migration_dir) {
218
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx knex migrate:make initial' });
219
+ }
220
+
221
+ return { ...info, findings };
222
+ }
223
+
224
+ /**
225
+ * Revisa migraciones de Alembic (Python/SQLAlchemy).
226
+ * Detecta mediante alembic.ini, directorio alembic/versions/, requirements.txt o pyproject.toml.
227
+ * Compara revisiones encontradas en archivos contra .alembic_applied.txt (opcional).
228
+ * @param {string} dir
229
+ * @returns {object}
230
+ */
231
+ function checkAlembic(dir) {
232
+ const findings = [];
233
+ const info = {
234
+ orm: 'alembic',
235
+ versions_dir: null,
236
+ revisions_found: [],
237
+ revisions_applied: null,
238
+ pending: [],
239
+ extra_applied: [],
240
+ };
241
+
242
+ // Localizar directorio de versiones
243
+ const versionsDir = join(dir, 'alembic', 'versions');
244
+ if (existsSync(versionsDir)) {
245
+ info.versions_dir = 'alembic/versions';
246
+ }
247
+
248
+ if (!info.versions_dir) {
249
+ findings.push({
250
+ severity: 'medium',
251
+ message: 'No se encontró directorio alembic/versions/ — ejecutar: alembic init alembic',
252
+ });
253
+ return { ...info, findings };
254
+ }
255
+
256
+ // Parsear revision IDs de archivos de migración Python
257
+ let versionFiles = [];
258
+ try {
259
+ versionFiles = readdirSync(versionsDir).filter(f => f.endsWith('.py') && f !== '__init__.py');
260
+ } catch {
261
+ findings.push({ severity: 'high', message: `No se pudo leer el directorio ${info.versions_dir}` });
262
+ return { ...info, findings };
263
+ }
264
+
265
+ const revisionRegex = /revision\s*=\s*['"]([^'"]+)['"]/;
266
+ for (const file of versionFiles) {
267
+ try {
268
+ const content = readFileSync(join(versionsDir, file), 'utf8');
269
+ const match = content.match(revisionRegex);
270
+ if (match) {
271
+ info.revisions_found.push({ revision: match[1], file });
272
+ }
273
+ } catch { /* skip archivos no legibles */ }
274
+ }
275
+
276
+ if (info.revisions_found.length === 0 && versionFiles.length > 0) {
277
+ findings.push({
278
+ severity: 'medium',
279
+ message: `Se encontraron ${versionFiles.length} archivo(s) en alembic/versions/ pero ninguno tiene campo 'revision' — revisar formato`,
280
+ });
281
+ }
282
+
283
+ // Comparar contra .alembic_applied.txt (opcional)
284
+ const appliedPath = join(dir, '.alembic_applied.txt');
285
+ if (existsSync(appliedPath)) {
286
+ try {
287
+ const appliedContent = readFileSync(appliedPath, 'utf8');
288
+ const appliedRevisions = new Set(
289
+ appliedContent.split('\n').map(l => l.trim()).filter(Boolean)
290
+ );
291
+ info.revisions_applied = [...appliedRevisions];
292
+
293
+ const foundRevisions = new Set(info.revisions_found.map(r => r.revision));
294
+
295
+ // Pendientes: en archivos pero no aplicadas
296
+ info.pending = info.revisions_found
297
+ .filter(r => !appliedRevisions.has(r.revision))
298
+ .map(r => r.revision);
299
+
300
+ // Extra: aplicadas pero no en archivos (posible eliminación de migración)
301
+ info.extra_applied = [...appliedRevisions].filter(r => !foundRevisions.has(r));
302
+
303
+ if (info.pending.length > 0) {
304
+ findings.push({
305
+ severity: 'critical',
306
+ message: `${info.pending.length} migración(es) de Alembic pendiente(s) sin aplicar — ejecutar: alembic upgrade head`,
307
+ pending_revisions: info.pending,
308
+ });
309
+ }
310
+
311
+ if (info.extra_applied.length > 0) {
312
+ findings.push({
313
+ severity: 'high',
314
+ message: `${info.extra_applied.length} revisión(es) aplicada(s) no encontradas en archivos — posible eliminación de migración`,
315
+ extra_revisions: info.extra_applied,
316
+ });
317
+ }
318
+ } catch {
319
+ findings.push({ severity: 'low', message: 'No se pudo leer .alembic_applied.txt — sin comparación de estado aplicado' });
320
+ }
321
+ } else {
322
+ // Sin archivo de aplicadas — solo reportar conteo
323
+ if (info.revisions_found.length > 0) {
324
+ findings.push({
325
+ severity: 'info',
326
+ message: `${info.revisions_found.length} revisión(es) de Alembic encontradas. Crear .alembic_applied.txt con IDs aplicados para rastrear estado`,
327
+ });
328
+ }
329
+ }
330
+
331
+ info.revision_count = info.revisions_found.length;
332
+
333
+ return { ...info, findings };
334
+ }
335
+
336
+ function main() {
337
+ const args = process.argv.slice(2);
338
+ const rawDir = args.find(a => !a.startsWith('--'));
339
+ const dir = resolve(rawDir || process.cwd());
340
+
341
+ if (!existsSync(dir)) {
342
+ outputError(`Directorio no encontrado: ${dir}`);
343
+ process.exit(0);
344
+ }
345
+
346
+ const orm = detectOrm(dir);
347
+
348
+ if (!orm) {
349
+ outputJSON({
350
+ success: true,
351
+ packages_scanned: 1,
352
+ orm: null,
353
+ message: 'No se detectó un ORM compatible (Drizzle, Prisma, Knex, Alembic, TypeORM, Sequelize)',
354
+ findings: [],
355
+ });
356
+ process.exit(0);
357
+ }
358
+
359
+ let result;
360
+ switch (orm) {
361
+ case 'drizzle': result = checkDrizzle(dir); break;
362
+ case 'prisma': result = checkPrisma(dir); break;
363
+ case 'knex': result = checkKnex(dir); break;
364
+ case 'alembic': result = checkAlembic(dir); break;
365
+ default:
366
+ result = {
367
+ orm,
368
+ findings: [{
369
+ severity: 'info',
370
+ message: `${orm} detectado pero la verificación de migraciones aún no está implementada para este ORM`,
371
+ }],
372
+ };
373
+ }
374
+
375
+ const allFindings = result.findings || [];
376
+ const deploySafe = allFindings.filter(f => f.severity === 'critical').length === 0;
377
+
378
+ outputJSON({
379
+ success: true,
380
+ packages_scanned: 1,
381
+ deploy_safe: deploySafe,
382
+ orm,
383
+ result,
384
+ findings: allFindings,
385
+ });
386
+ }
387
+
388
+ if (require.main === module) {
389
+ main();
390
+ }
391
+
392
+ module.exports = { detectOrm, checkDrizzle, checkPrisma, checkKnex, checkAlembic };