feat: add base url mechanism

This commit is contained in:
2026-03-24 19:28:28 +01:00
parent 4aeb108c55
commit a90f7ba078
3 changed files with 143 additions and 73 deletions

View File

@@ -1,91 +1,118 @@
import readline from 'readline';
import prompts from 'prompts';
import { ApiKeyInfo } from './environment-finder';
import { colors } from './logger';
function ask(rl: readline.Interface, query: string): Promise<string> {
return new Promise((resolve) => rl.question(query, resolve));
function clearScreen(): void {
process.stdout.write('\x1Bc');
}
function printHeader(current?: number, total?: number): void {
const stepText =
current !== undefined && total !== undefined
? ` [${colors.cyan}${current}${colors.reset} de ${colors.cyan}${total}${colors.reset}]`
: '';
console.log(`\n ${colors.bright}🔑 Configuración de URLs base${colors.reset}${stepText}`);
console.log(` ${'─'.repeat(54)}\n`);
}
function printSummary(tags: string[], result: Record<string, string>): void {
clearScreen();
console.log(`\n ${colors.bright}✅ Configuración completada${colors.reset}`);
console.log(` ${'─'.repeat(54)}\n`);
tags.forEach((tag) => {
console.log(` ${colors.bright}${tag}${colors.reset}`);
console.log(` ${colors.cyan}environment.${result[tag]}.url${colors.reset}\n`);
});
console.log(` ${'─'.repeat(54)}\n`);
}
/**
* Interactively asks the user which environment API key to use for each tag.
* Interactively asks the user which environment API key to use for each tag,
* using arrow-key selection. The last option always allows typing manually.
* Returns a map of tag → environment key (e.g. { "SupplyingMaintenances": "suppliyingMaintenancesApi" }).
*/
export async function askApiKeysForTags(
tags: string[],
apiKeys: ApiKeyInfo[]
): Promise<Record<string, string>> {
if (tags.length === 0) return {};
clearScreen();
printHeader();
const modeResponse = await prompts({
type: 'select',
name: 'mode',
message: 'URL base para los repositorios',
choices: [
{ title: `${colors.bright}La misma para todos${colors.reset}`, value: 'all' },
{ title: `${colors.bright}Configurar individualmente${colors.reset}`, value: 'individual' }
],
hint: ' '
});
if (modeResponse.mode === undefined) process.exit(0);
const result: Record<string, string> = {};
if (tags.length === 0) return result;
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
console.log('\n' + '─'.repeat(60));
console.log(`${colors.bright}🔑 Configuración de URLs base para repositorios${colors.reset}`);
console.log('─'.repeat(60));
for (const tag of tags) {
result[tag] = await askApiKeyForTag(rl, tag, apiKeys);
if (modeResponse.mode === 'all') {
clearScreen();
printHeader();
const sharedKey = await askApiKeyForTag('todos los repositorios', apiKeys);
tags.forEach((tag) => (result[tag] = sharedKey));
} else {
for (let i = 0; i < tags.length; i++) {
clearScreen();
printHeader(i + 1, tags.length);
result[tags[i]] = await askApiKeyForTag(tags[i], apiKeys);
}
}
rl.close();
printSummary(tags, result);
return result;
}
async function askApiKeyForTag(
rl: readline.Interface,
tagName: string,
apiKeys: ApiKeyInfo[]
): Promise<string> {
console.log(
`\n Repositorio: ${colors.cyan}${tagName}RepositoryImpl${colors.reset}`
);
async function askApiKeyForTag(tagName: string, apiKeys: ApiKeyInfo[]): Promise<string> {
const MANUAL_VALUE = '__manual__';
if (apiKeys.length > 0) {
console.log(` Selecciona la clave de environment para la URL base:\n`);
apiKeys.forEach((k, i) => {
const urlText = k.url ? `\n ${colors.cyan}${k.url}${colors.reset}` : '';
console.log(` ${colors.bright}${i + 1})${colors.reset} ${k.key}${urlText}`);
});
console.log(` ${colors.bright}${apiKeys.length + 1})${colors.reset} Escribir manualmente`);
} else {
console.log(` No se encontraron claves de API en environment.ts.`);
console.log(` Escribe la clave manualmente (ej: myApi):\n`);
}
while (true) {
const answer = (await ask(rl, `\n > `)).trim();
if (apiKeys.length > 0) {
const num = parseInt(answer, 10);
if (!isNaN(num) && num >= 1 && num <= apiKeys.length) {
const chosen = apiKeys[num - 1].key;
console.log(`${colors.bright}environment.${chosen}.url${colors.reset}`);
return chosen;
}
if (num === apiKeys.length + 1 || answer === '') {
const manual = (await ask(rl, ` Escribe la clave (ej: myApi): `)).trim();
if (manual) {
console.log(`${colors.bright}environment.${manual}.url${colors.reset}`);
return manual;
}
console.log(` ⚠️ La clave no puede estar vacía.`);
continue;
}
if (answer && isNaN(num)) {
console.log(`${colors.bright}environment.${answer}.url${colors.reset}`);
return answer;
}
console.log(
` ⚠️ Opción inválida. Elige un número del 1 al ${apiKeys.length + 1} o escribe la clave directamente.`
);
} else {
if (answer) {
console.log(`${colors.bright}environment.${answer}.url${colors.reset}`);
return answer;
}
console.log(` ⚠️ La clave no puede estar vacía.`);
const choices = [
...apiKeys.map((k) => ({
title: k.url
? `${colors.bright}${k.key}${colors.reset}\n ${colors.cyan}${k.url}${colors.reset}`
: `${colors.bright}${k.key}${colors.reset}`,
value: k.key
})),
{
title: `${colors.bright}Escribir manualmente${colors.reset}`,
value: MANUAL_VALUE
}
];
const selectResponse = await prompts({
type: 'select',
name: 'key',
message: `Repositorio ${colors.bright}${tagName}${colors.reset}`,
choices,
hint: ' '
});
if (selectResponse.key === undefined) process.exit(0);
if (selectResponse.key !== MANUAL_VALUE) {
return selectResponse.key as string;
}
console.log();
const textResponse = await prompts({
type: 'text',
name: 'key',
message: `Clave de environment`,
hint: 'ej: aprovalmApi',
validate: (v: string) => v.trim().length > 0 || 'La clave no puede estar vacía'
});
if (textResponse.key === undefined) process.exit(0);
return (textResponse.key as string).trim();
}