script for updating dns records on porkbun
1import fs from "node:fs/promises";
2import type { Config } from "./types.js";
3import { getPaths } from "./utils.js";
4
5export async function loadConfig(
6 cliFlags: Partial<Config>,
7 customPath?: string,
8): Promise<Config> {
9 const paths = getPaths();
10 const configFilePath = customPath || paths.configFile;
11
12 console.log(`loading config from ${configFilePath}...`);
13 let fileConfig: Partial<Config> = {};
14 try {
15 const content = await fs.readFile(configFilePath, "utf-8");
16 fileConfig = JSON.parse(content);
17 } catch (e) {
18 if ((e as NodeJS.ErrnoException).code !== "ENOENT") {
19 throw new Error(
20 `failed to parse config file at ${configFilePath}: ${(e as Error).message}`,
21 );
22 }
23
24 if (customPath) {
25 throw new Error(`config file not found at custom path ${configFilePath}`);
26 }
27
28 console.warn(
29 `no config file found at ${configFilePath}, proceeding with environment variables and CLI flags`,
30 );
31 }
32
33 // cli flags > env > file
34 const config: Config = {
35 apiKey: cliFlags.apiKey || process.env.API_KEY || fileConfig.apiKey || "",
36 secretApiKey:
37 cliFlags.secretApiKey ||
38 process.env.SECRET_API_KEY ||
39 fileConfig.secretApiKey ||
40 "",
41 domain: cliFlags.domain || process.env.DOMAIN || fileConfig.domain || "",
42 initialIps:
43 cliFlags.initialIps ||
44 (process.env.IP
45 ? process.env.IP.split(",").map((s) => s.trim())
46 : undefined) ||
47 fileConfig.initialIps,
48 };
49
50 // validate
51 const missing = [];
52 if (!config.apiKey) missing.push("apiKey");
53 if (!config.secretApiKey) missing.push("secretApiKey");
54 if (!config.domain) missing.push("domain");
55
56 if (missing.length > 0) {
57 throw new Error(
58 `missing required configuration: ${missing.join(", ")}. \n` +
59 `please provide them via flags, environment variables, or a config file at ${paths.configFile}`,
60 );
61 }
62
63 return config;
64}