import { readFileSync, writeFileSync, existsSync, copyFileSync } from 'fs'; import { resolve, dirname } from 'path'; import { fileURLToPath } from 'url'; import { commandExists } from './utils/shell.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); export interface ContainerRuntime { // Binary name on PATH, e.g. `docker`, `podman`, `nerdctl`. cmd: string; // Argv prefix for compose subcommand, e.g. ['compose'] for `docker compose`. compose: string[]; // Human-readable label for status output. label: string; // Where the runtime was picked up. source: 'explicit' | 'env' | 'detected' | 'fallback'; } export interface CliConfig { apiUrl: string; apiKey: string; envFile: string; composeFile: string; substrateDir: string; cloudflareComposeFile: string; cloudflareConfigFile: string; runtime: ContainerRuntime; } function buildRuntime(cmd: string, label: string, source: ContainerRuntime['source']): ContainerRuntime { return { cmd, compose: ['compose'], label, source }; } function labelFor(cmd: string): string { switch (cmd) { case 'docker': return 'Docker'; case 'podman': return 'Podman'; case 'nerdctl': return 'nerdctl'; default: return cmd; } } // Picks the container CLI with precedence: --runtime flag > CONTAINER_RUNTIME env var > // CONTAINER_RUNTIME in .env > auto-detected from PATH > docker fallback. `source` is // surfaced in status output so users see where their runtime came from. export function resolveRuntime(opts: { explicit?: string; envFile?: string }): ContainerRuntime { const fromEnvFile = opts.envFile ? parseEnvFile(opts.envFile).CONTAINER_RUNTIME : undefined; const raw = (opts.explicit ?? process.env.CONTAINER_RUNTIME ?? fromEnvFile ?? '').trim().toLowerCase(); if (raw && raw !== 'auto') { const source: ContainerRuntime['source'] = opts.explicit ? 'explicit' : 'env'; return buildRuntime(raw, labelFor(raw), source); } if (commandExists('docker')) return buildRuntime('docker', 'Docker', 'detected'); if (commandExists('podman')) return buildRuntime('podman', 'Podman', 'detected'); if (commandExists('nerdctl')) return buildRuntime('nerdctl', 'nerdctl', 'detected'); return buildRuntime('docker', 'Docker', 'fallback'); } export function parseEnvFile(filePath: string): Record { if (!existsSync(filePath)) return {}; const content = readFileSync(filePath, 'utf-8'); const vars: Record = {}; for (const line of content.split('\n')) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) continue; const eqIdx = trimmed.indexOf('='); if (eqIdx === -1) continue; const key = trimmed.substring(0, eqIdx).trim(); let value = trimmed.substring(eqIdx + 1).trim(); // Strip surrounding quotes if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } vars[key] = value; } return vars; } export function envGet(key: string, envFile: string): string { const vars = parseEnvFile(envFile); return vars[key] || ''; } export function envSet(key: string, value: string, envFile: string): void { if (!existsSync(envFile)) { writeFileSync(envFile, `${key}=${value}\n`); return; } const content = readFileSync(envFile, 'utf-8'); const lines = content.split('\n'); let found = false; const updated = lines.map(line => { const trimmed = line.trim(); if (trimmed.startsWith(`${key}=`)) { found = true; return `${key}=${value}`; } return line; }); if (!found) updated.push(`${key}=${value}`); writeFileSync(envFile, updated.join('\n')); } export function ensureEnvFile(envFile: string, exampleFile: string): boolean { if (existsSync(envFile)) return false; if (existsSync(exampleFile)) { copyFileSync(exampleFile, envFile); } else { writeFileSync(envFile, ''); } return true; } export function loadConfig(opts?: { key?: string; url?: string; runtime?: string }): CliConfig { // Resolve paths relative to the CLI package location const substrateDir = resolve(__dirname, '../..'); const envFile = resolve(substrateDir, '.env'); const composeFile = resolve(substrateDir, 'docker-compose.yml'); const cloudflareComposeFile = resolve(substrateDir, 'docker-compose.cloudflared.yml'); const cloudflareConfigFile = resolve(substrateDir, 'cloudflared-config.yml'); const envVars = parseEnvFile(envFile); const apiKey = opts?.key || process.env.SUBSTRATE_API_KEY || envVars.SUBSTRATE_API_KEY || ''; const apiUrl = opts?.url || process.env.SUBSTRATE_URL || 'http://127.0.0.1:3100'; const runtime = resolveRuntime({ explicit: opts?.runtime, envFile }); return { apiUrl, apiKey, envFile, composeFile, substrateDir, cloudflareComposeFile, cloudflareConfigFile, runtime, }; }