-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig-file.ts
59 lines (46 loc) · 1.83 KB
/
config-file.ts
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
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { z } from 'zod';
import { providerNames } from './engine/providers/provider.js';
const LEGACY_CONFIG_FILENAME = '.airc';
const CONFIG_FILENAME = '.airc.json';
const CommonProviderSchema = z.object({
apiKey: z.string(),
model: z.string().optional(),
systemPrompt: z.string().optional(),
});
const ProvidersSchema = z.object({
openAi: z.optional(CommonProviderSchema),
anthropic: z.optional(CommonProviderSchema),
perplexity: z.optional(CommonProviderSchema),
mistral: z.optional(CommonProviderSchema),
});
const ConfigFileSchema = z.object({
providers: ProvidersSchema,
});
export type ConfigFile = z.infer<typeof ConfigFileSchema>;
export function parseConfigFile() {
const configPath = path.join(os.homedir(), CONFIG_FILENAME);
const content = fs.readFileSync(configPath);
const json = JSON.parse(content.toString());
const typedConfig = ConfigFileSchema.parse(json);
if (providerNames.every((p) => !typedConfig.providers[p]?.apiKey)) {
throw new Error(`Add your provider API key to "~/${CONFIG_FILENAME}" and try again.`);
}
// Note: we return original json object, and not `typedConfig` because we want to preserve
// the original order of providers in the config file.
return json;
}
export function writeConfigFile(configContents: ConfigFile) {
const configPath = path.join(os.homedir(), CONFIG_FILENAME);
fs.writeFileSync(configPath, JSON.stringify(configContents, null, 2) + '\n');
}
export function checkIfConfigExists() {
const legacyConfigPath = path.join(os.homedir(), LEGACY_CONFIG_FILENAME);
const configPath = path.join(os.homedir(), CONFIG_FILENAME);
if (fs.existsSync(legacyConfigPath) && !fs.existsSync(configPath)) {
fs.renameSync(legacyConfigPath, configPath);
}
return fs.existsSync(configPath);
}