UNPKG

@qalisa/vike-envz

Version:

A type-safe environment variable management system for Vike applications that enables validation and transformation of environment variables using Zod schemas.

73 lines (72 loc) 2.72 kB
// export const dotenvValuesAtKeyName = 'z.serverOnly'; /** * Retrieves an environment variable value from the specified source. * * @param {string} propertyName - The name of the environment variable to retrieve * @param {EnvZSource} source - The source from which to retrieve the value * @returns {string | undefined} The value of the environment variable, or undefined if not found * @private */ const _getPropertyFromSource = (propertyName, from, of) => { switch (from) { case "process": case "importMeta": return of[from][propertyName]; case "all": return (_getPropertyFromSource(propertyName, "importMeta", of) ?? _getPropertyFromSource(propertyName, "process", of)); } }; /** * Retrieves, validates and transforms server-side environment variables based on the provided configuration. * * @template T - Type extending EnvZ (a record of environment variable entries with their validation schemas) * @param {Record<string, any>} importMetaEnv - expects "import.meta.env" here * @param {T} envSchema - Configuration object defining environment variables and their validation schemas * @returns {Object} An object containing all validated and transformed environment variables * @throws {Error} When environment variables fail validation against their schemas * * @example * ```ts * import { getEnvZ } from 'vike-envz'; * import { z } from 'zod'; * * const env = getEnvZ(import.meta.env, { * PORT: [z.string().transform(Number), 'process'], * API_KEY: [z.string().min(1)] * }); * * // env.PORT is now a validated number * // env.API_KEY is a validated non-empty string * ``` */ export const parseEnvZ = (importMetaEnv, envSchema) => { // if (!importMetaEnv[dotenvValuesAtKeyName]) { throw new Error("You probably forgot to use @qalisa/vike-envz/plugin in your vite.config.js. Please refer to documentation."); } // const rawValues = {}; const result = {}; // Retrieve raw values from defined sources for (const key in envSchema) { const [, source = "all"] = envSchema[key]; rawValues[key] = _getPropertyFromSource(key, source, { importMeta: importMetaEnv[dotenvValuesAtKeyName], process: process.env }); } // Validate each value against its corresponding schema for (const key in envSchema) { const [schema] = envSchema[key]; const { success, data, error } = schema.safeParse(rawValues[key]); if (success) { result[key] = data; } else { throw new Error(`Error while checking for "${key}" from env: ${error}`); } } return result; };