@xlameiro/env-typegen 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js","../src/cli.ts","../src/config.ts","../src/pipeline.ts","../src/generators/declaration-generator.ts","../src/generators/t3-generator.ts","../src/generators/typescript-generator.ts","../src/generators/zod-generator.ts","../src/parser/env-parser.ts","../src/inferrer/rules.ts","../src/inferrer/type-inferrer.ts","../src/parser/comment-parser.ts","../src/utils/file.ts","../src/utils/format.ts","../src/utils/logger.ts","../src/watch.ts"],"sourcesContent":["let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n","// CLI entry point — shebang (#!/usr/bin/env node) is injected by tsup banner config.\nimport { createRequire } from \"node:module\";\nimport { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { inspect, parseArgs } from \"node:util\";\n\nimport { loadConfig, type EnvTypegenConfig, type GeneratorName } from \"./config.js\";\nimport { runGenerate, type RunGenerateOptions } from \"./pipeline.js\";\nimport { error } from \"./utils/logger.js\";\nimport { startWatch } from \"./watch.js\";\n\n// Re-export for consumers who import programmatic API via this file\nexport { runGenerate } from \"./pipeline.js\";\nexport type { RunGenerateOptions } from \"./pipeline.js\";\n\nconst _require = createRequire(import.meta.url);\nconst VERSION = (_require(\"../package.json\") as { version: string }).version;\n\nconst HELP_TEXT = [\n \"env-typegen — Generate TypeScript types from .env.example\",\n \"\",\n \"Usage:\",\n \" env-typegen -i <path> [options]\",\n \"\",\n \"Options:\",\n \" -i, --input <path> Path to .env.example file(s). May be specified multiple times.\",\n \" -o, --output <path> Output file path (default: env.generated.ts)\",\n \" -f, --format <name> Generator format: ts|zod|t3|declaration\",\n \" May be specified multiple times.\",\n \" -g, --generator <name> Backward-compatible alias for --format\",\n \" --stdout Print generated output to stdout\",\n \" --dry-run Parse and generate without writing files\",\n \" --no-format Disable prettier formatting\",\n \" -s, --silent Suppress success logs\",\n \" -w, --watch Watch for changes and regenerate\",\n \" -c, --config <path> Path to config file\",\n \" -v, --version Print version\",\n \" -h, --help Show this help\",\n].join(\"\\n\");\n\nconst FORMAT_TO_GENERATOR: Readonly<Record<string, GeneratorName>> = {\n ts: \"typescript\",\n typescript: \"typescript\",\n zod: \"zod\",\n t3: \"t3\",\n declaration: \"declaration\",\n};\n\nfunction normalizeGenerator(input: string): GeneratorName | undefined {\n return FORMAT_TO_GENERATOR[input] ?? FORMAT_TO_GENERATOR[input.toLowerCase()];\n}\n\nfunction getErrorMessage(errorValue: unknown): string {\n if (errorValue instanceof Error) {\n return errorValue.message;\n }\n\n return inspect(errorValue, { depth: 2 });\n}\n\n/** Resolve a config-file path relative to the config file's directory when relative. */\nfunction resolveConfigRelative(value: string | undefined, configDir: string): string | undefined {\n if (value === undefined || path.isAbsolute(value)) return value;\n return path.resolve(configDir, value);\n}\n\n/** Apply resolved (config-dir-relative) input/output paths onto a raw config object. */\nfunction applyConfigPaths(config: EnvTypegenConfig, configDir: string): EnvTypegenConfig {\n let input: string | string[] | undefined;\n if (Array.isArray(config.input)) {\n input = config.input.map((v) => resolveConfigRelative(v, configDir) ?? v);\n } else {\n input = resolveConfigRelative(config.input, configDir);\n }\n const output = resolveConfigRelative(config.output, configDir);\n return {\n ...config,\n ...(input !== undefined && { input }),\n ...(output !== undefined && { output }),\n };\n}\n\n/**\n * Parses command-line arguments and runs the CLI.\n *\n * Exported for unit testing — pass a custom argv array to avoid reading\n * from process.argv.\n */\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: \"string\", short: \"i\", multiple: true },\n output: { type: \"string\", short: \"o\" },\n generator: { type: \"string\", short: \"g\", multiple: true },\n format: { type: \"string\", short: \"f\", multiple: true },\n \"no-format\": { type: \"boolean\" },\n stdout: { type: \"boolean\" },\n \"dry-run\": { type: \"boolean\" },\n silent: { type: \"boolean\", short: \"s\" },\n watch: { type: \"boolean\", short: \"w\" },\n config: { type: \"string\", short: \"c\" },\n version: { type: \"boolean\", short: \"v\" },\n help: { type: \"boolean\", short: \"h\" },\n } as const,\n });\n\n if (values.version === true) {\n console.log(VERSION);\n return;\n }\n\n if (values.help === true) {\n console.log(HELP_TEXT);\n return;\n }\n\n // Load config file — explicit path from --config, or auto-discover in cwd\n let fileConfig: EnvTypegenConfig | undefined;\n if (values.config === undefined) {\n fileConfig = await loadConfig(process.cwd());\n } else {\n const configPath = path.resolve(values.config);\n const configDir = path.dirname(configPath);\n const mod = (await import(pathToFileURL(configPath).href)) as {\n default?: EnvTypegenConfig;\n };\n const rawConfig = mod.default;\n // Resolve input/output paths relative to the config file's directory so that\n // configs in subdirectories (e.g. config/env-typegen.config.mjs) work correctly.\n if (rawConfig) {\n fileConfig = applyConfigPaths(rawConfig, configDir);\n }\n }\n\n // Merge: CLI flags take precedence over config file values\n const cliInput = values.input?.length ? values.input : undefined;\n const input: string | string[] | undefined = cliInput ?? fileConfig?.input;\n if (input === undefined) {\n error(\"No input file specified. Use -i <path> or set input in env-typegen.config.ts\");\n process.exit(1);\n }\n\n const output = values.output ?? fileConfig?.output ?? \"env.generated.ts\";\n\n // Collect and validate generators from --format (spec) and --generator (compat)\n const rawFormats = values.format;\n const rawGenerators = values.generator;\n\n const requested = [...(rawFormats ?? []), ...(rawGenerators ?? [])].map(String);\n let generators: GeneratorName[];\n if (requested.length > 0) {\n const normalizedGenerators = requested\n .map((item) => normalizeGenerator(item))\n .filter((item): item is GeneratorName => item !== undefined);\n\n const invalid = requested.filter((item) => normalizeGenerator(item) === undefined);\n if (invalid.length > 0) {\n error(`Unknown format(s): ${invalid.join(\", \")}. Valid: ts, zod, t3, declaration`);\n process.exit(1);\n }\n\n generators = [...new Set(normalizedGenerators)];\n } else {\n generators =\n fileConfig?.generators ?? ([\"typescript\", \"zod\", \"t3\", \"declaration\"] as GeneratorName[]);\n }\n\n const shouldFormat = values[\"no-format\"] === true ? false : (fileConfig?.format ?? true);\n const useStdout = values.stdout ?? false;\n const isDryRun = values[\"dry-run\"] ?? false;\n const isSilent = values.silent ?? false;\n const shouldWatch = values.watch ?? false;\n\n const options: RunGenerateOptions = {\n input,\n output,\n generators,\n format: shouldFormat,\n stdout: useStdout,\n dryRun: isDryRun,\n silent: isSilent,\n ...(fileConfig?.inferenceRules !== undefined && { inferenceRules: fileConfig.inferenceRules }),\n };\n\n if (shouldWatch) {\n startWatch({ inputPath: input, runOptions: options });\n } else {\n await runGenerate(options);\n }\n}\n\n// Only auto-execute when this file is the CLI entry point, not when imported.\n// realpathSync resolves both sides so the comparison works when invoked via an\n// npm .bin/ symlink (where process.argv[1] is the symlink, not the real file).\nif (\n process.argv[1] !== undefined &&\n (() => {\n try {\n return (\n realpathSync(path.resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url))\n );\n } catch {\n return false;\n }\n })()\n) {\n await runCli().catch((err: unknown) => {\n error(getErrorMessage(err));\n process.exit(1);\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { InferenceRule } from \"./inferrer/rules.js\";\n\nexport type { InferenceRule };\n\n/** Generator identifiers supported by env-typegen. */\nexport type GeneratorName = \"typescript\" | \"zod\" | \"t3\" | \"declaration\";\n\n/** Configuration shape accepted by env-typegen's CLI and programmatic API. */\nexport type EnvTypegenConfig = {\n /** Path(s) to the .env.example file(s) to parse. */\n input: string | string[];\n /** Output directory for generated files. Defaults to the input file's directory. */\n output?: string;\n /** Which generators to run. When omitted, all four generators run. */\n generators?: GeneratorName[];\n /** Format generated output with prettier. Defaults to true. */\n format?: boolean;\n /**\n * Additional inference rules to prepend before the built-in rules.\n * Rules are matched in ascending priority order; lower numbers win.\n */\n inferenceRules?: InferenceRule[];\n};\n\n/** Config file names searched in order when calling loadConfig(). */\nexport const CONFIG_FILE_NAMES = [\n \"env-typegen.config.ts\",\n \"env-typegen.config.mjs\",\n \"env-typegen.config.js\",\n] as const;\n\n/**\n * Type-safe config helper.\n * Returns the config object unchanged — exists purely for IDE autocompletion\n * and compile-time validation of the config shape.\n */\nexport function defineConfig(config: EnvTypegenConfig): EnvTypegenConfig {\n return config;\n}\n\n/**\n * Loads env-typegen config by searching for a config file in `cwd`.\n * Searches for env-typegen.config.ts → .mjs → .js in order.\n * Returns `undefined` when no config file is found.\n */\nexport async function loadConfig(\n cwd: string = process.cwd(),\n): Promise<EnvTypegenConfig | undefined> {\n for (const name of CONFIG_FILE_NAMES) {\n const filePath = path.resolve(cwd, name);\n if (existsSync(filePath)) {\n const fileUrl = pathToFileURL(filePath).href;\n const mod = (await import(fileUrl)) as { default?: EnvTypegenConfig };\n return mod.default;\n }\n }\n return undefined;\n}\n","import path from \"node:path\";\n\nimport { type GeneratorName, type InferenceRule } from \"./config.js\";\nimport { generateDeclaration } from \"./generators/declaration-generator.js\";\nimport { generateT3Env } from \"./generators/t3-generator.js\";\nimport { generateTypeScriptTypes } from \"./generators/typescript-generator.js\";\nimport { generateZodSchema } from \"./generators/zod-generator.js\";\nimport { parseEnvFileContent } from \"./parser/env-parser.js\";\nimport type { ParsedEnvFile } from \"./parser/types.js\";\nimport { readEnvFile, writeOutput } from \"./utils/file.js\";\nimport { formatOutput } from \"./utils/format.js\";\nimport { success } from \"./utils/logger.js\";\n\n/** Options accepted by the runGenerate pipeline. */\nexport type RunGenerateOptions = {\n input: string | string[];\n output: string;\n generators: GeneratorName[];\n format: boolean;\n stdout?: boolean;\n dryRun?: boolean;\n silent?: boolean;\n /** Additional inference rules to prepend before built-in rules. */\n inferenceRules?: InferenceRule[];\n};\n\n/** Derive the output file path for a generator when multiple generators are in use. */\nfunction deriveOutputPath(base: string, generator: GeneratorName, isSingle: boolean): string {\n if (isSingle) return base;\n const ext = path.extname(base);\n const noExt = ext.length > 0 ? base.slice(0, -ext.length) : base;\n // The declaration generator produces ambient TypeScript declarations (.d.ts).\n // Use the correct extension so IDEs and tsc pick it up as a declaration file.\n const baseExt = ext.length > 0 ? ext : \".ts\";\n const outExt = generator === \"declaration\" ? \".d.ts\" : baseExt;\n return `${noExt}.${generator}${outExt}`;\n}\n\n/**\n * When running against multiple input files, derive a per-input output base so\n * each file produces a distinct set of outputs. The input's basename (without\n * extension) is used as the stem; directory and extension come from the\n * user-supplied `output` option.\n */\nfunction deriveOutputBaseForInput(output: string, inputPath: string): string {\n const dir = path.dirname(output);\n const ext = path.extname(output);\n const stem = path.basename(inputPath, path.extname(inputPath));\n return path.join(dir, `${stem}${ext}`);\n}\n\n/** Invoke the correct generator function for the given name. */\nfunction buildOutput(generator: GeneratorName, parsed: ParsedEnvFile): string {\n switch (generator) {\n case \"typescript\":\n return generateTypeScriptTypes(parsed);\n case \"zod\":\n return generateZodSchema(parsed);\n case \"t3\":\n return generateT3Env(parsed);\n case \"declaration\":\n return generateDeclaration(parsed);\n }\n}\n\nasync function persistOutput(params: {\n generated: string;\n generator: GeneratorName;\n outputPath: string;\n isSingle: boolean;\n stdout: boolean;\n dryRun: boolean;\n silent: boolean;\n}): Promise<void> {\n const { generated, generator, outputPath, isSingle, stdout, dryRun, silent } = params;\n\n if (stdout) {\n if (isSingle) {\n console.log(generated);\n } else {\n console.log(`// --- ${generator}:${outputPath} ---`);\n console.log(generated);\n }\n return;\n }\n\n if (dryRun) {\n if (!silent) {\n if (!isSingle) {\n console.log(`// --- ${generator}: ${outputPath} ---`);\n }\n console.log(generated);\n success(`Dry run: would write ${outputPath}`);\n }\n return;\n }\n\n await writeOutput(outputPath, generated);\n if (!silent) {\n success(`Generated ${outputPath}`);\n }\n}\n\n/**\n * Reads the input file(s), runs the requested generators, optionally formats each\n * output, and writes the results to disk.\n *\n * Exported for unit testing — call this directly rather than spawning a child process.\n */\nexport async function runGenerate(options: RunGenerateOptions): Promise<void> {\n const {\n input,\n output,\n generators,\n format: shouldFormat,\n stdout = false,\n dryRun = false,\n silent = false,\n inferenceRules,\n } = options;\n const inputs = Array.isArray(input) ? input : [input];\n const hasMultipleInputs = inputs.length > 1;\n const isSingle = generators.length === 1;\n\n for (const inputPath of inputs) {\n const outputBase = hasMultipleInputs ? deriveOutputBaseForInput(output, inputPath) : output;\n const content = await readEnvFile(inputPath);\n const parsed = parseEnvFileContent(\n content,\n inputPath,\n inferenceRules !== undefined ? { inferenceRules } : undefined,\n );\n\n for (const generator of generators) {\n let generated = buildOutput(generator, parsed);\n if (shouldFormat && !dryRun) {\n generated = await formatOutput(generated);\n }\n const outputPath = deriveOutputPath(outputBase, generator, isSingle);\n await persistOutput({\n generated,\n generator,\n outputPath,\n isSingle,\n stdout,\n dryRun,\n silent,\n });\n }\n }\n}\n","import path from \"node:path\";\n\nimport type { ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Generates an ambient `.d.ts` declaration file from a parsed .env.example.\n *\n * Output is a pure `NodeJS.ProcessEnv` augmentation — no `export type` statements.\n * This makes the file valid as a global ambient declaration that can be dropped\n * into `lib/` or `types/` without affecting module resolution.\n *\n * Output structure:\n * ```\n * // Generated by env-typegen — do not edit manually\n * // Source: .env.example\n *\n * declare namespace NodeJS {\n * interface ProcessEnv {\n * readonly KEY: string; // all vars are runtime strings\n * readonly OPT?: string; // optional vars use ?: string\n * readonly NUM: string; // coerce to number: Number(process.env.NUM)\n * readonly FLAG: string; // coerce to boolean: process.env.FLAG === 'true'\n * }\n * }\n * ```\n *\n * For a `.ts` output with typed `export type EnvVars` / `ServerEnvVars` /\n * `ClientEnvVars`, use `generateTypeScriptTypes` instead.\n *\n * - `ProcessEnv` uses `readonly string` for every variable (runtime reality)\n * - Number and boolean vars include an inline coercion hint comment\n * - `annotatedType` takes precedence over `inferredType`\n */\nexport function generateDeclaration(parsed: ParsedEnvFile): string {\n const fileName = path.basename(parsed.filePath);\n const lines: string[] = [];\n\n // Header\n lines.push(\"// Generated by env-typegen — do not edit manually\");\n lines.push(`// Source: ${fileName}`);\n lines.push(\"\");\n\n // NodeJS.ProcessEnv augmentation — ambient only, no exports\n lines.push(\"declare namespace NodeJS {\");\n lines.push(\" interface ProcessEnv {\");\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const optional = variable.isOptional ? \"?\" : \"\";\n if (variable.description !== undefined) {\n lines.push(` /** ${variable.description} */`);\n }\n let propLine = ` readonly ${variable.key}${optional}: string;`;\n if (effectiveType === \"number\") {\n propLine += ` // coerce to number: Number(process.env.${variable.key})`;\n } else if (effectiveType === \"boolean\") {\n propLine += ` // coerce to boolean: process.env.${variable.key} === 'true'`;\n }\n lines.push(propLine);\n }\n lines.push(\" }\");\n lines.push(\"}\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import type { EnvVarType, ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Maps an EnvVarType to its Zod schema expression for use in t3-env createEnv().\n *\n * Note: boolean uses `z.coerce.boolean()` here (not the `.transform()` approach\n * in the standalone zod-generator) because @t3-oss/env-nextjs handles coercion\n * internally with `z.coerce`.\n */\nfunction toT3ZodType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"z.coerce.number()\";\n if (envVarType === \"boolean\") return \"z.coerce.boolean()\";\n if (envVarType === \"url\") return \"z.string().url()\";\n if (envVarType === \"email\") return \"z.string().email()\";\n return \"z.string()\";\n}\n\n/**\n * Generates a `@t3-oss/env-nextjs` configuration file from a parsed .env.example.\n *\n * Output structure:\n * ```\n * import { createEnv } from \"@t3-oss/env-nextjs\";\n * import { z } from \"zod\";\n *\n * export const env = createEnv({\n * server: { /* non-NEXT_PUBLIC_ vars *\\/ },\n * client: { /* NEXT_PUBLIC_ vars *\\/ },\n * runtimeEnv: { /* all vars mapped to process.env *\\/ },\n * });\n * ```\n *\n * - `server:` is omitted when there are no server-side vars\n * - `client:` is omitted when there are no client-side vars (NEXT_PUBLIC_ prefix)\n * - `runtimeEnv:` always includes all vars\n * - `annotatedType` takes precedence over `inferredType`\n * - Optional vars have `.optional()` appended\n * - Vars with a description have `.describe(\"text\")` appended (before `.optional()`)\n */\nexport function generateT3Env(parsed: ParsedEnvFile): string {\n const serverVars = parsed.vars.filter((v) => !v.isClientSide);\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n const lines: string[] = [];\n\n lines.push(\"// Generated by env-typegen — do not edit manually\");\n lines.push('import { createEnv } from \"@t3-oss/env-nextjs\";');\n lines.push('import { z } from \"zod\";');\n lines.push(\"\");\n lines.push(\"export const env = createEnv({\");\n\n if (serverVars.length > 0) {\n lines.push(\" server: {\");\n for (const variable of serverVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n let zodExpr = toT3ZodType(effectiveType);\n if (variable.description !== undefined) {\n zodExpr += `.describe(\"${variable.description.replace(/\"/g, '\\\\\"')}\")`;\n }\n if (variable.isOptional) {\n zodExpr += \".optional()\";\n }\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n lines.push(\" },\");\n }\n\n if (clientVars.length > 0) {\n lines.push(\" client: {\");\n for (const variable of clientVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n let zodExpr = toT3ZodType(effectiveType);\n if (variable.description !== undefined) {\n zodExpr += `.describe(\"${variable.description.replace(/\"/g, '\\\\\"')}\")`;\n }\n if (variable.isOptional) {\n zodExpr += \".optional()\";\n }\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n lines.push(\" },\");\n }\n\n lines.push(\" runtimeEnv: {\");\n for (const variable of parsed.vars) {\n lines.push(` ${variable.key}: process.env.${variable.key},`);\n }\n lines.push(\" },\");\n lines.push(\"});\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import path from \"node:path\";\n\nimport type { EnvVarType, ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Maps an EnvVarType to its TypeScript primitive equivalent.\n * url, email, semver, json, and unknown all map to `string` because\n * TypeScript has no built-in branded types for these.\n */\nfunction toTsType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"number\";\n if (envVarType === \"boolean\") return \"boolean\";\n return \"string\";\n}\n\n/**\n * Generates a TypeScript source file from a parsed .env.example file.\n *\n * Output structure:\n * 1. Header comments — generated-by notice, source file name, ISO timestamp\n * 2. `declare namespace NodeJS { interface ProcessEnv { ... } }` — global augmentation\n * where all properties are typed as `readonly string` (the runtime reality).\n * Number and boolean vars include an inline coercion hint comment.\n * 3. `export type EnvVars = { ... }` — typed module export using semantic types\n * (number, boolean, string).\n * 4. `ServerEnvVars` / `ClientEnvVars` — emitted only when `NEXT_PUBLIC_` vars exist.\n *\n * The output is valid as both a `.ts` and `.d.ts` file.\n * For an ambient-only `.d.ts` (without `export type` statements), use\n * `generateDeclaration` instead.\n *\n * `annotatedType` takes precedence over `inferredType` when both are set.\n */\nexport function generateTypeScriptTypes(parsed: ParsedEnvFile): string {\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n const hasClientVars = clientVars.length > 0;\n const fileName = path.basename(parsed.filePath);\n const timestamp = new Date().toISOString();\n const lines: string[] = [];\n\n // Header\n lines.push(\"// Generated by env-typegen — do not edit manually\");\n lines.push(`// Source: ${fileName}`);\n lines.push(`// Generated at: ${timestamp}`);\n lines.push(\"\");\n\n // NodeJS.ProcessEnv augmentation — all props are runtime strings with optional coercion hints\n lines.push(\"declare namespace NodeJS {\");\n lines.push(\" interface ProcessEnv {\");\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const optional = variable.isOptional ? \"?\" : \"\";\n if (variable.description !== undefined) {\n lines.push(` /** ${variable.description} */`);\n }\n let propLine = ` readonly ${variable.key}${optional}: string;`;\n if (effectiveType === \"number\") {\n propLine += ` // coerce to number: Number(process.env.${variable.key})`;\n } else if (effectiveType === \"boolean\") {\n propLine += ` // coerce to boolean: process.env.${variable.key} === 'true'`;\n }\n lines.push(propLine);\n }\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n // EnvVars type with semantic TypeScript types\n lines.push(\"export type EnvVars = {\");\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const tsType = toTsType(effectiveType);\n const optional = variable.isOptional ? \"?\" : \"\";\n lines.push(` ${variable.key}${optional}: ${tsType};`);\n }\n lines.push(\"};\");\n\n // ServerEnvVars / ClientEnvVars — only emitted when NEXT_PUBLIC_ vars exist\n if (hasClientVars) {\n const clientKeyUnion = clientVars.map((v) => `\"${v.key}\"`).join(\" | \");\n lines.push(\"\");\n lines.push(`export type ServerEnvVars = Omit<EnvVars, ${clientKeyUnion}>;`);\n lines.push(`export type ClientEnvVars = Pick<EnvVars, ${clientKeyUnion}>;`);\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\n/**\n * Generates a runtime `validateEnv()` function that throws when any required\n * environment variable is absent from `process.env`.\n */\nexport function generateEnvValidation(parsed: ParsedEnvFile): string {\n const required = parsed.vars.filter((v) => v.isRequired).map((v) => v.key);\n const lines: string[] = [];\n\n lines.push(\"// Generated by env-typegen — do not edit manually\");\n lines.push(\"\");\n lines.push(\"export function validateEnv(): void {\");\n\n if (required.length === 0) {\n lines.push(\" // No required environment variables defined\");\n } else {\n const keyList = required.map((k) => `\"${k}\"`).join(\", \");\n lines.push(` const required = [${keyList}];`);\n lines.push(\" for (const key of required) {\");\n lines.push(\" if (!process.env[key]) {\");\n lines.push(\" throw new Error(`Missing required environment variable: ${key}`);\");\n lines.push(\" }\");\n lines.push(\" }\");\n }\n\n lines.push(\"}\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import type { EnvVarType, ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Maps an EnvVarType to its Zod schema expression.\n *\n * - `number` → `z.coerce.number()` (env vars are strings; coerce handles the cast)\n * - `boolean` → `z.coerce.boolean()` (env vars are strings; coerce handles truthy cast)\n * - `url` → `z.string().url()`\n * - `email` → `z.string().email()`\n * - everything else → `z.string()` (string | semver | json | unknown)\n */\nfunction toZodType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"z.coerce.number()\";\n if (envVarType === \"boolean\") return \"z.coerce.boolean()\";\n if (envVarType === \"url\") return \"z.string().url()\";\n if (envVarType === \"email\") return \"z.string().email()\";\n return \"z.string()\";\n}\n\n/**\n * Generates a Zod schema file from a parsed .env.example file.\n *\n * Output structure:\n * ```\n * // Generated by env-typegen — do not edit manually\n * import { z } from \"zod\";\n *\n * export const serverEnvSchema = z.object({\n * DATABASE_URL: z.string().url(),\n * PORT: z.coerce.number(),\n * });\n *\n * export const clientEnvSchema = z.object({\n * NEXT_PUBLIC_API_URL: z.string().url(),\n * });\n *\n * export const envSchema = serverEnvSchema.merge(clientEnvSchema);\n * export type Env = z.infer<typeof envSchema>;\n * ```\n *\n * - Server-side vars (non-`NEXT_PUBLIC_`) go into `serverEnvSchema`\n * - Client-side vars (`NEXT_PUBLIC_` prefix) go into `clientEnvSchema`\n * - `envSchema` is the merged union of both, for full-stack validation\n * - `annotatedType` takes precedence over `inferredType` when both are set\n * - Optional vars have `.optional()` appended to their Zod expression\n */\nexport function generateZodSchema(parsed: ParsedEnvFile): string {\n const serverVars = parsed.vars.filter((v) => !v.isClientSide);\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n const lines: string[] = [];\n\n lines.push(\"// Generated by env-typegen — do not edit manually\");\n lines.push('import { z } from \"zod\";');\n lines.push(\"\");\n\n // serverEnvSchema — non-NEXT_PUBLIC_ vars\n lines.push(\"export const serverEnvSchema = z.object({\");\n for (const variable of serverVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const zodExpr = variable.isOptional\n ? `${toZodType(effectiveType)}.optional()`\n : toZodType(effectiveType);\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n lines.push(\"});\");\n lines.push(\"\");\n\n // clientEnvSchema — NEXT_PUBLIC_ vars\n lines.push(\"export const clientEnvSchema = z.object({\");\n for (const variable of clientVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const zodExpr = variable.isOptional\n ? `${toZodType(effectiveType)}.optional()`\n : toZodType(effectiveType);\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n lines.push(\"});\");\n lines.push(\"\");\n\n // Merged schema — the full validation object for use in lib/env.ts\n lines.push(\"export const envSchema = serverEnvSchema.merge(clientEnvSchema);\");\n lines.push(\"export type Env = z.infer<typeof envSchema>;\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import { readFileSync } from \"node:fs\";\n\nimport type { InferenceRule } from \"../inferrer/rules.js\";\nimport { inferType } from \"../inferrer/type-inferrer.js\";\nimport { parseCommentBlock } from \"./comment-parser.js\";\nimport type { ParsedEnvFile, ParsedEnvVar } from \"./types.js\";\n\nexport { inferType } from \"../inferrer/type-inferrer.js\";\n\n/** Options forwarded to the type-inference step during parsing. */\ntype ParseOptions = {\n /** Additional inference rules to evaluate before the built-in rules. */\n inferenceRules?: InferenceRule[];\n};\n\n/** Matches a valid env var declaration: KEY=VALUE (value may be empty) */\nconst ENV_VAR_RE = /^([A-Z_][A-Z0-9_]*)=(.*)$/;\n\n/**\n * Matches a section header comment of the form:\n * `# --- SectionName ---` or `# === SectionName ===`\n */\nconst SECTION_HEADER_RE = /^#\\s+[-=]{3,}\\s+(.+?)\\s+[-=]{3,}\\s*$/;\n\n/**\n * Parse the string content of a `.env.example` file into a `ParsedEnvFile`.\n *\n * Exposed separately from `parseEnvFile` to enable unit testing without\n * filesystem access.\n *\n * @param content - Raw file content as a UTF-8 string\n * @param filePath - Used to populate `ParsedEnvFile.filePath` only\n * @param options - Optional parse configuration (custom inference rules)\n */\nexport function parseEnvFileContent(\n content: string,\n filePath: string,\n options?: ParseOptions,\n): ParsedEnvFile {\n const lines = content.split(\"\\n\");\n const vars: ParsedEnvVar[] = [];\n const groups: string[] = [];\n\n let currentGroup: string | undefined;\n let commentBlock: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n const lineNumber = i + 1;\n const trimmed = line.trim();\n\n // Blank line — break the comment block association\n if (trimmed === \"\") {\n commentBlock = [];\n continue;\n }\n\n // Section header — update current group and reset comment block\n const sectionMatch = SECTION_HEADER_RE.exec(trimmed);\n if (sectionMatch !== null) {\n const groupName = (sectionMatch[1] ?? \"\").trim();\n currentGroup = groupName;\n if (!groups.includes(groupName)) {\n groups.push(groupName);\n }\n commentBlock = [];\n continue;\n }\n\n // Comment line — accumulate for the next env var\n if (trimmed.startsWith(\"#\")) {\n commentBlock.push(line);\n continue;\n }\n\n // Env var declaration\n const envMatch = ENV_VAR_RE.exec(trimmed);\n if (envMatch !== null) {\n const key = envMatch[1] ?? \"\";\n const rawValue = envMatch[2] ?? \"\";\n const annotations = parseCommentBlock(commentBlock);\n const inferredType = inferType(\n key,\n rawValue,\n ...(options?.inferenceRules !== undefined ? [{ extraRules: options.inferenceRules }] : []),\n );\n const isRequired = rawValue.length > 0 || annotations.isRequired;\n const isOptional = rawValue.length === 0 && !annotations.isRequired;\n const isClientSide = key.startsWith(\"NEXT_PUBLIC_\");\n\n const parsedVar: ParsedEnvVar = {\n key,\n rawValue,\n inferredType,\n isRequired,\n isOptional,\n isClientSide,\n lineNumber,\n };\n\n // Only set optional fields when they have a value (exactOptionalPropertyTypes)\n if (annotations.annotatedType !== undefined) {\n parsedVar.annotatedType = annotations.annotatedType;\n }\n if (annotations.description !== undefined) {\n parsedVar.description = annotations.description;\n }\n if (currentGroup !== undefined) {\n parsedVar.group = currentGroup;\n }\n\n vars.push(parsedVar);\n commentBlock = [];\n } else {\n // Unrecognised line — reset comment block\n commentBlock = [];\n }\n }\n\n return { filePath, vars, groups };\n}\n\n/**\n * Read and parse a `.env.example` file from disk.\n *\n * @param filePath - Absolute or relative path to the file\n */\nexport function parseEnvFile(filePath: string): ParsedEnvFile {\n const content = readFileSync(filePath, \"utf8\");\n return parseEnvFileContent(content, filePath);\n}\n","import type { EnvVarType } from \"../parser/types.js\";\n\nexport type InferenceRule = {\n id: string;\n priority: number;\n match: (key: string, value: string) => boolean;\n type: EnvVarType;\n};\n\nexport const inferenceRules: readonly InferenceRule[] = [\n {\n id: \"P2_key_url_suffix\",\n priority: 2,\n match: (key: string) => key.toUpperCase().endsWith(\"_URL\"),\n type: \"url\",\n },\n {\n id: \"P3_key_email_from_suffix\",\n priority: 3,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return normalizedKey.endsWith(\"_EMAIL\") || normalizedKey.endsWith(\"_FROM\");\n },\n type: \"email\",\n },\n {\n id: \"P4_boolean_prefix\",\n priority: 4,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return (\n normalizedKey.startsWith(\"ENABLE_\") ||\n normalizedKey.startsWith(\"DISABLE_\") ||\n normalizedKey.startsWith(\"IS_\") ||\n normalizedKey.startsWith(\"DEBUG\") ||\n normalizedKey.startsWith(\"FEATURE_\")\n );\n },\n type: \"boolean\",\n },\n {\n id: \"P5_key_port\",\n priority: 5,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return normalizedKey.endsWith(\"_PORT\") || normalizedKey === \"PORT\";\n },\n type: \"number\",\n },\n {\n id: \"P6_empty_unknown\",\n priority: 6,\n match: (_key: string, value: string) => value.length === 0,\n type: \"unknown\",\n },\n {\n id: \"P7_boolean_literal\",\n priority: 7,\n match: (_key: string, value: string) => {\n const lower = value.toLowerCase();\n return lower === \"true\" || lower === \"false\";\n },\n type: \"boolean\",\n },\n {\n id: \"P8_numeric_literal\",\n priority: 8,\n match: (_key: string, value: string) => /^\\d+(\\.\\d+)?$/.test(value),\n type: \"number\",\n },\n {\n id: \"P9_semver\",\n priority: 9,\n match: (_key: string, value: string) => /^\\d+\\.\\d+\\.\\d+/.test(value),\n type: \"semver\",\n },\n {\n id: \"P10_url_scheme\",\n priority: 10,\n match: (_key: string, value: string) => /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value),\n type: \"url\",\n },\n {\n id: \"P11_email_literal\",\n priority: 11,\n match: (_key: string, value: string) => /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(value),\n type: \"email\",\n },\n {\n id: \"P12_json_object_array\",\n priority: 12,\n match: (_key: string, value: string) => {\n try {\n const parsed: unknown = JSON.parse(value);\n return typeof parsed === \"object\" && parsed !== null;\n } catch {\n return false;\n }\n },\n type: \"json\",\n },\n] as const;\n","import type { EnvVarType } from \"../parser/types.js\";\nimport type { InferenceRule } from \"./rules.js\";\nimport { inferenceRules } from \"./rules.js\";\n\ntype InferTypeOptions = {\n fallbackType?: EnvVarType;\n /**\n * Additional rules to check before the built-in rules.\n * Within extraRules, lower priority number = higher precedence.\n */\n extraRules?: InferenceRule[];\n};\n\nconst sortedRules = [...inferenceRules].sort((left, right) => left.priority - right.priority);\n\nexport function inferType(key: string, value: string, options?: InferTypeOptions): EnvVarType {\n const extra = options?.extraRules;\n const rules =\n extra && extra.length > 0\n ? [...extra].sort((a, b) => a.priority - b.priority).concat(sortedRules)\n : sortedRules;\n\n for (const rule of rules) {\n if (rule.match(key, value)) {\n return rule.type;\n }\n }\n\n return options?.fallbackType ?? \"string\";\n}\n\nexport function inferTypesFromParsedVars(\n parsed: { vars: Array<{ key: string; rawValue: string }> },\n options?: InferTypeOptions,\n): EnvVarType[] {\n return parsed.vars.map((item) => inferType(item.key, item.rawValue, options));\n}\n","import type { EnvVarType } from \"./types.js\";\n\n/**\n * Structured annotations extracted from a JSDoc-style comment block\n * that precedes an env var declaration.\n *\n * @example\n * ```\n * # @description PostgreSQL connection string\n * # @required\n * # @type string\n * DATABASE_URL=\n * ```\n */\nexport type CommentAnnotations = {\n /** Type explicitly declared with `@type` in the comment block */\n annotatedType?: EnvVarType;\n\n /** Description from `@description` or the first free-form comment line */\n description?: string;\n\n /** true when the `@required` annotation is present in the comment block */\n isRequired: boolean;\n};\n\nconst VALID_ENV_VAR_TYPES = new Set<string>([\n \"string\",\n \"number\",\n \"boolean\",\n \"url\",\n \"email\",\n \"semver\",\n \"json\",\n \"unknown\",\n]);\n\nfunction isEnvVarType(value: string): value is EnvVarType {\n return VALID_ENV_VAR_TYPES.has(value);\n}\n\n/**\n * Parse a block of consecutive comment lines (each starting with `#`) and\n * extract JSDoc-style annotations.\n *\n * Recognised annotations:\n * - `@description <text>` — sets the variable description\n * - `@required` — marks the variable as required regardless of value\n * - `@optional` — informational (isRequired stays false)\n * - `@type <EnvVarType>` — overrides the inferred type\n *\n * Non-annotation comment lines act as a fallback description when no\n * `@description` annotation is present (first non-empty line wins).\n *\n * @param lines - Raw comment lines from the .env file, e.g. `[\"# @required\"]`\n */\nexport function parseCommentBlock(lines: readonly string[]): CommentAnnotations {\n let annotatedType: EnvVarType | undefined;\n let description: string | undefined;\n let isRequired = false;\n\n for (const line of lines) {\n // Strip the leading `#` and any trailing whitespace\n const content = line.replace(/^#\\s*/, \"\").trimEnd();\n\n if (content.startsWith(\"@description \")) {\n description = content.slice(\"@description \".length).trim();\n } else if (content.startsWith(\"@type \")) {\n const typeStr = content.slice(\"@type \".length).trim();\n if (isEnvVarType(typeStr)) {\n annotatedType = typeStr;\n }\n } else if (content.trim() === \"@required\") {\n isRequired = true;\n } else if (content.trim() === \"@optional\") {\n // Informational only — isRequired stays false (which is already the default)\n } else if (description === undefined && content.trim().length > 0) {\n // First non-empty, non-annotation line is a fallback description\n description = content.trim();\n }\n }\n\n const result: CommentAnnotations = { isRequired };\n if (annotatedType !== undefined) result.annotatedType = annotatedType;\n if (description !== undefined) result.description = description;\n return result;\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Reads a .env file from `filePath` and returns its full text content.\n * Rejects with a Node.js filesystem error if the file does not exist.\n */\nexport async function readEnvFile(filePath: string): Promise<string> {\n return readFile(path.resolve(filePath), \"utf8\");\n}\n\n/**\n * Writes `content` to `filePath`, creating intermediate directories as needed.\n * Overwrites any existing file at that path.\n */\nexport async function writeOutput(filePath: string, content: string): Promise<void> {\n const resolved = path.resolve(filePath);\n await mkdir(path.dirname(resolved), { recursive: true });\n await writeFile(resolved, content, \"utf8\");\n}\n","import { format } from \"prettier\";\n\n/**\n * Formats `content` using prettier with the specified `parser`.\n * Defaults to the \"typescript\" parser, which is correct for all generator outputs.\n * Returns the original content unchanged if prettier throws (e.g., invalid syntax).\n */\nexport async function formatOutput(\n content: string,\n parser: string = \"typescript\",\n): Promise<string> {\n try {\n return await format(content, { parser });\n } catch (err) {\n console.warn(\n \"env-typegen: Prettier formatting failed, writing unformatted output.\",\n err instanceof Error ? err.message : String(err),\n );\n return content;\n }\n}\n","import { green, red, yellow } from \"picocolors\";\n\n/** Prints a plain informational message to stdout. */\nexport function log(message: string): void {\n console.log(message);\n}\n\n/** Prints a yellow ⚠ warning message to stderr. */\nexport function warn(message: string): void {\n console.warn(yellow(`⚠ ${message}`));\n}\n\n/** Prints a red ✖ error message to stderr. */\nexport function error(message: string): void {\n console.error(red(`✖ ${message}`));\n}\n\n/** Prints a green ✔ success message to stdout. */\nexport function success(message: string): void {\n console.log(green(`✔ ${message}`));\n}\n","import path from \"node:path\";\nimport { watch } from \"chokidar\";\n\nimport { loadConfig, CONFIG_FILE_NAMES } from \"./config.js\";\nimport type { RunGenerateOptions } from \"./pipeline.js\";\nimport { runGenerate } from \"./pipeline.js\";\nimport { error, log } from \"./utils/logger.js\";\n\ntype WatchOptions = {\n inputPath: string | string[];\n runOptions: RunGenerateOptions;\n /** CWD used to locate the config file; defaults to process.cwd(). */\n cwd?: string;\n};\n\n/** Debounced wrapper: the inner function is called at most once per `delay` ms. */\nfunction debounce<TArgs extends unknown[]>(\n fn: (...args: TArgs) => void,\n delay: number,\n): (...args: TArgs) => void {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return (...args: TArgs) => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n fn(...args);\n }, delay);\n };\n}\n\nexport function startWatch({ inputPath, runOptions, cwd = process.cwd() }: WatchOptions): void {\n const inputLabel = Array.isArray(inputPath) ? inputPath.join(\", \") : inputPath;\n log(`Watching ${inputLabel} for changes...`);\n\n // Run once immediately on start\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n\n const handleChange = debounce((eventPath: string) => {\n log(`${eventPath} changed, regenerating...`);\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n }, 200);\n\n const handleConfigChange = debounce(async (eventPath: string) => {\n log(`Config file ${eventPath} changed, reloading...`);\n try {\n const reloaded = await loadConfig(cwd);\n if (reloaded) {\n // Apply updated generators/format/inferenceRules settings from the new config\n runOptions.generators = reloaded.generators ?? runOptions.generators;\n runOptions.format = reloaded.format ?? runOptions.format;\n if (reloaded.inferenceRules !== undefined) {\n runOptions.inferenceRules = reloaded.inferenceRules;\n }\n }\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(`Failed to reload config: ${message}`);\n }\n }, 200);\n\n // Watch the input file — fire on create, modify, or delete+recreate\n const inputWatcher = watch(inputPath, { persistent: true });\n for (const event of [\"add\", \"change\", \"unlink\"] as const) {\n inputWatcher.on(event, handleChange);\n }\n\n // Watch config files so changes take effect without restarting\n const configPaths = CONFIG_FILE_NAMES.map((name) => path.resolve(cwd, name));\n const configWatcher = watch(configPaths, { persistent: true, ignoreInitial: true });\n for (const event of [\"add\", \"change\"] as const) {\n configWatcher.on(event, (eventPath: string) => void handleConfigChange(eventPath));\n }\n\n process.on(\"SIGINT\", () => {\n void Promise.all([inputWatcher.close(), configWatcher.close()]).then(() => {\n log(\"Watcher stopped.\");\n process.exit(0);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAI,IAAI,WAAW,CAAC;AAApB,QAAuB,OAAO,EAAE,QAAQ,CAAC;AAAzC,QAA4C,MAAM,EAAE,OAA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AS,mBAAmB,IAAI,MAAM,MAAS;AACjF,QAAI,QAAQ,SAAS,GAAG;AACtB,YAAM,sBAAsB,QAAQ,KAAK,IAAI,CAAC,mCAAmC;AACjF,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,iBAAa,CAAC,GAAG,IAAI,IAAI,oBAAoB,CAAC;AAAA,EAChD,OAAO;AACL,iBACE,YAAY,cAAe,CAAC,cAAc,OAAO,MAAM,aAAa;AAAA,EACxE;AAEA,QAAM,eAAe,OAAO,WAAW,MAAM,OAAO,QAAS,YAAY,UAAU;AACnF,QAAM,YAAY,OAAO,UAAU;AACnC,QAAM,WAAW,OAAO,SAAS,KAAK;AACtC,QAAM,WAAW,OAAO,UAAU;AAClC,QAAM,cAAc,OAAO,SAAS;AAEpC,QAAM,UAA8B;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,GAAI,YAAY,mBAAmB,UAAa,EAAE,gBAAgB,WAAW,eAAe;AAAA,EAC9F;AAEA,MAAI,aAAa;AACf,eAAW,EAAE,WAAW,OAAO,YAAY,QAAQ,CAAC;AAAA,EACtD,OAAO;AACL,UAAM,YAAY,OAAO;AAAA,EAC3B;AACF;AAKA,IACE,QAAQ,KAAK,CAAC,MAAM,WACnB,MAAM;AACL,MAAI;AACF,WACE,aAAaD,MAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAE/F,QAAQ;AACN,WAAO;AAAA,EACT;AACF,GAAG,GACH;AACA,QAAM,OAAO,EAAE,MAAM,CAAC,QAAiB;AACrC,UAAM,gBAAgB,GAAG,CAAC;AAC1B,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["path","pathToFileURL","path","path","path","path","path","inferenceRules","path","path","path","pathToFileURL"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js","../src/cli.ts","../src/config.ts","../src/pipeline.ts","../src/generators/declaration-generator.ts","../src/generators/t3-generator.ts","../src/generators/typescript-generator.ts","../src/generators/zod-generator.ts","../src/parser/env-parser.ts","../src/inferrer/rules.ts","../src/inferrer/type-inferrer.ts","../src/parser/comment-parser.ts","../src/utils/file.ts","../src/utils/format.ts","../src/utils/logger.ts","../src/validation-command.ts","../src/cloud/connectors.ts","../src/contract.ts","../src/plugins.ts","../src/validation/engine.ts","../src/validation/env-source.ts","../src/validation/output.ts","../src/watch.ts"],"sourcesContent":["let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n","// CLI entry point — shebang (#!/usr/bin/env node) is injected by tsup banner config.\nimport { realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { inspect, parseArgs } from \"node:util\";\n\nimport { loadConfig, type EnvTypegenConfig, type GeneratorName } from \"./config.js\";\nimport { runGenerate, type RunGenerateOptions } from \"./pipeline.js\";\nimport { error } from \"./utils/logger.js\";\nimport { runValidationCommand } from \"./validation-command.js\";\nimport { startWatch } from \"./watch.js\";\n\n// Re-export for consumers who import programmatic API via this file\nexport { runGenerate } from \"./pipeline.js\";\nexport type { RunGenerateOptions } from \"./pipeline.js\";\n\nconst _require = createRequire(import.meta.url);\nconst VERSION = (_require(\"../package.json\") as { version: string }).version;\n\nconst HELP_TEXT = [\n \"env-typegen — Generate TypeScript types from .env.example\",\n \"\",\n \"Usage:\",\n \" env-typegen [generate] -i <path> [options]\",\n \" env-typegen check [options]\",\n \" env-typegen diff [options]\",\n \" env-typegen doctor [options]\",\n \"\",\n \"Options:\",\n \" -i, --input <path> Path to .env.example file(s). May be specified multiple times.\",\n \" -o, --output <path> Output base path (default: env.generated.ts).\",\n \" With multiple generators, suffixes are appended:\",\n \" env.generated.typescript.ts, .zod.ts, .t3.ts, .declaration.d.ts\",\n \" -f, --format <name> Generator format: ts|zod|t3|declaration\",\n \" May be specified multiple times.\",\n \" -g, --generator <name> Backward-compatible alias for --format\",\n \" --stdout Print generated output to stdout\",\n \" --dry-run Parse and generate without writing files\",\n \" --no-format Disable prettier formatting\",\n \" -s, --silent Suppress success logs\",\n \" -w, --watch Watch for changes and regenerate\",\n \" -c, --config <path> Path to config file\",\n \" -v, --version Print version\",\n \" -h, --help Show this help\",\n \"\",\n \"Config file:\",\n \" Auto-discovered in order: env-typegen.config.mjs → .js → .ts (in cwd)\",\n \" CLI flags always override config file values.\",\n \" Use defineConfig() from @xlameiro/env-typegen for IDE autocompletion.\",\n \"\",\n \"Exit codes:\",\n \" 0 Success — files generated without errors\",\n \" 1 Error — invalid flags or generation failed\",\n].join(\"\\n\");\n\nconst VALIDATION_SUBCOMMANDS = new Set([\"check\", \"diff\", \"doctor\"]);\n\nconst FORMAT_TO_GENERATOR: Readonly<Record<string, GeneratorName>> = {\n ts: \"typescript\",\n typescript: \"typescript\",\n zod: \"zod\",\n t3: \"t3\",\n declaration: \"declaration\",\n};\n\nfunction normalizeGenerator(input: string): GeneratorName | undefined {\n return FORMAT_TO_GENERATOR[input] ?? FORMAT_TO_GENERATOR[input.toLowerCase()];\n}\n\nfunction resolveGenerators(\n rawFormats: readonly string[] | undefined,\n rawGenerators: readonly string[] | undefined,\n fallback: GeneratorName[] | undefined,\n): GeneratorName[] {\n const requested = [...(rawFormats ?? []), ...(rawGenerators ?? [])].map(String);\n if (requested.length === 0) {\n return fallback ?? ([\"typescript\", \"zod\", \"t3\", \"declaration\"] as GeneratorName[]);\n }\n\n const normalizedGenerators = requested\n .map((item) => normalizeGenerator(item))\n .filter((item): item is GeneratorName => item !== undefined);\n\n const invalid = requested.filter((item) => normalizeGenerator(item) === undefined);\n if (invalid.length > 0) {\n error(`Unknown format(s): ${invalid.join(\", \")}. Valid: ts, zod, t3, declaration`);\n process.exit(1);\n }\n\n return [...new Set(normalizedGenerators)];\n}\n\nfunction getErrorMessage(errorValue: unknown): string {\n if (errorValue instanceof Error) {\n return errorValue.message;\n }\n\n return inspect(errorValue, { depth: 2 });\n}\n\n/** Resolve a config-file path relative to the config file's directory when relative. */\nfunction resolveConfigRelative(value: string | undefined, configDir: string): string | undefined {\n if (value === undefined || path.isAbsolute(value)) return value;\n return path.resolve(configDir, value);\n}\n\n/** Apply resolved (config-dir-relative) input/output paths onto a raw config object. */\nfunction applyConfigPaths(config: EnvTypegenConfig, configDir: string): EnvTypegenConfig {\n let input: string | string[] | undefined;\n if (Array.isArray(config.input)) {\n input = config.input.map((v) => resolveConfigRelative(v, configDir) ?? v);\n } else {\n input = resolveConfigRelative(config.input, configDir);\n }\n const output = resolveConfigRelative(config.output, configDir);\n return {\n ...config,\n ...(input !== undefined && { input }),\n ...(output !== undefined && { output }),\n };\n}\n\ntype ValidationSubcommand = \"check\" | \"diff\" | \"doctor\";\n\nasync function runValidationSubcommand(\n subcommand: ValidationSubcommand,\n argv: string[],\n): Promise<void> {\n const exitCode = await runValidationCommand({ command: subcommand, argv });\n if (exitCode !== 0) {\n process.exitCode = exitCode;\n }\n}\n\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const maybeSubcommand = argv[0];\n if (maybeSubcommand !== undefined && VALIDATION_SUBCOMMANDS.has(maybeSubcommand)) {\n await runValidationSubcommand(maybeSubcommand as ValidationSubcommand, argv.slice(1));\n return;\n }\n\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: \"string\", short: \"i\", multiple: true },\n output: { type: \"string\", short: \"o\" },\n generator: { type: \"string\", short: \"g\", multiple: true },\n format: { type: \"string\", short: \"f\", multiple: true },\n \"no-format\": { type: \"boolean\" },\n stdout: { type: \"boolean\" },\n \"dry-run\": { type: \"boolean\" },\n silent: { type: \"boolean\", short: \"s\" },\n watch: { type: \"boolean\", short: \"w\" },\n config: { type: \"string\", short: \"c\" },\n version: { type: \"boolean\", short: \"v\" },\n help: { type: \"boolean\", short: \"h\" },\n } as const,\n });\n\n if (values.version === true) {\n console.log(VERSION);\n return;\n }\n\n if (values.help === true) {\n console.log(HELP_TEXT);\n return;\n }\n\n // Load config file — explicit path from --config, or auto-discover in cwd\n let fileConfig: EnvTypegenConfig | undefined;\n if (values.config === undefined) {\n fileConfig = await loadConfig(process.cwd());\n } else {\n const configPath = path.resolve(values.config);\n const configDir = path.dirname(configPath);\n const mod = (await import(pathToFileURL(configPath).href)) as {\n default?: EnvTypegenConfig;\n };\n const rawConfig = mod.default;\n // Resolve input/output paths relative to the config file's directory so that\n // configs in subdirectories (e.g. config/env-typegen.config.mjs) work correctly.\n if (rawConfig) {\n fileConfig = applyConfigPaths(rawConfig, configDir);\n }\n }\n\n // Merge: CLI flags take precedence over config file values\n const cliInput = values.input?.length ? values.input : undefined;\n const input: string | string[] | undefined = cliInput ?? fileConfig?.input;\n if (input === undefined) {\n error(\"No input file specified. Use -i <path> or set input in env-typegen.config.ts\");\n process.exit(1);\n }\n\n const output = values.output ?? fileConfig?.output ?? \"env.generated.ts\";\n\n // Collect and validate generators from --format (spec) and --generator (compat)\n const generators = resolveGenerators(values.format, values.generator, fileConfig?.generators);\n\n const shouldFormat = values[\"no-format\"] === true ? false : (fileConfig?.format ?? true);\n const useStdout = values.stdout ?? false;\n const isDryRun = values[\"dry-run\"] ?? false;\n const isSilent = values.silent ?? false;\n const shouldWatch = values.watch ?? false;\n\n const options: RunGenerateOptions = {\n input,\n output,\n generators,\n format: shouldFormat,\n stdout: useStdout,\n dryRun: isDryRun,\n silent: isSilent,\n ...(fileConfig?.inferenceRules !== undefined && { inferenceRules: fileConfig.inferenceRules }),\n };\n\n if (shouldWatch) {\n startWatch({ inputPath: input, runOptions: options });\n } else {\n await runGenerate(options);\n }\n}\n\n// Only auto-execute when this file is the CLI entry point, not when imported.\n// realpathSync resolves both sides so the comparison works when invoked via an\n// npm .bin/ symlink (where process.argv[1] is the symlink, not the real file).\nif (\n process.argv[1] !== undefined &&\n (() => {\n try {\n return (\n realpathSync(path.resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url))\n );\n } catch {\n return false;\n }\n })()\n) {\n await runCli().catch((err: unknown) => {\n error(getErrorMessage(err));\n process.exit(1);\n });\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { InferenceRule } from \"./inferrer/rules.js\";\nimport type { PluginReference } from \"./plugins.js\";\n\nexport type { InferenceRule } from \"./inferrer/rules.js\";\nexport type { PluginReference } from \"./plugins.js\";\n\n/** Generator identifiers supported by env-typegen. */\nexport type GeneratorName = \"typescript\" | \"zod\" | \"t3\" | \"declaration\";\n\n/** Configuration shape accepted by env-typegen's CLI and programmatic API. */\nexport type EnvTypegenConfig = {\n /** Path(s) to the .env.example file(s) to parse. */\n input: string | string[];\n /** Output directory for generated files. Defaults to the input file's directory. */\n output?: string;\n /** Which generators to run. When omitted, all four generators run. */\n generators?: GeneratorName[];\n /** Format generated output with prettier. Defaults to true. */\n format?: boolean;\n /**\n * Additional inference rules to prepend before the built-in rules.\n * Rules are matched in ascending priority order; lower numbers win.\n */\n inferenceRules?: InferenceRule[];\n\n /**\n * Path to the contract file (`env.contract.ts`).\n * When provided, the contract is the authoritative source of type information.\n * Relative to the config file directory or `process.cwd()`.\n */\n schemaFile?: string;\n\n /**\n * When `true`, variables absent from the contract emit errors rather than warnings.\n * Defaults to `true`.\n */\n strict?: boolean;\n\n /**\n * Resolution strategy for type information.\n * - `\"legacy\"` (default): inference-first; annotations override inferred types.\n * - `\"contract-first\"`: contract is authoritative; inference is a fallback only.\n */\n schemaMode?: \"legacy\" | \"contract-first\";\n\n /** Default target files for `env-typegen diff` when --targets is omitted. */\n diffTargets?: string[];\n\n /** Plugin references (module paths or plugin objects). */\n plugins?: PluginReference[];\n};\n\n/** Config file names searched in order when calling loadConfig(). */\nexport const CONFIG_FILE_NAMES = [\n \"env-typegen.config.mjs\",\n \"env-typegen.config.js\",\n \"env-typegen.config.ts\",\n] as const;\n\n/**\n * Type-safe config helper.\n * Returns the config object unchanged — exists purely for IDE autocompletion\n * and compile-time validation of the config shape.\n */\nexport function defineConfig(config: EnvTypegenConfig): EnvTypegenConfig {\n return config;\n}\n\n/**\n * Loads env-typegen config by searching for a config file in `cwd`.\n * Searches for env-typegen.config.ts → .mjs → .js in order.\n * Returns `undefined` when no config file is found.\n */\nexport async function loadConfig(\n cwd: string = process.cwd(),\n): Promise<EnvTypegenConfig | undefined> {\n for (const name of CONFIG_FILE_NAMES) {\n const filePath = path.resolve(cwd, name);\n if (existsSync(filePath)) {\n // Node.js cannot import TypeScript files natively — attempting import()\n // on a .ts path throws \"Unknown file extension .ts\" and crashes every command.\n // Detect early and emit an actionable error instead.\n if (filePath.endsWith(\".ts\")) {\n throw new Error(\n `Config file \"${name}\" was found but TypeScript files cannot be loaded directly at runtime.\\n` +\n `Rename it to \"env-typegen.config.mjs\" and use ESM export syntax:\\n\\n` +\n ` // env-typegen.config.mjs\\n` +\n ` import { defineConfig } from \"@xlameiro/env-typegen\";\\n` +\n ` export default defineConfig({ input: \".env.example\" });\\n\\n` +\n `Tip: keep env-typegen.config.ts for IDE autocompletion and create a sibling\\n` +\n `env-typegen.config.mjs for runtime loading.`,\n );\n }\n const fileUrl = pathToFileURL(filePath).href;\n const mod = (await import(fileUrl)) as { default?: EnvTypegenConfig };\n return mod.default;\n }\n }\n return undefined;\n}\n","import path from \"node:path\";\n\nimport { type GeneratorName, type InferenceRule } from \"./config.js\";\nimport { generateDeclaration } from \"./generators/declaration-generator.js\";\nimport { generateT3Env } from \"./generators/t3-generator.js\";\nimport { generateTypeScriptTypes } from \"./generators/typescript-generator.js\";\nimport { generateZodSchema } from \"./generators/zod-generator.js\";\nimport { parseEnvFileContent } from \"./parser/env-parser.js\";\nimport type { ParsedEnvFile } from \"./parser/types.js\";\nimport { readEnvFile, writeOutput } from \"./utils/file.js\";\nimport { formatOutput } from \"./utils/format.js\";\nimport { success } from \"./utils/logger.js\";\n\n/** Options accepted by the runGenerate pipeline. */\nexport type RunGenerateOptions = {\n input: string | string[];\n output: string;\n generators: GeneratorName[];\n format: boolean;\n stdout?: boolean;\n dryRun?: boolean;\n silent?: boolean;\n /** Additional inference rules to prepend before built-in rules. */\n inferenceRules?: InferenceRule[];\n};\n\n/** Derive the output file path for a generator when multiple generators are in use. */\nfunction deriveOutputPath(base: string, generator: GeneratorName, isSingle: boolean): string {\n if (isSingle) return base;\n const ext = path.extname(base);\n const noExt = ext.length > 0 ? base.slice(0, -ext.length) : base;\n // The declaration generator produces ambient TypeScript declarations (.d.ts).\n // Use the correct extension so IDEs and tsc pick it up as a declaration file.\n const baseExt = ext.length > 0 ? ext : \".ts\";\n const outExt = generator === \"declaration\" ? \".d.ts\" : baseExt;\n return `${noExt}.${generator}${outExt}`;\n}\n\n/**\n * When running against multiple input files, derive a per-input output base so\n * each file produces a distinct set of outputs. The input's basename (without\n * extension) is used as the stem; directory and extension come from the\n * user-supplied `output` option.\n */\nfunction deriveOutputBaseForInput(output: string, inputPath: string): string {\n const dir = path.dirname(output);\n const ext = path.extname(output);\n const stem = path.basename(inputPath, path.extname(inputPath));\n return path.join(dir, `${stem}${ext}`);\n}\n\n/** Invoke the correct generator function for the given name. */\nfunction buildOutput(generator: GeneratorName, parsed: ParsedEnvFile): string {\n switch (generator) {\n case \"typescript\":\n return generateTypeScriptTypes(parsed);\n case \"zod\":\n return generateZodSchema(parsed);\n case \"t3\":\n return generateT3Env(parsed);\n case \"declaration\":\n return generateDeclaration(parsed);\n }\n}\n\nasync function persistOutput(params: {\n generated: string;\n generator: GeneratorName;\n outputPath: string;\n isSingle: boolean;\n stdout: boolean;\n dryRun: boolean;\n silent: boolean;\n}): Promise<void> {\n const { generated, generator, outputPath, isSingle, stdout, dryRun, silent } = params;\n\n if (stdout) {\n if (isSingle) {\n console.log(generated);\n } else {\n console.log(`// --- ${generator}:${outputPath} ---`);\n console.log(generated);\n }\n return;\n }\n\n if (dryRun) {\n if (!silent) {\n if (!isSingle) {\n console.log(`// --- ${generator}: ${outputPath} ---`);\n }\n console.log(generated);\n success(`Dry run: would write ${outputPath}`);\n }\n return;\n }\n\n await writeOutput(outputPath, generated);\n if (!silent) {\n success(`Generated ${outputPath}`);\n }\n}\n\n/**\n * Reads the input file(s), runs the requested generators, optionally formats each\n * output, and writes the results to disk.\n *\n * Exported for unit testing — call this directly rather than spawning a child process.\n */\nexport async function runGenerate(options: RunGenerateOptions): Promise<void> {\n const {\n input,\n output,\n generators,\n format: shouldFormat,\n stdout = false,\n dryRun = false,\n silent = false,\n inferenceRules,\n } = options;\n const inputs = Array.isArray(input) ? input : [input];\n const hasMultipleInputs = inputs.length > 1;\n const isSingle = generators.length === 1;\n\n for (const inputPath of inputs) {\n const outputBase = hasMultipleInputs ? deriveOutputBaseForInput(output, inputPath) : output;\n const content = await readEnvFile(inputPath);\n const parsed = parseEnvFileContent(\n content,\n inputPath,\n inferenceRules === undefined ? undefined : { inferenceRules },\n );\n\n for (const generator of generators) {\n let generated = buildOutput(generator, parsed);\n if (shouldFormat && !dryRun) {\n generated = await formatOutput(generated);\n }\n const outputPath = deriveOutputPath(outputBase, generator, isSingle);\n await persistOutput({\n generated,\n generator,\n outputPath,\n isSingle,\n stdout,\n dryRun,\n silent,\n });\n }\n }\n}\n","import path from \"node:path\";\n\nimport type { ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Generates an ambient `.d.ts` declaration file from a parsed .env.example.\n *\n * Output is a pure `NodeJS.ProcessEnv` augmentation — no `export type` statements.\n * This makes the file valid as a global ambient declaration that can be dropped\n * into `lib/` or `types/` without affecting module resolution.\n *\n * Output structure:\n * ```\n * // Generated by env-typegen — do not edit manually\n * // Source: .env.example\n *\n * declare namespace NodeJS {\n * interface ProcessEnv {\n * readonly KEY: string; // all vars are runtime strings\n * readonly OPT?: string; // optional vars use ?: string\n * readonly NUM: string; // coerce to number: Number(process.env.NUM)\n * readonly FLAG: string; // coerce to boolean: process.env.FLAG === 'true'\n * }\n * }\n * ```\n *\n * For a `.ts` output with typed `export type EnvVars` / `ServerEnvVars` /\n * `ClientEnvVars`, use `generateTypeScriptTypes` instead.\n *\n * - `ProcessEnv` uses `readonly string` for every variable (runtime reality)\n * - Number and boolean vars include an inline coercion hint comment\n * - `annotatedType` takes precedence over `inferredType`\n */\nexport function generateDeclaration(parsed: ParsedEnvFile): string {\n const fileName = path.basename(parsed.filePath);\n\n // NodeJS.ProcessEnv augmentation — ambient only, no exports\n const lines = [\n \"// Generated by env-typegen — do not edit manually\",\n `// Source: ${fileName}`,\n \"\",\n \"declare namespace NodeJS {\",\n \" interface ProcessEnv {\",\n ];\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const optional = variable.isOptional ? \"?\" : \"\";\n if (variable.description !== undefined) {\n lines.push(` /** ${variable.description} */`);\n }\n let propLine = ` readonly ${variable.key}${optional}: string;`;\n if (effectiveType === \"number\") {\n propLine += ` // coerce to number: Number(process.env.${variable.key})`;\n } else if (effectiveType === \"boolean\") {\n propLine += ` // coerce to boolean: process.env.${variable.key} === 'true'`;\n }\n lines.push(propLine);\n }\n lines.push(\" }\", \"}\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import type { EnvVarType, ParsedEnvFile, ParsedEnvVar } from \"../parser/types.js\";\n\n/**\n * Escapes a string for safe embedding inside a double-quoted JavaScript string\n * literal. Backslashes must be escaped before double quotes so that a backslash\n * at the end of the value does not inadvertently escape the closing quote.\n */\nfunction escapeJsStringLiteral(value: string): string {\n return value.replaceAll(\"\\\\\", String.raw`\\\\`).replaceAll('\"', String.raw`\\\"`);\n}\n\n/**\n * Maps an EnvVarType to its Zod schema expression for use in t3-env createEnv().\n *\n * Note: boolean uses `z.coerce.boolean()` here (not the `.transform()` approach\n * in the standalone zod-generator) because @t3-oss/env-nextjs handles coercion\n * internally with `z.coerce`.\n */\nfunction toT3ZodType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"z.coerce.number()\";\n if (envVarType === \"boolean\") return \"z.coerce.boolean()\";\n if (envVarType === \"url\") return \"z.string().url()\";\n if (envVarType === \"email\") return \"z.string().email()\";\n return \"z.string()\";\n}\n\n/**\n * Builds the Zod schema expression for a single env variable including\n * optional `.describe()` and `.optional()` modifiers.\n */\nfunction buildZodExpr(variable: ParsedEnvVar): string {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n let zodExpr = toT3ZodType(effectiveType);\n if (variable.description !== undefined) {\n zodExpr += `.describe(\"${escapeJsStringLiteral(variable.description)}\")`;\n }\n if (variable.isOptional) {\n zodExpr += \".optional()\";\n }\n return zodExpr;\n}\n\n/**\n * Generates a `@t3-oss/env-nextjs` configuration file from a parsed .env.example.\n *\n * Output structure:\n * ```\n * import { createEnv } from \"@t3-oss/env-nextjs\";\n * import { z } from \"zod\";\n *\n * export const env = createEnv({\n * server: { /* non-NEXT_PUBLIC_ vars *\\/ },\n * client: { /* NEXT_PUBLIC_ vars *\\/ },\n * runtimeEnv: { /* all vars mapped to process.env *\\/ },\n * });\n * ```\n *\n * - `server:` is omitted when there are no server-side vars\n * - `client:` is omitted when there are no client-side vars (NEXT_PUBLIC_ prefix)\n * - `runtimeEnv:` always includes all vars\n * - `annotatedType` takes precedence over `inferredType`\n * - Optional vars have `.optional()` appended\n * - Vars with a description have `.describe(\"text\")` appended (before `.optional()`)\n */\nexport function generateT3Env(parsed: ParsedEnvFile): string {\n const serverVars = parsed.vars.filter((v) => !v.isClientSide);\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n\n const lines = [\n \"// Generated by env-typegen — do not edit manually\",\n 'import { createEnv } from \"@t3-oss/env-nextjs\";',\n 'import { z } from \"zod\";',\n \"\",\n \"export const env = createEnv({\",\n ];\n\n if (serverVars.length > 0) {\n lines.push(\n \" server: {\",\n ...serverVars.map((v) => ` ${v.key}: ${buildZodExpr(v)},`),\n \" },\",\n );\n }\n\n if (clientVars.length > 0) {\n lines.push(\n \" client: {\",\n ...clientVars.map((v) => ` ${v.key}: ${buildZodExpr(v)},`),\n \" },\",\n );\n }\n\n lines.push(\n \" runtimeEnv: {\",\n ...parsed.vars.map((v) => ` ${v.key}: process.env.${v.key},`),\n \" },\",\n \"});\",\n );\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import path from \"node:path\";\n\nimport type { EnvVarType, ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Maps an EnvVarType to its TypeScript primitive equivalent.\n * url, email, semver, json, and unknown all map to `string` because\n * TypeScript has no built-in branded types for these.\n */\nfunction toTsType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"number\";\n if (envVarType === \"boolean\") return \"boolean\";\n return \"string\";\n}\n\n/**\n * Generates a TypeScript source file from a parsed .env.example file.\n *\n * Output structure:\n * 1. Header comments — generated-by notice, source file name, ISO timestamp\n * 2. `declare namespace NodeJS { interface ProcessEnv { ... } }` — global augmentation\n * where all properties are typed as `readonly string` (the runtime reality).\n * Number and boolean vars include an inline coercion hint comment.\n * 3. `export type EnvVars = { ... }` — typed module export using semantic types\n * (number, boolean, string).\n * 4. `ServerEnvVars` / `ClientEnvVars` — emitted only when `NEXT_PUBLIC_` vars exist.\n *\n * The output is valid as both a `.ts` and `.d.ts` file.\n * For an ambient-only `.d.ts` (without `export type` statements), use\n * `generateDeclaration` instead.\n *\n * `annotatedType` takes precedence over `inferredType` when both are set.\n */\nexport function generateTypeScriptTypes(parsed: ParsedEnvFile): string {\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n const hasClientVars = clientVars.length > 0;\n const fileName = path.basename(parsed.filePath);\n const timestamp = new Date().toISOString();\n const lines: string[] = [];\n\n // Header + open NodeJS namespace\n lines.push(\n \"// Generated by env-typegen — do not edit manually\",\n `// Source: ${fileName}`,\n `// Generated at: ${timestamp}`,\n \"\",\n \"declare namespace NodeJS {\",\n \" interface ProcessEnv {\",\n );\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const optional = variable.isOptional ? \"?\" : \"\";\n if (variable.description !== undefined) {\n lines.push(` /** ${variable.description} */`);\n }\n let propLine = ` readonly ${variable.key}${optional}: string;`;\n if (effectiveType === \"number\") {\n propLine += ` // coerce to number: Number(process.env.${variable.key})`;\n } else if (effectiveType === \"boolean\") {\n propLine += ` // coerce to boolean: process.env.${variable.key} === 'true'`;\n }\n lines.push(propLine);\n }\n // Close NodeJS namespace + open EnvVars type\n lines.push(\" }\", \"}\", \"\", \"export type EnvVars = {\");\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const tsType = toTsType(effectiveType);\n const optional = variable.isOptional ? \"?\" : \"\";\n lines.push(` ${variable.key}${optional}: ${tsType};`);\n }\n lines.push(\"};\");\n\n // ServerEnvVars / ClientEnvVars — only emitted when NEXT_PUBLIC_ vars exist\n if (hasClientVars) {\n const clientKeyUnion = clientVars.map((v) => `\"${v.key}\"`).join(\" | \");\n lines.push(\n \"\",\n `export type ServerEnvVars = Omit<EnvVars, ${clientKeyUnion}>;`,\n `export type ClientEnvVars = Pick<EnvVars, ${clientKeyUnion}>;`,\n );\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\n/**\n * Generates a runtime `validateEnv()` function that throws when any required\n * environment variable is absent from `process.env`.\n */\nexport function generateEnvValidation(parsed: ParsedEnvFile): string {\n const required = parsed.vars.filter((v) => v.isRequired).map((v) => v.key);\n const lines: string[] = [];\n\n lines.push(\n \"// Generated by env-typegen — do not edit manually\",\n \"\",\n \"export function validateEnv(): void {\",\n );\n\n if (required.length === 0) {\n lines.push(\" // No required environment variables defined\");\n } else {\n const keyList = required.map((k) => `\"${k}\"`).join(\", \");\n lines.push(\n ` const required = [${keyList}];`,\n \" for (const key of required) {\",\n \" if (!process.env[key]) {\",\n \" throw new Error(`Missing required environment variable: ${key}`);\",\n \" }\",\n \" }\",\n );\n }\n\n lines.push(\"}\");\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import type { EnvVarType, ParsedEnvFile } from \"../parser/types.js\";\n\n/**\n * Maps an EnvVarType to its Zod schema expression.\n *\n * - `number` → `z.coerce.number()` (env vars are strings; coerce handles the cast)\n * - `boolean` → `z.coerce.boolean()` (env vars are strings; coerce handles truthy cast)\n * - `url` → `z.string().url()`\n * - `email` → `z.string().email()`\n * - everything else → `z.string()` (string | semver | json | unknown)\n */\nfunction toZodType(envVarType: EnvVarType): string {\n if (envVarType === \"number\") return \"z.coerce.number()\";\n if (envVarType === \"boolean\") return \"z.coerce.boolean()\";\n if (envVarType === \"url\") return \"z.string().url()\";\n if (envVarType === \"email\") return \"z.string().email()\";\n return \"z.string()\";\n}\n\n/**\n * Generates a Zod schema file from a parsed .env.example file.\n *\n * Output structure:\n * ```\n * // Generated by env-typegen — do not edit manually\n * import { z } from \"zod\";\n *\n * export const serverEnvSchema = z.object({\n * DATABASE_URL: z.string().url(),\n * PORT: z.coerce.number(),\n * });\n *\n * export const clientEnvSchema = z.object({\n * NEXT_PUBLIC_API_URL: z.string().url(),\n * });\n *\n * export const envSchema = serverEnvSchema.merge(clientEnvSchema);\n * export type Env = z.infer<typeof envSchema>;\n * ```\n *\n * - Server-side vars (non-`NEXT_PUBLIC_`) go into `serverEnvSchema`\n * - Client-side vars (`NEXT_PUBLIC_` prefix) go into `clientEnvSchema`\n * - `envSchema` is the merged union of both, for full-stack validation\n * - `annotatedType` takes precedence over `inferredType` when both are set\n * - Optional vars have `.optional()` appended to their Zod expression\n */\nexport function generateZodSchema(parsed: ParsedEnvFile): string {\n const serverVars = parsed.vars.filter((v) => !v.isClientSide);\n const clientVars = parsed.vars.filter((v) => v.isClientSide);\n const lines: string[] = [];\n\n // Header + open serverEnvSchema\n lines.push(\n \"// Generated by env-typegen — do not edit manually\",\n 'import { z } from \"zod\";',\n \"\",\n \"export const serverEnvSchema = z.object({\",\n );\n for (const variable of serverVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const zodExpr = variable.isOptional\n ? `${toZodType(effectiveType)}.optional()`\n : toZodType(effectiveType);\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n // Close serverEnvSchema + open clientEnvSchema\n lines.push(\"});\", \"\", \"export const clientEnvSchema = z.object({\");\n for (const variable of clientVars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n const zodExpr = variable.isOptional\n ? `${toZodType(effectiveType)}.optional()`\n : toZodType(effectiveType);\n lines.push(` ${variable.key}: ${zodExpr},`);\n }\n // Close clientEnvSchema + merged schema + type\n lines.push(\n \"});\",\n \"\",\n \"export const envSchema = serverEnvSchema.merge(clientEnvSchema);\",\n \"export type Env = z.infer<typeof envSchema>;\",\n );\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import { readFileSync } from \"node:fs\";\n\nimport type { InferenceRule } from \"../inferrer/rules.js\";\nimport { inferType } from \"../inferrer/type-inferrer.js\";\nimport { parseCommentBlock } from \"./comment-parser.js\";\nimport type { ParsedEnvFile, ParsedEnvVar } from \"./types.js\";\n\nexport { inferType } from \"../inferrer/type-inferrer.js\";\n\n/** Options forwarded to the type-inference step during parsing. */\ntype ParseOptions = {\n /** Additional inference rules to evaluate before the built-in rules. */\n inferenceRules?: InferenceRule[];\n};\n\n/** Matches a valid env var declaration: KEY=VALUE (value may be empty) */\nconst ENV_VAR_RE = /^([A-Z_][A-Z0-9_]*)=(.*)$/;\n\n/**\n * Matches a section header comment of the form:\n * `# --- SectionName ---` or `# === SectionName ===`\n *\n * `\\S+(?:\\s+\\S+)*` replaces `.+?` so that the non-whitespace word tokens\n * cannot overlap with the surrounding `\\s+` groups, eliminating the\n * super-linear backtracking that `.+?` combined with `\\s+` can trigger.\n */\nconst SECTION_HEADER_RE = /^#\\s+[-=]{3,}\\s+(\\S+(?:\\s+\\S+)*)\\s+[-=]{3,}\\s*$/;\n\n/**\n * Builds a {@link ParsedEnvVar} from a matched env-var line.\n * Extracted from `parseEnvFileContent` to reduce cognitive complexity.\n */\nfunction buildParsedVar(\n params: { key: string; rawValue: string; lineNumber: number; currentGroup: string | undefined },\n commentBlock: string[],\n options: ParseOptions | undefined,\n): ParsedEnvVar {\n const annotations = parseCommentBlock(commentBlock);\n // Capture once so TypeScript can narrow the type in the spread below.\n const extraRules = options?.inferenceRules;\n const inferredType = inferType(\n params.key,\n params.rawValue,\n ...(extraRules === undefined ? [] : [{ extraRules }]),\n );\n const isRequired = params.rawValue.length > 0 || annotations.isRequired;\n const isOptional = params.rawValue.length === 0 && !annotations.isRequired;\n const isClientSide = params.key.startsWith(\"NEXT_PUBLIC_\");\n\n const parsedVar: ParsedEnvVar = {\n key: params.key,\n rawValue: params.rawValue,\n inferredType,\n isRequired,\n isOptional,\n isClientSide,\n lineNumber: params.lineNumber,\n };\n\n // Only set optional fields when they have a value (exactOptionalPropertyTypes)\n if (annotations.annotatedType !== undefined) {\n parsedVar.annotatedType = annotations.annotatedType;\n }\n if (annotations.description !== undefined) {\n parsedVar.description = annotations.description;\n }\n if (params.currentGroup !== undefined) {\n parsedVar.group = params.currentGroup;\n }\n if (annotations.enumValues !== undefined) {\n parsedVar.enumValues = annotations.enumValues;\n }\n if (annotations.constraints !== undefined) {\n parsedVar.constraints = annotations.constraints;\n }\n if (annotations.runtime !== undefined) {\n parsedVar.runtime = annotations.runtime;\n }\n if (annotations.isSecret !== undefined) {\n parsedVar.isSecret = annotations.isSecret;\n }\n\n return parsedVar;\n}\n\n/**\n * Parse the string content of a `.env.example` file into a `ParsedEnvFile`.\n *\n * Exposed separately from `parseEnvFile` to enable unit testing without\n * filesystem access.\n *\n * @param content - Raw file content as a UTF-8 string\n * @param filePath - Used to populate `ParsedEnvFile.filePath` only\n * @param options - Optional parse configuration (custom inference rules)\n */\nexport function parseEnvFileContent(\n content: string,\n filePath: string,\n options?: ParseOptions,\n): ParsedEnvFile {\n const lines = content.split(\"\\n\");\n const vars: ParsedEnvVar[] = [];\n const groups: string[] = [];\n\n let currentGroup: string | undefined;\n let commentBlock: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n const lineNumber = i + 1;\n const trimmed = line.trim();\n\n // Blank line — break the comment block association\n if (trimmed === \"\") {\n commentBlock = [];\n continue;\n }\n\n // Section header — update current group and reset comment block\n const sectionMatch = SECTION_HEADER_RE.exec(trimmed);\n if (sectionMatch !== null) {\n const groupName = (sectionMatch[1] ?? \"\").trim();\n currentGroup = groupName;\n if (!groups.includes(groupName)) {\n groups.push(groupName);\n }\n commentBlock = [];\n continue;\n }\n\n // Comment line — accumulate for the next env var\n if (trimmed.startsWith(\"#\")) {\n commentBlock.push(line);\n continue;\n }\n\n // Env var declaration\n const envMatch = ENV_VAR_RE.exec(trimmed);\n if (envMatch === null) {\n // Unrecognised line — reset comment block\n commentBlock = [];\n continue;\n }\n\n vars.push(\n buildParsedVar(\n { key: envMatch[1] ?? \"\", rawValue: envMatch[2] ?? \"\", lineNumber, currentGroup },\n commentBlock,\n options,\n ),\n );\n commentBlock = [];\n }\n\n return { filePath, vars, groups };\n}\n\n/**\n * Read and parse a `.env.example` file from disk.\n *\n * @param filePath - Absolute or relative path to the file\n */\nexport function parseEnvFile(filePath: string): ParsedEnvFile {\n const content = readFileSync(filePath, \"utf8\");\n return parseEnvFileContent(content, filePath);\n}\n","import type { EnvVarType } from \"../parser/types.js\";\n\nexport type InferenceRule = {\n id: string;\n priority: number;\n match: (key: string, value: string) => boolean;\n type: EnvVarType;\n};\n\nexport const inferenceRules: readonly InferenceRule[] = [\n {\n id: \"P2_key_url_suffix\",\n priority: 2,\n match: (key: string) => key.toUpperCase().endsWith(\"_URL\"),\n type: \"url\",\n },\n {\n id: \"P3_key_email_from_suffix\",\n priority: 3,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return normalizedKey.endsWith(\"_EMAIL\") || normalizedKey.endsWith(\"_FROM\");\n },\n type: \"email\",\n },\n {\n id: \"P4_boolean_prefix\",\n priority: 4,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return (\n normalizedKey.startsWith(\"ENABLE_\") ||\n normalizedKey.startsWith(\"DISABLE_\") ||\n normalizedKey.startsWith(\"IS_\") ||\n normalizedKey.startsWith(\"DEBUG\") ||\n normalizedKey.startsWith(\"FEATURE_\")\n );\n },\n type: \"boolean\",\n },\n {\n id: \"P5_key_port\",\n priority: 5,\n match: (key: string) => {\n const normalizedKey = key.toUpperCase();\n return normalizedKey.endsWith(\"_PORT\") || normalizedKey === \"PORT\";\n },\n type: \"number\",\n },\n {\n id: \"P6_empty_unknown\",\n priority: 6,\n match: (_key: string, value: string) => value.length === 0,\n type: \"unknown\",\n },\n {\n id: \"P7_boolean_literal\",\n priority: 7,\n match: (_key: string, value: string) => {\n const lower = value.toLowerCase();\n return lower === \"true\" || lower === \"false\";\n },\n type: \"boolean\",\n },\n {\n id: \"P8_numeric_literal\",\n priority: 8,\n // Non-capturing group with \\d keeps the dot/digit boundary unambiguous,\n // eliminating super-linear backtracking (ReDoS-safe).\n match: (_key: string, value: string) => /^\\d+(?:\\.\\d+)?$/.test(value),\n type: \"number\",\n },\n {\n id: \"P9_semver\",\n priority: 9,\n match: (_key: string, value: string) => /^\\d+\\.\\d+\\.\\d+/.test(value),\n type: \"semver\",\n },\n {\n id: \"P10_url_scheme\",\n priority: 10,\n match: (_key: string, value: string) => /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value),\n type: \"url\",\n },\n {\n id: \"P11_email_literal\",\n priority: 11,\n // Dots are excluded from each domain-segment character class so that the\n // literal \\. separators are unambiguous, preventing super-linear backtracking.\n match: (_key: string, value: string) => /^[^@\\s]+@[^@\\s.]+(?:\\.[^@\\s.]+)+$/.test(value),\n type: \"email\",\n },\n {\n id: \"P12_json_object_array\",\n priority: 12,\n match: (_key: string, value: string) => {\n try {\n const parsed: unknown = JSON.parse(value);\n return typeof parsed === \"object\" && parsed !== null;\n } catch {\n return false;\n }\n },\n type: \"json\",\n },\n] as const;\n","import type { EnvVarType } from \"../parser/types.js\";\nimport type { InferenceRule } from \"./rules.js\";\nimport { inferenceRules } from \"./rules.js\";\n\ntype InferTypeOptions = {\n fallbackType?: EnvVarType;\n /**\n * Additional rules to check before the built-in rules.\n * Within extraRules, lower priority number = higher precedence.\n */\n extraRules?: InferenceRule[];\n};\n\nconst sortedRules = [...inferenceRules].sort((left, right) => left.priority - right.priority);\n\nexport function inferType(key: string, value: string, options?: InferTypeOptions): EnvVarType {\n const extra = options?.extraRules;\n const rules =\n extra && extra.length > 0\n ? [...extra].sort((a, b) => a.priority - b.priority).concat(sortedRules)\n : sortedRules;\n\n for (const rule of rules) {\n if (rule.match(key, value)) {\n return rule.type;\n }\n }\n\n return options?.fallbackType ?? \"string\";\n}\n\nexport function inferTypesFromParsedVars(\n parsed: { vars: Array<{ key: string; rawValue: string }> },\n options?: InferTypeOptions,\n): EnvVarType[] {\n return parsed.vars.map((item) => inferType(item.key, item.rawValue, options));\n}\n","import type { EnvVarType } from \"./types.js\";\n\n/**\n * Structured annotations extracted from a JSDoc-style comment block\n * that precedes an env var declaration.\n *\n * @example\n * ```\n * # @description PostgreSQL connection string\n * # @required\n * # @type string\n * DATABASE_URL=\n * ```\n */\nexport type CommentAnnotations = {\n /** Type explicitly declared with `@type` in the comment block */\n annotatedType?: EnvVarType;\n\n /** Description from `@description` or the first free-form comment line */\n description?: string;\n\n /** true when the `@required` annotation is present in the comment block */\n isRequired: boolean;\n\n /** Allowed literal values from a `@enum` annotation (comma-separated list) */\n enumValues?: string[];\n\n /** Numeric range constraints from `@min` and/or `@max` annotations */\n constraints?: { min?: number; max?: number };\n\n /** Runtime scope from a `@runtime` annotation (`server` | `client` | `edge`) */\n runtime?: \"server\" | \"client\" | \"edge\";\n\n /** true when the `@secret` annotation is present — value must never appear in reports */\n isSecret?: boolean;\n};\n\nconst VALID_ENV_VAR_TYPES = new Set<string>([\n \"string\",\n \"number\",\n \"boolean\",\n \"url\",\n \"email\",\n \"semver\",\n \"json\",\n \"unknown\",\n]);\n\nfunction isEnvVarType(value: string): value is EnvVarType {\n return VALID_ENV_VAR_TYPES.has(value);\n}\n\n/** Internal mutable accumulator used while processing annotation lines. */\ntype AnnotationState = {\n isRequired: boolean;\n annotatedType?: EnvVarType;\n description?: string;\n enumValues?: string[];\n minConstraint?: number;\n maxConstraint?: number;\n runtime?: \"server\" | \"client\" | \"edge\";\n isSecret?: boolean;\n};\n\nfunction applyTypeAnnotation(state: AnnotationState, content: string): void {\n const typeStr = content.slice(\"@type \".length).trim();\n if (isEnvVarType(typeStr)) state.annotatedType = typeStr;\n}\n\nfunction applyEnumAnnotation(state: AnnotationState, content: string): void {\n const values = content\n .slice(\"@enum \".length)\n .trim()\n .split(\",\")\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length > 0) state.enumValues = values;\n}\n\nfunction applyMinAnnotation(state: AnnotationState, content: string): void {\n const num = Number(content.slice(\"@min \".length).trim());\n if (Number.isFinite(num)) state.minConstraint = num;\n}\n\nfunction applyMaxAnnotation(state: AnnotationState, content: string): void {\n const num = Number(content.slice(\"@max \".length).trim());\n if (Number.isFinite(num)) state.maxConstraint = num;\n}\n\nfunction applyRuntimeAnnotation(state: AnnotationState, content: string): void {\n const scope = content.slice(\"@runtime \".length).trim();\n if (scope === \"server\" || scope === \"client\" || scope === \"edge\") {\n state.runtime = scope;\n }\n}\n\nfunction processAnnotationContent(state: AnnotationState, content: string): void {\n const trimmed = content.trim();\n if (trimmed === \"@required\") {\n state.isRequired = true;\n return;\n }\n if (trimmed === \"@secret\") {\n state.isSecret = true;\n return;\n }\n if (trimmed === \"@optional\") return;\n if (content.startsWith(\"@description \")) {\n state.description = content.slice(\"@description \".length).trim();\n } else if (content.startsWith(\"@type \")) {\n applyTypeAnnotation(state, content);\n } else if (content.startsWith(\"@enum \")) {\n applyEnumAnnotation(state, content);\n } else if (content.startsWith(\"@min \")) {\n applyMinAnnotation(state, content);\n } else if (content.startsWith(\"@max \")) {\n applyMaxAnnotation(state, content);\n } else if (content.startsWith(\"@runtime \")) {\n applyRuntimeAnnotation(state, content);\n } else if (state.description === undefined && trimmed.length > 0) {\n // First non-empty, non-annotation line is a fallback description\n state.description = trimmed;\n }\n}\n\n/**\n * Parse a block of consecutive comment lines (each starting with `#`) and\n * extract JSDoc-style annotations.\n *\n * Recognised annotations:\n * - `@description <text>` — sets the variable description\n * - `@required` — marks the variable as required regardless of value\n * - `@optional` — informational (isRequired stays false)\n * - `@type <EnvVarType>` — overrides the inferred type\n * - `@enum val1,val2,...` — declares allowed literal values (comma-separated)\n * - `@min <number>` — declares a numeric minimum constraint\n * - `@max <number>` — declares a numeric maximum constraint\n * - `@runtime <scope>` — declares runtime scope: `server` | `client` | `edge`\n * - `@secret` — marks the value as sensitive (never logged or reported)\n *\n * Non-annotation comment lines act as a fallback description when no\n * `@description` annotation is present (first non-empty line wins).\n *\n * @param lines - Raw comment lines from the .env file, e.g. `[\"# @required\"]`\n */\nexport function parseCommentBlock(lines: readonly string[]): CommentAnnotations {\n const state: AnnotationState = { isRequired: false };\n\n for (const line of lines) {\n processAnnotationContent(state, line.replace(/^#\\s*/, \"\").trimEnd());\n }\n\n let constraints: { min?: number; max?: number } | undefined;\n if (state.minConstraint !== undefined || state.maxConstraint !== undefined) {\n constraints = {};\n if (state.minConstraint !== undefined) constraints.min = state.minConstraint;\n if (state.maxConstraint !== undefined) constraints.max = state.maxConstraint;\n }\n\n const result: CommentAnnotations = { isRequired: state.isRequired };\n if (state.annotatedType !== undefined) result.annotatedType = state.annotatedType;\n if (state.description !== undefined) result.description = state.description;\n if (state.enumValues !== undefined) result.enumValues = state.enumValues;\n if (constraints !== undefined) result.constraints = constraints;\n if (state.runtime !== undefined) result.runtime = state.runtime;\n if (state.isSecret !== undefined) result.isSecret = state.isSecret;\n return result;\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Reads a .env file from `filePath` and returns its full text content.\n * Rejects with a Node.js filesystem error if the file does not exist.\n */\nexport async function readEnvFile(filePath: string): Promise<string> {\n return readFile(path.resolve(filePath), \"utf8\");\n}\n\n/**\n * Writes `content` to `filePath`, creating intermediate directories as needed.\n * Overwrites any existing file at that path.\n */\nexport async function writeOutput(filePath: string, content: string): Promise<void> {\n const resolved = path.resolve(filePath);\n await mkdir(path.dirname(resolved), { recursive: true });\n await writeFile(resolved, content, \"utf8\");\n}\n","import { format } from \"prettier\";\n\n/**\n * Formats `content` using prettier with the specified `parser`.\n * Defaults to the \"typescript\" parser, which is correct for all generator outputs.\n * Returns the original content unchanged if prettier throws (e.g., invalid syntax).\n */\nexport async function formatOutput(\n content: string,\n parser: string = \"typescript\",\n): Promise<string> {\n try {\n return await format(content, { parser });\n } catch (err) {\n console.warn(\n \"env-typegen: Prettier formatting failed, writing unformatted output.\",\n err instanceof Error ? err.message : String(err),\n );\n return content;\n }\n}\n","import { green, red, yellow } from \"picocolors\";\n\n/** Prints a plain informational message to stdout. */\nexport function log(message: string): void {\n console.log(message);\n}\n\n/** Prints a yellow ⚠ warning message to stderr. */\nexport function warn(message: string): void {\n console.warn(yellow(`⚠ ${message}`));\n}\n\n/** Prints a red ✖ error message to stderr. */\nexport function error(message: string): void {\n console.error(red(`✖ ${message}`));\n}\n\n/** Prints a green ✔ success message to stdout. */\nexport function success(message: string): void {\n console.log(green(`✔ ${message}`));\n}\n","import path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\n\nimport { loadCloudSource, type CloudProvider } from \"./cloud/connectors.js\";\nimport { loadConfig, type EnvTypegenConfig } from \"./config.js\";\nimport { loadValidationContract } from \"./contract.js\";\nimport {\n applyContractPlugins,\n applyReportPlugins,\n applySourcePlugins,\n loadPlugins,\n type PluginReference,\n} from \"./plugins.js\";\nimport {\n buildDoctorReport,\n diffEnvironmentSources,\n validateAgainstContract,\n} from \"./validation/engine.js\";\nimport { loadEnvSource } from \"./validation/env-source.js\";\nimport { emitValidationReport } from \"./validation/output.js\";\nimport type { ValidationReport } from \"./validation/types.js\";\n\ntype ValidationCommand = \"check\" | \"diff\" | \"doctor\";\ntype JsonMode = \"off\" | \"compact\" | \"pretty\";\n\ntype ValidationArgValues = {\n env?: string[];\n targets?: string;\n contract?: string;\n example?: string;\n strict?: boolean;\n \"no-strict\"?: boolean;\n json?: boolean;\n \"output-file\"?: string;\n \"debug-values\"?: boolean;\n \"cloud-provider\"?: string;\n \"cloud-file\"?: string;\n plugin?: string[];\n config?: string;\n help?: boolean;\n};\n\ntype ParsedValidationArgs = {\n values: ValidationArgValues;\n jsonMode: JsonMode;\n};\n\ntype LoadCommandConfigModule = {\n default?: EnvTypegenConfig;\n};\n\nconst HELP_TEXT: Record<ValidationCommand, string> = {\n check: [\n \"Usage: env-typegen check [options]\",\n \"\",\n \"Options:\",\n \" --env <path> Environment file to validate (default: .env)\",\n \" --contract <path> Contract file path (default: env.contract.ts)\",\n \" --example <path> Fallback .env.example used to bootstrap contract\",\n \" --strict Validate extras as errors (default: true)\",\n \" --no-strict Downgrade extras to warnings\",\n \" --json Emit machine-readable JSON report\",\n \" --json=pretty Emit pretty JSON report\",\n \" --output-file <path> Persist JSON report to a file\",\n \" --debug-values Include raw values in issues (unsafe for CI logs)\",\n \" --cloud-provider <name> vercel | cloudflare | aws\",\n \" --cloud-file <path> Cloud snapshot JSON file\",\n \" --plugin <path> Plugin module path (repeatable)\",\n \" -c, --config <path> Config file path\",\n \" -h, --help Show this help\",\n \"\",\n \"Exit codes:\",\n \" 0 All checks passed (status: ok or warn)\",\n \" 1 One or more checks failed (status: fail) or invalid usage\",\n ].join(\"\\n\"),\n diff: [\n \"Usage: env-typegen diff [options]\",\n \"\",\n \"Options:\",\n \" --targets <list> Comma-separated targets (default: .env,.env.example,.env.production)\",\n \" --contract <path> Contract file path (default: env.contract.ts)\",\n \" --example <path> Fallback .env.example used to bootstrap contract\",\n \" --strict Validate extras as errors (default: true)\",\n \" --no-strict Downgrade extras to warnings\",\n \" --json Emit machine-readable JSON report\",\n \" --json=pretty Emit pretty JSON report\",\n \" --output-file <path> Persist JSON report to a file\",\n \" --debug-values Include raw values in issues (unsafe for CI logs)\",\n \" --cloud-provider <name> vercel | cloudflare | aws\",\n \" --cloud-file <path> Cloud snapshot JSON file added to diff sources\",\n \" --plugin <path> Plugin module path (repeatable)\",\n \" -c, --config <path> Config file path\",\n \" -h, --help Show this help\",\n \"\",\n \"Exit codes:\",\n \" 0 All checks passed (status: ok or warn)\",\n \" 1 One or more checks failed (status: fail) or invalid usage\",\n ].join(\"\\n\"),\n doctor: [\n \"Usage: env-typegen doctor [options]\",\n \"\",\n \"Options:\",\n \" --env <path> Environment file to validate (default: .env)\",\n \" --targets <list> Comma-separated targets for drift analysis\",\n \" --contract <path> Contract file path (default: env.contract.ts)\",\n \" --example <path> Fallback .env.example used to bootstrap contract\",\n \" --strict Validate extras as errors (default: true)\",\n \" --no-strict Downgrade extras to warnings\",\n \" --json Emit machine-readable JSON report\",\n \" --json=pretty Emit pretty JSON report\",\n \" --output-file <path> Persist JSON report to a file\",\n \" --debug-values Include raw values in issues (unsafe for CI logs)\",\n \" --cloud-provider <name> vercel | cloudflare | aws\",\n \" --cloud-file <path> Cloud snapshot JSON file\",\n \" --plugin <path> Plugin module path (repeatable)\",\n \" -c, --config <path> Config file path\",\n \" -h, --help Show this help\",\n \"\",\n \"Exit codes:\",\n \" 0 All checks passed (status: ok or warn)\",\n \" 1 One or more checks failed (status: fail) or invalid usage\",\n ].join(\"\\n\"),\n};\n\nfunction resolveConfigRelative(value: string | undefined, configDir: string): string | undefined {\n if (value === undefined || path.isAbsolute(value)) return value;\n return path.resolve(configDir, value);\n}\n\nfunction resolvePluginReference(reference: PluginReference, configDir: string): PluginReference {\n if (typeof reference === \"string\" && !path.isAbsolute(reference)) {\n return path.resolve(configDir, reference);\n }\n return reference;\n}\n\nfunction applyConfigPaths(config: EnvTypegenConfig, configDir: string): EnvTypegenConfig {\n let input: string | string[] | undefined;\n if (Array.isArray(config.input)) {\n input = config.input.map((item) => resolveConfigRelative(item, configDir) ?? item);\n } else {\n input = resolveConfigRelative(config.input, configDir);\n }\n const output = resolveConfigRelative(config.output, configDir);\n const schemaFile = resolveConfigRelative(config.schemaFile, configDir);\n\n return {\n ...config,\n ...(input !== undefined && { input }),\n ...(output !== undefined && { output }),\n ...(schemaFile !== undefined && { schemaFile }),\n ...(config.diffTargets !== undefined && {\n diffTargets: config.diffTargets.map(\n (target) => resolveConfigRelative(target, configDir) ?? target,\n ),\n }),\n ...(config.plugins !== undefined && {\n plugins: config.plugins.map((reference) => resolvePluginReference(reference, configDir)),\n }),\n };\n}\n\nasync function loadCommandConfig(\n configPath: string | undefined,\n): Promise<EnvTypegenConfig | undefined> {\n if (configPath === undefined) {\n return loadConfig(process.cwd());\n }\n\n const resolvedPath = path.resolve(configPath);\n const configDir = path.dirname(resolvedPath);\n const moduleValue = (await import(pathToFileURL(resolvedPath).href)) as LoadCommandConfigModule;\n if (moduleValue.default === undefined) return undefined;\n return applyConfigPaths(moduleValue.default, configDir);\n}\n\nfunction preprocessJsonArguments(argv: string[]): {\n normalizedArgs: string[];\n assignedMode: JsonMode;\n} {\n const normalizedArgs: string[] = [];\n let assignedMode: JsonMode = \"off\";\n\n for (const item of argv) {\n if (item === \"--json=pretty\") {\n normalizedArgs.push(\"--json\");\n assignedMode = \"pretty\";\n continue;\n }\n if (item === \"--json=compact\") {\n normalizedArgs.push(\"--json\");\n assignedMode = \"compact\";\n continue;\n }\n normalizedArgs.push(item);\n }\n\n return { normalizedArgs, assignedMode };\n}\n\nfunction parseValidationArgs(argv: string[]): ParsedValidationArgs {\n const { normalizedArgs, assignedMode } = preprocessJsonArguments(argv);\n const { values } = parseArgs({\n args: normalizedArgs,\n options: {\n env: { type: \"string\", multiple: true },\n targets: { type: \"string\" },\n contract: { type: \"string\" },\n example: { type: \"string\" },\n strict: { type: \"boolean\" },\n \"no-strict\": { type: \"boolean\" },\n json: { type: \"boolean\" },\n \"output-file\": { type: \"string\" },\n \"debug-values\": { type: \"boolean\" },\n \"cloud-provider\": { type: \"string\" },\n \"cloud-file\": { type: \"string\" },\n plugin: { type: \"string\", multiple: true },\n config: { type: \"string\", short: \"c\" },\n help: { type: \"boolean\", short: \"h\" },\n } as const,\n });\n\n const castValues = values as ValidationArgValues;\n let jsonMode: JsonMode = \"off\";\n if (castValues.json === true) {\n jsonMode = assignedMode === \"off\" ? \"compact\" : assignedMode;\n }\n\n return { values: castValues, jsonMode };\n}\n\nfunction resolveStrict(\n values: ValidationArgValues,\n fileConfig: EnvTypegenConfig | undefined,\n): boolean {\n if (values[\"no-strict\"] === true) return false;\n if (values.strict !== undefined) return values.strict;\n if (fileConfig?.strict !== undefined) return fileConfig.strict;\n return true;\n}\n\nfunction parseCloudProvider(value: string | undefined): CloudProvider | undefined {\n if (value === undefined) return undefined;\n if (value === \"vercel\" || value === \"cloudflare\" || value === \"aws\") return value;\n throw new Error(`Unknown cloud provider: ${value}. Valid: vercel, cloudflare, aws`);\n}\n\nfunction parseTargets(\n values: ValidationArgValues,\n fileConfig: EnvTypegenConfig | undefined,\n): string[] {\n const fromCli = values.targets;\n if (fromCli !== undefined) {\n return fromCli\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n }\n\n if (fileConfig?.diffTargets !== undefined && fileConfig.diffTargets.length > 0) {\n return fileConfig.diffTargets;\n }\n\n return [\".env\", \".env.example\", \".env.production\"];\n}\n\nasync function prepareCommonContext(values: ValidationArgValues): Promise<{\n fileConfig: EnvTypegenConfig | undefined;\n strict: boolean;\n debugValues: boolean;\n outputFile: string | undefined;\n contractPath: string | undefined;\n fallbackExamplePath: string;\n cloudProvider: CloudProvider | undefined;\n cloudFile: string | undefined;\n plugins: Awaited<ReturnType<typeof loadPlugins>>;\n}> {\n const fileConfig = await loadCommandConfig(values.config);\n const strict = resolveStrict(values, fileConfig);\n const debugValues = values[\"debug-values\"] ?? false;\n const contractPath = values.contract ?? fileConfig?.schemaFile;\n const fallbackExamplePath = values.example ?? \".env.example\";\n const cloudProvider = parseCloudProvider(values[\"cloud-provider\"]);\n const cloudFile = values[\"cloud-file\"];\n const pluginLoadOptions = {\n pluginPaths: values.plugin ?? [],\n cwd: process.cwd(),\n ...(fileConfig?.plugins !== undefined && { configPlugins: fileConfig.plugins }),\n };\n const plugins = await loadPlugins(pluginLoadOptions);\n\n return {\n fileConfig,\n strict,\n debugValues,\n outputFile: values[\"output-file\"],\n contractPath,\n fallbackExamplePath,\n cloudProvider,\n cloudFile,\n plugins,\n };\n}\n\nasync function emitAndReturnExitCode(\n report: ValidationReport,\n params: {\n jsonMode: JsonMode;\n outputFile?: string;\n },\n): Promise<number> {\n const emitOptions = {\n report,\n jsonMode: params.jsonMode,\n ...(params.outputFile !== undefined && { outputFile: params.outputFile }),\n };\n await emitValidationReport(emitOptions);\n return report.status === \"fail\" ? 1 : 0;\n}\n\nasync function runCheckCommand(args: ParsedValidationArgs): Promise<number> {\n const context = await prepareCommonContext(args.values);\n const loadContractOptions = {\n fallbackExamplePath: context.fallbackExamplePath,\n cwd: process.cwd(),\n ...(context.contractPath !== undefined && { contractPath: context.contractPath }),\n };\n const contract = applyContractPlugins(\n await loadValidationContract(loadContractOptions),\n context.plugins,\n );\n\n const provider = context.cloudProvider;\n let environment = args.values.env?.[0] ?? \".env\";\n let sourceValues: Record<string, string>;\n\n if (provider === undefined) {\n sourceValues = await loadEnvSource({ filePath: environment, allowMissing: true });\n } else {\n const cloudFile = context.cloudFile ?? `${provider}.env.json`;\n sourceValues = await loadCloudSource({ provider, filePath: cloudFile });\n environment = `cloud:${provider}`;\n }\n\n sourceValues = applySourcePlugins({ environment, values: sourceValues }, context.plugins);\n\n const report = applyReportPlugins(\n validateAgainstContract({\n contract,\n values: sourceValues,\n environment,\n strict: context.strict,\n debugValues: context.debugValues,\n }),\n context.plugins,\n );\n\n return emitAndReturnExitCode(report, {\n jsonMode: args.jsonMode,\n ...(context.outputFile !== undefined && { outputFile: context.outputFile }),\n });\n}\n\nasync function runDiffCommand(args: ParsedValidationArgs): Promise<number> {\n const context = await prepareCommonContext(args.values);\n const loadContractOptions = {\n fallbackExamplePath: context.fallbackExamplePath,\n cwd: process.cwd(),\n ...(context.contractPath !== undefined && { contractPath: context.contractPath }),\n };\n const contract = applyContractPlugins(\n await loadValidationContract(loadContractOptions),\n context.plugins,\n );\n\n const sources: Record<string, Record<string, string>> = {};\n for (const target of parseTargets(args.values, context.fileConfig)) {\n const values = await loadEnvSource({ filePath: target, allowMissing: true });\n sources[target] = applySourcePlugins({ environment: target, values }, context.plugins);\n }\n\n if (context.cloudProvider !== undefined) {\n const cloudFile = context.cloudFile ?? `${context.cloudProvider}.env.json`;\n const cloudEnvironment = `cloud:${context.cloudProvider}`;\n const cloudValues = await loadCloudSource({\n provider: context.cloudProvider,\n filePath: cloudFile,\n });\n sources[cloudEnvironment] = applySourcePlugins(\n { environment: cloudEnvironment, values: cloudValues },\n context.plugins,\n );\n }\n\n const report = applyReportPlugins(\n diffEnvironmentSources({\n contract,\n sources,\n strict: context.strict,\n debugValues: context.debugValues,\n }),\n context.plugins,\n );\n\n return emitAndReturnExitCode(report, {\n jsonMode: args.jsonMode,\n ...(context.outputFile !== undefined && { outputFile: context.outputFile }),\n });\n}\n\nasync function runDoctorCommand(args: ParsedValidationArgs): Promise<number> {\n const context = await prepareCommonContext(args.values);\n const loadContractOptions = {\n fallbackExamplePath: context.fallbackExamplePath,\n cwd: process.cwd(),\n ...(context.contractPath !== undefined && { contractPath: context.contractPath }),\n };\n const contract = applyContractPlugins(\n await loadValidationContract(loadContractOptions),\n context.plugins,\n );\n\n const checkEnvironment = args.values.env?.[0] ?? \".env\";\n let checkValues = await loadEnvSource({ filePath: checkEnvironment, allowMissing: true });\n checkValues = applySourcePlugins(\n { environment: checkEnvironment, values: checkValues },\n context.plugins,\n );\n\n const checkReport = validateAgainstContract({\n contract,\n values: checkValues,\n environment: checkEnvironment,\n strict: context.strict,\n debugValues: context.debugValues,\n });\n\n const sources: Record<string, Record<string, string>> = {};\n for (const target of parseTargets(args.values, context.fileConfig)) {\n const values = await loadEnvSource({ filePath: target, allowMissing: true });\n sources[target] = applySourcePlugins({ environment: target, values }, context.plugins);\n }\n\n if (context.cloudProvider !== undefined) {\n const cloudFile = context.cloudFile ?? `${context.cloudProvider}.env.json`;\n const cloudEnvironment = `cloud:${context.cloudProvider}`;\n const cloudValues = await loadCloudSource({\n provider: context.cloudProvider,\n filePath: cloudFile,\n });\n sources[cloudEnvironment] = applySourcePlugins(\n { environment: cloudEnvironment, values: cloudValues },\n context.plugins,\n );\n }\n\n const diffReport = diffEnvironmentSources({\n contract,\n sources,\n strict: context.strict,\n debugValues: context.debugValues,\n });\n\n const report = applyReportPlugins(\n buildDoctorReport({ checkReport, diffReport }),\n context.plugins,\n );\n\n return emitAndReturnExitCode(report, {\n jsonMode: args.jsonMode,\n ...(context.outputFile !== undefined && { outputFile: context.outputFile }),\n });\n}\n\nexport async function runValidationCommand(params: {\n command: ValidationCommand;\n argv: string[];\n}): Promise<number> {\n const parsed = parseValidationArgs(params.argv);\n if (parsed.values.help === true) {\n console.log(HELP_TEXT[params.command]);\n return 0;\n }\n\n if (params.command === \"check\") {\n return runCheckCommand(parsed);\n }\n if (params.command === \"diff\") {\n return runDiffCommand(parsed);\n }\n return runDoctorCommand(parsed);\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type CloudProvider = \"vercel\" | \"cloudflare\" | \"aws\";\n\ntype CloudConnectorLoadOptions = {\n provider: CloudProvider;\n filePath: string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readEntryValue(entry: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = entry[key];\n if (typeof value === \"string\") return value;\n }\n return undefined;\n}\n\nfunction getVercelEntries(value: unknown): unknown[] {\n if (Array.isArray(value)) return value as unknown[];\n if (isRecord(value) && Array.isArray(value.envs)) return value.envs as unknown[];\n return [];\n}\n\nfunction parseVercelPayload(value: unknown): Record<string, string> {\n const entries = getVercelEntries(value);\n const result: Record<string, string> = {};\n for (const entry of entries) {\n if (!isRecord(entry)) continue;\n const key = readEntryValue(entry, [\"key\", \"name\"]);\n if (key === undefined) continue;\n const envValue = readEntryValue(entry, [\"value\", \"targetValue\", \"content\"]) ?? \"\";\n result[key] = envValue;\n }\n return result;\n}\n\nfunction getCloudflareEntries(value: unknown): unknown[] {\n if (Array.isArray(value)) return value as unknown[];\n if (isRecord(value) && Array.isArray(value.result)) return value.result as unknown[];\n return [];\n}\n\nfunction parseCloudflarePayload(value: unknown): Record<string, string> {\n const entries = getCloudflareEntries(value);\n const result: Record<string, string> = {};\n for (const entry of entries) {\n if (!isRecord(entry)) continue;\n const key = readEntryValue(entry, [\"name\", \"key\"]);\n if (key === undefined) continue;\n const envValue = readEntryValue(entry, [\"text\", \"value\", \"secret\"]) ?? \"\";\n result[key] = envValue;\n }\n return result;\n}\n\nfunction parseAwsPayload(value: unknown): Record<string, string> {\n const entries = isRecord(value) && Array.isArray(value.Parameters) ? value.Parameters : [];\n const result: Record<string, string> = {};\n for (const entry of entries) {\n if (!isRecord(entry)) continue;\n const name = readEntryValue(entry, [\"Name\", \"name\"]);\n if (name === undefined) continue;\n const key = name.split(\"/\").findLast((part) => part.length > 0) ?? name;\n const envValue = readEntryValue(entry, [\"Value\", \"value\"]) ?? \"\";\n result[key] = envValue;\n }\n return result;\n}\n\nfunction parseProviderPayload(provider: CloudProvider, value: unknown): Record<string, string> {\n if (provider === \"vercel\") return parseVercelPayload(value);\n if (provider === \"cloudflare\") return parseCloudflarePayload(value);\n return parseAwsPayload(value);\n}\n\nexport async function loadCloudSource(\n options: CloudConnectorLoadOptions,\n): Promise<Record<string, string>> {\n const resolvedPath = path.resolve(options.filePath);\n const raw = await readFile(resolvedPath, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n return parseProviderPayload(options.provider, parsed);\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { EnvVarType } from \"./parser/types.js\";\nimport { parseEnvFile } from \"./parser/env-parser.js\";\nimport type { EnvContract as LegacyEnvContract, EnvContractEntry } from \"./schema/schema-model.js\";\nimport type { EnvContract, EnvContractVariable, Expected } from \"./validation/types.js\";\n\ntype LoadValidationContractOptions = {\n fallbackExamplePath: string;\n contractPath?: string;\n cwd?: string;\n};\n\ntype ContractModule = {\n default?: unknown;\n contract?: unknown;\n};\n\nconst SECRET_KEY_RE = /(SECRET|TOKEN|PASSWORD|PRIVATE|API_KEY|ACCESS_KEY|CLIENT_SECRET)/i;\nconst CONTRACT_FILE_NAMES = [\"env.contract.ts\", \"env.contract.mjs\", \"env.contract.js\"] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isExpected(value: unknown): value is Expected {\n if (!isRecord(value)) return false;\n const typeValue = value.type;\n if (typeof typeValue !== \"string\") return false;\n const validTypes = new Set([\n \"string\",\n \"number\",\n \"boolean\",\n \"enum\",\n \"url\",\n \"email\",\n \"json\",\n \"semver\",\n \"unknown\",\n ]);\n if (!validTypes.has(typeValue)) return false;\n if (typeValue === \"enum\") {\n return Array.isArray(value.values) && value.values.every((item) => typeof item === \"string\");\n }\n return true;\n}\n\nfunction isEnvContractVariable(value: unknown): value is EnvContractVariable {\n if (!isRecord(value)) return false;\n if (!isExpected(value.expected)) return false;\n if (typeof value.required !== \"boolean\") return false;\n if (typeof value.clientSide !== \"boolean\") return false;\n if (value.description !== undefined && typeof value.description !== \"string\") return false;\n if (value.secret !== undefined && typeof value.secret !== \"boolean\") return false;\n return true;\n}\n\nfunction isEnvContract(value: unknown): value is EnvContract {\n if (!isRecord(value)) return false;\n if (value.schemaVersion !== 1) return false;\n if (!isRecord(value.variables)) return false;\n return Object.values(value.variables).every((item) => isEnvContractVariable(item));\n}\n\nfunction isLegacyContract(value: unknown): value is LegacyEnvContract {\n if (!isRecord(value)) return false;\n if (!Array.isArray(value.vars)) return false;\n return value.vars.every((entry) => isRecord(entry) && typeof entry.name === \"string\");\n}\n\nfunction mapEnvVarTypeToExpected(type: EnvVarType): Expected {\n if (type === \"number\") return { type: \"number\" };\n if (type === \"boolean\") return { type: \"boolean\" };\n if (type === \"url\") return { type: \"url\" };\n if (type === \"email\") return { type: \"email\" };\n if (type === \"json\") return { type: \"json\" };\n if (type === \"semver\") return { type: \"semver\" };\n if (type === \"unknown\") return { type: \"unknown\" };\n return { type: \"string\" };\n}\n\nfunction shouldTreatAsSecret(key: string): boolean {\n return SECRET_KEY_RE.test(key);\n}\n\nfunction toExpectedFromLegacyEntry(entry: EnvContractEntry): Expected {\n if (entry.enumValues !== undefined && entry.enumValues.length > 0) {\n return { type: \"enum\", values: entry.enumValues };\n }\n if (entry.expectedType === \"number\") {\n return {\n type: \"number\",\n ...(entry.constraints?.min !== undefined && { min: entry.constraints.min }),\n ...(entry.constraints?.max !== undefined && { max: entry.constraints.max }),\n };\n }\n if (entry.expectedType === \"boolean\") return { type: \"boolean\" };\n if (entry.expectedType === \"url\") return { type: \"url\" };\n if (entry.expectedType === \"email\") return { type: \"email\" };\n if (entry.expectedType === \"json\") return { type: \"json\" };\n if (entry.expectedType === \"semver\") return { type: \"semver\" };\n if (entry.expectedType === \"unknown\") return { type: \"unknown\" };\n return { type: \"string\" };\n}\n\nfunction convertLegacyContract(contract: LegacyEnvContract): EnvContract {\n const variables: Record<string, EnvContractVariable> = {};\n for (const entry of contract.vars) {\n const clientSide = entry.runtime === \"client\" || entry.name.startsWith(\"NEXT_PUBLIC_\");\n variables[entry.name] = {\n expected: toExpectedFromLegacyEntry(entry),\n required: entry.required,\n clientSide,\n ...(entry.description !== undefined && { description: entry.description }),\n ...((entry.isSecret ?? shouldTreatAsSecret(entry.name)) && { secret: true }),\n };\n }\n return {\n schemaVersion: 1,\n variables,\n };\n}\n\nfunction buildContractFromExample(examplePath: string): EnvContract {\n const parsed = parseEnvFile(examplePath);\n const variables: Record<string, EnvContractVariable> = {};\n\n for (const variable of parsed.vars) {\n const effectiveType = variable.annotatedType ?? variable.inferredType;\n variables[variable.key] = {\n expected: mapEnvVarTypeToExpected(effectiveType),\n required: variable.isRequired,\n clientSide: variable.isClientSide,\n ...(variable.description !== undefined && { description: variable.description }),\n ...(shouldTreatAsSecret(variable.key) && { secret: true }),\n };\n }\n\n return {\n schemaVersion: 1,\n variables,\n };\n}\n\nfunction findDefaultContractPath(cwd: string): string | undefined {\n for (const fileName of CONTRACT_FILE_NAMES) {\n const candidatePath = path.resolve(cwd, fileName);\n if (existsSync(candidatePath)) return candidatePath;\n }\n return undefined;\n}\n\nexport async function loadValidationContract(\n options: LoadValidationContractOptions,\n): Promise<EnvContract> {\n const { fallbackExamplePath, contractPath, cwd = process.cwd() } = options;\n const discoveredContractPath = findDefaultContractPath(cwd);\n const resolvedContractPath =\n contractPath === undefined ? discoveredContractPath : path.resolve(cwd, contractPath);\n\n if (resolvedContractPath !== undefined && existsSync(resolvedContractPath)) {\n const moduleUrl = pathToFileURL(resolvedContractPath).href;\n const moduleValue = (await import(moduleUrl)) as ContractModule;\n const candidate = moduleValue.default ?? moduleValue.contract;\n if (isEnvContract(candidate)) {\n return candidate;\n }\n if (isLegacyContract(candidate)) {\n return convertLegacyContract(candidate);\n }\n throw new Error(\n `Invalid contract at ${resolvedContractPath}. Export default must match EnvContract.`,\n );\n }\n\n return buildContractFromExample(path.resolve(cwd, fallbackExamplePath));\n}\n","import path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { EnvContract, ValidationReport } from \"./validation/types.js\";\n\nexport type EnvTypegenPlugin = {\n name: string;\n transformContract?: (contract: EnvContract) => EnvContract;\n transformSource?: (input: {\n environment: string;\n values: Record<string, string>;\n }) => Record<string, string>;\n transformReport?: (report: ValidationReport) => ValidationReport;\n};\n\nexport type PluginReference = string | EnvTypegenPlugin;\n\ntype LoadPluginsOptions = {\n pluginPaths: string[];\n configPlugins?: PluginReference[];\n cwd?: string;\n};\n\ntype PluginModule = {\n default?: unknown;\n plugin?: unknown;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isPlugin(value: unknown): value is EnvTypegenPlugin {\n if (!isRecord(value)) return false;\n if (typeof value.name !== \"string\") return false;\n if (value.transformContract !== undefined && typeof value.transformContract !== \"function\") {\n return false;\n }\n if (value.transformSource !== undefined && typeof value.transformSource !== \"function\") {\n return false;\n }\n if (value.transformReport !== undefined && typeof value.transformReport !== \"function\") {\n return false;\n }\n return true;\n}\n\nasync function loadPluginFromPath(pluginPath: string, cwd: string): Promise<EnvTypegenPlugin> {\n const resolvedPath = path.resolve(cwd, pluginPath);\n const moduleValue = (await import(pathToFileURL(resolvedPath).href)) as PluginModule;\n const candidate = moduleValue.default ?? moduleValue.plugin;\n if (isPlugin(candidate)) return candidate;\n throw new Error(\n `Invalid plugin at ${resolvedPath}.\\n` +\n `Expected a default export matching:\\n` +\n ` { name: string,\\n` +\n ` transformSource?(ctx: { environment: string; values: Record<string, string> }): Record<string, string>,\\n` +\n ` transformReport?(report: ValidationReport): ValidationReport,\\n` +\n ` transformContract?(contract: EnvContract): EnvContract }`,\n );\n}\n\nexport async function loadPlugins(options: LoadPluginsOptions): Promise<EnvTypegenPlugin[]> {\n const cwd = options.cwd ?? process.cwd();\n const plugins: EnvTypegenPlugin[] = [];\n\n const references: PluginReference[] = [...(options.configPlugins ?? []), ...options.pluginPaths];\n\n for (const reference of references) {\n if (typeof reference === \"string\") {\n plugins.push(await loadPluginFromPath(reference, cwd));\n continue;\n }\n if (isPlugin(reference)) {\n plugins.push(reference);\n continue;\n }\n throw new Error(\"Invalid plugin reference in configuration.\");\n }\n\n return plugins;\n}\n\nexport function applyContractPlugins(\n contract: EnvContract,\n plugins: readonly EnvTypegenPlugin[],\n): EnvContract {\n let next = contract;\n for (const plugin of plugins) {\n if (plugin.transformContract === undefined) continue;\n next = plugin.transformContract(next);\n }\n return next;\n}\n\nexport function applySourcePlugins(\n params: { environment: string; values: Record<string, string> },\n plugins: readonly EnvTypegenPlugin[],\n): Record<string, string> {\n let next = params.values;\n for (const plugin of plugins) {\n if (plugin.transformSource === undefined) continue;\n next = plugin.transformSource({ environment: params.environment, values: next });\n }\n return next;\n}\n\nexport function applyReportPlugins(\n report: ValidationReport,\n plugins: readonly EnvTypegenPlugin[],\n): ValidationReport {\n let next = report;\n for (const plugin of plugins) {\n if (plugin.transformReport === undefined) continue;\n next = plugin.transformReport(next);\n }\n return next;\n}\n","import type {\n EnvContract,\n EnvContractVariable,\n Expected,\n IssueCode,\n IssueSeverity,\n IssueType,\n ValidationIssue,\n ValidationReport,\n} from \"./types.js\";\n\ntype ValidateValueResult =\n | { isValid: true; receivedType: string }\n | { isValid: false; receivedType: string; issueType: \"invalid_type\" | \"invalid_value\" };\n\ntype ValidateAgainstContractOptions = {\n contract: EnvContract;\n values: Record<string, string>;\n environment: string;\n strict: boolean;\n debugValues: boolean;\n};\n\ntype DiffEnvironmentSourcesOptions = {\n contract: EnvContract;\n sources: Record<string, Record<string, string>>;\n strict: boolean;\n debugValues: boolean;\n};\n\ntype BuildDoctorReportOptions = {\n checkReport: ValidationReport;\n diffReport: ValidationReport;\n};\n\n// Dots are excluded from each domain-segment class so that the literal \\.\n// separators are unambiguous, eliminating super-linear backtracking.\nconst EMAIL_RE = /^[^@\\s]+@[^@\\s.]+(?:\\.[^@\\s.]+)+$/;\n// Dots are excluded from inside [\\w.-] groups: only the literal \\. separator\n// carries dot semantics, so there is no backtracking ambiguity (ReDoS-safe).\nconst SEMVER_RE = /^\\d+\\.\\d+\\.\\d+(?:-[\\w.-]+)?(?:\\+[\\w.-]+)?$/;\n\nfunction detectReceivedType(value: string): string {\n const normalized = value.trim();\n if (normalized.length === 0) return \"unknown\";\n if ([\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"].includes(normalized.toLowerCase())) return \"boolean\";\n if (!Number.isNaN(Number(normalized)) && Number.isFinite(Number(normalized))) return \"number\";\n if (SEMVER_RE.test(normalized)) return \"semver\";\n try {\n const url = new URL(normalized);\n if (url.protocol.length > 0) return \"url\";\n } catch {\n // noop\n }\n if (EMAIL_RE.test(normalized)) return \"email\";\n try {\n const parsed: unknown = JSON.parse(normalized);\n if (typeof parsed === \"object\" && parsed !== null) return \"json\";\n } catch {\n // noop\n }\n return \"string\";\n}\n\nfunction validateNumber(\n expected: Extract<Expected, { type: \"number\" }>,\n normalized: string,\n receivedType: string,\n): ValidateValueResult {\n const parsed = Number(normalized);\n if (Number.isNaN(parsed) || !Number.isFinite(parsed)) {\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n }\n if (expected.min !== undefined && parsed < expected.min) {\n return { isValid: false, receivedType, issueType: \"invalid_value\" };\n }\n if (expected.max !== undefined && parsed > expected.max) {\n return { isValid: false, receivedType, issueType: \"invalid_value\" };\n }\n return { isValid: true, receivedType };\n}\n\nfunction validateBoolean(normalized: string, receivedType: string): ValidateValueResult {\n if (![\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"].includes(normalized.toLowerCase())) {\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n }\n return { isValid: true, receivedType };\n}\n\nfunction validateEnum(\n expected: Extract<Expected, { type: \"enum\" }>,\n normalized: string,\n receivedType: string,\n): ValidateValueResult {\n if (!expected.values.includes(normalized)) {\n return { isValid: false, receivedType, issueType: \"invalid_value\" };\n }\n return { isValid: true, receivedType };\n}\n\nfunction validateUrl(normalized: string, receivedType: string): ValidateValueResult {\n try {\n const value = new URL(normalized);\n if (value.protocol.length === 0)\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n return { isValid: true, receivedType };\n } catch {\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n }\n}\n\nfunction validateEmail(normalized: string, receivedType: string): ValidateValueResult {\n if (!EMAIL_RE.test(normalized))\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n return { isValid: true, receivedType };\n}\n\nfunction validateJson(normalized: string, receivedType: string): ValidateValueResult {\n try {\n const parsed: unknown = JSON.parse(normalized);\n if (typeof parsed === \"object\" && parsed !== null) return { isValid: true, receivedType };\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n } catch {\n return { isValid: false, receivedType, issueType: \"invalid_type\" };\n }\n}\n\nfunction validateSemver(normalized: string, receivedType: string): ValidateValueResult {\n if (!SEMVER_RE.test(normalized))\n return { isValid: false, receivedType, issueType: \"invalid_value\" };\n return { isValid: true, receivedType };\n}\n\nfunction validateValueAgainstExpected(expected: Expected, rawValue: string): ValidateValueResult {\n const normalized = rawValue.trim();\n const receivedType = detectReceivedType(normalized);\n\n if (expected.type === \"unknown\" || expected.type === \"string\")\n return { isValid: true, receivedType };\n if (expected.type === \"number\") return validateNumber(expected, normalized, receivedType);\n if (expected.type === \"boolean\") return validateBoolean(normalized, receivedType);\n if (expected.type === \"enum\") return validateEnum(expected, normalized, receivedType);\n if (expected.type === \"url\") return validateUrl(normalized, receivedType);\n if (expected.type === \"email\") return validateEmail(normalized, receivedType);\n if (expected.type === \"json\") return validateJson(normalized, receivedType);\n if (expected.type === \"semver\") return validateSemver(normalized, receivedType);\n return { isValid: true, receivedType };\n}\n\nfunction toIssueCode(issueType: IssueType): IssueCode {\n if (issueType === \"missing\") return \"ENV_MISSING\";\n if (issueType === \"extra\") return \"ENV_EXTRA\";\n if (issueType === \"invalid_type\") return \"ENV_INVALID_TYPE\";\n if (issueType === \"invalid_value\") return \"ENV_INVALID_VALUE\";\n if (issueType === \"conflict\") return \"ENV_CONFLICT\";\n return \"ENV_SECRET_EXPOSED\";\n}\n\nfunction toIssueValue(value: string | undefined, debugValues: boolean): string | null {\n if (!debugValues) return null;\n if (value === undefined) return null;\n return value;\n}\n\nfunction createIssue(params: {\n type: IssueType;\n severity: IssueSeverity;\n key: string;\n environment: string;\n message: string;\n value?: string;\n debugValues: boolean;\n expected?: Expected;\n receivedType?: string;\n}): ValidationIssue {\n return {\n code: toIssueCode(params.type),\n type: params.type,\n severity: params.severity,\n key: params.key,\n environment: params.environment,\n message: params.message,\n value: toIssueValue(params.value, params.debugValues),\n ...(params.expected !== undefined && { expected: params.expected }),\n ...(params.receivedType !== undefined && { receivedType: params.receivedType }),\n };\n}\n\nfunction dedupeIssues(issues: ValidationIssue[]): ValidationIssue[] {\n const seen = new Set<string>();\n const unique: ValidationIssue[] = [];\n\n for (const issue of issues) {\n const token = [\n issue.code,\n issue.type,\n issue.severity,\n issue.environment,\n issue.key,\n issue.message,\n issue.receivedType ?? \"\",\n ].join(\"|\");\n if (seen.has(token)) continue;\n seen.add(token);\n unique.push(issue);\n }\n\n return unique;\n}\n\nfunction buildReport(\n env: string,\n issues: ValidationIssue[],\n recommendations?: string[],\n): ValidationReport {\n const dedupedIssues = dedupeIssues(issues);\n const errors = dedupedIssues.filter((item) => item.severity === \"error\").length;\n const warnings = dedupedIssues.filter((item) => item.severity === \"warning\").length;\n const status = errors > 0 ? \"fail\" : \"ok\";\n\n return {\n schemaVersion: 1,\n status,\n summary: {\n errors,\n warnings,\n total: dedupedIssues.length,\n },\n issues: dedupedIssues,\n meta: {\n env,\n timestamp: new Date().toISOString(),\n },\n ...(recommendations !== undefined && recommendations.length > 0 && { recommendations }),\n };\n}\n\nfunction isClientSecret(variable: EnvContractVariable, key: string): boolean {\n return variable.secret === true && (variable.clientSide || key.startsWith(\"NEXT_PUBLIC_\"));\n}\n\ntype ContractCheckContext = {\n options: ValidateAgainstContractOptions;\n issues: ValidationIssue[];\n};\n\nfunction checkContractVariable(\n key: string,\n variable: EnvContractVariable,\n context: ContractCheckContext,\n): void {\n const { options, issues } = context;\n const value = options.values[key];\n const hasValue = value !== undefined && value.trim().length > 0;\n\n if (variable.required && !hasValue) {\n issues.push(\n createIssue({\n type: \"missing\",\n severity: \"error\",\n key,\n environment: options.environment,\n message: `Required variable ${key} is missing.`,\n debugValues: options.debugValues,\n expected: variable.expected,\n }),\n );\n return;\n }\n\n if (!hasValue) return;\n\n const validation = validateValueAgainstExpected(variable.expected, value);\n if (!validation.isValid) {\n const message =\n validation.issueType === \"invalid_type\"\n ? `Variable ${key} has invalid type.`\n : `Variable ${key} has invalid value.`;\n issues.push(\n createIssue({\n type: validation.issueType,\n severity: \"error\",\n key,\n environment: options.environment,\n message,\n value,\n debugValues: options.debugValues,\n expected: variable.expected,\n receivedType: validation.receivedType,\n }),\n );\n }\n\n if (isClientSecret(variable, key)) {\n issues.push(\n createIssue({\n type: \"secret_exposed\",\n severity: \"error\",\n key,\n environment: options.environment,\n message: `Secret variable ${key} is marked as client-side.`,\n value,\n debugValues: options.debugValues,\n expected: variable.expected,\n }),\n );\n }\n}\n\nexport function validateAgainstContract(options: ValidateAgainstContractOptions): ValidationReport {\n const issues: ValidationIssue[] = [];\n const contractKeys = new Set(Object.keys(options.contract.variables));\n\n for (const [key, variable] of Object.entries(options.contract.variables)) {\n checkContractVariable(key, variable, { options, issues });\n }\n\n for (const [key, value] of Object.entries(options.values)) {\n if (contractKeys.has(key)) continue;\n const severity: IssueSeverity = options.strict ? \"error\" : \"warning\";\n issues.push(\n createIssue({\n type: \"extra\",\n severity,\n key,\n environment: options.environment,\n message: `Variable ${key} is not defined in the contract.`,\n value,\n debugValues: options.debugValues,\n }),\n );\n }\n\n return buildReport(options.environment, issues);\n}\n\nfunction collectUnionKeys(\n contract: EnvContract,\n sources: Record<string, Record<string, string>>,\n): Set<string> {\n const union = new Set<string>(Object.keys(contract.variables));\n for (const source of Object.values(sources)) {\n for (const key of Object.keys(source)) {\n union.add(key);\n }\n }\n return union;\n}\n\ntype SourceEntry = { sourceName: string; value: string | undefined };\n\ntype DiffKeyContext = {\n variable: EnvContractVariable | undefined;\n options: DiffEnvironmentSourcesOptions;\n issues: ValidationIssue[];\n};\n\nfunction diffMissingEntries(key: string, missing: SourceEntry[], context: DiffKeyContext): void {\n const { variable, options, issues } = context;\n for (const entry of missing) {\n issues.push(\n createIssue({\n type: \"missing\",\n severity: \"error\",\n key,\n environment: entry.sourceName,\n message: `Variable ${key} is missing in ${entry.sourceName}.`,\n debugValues: options.debugValues,\n ...(variable !== undefined && { expected: variable.expected }),\n }),\n );\n }\n}\n\nfunction diffTypeConflicts(key: string, present: SourceEntry[], context: DiffKeyContext): void {\n const { variable, options, issues } = context;\n const typeBySource = new Map<string, string>();\n for (const entry of present) {\n typeBySource.set(entry.sourceName, detectReceivedType(entry.value ?? \"\"));\n }\n if (new Set(typeBySource.values()).size <= 1) return;\n for (const [sourceName, detectedType] of typeBySource.entries()) {\n issues.push(\n createIssue({\n type: \"conflict\",\n severity: \"error\",\n key,\n environment: sourceName,\n message: `Variable ${key} has conflicting inferred type across environments.`,\n debugValues: options.debugValues,\n receivedType: detectedType,\n ...(options.sources[sourceName]?.[key] !== undefined && {\n value: options.sources[sourceName]?.[key],\n }),\n ...(variable !== undefined && { expected: variable.expected }),\n }),\n );\n }\n}\n\nfunction diffPresentEntry(key: string, entry: SourceEntry, context: DiffKeyContext): void {\n const { variable, options, issues } = context;\n if (entry.value === undefined) return;\n\n if (variable === undefined) {\n const severity: IssueSeverity = options.strict ? \"error\" : \"warning\";\n issues.push(\n createIssue({\n type: \"extra\",\n severity,\n key,\n environment: entry.sourceName,\n message: `Variable ${key} is not defined in the contract.`,\n value: entry.value,\n debugValues: options.debugValues,\n }),\n );\n return;\n }\n\n const validation = validateValueAgainstExpected(variable.expected, entry.value);\n if (!validation.isValid) {\n const message =\n validation.issueType === \"invalid_type\"\n ? `Variable ${key} has invalid type in ${entry.sourceName}.`\n : `Variable ${key} has invalid value in ${entry.sourceName}.`;\n issues.push(\n createIssue({\n type: validation.issueType,\n severity: \"error\",\n key,\n environment: entry.sourceName,\n message,\n value: entry.value,\n debugValues: options.debugValues,\n expected: variable.expected,\n receivedType: validation.receivedType,\n }),\n );\n }\n\n if (isClientSecret(variable, key)) {\n issues.push(\n createIssue({\n type: \"secret_exposed\",\n severity: \"error\",\n key,\n environment: entry.sourceName,\n message: `Secret variable ${key} is marked as client-side.`,\n value: entry.value,\n debugValues: options.debugValues,\n expected: variable.expected,\n }),\n );\n }\n}\n\nexport function diffEnvironmentSources(options: DiffEnvironmentSourcesOptions): ValidationReport {\n const issues: ValidationIssue[] = [];\n const sourceNames = Object.keys(options.sources);\n const unionKeys = collectUnionKeys(options.contract, options.sources);\n\n for (const key of unionKeys) {\n const variable = options.contract.variables[key];\n const valuesBySource: SourceEntry[] = sourceNames.map((sourceName) => ({\n sourceName,\n value: options.sources[sourceName]?.[key],\n }));\n const present = valuesBySource.filter(\n (entry) => entry.value !== undefined && entry.value !== \"\",\n );\n const missing = valuesBySource.filter(\n (entry) => entry.value === undefined || entry.value === \"\",\n );\n\n if (present.length === 0 && variable?.required === true) {\n for (const entry of missing) {\n issues.push(\n createIssue({\n type: \"missing\",\n severity: \"error\",\n key,\n environment: entry.sourceName,\n message: `Required variable ${key} is missing in ${entry.sourceName}.`,\n debugValues: options.debugValues,\n expected: variable.expected,\n }),\n );\n }\n continue;\n }\n\n const ctx: DiffKeyContext = { variable, options, issues };\n if (present.length > 0) {\n diffMissingEntries(key, missing, ctx);\n }\n diffTypeConflicts(key, present, ctx);\n for (const entry of present) {\n diffPresentEntry(key, entry, ctx);\n }\n }\n\n return buildReport(\"diff\", issues);\n}\n\nfunction buildRecommendations(issues: ValidationIssue[]): string[] {\n const codes = new Set<IssueCode>(issues.map((item) => item.code));\n const recommendations: string[] = [];\n\n if (codes.has(\"ENV_MISSING\")) {\n recommendations.push(\"Add missing required variables to each target environment.\");\n }\n if (codes.has(\"ENV_EXTRA\")) {\n recommendations.push(\n \"Remove undeclared variables or add them to env.contract.ts intentionally.\",\n );\n }\n if (codes.has(\"ENV_INVALID_TYPE\") || codes.has(\"ENV_INVALID_VALUE\")) {\n recommendations.push(\n \"Normalize variable values so they match the expected contract types and constraints.\",\n );\n }\n if (codes.has(\"ENV_CONFLICT\")) {\n recommendations.push(\"Align variable semantics across environments to avoid drift.\");\n }\n if (codes.has(\"ENV_SECRET_EXPOSED\")) {\n recommendations.push(\n \"Move secret variables to server-only scope and avoid NEXT_PUBLIC_ exposure for secrets.\",\n );\n }\n\n return recommendations;\n}\n\nexport function buildDoctorReport(options: BuildDoctorReportOptions): ValidationReport {\n const merged = [...options.checkReport.issues, ...options.diffReport.issues];\n const recommendations = buildRecommendations(merged);\n return buildReport(\"doctor\", merged, recommendations);\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\ntype LoadEnvSourceOptions = {\n filePath: string;\n allowMissing?: boolean;\n};\n\nfunction stripWrappingQuotes(value: string): string {\n if (value.length < 2) return value;\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\nfunction parseEnvSourceContent(content: string): Record<string, string> {\n const result: Record<string, string> = {};\n const lines = content.split(\"\\n\");\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) continue;\n const match = /^(?:export\\s+)?([A-Za-z_]\\w*)=(.*)$/.exec(trimmed);\n if (match === null) continue;\n const key = match[1] ?? \"\";\n const rawValue = match[2] ?? \"\";\n result[key] = stripWrappingQuotes(rawValue.trim());\n }\n\n return result;\n}\n\nexport async function loadEnvSource(\n options: LoadEnvSourceOptions,\n): Promise<Record<string, string>> {\n const resolvedPath = path.resolve(options.filePath);\n try {\n const content = await readFile(resolvedPath, \"utf8\");\n return parseEnvSourceContent(content);\n } catch (error_) {\n if (\n options.allowMissing === true &&\n error_ instanceof Error &&\n \"code\" in error_ &&\n error_.code === \"ENOENT\"\n ) {\n return {};\n }\n throw error_;\n }\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { ValidationIssue, ValidationReport } from \"./types.js\";\n\ntype JsonOutputMode = \"off\" | \"compact\" | \"pretty\";\n\ntype EmitValidationReportOptions = {\n report: ValidationReport;\n jsonMode: JsonOutputMode;\n outputFile?: string;\n};\n\nfunction toJsonString(report: ValidationReport, mode: JsonOutputMode): string {\n if (mode === \"pretty\") return `${JSON.stringify(report, null, 2)}\\n`;\n return `${JSON.stringify(report)}\\n`;\n}\n\nfunction formatIssue(issue: ValidationIssue): string {\n const expected = issue.expected === undefined ? \"\" : ` expected=${issue.expected.type}`;\n const received = issue.receivedType === undefined ? \"\" : ` received=${issue.receivedType}`;\n return `${issue.severity.toUpperCase()} [${issue.code}] ${issue.environment}:${issue.key} ${issue.message}${expected}${received}`;\n}\n\nfunction formatHumanReport(report: ValidationReport): string {\n const lines: string[] = [];\n lines.push(\n `Status: ${report.status.toUpperCase()} (errors=${report.summary.errors}, warnings=${report.summary.warnings}, total=${report.summary.total})`,\n );\n if (report.issues.length > 0) {\n lines.push(\"\", \"Issues:\");\n for (const issue of report.issues) {\n lines.push(`- ${formatIssue(issue)}`);\n }\n }\n if (report.recommendations !== undefined && report.recommendations.length > 0) {\n lines.push(\"\", \"Recommendations:\");\n for (const recommendation of report.recommendations) {\n lines.push(`- ${recommendation}`);\n }\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function persistJsonOutput(outputFile: string, report: ValidationReport): Promise<void> {\n const resolvedPath = path.resolve(outputFile);\n await mkdir(path.dirname(resolvedPath), { recursive: true });\n await writeFile(resolvedPath, `${JSON.stringify(report, null, 2)}\\n`, \"utf8\");\n}\n\nexport async function emitValidationReport(options: EmitValidationReportOptions): Promise<void> {\n const { report, outputFile, jsonMode } = options;\n\n if (outputFile !== undefined) {\n await persistJsonOutput(outputFile, report);\n }\n\n if (jsonMode === \"off\") {\n process.stdout.write(formatHumanReport(report));\n return;\n }\n\n process.stdout.write(toJsonString(report, jsonMode));\n}\n","import { watch } from \"chokidar\";\nimport path from \"node:path\";\n\nimport { CONFIG_FILE_NAMES, loadConfig } from \"./config.js\";\nimport type { RunGenerateOptions } from \"./pipeline.js\";\nimport { runGenerate } from \"./pipeline.js\";\nimport { error, log } from \"./utils/logger.js\";\n\ntype WatchOptions = {\n inputPath: string | string[];\n runOptions: RunGenerateOptions;\n /** CWD used to locate the config file; defaults to process.cwd(). */\n cwd?: string;\n};\n\n/** Debounced wrapper: the inner function is called at most once per `delay` ms. */\nfunction debounce<TArgs extends unknown[]>(\n fn: (...args: TArgs) => void,\n delay: number,\n): (...args: TArgs) => void {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return (...args: TArgs) => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n fn(...args);\n }, delay);\n };\n}\n\nexport function startWatch({ inputPath, runOptions, cwd = process.cwd() }: WatchOptions): void {\n const inputLabel = Array.isArray(inputPath) ? inputPath.join(\", \") : inputPath;\n log(`Watching ${inputLabel} for changes...`);\n\n // Run once immediately on start\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n\n const handleChange = debounce((eventPath: string) => {\n log(`${eventPath} changed, regenerating...`);\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n }, 200);\n\n const handleConfigChange = debounce(async (eventPath: string) => {\n log(`Config file ${eventPath} changed, reloading...`);\n try {\n const reloaded = await loadConfig(cwd);\n if (reloaded) {\n // Apply updated generators/format/inferenceRules settings from the new config\n runOptions.generators = reloaded.generators ?? runOptions.generators;\n runOptions.format = reloaded.format ?? runOptions.format;\n if (reloaded.inferenceRules !== undefined) {\n runOptions.inferenceRules = reloaded.inferenceRules;\n }\n if (reloaded.output !== undefined) {\n runOptions.output = reloaded.output;\n }\n }\n void runGenerate(runOptions).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(message);\n });\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : JSON.stringify(err);\n error(`Failed to reload config: ${message}`);\n }\n }, 200);\n\n // Watch the input file — fire on create, modify, or delete+recreate\n const inputWatcher = watch(inputPath, { persistent: true });\n for (const event of [\"add\", \"change\", \"unlink\"] as const) {\n inputWatcher.on(event, handleChange);\n }\n\n // Watch config files so changes take effect without restarting\n const configPaths = CONFIG_FILE_NAMES.map((name) => path.resolve(cwd, name));\n const configWatcher = watch(configPaths, { persistent: true, ignoreInitial: true });\n for (const event of [\"add\", \"change\"] as const) {\n configWatcher.on(event, (eventPath: string) => handleConfigChange(eventPath));\n }\n\n process.on(\"SIGINT\", () => {\n void Promise.all([inputWatcher.close(), configWatcher.close()]).then(() => {\n log(\"Watcher stopped.\");\n process.exit(0);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAI,IAAI,WAAW,CAAC;AAApB,QAAuB,OAAO,EAAE,QAAQ,CAAC;AAAzC,QAA4C,MAAM,EAAE,OAAO,CAAC;AAC5D,QAAI,mBACH,EAAE,CAAC,CAAC,IAAI,YAAY,KAAK,SAAS,YAAY,OAC7C,CAAC,CAAC,IAAI,eAAe,KAAK,SAAS,SAAS,KAAK,EAAE,aAAa,YAAa,EAAE,UAAU,CAAC,GAAG,SAAS,IAAI,SAAS,UAAW,CAAC,CAAC,IAAI;AAEtI,QAAI,YAAY,CAAC,MAAM,OAAO,UAAU,SACvC,WAAS;AACR,UAAI,SAAS,KAAK,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,MAAM;AAClE,aAAO,CAAC,QAAQ,OAAO,aAAa,QAAQ,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,SAAS;AAAA,IAC9F;AAED,QAAI,eAAe,CAAC,QAAQ,OAAO,SAAS,UAAU;AACrD,UAAI,SAAS,IAAI,SAAS;AAC1B,SAAG;AACF,kBAAU,OAAO,UAAU,QAAQ,KAAK,IAAI;AAC5C,iBAAS,QAAQ,MAAM;AACvB,gBAAQ,OAAO,QAAQ,OAAO,MAAM;AAAA,MACrC,SAAS,CAAC;AACV,aAAO,SAAS,OAAO,UAAU,MAAM;AAAA,IACxC;AAEA,QAAI,eAAe,CAAC,UAAU,qBAAqB;AAClD,UAAI,IAAI,UAAU,YAAY,MAAM;AACpC,aAAO;AAAA,QACN,kBAAkB;AAAA,QAClB,OAAO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AClC,QAAM,cAAc,OAAO,SAAS;AAEpC,QAAM,UAA8B;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,GAAI,YAAY,mBAAmB,UAAa,EAAE,gBAAgB,WAAW,eAAe;AAAA,EAC9F;AAEA,MAAI,aAAa;AACf,eAAW,EAAE,WAAW,OAAO,YAAY,QAAQ,CAAC;AAAA,EACtD,OAAO;AACL,UAAM,YAAY,OAAO;AAAA,EAC3B;AACF;AAKA,IACE,QAAQ,KAAK,CAAC,MAAM,WACnB,MAAM;AACL,MAAI;AACF,WACE,aAAaD,OAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAE/F,QAAQ;AACN,WAAO;AAAA,EACT;AACF,GAAG,GACH;AACA,QAAM,OAAO,EAAE,MAAM,CAAC,QAAiB;AACrC,UAAM,gBAAgB,GAAG,CAAC;AAC1B,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["path","pathToFileURL","parseArgs","path","path","path","path","path","inferenceRules","path","pathToFileURL","readFile","path","existsSync","path","pathToFileURL","isRecord","path","existsSync","pathToFileURL","path","pathToFileURL","isRecord","readFile","path","mkdir","writeFile","path","path","pathToFileURL","path","path","HELP_TEXT","resolveConfigRelative","path","applyConfigPaths","parseArgs","pathToFileURL"]}