### Example: Full Configuration Setup with LoadConfig Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Demonstrates a complete configuration setup using zod for schema validation, a custom logger, and multiple adapters (JSON and environment variables) with loadConfig. ```typescript import { z } from 'zod'; import { loadConfig, type Config, type Adapter, type Logger, } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; import { jsonAdapter } from 'zod-config/json-adapter'; const schema = z.object({ port: z.string(), host: z.string(), }); const logger: Logger = { warn: (msg) => console.warn('[CONFIG]', msg), }; const config: Config = { schema, logger, keyMatching: 'lenient', adapters: [ jsonAdapter({ path: './config.json' }), envAdapter({ regex: /^APP_/ }), ], }; const result = await loadConfig(config); ``` -------------------------------- ### Zod-Config Complete Import Map Example Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md This example demonstrates how to import all necessary types and functions from the Zod-Config library. Ensure all listed modules are installed and available in your project. ```typescript import { loadConfig, loadConfigSync, ConfigAdapter, ConfigOptions, ConfigError, createConfigError, zodConfig, zodConfigSync, zodConfigAdapter, zodConfigOptions, zodConfigError, } from "zod-config"; ``` -------------------------------- ### Install Zod Config and Zod Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Install the zod-config and zod packages using npm, pnpm, or yarn. ```bash npm install zod-config zod # npm pnpm add zod-config zod # pnpm yarn add zod-config zod # yarn ``` -------------------------------- ### Adapter Functions Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Documentation for all 8 built-in adapters, including their type, file location, and full details such as signature, properties, return values, error handling, and examples. ```APIDOC ## Adapter Functions ### `envAdapter()` - **Type:** Sync - **File:** env-adapter - **Coverage:** Full: signature, props, returns, throws, 4 examples ### `jsonAdapter()` - **Type:** Sync - **File:** json-adapter - **Coverage:** Full: signature, props, returns, throws, example ### `json5Adapter()` - **Type:** Sync - **File:** json5-adapter - **Coverage:** Full: signature, props, returns, throws, example ### `yamlAdapter()` - **Type:** Sync - **File:** yaml-adapter - **Coverage:** Full: signature, props, returns, throws, example ### `tomlAdapter()` - **Type:** Sync - **File:** toml-adapter - **Coverage:** Full: signature, props, returns, throws, example ### `dotEnvAdapter()` - **Type:** Sync - **File:** dotenv-adapter - **Coverage:** Full: signature, props, returns, throws, example ### `scriptAdapter()` - **Type:** Async - **File:** script-adapter - **Coverage:** Full: signature, props, returns, example ### `directoryAdapter()` - **Type:** Async - **File:** directory-adapter - **Coverage:** Full: signature, props, returns, load order, example ``` -------------------------------- ### Load configuration from .env file Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Loads configuration from a .env file using the dotEnvAdapter. Ensure the dotenv package is installed. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { dotEnvAdapter } from 'zod-config/dotenv-adapter'; import path from 'path'; const schemaConfig = z.object({ MY_APP_PORT: z.string().regex(/^\d+$/), MY_APP_HOST: z.string(), }); const filePath = path.join(__dirname, '.env'); const config = await loadConfig({ schema: schemaConfig, adapters: dotEnvAdapter({ path: filePath }), }); ``` -------------------------------- ### Install dotenv dependency Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Install the dotenv package as a peer dependency to use the dotEnvAdapter. ```bash npm install dotenv ``` -------------------------------- ### Develop a Custom Adapter for Zod-Config Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/utilities.md Implement the `Adapter` interface to create custom configuration loading logic. The example demonstrates reading from a custom source, applying transformations, and configuring adapter behavior. ```typescript import type { Adapter } from 'zod-config'; export function myCustomAdapter(options): Adapter { return { name: 'my custom adapter', read: async () => { // Load configuration from custom source const data = await fetchConfigFromMySource(); // Apply transformations if needed if (options.transform) { // Use internal utilities return applyDataTransformation(data, options.transform); } return data; }, silent: options.silent, keyMatching: options.keyMatching, transform: options.transform, nestingSeparator: options.nestingSeparator, }; } ``` -------------------------------- ### Core Functions Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Coverage for the main configuration loading functions: `loadConfig` and `loadConfigSync`. Both are fully documented with signatures, parameters, return types, error handling, and multiple examples. ```APIDOC ## Core Functions ### `loadConfig()` Async config loading with full signature, parameters table, return type, throws, and 5+ examples. ### `loadConfigSync()` Sync config loading with full signature, parameters table, return type, throws, and 5+ examples. ``` -------------------------------- ### Import Zod and Load Config with Env Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Demonstrates importing Zod versions and loading configuration asynchronously using the `loadConfig` function with the `envAdapter`. Ensure correct Zod and zod-config versions are installed. ```typescript // Using Zod 4 import { z } from "zod/v4"; // for ^4.0.0 zod versions, you can import from "zod" instead // Using Zod 4 Mini import { z } from "zod/v4-mini"; // for ^4.0.0 zod versions, you can import from "zod/mini" instead // Using Zod 3 import { z } from "zod/v3"; import { loadConfig } from "zod-config"; import { envAdapter } from "zod-config/env-adapter"; const schema = z.object({ name: z.string(), }); const config = await loadConfig({ schema, adapters: [ envAdapter(), ], }); ``` -------------------------------- ### Load Configuration with Key Filtering Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Loads configuration from environment variables, filtering keys that match a specific regular expression. This example only loads keys prefixed with 'MY_APP_'. ```typescript const config = await loadConfig({ schema, adapters: envAdapter({ regex: /^MY_APP_/, // Only load MY_APP_* keys }), }); ``` -------------------------------- ### Using getSchemaShape Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Example of the `getSchemaShape` utility for retrieving the shape of a Zod schema. ```javascript const { getSchemaShape } = require('zod-config/lib/utils'); const z = require('zod'); const MySchema = z.object({ name: z.string(), age: z.number() }); const shape = getSchemaShape(MySchema); console.log(shape); // { name: [Function: ZodString] { ... }, age: [Function: ZodNumber] { ... } } ``` -------------------------------- ### Load Configuration from TOML File Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/adapters.md Use tomlAdapter to load configuration from a TOML file. Ensure the 'smol-toml' package is installed as a peer dependency. This adapter is synchronous. ```typescript import { loadConfig } from 'zod-config'; import { tomlAdapter } from 'zod-config/toml-adapter'; import { z } from 'zod'; import path from 'path'; const schema = z.object({ port: z.string(), host: z.string(), }); const config = await loadConfig({ schema, adapters: tomlAdapter({ path: path.join(__dirname, 'config.toml'), }), }); ``` -------------------------------- ### Load Config from TOML File Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Loads configuration from a TOML file. Requires the 'smol-toml' package to be installed. Supports filtering keys with a regex. ```bash npm install smol-toml ``` ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { tomlAdapter } from 'zod-config/toml-adapter'; import path from 'path'; const schemaConfig = z.object({ MY_APP_PORT: z.string().regex(/^\d+$/), MY_APP_HOST: z.string(), }); const filePath = path.join(__dirname, 'config.toml'); const config = await loadConfig({ schema: schemaConfig, adapters: tomlAdapter({ path: filePath }), }); ``` ```typescript // using filter regex to match only the keys we need const customConfig = await loadConfig({ schema: schemaConfig, adapters: tomlAdapter({ path: filePath, regex: /^MY_APP_/, }), }); ``` -------------------------------- ### Transform Function Example Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Shows how to use a transform function to manipulate configuration key-value pairs. It can be used to drop pairs or modify keys and values. ```typescript transform: ({ key, value }) => { if (key.includes('SECRET')) { return false; // Drop this pair } return { key: key.toLowerCase(), value: value.trim(), }; } ``` -------------------------------- ### Nesting Separator Example Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Demonstrates how a nesting separator converts flat keys into nested objects. This is useful for organizing configuration with common prefixes. ```typescript // With nestingSeparator: '_' { 'DATABASE_HOST': 'localhost', 'DATABASE_PORT': '5432' } // becomes { database: { host: 'localhost', port: '5432' } } ``` -------------------------------- ### Load Config from YAML File Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Loads configuration from a YAML file. Requires the 'yaml' package to be installed. Supports filtering keys with a regex. ```bash npm install yaml ``` ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { yamlAdapter } from 'zod-config/yaml-adapter'; import path from 'path'; const schemaConfig = z.object({ MY_APP_PORT: z.string().regex(/^\d+$/), MY_APP_HOST: z.string(), }); const filePath = path.join(__dirname, 'config.yaml'); const config = await loadConfig({ schema: schemaConfig, adapters: yamlAdapter({ path: filePath }), }); ``` ```typescript // using filter regex to match only the keys we need const customConfig = await loadConfig({ schema: schemaConfig, adapters: yamlAdapter({ path: filePath, regex: /^MY_APP_/, }), }); ``` -------------------------------- ### Load Config from JSON5 File Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Loads configuration from a JSON5 file. Requires the 'json5' package to be installed. Supports standard JSON5 syntax including comments, unquoted keys, and trailing commas. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { json5Adapter } from 'zod-config/json5-adapter'; import path from 'path'; /** content of config.json5 { // Server settings host: 'localhost', // Single quotes + unquoted key port: 3000, // Trailing comma allowedIPs: [ '192.168.0.1', '10.0.0.1', // Local access ] } */ const filePath = path.join(__dirname, 'config.json5'); const schemaConfig = z.object({ host: z.string(), port: z.number(), allowedIPs: z.array(z.string()), }); const config = await loadConfig({ schema: schemaConfig, adapters: json5Adapter({ path: filePath }), }); ``` -------------------------------- ### Load Environment Variables with envAdapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/adapters.md Use `envAdapter` to load configuration from environment variables. This example demonstrates loading `PORT` and `HOST` from `process.env` after defining a Zod schema. ```typescript import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; import { z } from 'zod'; const schema = z.object({ PORT: z.string(), HOST: z.string(), }); const config = await loadConfig({ schema, adapters: envAdapter(), }); ``` -------------------------------- ### loadConfig with Transform Function Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config.md Shows how to use a `transform` function with `loadConfig` to modify key-value pairs before validation. This example demonstrates dropping sensitive keys and transforming key formats. ```typescript const config = await loadConfig({ schema: z.object({ api: z.object({ key: z.string(), timeout: z.string(), }), }), transform: ({ key, value }) => { // Drop sensitive keys if (key.includes('SECRET')) { return false; } // Transform key format return { key: key.toLowerCase(), value, }; }, adapters: envAdapter({ customEnv: { 'API_KEY': 'key123', 'API_TIMEOUT': '5000', 'SECRET_TOKEN': 'should-be-dropped', }, }), }); ``` -------------------------------- ### Load Configuration with Directory Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/adapters.md Demonstrates how to use directoryAdapter to load configuration from files. It specifies the schema, the directory path, and how to handle different file extensions using scriptAdapter. The load order is also illustrated. ```typescript import { loadConfig } from 'zod-config'; import { directoryAdapter } from 'zod-config/directory-adapter'; import { scriptAdapter } from 'zod-config/script-adapter'; import { z } from 'zod'; import path from 'path'; const schema = z.object({ port: z.string(), host: z.string(), }); const config = await loadConfig({ schema, adapters: directoryAdapter({ paths: path.join(__dirname, 'config'), adapters: [ { extensions: ['.ts', '.js'], adapterFactory: (filePath: string) => scriptAdapter({ path: filePath }), }, ], }), }); // Loads from: default.ts → {deployment}.ts → {hostname}.ts → local.ts ``` -------------------------------- ### Adapter-Level Transform Example Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Illustrates an adapter-level transform function that only processes keys starting with 'MY_APP_', removing the prefix and converting to lowercase. This transform takes precedence over global transforms for this specific adapter. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; const schema = z.object({ database: z.object({ host: z.string(), port: z.string(), }), apiKey: z.string(), }); // Adapter-level transform - applied only to this adapter const configWithAdapterTransform = await loadConfig({ schema, adapters: envAdapter({ customEnv: { 'MY_APP_DATABASE_HOST': 'localhost', 'MY_APP_DATABASE_PORT': '5432', 'MY_APP_API_KEY': 'my-key', 'OTHER_VAR': 'ignored', }, transform: ({ key, value }) => { // Only process keys that start with 'MY_APP_' if (!key.startsWith('MY_APP_')) { return false; } // Remove the prefix and convert to lowercase const cleanKey = key.replace(/^MY_APP_/, '').toLowerCase(); return { key: cleanKey, value, }; }, nestingSeparator: '_', }), }); ``` -------------------------------- ### Synchronous Config Load with Regex Filter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config-sync.md Use this snippet to load configuration synchronously from a JSON file, filtering keys based on a regular expression. Ensure zod and zod-config are installed. The regex /^APP_/ ensures only keys starting with 'APP_' are loaded. ```typescript import { z } from 'zod'; import { loadConfigSync } from 'zod-config'; import { jsonAdapter } from 'zod-config/json-adapter'; const schema = z.object({ 'APP_PORT': z.string(), 'APP_HOST': z.string(), }); const config = loadConfigSync({ schema, adapters: jsonAdapter({ path: './config.json', regex: /^APP_/, // Only load keys starting with APP_ }), }); ``` -------------------------------- ### Load Config with Directory Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Demonstrates how to use the `directoryAdapter` to load configuration files from a specified directory. It shows how to map file extensions to specific adapter factories, such as `scriptAdapter` for TypeScript and JavaScript files. ```typescript import { directoryAdapter } from 'zod-config/directory-adapter'; import { scriptAdapter } from 'zod-config/script-adapter'; const config = await loadConfig({ schema, adapters: directoryAdapter({ paths: './config', adapters: [ { extensions: ['.ts', '.js'], adapterFactory: (path) => scriptAdapter({ path }), }, ], }), }); ``` -------------------------------- ### Multiple Adapters with Different Options Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/configuration.md Demonstrates using multiple adapters (JSON, environment variables, YAML) with different configuration options, including overriding global key matching at the adapter level. ```typescript await loadConfig({ schema, keyMatching: 'lenient', // Global: apply to all adapters: [ // JSON file uses global keyMatching jsonAdapter({ path: './config.json', }), // Env vars use strict matching (overrides global) envAdapter({ keyMatching: 'strict', }), // YAML uses global keyMatching with custom transform yamlAdapter({ path: './config.yaml', transform: ({ key, value }) => { // Custom logic for YAML only return { key, value }; }, }), ], }); ``` -------------------------------- ### Infer Configuration Data Type Example Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md An example demonstrating how `InferredDataConfig` infers the TypeScript type for a configuration object based on a Zod schema. ```typescript const schema = z.object({ port: z.string(), debug: z.boolean().optional(), }); type ConfigType = InferredDataConfig; // Result: { port: string; debug?: boolean } ``` -------------------------------- ### Using applyKeyMatching Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Demonstrates the `applyKeyMatching` utility for filtering keys based on a matching strategy. ```javascript const { applyKeyMatching } = require('zod-config/lib/utils'); const data = { 'user-name': 'John Doe', username: 'johndoe', 'user_id': 123 }; const keyMatching = 'strict'; // or 'lenient' const filtered = applyKeyMatching(data, keyMatching); console.log(filtered); // Depends on keyMatching strategy ``` -------------------------------- ### Using filteredData Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Example of the `filteredData` utility for filtering data based on a regex. ```javascript const { filteredData } = require('zod-config/lib/utils'); const data = { 'api_key': '12345', 'user_id': 101, 'debug_mode': true }; const regex = /^[^api_].*$/; const filtered = filteredData(data, regex); console.log(filtered); // { user_id: 101, 'debug_mode': true } ``` -------------------------------- ### Custom Adapter Development Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/utilities.md Guidance on developing custom adapters by implementing the `Adapter` or `SyncAdapter` interface, and a list of internal utilities available for use. ```APIDOC ## Custom Adapter Development When creating custom adapters, implement the `Adapter` or `SyncAdapter` interface: ```typescript import type { Adapter } from 'zod-config'; export function myCustomAdapter(options): Adapter { return { name: 'my custom adapter', read: async () => { // Load configuration from custom source const data = await fetchConfigFromMySource(); // Apply transformations if needed if (options.transform) { // Use internal utilities return applyDataTransformation(data, options.transform); } return data; }, silent: options.silent, keyMatching: options.keyMatching, transform: options.transform, nestingSeparator: options.nestingSeparator, }; } ``` Custom adapters can use these internal utilities for consistent behavior with built-in adapters: - `deepMerge()` - Combine multiple data sources - `applyKeyMatching()` - Match keys to schema - `applyDataTransformation()` - Apply transform and nesting - `processAdapterData()` - All-in-one processing - `filteredData()` - Filter by regex ``` -------------------------------- ### Using deepMerge Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Example of the `deepMerge` utility function, used for merging nested objects. ```javascript const deepMerge = require('zod-config/lib/utils').deepMerge; const obj1 = { a: 1, b: { c: 2 } }; const obj2 = { b: { d: 3 }, e: 4 }; const merged = deepMerge(obj1, obj2); console.log(merged); // { a: 1, b: { c: 2, d: 3 }, e: 4 } ``` -------------------------------- ### Load Configuration Synchronously Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Demonstrates how to import and use the `loadConfigSync` function to synchronously load and validate configuration. Requires schema and adapter definitions. ```typescript import { loadConfig, loadConfigSync } from 'zod-config'; import type { Adapter, SyncAdapter, Config, Logger } from 'zod-config'; const config = await loadConfigSync({ schema: mySchema, adapters: myAdapter, }); ``` -------------------------------- ### Basic Synchronous Configuration Loading Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config-sync.md Demonstrates how to load and validate a JSON configuration file synchronously using `loadConfigSync` and the `jsonAdapter`. Ensure the schema matches the expected configuration structure. ```typescript import { z } from 'zod'; import { loadConfigSync } from 'zod-config'; import { jsonAdapter } from 'zod-config/json-adapter'; const schema = z.object({ port: z.string(), host: z.string(), }); const config = loadConfigSync({ schema, adapters: jsonAdapter({ path: './config.json' }), }); console.log(config.port); ``` -------------------------------- ### Load Config with Multiple Synchronous Adapters Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config-sync.md Demonstrates loading configuration synchronously using multiple adapters. Adapters are processed in order, with later adapters overriding earlier ones. `jsonAdapter`, `dotEnvAdapter`, and `envAdapter` are used here. ```typescript import { z } from 'zod'; import { loadConfigSync } from 'zod-config'; import { jsonAdapter } from 'zod-config/json-adapter'; import { envAdapter } from 'zod-config/env-adapter'; import { dotEnvAdapter } from 'zod-config/dotenv-adapter'; const schema = z.object({ port: z.string(), host: z.string(), debug: z.boolean().optional(), }); const config = loadConfigSync({ schema, adapters: [ jsonAdapter({ path: './config.json' }), dotEnvAdapter({ path: './.env' }), envAdapter(), // process.env takes precedence ], }); ``` -------------------------------- ### Global Transform Example Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Demonstrates a global transform function that drops sensitive keys and converts all other keys to lowercase. Applied to all adapters. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; const schema = z.object({ database: z.object({ host: z.string(), port: z.string(), }), apiKey: z.string(), }); // Global transform - applied to all adapters const config = await loadConfig({ schema, transform: ({ key, value }) => { // Drop sensitive keys if (key.includes('SECRET')) { return false; } // Transform keys to lowercase return { key: key.toLowerCase(), value, }; }, adapters: envAdapter({ customEnv: { 'DATABASE_HOST': 'localhost', 'DATABASE_PORT': '5432', 'API_KEY': 'my-key', 'SECRET_TOKEN': 'should-be-dropped', }, nestingSeparator: '_', }), }); ``` -------------------------------- ### Load Configuration with TOML Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Demonstrates how to load configuration from a TOML file using the `tomlAdapter`. Ensure the `zod-config/toml-adapter` is imported and the `path` property is correctly set. ```typescript import { tomlAdapter } from 'zod-config/toml-adapter'; const config = await loadConfig({ schema, adapters: tomlAdapter({ path: './config.toml' }), }); ``` -------------------------------- ### directoryAdapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/adapters.md Loads configuration from multiple files in a directory following a specific load order. This adapter is asynchronous. ```APIDOC ## directoryAdapter Loads configuration from multiple files in a directory following a specific load order (similar to node-config). Useful for environment-specific configurations. **Import:** `import { directoryAdapter } from 'zod-config/directory-adapter'` **Sync:** No (async) ### Function Signature ```typescript directoryAdapter(props: DirectoryAdapterProps): Adapter ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | props | `DirectoryAdapterProps` | Yes | — | Adapter configuration options | | props.paths | `string | string[]` | Yes | — | Absolute or relative path(s) to directory/directories containing config files | | props.adapters | `AdapterSpecifier | AdapterSpecifier[]` | Yes | — | Adapter specifiers defining which file extensions map to which adapters | | props.regex | `RegExp` | No | — | Regular expression to filter keys | | props.silent | `boolean` | No | `false` | Whether to suppress error warnings | | props.keyMatching | `'strict' | 'lenient'` | No | `'strict'` | Key matching strategy | | props.transform | `Transform` | No | — | Function to transform key-value pairs | ### Load Order Files are loaded in the following order (later files override earlier ones): 1. `default.EXT` 2. `default-{instance}.EXT` 3. `{deployment}.EXT` 4. `{deployment}-{instance}.EXT` 5. `{short_hostname}.EXT` 6. `{short_hostname}-{instance}.EXT` 7. `{short_hostname}-{deployment}.EXT` 8. `{short_hostname}-{deployment}-{instance}.EXT` 9. `{hostname}.EXT` 10. `{hostname}-{instance}.EXT` 11. `{hostname}-{deployment}.EXT` 12. `{hostname}-{deployment}-{instance}.EXT` 13. `local.EXT` 14. `local-{instance}.EXT` 15. `local-{deployment}.EXT` 16. `local-{deployment}-{instance}.EXT` Where: - `EXT` = file extension (ts, js, json) - `instance` = `NODE_APP_INSTANCE` environment variable - `deployment` = `NODE_CONFIG_ENV` or `NODE_ENV` environment variable - `hostname` = `HOST`, `HOSTNAME` environment variables or `os.hostname()` - `short_hostname` = first part of hostname before the first dot ### Returns `Adapter` with name "directory adapter" (async) ### Example ```typescript import { loadConfig } from 'zod-config'; import { directoryAdapter } from 'zod-config/directory-adapter'; import { scriptAdapter } from 'zod-config/script-adapter'; import { z } from 'zod'; import path from 'path'; const schema = z.object({ port: z.string(), host: z.string(), }); const config = await loadConfig({ schema, adapters: directoryAdapter({ paths: path.join(__dirname, 'config'), adapters: [ { extensions: ['.ts', '.js'], adapterFactory: (filePath: string) => scriptAdapter({ path: filePath }), }, ], }), }); // Loads from: default.ts → {deployment}.ts → {hostname}.ts → local.ts ``` ### AdapterSpecifier Interface ```typescript type AdapterSpecifier = { extensions: string[]; // File extensions this adapter handles adapterFactory: AdapterFactory; // Factory function that creates adapters }; type AdapterFactory = (path: string) => Adapter; ``` ``` -------------------------------- ### Using applyDataTransformation Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Shows how to use the `applyDataTransformation` utility to transform key-value pairs. ```javascript const { applyDataTransformation } = require('zod-config/lib/utils'); const data = { 'user-name': 'John Doe', age: '30' }; const transform = { 'user-name': (value) => value.toUpperCase(), age: (value) => parseInt(value, 10) }; const transformed = applyDataTransformation(data, transform); console.log(transformed); // { 'user-name': 'JOHN DOE', age: 30 } ``` -------------------------------- ### loadConfigSync Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config-sync.md Synchronously loads and validates configuration from synchronous adapters using a Zod schema. If no adapters are provided, reads from process.env by default. Multiple adapters are deep-merged with later adapters taking precedence. ```APIDOC ## loadConfigSync ### Description Synchronously loads and validates configuration from synchronous adapters using a Zod schema. If no adapters are provided, reads from `process.env` by default. Multiple adapters are deep-merged with later adapters taking precedence. ### Function Signature ```typescript loadConfigSync(config: SyncConfig): InferredDataConfig ``` ### Parameters #### config (`SyncConfig`) Configuration object containing schema, adapters, and options - **schema** (`SchemaConfig`) - Required - Zod object schema to validate the loaded configuration - **adapters** (`SyncAdapter | Array`) - Optional - One or more synchronous adapters to load configuration from. Defaults to `process.env`. - **onSuccess** (`(data: InferredDataConfig) => void`) - Optional - Callback function invoked when configuration loads and validates successfully - **onError** (`(error: InferredErrorConfig) => void`) - Optional - Callback function invoked when validation fails (if provided, error is not thrown) - **logger** (`Logger`) - Optional - Custom logger implementation for warnings and errors. Defaults to `console`. - **keyMatching** (`'strict' | 'lenient'`) - Optional - Key matching strategy: 'strict' for exact matches, 'lenient' for case/format-insensitive matching. Defaults to `'strict'`. - **silent** (`boolean`) - Optional - Whether to suppress adapter error warnings. Defaults to `false`. - **transform** (`Transform`) - Optional - Function to transform key-value pairs before validation. ``` -------------------------------- ### Get Safe Process Environment Variables Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/utilities.md Use `getSafeProcessEnv` to obtain a serializable copy of `process.env`. This is particularly useful when `loadConfig` is called without explicit adapters. ```typescript const env = getSafeProcessEnv(); console.log(env.PORT); ``` -------------------------------- ### Load Configuration with Script Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Illustrates loading configuration from a script file (TypeScript, JavaScript, or JSON) using the `scriptAdapter`. Import `zod-config/script-adapter` and provide the path to your script file. ```typescript import { scriptAdapter } from 'zod-config/script-adapter'; const config = await loadConfig({ schema, adapters: scriptAdapter({ path: './config.ts' }), }); ``` -------------------------------- ### Load Configuration Asynchronously Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Demonstrates how to import and use the `loadConfig` function to asynchronously load and validate configuration. Requires schema and adapter definitions. ```typescript import { loadConfig, loadConfigSync } from 'zod-config'; import type { Adapter, SyncAdapter, Config, Logger } from 'zod-config'; const config = await loadConfig({ schema: mySchema, adapters: myAdapter, }); ``` -------------------------------- ### dotEnvAdapter() Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Creates an adapter for loading configuration from a .env file. ```APIDOC ## `dotEnvAdapter()` ### Description Creates an adapter for loading configuration from a .env file. ### Returns `SyncAdapter` - An adapter for .env files. ### Mode — ``` -------------------------------- ### Handle Invalid Data Transform Results Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/errors.md Shows an example of a data transformation error. This occurs when the `transform` function returns a value that is not in the expected `{ key, value }` format or `false`. ```typescript await loadConfig({ schema, transform: ({ key, value }) => { return 'invalid'; // Invalid return type }, adapters: envAdapter(), }); // Error: Invalid transform result for key "MY_VAR": expected { key: string, value: unknown } or false, received: "invalid" ``` -------------------------------- ### Load Configuration with Directory Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Loads configuration from files within a directory, supporting JSON files with specific extensions. Configuration is loaded in a cascading order: default.json, then environment-specific JSON, and finally local.json. ```typescript const config = await loadConfig({ schema, adapters: directoryAdapter({ paths: './config', adapters: [{ extensions: ['.json'], adapterFactory: (path) => jsonAdapter({ path }), }], }), }); // Loads: default.json → {NODE_ENV}.json → local.json (in order) ``` -------------------------------- ### Load Configuration from JSON5 File Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Use the `json5Adapter` to load configuration from a JSON5 file. Specify the file path using the `path` property. ```typescript import { json5Adapter } from 'zod-config/json5-adapter'; const config = await loadConfig({ schema, adapters: json5Adapter({ path: './config.json5' }), }); ``` -------------------------------- ### Using processAdapterData Utility Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Demonstrates the `processAdapterData` utility for processing data from an adapter. ```javascript const { processAdapterData } = require('zod-config/lib/utils'); const adapterData = { host: 'localhost', port: '5432' }; const schema = { host: { type: 'string' }, port: { type: 'number' } }; const processed = processAdapterData(adapterData, schema); console.log(processed); // { host: 'localhost', port: 5432 } ``` -------------------------------- ### Safely Accessing Environment Variables Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/COVERAGE.md Shows how to use `getSafeProcessEnv` to safely access environment variables, providing a default value if the variable is not set. ```javascript const { getSafeProcessEnv } = require('zod-config/lib/utils'); const port = getSafeProcessEnv('PORT', '3000'); console.log(`Server running on port: ${port}`); const apiKey = getSafeProcessEnv('API_KEY'); // Returns undefined if API_KEY is not set ``` -------------------------------- ### Load Configuration with Dotenv Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Shows how to load configuration from a `.env` file using the `dotEnvAdapter`. Import `zod-config/dotenv-adapter` and specify the path to your `.env` file. ```typescript import { dotEnvAdapter } from 'zod-config/dotenv-adapter'; const config = await loadConfig({ schema, adapters: dotEnvAdapter({ path: './.env' }), }); ``` -------------------------------- ### json5Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Loads configuration from a JSON5 file. It accepts an object with a `path` property indicating the JSON5 file's location. ```APIDOC ## json5Adapter ### Description Loads configuration from a JSON5 file. ### Signature `(props: Json5AdapterProps) => SyncAdapter` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `Json5AdapterProps`: - **path** (string) - Required - The path to the JSON5 configuration file. ### Request Example ```typescript import { json5Adapter } from 'zod-config/json5-adapter'; const config = await loadConfig({ schema, adapters: json5Adapter({ path: './config.json5' }), }); ``` ### Response `SyncAdapter` ``` -------------------------------- ### Load Config with Default Env Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Shows how to load configuration asynchronously using `loadConfig` when no adapter is specified, defaulting to `process.env`. The loaded configuration is type-safe. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const config = await loadConfig({ schema: schemaConfig }); // config is now type safe! console.log(config.port) console.log(config.host) ``` -------------------------------- ### loadConfig with Lenient Key Matching Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config.md Demonstrates using the 'lenient' key matching strategy with `loadConfig` and `envAdapter`. This allows for case-insensitive and format-insensitive matching of environment variable keys. ```typescript const config = await loadConfig({ schema: z.object({ myApiKey: z.string(), databaseHost: z.string(), }), keyMatching: 'lenient', adapters: envAdapter({ customEnv: { 'MY_API_KEY': 'secret123', 'DATABASE_HOST': 'localhost', }, }), }); // Keys with different casing/formatting are matched automatically ``` -------------------------------- ### directoryAdapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/INDEX.md Creates an adapter for reading configuration files from a directory. This is useful for loading multiple configuration files. ```APIDOC ## directoryAdapter(props: DirectoryAdapterProps): Adapter ### Description Provides an adapter for reading configuration files from a specified directory. Requires properties to define the directory and potentially file patterns. ### Parameters - **props** (`DirectoryAdapterProps`): Properties to configure the directory adapter, including the directory path. ### Returns - `Adapter`: An adapter instance. ``` -------------------------------- ### Load Configuration from JSON File Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Use the `jsonAdapter` to load configuration from a JSON file. Ensure the `path` property points to your configuration file. ```typescript import { jsonAdapter } from 'zod-config/json-adapter'; const config = await loadConfig({ schema, adapters: jsonAdapter({ path: './config.json' }), }); ``` -------------------------------- ### Load YAML Config with Lenient Key Matching Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config-sync.md Illustrates loading configuration from a YAML file using `yamlAdapter` with `keyMatching: 'lenient'`. This allows for flexible key naming in the YAML file, such as `database_url` or `DATABASE-URL`, to match the schema's `databaseUrl`. ```typescript import { z } from 'zod'; import { loadConfigSync } from 'zod-config'; import { yamlAdapter } from 'zod-config/yaml-adapter'; const schema = z.object({ databaseUrl: z.string(), apiTimeout: z.string(), }); const config = loadConfigSync({ schema, keyMatching: 'lenient', adapters: yamlAdapter({ path: './config.yaml' }), }); // Keys in YAML like 'database_url' or 'DATABASE-URL' are matched to 'databaseUrl' ``` -------------------------------- ### Load configuration from directory with multiple files Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Loads configuration from a directory containing multiple configuration files, respecting a specific file load order inspired by node-config. This adapter is often used with scriptAdapter for different file types. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { directoryAdapter } from 'zod-config/directory-adapter'; import { scriptAdapter } from 'zod-config/script-adapter'; import path from 'path'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const directories = [path.join(__dirname, 'config-dir')]; const config = await loadConfig({ schema, adapters: directoryAdapter({ paths: directories, adapters: [ { // Restrict adapter to handle only ts files extensions: [".ts"], // Use the scriptAdapter for handling .ts files adapterFactory: (filePath: string) => scriptAdapter({ path: filePath, }), }, // { // Add here other adapters for other file types if needed // } ], }), }); ``` -------------------------------- ### loadConfig Function Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config.md Asynchronously loads and validates configuration from one or more adapters using a Zod schema. If no adapters are provided, reads from process.env by default. Multiple adapters are deep-merged with later adapters taking precedence. ```APIDOC ## Function Signature ```typescript loadConfig(config: Config): Promise> ``` ### Parameters #### config (`Config`) - Required Configuration object containing schema, adapters, and options. - **schema** (`SchemaConfig`) - Required - Zod object schema to validate the loaded configuration. - **adapters** (`Adapter | SyncAdapter | Array`) - Optional - One or more adapters to load configuration from. Can be a single adapter or an array. Defaults to `process.env`. - **onSuccess** (`(data: InferredDataConfig) => void`) - Optional - Callback function invoked when configuration loads and validates successfully. - **onError** (`(error: InferredErrorConfig) => void`) - Optional - Callback function invoked when validation fails (if provided, error is not thrown). - **logger** (`Logger`) - Optional - Custom logger implementation for warnings and errors. Defaults to `console`. - **keyMatching** (`'strict' | 'lenient'`) - Optional - Key matching strategy: 'strict' for exact matches, 'lenient' for case/format-insensitive matching. Defaults to `'strict'`. - **silent** (`boolean`) - Optional - Whether to suppress adapter error warnings. Defaults to `false`. - **transform** (`Transform`) - Optional - Function to transform key-value pairs before validation. ### Return Type `Promise>` A promise that resolves to the validated configuration object typed according to the provided schema. If an `onError` callback is provided, returns an empty object `{}` on validation failure instead of throwing. ### Throws - `ZodError` if schema validation fails and no `onError` callback is provided. - `Error` if all adapters fail to read (wrapped in adapter error messages). ### Behavior 1. Normalizes adapters to array format. 2. Reads data from all adapters in sequence (async). 3. Handles adapter failures gracefully—failed adapters log warnings but don't halt processing. 4. Deep-merges data from all adapters (later adapters override earlier ones). 5. Applies schema validation using Zod v3 or v4 (auto-detected). 6. Invokes `onSuccess` or `onError` callback if provided. 7. Throws or returns based on callback configuration. ``` -------------------------------- ### Load Configuration with Fallback Chain Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Loads configuration using a fallback chain of adapters, prioritizing environment variables, then a JSON file, and finally hardcoded default values. ```typescript const config = await loadConfig({ schema, adapters: [ envAdapter(), jsonAdapter({ path: './config.json' }), envAdapter({ customEnv: DEFAULT_CONFIG, silent: true, }), ], }); // Tries env → JSON file → hardcoded defaults ``` -------------------------------- ### scriptAdapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/INDEX.md Creates an adapter that executes a script to retrieve configuration values. This allows for dynamic configuration loading. ```APIDOC ## scriptAdapter(props: ScriptAdapterProps): Adapter ### Description Provides an adapter that executes a script to dynamically fetch configuration values. Requires properties to specify the script to run. ### Parameters - **props** (`ScriptAdapterProps`): Properties to configure the script adapter, including the script path or command. ### Returns - `Adapter`: An adapter instance. ``` -------------------------------- ### loadConfig() Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/README.md Asynchronously loads configuration based on the provided schema and adapters. It supports various adapters for different configuration sources like environment variables, JSON, JSON5, YAML, TOML, dotenv files, and scripts. ```APIDOC ## `loadConfig()` ### Description Asynchronously loads configuration based on the provided schema and adapters. It supports various adapters for different configuration sources like environment variables, JSON, JSON5, YAML, TOML, dotenv files, and scripts. ### Returns `Promise` - A promise that resolves to the loaded configuration object. ### Mode Async ``` -------------------------------- ### Combine Multiple Adapters for Configuration Loading Source: https://github.com/alexmarqs/zod-config/blob/main/README.md Load configuration from multiple sources by combining adapters. Configuration is deep-merged in the order provided. Be aware that `null` values from later adapters will override existing values. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; import { jsonAdapter } from 'zod-config/json-adapter'; import path from 'path'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const filePath = path.join(__dirname, 'config.json'); const config = await loadConfig({ schema: schemaConfig, adapters: [ jsonAdapter({ path: filePath }), envAdapter(), ], }); ``` -------------------------------- ### loadConfig with Multiple Adapters Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/load-config.md Shows how to use loadConfig with multiple adapters, including a JSON file adapter and an environment variable adapter. Later adapters override earlier ones. ```typescript import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { jsonAdapter } from 'zod-config/json-adapter'; import { envAdapter } from 'zod-config/env-adapter'; const schema = z.object({ port: z.string(), host: z.string(), }); const config = await loadConfig({ schema, adapters: [ jsonAdapter({ path: './config.json' }), envAdapter(), // env vars override json file ], }); ``` -------------------------------- ### Use Environment Variable Adapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Shows how to import and use the `envAdapter` from 'zod-config/env-adapter' to load configuration from environment variables. Allows customization of environment variables and regex for matching. ```typescript import { envAdapter } from 'zod-config/env-adapter'; const config = await loadConfig({ schema, adapters: envAdapter({ customEnv: process.env, regex: /^APP_/, }), }); ``` -------------------------------- ### scriptAdapter Source: https://github.com/alexmarqs/zod-config/blob/main/_autodocs/api-reference/module-exports.md Loads configuration from a TypeScript, JavaScript, or JSON file. It accepts an object with a `path` property specifying the script file location. ```APIDOC ## scriptAdapter ### Description Loads configuration from a TypeScript/JavaScript/JSON file. ### Signature `(props: ScriptAdapterProps) => Adapter` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the script configuration file. ### Example ```typescript import { scriptAdapter, type ScriptAdapterProps } from 'zod-config/script-adapter'; const config = await loadConfig({ schema, adapters: scriptAdapter({ path: './config.ts' }), }); ``` ```