Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 8x 9x 80x 80x 26x 26x 26x 26x 26x 26x 80x 9x 7x 7x 1x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 1x 7x 9x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 9x 5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 8x 8x 8x 8x 8x 9x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 1x 80x 80x 80x 80x 146x 17x 17x 146x 129x 129x 63x 63x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x | /**
* OpenFang Configuration Parser
*
* Provides configuration parsing, validation, and serialization for OpenFang TOML files.
*
* @module lib/config-parser
*/
import { tomlUtils, TomlParseError } from './toml-utils';
import { DEFAULT_MODEL_ID, DEFAULT_PROVIDER } from '../constants/models';
import type {
OpenFangConfig,
ConfigValidationResult,
ConfigValidationError,
ConfigValidationWarning,
ConfigFileMetadata,
ServerConfig,
AgentSectionConfig,
LLMConfig,
} from '../types/config';
/**
* Error class for configuration parsing errors
*/
export class ConfigParseError extends Error {
constructor(
message: string,
public readonly cause?: unknown
) {
super(message);
this.name = 'ConfigParseError';
}
}
/**
* Error class for configuration validation errors (thrown when validation fails)
*/
export class ConfigValidationFailedError extends Error {
constructor(
message: string,
public readonly errors: ConfigValidationError[]
) {
super(message);
this.name = 'ConfigValidationFailedError';
}
}
/**
* Required configuration fields with their paths
*/
const REQUIRED_FIELDS: Array<{ path: string; description: string }> = [
{ path: 'server', description: 'Server configuration' },
{ path: 'server.host', description: 'Server host address' },
{ path: 'server.port', description: 'Server port number' },
{ path: 'agent', description: 'Agent configuration' },
{ path: 'agent.defaults', description: 'Agent defaults' },
{ path: 'agent.defaults.workspace', description: 'Default workspace path' },
{ path: 'agent.defaults.default_model', description: 'Default model name' },
{ path: 'llm', description: 'LLM configuration' },
{ path: 'llm.default_provider', description: 'Default LLM provider' },
{ path: 'llm.default_model', description: 'Default LLM model' },
];
/**
* Default configuration values
*/
const DEFAULT_CONFIG: Partial<OpenFangConfig> = {
server: {
host: '127.0.0.1',
port: 4200,
websocket_port: 4200,
websocket_path: '/ws',
api_version: 'v1',
},
agent: {
defaults: {
workspace: '~/.openfang/workspace',
default_model: DEFAULT_MODEL_ID,
},
},
llm: {
default_provider: DEFAULT_PROVIDER,
default_model: DEFAULT_MODEL_ID,
},
};
/**
* Configuration parser and validator
*/
export const configParser = {
/**
* Parse TOML content into an OpenFang configuration object
*
* @param content - The TOML content to parse
* @param envVars - Optional environment variables for resolution
* @returns The parsed configuration object
* @throws ConfigParseError if parsing fails
*
* @example
* ```typescript
* const config = configParser.parseConfig(tomlContent, { OPENAI_API_KEY: 'sk-...' });
* ```
*/
parseConfig: (content: string, envVars?: Record<string, string | undefined>): OpenFangConfig => {
try {
// First resolve environment variables
const resolved = tomlUtils.resolveEnvVars(content, envVars);
// Parse TOML
const parsed = tomlUtils.parse<OpenFangConfig>(resolved);
return parsed;
} catch (error) {
if (error instanceof TomlParseError) {
throw new ConfigParseError(`Failed to parse configuration: ${error.message}`, error);
}
throw new ConfigParseError(
`Unexpected error parsing configuration: ${error instanceof Error ? error.message : String(error)}`,
error
);
}
},
/**
* Validate an OpenFang configuration object
*
* @param config - The configuration object to validate
* @returns Validation result with errors and warnings
*
* @example
* ```typescript
* const result = configParser.validateConfig(parsedConfig);
* if (!result.valid) {
* console.error('Config errors:', result.errors);
* }
* ```
*/
validateConfig: (config: unknown): ConfigValidationResult => {
const errors: ConfigValidationError[] = [];
const warnings: ConfigValidationWarning[] = [];
// Basic type check
if (typeof config !== 'object' || config === null) {
errors.push({
path: '',
message: 'Configuration must be a non-null object',
severity: 'error',
});
return { valid: false, errors, warnings };
}
const cfg = config as Record<string, unknown>;
// Check required fields
for (const { path, description } of REQUIRED_FIELDS) {
const value = getNestedValue(cfg, path);
if (value === undefined) {
errors.push({
path,
message: `Missing required field: ${description}`,
severity: 'error',
});
}
}
// Validate server configuration
if (cfg.server && typeof cfg.server === 'object') {
const server = cfg.server as ServerConfig;
if (typeof server.port === 'number' && (server.port < 1 || server.port > 65535)) {
errors.push({
path: 'server.port',
message: 'Port must be between 1 and 65535',
severity: 'error',
});
}
if (typeof server.host === 'string' && server.host.length === 0) {
errors.push({
path: 'server.host',
message: 'Host cannot be empty',
severity: 'error',
});
}
}
// Validate agent configuration
if (cfg.agent && typeof cfg.agent === 'object') {
const agent = cfg.agent as AgentSectionConfig;
if (agent.defaults) {
if (typeof agent.defaults.workspace === 'string' && agent.defaults.workspace.length === 0) {
warnings.push({
path: 'agent.defaults.workspace',
message: 'Workspace path is empty',
severity: 'warning',
});
}
if (typeof agent.defaults.default_model === 'string' && agent.defaults.default_model.length === 0) {
errors.push({
path: 'agent.defaults.default_model',
message: 'Default model cannot be empty',
severity: 'error',
});
}
}
}
// Validate LLM configuration
if (cfg.llm && typeof cfg.llm === 'object') {
const llm = cfg.llm as LLMConfig;
if (typeof llm.default_provider === 'string' && llm.default_provider.length === 0) {
errors.push({
path: 'llm.default_provider',
message: 'Default provider cannot be empty',
severity: 'error',
});
}
if (typeof llm.default_model === 'string' && llm.default_model.length === 0) {
errors.push({
path: 'llm.default_model',
message: 'Default model cannot be empty',
severity: 'error',
});
}
}
return {
valid: errors.length === 0,
errors,
warnings,
};
},
/**
* Parse and validate configuration in one step
*
* @param content - The TOML content to parse
* @param envVars - Optional environment variables for resolution
* @returns The parsed and validated configuration
* @throws ConfigParseError if parsing fails
* @throws ConfigValidationFailedError if validation fails
*
* @example
* ```typescript
* const config = configParser.parseAndValidate(tomlContent);
* ```
*/
parseAndValidate: (
content: string,
envVars?: Record<string, string | undefined>
): OpenFangConfig => {
const config = configParser.parseConfig(content, envVars);
const result = configParser.validateConfig(config);
if (!result.valid) {
throw new ConfigValidationFailedError(
`Configuration validation failed: ${result.errors.map((e) => e.message).join(', ')}`,
result.errors
);
}
return config;
},
/**
* Serialize a configuration object to TOML format
*
* @param config - The configuration object to serialize
* @returns The TOML string
*
* @example
* ```typescript
* const toml = configParser.stringifyConfig(config);
* ```
*/
stringifyConfig: (config: OpenFangConfig): string => {
return tomlUtils.stringify(config as unknown as Record<string, unknown>);
},
/**
* Merge partial configuration with defaults
*
* @param config - Partial configuration to merge
* @returns Complete configuration with defaults applied
*
* @example
* ```typescript
* const fullConfig = configParser.mergeWithDefaults(partialConfig);
* ```
*/
mergeWithDefaults: (config: Partial<OpenFangConfig>): OpenFangConfig => {
return deepMerge(DEFAULT_CONFIG, config) as unknown as OpenFangConfig;
},
/**
* Extract metadata from a TOML configuration file
*
* @param content - The TOML content
* @param filePath - The file path
* @returns Configuration file metadata
*
* @example
* ```typescript
* const metadata = configParser.extractMetadata(tomlContent, '/path/to/config.toml');
* console.log('Env vars needed:', metadata.envVars);
* ```
*/
extractMetadata: (content: string, filePath: string): ConfigFileMetadata => {
const envVars = tomlUtils.extractEnvVarNames(content);
const hasUnresolvedEnvVars = tomlUtils.hasUnresolvedEnvVars(content);
return {
path: filePath,
name: filePath.split('/').pop() || filePath,
envVars,
hasUnresolvedEnvVars,
};
},
/**
* Get default configuration
*
* @returns Default OpenFang configuration
*/
getDefaults: (): OpenFangConfig => {
return JSON.parse(JSON.stringify(DEFAULT_CONFIG)) as OpenFangConfig;
},
/**
* Check if a configuration object is valid
*
* @param config - The configuration to check
* @returns Type guard for OpenFangConfig
*/
isOpenFangConfig: (config: unknown): config is OpenFangConfig => {
const result = configParser.validateConfig(config);
return result.valid;
},
};
/**
* Helper function to get a nested value from an object using dot-notation path
*/
function getNestedValue(obj: Record<string, unknown>, path: string): unknown {
const parts = path.split('.');
let current: unknown = obj;
for (const part of parts) {
if (current === null || current === undefined) {
return undefined;
}
if (typeof current !== 'object') {
return undefined;
}
current = (current as Record<string, unknown>)[part];
}
return current;
}
/**
* Helper function to deep merge two objects
*/
function deepMerge<T extends Record<string, unknown>>(
target: Partial<T>,
source: Partial<T>
): Partial<T> {
const result = { ...target };
for (const key of Object.keys(source) as (keyof T)[]) {
const sourceValue = source[key];
const targetValue = target[key];
if (
sourceValue !== undefined &&
typeof sourceValue === 'object' &&
sourceValue !== null &&
!Array.isArray(sourceValue) &&
targetValue !== undefined &&
typeof targetValue === 'object' &&
targetValue !== null &&
!Array.isArray(targetValue)
) {
result[key] = deepMerge(
targetValue as Record<string, unknown>,
sourceValue as Record<string, unknown>
) as T[keyof T];
} else if (sourceValue !== undefined) {
// Safe assignment: sourceValue is typed as Partial<T>[keyof T], result[key] expects T[keyof T]
result[key] = sourceValue as T[keyof T];
}
}
return result;
}
export default configParser;
|