@visionfi/server-cli
Version:
Command-line interface for VisionFI Server SDK
89 lines (88 loc) • 2.97 kB
JavaScript
/**
* Configuration management for VisionFI CLI
* Copyright (c) 2024-2025 VisionFI. All Rights Reserved.
*/
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { VisionFI } from '@visionfi/server-sdk';
import { GoogleAuth } from 'google-auth-library';
const CONFIG_DIR = path.join(os.homedir(), '.visionfi', 'server');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
/**
* Load configuration from file or environment
*/
export function loadConfig() {
const config = {};
// Check for config file
if (fs.existsSync(CONFIG_FILE)) {
try {
const fileConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
Object.assign(config, fileConfig);
}
catch (error) {
console.warn('Warning: Failed to parse config file:', error);
}
}
// Environment variables override file config
if (process.env.VISIONFI_SERVICE_ACCOUNT_PATH) {
config.serviceAccountPath = process.env.VISIONFI_SERVICE_ACCOUNT_PATH;
}
if (process.env.VISIONFI_IMPERSONATE_SERVICE_ACCOUNT) {
config.impersonateServiceAccount = process.env.VISIONFI_IMPERSONATE_SERVICE_ACCOUNT;
config.authMethod = 'impersonate';
}
if (process.env.VISIONFI_API_URL) {
config.apiUrl = process.env.VISIONFI_API_URL;
}
// Check for Google Application Default Credentials
if (!config.serviceAccountPath && !config.impersonateServiceAccount) {
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
config.serviceAccountPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
}
}
return config;
}
/**
* Save configuration to file
*/
export function saveConfig(config) {
// Ensure config directory exists
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
// Don't save authClient (it's runtime only)
const configToSave = { ...config };
delete configToSave.authClient;
fs.writeFileSync(CONFIG_FILE, JSON.stringify(configToSave, null, 2));
}
/**
* Get config file path
*/
export function getConfigPath() {
return CONFIG_FILE;
}
/**
* Create a VisionFI client with proper authentication
*/
export function createClient() {
const config = loadConfig();
// Handle impersonation mode
if (config.authMethod === 'impersonate' && config.impersonateServiceAccount) {
// Pass impersonation config to SDK
return new VisionFI({
apiUrl: config.apiUrl,
audience: config.audience,
impersonateServiceAccount: config.impersonateServiceAccount,
apiKey: config.apiKey
});
}
// Create GoogleAuth instance if service account path is provided
if (config.serviceAccountPath) {
const auth = new GoogleAuth({
keyFilename: config.serviceAccountPath
});
config.authClient = auth;
}
return new VisionFI(config);
}