|
1 | 1 | import { readFileSync } from 'fs'; |
2 | 2 | import { join } from 'path'; |
3 | | -import { validate as jsonSchemaValidate } from 'jsonschema'; |
| 3 | +import { ConfigSchema, type Config } from '../../proxy.config.schema'; |
4 | 4 |
|
5 | | -export let configFile: string = join(process.cwd(), 'proxy.config.json'); |
| 5 | +export let configFile: string = join(process.cwd(), 'config.proxy.json'); |
| 6 | +export let config: Config; |
6 | 7 |
|
7 | 8 | /** |
8 | | - * Set the config file path. |
9 | | - * @param {string} file - The path to the config file. |
| 9 | + * Sets the path to the configuration file. |
| 10 | + * |
| 11 | + * @param {string} file - The path to the configuration file. |
| 12 | + * @return {void} |
10 | 13 | */ |
11 | 14 | export function setConfigFile(file: string) { |
12 | 15 | configFile = file; |
13 | 16 | } |
14 | 17 |
|
15 | 18 | /** |
16 | | - * Validate config file. |
17 | | - * @param {string} configFilePath - The path to the config file. |
18 | | - * @return {boolean} - Returns true if validation is successful. |
19 | | - * @throws Will throw an error if the validation fails. |
| 19 | + * Loads and validates the configuration file using Zod. |
| 20 | + * If validation succeeds, the parsed config is stored in the exported `config`. |
| 21 | + * |
| 22 | + * @return {Config} The validated and default-filled configuration object. |
| 23 | + * @throws {ZodError} If validation fails. |
20 | 24 | */ |
21 | | -export function validate(configFilePath: string = configFile!): boolean { |
22 | | - const config = JSON.parse(readFileSync(configFilePath, 'utf-8')); |
23 | | - const schemaPath = join(process.cwd(), 'config.schema.json'); |
24 | | - const schema = JSON.parse(readFileSync(schemaPath, 'utf-8')); |
25 | | - jsonSchemaValidate(config, schema, { required: true, throwError: true }); |
| 25 | +export function loadConfig(): Config { |
| 26 | + const raw = JSON.parse(readFileSync(configFile, 'utf-8')); |
| 27 | + const parsed = ConfigSchema.parse(raw); |
| 28 | + config = parsed; |
| 29 | + return parsed; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Validates a configuration file without mutating the exported `config`. |
| 34 | + * |
| 35 | + * @param {string} [filePath=configFile] - Path to the configuration file to validate. |
| 36 | + * @return {boolean} Returns `true` if the file passes validation. |
| 37 | + * @throws {ZodError} If validation fails. |
| 38 | + */ |
| 39 | +export function validate(filePath: string = configFile): boolean { |
| 40 | + const raw = JSON.parse(readFileSync(filePath, 'utf-8')); |
| 41 | + ConfigSchema.parse(raw); |
26 | 42 | return true; |
27 | 43 | } |
0 commit comments