Configuration¶
Katal provides a Laravel-grade configuration architecture designed for modern TypeScript and cross-runtime execution (Bun, Node.js, Deno) with strictly zero external dependencies.
1. Core Architecture¶
flowchart TD
Env[".env, .env.local, .env.[NODE_ENV]"] --> DotEnv["Zero-Dep DotEnv Engine"]
Modules["config/*.ts, *.js, *.mjs, *.json"] --> Loader["Multi-Format ConfigLoader"]
DotEnv --> Loader
Loader --> Repo["ConfigRepository (Dot Notation)"]
Repo --> Global["Global config() Facade"]
Repo --> IoC["IoC Container (ConfigToken)"]
Repo --> Cache["katal config:cache (.katal/cache/config.json)"]
The configuration subsystem provides:
- Multi-Format Dynamic Modules: Author configuration in config/*.ts, config/*.js, config/*.mjs, or config/*.json.
- Standalone env<T>() Helper: Full Laravel-style type-casting semantics ((true), (false), (null), (empty)).
- RFC-Compliant Zero-Dep .env Engine: Comments, quotes, escaped characters, multiline strings, variable expansion ${VAR:-default}, and cascading file resolution.
- Recursive Dot-Notation Traversal: Query deep nested keys seamlessly: config('database.connections.mysql.host').
- Global config() Facade: Standalone helper callable anywhere with zero ceremony.
- Production Compilation Caching: katal config:cache freezes configuration for sub-millisecond cold starts ($< 1\text{ ms}$).
2. Defining Configuration Files (config/*.ts)¶
Katal discovers and mounts all files inside your project's config/ directory during boot. The file's base name becomes the top-level configuration namespace (e.g. config/database.ts $\rightarrow$ "database").
Use the zero-cost defineConfig helper for strong IDE autocomplete and type inference:
Example: config/app.ts¶
import { defineConfig, env } from "katal";
export default defineConfig({
name: env("APP_NAME", "Katal Application"),
env: env("APP_ENV", "production"),
debug: env("APP_DEBUG", false),
url: env("APP_URL", "http://localhost:3000"),
port: env<number>("PORT", 3000),
timezone: env("APP_TIMEZONE", "UTC"),
});
Example: config/database.ts¶
import { defineConfig, env } from "katal";
export default defineConfig({
default: env("DB_CONNECTION", "mysql"),
connections: {
mysql: {
host: env("DB_HOST", "127.0.0.1"),
port: env<number>("DB_PORT", 3306),
database: env("DB_DATABASE", "katal_db"),
username: env("DB_USERNAME", "root"),
password: env("DB_PASSWORD", null),
},
redis: {
host: env("REDIS_HOST", "127.0.0.1"),
port: env<number>("REDIS_PORT", 6379),
password: env("REDIS_PASSWORD", null),
},
},
});
3. Reading Configuration: The config() Facade¶
The global config() function provides 100% parity with Laravel's config() helper and can be imported and invoked anywhere in your codebase:
import { config } from "katal";
// 1. Read nested value with dot notation and default fallback
const dbHost = config("database.connections.mysql.host", "localhost");
const port = config<number>("app.port", 3000);
// 2. Check key existence
if (config().has("services.stripe.webhookSecret")) {
console.log("Stripe webhook listener configured");
}
// 3. Retrieve entire configuration dictionary
const allConfigs = config().all();
// 4. Runtime mutation (ideal for tests)
config({ "app.debug": true });
4. The env() Helper & Environment Engine¶
Katal ships with an in-process, zero-dependency environment engine that parses .env files automatically without third-party libraries.
Laravel-Style Type Casting¶
The env() function automatically casts string representations to native types:
Raw .env Value |
Inferred / Cast Type |
|---|---|
"true" or "(true)" |
true (boolean) |
"false" or "(false)" |
false (boolean) |
"null" or "(null)" |
null |
"empty" or "(empty)" |
"" (empty string) |
"8080" with default number |
8080 (number) |
{"key": "val"} |
parsed JSON object |
Variable Expansion in .env¶
You can compose variables and define default fallbacks directly in your .env file:
APP_HOST=localhost
APP_PORT=3000
APP_URL=http://${APP_HOST}:${APP_PORT}
FALLBACK_GATEWAY=${EXTERNAL_GATEWAY:-https://default.gateway.io}
Cascading .env Hierarchy¶
Katal loads environment files in the following precedence order:
1. .env
2. .env.local
3. .env.[NODE_ENV] (e.g. .env.production, .env.test)
4. .env.[NODE_ENV].local
5. Standard Schema v1 Validation on Configuration¶
You can attach a Standard Schema v1 validator (Zod, Valibot, ArkType, or Katal's native validator) to any configuration file. Katal validates the configuration during Application.boot(), failing fast before opening network ports if required environment variables or settings are missing:
// config/server.ts
import { defineConfig, env } from "katal";
import { z } from "zod";
const ServerConfigSchema = z.object({
port: z.number().int().min(1).max(65535),
host: z.string().min(1),
});
export default defineConfig({
schema: ServerConfigSchema,
config: {
port: env<number>("PORT", 3000),
host: env("HOST", "0.0.0.0"),
},
});
If validation fails, Katal produces a clean diagnostic report and halts startup:
Fatal configuration validation error in "config/server.ts":
- port: Expected number, received NaN
Server boot aborted.
6. Production Configuration Caching (config:cache)¶
In production environments, scanning directories and executing dynamic imports on every cold boot can add 50–150ms of latency. Katal provides an artisan-style CLI compiler:
# Compile and freeze all configuration files into .katal/cache/config.json
$ katal config:cache
# Clear the compiled configuration cache
$ katal config:clear
# Inspect configuration values (automatically masks passwords and secrets)
$ katal config:show database.connections.mysql
# Display full configuration including plaintext secrets
$ katal config:show database.connections.mysql --show-secrets
When .katal/cache/config.json exists, Katal loads the entire configuration in $< 1\text{ ms}$ via a single synchronous read.
7. Backward Compatibility: Options Pattern¶
Existing app.configure() and app.getConfig() calls continue to work seamlessly:
const mail = app.configure("mail", mailSchema, {
source: { host: "smtp.example.com" },
envPrefix: "MAIL_",
});
const resolved = app.getConfig("mail.host");