@redcumbrecl/cli 0.1.0

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.
package/dist/cli.js ADDED
@@ -0,0 +1,1049 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command, Option } from "commander";
5
+
6
+ // src/comandos/conectar-mcp.ts
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ // src/nucleo/salida.ts
11
+ var ErrorCli = class extends Error {
12
+ constructor(mensaje, codigoSalida = 1) {
13
+ super(mensaje);
14
+ this.codigoSalida = codigoSalida;
15
+ this.name = "ErrorCli";
16
+ }
17
+ };
18
+ function crearSalida(json, flujos = { out: process.stdout, err: process.stderr }) {
19
+ const avisos = [];
20
+ const humano = json ? flujos.err : flujos.out;
21
+ return {
22
+ json,
23
+ avisos,
24
+ linea(texto = "") {
25
+ humano.write(`${texto}
26
+ `);
27
+ },
28
+ aviso(texto) {
29
+ avisos.push(texto);
30
+ humano.write(`\u26A0 ${texto}
31
+ `);
32
+ },
33
+ resultado(objeto) {
34
+ if (json) flujos.out.write(`${JSON.stringify({ ...objeto, avisos }, null, 2)}
35
+ `);
36
+ }
37
+ };
38
+ }
39
+
40
+ // src/comandos/conectar-mcp.ts
41
+ var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
42
+ var NOMBRE_SERVIDOR_MCP = "rcapi";
43
+ var ARCHIVOS_MCP = [".mcp.json", path.join(".cursor", "mcp.json")];
44
+ var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
45
+ function esObjeto(v) {
46
+ return typeof v === "object" && v !== null && !Array.isArray(v);
47
+ }
48
+ function mismaEntrada(v) {
49
+ return esObjeto(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
50
+ }
51
+ function planificar(proyecto, relativa) {
52
+ const absoluta = path.join(proyecto, relativa);
53
+ const ruta = relativa.split(path.sep).join("/");
54
+ if (!fs.existsSync(absoluta)) {
55
+ return { ruta, absoluta, accion: "creado", contenido: `${JSON.stringify({ mcpServers: { [NOMBRE_SERVIDOR_MCP]: ENTRADA } }, null, 2)}
56
+ ` };
57
+ }
58
+ let actual;
59
+ try {
60
+ actual = JSON.parse(fs.readFileSync(absoluta, "utf8"));
61
+ } catch (error) {
62
+ throw new ErrorCli(`${ruta} no tiene JSON v\xE1lido (${error.message}): no se modific\xF3. Corr\xEDgelo y vuelve a correr redcumbre conectar-mcp.`);
63
+ }
64
+ if (!esObjeto(actual) || actual.mcpServers !== void 0 && !esObjeto(actual.mcpServers)) {
65
+ throw new ErrorCli(`${ruta} no tiene la forma { "mcpServers": { \u2026 } }: no se modific\xF3.`);
66
+ }
67
+ const servidores2 = actual.mcpServers ?? {};
68
+ if (mismaEntrada(servidores2[NOMBRE_SERVIDOR_MCP])) return { ruta, absoluta, accion: "sin_cambios" };
69
+ const fusionado = { ...actual, mcpServers: { ...servidores2, [NOMBRE_SERVIDOR_MCP]: ENTRADA } };
70
+ return { ruta, absoluta, accion: "actualizado", contenido: `${JSON.stringify(fusionado, null, 2)}
71
+ ` };
72
+ }
73
+ function conectarMcp(proyecto) {
74
+ const planes = ARCHIVOS_MCP.map((relativa) => planificar(proyecto, relativa));
75
+ for (const p of planes) {
76
+ if (p.contenido === void 0) continue;
77
+ fs.mkdirSync(path.dirname(p.absoluta), { recursive: true });
78
+ fs.writeFileSync(p.absoluta, p.contenido);
79
+ }
80
+ return planes.map(({ ruta, accion }) => ({ ruta, accion }));
81
+ }
82
+ var TEXTO_ACCION = {
83
+ creado: "creado",
84
+ actualizado: "actualizado (se agreg\xF3 rcapi; los otros servidores quedaron igual)",
85
+ sin_cambios: "ya estaba configurado"
86
+ };
87
+ function informarMcp(salida, archivos) {
88
+ salida.linea(`Servidor MCP de rCAPI (${URL_MCP_REDCUMBRE}):`);
89
+ for (const a of archivos) salida.linea(` ${a.ruta}: ${TEXTO_ACCION[a.accion]}`);
90
+ if (archivos.some((a) => a.accion !== "sin_cambios")) {
91
+ salida.linea("Al abrir el proyecto en Claude Code o Cursor, el asistente te pedir\xE1 autorizar rCAPI con tu cuenta.");
92
+ }
93
+ }
94
+ async function ejecutarConectarMcp(opciones, deps) {
95
+ const proyecto = path.resolve(deps.cwd, opciones.carpeta ?? ".");
96
+ if (!fs.existsSync(proyecto) || !fs.statSync(proyecto).isDirectory()) throw new ErrorCli(`La carpeta ${proyecto} no existe.`);
97
+ const archivos = conectarMcp(proyecto);
98
+ informarMcp(deps.salida, archivos);
99
+ deps.salida.resultado({ ok: true, archivos });
100
+ }
101
+
102
+ // src/comandos/init.ts
103
+ import path4 from "node:path";
104
+
105
+ // ../../packages/config/src/cli/llaves.ts
106
+ var ENTORNOS_LLAVE = ["sandbox", "produccion"];
107
+ var ENTORNO_LLAVE_REGISTRY = {
108
+ sandbox: { label: "Sandbox", isSandbox: true },
109
+ produccion: { label: "Producci\xF3n", isSandbox: false }
110
+ };
111
+ function esEntornoLlave(valor) {
112
+ return typeof valor === "string" && ENTORNOS_LLAVE.includes(valor);
113
+ }
114
+
115
+ // src/nucleo/api.ts
116
+ var ErrorSesionRechazada = class extends Error {
117
+ constructor() {
118
+ super("La plataforma rechaz\xF3 tu sesi\xF3n.");
119
+ this.name = "ErrorSesionRechazada";
120
+ }
121
+ };
122
+ var ErrorVerificacionNoDisponible = class extends ErrorCli {
123
+ constructor() {
124
+ super("La plataforma no pudo verificar tu sesi\xF3n en este momento. No se cre\xF3 ninguna llave; vuelve a intentarlo en unos minutos.");
125
+ this.name = "ErrorVerificacionNoDisponible";
126
+ }
127
+ };
128
+ var ErrorSinRolAdministrador = class extends Error {
129
+ constructor() {
130
+ super("Crear llaves exige ser administrador de la empresa.");
131
+ this.name = "ErrorSinRolAdministrador";
132
+ }
133
+ };
134
+ var ErrorDeRed = class extends ErrorCli {
135
+ constructor(url, causa) {
136
+ const detalle = causa instanceof Error && causa.cause instanceof Error ? causa.cause.message : String(causa);
137
+ super(`No pude conectar con ${url} (${detalle}). Revisa tu conexi\xF3n y vuelve a correr el comando; no se cre\xF3 ninguna llave.`);
138
+ this.name = "ErrorDeRed";
139
+ }
140
+ };
141
+ var MENSAJE_SIN_FILA_LOCAL = "Tu cuenta todav\xEDa no entr\xF3 a app.redcumbre.cl. Entra una vez con tu cuenta y vuelve a correr el comando.";
142
+ var ClienteApi = class {
143
+ constructor(api, hacerFetch = fetch) {
144
+ this.api = api;
145
+ this.hacerFetch = hacerFetch;
146
+ }
147
+ async pedir(ruta, init) {
148
+ const url = `${this.api}${ruta}`;
149
+ try {
150
+ return await this.hacerFetch(url, init);
151
+ } catch (error) {
152
+ throw new ErrorDeRed(url, error);
153
+ }
154
+ }
155
+ /**
156
+ * Traduce las respuestas que valen para toda petición con la sesión del CLI y devuelve el cuerpo ya
157
+ * leído (un `Response` se lee una sola vez).
158
+ */
159
+ async leerConSesion(res) {
160
+ if (res.status === 401) throw new ErrorSesionRechazada();
161
+ const cuerpo = await leerJson(res);
162
+ if (res.status === 503 && cuerpo?.code === "REAUTH_CHECK_UNAVAILABLE") throw new ErrorVerificacionNoDisponible();
163
+ if (res.status === 403 && cuerpo?.code === "CLI_USER_NOT_FOUND") throw new ErrorCli(MENSAJE_SIN_FILA_LOCAL);
164
+ return cuerpo;
165
+ }
166
+ async empresas(token) {
167
+ const res = await this.pedir("/cli/empresas", { headers: { Authorization: `Bearer ${token}` } });
168
+ const cuerpo = await this.leerConSesion(res);
169
+ if (!res.ok) throw new ErrorCli(`No pude obtener tus empresas: ${describir(res, cuerpo)}.`);
170
+ return cuerpo.empresas;
171
+ }
172
+ async crearLlave(token, tenantSlug, nombre, entorno) {
173
+ const res = await this.pedir(`/${encodeURIComponent(tenantSlug)}/cli/llaves`, {
174
+ method: "POST",
175
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
176
+ body: JSON.stringify({ nombre, entorno })
177
+ });
178
+ const cuerpo = await this.leerConSesion(res);
179
+ if (res.status === 403) throw new ErrorSinRolAdministrador();
180
+ if (res.status !== 201) throw new ErrorCli(`No pude crear la llave en ${tenantSlug}: ${describir(res, cuerpo)}. No se cre\xF3 ninguna llave.`);
181
+ return cuerpo;
182
+ }
183
+ /** `whoami` con la llave del proyecto: 200 = válida, 401 = rechazada, sin red = error (`D-112`). */
184
+ async whoami(tokenLlave, tenantSlug) {
185
+ const res = await this.pedir(`/${encodeURIComponent(tenantSlug)}/whoami`, {
186
+ headers: { Authorization: `Bearer ${tokenLlave}` }
187
+ });
188
+ if (res.status === 401) return { estado: "rechazada" };
189
+ if (!res.ok) throw new ErrorCli(`No pude comprobar la llave: whoami respondi\xF3 ${res.status}. No se cre\xF3 ninguna llave.`);
190
+ const cuerpo = await res.json();
191
+ return { estado: "valida", tenant: cuerpo.data.tenant, sandbox: cuerpo.data.credencial.sandbox };
192
+ }
193
+ };
194
+ async function leerJson(res) {
195
+ const texto = await res.text();
196
+ try {
197
+ return JSON.parse(texto);
198
+ } catch {
199
+ return null;
200
+ }
201
+ }
202
+ function describir(res, cuerpo) {
203
+ const mensaje = Array.isArray(cuerpo?.message) ? cuerpo.message.join("; ") : cuerpo?.message;
204
+ return `el API respondi\xF3 ${res.status}${mensaje ? ` (${mensaje})` : ""}`;
205
+ }
206
+
207
+ // src/nucleo/config.ts
208
+ var PRODUCCION = {
209
+ api: "https://api.redcumbre.cl",
210
+ web: "https://app.redcumbre.cl"
211
+ };
212
+ var CLIENTE_OIDC = {
213
+ issuer: "https://id.redcumbre.cl",
214
+ clientId: "391851369151135746",
215
+ projectId: "346407127679500290"
216
+ };
217
+ var SCOPE = `openid profile email offline_access urn:zitadel:iam:org:project:id:${CLIENTE_OIDC.projectId}:aud`;
218
+ var URL_ENTORNOS = "https://docs.redcumbre.cl/primeros-pasos/entornos/";
219
+ var SERVICIO_LLAVERO = "redcumbrecl-cli";
220
+ function origen(variable, valor) {
221
+ let url;
222
+ try {
223
+ url = new URL(valor);
224
+ } catch {
225
+ throw new Error(`${variable} no es una URL v\xE1lida: \xAB${valor}\xBB`);
226
+ }
227
+ if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
228
+ throw new Error(`${variable} debe usar https (recib\xED \xAB${valor}\xBB)`);
229
+ }
230
+ return url.origin;
231
+ }
232
+ function servidores(env = process.env) {
233
+ return {
234
+ api: env.REDCUMBRE_API_URL ? origen("REDCUMBRE_API_URL", env.REDCUMBRE_API_URL) : PRODUCCION.api,
235
+ web: env.REDCUMBRE_WEB_URL ? origen("REDCUMBRE_WEB_URL", env.REDCUMBRE_WEB_URL) : PRODUCCION.web
236
+ };
237
+ }
238
+
239
+ // src/nucleo/instalacion.ts
240
+ import { spawnSync } from "node:child_process";
241
+ import fs2 from "node:fs";
242
+ import path2 from "node:path";
243
+ var LARGO_MAXIMO_NOMBRE = 191;
244
+ var SEPARADOR = " \xB7 ";
245
+ function fechaLocal(fecha) {
246
+ const dos = (n) => String(n).padStart(2, "0");
247
+ return `${fecha.getFullYear()}-${dos(fecha.getMonth() + 1)}-${dos(fecha.getDate())}`;
248
+ }
249
+ function nombreDeLlave(carpeta, entorno, fecha) {
250
+ const cola = `${SEPARADOR}${entorno}${SEPARADOR}${fechaLocal(fecha)}`;
251
+ const proyecto = Array.from(path2.basename(path2.resolve(carpeta)).trim());
252
+ const disponible = LARGO_MAXIMO_NOMBRE - cola.length;
253
+ return `${proyecto.slice(0, disponible).join("").trimEnd()}${cola}`;
254
+ }
255
+ var variableDeEntorno = (entorno) => `REDCUMBRE_LLAVE_${entorno.toUpperCase()}`;
256
+ var rutaRelativaLlave = (entorno) => `keys/redcumbre-${entorno}.json`;
257
+ var rutaLlave = (proyecto, entorno) => path2.join(proyecto, "keys", `redcumbre-${entorno}.json`);
258
+ function estaVersionado(proyecto, archivo) {
259
+ const r = spawnSync("git", ["ls-files", "--error-unmatch", "--", archivo], { cwd: proyecto, stdio: "ignore" });
260
+ return r.status === 0;
261
+ }
262
+ function asegurarExclusiones(proyecto, envVersionado) {
263
+ const ruta = path2.join(proyecto, ".gitignore");
264
+ const actual = fs2.existsSync(ruta) ? fs2.readFileSync(ruta, "utf8") : "";
265
+ const presentes = new Set(actual.split(/\r?\n/).map((l) => l.trim()));
266
+ const deseadas = ["keys/", ".redcumbre/", ...envVersionado ? [] : [".env"]];
267
+ const faltan = deseadas.filter((linea) => !presentes.has(linea) && !presentes.has(`/${linea}`));
268
+ if (faltan.length === 0) return [];
269
+ const prefijo = actual.length > 0 && !actual.endsWith("\n") ? "\n" : "";
270
+ fs2.writeFileSync(ruta, `${actual}${prefijo}# Llaves de rCAPI (npx @redcumbrecl/cli init)
271
+ ${faltan.join("\n")}
272
+ `);
273
+ return faltan;
274
+ }
275
+ function escribirLlave(proyecto, entorno, llave) {
276
+ const ruta = rutaLlave(proyecto, entorno);
277
+ fs2.mkdirSync(path2.dirname(ruta), { recursive: true });
278
+ fs2.writeFileSync(ruta, `${JSON.stringify(llave, null, 2)}
279
+ `, { mode: 384 });
280
+ fs2.chmodSync(ruta, 384);
281
+ }
282
+ function leerLlave(proyecto, entorno) {
283
+ const ruta = rutaLlave(proyecto, entorno);
284
+ if (!fs2.existsSync(ruta)) return null;
285
+ let datos;
286
+ try {
287
+ datos = JSON.parse(fs2.readFileSync(ruta, "utf8"));
288
+ } catch {
289
+ throw new Error(`${ruta} no es un JSON v\xE1lido. D\xE9jalo tal como lo descargaste de la web, o b\xF3rralo y vuelve a correr el comando.`);
290
+ }
291
+ if (typeof datos.token !== "string" || typeof datos.tenantSlug !== "string") {
292
+ throw new Error(`${ruta} no tiene el formato de una llave de rCAPI (faltan tenantSlug o token).`);
293
+ }
294
+ return datos;
295
+ }
296
+ function borrarLlave(proyecto, entorno) {
297
+ fs2.rmSync(rutaLlave(proyecto, entorno), { force: true });
298
+ }
299
+ function lineasEnv(proyecto) {
300
+ const ruta = path2.join(proyecto, ".env");
301
+ const texto = fs2.existsSync(ruta) ? fs2.readFileSync(ruta, "utf8") : "";
302
+ return { ruta, lineas: texto === "" ? [] : texto.replace(/\n$/, "").split("\n"), finalConSalto: texto.endsWith("\n") || texto === "" };
303
+ }
304
+ var esLineaDe = (variable) => (linea) => new RegExp(`^\\s*(export\\s+)?${variable}\\s*=`).test(linea);
305
+ function escribirPuntero(proyecto, entorno) {
306
+ const { ruta, lineas } = lineasEnv(proyecto);
307
+ const variable = variableDeEntorno(entorno);
308
+ const puntero = `${variable}=${rutaRelativaLlave(entorno)}`;
309
+ const indice = lineas.findIndex(esLineaDe(variable));
310
+ if (indice >= 0) {
311
+ if (lineas[indice] === puntero) return;
312
+ lineas[indice] = puntero;
313
+ } else {
314
+ lineas.push(puntero);
315
+ }
316
+ fs2.writeFileSync(ruta, `${lineas.join("\n")}
317
+ `);
318
+ }
319
+ function quitarPuntero(proyecto, entorno) {
320
+ const { ruta, lineas, finalConSalto } = lineasEnv(proyecto);
321
+ const quedan = lineas.filter((l) => !esLineaDe(variableDeEntorno(entorno))(l));
322
+ if (quedan.length === lineas.length) return;
323
+ fs2.writeFileSync(ruta, quedan.length ? `${quedan.join("\n")}${finalConSalto ? "\n" : ""}` : "");
324
+ }
325
+ var rutaEstado = (proyecto) => path2.join(proyecto, ".redcumbre", "estado.json");
326
+ function leerEstado(proyecto) {
327
+ const ruta = rutaEstado(proyecto);
328
+ if (!fs2.existsSync(ruta)) return null;
329
+ return JSON.parse(fs2.readFileSync(ruta, "utf8"));
330
+ }
331
+ function registrarEnEstado(proyecto, tenantSlug, entorno, sandbox) {
332
+ const anterior = leerEstado(proyecto) ?? {};
333
+ const ambientes = anterior.tenantSlug === tenantSlug ? { ...anterior.ambientes ?? {} } : {};
334
+ ambientes[entorno] = { keyEnvVar: variableDeEntorno(entorno), sandbox };
335
+ const estado = { ...anterior, tenantSlug, ambientes, actualizado: (/* @__PURE__ */ new Date()).toISOString() };
336
+ fs2.mkdirSync(path2.dirname(rutaEstado(proyecto)), { recursive: true });
337
+ fs2.writeFileSync(rutaEstado(proyecto), `${JSON.stringify(estado, null, 2)}
338
+ `);
339
+ }
340
+ function llavesDelProyecto(proyecto) {
341
+ const llaves = {};
342
+ for (const entorno of ENTORNOS_LLAVE) {
343
+ const llave = leerLlave(proyecto, entorno);
344
+ if (llave) llaves[entorno] = llave;
345
+ }
346
+ return llaves;
347
+ }
348
+ var llavesAjenas = (proyecto, empresa) => Object.entries(llavesDelProyecto(proyecto)).filter(([, llave]) => llave.tenantSlug !== empresa);
349
+ function empresaAnterior(proyecto, nuevaEmpresa) {
350
+ const ajenas = llavesAjenas(proyecto, nuevaEmpresa);
351
+ return ajenas.length ? { empresa: ajenas[0][1].tenantSlug, entornos: ajenas.map(([entorno]) => entorno) } : null;
352
+ }
353
+ function soltarEmpresaAnterior(proyecto, nuevaEmpresa) {
354
+ for (const [entorno] of llavesAjenas(proyecto, nuevaEmpresa)) {
355
+ borrarLlave(proyecto, entorno);
356
+ quitarPuntero(proyecto, entorno);
357
+ }
358
+ }
359
+
360
+ // src/nucleo/proyecto.ts
361
+ import { spawnSync as spawnSync2 } from "node:child_process";
362
+ import fs3 from "node:fs";
363
+ import path3 from "node:path";
364
+ import { fileURLToPath } from "node:url";
365
+ var LENGUAJES = ["typescript", "python", "dotnet", "php"];
366
+ var LENGUAJE_REGISTRY = {
367
+ typescript: {
368
+ label: "TypeScript con Node",
369
+ binario: "npm",
370
+ generador: ["npm", "create", "--yes"],
371
+ correrEjemplo: "npm run redcumbre:ejemplo",
372
+ ajustar(proyecto) {
373
+ const ruta = path3.join(proyecto, "package.json");
374
+ const paquete = JSON.parse(fs3.readFileSync(ruta, "utf8"));
375
+ paquete.scripts = { ...paquete.scripts, "redcumbre:ejemplo": "npx --yes tsx redcumbre/ejemplo.ts" };
376
+ fs3.writeFileSync(ruta, `${JSON.stringify(paquete, null, 2)}
377
+ `);
378
+ }
379
+ },
380
+ python: {
381
+ label: "Python",
382
+ binario: "uv",
383
+ // `--vcs none`: el CLI no inicia ni cambia repositorios de git (`D-16`).
384
+ generador: ["uv", "init", "--app", "--vcs", "none", "--no-workspace", "."],
385
+ correrEjemplo: "uv run redcumbre_ejemplo.py"
386
+ },
387
+ dotnet: {
388
+ label: ".NET (C#)",
389
+ binario: "dotnet",
390
+ generador: ["dotnet", "new", "console", "--output", "."],
391
+ correrEjemplo: "dotnet run"
392
+ },
393
+ php: {
394
+ label: "PHP",
395
+ binario: "composer",
396
+ generador: ["composer", "create-project", "--no-interaction", "slim/slim-skeleton", "."],
397
+ correrEjemplo: "php redcumbre/ejemplo.php"
398
+ }
399
+ };
400
+ function esLenguaje(valor) {
401
+ return typeof valor === "string" && LENGUAJES.includes(valor);
402
+ }
403
+ function carpetaVacia(carpeta) {
404
+ return !fs3.existsSync(carpeta) || fs3.readdirSync(carpeta).length === 0;
405
+ }
406
+ function encontrarEnPath(binario, env = process.env) {
407
+ const directorios = (env.PATH ?? env.Path ?? "").split(path3.delimiter).filter(Boolean);
408
+ const extensiones = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
409
+ for (const directorio of directorios) {
410
+ for (const extension of extensiones) {
411
+ const candidato = path3.join(directorio, `${binario}${extension}`);
412
+ try {
413
+ if (fs3.statSync(candidato).isFile()) return candidato;
414
+ } catch {
415
+ }
416
+ }
417
+ }
418
+ return null;
419
+ }
420
+ function exigirGenerador(lenguaje, env = process.env) {
421
+ const { binario, label } = LENGUAJE_REGISTRY[lenguaje];
422
+ if (!encontrarEnPath(binario, env)) {
423
+ throw new ErrorCli(`Para armar un proyecto ${label} necesito \`${binario}\`, y no est\xE1 instalado (no lo encuentro en el PATH). Inst\xE1lalo y vuelve a correr el comando; no cre\xE9 ning\xFAn archivo.`);
424
+ }
425
+ }
426
+ function correrGenerador(lenguaje, carpeta, salidaHumana) {
427
+ const [comando, ...argumentos] = LENGUAJE_REGISTRY[lenguaje].generador;
428
+ fs3.mkdirSync(carpeta, { recursive: true });
429
+ const r = spawnSync2(comando, argumentos, {
430
+ cwd: carpeta,
431
+ // Con `--json` la salida estándar es del objeto final: la del generador va a stderr.
432
+ stdio: ["ignore", salidaHumana === "inherit" ? "inherit" : process.stderr, "inherit"],
433
+ shell: process.platform === "win32"
434
+ });
435
+ if (r.error) throw new ErrorCli(`No pude correr \`${comando}\`: ${r.error.message}`);
436
+ if (r.status !== 0) throw new ErrorCli(`\`${[comando, ...argumentos].join(" ")}\` termin\xF3 con error (${r.status}). Revisa su salida arriba.`);
437
+ }
438
+ var carpetaPlantillas = () => {
439
+ const aqui = path3.dirname(fileURLToPath(import.meta.url));
440
+ for (const candidata of [path3.join(aqui, "plantillas"), path3.join(aqui, "..", "..", "plantillas")]) {
441
+ if (fs3.existsSync(candidata)) return candidata;
442
+ }
443
+ throw new ErrorCli("El paquete no trae las plantillas por lenguaje: la instalaci\xF3n del CLI est\xE1 incompleta. Reinst\xE1lalo.");
444
+ };
445
+ function agregarCapa(lenguaje, proyecto) {
446
+ const origen2 = path3.join(carpetaPlantillas(), lenguaje);
447
+ const escritos = [];
448
+ const copiar = (desde, hacia) => {
449
+ for (const entrada of fs3.readdirSync(desde, { withFileTypes: true })) {
450
+ const a = path3.join(desde, entrada.name);
451
+ const b = path3.join(hacia, entrada.name);
452
+ if (entrada.isDirectory()) {
453
+ fs3.mkdirSync(b, { recursive: true });
454
+ copiar(a, b);
455
+ } else {
456
+ fs3.copyFileSync(a, b);
457
+ escritos.push(path3.relative(proyecto, b));
458
+ }
459
+ }
460
+ };
461
+ copiar(origen2, proyecto);
462
+ LENGUAJE_REGISTRY[lenguaje].ajustar?.(proyecto);
463
+ return escritos.sort();
464
+ }
465
+
466
+ // src/comandos/init.ts
467
+ async function ejecutarInit(opciones, deps) {
468
+ const { salida, interactivo, preguntas } = deps;
469
+ if (opciones.entorno !== void 0 && !esEntornoLlave(opciones.entorno)) {
470
+ throw new ErrorCli(`--entorno debe ser ${ENTORNOS_LLAVE.join(" o ")} (recib\xED \xAB${opciones.entorno}\xBB).`);
471
+ }
472
+ if (!interactivo && opciones.entorno === void 0) {
473
+ throw new ErrorCli(`Sin una terminal interactiva, --entorno es obligatorio (${ENTORNOS_LLAVE.join(" o ")}). No elijo el entorno por ti.`);
474
+ }
475
+ if (opciones.lenguaje !== void 0 && !esLenguaje(opciones.lenguaje)) {
476
+ throw new ErrorCli(`--lenguaje debe ser uno de: ${LENGUAJES.join(", ")} (recib\xED \xAB${opciones.lenguaje}\xBB).`);
477
+ }
478
+ let proyecto = path4.resolve(deps.cwd, opciones.carpeta ?? ".");
479
+ let lenguaje = null;
480
+ if (carpetaVacia(proyecto)) {
481
+ if (opciones.lenguaje) lenguaje = opciones.lenguaje;
482
+ else if (interactivo) lenguaje = await preguntas.lenguaje();
483
+ else salida.linea(`La carpeta ${proyecto} est\xE1 vac\xEDa y no pasaste --lenguaje: instalo s\xF3lo la llave, sin armar un proyecto.`);
484
+ if (lenguaje) exigirGenerador(lenguaje);
485
+ } else {
486
+ if (opciones.lenguaje) throw new ErrorCli(`La carpeta ${proyecto} no est\xE1 vac\xEDa: --lenguaje s\xF3lo sirve para armar un proyecto desde cero. En un proyecto existente instalo s\xF3lo la llave.`);
487
+ if (interactivo && opciones.carpeta === void 0) proyecto = path4.resolve(deps.cwd, await preguntas.dondeInstalar("."));
488
+ }
489
+ const sesion = await deps.sesion();
490
+ const empresas = await sesion.usar((token) => deps.api.empresas(token));
491
+ if (empresas.length === 0) throw new ErrorCli("Tu cuenta no pertenece a ninguna empresa en rCAPI.");
492
+ let slug;
493
+ if (opciones.empresa) {
494
+ if (!empresas.some((e) => e.slug === opciones.empresa)) {
495
+ throw new ErrorCli(`No perteneces a la empresa \xAB${opciones.empresa}\xBB. Tus empresas: ${empresas.map((e) => e.slug).join(", ")}.`);
496
+ }
497
+ slug = opciones.empresa;
498
+ } else if (interactivo) {
499
+ slug = await preguntas.empresa(empresas);
500
+ } else {
501
+ throw new ErrorCli(`Sin una terminal interactiva, --empresa es obligatorio. Tus empresas: ${empresas.map((e) => e.slug).join(", ")}.`);
502
+ }
503
+ const empresa = empresas.find((e) => e.slug === slug);
504
+ const entorno = opciones.entorno ?? await preguntas.entorno();
505
+ if (lenguaje) {
506
+ salida.linea(`Armando el proyecto ${LENGUAJE_REGISTRY[lenguaje].label} con \`${LENGUAJE_REGISTRY[lenguaje].generador.join(" ")}\`\u2026`);
507
+ correrGenerador(lenguaje, proyecto, salida.json ? "pipe" : "inherit");
508
+ const capa = agregarCapa(lenguaje, proyecto);
509
+ salida.linea(`Capa de rCAPI agregada: ${capa.join(", ")}.`);
510
+ }
511
+ const anterior = empresaAnterior(proyecto, slug);
512
+ const instaladas = [];
513
+ instaladas.push(await instalarEntorno(proyecto, empresa, entorno, sesion, deps));
514
+ if (anterior) {
515
+ soltarEmpresaAnterior(proyecto, slug);
516
+ salida.aviso(`El proyecto apuntaba a ${anterior.empresa} (${anterior.entornos.join(" y ")}). Dej\xF3 de apuntar a esas llaves; siguen activas en la web y puedes revocarlas ah\xED.`);
517
+ }
518
+ for (const faltante of anterior?.entornos.filter((e) => e !== entorno) ?? []) {
519
+ salida.aviso(`El proyecto qued\xF3 sin llave de ${ENTORNO_LLAVE_REGISTRY[faltante].label} para ${empresa.nombre}.`);
520
+ if (interactivo && await preguntas.otroEntorno(faltante, empresa.nombre)) {
521
+ instaladas.push(await instalarEntorno(proyecto, empresa, faltante, sesion, deps));
522
+ } else {
523
+ salida.linea(`Para crearla: npx @redcumbrecl/cli init --empresa ${slug} --entorno ${faltante}`);
524
+ }
525
+ }
526
+ if (lenguaje) salida.linea(`Para probar la integraci\xF3n: ${LENGUAJE_REGISTRY[lenguaje].correrEjemplo}`);
527
+ let mcp = null;
528
+ if (!opciones.sinMcp) {
529
+ try {
530
+ mcp = conectarMcp(proyecto);
531
+ informarMcp(salida, mcp);
532
+ } catch (error) {
533
+ if (!(error instanceof ErrorCli)) throw error;
534
+ salida.aviso(`${error.message} La llave qued\xF3 instalada; el servidor MCP no se configur\xF3.`);
535
+ }
536
+ }
537
+ salida.resultado({
538
+ ok: true,
539
+ proyecto,
540
+ empresa: { slug: empresa.slug, nombre: empresa.nombre },
541
+ lenguaje,
542
+ llaves: instaladas.map((i) => ({
543
+ entorno: i.entorno,
544
+ resultado: i.resultado,
545
+ archivo: rutaRelativaLlave(i.entorno),
546
+ variable: variableDeEntorno(i.entorno),
547
+ sandbox: i.sandbox
548
+ })),
549
+ mcp
550
+ });
551
+ }
552
+ async function instalarEntorno(proyecto, empresa, entorno, sesion, deps) {
553
+ const { salida, api } = deps;
554
+ const envVersionado = estaVersionado(proyecto, ".env");
555
+ let resultado = "creada";
556
+ const guardada = leerLlave(proyecto, entorno);
557
+ const existente = guardada?.tenantSlug === empresa.slug ? guardada : null;
558
+ if (existente) {
559
+ const estado = await api.whoami(existente.token, existente.tenantSlug);
560
+ if (estado.estado === "valida" && estado.tenant.slug === empresa.slug && estado.sandbox === ENTORNO_LLAVE_REGISTRY[entorno].isSandbox) {
561
+ asegurarExclusiones(proyecto, envVersionado);
562
+ escribirPuntero(proyecto, entorno);
563
+ registrarEnEstado(proyecto, empresa.slug, entorno, estado.sandbox);
564
+ avisarEnvVersionado(salida, envVersionado);
565
+ mostrarWhoami(salida, estado.tenant, estado.sandbox, "Se reutiliz\xF3 la llave que ya ten\xEDa el proyecto");
566
+ return { entorno, resultado: "reutilizada", sandbox: estado.sandbox };
567
+ }
568
+ salida.linea(
569
+ estado.estado === "rechazada" ? `La llave de ${rutaRelativaLlave(entorno)} ya no funciona (\xBFla revocaron?): creo una nueva en su lugar.` : `La llave de ${rutaRelativaLlave(entorno)} no es de ${empresa.nombre} en ${ENTORNO_LLAVE_REGISTRY[entorno].label}: creo una nueva en su lugar.`
570
+ );
571
+ resultado = "reemplazada";
572
+ }
573
+ asegurarExclusiones(proyecto, envVersionado);
574
+ const nombre = nombreDeLlave(proyecto, entorno, deps.ahora());
575
+ let creada;
576
+ try {
577
+ creada = await sesion.usar((token) => api.crearLlave(token, empresa.slug, nombre, entorno));
578
+ } catch (error) {
579
+ if (!(error instanceof ErrorSinRolAdministrador)) throw error;
580
+ escribirPuntero(proyecto, entorno);
581
+ avisarEnvVersionado(salida, envVersionado);
582
+ throw new ErrorCli(
583
+ `Crear llaves exige ser administrador de ${empresa.nombre}: p\xEDdele a un administrador de ${empresa.nombre} que cree la llave en la pantalla web de llaves, y deja el archivo descargado en ${rutaLlave(proyecto, entorno)}`
584
+ );
585
+ }
586
+ escribirLlave(proyecto, entorno, {
587
+ tenantSlug: creada.tenantSlug,
588
+ name: creada.nombre,
589
+ role: "FULL-API",
590
+ isSandbox: ENTORNO_LLAVE_REGISTRY[creada.entorno].isSandbox,
591
+ token: creada.token,
592
+ expiresAt: creada.expiresAt,
593
+ createdAt: creada.createdAt
594
+ });
595
+ escribirPuntero(proyecto, entorno);
596
+ avisarEnvVersionado(salida, envVersionado);
597
+ const comprobada = await api.whoami(creada.token, creada.tenantSlug);
598
+ if (comprobada.estado !== "valida") {
599
+ throw new ErrorCli(`La llave reci\xE9n creada no pas\xF3 whoami. Qued\xF3 en ${rutaRelativaLlave(entorno)}; rev\xEDsala en la pantalla web de llaves.`);
600
+ }
601
+ registrarEnEstado(proyecto, comprobada.tenant.slug, entorno, comprobada.sandbox);
602
+ mostrarWhoami(salida, comprobada.tenant, comprobada.sandbox, `Llave \xAB${creada.nombre}\xBB instalada en ${rutaRelativaLlave(entorno)}`);
603
+ return { entorno, resultado, sandbox: comprobada.sandbox };
604
+ }
605
+ function avisarEnvVersionado(salida, versionado) {
606
+ if (versionado) {
607
+ salida.aviso("Tu .env est\xE1 en el control de versiones: s\xF3lo le agregu\xE9 la ruta a la llave (el secreto qued\xF3 en keys/, excluido). No lo saqu\xE9 de git; decide t\xFA si corresponde.");
608
+ }
609
+ }
610
+ function mostrarWhoami(salida, tenant, sandbox, encabezado) {
611
+ salida.linea(`\u2713 ${encabezado}.`);
612
+ salida.linea(` Empresa ${tenant.nombre} (${tenant.slug})`);
613
+ salida.linea(` Entorno ${sandbox ? "sandbox \u2014 no llega al SII ni consume folios" : "producci\xF3n \u2014 los documentos que emitas son reales ante el SII"}`);
614
+ if (sandbox) salida.aviso(`En sandbox no todo funciona. La lista de lo que s\xED: ${URL_ENTORNOS}`);
615
+ }
616
+
617
+ // src/comandos/login.ts
618
+ async function ejecutarLogin(deps) {
619
+ const sesion = await deps.sesion();
620
+ const empresas = await sesion.usar((token) => deps.api.empresas(token));
621
+ deps.salida.linea(`Tienes sesi\xF3n. Tus empresas: ${empresas.map((e) => `${e.nombre} (${e.slug})`).join(", ") || "ninguna"}.`);
622
+ deps.salida.resultado({ ok: true, empresas });
623
+ }
624
+
625
+ // src/comandos/logout.ts
626
+ async function ejecutarLogout(deps) {
627
+ const cerrada = await (await deps.sesion()).cerrar();
628
+ deps.salida.linea(cerrada ? "Sesi\xF3n cerrada: la revoqu\xE9 en el servidor de identidad y la borr\xE9 de este computador." : "No hab\xEDa una sesi\xF3n iniciada.");
629
+ deps.salida.resultado({ ok: true, sesionCerrada: cerrada });
630
+ }
631
+
632
+ // src/nucleo/preguntas.ts
633
+ import { confirm, input, select } from "@inquirer/prompts";
634
+ var DETALLE_ENTORNO = {
635
+ sandbox: "pruebas: no env\xEDa nada al SII ni consume folios",
636
+ produccion: "los documentos que emitas son reales ante el SII"
637
+ };
638
+ function preguntaEntorno() {
639
+ const opciones = ENTORNOS_LLAVE.map((entorno, i) => ` ${i + 1}) ${ENTORNO_LLAVE_REGISTRY[entorno].label} \u2014 ${DETALLE_ENTORNO[entorno]}`);
640
+ return {
641
+ message: ["\xBFPara qu\xE9 entorno es la llave?", ...opciones, `Escribe ${ENTORNOS_LLAVE.map((_, i) => i + 1).join(" o ")}:`].join("\n"),
642
+ validate: (respuesta) => interpretarEntorno(respuesta) ? true : `Escribe ${ENTORNOS_LLAVE.map((_, i) => i + 1).join(" o ")} (sin valor por omisi\xF3n).`
643
+ };
644
+ }
645
+ function interpretarEntorno(respuesta) {
646
+ const limpia = respuesta.trim().toLowerCase();
647
+ const porNumero = ENTORNOS_LLAVE[Number(limpia) - 1];
648
+ if (/^\d+$/.test(limpia) && porNumero) return porNumero;
649
+ return ENTORNOS_LLAVE.includes(limpia) ? limpia : null;
650
+ }
651
+ async function preguntarEntorno() {
652
+ const respuesta = await input(preguntaEntorno());
653
+ return interpretarEntorno(respuesta);
654
+ }
655
+ async function preguntarEmpresa(empresas) {
656
+ return select({
657
+ message: "\xBFPara qu\xE9 empresa es la llave?",
658
+ choices: empresas.map((e) => ({ name: `${e.nombre} (${e.slug})`, value: e.slug }))
659
+ });
660
+ }
661
+ async function preguntarLenguaje() {
662
+ return select({
663
+ message: "La carpeta est\xE1 vac\xEDa. \xBFEn qu\xE9 lenguaje armo el proyecto?",
664
+ choices: LENGUAJES.map((l) => ({ name: LENGUAJE_REGISTRY[l].label, value: l }))
665
+ });
666
+ }
667
+ async function preguntarDondeInstalar(actual) {
668
+ return input({ message: "\xBFEn qu\xE9 carpeta del proyecto instalo la llave? (Enter = la carpeta actual)", default: actual });
669
+ }
670
+ async function preguntarOtroEntorno(entorno, empresa) {
671
+ return confirm({ message: `\xBFCreo tambi\xE9n la llave de ${ENTORNO_LLAVE_REGISTRY[entorno].label} para ${empresa}?`, default: false });
672
+ }
673
+ async function leerLineaDeTerminal(pregunta, salida, entrada = process.stdin) {
674
+ const { createInterface } = await import("node:readline");
675
+ const rl = createInterface({ input: entrada, output: salida, terminal: false });
676
+ salida.write(pregunta);
677
+ return new Promise((resolver, rechazar) => {
678
+ let leida = null;
679
+ rl.once("line", (linea) => {
680
+ leida = linea;
681
+ rl.close();
682
+ });
683
+ rl.once("close", () => {
684
+ entrada.pause();
685
+ entrada.unref?.();
686
+ if (leida === null) rechazar(new ErrorCli("La entrada se cerr\xF3 antes de recibir el c\xF3digo. Vuelve a correr el comando."));
687
+ else resolver(leida);
688
+ });
689
+ });
690
+ }
691
+
692
+ // src/nucleo/sesion.ts
693
+ import { spawn } from "node:child_process";
694
+ import fs4 from "node:fs";
695
+ import http from "node:http";
696
+ import os from "node:os";
697
+ import path5 from "node:path";
698
+ import * as oidc from "openid-client";
699
+ function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
700
+ if (plataforma === "win32") {
701
+ if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
702
+ return path5.join(env.APPDATA, "redcumbre");
703
+ }
704
+ const base = env.XDG_CONFIG_HOME || path5.join(os.homedir(), ".config");
705
+ return path5.join(base, "redcumbre");
706
+ }
707
+ var AlmacenArchivo = class {
708
+ ruta;
709
+ descripcion;
710
+ /** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
711
+ constructor(carpeta, proyecto) {
712
+ this.ruta = path5.join(carpeta, "sesion.json");
713
+ const relativa = path5.relative(path5.resolve(proyecto), path5.resolve(this.ruta));
714
+ if (!relativa.startsWith("..") && !path5.isAbsolute(relativa)) {
715
+ throw new ErrorCli(
716
+ `La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
717
+ );
718
+ }
719
+ this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
720
+ }
721
+ leer() {
722
+ if (!fs4.existsSync(this.ruta)) return null;
723
+ return JSON.parse(fs4.readFileSync(this.ruta, "utf8"));
724
+ }
725
+ guardar(par) {
726
+ fs4.mkdirSync(path5.dirname(this.ruta), { recursive: true, mode: 448 });
727
+ fs4.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
728
+ fs4.chmodSync(this.ruta, 384);
729
+ }
730
+ borrar() {
731
+ fs4.rmSync(this.ruta, { force: true });
732
+ }
733
+ };
734
+ var AlmacenLlavero = class {
735
+ constructor(entrada) {
736
+ this.entrada = entrada;
737
+ }
738
+ descripcion = `el llavero del sistema (servicio ${SERVICIO_LLAVERO})`;
739
+ leer() {
740
+ const valor = this.entrada.getPassword();
741
+ return valor ? JSON.parse(valor) : null;
742
+ }
743
+ guardar(par) {
744
+ this.entrada.setPassword(JSON.stringify(par));
745
+ }
746
+ borrar() {
747
+ this.entrada.deletePassword();
748
+ }
749
+ };
750
+ async function elegirAlmacen(proyecto, env = process.env) {
751
+ if (env.REDCUMBRE_SESION_EN_ARCHIVO === "1") return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
752
+ try {
753
+ const { Entry } = await import("@napi-rs/keyring");
754
+ const entrada = new Entry(SERVICIO_LLAVERO, "sesion");
755
+ entrada.getPassword();
756
+ return new AlmacenLlavero(entrada);
757
+ } catch {
758
+ return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
759
+ }
760
+ }
761
+ var ErrorRefreshInvalido = class extends Error {
762
+ constructor() {
763
+ super("La sesi\xF3n guardada ya no es v\xE1lida.");
764
+ this.name = "ErrorRefreshInvalido";
765
+ }
766
+ };
767
+ function comoPar(respuesta) {
768
+ if (!respuesta.refresh_token) throw new ErrorCli("El servidor de identidad no devolvi\xF3 un refresh token.");
769
+ const segundos = respuesta.expiresIn();
770
+ if (segundos === void 0) throw new ErrorCli("El servidor de identidad no dijo cu\xE1ndo vence el token.");
771
+ return {
772
+ access_token: respuesta.access_token,
773
+ refresh_token: respuesta.refresh_token,
774
+ expira: new Date(Date.now() + segundos * 1e3).toISOString()
775
+ };
776
+ }
777
+ function refreshInvalido(codigo, descripcion) {
778
+ return codigo === "invalid_grant" || codigo === "invalid_request" && /RefreshToken/i.test(descripcion ?? "");
779
+ }
780
+ function esRefreshInvalido(error) {
781
+ return error instanceof oidc.ResponseBodyError && refreshInvalido(error.error, error.error_description);
782
+ }
783
+ function errorDeIdentidad(error) {
784
+ if (error instanceof oidc.ResponseBodyError) {
785
+ return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error.error}${error.error_description ? ` (${error.error_description})` : ""}.`);
786
+ }
787
+ const detalle = error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
788
+ return new ErrorCli(`No pude hablar con ${CLIENTE_OIDC.issuer} (${detalle}). Revisa tu conexi\xF3n y vuelve a intentarlo.`);
789
+ }
790
+ function identidadOidc() {
791
+ let configuracion = null;
792
+ const config = () => {
793
+ configuracion ??= oidc.discovery(new URL(CLIENTE_OIDC.issuer), CLIENTE_OIDC.clientId, void 0, oidc.None()).catch((error) => {
794
+ configuracion = null;
795
+ throw errorDeIdentidad(error);
796
+ });
797
+ return configuracion;
798
+ };
799
+ return {
800
+ async urlDeAutorizacion(redirectUri, pkce) {
801
+ return oidc.buildAuthorizationUrl(await config(), {
802
+ redirect_uri: redirectUri,
803
+ scope: SCOPE,
804
+ code_challenge: pkce.desafio,
805
+ code_challenge_method: "S256",
806
+ state: pkce.estado
807
+ }).toString();
808
+ },
809
+ async canjear(retorno, pkce) {
810
+ try {
811
+ return comoPar(await oidc.authorizationCodeGrant(await config(), retorno, { pkceCodeVerifier: pkce.verificador, expectedState: pkce.estado }));
812
+ } catch (error) {
813
+ if (error instanceof ErrorCli) throw error;
814
+ throw errorDeIdentidad(error);
815
+ }
816
+ },
817
+ async renovar(refreshToken) {
818
+ try {
819
+ return comoPar(await oidc.refreshTokenGrant(await config(), refreshToken));
820
+ } catch (error) {
821
+ if (esRefreshInvalido(error)) throw new ErrorRefreshInvalido();
822
+ if (error instanceof ErrorCli) throw error;
823
+ throw errorDeIdentidad(error);
824
+ }
825
+ },
826
+ async revocar(refreshToken) {
827
+ try {
828
+ await oidc.tokenRevocation(await config(), refreshToken, { token_type_hint: "refresh_token" });
829
+ } catch (error) {
830
+ throw errorDeIdentidad(error);
831
+ }
832
+ },
833
+ async exigeIss() {
834
+ return (await config()).serverMetadata().authorization_response_iss_parameter_supported === true;
835
+ }
836
+ };
837
+ }
838
+ async function crearPkce() {
839
+ const verificador = oidc.randomPKCECodeVerifier();
840
+ return { verificador, desafio: await oidc.calculatePKCECodeChallenge(verificador), estado: oidc.randomState() };
841
+ }
842
+ function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.platform) {
843
+ if (pedido) return true;
844
+ if (env.SSH_CONNECTION || env.SSH_TTY) return true;
845
+ return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
846
+ }
847
+ async function abrirNavegadorDelSistema(url) {
848
+ const [comando, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
849
+ return new Promise((resolver) => {
850
+ const hijo = spawn(comando, argumentos, { stdio: "ignore", detached: true });
851
+ hijo.once("error", () => resolver(false));
852
+ hijo.once("spawn", () => {
853
+ hijo.unref();
854
+ resolver(true);
855
+ });
856
+ });
857
+ }
858
+ var PAGINA_LISTO = `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>REDCUMBRE</title>
859
+ <meta name="viewport" content="width=device-width, initial-scale=1">
860
+ <style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:Canvas;color:CanvasText}
861
+ main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;opacity:.8}</style></head>
862
+ <body><main><h1>Listo, ya iniciaste sesi\xF3n</h1><p>Ya puedes cerrar esta ventana y volver a la terminal.</p></main></body></html>`;
863
+ async function loginConLoopback(identidad, salida, opciones) {
864
+ const pkce = await crearPkce();
865
+ let resolver;
866
+ let rechazar;
867
+ const retorno = new Promise((ok, falla) => {
868
+ resolver = ok;
869
+ rechazar = falla;
870
+ });
871
+ const servidor = http.createServer((req, res) => {
872
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
873
+ if (url.pathname !== "/callback") {
874
+ res.writeHead(404).end();
875
+ return;
876
+ }
877
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(PAGINA_LISTO);
878
+ resolver(url);
879
+ });
880
+ await new Promise((ok) => servidor.listen(0, "127.0.0.1", ok));
881
+ const { port } = servidor.address();
882
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
883
+ const espera = setTimeout(() => rechazar(new ErrorCli("No lleg\xF3 la autorizaci\xF3n del navegador en 5 minutos. Vuelve a correr el comando.")), opciones.esperaMs ?? 3e5);
884
+ try {
885
+ const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
886
+ const abierto = await (opciones.abrirNavegador ?? abrirNavegadorDelSistema)(url);
887
+ salida.linea(abierto ? "Abr\xED tu navegador para que inicies sesi\xF3n. Si no se abri\xF3, abre esta URL:" : "Abre esta URL en tu navegador para iniciar sesi\xF3n:");
888
+ salida.linea(url);
889
+ const vuelta = await retorno;
890
+ const recibida = new URL(`${redirectUri}${vuelta.search}`);
891
+ const error = recibida.searchParams.get("error");
892
+ if (error) throw new ErrorCli(`El inicio de sesi\xF3n no se complet\xF3: ${error}.`);
893
+ return await identidad.canjear(recibida, pkce);
894
+ } finally {
895
+ clearTimeout(espera);
896
+ servidor.close();
897
+ }
898
+ }
899
+ async function loginPegandoCodigo(identidad, salida, opciones) {
900
+ const pkce = await crearPkce();
901
+ const redirectUri = `${opciones.web}/cli/codigo`;
902
+ const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
903
+ salida.linea("Abre esta URL en un navegador, inicia sesi\xF3n y copia el c\xF3digo que te muestra la p\xE1gina:");
904
+ salida.linea(url);
905
+ const codigo = (await opciones.leerLinea("Pega el c\xF3digo aqu\xED: ")).trim();
906
+ if (!codigo) throw new ErrorCli("No recib\xED ning\xFAn c\xF3digo. Vuelve a correr el comando.");
907
+ const retorno = new URL(redirectUri);
908
+ retorno.searchParams.set("code", codigo);
909
+ retorno.searchParams.set("state", pkce.estado);
910
+ if (await identidad.exigeIss()) retorno.searchParams.set("iss", CLIENTE_OIDC.issuer);
911
+ return identidad.canjear(retorno, pkce);
912
+ }
913
+ async function iniciarSesion(identidad, salida, opciones) {
914
+ return opciones.sinNavegador ? loginPegandoCodigo(identidad, salida, opciones) : loginConLoopback(identidad, salida, opciones);
915
+ }
916
+ var Sesion = class {
917
+ constructor(almacen, identidad, salida, login) {
918
+ this.almacen = almacen;
919
+ this.identidad = identidad;
920
+ this.salida = salida;
921
+ this.login = login;
922
+ }
923
+ actual = null;
924
+ async entrar() {
925
+ const par = await this.login();
926
+ this.almacen.guardar(par);
927
+ this.salida.linea(`Sesi\xF3n iniciada. Qued\xF3 guardada en ${this.almacen.descripcion}.`);
928
+ return par;
929
+ }
930
+ /** El access token de esta corrida: renueva siempre la sesión guardada y guarda el par rotado. */
931
+ async token() {
932
+ if (this.actual) return this.actual.access_token;
933
+ const guardada = this.almacen.leer();
934
+ if (!guardada) {
935
+ this.actual = await this.entrar();
936
+ return this.actual.access_token;
937
+ }
938
+ try {
939
+ this.actual = await this.identidad.renovar(guardada.refresh_token);
940
+ this.almacen.guardar(this.actual);
941
+ } catch (error) {
942
+ if (!(error instanceof ErrorRefreshInvalido)) throw error;
943
+ this.almacen.borrar();
944
+ this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
945
+ this.actual = await this.entrar();
946
+ }
947
+ return this.actual.access_token;
948
+ }
949
+ /**
950
+ * Corre `operacion` con el token de la sesión. Si el API responde 401, borra la sesión, pide login y
951
+ * la repite UNA vez con el token nuevo; nunca reintenta con el mismo (`CA-33`).
952
+ */
953
+ async usar(operacion) {
954
+ try {
955
+ return await operacion(await this.token());
956
+ } catch (error) {
957
+ if (!(error instanceof ErrorSesionRechazada)) throw error;
958
+ this.almacen.borrar();
959
+ this.actual = null;
960
+ this.salida.linea("La plataforma rechaz\xF3 tu sesi\xF3n (por ejemplo, porque cambiaste tu contrase\xF1a). Inicia sesi\xF3n de nuevo.");
961
+ this.actual = await this.entrar();
962
+ try {
963
+ return await operacion(this.actual.access_token);
964
+ } catch (otra) {
965
+ if (otra instanceof ErrorSesionRechazada) throw new ErrorCli("La plataforma volvi\xF3 a rechazar la sesi\xF3n reci\xE9n iniciada. Escr\xEDbenos a soporte con la hora del intento.");
966
+ throw otra;
967
+ }
968
+ }
969
+ }
970
+ /** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
971
+ async cerrar() {
972
+ const guardada = this.almacen.leer();
973
+ if (!guardada) return false;
974
+ await this.identidad.revocar(guardada.refresh_token);
975
+ this.almacen.borrar();
976
+ return true;
977
+ }
978
+ };
979
+
980
+ // src/cli.ts
981
+ var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
982
+ function contexto(opciones, proyecto) {
983
+ const salida = crearSalida(Boolean(opciones.json));
984
+ const { api, web } = servidores();
985
+ const clienteApi = new ClienteApi(api);
986
+ const interactivo = Boolean(process.stdin.isTTY && process.stdout.isTTY);
987
+ const sesion = async () => {
988
+ const identidad = identidadOidc();
989
+ const almacen = await elegirAlmacen(proyecto);
990
+ return new Sesion(
991
+ almacen,
992
+ identidad,
993
+ salida,
994
+ () => iniciarSesion(identidad, salida, {
995
+ web,
996
+ sinNavegador: hayQueIrSinNavegador(Boolean(opciones.sinNavegador)),
997
+ leerLinea: (pregunta) => leerLineaDeTerminal(pregunta, salida.json ? process.stderr : process.stdout)
998
+ })
999
+ );
1000
+ };
1001
+ return { salida, api: clienteApi, interactivo, sesion };
1002
+ }
1003
+ async function correr(salida, accion) {
1004
+ try {
1005
+ await accion();
1006
+ } catch (error) {
1007
+ const s = salida();
1008
+ const mensaje = error instanceof Error ? error.message : String(error);
1009
+ if (s.json) process.stdout.write(`${JSON.stringify({ ok: false, error: mensaje, avisos: s.avisos }, null, 2)}
1010
+ `);
1011
+ process.stderr.write(`\u2717 ${mensaje}
1012
+ `);
1013
+ process.exitCode = error instanceof ErrorCli ? error.codigoSalida : 1;
1014
+ }
1015
+ }
1016
+ var programa = new Command().name("redcumbre").description("Conecta tu proyecto con rCAPI de REDCUMBRE: inicia sesi\xF3n con tu cuenta e instala la llave de la API en el proyecto.").version("0.1.0", "-v, --version", "muestra la versi\xF3n").helpOption("-h, --help", "muestra esta ayuda").helpCommand(false).usage("[opciones] [comando]").configureHelp({ styleTitle: (titulo) => TITULOS_AYUDA[titulo] ?? titulo, subcommandTerm: (comando) => `${comando.name()} [opciones]` }).showHelpAfterError("(corre redcumbre --help para ver los comandos)");
1017
+ var opcionSinNavegador = new Option("--sin-navegador", "no abre el navegador: imprime la URL y espera el c\xF3digo que muestra la p\xE1gina");
1018
+ var opcionJson = new Option("--json", "salida en JSON para agentes de c\xF3digo (nunca incluye el secreto de la llave)");
1019
+ programa.command("init").usage("[opciones]").description("inicia sesi\xF3n si hace falta e instala la llave de la API en el proyecto (en una carpeta vac\xEDa, arma antes el proyecto)").option("--empresa <slug>", "la empresa (tenantSlug) de la llave").option("--entorno <entorno>", `entorno de la llave: ${ENTORNOS_LLAVE.join(" o ")}; obligatorio sin terminal interactiva`).option("--lenguaje <lenguaje>", `lenguaje del proyecto desde cero, s\xF3lo en una carpeta vac\xEDa: ${LENGUAJES.join(", ")}`).option("--carpeta <ruta>", "carpeta del proyecto (por defecto, la actual)").option("--sin-mcp", "no configura el servidor MCP de rCAPI en .mcp.json ni .cursor/mcp.json").addOption(opcionJson).addOption(opcionSinNavegador).action(async (opciones) => {
1020
+ const ctx = contexto(opciones, opciones.carpeta ?? process.cwd());
1021
+ await correr(
1022
+ () => ctx.salida,
1023
+ () => ejecutarInit(opciones, {
1024
+ ...ctx,
1025
+ cwd: process.cwd(),
1026
+ ahora: () => /* @__PURE__ */ new Date(),
1027
+ preguntas: {
1028
+ entorno: preguntarEntorno,
1029
+ empresa: preguntarEmpresa,
1030
+ lenguaje: preguntarLenguaje,
1031
+ dondeInstalar: preguntarDondeInstalar,
1032
+ otroEntorno: preguntarOtroEntorno
1033
+ }
1034
+ })
1035
+ );
1036
+ });
1037
+ programa.command("conectar-mcp").usage("[opciones]").description("configura el servidor MCP de rCAPI para Claude Code (.mcp.json) y Cursor (.cursor/mcp.json) sin tocar otros servidores; no crea llaves").option("--carpeta <ruta>", "carpeta del proyecto (por defecto, la actual)").addOption(opcionJson).action(async (opciones) => {
1038
+ const salida = crearSalida(Boolean(opciones.json));
1039
+ await correr(() => salida, () => ejecutarConectarMcp(opciones, { salida, cwd: process.cwd() }));
1040
+ });
1041
+ programa.command("login").usage("[opciones]").description("inicia sesi\xF3n con tu cuenta de REDCUMBRE en el navegador (no crea llaves)").addOption(opcionJson).addOption(opcionSinNavegador).action(async (opciones) => {
1042
+ const ctx = contexto(opciones, process.cwd());
1043
+ await correr(() => ctx.salida, () => ejecutarLogin(ctx));
1044
+ });
1045
+ programa.command("logout").usage("[opciones]").description("cierra la sesi\xF3n: la revoca en el servidor de identidad y la borra de este computador").addOption(opcionJson).action(async (opciones) => {
1046
+ const ctx = contexto(opciones, process.cwd());
1047
+ await correr(() => ctx.salida, () => ejecutarLogout(ctx));
1048
+ });
1049
+ await programa.parseAsync(process.argv);