### Install Dependencies with npm Source: https://github.com/redsquiggle/envictus/blob/main/examples/joi/README.md Installs the necessary dependencies for the Joi example using npm. This is a prerequisite for running the envictus Joi demonstration. ```bash cd examples/joi npm install ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/redsquiggle/envictus/blob/main/examples/custom-discriminator/README.md Installs the necessary dependencies for the custom discriminator example using npm. This is a standard setup step for Node.js projects. ```bash cd examples/custom-discriminator npm install ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/examples/valibot/README.md Installs the necessary dependencies for the Valibot example using npm. This is a prerequisite for running the envictus and Valibot configurations. ```bash cd examples/valibot npm install ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/examples/yup/README.md Installs the necessary dependencies for the Yup example project using npm. ```bash cd examples/yup npm install ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/redsquiggle/envictus/blob/main/examples/env-files/README.md Installs the necessary project dependencies using npm. This is a prerequisite for running the envictus examples. ```bash cd examples/env-files npm install ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/redsquiggle/envictus/blob/main/examples/arktype/README.md Installs the necessary project dependencies using npm. This is a prerequisite for running the envictus and ArkType examples. ```bash cd examples/arktype npm install ``` -------------------------------- ### Install Envictus with Joi Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/01-installation.md Installs the Envictus library and the Joi schema validation library using npm. This option allows for the use of Joi for validating environment variables managed by Envictus. ```bash npm install envictus joi ``` -------------------------------- ### Run Command with Envictus Validation Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/02-quick-start.md Executes a command (e.g., `npm run dev`) after Envictus has validated the environment variables against the defined schema. This ensures that your application starts only with correctly configured environment variables. ```bash envictus -- npm run dev ``` -------------------------------- ### Install Envictus with Valibot Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/01-installation.md Installs the Envictus library and the Valibot schema validation library using npm. This option is for users who prefer Valibot for defining and validating their environment variables. ```bash npm install envictus valibot ``` -------------------------------- ### Install Envictus with Yup Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/01-installation.md Installs the Envictus library and the Yup schema validation library using npm. This command is for integrating Envictus with Yup for environment variable validation. ```bash npm install envictus yup ``` -------------------------------- ### Install Envictus with ArkType Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/01-installation.md Installs the Envictus library along with the ArkType schema validation library via npm. This is suitable for developers who utilize ArkType for their schema definitions. ```bash npm install envictus arktype ``` -------------------------------- ### Run Envictus with Production Defaults (NODE_ENV) Source: https://github.com/redsquiggle/envictus/blob/main/examples/joi/README.md Runs envictus with production defaults by setting the NODE_ENV environment variable. The Node.js script then logs the PORT, which is configured to be 8080 in production. ```bash NODE_ENV=production envictus -- node -e "console.log(process.env.PORT)" ``` -------------------------------- ### Run Application with Server Configuration using Envictus CLI Source: https://github.com/redsquiggle/envictus/blob/main/examples/composition/README.md This command executes a Node.js application using the server environment configuration. Envictus loads and validates the specified configuration before running the target script. ```bash envictus -c examples/composition/server.env.config.ts -- node server.js ``` -------------------------------- ### Run Application with Development Defaults Source: https://github.com/redsquiggle/envictus/blob/main/examples/arktype/README.md Executes a Node.js script using envictus, applying the default development environment variables. It demonstrates accessing an environment variable like PORT. ```bash envictus -- node -e "console.log(process.env.PORT)" ``` -------------------------------- ### Run Build Step with Client Configuration using Envictus CLI Source: https://github.com/redsquiggle/envictus/blob/main/examples/composition/README.md This command executes a Next.js build step using the client environment configuration. Envictus ensures that only public, browser-safe variables are available during the build process. ```bash envictus -c examples/composition/client.env.config.ts -- next build ``` -------------------------------- ### Install Envictus with Zod Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/01-installation.md Installs the Envictus library along with the Zod schema validation library using npm. This is the primary method for integrating Envictus with Zod for environment variable validation. ```bash npm install envictus zod ``` -------------------------------- ### Run Envictus with Production Defaults (-m flag) Source: https://github.com/redsquiggle/envictus/blob/main/examples/joi/README.md Executes envictus using the '-m' flag to explicitly specify the production environment. This loads production defaults, and the Node.js script logs the PORT, expected to be 8080. ```bash envictus -m production -- node -e "console.log(process.env.PORT)" ``` -------------------------------- ### Valibot Schema Validation Example Source: https://context7.com/redsquiggle/envictus/llms.txt Illustrates configuring envictus with Valibot schemas. This example highlights Valibot's explicit transformation pipelines using v.pipe() for type coercion and validation. ```typescript import { defineConfig } from "envictus"; import * as v from "valibot"; export default defineConfig({ schema: v.object({ NODE_ENV: v.optional(v.picklist(["development", "production", "test"])), "development"), DATABASE_URL: v.pipe(v.string(), v.url()), PORT: v.pipe(v.unknown(), v.transform(Number), v.number(), v.minValue(1), v.maxValue(65535)), DEBUG: v.optional( v.pipe( v.unknown(), v.transform((val) => val === "true" || val === "1"), ), ), LOG_LEVEL: v.optional(v.picklist(["debug", "info", "warn", "error"])), "info"), }), discriminator: "NODE_ENV", defaults: { development: { DATABASE_URL: "postgres://localhost:5432/dev", PORT: 3000, DEBUG: true, }, production: { DATABASE_URL: "postgres://prod.example.com:5432/prod", PORT: 8080, DEBUG: false, }, }, }); ``` -------------------------------- ### Validate Client Configuration with Envictus CLI Source: https://github.com/redsquiggle/envictus/blob/main/examples/composition/README.md This command validates the client environment configuration file using the Envictus CLI. It checks for browser-safe variables and adherence to the client schema. ```bash envictus check -c examples/composition/client.env.config.ts ``` -------------------------------- ### Run Application with Production Defaults Source: https://github.com/redsquiggle/envictus/blob/main/examples/arktype/README.md Executes a Node.js script using envictus, applying production environment variables. This can be achieved either by setting the NODE_ENV variable or using the -m flag. ```bash # Via environment variable NODE_ENV=production envictus -- node -e "console.log(process.env.PORT)" # Via -m flag envictus -m production -- node -e "console.log(process.env.PORT)" ``` -------------------------------- ### Programmatic Configuration Access (TypeScript) Source: https://github.com/redsquiggle/envictus/blob/main/examples/groups/README.md Accesses configuration values programmatically after loading the root config. It demonstrates accessing both root-level fields and fields nested within groups. ```typescript import config from "./env.config.js"; const env = await config.env; // Root fields — flat access env.PORT; // number env.DATABASE_URL; // string env.LOG_LEVEL; // "debug" | "info" | "warn" | "error" // Group fields — namespaced env.stripe.STRIPE_SECRET_KEY; // string env.stripe.STRIPE_WEBHOOK_SECRET; // string env.stripe.STRIPE_PUBLISHABLE_KEY; // string ``` -------------------------------- ### ArkType Schema Validation Example Source: https://context7.com/redsquiggle/envictus/llms.txt Shows how to use ArkType with envictus for defining environment variable schemas. This example leverages ArkType's string-based type expressions and inline defaults. ```typescript import { type } from "arktype"; import { defineConfig } from "envictus"; export default defineConfig({ schema: type({ NODE_ENV: "'development' | 'production' | 'test' = 'development'", DATABASE_URL: "string.url", PORT: "string.numeric", "DEBUG?": "string", LOG_LEVEL: "'debug' | 'info' | 'warn' | 'error' = 'info'", }), discriminator: "NODE_ENV", defaults: { development: { DATABASE_URL: "postgres://localhost:5432/dev", PORT: "3000", DEBUG: "true", LOG_LEVEL: "debug", }, production: { DATABASE_URL: "postgres://prod.example.com:5432/prod", PORT: "8080", LOG_LEVEL: "warn", }, }, }); ``` -------------------------------- ### Validate Envictus Configuration Source: https://github.com/redsquiggle/envictus/blob/main/examples/env-files/README.md Checks the validity of the envictus configuration. This command helps ensure that the environment variables are correctly set up according to the defined schema. ```bash envictus check ``` ```bash NODE_ENV=production envictus check ``` -------------------------------- ### Validate Envictus Configuration Source: https://github.com/redsquiggle/envictus/blob/main/examples/joi/README.md Checks the validity of the current envictus configuration based on the defined Joi schemas. This command helps ensure that all required environment variables are set correctly. ```bash envictus check ``` -------------------------------- ### Run Application with envictus and Custom Discriminators Source: https://github.com/redsquiggle/envictus/blob/main/examples/custom-discriminator/README.md Executes a Node.js script using envictus, demonstrating how to apply different environment configurations based on the custom discriminator 'APP_ENV'. It shows default, staging, and production environments. ```bash # Run with local defaults (default) envictus -- node -e "console.log(process.env.API_URL)" # http://localhost:4000 # Run with staging defaults (via environment variable) APP_ENV=staging envictus -- node -e "console.log(process.env.API_URL)" # https://staging.api.example.com # Run with prod defaults (via -m flag) envictus -m prod -- node -e "console.log(process.env.API_URL)" # https://api.example.com ``` -------------------------------- ### Run Application with Development Defaults Source: https://github.com/redsquiggle/envictus/blob/main/examples/env-files/README.md Executes a Node.js script using envictus, loading default environment variables from `.env.local` for development. It demonstrates accessing the `API_URL` environment variable. ```bash envictus -- node -e "console.log(process.env.API_URL)" ``` -------------------------------- ### Validate Server Configuration with Envictus CLI Source: https://github.com/redsquiggle/envictus/blob/main/examples/composition/README.md This command validates the server environment configuration file using the Envictus CLI. It ensures that all required server-specific variables are correctly defined and formatted. ```bash envictus check -c examples/composition/server.env.config.ts ``` -------------------------------- ### Standalone Group Configuration Access (TypeScript) Source: https://github.com/redsquiggle/envictus/blob/main/examples/groups/README.md Demonstrates accessing configuration values directly from a standalone group config. This is useful when a specific group's configuration needs to be used independently. ```typescript import { stripe } from "./stripe.env.config.js"; const stripeEnv = await stripe.env; stripeEnv.STRIPE_SECRET_KEY; // string ``` -------------------------------- ### Validate Production Envictus Configuration Source: https://github.com/redsquiggle/envictus/blob/main/examples/joi/README.md Validates the envictus configuration specifically for the production environment by setting NODE_ENV. This ensures that the production-specific environment variables meet the defined schema requirements. ```bash NODE_ENV=production envictus check ``` -------------------------------- ### Validate Envictus Configuration (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/examples/yup/README.md Validates the current Envictus configuration. This command checks if the environment variables conform to the defined Yup schema. ```bash envictus check ``` ```bash NODE_ENV=production envictus check ``` -------------------------------- ### Validate Environment Configuration Source: https://github.com/redsquiggle/envictus/blob/main/examples/arktype/README.md Validates the current environment's configuration against the defined ArkType schema using envictus. This helps ensure that all required environment variables are set correctly. ```bash # Validate development configuration (default) envictus check # Validate production configuration NODE_ENV=production envictus check ``` -------------------------------- ### Validate envictus Configuration (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/examples/valibot/README.md Checks the validity of the envictus configuration, optionally with production defaults. This command verifies that all required environment variables are present and correctly typed according to the defined schema. ```bash # Validate default configuration envictus check # Validate production configuration NODE_ENV=production envictus check ``` -------------------------------- ### Programmatic Envictus Configuration with Top-Level Await Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript example demonstrates programmatic usage of envictus. It configures the environment variables, including loading from a '.env.prod' file for production. The top-level await ensures that the validated environment variables are available as a typed object (`env`) when the module is imported. ```typescript // env.config.ts import { defineConfig, parseEnv } from "envictus"; const config = defineConfig({ schema: envSchema, discriminator: "APP_ENV", defaults: { dev: { DATABASE_URL: "postgres://localhost:5432/myapp_dev", PUBLIC_URL: "https://app-dev.example.com", LOG_LEVEL: "debug", }, prod: { PUBLIC_URL: "https://app.example.com", LOG_LEVEL: "error", ...parseEnv(".env.prod", { onMissing: "ignore" }), }, }, }); export default config; export const env = await config.env; ``` -------------------------------- ### Programmatic Access to Client and Server Environment Variables Source: https://github.com/redsquiggle/envictus/blob/main/examples/composition/README.md This TypeScript code demonstrates how to programmatically access validated client and server environment variables using Envictus. It imports configurations and asynchronously resolves their respective `.env` properties for type-safe access. ```typescript import clientConfig from "./client.env.config.js"; import serverConfig from "./server.env.config.js"; // Each config resolves independently with full type safety const clientEnv = await clientConfig.env; // ^? { NEXT_PUBLIC_APP_ENV: ..., NEXT_PUBLIC_API_URL: ..., ... } const serverEnv = await serverConfig.env; // ^? { NEXT_PUBLIC_APP_ENV: ..., NEXT_PUBLIC_API_URL: ..., LOG_LEVEL: ..., DATABASE_URL: ..., ... } ``` -------------------------------- ### Validate envictus Configuration Source: https://github.com/redsquiggle/envictus/blob/main/examples/custom-discriminator/README.md Validates the current envictus configuration, ensuring that all environment variables and their types match the defined schema. This is crucial for catching configuration errors early. ```bash # Validate configuration envictus check # Validate production configuration APP_ENV=prod envictus check ``` -------------------------------- ### Run Envictus with Production Defaults (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/examples/yup/README.md Executes a Node.js script using Envictus with production defaults. This can be achieved by setting the NODE_ENV environment variable or using the -m flag. It logs the PORT environment variable, which defaults to 8080 in production. ```bash NODE_ENV=production envictus -- node -e "console.log(process.env.PORT)" ``` ```bash envictus -m production -- node -e "console.log(process.env.PORT)" ``` -------------------------------- ### Specify Custom Configuration Path (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Use the `-c` or `--config` flag to specify a custom path to the environment configuration file. This allows for more organized project structures. The example shows using a TypeScript file for configuration. ```bash # Custom config path envictus -c ./config/env.ts -- node server.js envictus --config ./config/env.ts -- node server.js ``` -------------------------------- ### Define Envictus Configuration with Zod Schema Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/02-quick-start.md Creates an `env.config.ts` file to define environment variable schemas using Zod and provides default values for different environments. This ensures type safety and validation for your application's environment variables. ```typescript import { defineConfig } from "envictus"; import { z } from "zod"; export default defineConfig({ schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]).default("development"), DATABASE_URL: z.string().url(), PORT: z.coerce.number().min(1).max(65535), DEBUG: z.coerce.boolean().optional(), }), discriminator: "NODE_ENV", defaults: { development: { DATABASE_URL: "postgres://localhost:5432/dev", PORT: 3000, DEBUG: true, }, production: { DATABASE_URL: "postgres://prod.example.com:5432/prod", PORT: 8080, DEBUG: false, }, test: { DATABASE_URL: "postgres://localhost:5432/test", PORT: 3001, DEBUG: false, }, }, }); ``` -------------------------------- ### Define Environment Variables with Valibot Schema Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/01-schema.md Defines environment variables using Valibot, a lightweight and fast schema validation library. It provides examples for NODE_ENV, DATABASE_URL, and PORT with specific validation rules. ```typescript import * as v from "valibot"; schema: v.object({ NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"), DATABASE_URL: v.pipe(v.string(), v.url()), PORT: v.pipe(v.string(), v.transform(Number), v.minValue(1), v.maxValue(65535)), }) ``` -------------------------------- ### Print Resolved Environment (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Output the fully resolved environment variables to standard output. The `--format json` option can be used to get the output in JSON format, which is useful for scripting or debugging. ```bash # Print resolved environment to stdout envictus printenv envictus printenv --format json ``` -------------------------------- ### Enable Debug Output with --verbose Flag in Bash Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/08-debugging.md This snippet demonstrates how to enable debug output in envictus using the --verbose flag in a bash environment. It shows two examples: one running an npm script and another executing a 'check' command. This flag provides detailed information about discriminator resolution and mode selection. ```bash envictus --verbose -- npm run dev envictus -v check ``` -------------------------------- ### Define Environment Variables with ArkType Schema Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/01-schema.md Defines environment variables using ArkType, a schema-based type system for TypeScript. This example shows how to declare NODE_ENV, DATABASE_URL, and PORT with ArkType's string-based schema syntax. ```typescript import { type } from "arktype"; schema: type({ NODE_ENV: "'development' | 'production' | 'test' = 'development'", DATABASE_URL: "string.url", PORT: "string.numeric.parse.integer > 0", }) ``` -------------------------------- ### Check Command with Envictus CLI (Bash) Source: https://context7.com/redsquiggle/envictus/llms.txt Validates environment configuration without executing a command. This is useful for CI/CD pipelines to verify environment setup before deployment. It can be used with a custom config file and supports verbose output for detailed validation information. ```bash # Validate current environment envictus check # Output: ✓ Environment is valid # Validate with custom config envictus check --config ./env.config.ts # Verbose validation output envictus check --verbose # Output: [envictus] Using NODE_ENV from environment: production # ✓ Environment is valid ``` -------------------------------- ### Configure Envictus with Zod Schema and Defaults Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript code defines the environment configuration for envictus. It specifies a Zod schema for validation, a discriminator ('NODE_ENV') to switch between environments, and default values for 'development', 'production', and 'test' modes. This setup ensures type-safe access to environment variables. ```typescript import { defineConfig } from "envictus"; import { z } from "zod"; export default defineConfig({ schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]) .default("development"), DATABASE_URL: z.string().url(), PORT: z.coerce.number().min(1).max(65535), DEBUG: z.coerce.boolean().optional(), }), discriminator: "NODE_ENV", defaults: { development: { DATABASE_URL: "postgres://localhost:5432/dev", PORT: 3000, DEBUG: true, }, production: { DATABASE_URL: "postgres://prod.example.com:5432/prod", PORT: 8080, DEBUG: false, }, test: { DATABASE_URL: "postgres://localhost:5432/test", PORT: 3001, DEBUG: false, }, }, }); ``` -------------------------------- ### TypeScript Discriminator Configuration Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/02-discriminator.md Configures the application's discriminator using TypeScript. It defines a schema with APP_ENV and API_URL, sets APP_ENV as the discriminator, and provides default API_URL values for local, staging, and production environments. This setup helps manage environment-specific configurations effectively. ```typescript export default defineConfig({ schema: z.object({ APP_ENV: z.enum(["local", "staging", "prod"]), API_URL: z.string().url(), }), discriminator: "APP_ENV", defaults: { local: { API_URL: "http://localhost:4000", }, staging: { API_URL: "https://staging.api.example.com", }, prod: { API_URL: "https://api.example.com", }, }, }); ``` -------------------------------- ### Get Environment Variables Programmatically with getEnv (TypeScript) Source: https://context7.com/redsquiggle/envictus/llms.txt Resolves and validates environment variables programmatically using a defined envictus configuration. The resolution order prioritizes environment-specific defaults, then group defaults, and finally process.env values. It throws an `EnvValidationError` on validation failure, providing structured issue details. Supports explicit mode overrides or implicit resolution from `process.env`. ```typescript import { defineConfig, getEnv } from "envictus"; import { z } from "zod"; const config = defineConfig({ schema: z.object({ APP_ENV: z.enum(["dev", "prod"]).default("dev"), API_KEY: z.string().min(1), TIMEOUT: z.coerce.number().default(5000), }), discriminator: "APP_ENV", defaults: { dev: { API_KEY: "dev-key-123" }, prod: { /* API_KEY required from environment */ }, }, }); // Resolve with explicit mode override const env = await getEnv(config, "prod"); // Returns: { APP_ENV: "prod", API_KEY: string, TIMEOUT: number } // Or use implicit resolution from process.env const envAuto = await getEnv(config); // Mode determined from process.env.APP_ENV or schema default ``` -------------------------------- ### Scaffold New Configuration File (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Initialize a new environment configuration file. You can specify a custom path for the new file, or it will be created in the current directory by default. ```bash # Scaffold a new config file envictus init envictus init ./config/env.config.ts ``` -------------------------------- ### Development and Build Commands Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md A collection of common pnpm commands used for building, testing, linting, and formatting the envictus project. These commands facilitate the development workflow. ```bash pnpm build # Compile TypeScript pnpm dev # Watch mode pnpm test # Run Vitest pnpm lint # Biome linting pnpm lint:fix # Auto-fix lint issues pnpm format # Format with Biome pnpm check-types # Type checking pnpm knip # Dead code detection pnpm check # Full validation (lint, types, build, knip) ``` -------------------------------- ### Project Structure Overview Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md This snippet outlines the directory structure of the envictus project, detailing the purpose of each major directory and key files within the 'src' folder. ```tree src/ ├── __tests__/ # Vitest test files ├── commands/ # CLI command implementations │ ├── check.ts # Validate environment │ ├── init.ts # Scaffold new config │ └── run.ts # Execute command with resolved env ├── bin.ts # CLI entry point ├── cli.ts # Command program setup ├── config.ts # defineConfig() helper ├── env.ts # parseEnv() for .env files ├── index.ts # Public API exports ├── loader.ts # TypeScript config loading (jiti) ├── resolver.ts # Core resolution logic └── types.ts # TypeScript types/interfaces examples/ # Example configs for each schema library dist/ # Compiled output (gitignored) ``` -------------------------------- ### Environment Variable Resolution Pipeline Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md Outlines the step-by-step process envictus follows to resolve environment variables, from loading configuration to final validation and execution. ```text 1. Load config from env.config.ts (TypeScript via jiti) 2. Determine discriminator value (--mode flag → process.env → schema default → "development") 3. Merge: schema defaults → environment-specific defaults → process.env → mode override 4. Validate against Standard Schema 5. Convert to environment variable strings 6. Execute command with merged environment ``` -------------------------------- ### Load .env Defaults with defineConfig - TypeScript Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/03-env-files.md Demonstrates loading default configuration values from different .env files based on the application environment using `defineConfig` and `parseEnv`. It defines a Zod schema for validation and specifies default loading for local, staging, and production environments. ```typescript import { defineConfig, parseEnv } from "envictus"; import { z } from "zod"; export default defineConfig({ schema: z.object({ APP_ENV: z.enum(["local", "staging", "prod"]).default("local"), API_URL: z.string().url(), API_KEY: z.string().min(1), }), discriminator: "APP_ENV", defaults: { local: parseEnv(".env.local"), staging: parseEnv(".env.staging"), prod: parseEnv(".env.prod"), }, }); ``` -------------------------------- ### Handle Missing .env Files with parseEnv - TypeScript Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/03-env-files.md Illustrates how to use the `parseEnv()` function with options to manage missing .env files. The `onMissing` option can be set to 'ignore' to silently skip missing files or 'warn' to log a warning without failing the process, useful for optional local overrides. ```typescript // Ignore missing files (useful for optional local overrides) parseEnv(".env.local", { onMissing: "ignore" }) // Warn but don't fail on missing files parseEnv(".env.local", { onMissing: "warn" }) ``` -------------------------------- ### TypeScript Configuration Settings Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md Details the TypeScript configuration for the envictus project, focusing on module system, target, module resolution, and strictness settings. ```json { "compilerOptions": { "module": "ESNext", "target": "ESNext", "moduleResolution": "NodeNext", "strict": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, "verbatimModuleSyntax": true } } ``` -------------------------------- ### Vitest Testing Patterns Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md Illustrates common patterns employed in Vitest test files within the envictus project. These include isolating environment variable changes and using temporary directories for integration tests. ```typescript // Isolate process.env changes with backup/restore in beforeEach/afterEach // Use mkdtempSync for temp directories in integration tests // Test against actual example configs for real-world validation ``` -------------------------------- ### Run Command with Validated Environment (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Execute a command after validating environment variables against a configuration. The `` placeholder should be replaced with the actual command to run. ```bash # Run a command with validated env envictus -- ``` -------------------------------- ### Run Command with Envictus CLI (Bash) Source: https://context7.com/redsquiggle/envictus/llms.txt The default CLI command resolves environment variables and executes the wrapped command. It validates against the schema and injects resolved variables into the subprocess environment. Options include specifying a config file, skipping validation, and enabling verbose logging. ```bash # Basic usage - run with validated environment envictus -- npm run dev # Specify custom config file envictus --config ./configs/env.config.ts -- npm start # Skip validation (use merged defaults without schema check) envictus --no-validate -- npm run dev # Enable verbose logging for debugging envictus --verbose -- npm run dev # Override environment for specific run NODE_ENV=production envictus -- npm start ``` -------------------------------- ### Compose Root Config with Stripe Group Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript code integrates the standalone Stripe configuration into the main application configuration using the `groups` property. It defines the root application schema and defaults, and then includes the `stripe` config as a nested group, allowing for independent environment management. ```typescript // env.config.ts import { defineConfig } from "envictus"; import { z } from "zod"; import { stripe } from "./stripe.env.config.js"; export default defineConfig({ schema: z.object({ APP_ENV: z.enum(["development", "production"]) .default("development"), PORT: z.coerce.number().min(1).max(65535), DATABASE_URL: z.string().url(), }), discriminator: "APP_ENV", defaults: { development: { PORT: 3000, DATABASE_URL: "postgres://localhost:5432/myapp_dev", }, production: { PORT: 8080 }, }, groups: { stripe }, }); ``` -------------------------------- ### Check Environment Configuration (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Perform a validation check of the environment configuration without executing any command. This is helpful for ensuring your configuration is set up correctly before running your application. ```bash # Validate without running a command envictus check ``` -------------------------------- ### Accessing Envictus Variables in Application Code Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript code shows how to import and use the validated environment variables provided by envictus. The `env` object is typed and ready for use, ensuring that all required variables are present and correctly formatted. ```typescript // app.ts import { env } from "./env.config"; env.PUBLIC_URL; // fully typed, validated, and ready to use ``` -------------------------------- ### Define Configuration with defineConfig (TypeScript) Source: https://context7.com/redsquiggle/envictus/llms.txt Creates an envictus configuration object with full type inference using a provided schema and discriminator. The returned config includes a lazy `.env` property that resolves and caches validated environment variables on first access. It supports defining environment-specific defaults. ```typescript import { defineConfig } from "envictus"; import { z } from "zod"; const config = defineConfig({ schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]).default("development"), DATABASE_URL: z.string().url(), PORT: z.coerce.number().min(1).max(65535), DEBUG: z.coerce.boolean().optional(), LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"), }), discriminator: "NODE_ENV", defaults: { development: { DATABASE_URL: "postgres://localhost:5432/dev", PORT: 3000, DEBUG: true, LOG_LEVEL: "debug", }, production: { DATABASE_URL: "postgres://prod.example.com:5432/prod", PORT: 8080, DEBUG: false, LOG_LEVEL: "warn", }, test: { DATABASE_URL: "postgres://localhost:5432/test", PORT: 3001, DEBUG: false, LOG_LEVEL: "error", }, }, }); export default config; export const env = await config.env; // env.PORT -> number (typed and validated) // env.DATABASE_URL -> string ``` -------------------------------- ### EnvValidationError Handling with Zod Source: https://context7.com/redsquiggle/envictus/llms.txt Demonstrates catching and formatting validation errors using envictus's custom EnvValidationError and the formatValidationIssues helper. It shows how to access structured error details. ```typescript import { defineConfig, getEnv, EnvValidationError, formatValidationIssues } from "envictus"; import { z } from "zod"; const config = defineConfig({ schema: z.object({ PORT: z.coerce.number().min(1).max(65535), DATABASE_URL: z.string().url(), }), discriminator: "NODE_ENV", defaults: {}, }); try { const env = await getEnv(config); } catch (error) { if (error instanceof EnvValidationError) { console.error("Validation failed:"); console.error(formatValidationIssues(error.issues)); // Output: // - PORT: Expected number, received nan // - DATABASE_URL: Invalid url // Access structured issues for (const issue of error.issues) { console.log(`Field: ${issue.path?.join(".")}, Error: ${issue.message}`); } } } ``` -------------------------------- ### Printenv Command with Envictus CLI (Bash) Source: https://context7.com/redsquiggle/envictus/llms.txt Outputs resolved environment variables to stdout in dotenv or JSON format. This is useful for debugging, piping to other tools, or generating `.env` files. The output format can be specified, and the output can be redirected to a file. ```bash # Print as dotenv format (default) envictus printenv # Output: # NODE_ENV=development # DATABASE_URL=postgres://localhost:5432/dev # PORT=3000 # Print as JSON envictus printenv --format json # Output: # { # "NODE_ENV": "development", # "DATABASE_URL": "postgres://localhost:5432/dev", # "PORT": "3000" # } # Generate .env file from resolved config envictus printenv > .env.generated ``` -------------------------------- ### Decrypt SOPS-Encrypted .env Files with parseEnv - TypeScript Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/03-env-files.md Shows how to use `parseEnv()` to decrypt SOPS-encrypted .env files. By specifying the `decrypt` option with the value 'sops', the function can handle encrypted configuration files, ensuring secure loading of sensitive production credentials. ```typescript // Decrypt SOPS-encrypted env files parseEnv(".env.prod.enc", { decrypt: "sops" }) ``` -------------------------------- ### Set Envictus Config Path in package.json Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/01-config-path.md This JSON snippet demonstrates how to define the 'configPath' for Envictus within the 'package.json' file. This setting allows the CLI to automatically locate the configuration file, simplifying its usage. No external dependencies are required for this configuration. ```json { "name": "my-app", "envictus": { "configPath": "./config/env.config.ts" } } ``` -------------------------------- ### Define Standalone Stripe Configuration Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript code defines a separate envictus configuration specifically for Stripe-related environment variables. It includes a schema, discriminator, and defaults for different Stripe environments (development and production), promoting modularity in configuration. ```typescript // stripe.env.config.ts import { defineConfig } from "envictus"; import { z } from "zod"; export const stripe = defineConfig({ schema: z.object({ STRIPE_SECRET_KEY: z.string().min(1), STRIPE_WEBHOOK_SECRET: z.string().min(1), STRIPE_PUBLISHABLE_KEY: z.string().min(1), }), discriminator: "STRIPE_ENV", defaults: { development: { STRIPE_SECRET_KEY: "sk_test_placeholder", STRIPE_WEBHOOK_SECRET: "whsec_test_placeholder", STRIPE_PUBLISHABLE_KEY: "pk_test_placeholder", }, production: { STRIPE_SECRET_KEY: undefined, STRIPE_WEBHOOK_SECRET: undefined, STRIPE_PUBLISHABLE_KEY: undefined, }, }, }); ``` -------------------------------- ### Set Environment Mode with envictus CLI (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/02-setting-mode.md Demonstrates how to set the environment mode for the envictus CLI using bash commands. This includes setting the NODE_ENV variable for development (default) and production environments, either directly in the command or by exporting the variable beforehand. ```bash # Development (default) envictus -- npm run dev # Production NODE_ENV=production envictus -- node dist/server.js # Or export it export NODE_ENV=production envictus -- node dist/server.js ``` -------------------------------- ### Customizing Missing Discriminator Behavior Source: https://context7.com/redsquiggle/envictus/llms.txt Demonstrates the `onMissingDiscriminator` callback in envictus. This allows custom logic for handling cases where the discriminator environment variable is not found, such as enforcing its presence in CI or setting local defaults. ```typescript import { defineConfig } from "envictus"; import { z } from "zod"; export default defineConfig({ schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]), DATABASE_URL: z.string().url(), PORT: z.coerce.number(), }), discriminator: "NODE_ENV", defaults: { development: { PORT: 3000, DATABASE_URL: "postgres://localhost/dev" }, production: { PORT: 8080 }, test: { PORT: 3001, DATABASE_URL: "postgres://localhost/test" }, }, onMissingDiscriminator({ discriminator, availableModes, parent }) { // Require explicit NODE_ENV in CI if (process.env.CI) { throw new Error(`${discriminator} must be set explicitly in CI`); } // When used as a group, cascade to parent mode if (parent?.mode) { return parent.mode as "development" | "production" | "test"; } // Silently default to development locally return availableModes[0] as "development" | "production" | "test"; }, }); ``` -------------------------------- ### Override Group Environment with CLI Flags Source: https://github.com/redsquiggle/envictus/blob/main/README.md These bash commands demonstrate how to override the environment settings for specific groups using environment variables when running the envictus CLI. The first command uses default development settings for the app. The second command sets the app to development mode but forces the Stripe group into production mode, showcasing independent group control. ```bash # Everything uses development defaults APP_ENV=development envictus -- node server.js ``` ```bash # App is development, but Stripe uses production keys APP_ENV=development STRIPE_ENV=production envictus -- node server.js ``` -------------------------------- ### Parse .env Files with parseEnv (TypeScript) Source: https://context7.com/redsquiggle/envictus/llms.txt Parses a specified .env file and returns its contents as an object, facilitating the loading of environment-specific defaults. This function supports parsing SOPS-encrypted files when the `decrypt` option is set to 'sops'. It can handle missing files by ignoring them or throwing an error. ```typescript import { defineConfig, parseEnv } from "envictus"; import { z } from "zod"; export default defineConfig({ schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]).default("development"), API_URL: z.string().url(), API_KEY: z.string().min(1), TIMEOUT_MS: z.coerce.number().positive().default(5000), }), discriminator: "NODE_ENV", defaults: { development: { // Load from .env.local if it exists, otherwise use inline defaults ...parseEnv(".env.local", { onMissing: "ignore" }), API_URL: "https://localhost:3000/api", }, test: { API_URL: "https://localhost:3000/api", API_KEY: "test-key", }, production: { // Decrypt SOPS-encrypted secrets for production ...parseEnv(".env.prod.enc", { decrypt: "sops" }), API_URL: "https://api.example.com", }, }, }); ``` -------------------------------- ### Merge Defaults in TypeScript Source: https://context7.com/redsquiggle/envictus/llms.txt Merges multiple default configuration objects into a single object. This is useful for combining client and server defaults, especially in applications with different environments (local, staging, production). It takes discriminator values and partial defaults from each source. ```typescript import { defineConfig, mergeDefaults } from "envictus"; import { z } from "zod"; // Shared client defaults (browser-safe variables) const clientDefaults = { local: { NEXT_PUBLIC_API_URL: "http://localhost:3000/api" }, staging: { NEXT_PUBLIC_API_URL: "https://staging.api.example.com" }, production: { NEXT_PUBLIC_API_URL: "https://api.example.com" }, }; // Server-only defaults const serverDefaults = { local: { DATABASE_URL: "postgres://localhost:5432/myapp_dev", PORT: 3000, LOG_LEVEL: "debug", }, staging: { PORT: 8080, LOG_LEVEL: "info" }, production: { PORT: 8080, LOG_LEVEL: "warn" }, }; const clientSchema = z.object({ NEXT_PUBLIC_APP_ENV: z.enum(["local", "staging", "production"]).default("local"), NEXT_PUBLIC_API_URL: z.string().url(), }); const serverSchema = z.object({ DATABASE_URL: z.string().url(), PORT: z.coerce.number().min(1).max(65535), LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"), }); export default defineConfig({ schema: clientSchema.merge(serverSchema), discriminator: "NEXT_PUBLIC_APP_ENV", defaults: mergeDefaults(clientDefaults, serverDefaults), }); // Result: Each mode gets combined client + server defaults ``` -------------------------------- ### Print Environment Variables (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/07-printenv.md Outputs resolved environment variables to stdout. Supports default dotenv format and JSON format using the `--format` or `-f` flag. Useful for piping to other tools. ```bash # Print in dotenv format (default) envictus printenv # Print in JSON format envictus printenv --format json envictus printenv -f json # Pipe to wrangler secret bulk envictus printenv | wrangler secret bulk # Pipe to other tools envictus printenv -f json | jq '.DATABASE_URL' ``` -------------------------------- ### Group Sub-Configurations in TypeScript Source: https://context7.com/redsquiggle/envictus/llms.txt Composes independent sub-configurations that resolve with their own discriminator and defaults. When a group's discriminator isn't set, it cascades to the parent's resolved mode. This enables service-specific configurations (e.g., Stripe, AWS) with independent environment control. ```typescript import { defineConfig } from "envictus"; import { z } from "zod"; // Standalone Stripe config const stripe = defineConfig({ schema: z.object({ STRIPE_SECRET_KEY: z.string().min(1), STRIPE_WEBHOOK_SECRET: z.string().min(1), STRIPE_PUBLISHABLE_KEY: z.string().min(1), }), discriminator: "STRIPE_ENV", defaults: { development: { STRIPE_SECRET_KEY: "sk_test_placeholder", STRIPE_WEBHOOK_SECRET: "whsec_test_placeholder", STRIPE_PUBLISHABLE_KEY: "pk_test_placeholder", }, production: { // Force env vars in production (no defaults) STRIPE_SECRET_KEY: undefined, STRIPE_WEBHOOK_SECRET: undefined, STRIPE_PUBLISHABLE_KEY: undefined, }, }, }); // Root config composing Stripe as a group export default defineConfig({ schema: z.object({ APP_ENV: z.enum(["development", "production"]).default("development"), PORT: z.coerce.number().min(1).max(65535), DATABASE_URL: z.string().url(), }), discriminator: "APP_ENV", defaults: { development: { PORT: 3000, DATABASE_URL: "postgres://localhost:5432/myapp_dev", }, production: { PORT: 8080 }, }, groups: { stripe }, }); // Usage: // APP_ENV=development envictus -- node server.js // -> Both app and stripe use development defaults // APP_ENV=development STRIPE_ENV=production envictus -- node server.js // -> App uses development, Stripe uses production (requires real keys) ``` -------------------------------- ### Access Nested Grouped Environment Variables Source: https://github.com/redsquiggle/envictus/blob/main/README.md This TypeScript code shows how to access environment variables from nested groups configured with envictus. The `env` object, obtained after awaiting the config, contains properties for the root variables (e.g., `env.PORT`) and nested group variables (e.g., `env.stripe.STRIPE_SECRET_KEY`), providing namespaced access. ```typescript import config from "./env.config.js"; const env = await config.env; env.PORT; // number (root) env.stripe.STRIPE_SECRET_KEY; // string (namespaced) ``` -------------------------------- ### Skip Validation (Bash) Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/03-cli-usage/index.md Bypass the environment variable validation step and only merge and inject the variables. This is useful for development workflows where validation might be temporarily disabled. The `--no-validate` flag achieves this. ```bash # Skip validation (just merge and inject) envictus --no-validate -- npm run dev ``` -------------------------------- ### Conventional Commits Specification Source: https://github.com/redsquiggle/envictus/blob/main/CLAUDE.md Defines the commit message format used in the envictus project, adhering to conventional commits. It specifies allowed types, subject line rules, and optional body content. ```markdown type: subject in lowercase Optional body **Types**: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert` **Rules**: - Subject must be lowercase (no uppercase letters) - No period at end of subject - Max 100 characters for subject ``` -------------------------------- ### Define Environment Variables with Zod Schema Source: https://github.com/redsquiggle/envictus/blob/main/docs/src/content/docs/04-configuration/01-schema.md Defines environment variables using Zod, a TypeScript-first schema declaration and validation library. It includes types for NODE_ENV, DATABASE_URL, PORT, API_KEY, and DEBUG. ```typescript import { z } from "zod"; schema: z.object({ NODE_ENV: z.enum(["development", "production", "test"]).default("development"), DATABASE_URL: z.string().url(), PORT: z.coerce.number().min(1).max(65535), API_KEY: z.string().min(1), DEBUG: z.coerce.boolean().optional(), }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.