node-env-resolver-vite 1.1.1 → 2.0.1
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/index.d.ts +4 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/plugin.d.ts +1 -1
- package/dist/plugin.js +1 -1
- package/dist/plugin.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';
|
|
2
|
-
export { EnvDefinition
|
|
3
|
-
export { boolean, custom, date, duration, email,
|
|
2
|
+
export { EnvDefinition } from 'node-env-resolver';
|
|
3
|
+
export { boolean, custom, date, duration, email, file, http, https, json, mongodb, mysql, number, numberArray, oneOf, port, postgres, redis, secret, string, stringArray, timestamp, url, urlArray } from 'node-env-resolver/validators';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* node-env-resolver/vite
|
|
@@ -8,7 +8,7 @@ export { boolean, custom, date, duration, email, enums, file, http, https, json,
|
|
|
8
8
|
*
|
|
9
9
|
* Vite handles .env files via process.env automatically.
|
|
10
10
|
* resolve() is synchronous and works with ALL validator types:
|
|
11
|
-
* - Basic types: string, number, boolean,
|
|
11
|
+
* - Basic types: string, number, boolean, oneOf, pattern, custom
|
|
12
12
|
* - Advanced types: postgres, url, email, json, port, etc.
|
|
13
13
|
*/
|
|
14
14
|
|
|
@@ -47,7 +47,7 @@ interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {
|
|
|
47
47
|
*
|
|
48
48
|
* Vite handles .env files automatically.
|
|
49
49
|
* This function is synchronous and supports ALL validator types:
|
|
50
|
-
* - Basic types: string, number, boolean,
|
|
50
|
+
* - Basic types: string, number, boolean, oneOf, pattern, custom
|
|
51
51
|
* - Advanced types: postgres, url, email, json, port, date, etc.
|
|
52
52
|
*
|
|
53
53
|
* @example
|
|
@@ -122,7 +122,6 @@ declare function safeResolve<TServer extends SimpleEnvSchema, TClient extends Si
|
|
|
122
122
|
server: InferSimpleSchema<TServer>;
|
|
123
123
|
client: InferSimpleSchema<TClient>;
|
|
124
124
|
}>;
|
|
125
|
-
|
|
126
125
|
declare const isServer: boolean;
|
|
127
126
|
declare const isClient: boolean;
|
|
128
127
|
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {resolve}from'node-env-resolver';export{boolean,custom,date,duration,email,
|
|
1
|
+
import {resolve}from'node-env-resolver';export{boolean,custom,date,duration,email,file,http,https,json,mongodb,mysql,number,numberArray,oneOf,port,postgres,redis,secret,string,stringArray,timestamp,url,urlArray}from'node-env-resolver/validators';function p(r,s={}){let{clientPrefix:e="VITE_",runtimeProtection:a=true}=s,n=Object.keys(r.client).filter(t=>!t.startsWith(e));if(n.length>0)throw new Error(`\u274C Client environment variables must be prefixed with '${e}': ${n.join(", ")}
|
|
2
2
|
\u{1F4A1} Rename these variables to start with '${e}' (e.g., ${n[0]} \u2192 ${e}${n[0]})`);let i=Object.keys(r.server).filter(t=>t.startsWith(e));if(i.length>0)throw new Error(`\u274C Server environment variables should not be prefixed with '${e}': ${i.join(", ")}
|
|
3
3
|
\u{1F4A1} These variables will be exposed to the client. Move to client schema or remove prefix.`);let c=resolve(r.server),v=resolve(r.client),m=()=>typeof window<"u";return {server:new Proxy(c,{get(t,o){if(a&&m())throw new Error(`\u274C Cannot access server environment variable '${String(o)}' in client-side code.
|
|
4
4
|
\u{1F4A1} Server variables are only available in server context (vite.config.ts, SSR, build scripts).
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["resolve","config","options","clientPrefix","runtimeProtection","incorrectClientKeys","key","incorrectServerKeys","serverResult","nodeEnvResolve","clientResult","isBrowser","target","prop","safeResolve","error","isServer","isClient"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["resolve","config","options","clientPrefix","runtimeProtection","incorrectClientKeys","key","incorrectServerKeys","serverResult","nodeEnvResolve","clientResult","isBrowser","target","prop","safeResolve","error","isServer","isClient"],"mappings":"sPAuHO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CAAkE,GAIlE,CACA,GAAM,CACJ,YAAA,CAAAC,CAAAA,CAAe,QACf,iBAAA,CAAAC,CAAAA,CAAoB,IACtB,CAAA,CAAIF,CAAAA,CAIEG,CAAAA,CADa,MAAA,CAAO,IAAA,CAAKJ,CAAAA,CAAO,MAAM,CAAA,CACL,MAAA,CAAOK,GAAO,CAACA,CAAAA,CAAI,WAAWH,CAAY,CAAC,EAClF,GAAIE,CAAAA,CAAoB,OAAS,CAAA,CAC/B,MAAM,IAAI,KAAA,CACR,CAAA,2DAAA,EAAyDF,CAAY,CAAA,GAAA,EAAME,CAAAA,CAAoB,IAAA,CAAK,IAAI,CAAC;AAAA,gDAAA,EAC7DF,CAAY,CAAA,SAAA,EAAYE,CAAAA,CAAoB,CAAC,CAAC,CAAA,QAAA,EAAMF,CAAY,CAAA,EAAGE,CAAAA,CAAoB,CAAC,CAAC,GACvI,CAAA,CAKF,IAAME,EADa,MAAA,CAAO,IAAA,CAAKN,EAAO,MAAM,CAAA,CACL,MAAA,CAAOK,CAAAA,EAAOA,EAAI,UAAA,CAAWH,CAAY,CAAC,CAAA,CACjF,GAAII,EAAoB,MAAA,CAAS,CAAA,CAC/B,MAAM,IAAI,MACR,CAAA,iEAAA,EAA+DJ,CAAY,MAAMI,CAAAA,CAAoB,IAAA,CAAK,IAAI,CAAC;AAAA,gGAAA,CAEjH,EAIF,IAAMC,CAAAA,CAAeC,OAAAA,CAAeR,CAAAA,CAAO,MAAM,CAAA,CAC3CS,CAAAA,CAAeD,OAAAA,CAAeR,CAAAA,CAAO,MAAM,CAAA,CAG3CU,CAAAA,CAAY,IAAM,OAAO,MAAA,CAAW,IAsB1C,OApBqB,CACnB,MAAA,CAAQ,IAAI,MAAMH,CAAAA,CAAc,CAC9B,GAAA,CAAII,CAAAA,CAAQC,EAAM,CAEhB,GAAIT,CAAAA,EAAqBO,CAAAA,GACvB,MAAM,IAAI,MACR,CAAA,kDAAA,EAAgD,MAAA,CAAOE,CAAI,CAAC,CAAA;AAAA;AAAA;AAAA,yCAAA,EAGhBV,CAAY,CAAA;AAAA;AAAA,gDAAA,CAG1D,CAAA,CAEF,OAAQS,CAAAA,CAAmCC,CAAc,CAC3D,CACF,CAAC,CAAA,CACD,MAAA,CAAQH,CACV,CAGF,CAgCO,SAASI,CAAAA,CACdb,CAAAA,CACAC,CAAAA,CAAkE,EAAC,CAIlE,CACD,GAAI,CAEF,OAAO,CAAE,OAAA,CAAS,CAAA,CAAA,CAAM,IAAA,CADTF,CAAAA,CAAQC,EAAQC,CAAO,CACD,CACvC,CAAA,MAASa,CAAAA,CAAO,CACd,OAAO,CACL,OAAA,CAAS,KAAA,CACT,KAAA,CAAOA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,QAAU,MAAA,CAAOA,CAAK,CAC9D,CACF,CACF,CAGO,IAAMC,CAAAA,CAAW,OAAO,MAAA,CAAW,GAAA,CAC7BC,CAAAA,CAAW,CAACD","file":"index.js","sourcesContent":["/**\n * node-env-resolver/vite\n * Zero-config Vite integration with automatic client/server split\n *\n * Vite handles .env files via process.env automatically.\n * resolve() is synchronous and works with ALL validator types:\n * - Basic types: string, number, boolean, oneOf, pattern, custom\n * - Advanced types: postgres, url, email, json, port, etc.\n */\n\nimport { resolve as nodeEnvResolve } from 'node-env-resolver';\nimport type { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';\n\n// Re-export all validators for convenience\nexport {\n string,\n url,\n port,\n postgres,\n email,\n number,\n boolean,\n oneOf,\n secret,\n custom,\n duration,\n file,\n json,\n stringArray,\n numberArray,\n urlArray,\n http,\n https,\n mysql,\n mongodb,\n redis,\n date,\n timestamp,\n} from 'node-env-resolver/validators';\n\n// Re-export useful types\nexport type { EnvDefinition } from 'node-env-resolver';\n\n// Safe resolve result types (Zod-like)\nexport interface SafeResolveResult<T> {\n success: true;\n data: T;\n}\n\nexport interface SafeResolveError {\n success: false;\n error: string;\n}\n\nexport type SafeResolveResultType<T> = SafeResolveResult<T> | SafeResolveError;\n\nexport interface ViteEnvConfig<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema> {\n server: TServer;\n client: TClient;\n}\n\nexport interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {\n /**\n * Prefix for client environment variables\n * @default 'VITE_'\n */\n clientPrefix?: string;\n \n /**\n * Enable variable expansion in .env files\n * @default true\n */\n expandVars?: boolean;\n \n /**\n * Enable runtime protection for server variables in client components\n * @default true\n */\n runtimeProtection?: boolean;\n}\n\n/**\n * Create type-safe environment configuration for Vite with automatic client/server split\n *\n * Vite handles .env files automatically.\n * This function is synchronous and supports ALL validator types:\n * - Basic types: string, number, boolean, oneOf, pattern, custom\n * - Advanced types: postgres, url, email, json, port, date, etc.\n *\n * @example\n * ```typescript\n * // env.ts\n * import { resolve } from 'node-env-resolver-vite';\n *\n * export const env = resolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173',\n * NODE_ENV: ['development', 'production'] as const\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * VITE_GA_ID: string({optional:true})\n * }\n * });\n *\n * // In server/build code (vite.config.ts, SSR)\n * import { env } from './env';\n *\n * console.log(env.server.DATABASE_URL); // ✅ Works, type: URL\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n *\n * // In browser code\n * console.log(env.server.DATABASE_URL); // ❌ Throws helpful error in dev\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n * ```\n */\nexport function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): {\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n} {\n const {\n clientPrefix = 'VITE_',\n runtimeProtection = true\n } = options;\n\n // Validate client keys have correct prefix\n const clientKeys = Object.keys(config.client);\n const incorrectClientKeys = clientKeys.filter(key => !key.startsWith(clientPrefix));\n if (incorrectClientKeys.length > 0) {\n throw new Error(\n `❌ Client environment variables must be prefixed with '${clientPrefix}': ${incorrectClientKeys.join(', ')}\\n` +\n `💡 Rename these variables to start with '${clientPrefix}' (e.g., ${incorrectClientKeys[0]} → ${clientPrefix}${incorrectClientKeys[0]})`\n );\n }\n\n // Validate server keys don't have client prefix\n const serverKeys = Object.keys(config.server);\n const incorrectServerKeys = serverKeys.filter(key => key.startsWith(clientPrefix));\n if (incorrectServerKeys.length > 0) {\n throw new Error(\n `❌ Server environment variables should not be prefixed with '${clientPrefix}': ${incorrectServerKeys.join(', ')}\\n` +\n `💡 These variables will be exposed to the client. Move to client schema or remove prefix.`\n );\n }\n\n // Use resolve - Vite already handles .env files via process.env, so no custom resolvers needed\n const serverResult = nodeEnvResolve(config.server) as InferSimpleSchema<TServer>;\n const clientResult = nodeEnvResolve(config.client) as InferSimpleSchema<TClient>;\n\n // Create protected environment object with runtime guards\n const isBrowser = () => typeof window !== 'undefined';\n\n const protectedEnv = {\n server: new Proxy(serverResult, {\n get(target, prop) {\n // Runtime protection for server variables in client\n if (runtimeProtection && isBrowser()) {\n throw new Error(\n `❌ Cannot access server environment variable '${String(prop)}' in client-side code.\\n` +\n `💡 Server variables are only available in server context (vite.config.ts, SSR, build scripts).\\n` +\n `💡 If you need this data on the client, consider:\\n` +\n ` - Moving it to the client schema with ${clientPrefix} prefix\\n` +\n ` - Fetching it via an API endpoint\\n` +\n ` - Using SSR to pass data to client components`\n );\n }\n return (target as Record<string, unknown>)[prop as string];\n }\n }),\n client: clientResult\n };\n\n return protectedEnv;\n}\n\n/**\n * Safe version of resolve() - returns result object instead of throwing (Zod-like pattern)\n *\n * Supports all validator types (basic and advanced).\n *\n * @example\n * ```typescript\n * // env.ts\n * import { safeResolve } from 'node-env-resolver-vite';\n *\n * const result = safeResolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173'\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * }\n * });\n *\n * if (result.success) {\n * export const env = result.data;\n * } else {\n * console.error('Environment validation failed:', result.error);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): SafeResolveResultType<{\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n}> {\n try {\n const result = resolve(config, options);\n return { success: true, data: result };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\n// Utility for runtime environment detection\nexport const isServer = typeof window === 'undefined';\nexport const isClient = !isServer;\n\n"]}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Plugin } from 'vite';
|
|
2
2
|
import { ViteOptions, ViteEnvConfig } from './index.js';
|
|
3
3
|
import { SimpleEnvSchema } from 'node-env-resolver';
|
|
4
|
-
import 'node-env-resolver/
|
|
4
|
+
import 'node-env-resolver/validators';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Vite plugin for node-env-resolver
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {existsSync,readFileSync,mkdirSync,writeFileSync}from'fs';import {dirname}from'path';import {resolve}from'node-env-resolver';import'node-env-resolver/
|
|
1
|
+
import {existsSync,readFileSync,mkdirSync,writeFileSync}from'fs';import {dirname}from'path';import {resolve}from'node-env-resolver';import'node-env-resolver/validators';function f(t,r={}){let{clientPrefix:e="VITE_",runtimeProtection:n=true}=r,l=Object.keys(t.client).filter(p=>!p.startsWith(e));if(l.length>0)throw new Error(`\u274C Client environment variables must be prefixed with '${e}': ${l.join(", ")}
|
|
2
2
|
\u{1F4A1} Rename these variables to start with '${e}' (e.g., ${l[0]} \u2192 ${e}${l[0]})`);let s=Object.keys(t.server).filter(p=>p.startsWith(e));if(s.length>0)throw new Error(`\u274C Server environment variables should not be prefixed with '${e}': ${s.join(", ")}
|
|
3
3
|
\u{1F4A1} These variables will be exposed to the client. Move to client schema or remove prefix.`);let a=resolve(t.server),c=resolve(t.client),m=()=>typeof window<"u";return {server:new Proxy(a,{get(p,v){if(n&&m())throw new Error(`\u274C Cannot access server environment variable '${String(v)}' in client-side code.
|
|
4
4
|
\u{1F4A1} Server variables are only available in server context (vite.config.ts, SSR, build scripts).
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"names":["resolve","config","options","clientPrefix","runtimeProtection","incorrectClientKeys","key","incorrectServerKeys","serverResult","nodeEnvResolve","clientResult","isBrowser","target","prop","inferType","definition","v","isOptional","baseType","tsType","def","funcStr","generateTypeDefinitions","clientSchema","lines","nodeEnvResolverPlugin","injectClientEnv","generateTypes","resolveOptions","env","error","define","value","jsonValue","resolvedConfig","typePath","shouldGenerate","existsSync","readFileSync","typeDefinitions","dir","dirname","mkdirSync","writeFileSync"],"mappings":"wKAyFO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CAAkE,EAAC,CAInE,CACA,GAAM,CACJ,YAAA,CAAAC,CAAAA,CAAe,OAAA,CACf,iBAAA,CAAAC,CAAAA,CAAoB,IACtB,CAAA,CAAIF,CAAAA,CAIEG,EADa,MAAA,CAAO,IAAA,CAAKJ,CAAAA,CAAO,MAAM,CAAA,CACL,MAAA,CAAOK,GAAO,CAACA,CAAAA,CAAI,UAAA,CAAWH,CAAY,CAAC,CAAA,CAClF,GAAIE,CAAAA,CAAoB,MAAA,CAAS,CAAA,CAC/B,MAAM,IAAI,KAAA,CACR,CAAA,2D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ACGG,YAAAA,CAAaH,CAAAA,CAAU,OAAO,CAAA,CAEjC,QAAA,CAAS,0CAA0C,CAAA,GACtEC,CAAAA,CAAiB,CAAA,CAAA,CACjB,QAAQ,GAAA,CAAI,CAAA,0CAAA,EAAmCT,CAAa,CAAA,wBAAA,CAA0B,CAAA,CAAA,CAAA,CAItFS,CAAAA,CAAgB,CAClB,IAAMG,CAAAA,CAAkBjB,CAAAA,CAAwBrB,CAAAA,CAAO,MAAM,CAAA,CAGvDuC,CAAAA,CAAMC,OAAAA,CAAQN,CAAQ,CAAA,CACvBE,UAAAA,CAAWG,CAAG,CAAA,EACjBE,SAAAA,CAAUF,CAAAA,CAAK,CAAE,SAAA,CAAW,CAAA,CAAK,CAAC,CAAA,CAGpCG,aAAAA,CAAcR,CAAAA,CAAUI,CAAAA,CAAiB,OAAO,CAAA,CAChD,OAAA,CAAQ,GAAA,CAAI,CAAA,2CAAA,EAAyCZ,CAAa,CAAA,CAAE,EACtE,CACF,CAAA,MAASG,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAA,CAAM,2CAAA,CAAmCA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAAC,EACzG,CAGF,OAAA,CAAQ,GAAA,CAAI,EAAE,EAChB,CACF,CACF,CACF","file":"plugin.js","sourcesContent":["/**\n * node-env-resolver/vite\n * Zero-config Vite integration with automatic client/server split\n *\n * Vite handles .env files via process.env automatically.\n * resolve() is synchronous and works with ALL validator types:\n * - Basic types: string, number, boolean, enums, pattern, custom\n * - Advanced types: postgres, url, email, json, port, etc.\n */\n\nimport { resolve as nodeEnvResolve } from 'node-env-resolver';\nimport type { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';\n\n// Safe resolve result types (Zod-like)\nexport interface SafeResolveResult<T> {\n success: true;\n data: T;\n}\n\nexport interface SafeResolveError {\n success: false;\n error: string;\n}\n\nexport type SafeResolveResultType<T> = SafeResolveResult<T> | SafeResolveError;\n\nexport interface ViteEnvConfig<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema> {\n server: TServer;\n client: TClient;\n}\n\nexport interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {\n /**\n * Prefix for client environment variables\n * @default 'VITE_'\n */\n clientPrefix?: string;\n \n /**\n * Enable variable expansion in .env files\n * @default true\n */\n expandVars?: boolean;\n \n /**\n * Enable runtime protection for server variables in client components\n * @default true\n */\n runtimeProtection?: boolean;\n}\n\n/**\n * Create type-safe environment configuration for Vite with automatic client/server split\n *\n * Vite handles .env files automatically.\n * This function is synchronous and supports ALL validator types:\n * - Basic types: string, number, boolean, enums, pattern, custom\n * - Advanced types: postgres, url, email, json, port, date, etc.\n *\n * @example\n * ```typescript\n * // env.ts\n * import { resolve } from 'node-env-resolver-vite';\n *\n * export const env = resolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173',\n * NODE_ENV: ['development', 'production'] as const\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * VITE_GA_ID: string({optional:true})\n * }\n * });\n *\n * // In server/build code (vite.config.ts, SSR)\n * import { env } from './env';\n *\n * console.log(env.server.DATABASE_URL); // ✅ Works, type: URL\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n *\n * // In browser code\n * console.log(env.server.DATABASE_URL); // ❌ Throws helpful error in dev\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n * ```\n */\nexport function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): {\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n} {\n const {\n clientPrefix = 'VITE_',\n runtimeProtection = true\n } = options;\n\n // Validate client keys have correct prefix\n const clientKeys = Object.keys(config.client);\n const incorrectClientKeys = clientKeys.filter(key => !key.startsWith(clientPrefix));\n if (incorrectClientKeys.length > 0) {\n throw new Error(\n `❌ Client environment variables must be prefixed with '${clientPrefix}': ${incorrectClientKeys.join(', ')}\\n` +\n `💡 Rename these variables to start with '${clientPrefix}' (e.g., ${incorrectClientKeys[0]} → ${clientPrefix}${incorrectClientKeys[0]})`\n );\n }\n\n // Validate server keys don't have client prefix\n const serverKeys = Object.keys(config.server);\n const incorrectServerKeys = serverKeys.filter(key => key.startsWith(clientPrefix));\n if (incorrectServerKeys.length > 0) {\n throw new Error(\n `❌ Server environment variables should not be prefixed with '${clientPrefix}': ${incorrectServerKeys.join(', ')}\\n` +\n `💡 These variables will be exposed to the client. Move to client schema or remove prefix.`\n );\n }\n\n // Use resolve - Vite already handles .env files via process.env, so no custom resolvers needed\n const serverResult = nodeEnvResolve(config.server) as InferSimpleSchema<TServer>;\n const clientResult = nodeEnvResolve(config.client) as InferSimpleSchema<TClient>;\n\n // Create protected environment object with runtime guards\n const isBrowser = () => typeof window !== 'undefined';\n\n const protectedEnv = {\n server: new Proxy(serverResult, {\n get(target, prop) {\n // Runtime protection for server variables in client\n if (runtimeProtection && isBrowser()) {\n throw new Error(\n `❌ Cannot access server environment variable '${String(prop)}' in client-side code.\\n` +\n `💡 Server variables are only available in server context (vite.config.ts, SSR, build scripts).\\n` +\n `💡 If you need this data on the client, consider:\\n` +\n ` - Moving it to the client schema with ${clientPrefix} prefix\\n` +\n ` - Fetching it via an API endpoint\\n` +\n ` - Using SSR to pass data to client components`\n );\n }\n return (target as Record<string, unknown>)[prop as string];\n }\n }),\n client: clientResult\n };\n\n return protectedEnv;\n}\n\n/**\n * Safe version of resolve() - returns result object instead of throwing (Zod-like pattern)\n *\n * Supports all validator types (basic and advanced).\n *\n * @example\n * ```typescript\n * // env.ts\n * import { safeResolve } from 'node-env-resolver-vite';\n *\n * const result = safeResolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173'\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * }\n * });\n *\n * if (result.success) {\n * export const env = result.data;\n * } else {\n * console.error('Environment validation failed:', result.error);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): SafeResolveResultType<{\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n}> {\n try {\n const result = resolve(config, options);\n return { success: true, data: result };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\n// Re-export useful types and utilities\nexport type { SimpleEnvSchema, EnvDefinition } from 'node-env-resolver';\nexport { string, url, port, postgres, email, number, boolean, enums, secret, custom, duration, file, json, stringArray, numberArray, urlArray, http, https, mysql, mongodb, redis, date, timestamp } from 'node-env-resolver/resolvers';\n\n// Utility for runtime environment detection\nexport const isServer = typeof window === 'undefined';\nexport const isClient = !isServer;\n\n","/**\n * Vite plugin for node-env-resolver\n * \n * Validates environment variables at config resolution time and\n * optionally injects validated env vars into Vite's define config.\n */\n\nimport type { Plugin } from 'vite';\nimport { writeFileSync, existsSync, readFileSync } from 'fs';\nimport { dirname } from 'path';\nimport { mkdirSync } from 'fs';\nimport { resolve, type ViteEnvConfig, type ViteOptions } from './index';\nimport type { SimpleEnvSchema } from 'node-env-resolver';\n\nexport interface PluginOptions<_TServer extends SimpleEnvSchema = SimpleEnvSchema, _TClient extends SimpleEnvSchema = SimpleEnvSchema> extends ViteOptions {\n /**\n * Whether to inject client env vars into Vite's define config\n * This makes them available as import.meta.env.VITE_* in the browser\n * @default true\n */\n injectClientEnv?: boolean;\n\n /**\n * Auto-generate TypeScript definitions for import.meta.env\n * Provide a file path (e.g., 'src/vite-env.d.ts') to enable\n * @default undefined (disabled)\n */\n generateTypes?: string;\n}\n\n/**\n * Infer TypeScript type from schema definition\n */\nfunction inferType(definition: unknown): string {\n // Handle literal values (defaults)\n if (typeof definition === 'number') return 'number';\n if (typeof definition === 'boolean') return 'boolean';\n \n // Handle array enums\n if (Array.isArray(definition)) {\n const values = definition.map(v => `'${v}'`).join(' | ');\n return values;\n }\n\n // Handle string type definitions\n if (typeof definition === 'string') {\n // Check if it's a literal default value\n if (!definition.includes(':') && !definition.endsWith('?') && \n !['string', 'number', 'boolean', 'url', 'email', 'postgres', 'mysql', \n 'mongodb', 'redis', 'http', 'https', 'port', 'json', 'date', 'timestamp',\n 'duration', 'file', 'string[]', 'number[]', 'url[]'].includes(definition)) {\n return 'string';\n }\n \n const isOptional = definition.endsWith('?');\n const baseType = definition.replace('?', '').split(':')[0];\n \n let tsType: string;\n if (baseType === 'string' || baseType === 'url' || baseType === 'email' || \n baseType === 'postgres' || baseType === 'mysql' || baseType === 'mongodb' || \n baseType === 'redis' || baseType === 'http' || baseType === 'https' ||\n baseType === 'date' || baseType === 'file') {\n tsType = 'string';\n } else if (baseType === 'number' || baseType === 'port' || baseType === 'timestamp' || baseType === 'duration') {\n tsType = 'number';\n } else if (baseType === 'boolean') {\n tsType = 'boolean';\n } else if (baseType === 'json') {\n tsType = 'unknown';\n } else if (baseType === 'string[]') {\n tsType = 'string[]';\n } else if (baseType === 'number[]') {\n tsType = 'number[]';\n } else if (baseType === 'url[]') {\n tsType = 'string[]';\n } else {\n tsType = 'string';\n }\n \n return isOptional ? `${tsType} | undefined` : tsType;\n }\n\n // Handle object form\n if (typeof definition === 'object' && definition !== null && 'type' in definition) {\n const def = definition as { type: string; optional?: boolean };\n const baseType = def.type.replace('?', '');\n let tsType: string;\n \n if (['string', 'url', 'email', 'postgres', 'mysql', 'mongodb', 'redis', 'http', 'https', 'date', 'file'].includes(baseType)) {\n tsType = 'string';\n } else if (['number', 'port', 'timestamp', 'duration'].includes(baseType)) {\n tsType = 'number';\n } else if (baseType === 'boolean') {\n tsType = 'boolean';\n } else if (baseType === 'json') {\n tsType = 'unknown';\n } else if (baseType === 'string[]') {\n tsType = 'string[]';\n } else if (baseType === 'number[]') {\n tsType = 'number[]';\n } else {\n tsType = 'string';\n }\n \n return def.optional ? `${tsType} | undefined` : tsType;\n }\n\n // Handle custom validator functions\n if (typeof definition === 'function') {\n const func = definition as unknown as Record<string, unknown>;\n const isOptional = func.optional === true;\n \n // Try to infer type from function name or return type\n const funcStr = definition.toString();\n \n let tsType = 'string'; // Default\n \n // Check if it's a typed validator by checking the function body or attached metadata\n if (funcStr.includes('parseFloat') || funcStr.includes('parseInt') || funcStr.includes('Number(')) {\n tsType = 'number';\n } else if (funcStr.includes('Boolean') || funcStr.includes('=== \\'true\\'')) {\n tsType = 'boolean';\n } else if (funcStr.includes('JSON.parse')) {\n tsType = 'unknown';\n } else if (funcStr.includes('Array.isArray')) {\n tsType = 'string[]';\n }\n \n return isOptional ? `${tsType} | undefined` : tsType;\n }\n\n return 'string';\n}\n\n/**\n * Generate TypeScript definition file content\n */\nfunction generateTypeDefinitions(clientSchema: SimpleEnvSchema): string {\n const lines: string[] = [\n '/// <reference types=\"vite/client\" />',\n '',\n '/**',\n ' * Auto-generated by node-env-resolver-vite',\n ' * DO NOT EDIT MANUALLY - Changes will be overwritten',\n ' */',\n '',\n 'interface ImportMetaEnv {'\n ];\n\n // Generate interface properties\n for (const [key, definition] of Object.entries(clientSchema)) {\n const tsType = inferType(definition);\n const readonly = ' readonly ';\n lines.push(`${readonly}${key}: ${tsType}`);\n }\n\n lines.push('}');\n lines.push('');\n lines.push('interface ImportMeta {');\n lines.push(' readonly env: ImportMetaEnv');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Vite plugin for environment variable validation and injection\n * \n * @example\n * ```typescript\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { nodeEnvResolverPlugin } from 'node-env-resolver-vite/plugin';\n *\n * export default defineConfig({\n * plugins: [\n * nodeEnvResolverPlugin({\n * server: {\n * DATABASE_URL: postgres(),\n * API_SECRET: string(),\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * },\n * generateTypes: 'src/vite-env.d.ts' // Auto-generate types!\n * })\n * ]\n * });\n * ```\n */\nexport function nodeEnvResolverPlugin<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: PluginOptions<TServer, TClient> = {}\n): Plugin {\n const {\n injectClientEnv = true,\n generateTypes,\n ...resolveOptions\n } = options;\n\n let env: ReturnType<typeof resolve<TServer, TClient>>;\n\n return {\n name: 'node-env-resolver-vite',\n \n // Validate environment variables early in the config resolution\n config() {\n try {\n // Resolve and validate env vars\n env = resolve(config, resolveOptions);\n \n // Log validation success\n console.log('✅ Environment variables validated successfully');\n } catch (error) {\n // Throw to prevent Vite from starting with invalid config\n console.error('❌ Environment validation failed:');\n throw error;\n }\n\n // Inject client env vars into Vite's define if enabled\n if (injectClientEnv) {\n const define: Record<string, string> = {};\n \n for (const [key, value] of Object.entries(env.client)) {\n // Convert values to JSON strings for Vite's define\n const jsonValue = JSON.stringify(value);\n define[`import.meta.env.${key}`] = jsonValue;\n }\n\n return {\n define\n };\n }\n },\n\n configResolved(resolvedConfig) {\n // Log environment info in dev mode\n if (resolvedConfig.command === 'serve' && resolvedConfig.mode === 'development') {\n console.log('\\n📦 Environment Configuration:');\n console.log(` • Mode: ${resolvedConfig.mode}`);\n console.log(` • Server vars: ${Object.keys(config.server).length}`);\n console.log(` • Client vars: ${Object.keys(config.client).length}`);\n \n // Generate TypeScript definitions if requested\n if (generateTypes) {\n try {\n const typePath = generateTypes.startsWith('/') \n ? generateTypes \n : `${resolvedConfig.root}/${generateTypes}`;\n \n // Check if file exists and contains custom content\n let shouldGenerate = true;\n if (existsSync(typePath)) {\n const existingContent = readFileSync(typePath, 'utf-8');\n // Only regenerate if it's our auto-generated file\n if (!existingContent.includes('Auto-generated by node-env-resolver-vite')) {\n shouldGenerate = false;\n console.log(` ⚠️ Skipping type generation: ${generateTypes} contains custom content`);\n }\n }\n \n if (shouldGenerate) {\n const typeDefinitions = generateTypeDefinitions(config.client);\n \n // Ensure directory exists\n const dir = dirname(typePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n \n writeFileSync(typePath, typeDefinitions, 'utf-8');\n console.log(` ✅ Generated TypeScript definitions: ${generateTypes}`);\n }\n } catch (error) {\n console.error(' ⚠️ Failed to generate types:', error instanceof Error ? error.message : String(error));\n }\n }\n \n console.log('');\n }\n }\n };\n}\n\n/**\n * Type-only export for plugin configuration\n */\nexport type { ViteEnvConfig, ViteOptions };\n\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"names":["resolve","config","options","clientPrefix","runtimeProtection","incorrectClientKeys","key","incorrectServerKeys","serverResult","nodeEnvResolve","clientResult","isBrowser","target","prop","inferType","definition","v","isOptional","baseType","tsType","def","funcStr","generateTypeDefinitions","clientSchema","lines","nodeEnvResolverPlugin","injectClientEnv","generateTypes","resolveOptions","env","error","define","value","jsonValue","resolvedConfig","typePath","shouldGenerate","existsSync","readFileSync","typeDefinitions","dir","dirname","mkdirSync","writeFileSync"],"mappings":"yKAuHO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CAAkE,EAAC,CAInE,CACA,GAAM,CACJ,YAAA,CAAAC,CAAAA,CAAe,OAAA,CACf,iBAAA,CAAAC,CAAAA,CAAoB,IACtB,CAAA,CAAIF,CAAAA,CAIEG,EADa,MAAA,CAAO,IAAA,CAAKJ,CAAAA,CAAO,MAAM,CAAA,CACL,MAAA,CAAOK,GAAO,CAACA,CAAAA,CAAI,UAAA,CAAWH,CAAY,CAAC,CAAA,CAClF,GAAIE,CAAAA,CAAoB,MAAA,CAAS,CAAA,CAC/B,MAAM,IAAI,KAAA,CACR,CAAA,2DAAA,EAAyDF,CAAY,CAAA,GAAA,EAAME,CAAAA,CAAoB,IAAA,CAAK,IAAI,CAAC;AAAA,gDAAA,EAC7DF,CAAY,CAAA,SAAA,EAAYE,CAAAA,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CAAI,CAAA,0CAAA,EAAmCT,CAAa,CAAA,wBAAA,CAA0B,CAAA,CAAA,CAAA,CAItFS,CAAAA,CAAgB,CAClB,IAAMG,CAAAA,CAAkBjB,CAAAA,CAAwBrB,CAAAA,CAAO,MAAM,CAAA,CAGvDuC,CAAAA,CAAMC,OAAAA,CAAQN,CAAQ,CAAA,CACvBE,UAAAA,CAAWG,CAAG,CAAA,EACjBE,SAAAA,CAAUF,CAAAA,CAAK,CAAE,SAAA,CAAW,CAAA,CAAK,CAAC,CAAA,CAGpCG,aAAAA,CAAcR,CAAAA,CAAUI,CAAAA,CAAiB,OAAO,CAAA,CAChD,OAAA,CAAQ,GAAA,CAAI,CAAA,2CAAA,EAAyCZ,CAAa,CAAA,CAAE,EACtE,CACF,CAAA,MAASG,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAA,CAAM,2CAAA,CAAmCA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAAC,EACzG,CAGF,OAAA,CAAQ,GAAA,CAAI,EAAE,EAChB,CACF,CACF,CACF","file":"plugin.js","sourcesContent":["/**\n * node-env-resolver/vite\n * Zero-config Vite integration with automatic client/server split\n *\n * Vite handles .env files via process.env automatically.\n * resolve() is synchronous and works with ALL validator types:\n * - Basic types: string, number, boolean, oneOf, pattern, custom\n * - Advanced types: postgres, url, email, json, port, etc.\n */\n\nimport { resolve as nodeEnvResolve } from 'node-env-resolver';\nimport type { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';\n\n// Re-export all validators for convenience\nexport {\n string,\n url,\n port,\n postgres,\n email,\n number,\n boolean,\n oneOf,\n secret,\n custom,\n duration,\n file,\n json,\n stringArray,\n numberArray,\n urlArray,\n http,\n https,\n mysql,\n mongodb,\n redis,\n date,\n timestamp,\n} from 'node-env-resolver/validators';\n\n// Re-export useful types\nexport type { EnvDefinition } from 'node-env-resolver';\n\n// Safe resolve result types (Zod-like)\nexport interface SafeResolveResult<T> {\n success: true;\n data: T;\n}\n\nexport interface SafeResolveError {\n success: false;\n error: string;\n}\n\nexport type SafeResolveResultType<T> = SafeResolveResult<T> | SafeResolveError;\n\nexport interface ViteEnvConfig<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema> {\n server: TServer;\n client: TClient;\n}\n\nexport interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {\n /**\n * Prefix for client environment variables\n * @default 'VITE_'\n */\n clientPrefix?: string;\n \n /**\n * Enable variable expansion in .env files\n * @default true\n */\n expandVars?: boolean;\n \n /**\n * Enable runtime protection for server variables in client components\n * @default true\n */\n runtimeProtection?: boolean;\n}\n\n/**\n * Create type-safe environment configuration for Vite with automatic client/server split\n *\n * Vite handles .env files automatically.\n * This function is synchronous and supports ALL validator types:\n * - Basic types: string, number, boolean, oneOf, pattern, custom\n * - Advanced types: postgres, url, email, json, port, date, etc.\n *\n * @example\n * ```typescript\n * // env.ts\n * import { resolve } from 'node-env-resolver-vite';\n *\n * export const env = resolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173',\n * NODE_ENV: ['development', 'production'] as const\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * VITE_GA_ID: string({optional:true})\n * }\n * });\n *\n * // In server/build code (vite.config.ts, SSR)\n * import { env } from './env';\n *\n * console.log(env.server.DATABASE_URL); // ✅ Works, type: URL\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n *\n * // In browser code\n * console.log(env.server.DATABASE_URL); // ❌ Throws helpful error in dev\n * console.log(env.client.VITE_API_URL); // ✅ Works, type: URL\n * ```\n */\nexport function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): {\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n} {\n const {\n clientPrefix = 'VITE_',\n runtimeProtection = true\n } = options;\n\n // Validate client keys have correct prefix\n const clientKeys = Object.keys(config.client);\n const incorrectClientKeys = clientKeys.filter(key => !key.startsWith(clientPrefix));\n if (incorrectClientKeys.length > 0) {\n throw new Error(\n `❌ Client environment variables must be prefixed with '${clientPrefix}': ${incorrectClientKeys.join(', ')}\\n` +\n `💡 Rename these variables to start with '${clientPrefix}' (e.g., ${incorrectClientKeys[0]} → ${clientPrefix}${incorrectClientKeys[0]})`\n );\n }\n\n // Validate server keys don't have client prefix\n const serverKeys = Object.keys(config.server);\n const incorrectServerKeys = serverKeys.filter(key => key.startsWith(clientPrefix));\n if (incorrectServerKeys.length > 0) {\n throw new Error(\n `❌ Server environment variables should not be prefixed with '${clientPrefix}': ${incorrectServerKeys.join(', ')}\\n` +\n `💡 These variables will be exposed to the client. Move to client schema or remove prefix.`\n );\n }\n\n // Use resolve - Vite already handles .env files via process.env, so no custom resolvers needed\n const serverResult = nodeEnvResolve(config.server) as InferSimpleSchema<TServer>;\n const clientResult = nodeEnvResolve(config.client) as InferSimpleSchema<TClient>;\n\n // Create protected environment object with runtime guards\n const isBrowser = () => typeof window !== 'undefined';\n\n const protectedEnv = {\n server: new Proxy(serverResult, {\n get(target, prop) {\n // Runtime protection for server variables in client\n if (runtimeProtection && isBrowser()) {\n throw new Error(\n `❌ Cannot access server environment variable '${String(prop)}' in client-side code.\\n` +\n `💡 Server variables are only available in server context (vite.config.ts, SSR, build scripts).\\n` +\n `💡 If you need this data on the client, consider:\\n` +\n ` - Moving it to the client schema with ${clientPrefix} prefix\\n` +\n ` - Fetching it via an API endpoint\\n` +\n ` - Using SSR to pass data to client components`\n );\n }\n return (target as Record<string, unknown>)[prop as string];\n }\n }),\n client: clientResult\n };\n\n return protectedEnv;\n}\n\n/**\n * Safe version of resolve() - returns result object instead of throwing (Zod-like pattern)\n *\n * Supports all validator types (basic and advanced).\n *\n * @example\n * ```typescript\n * // env.ts\n * import { safeResolve } from 'node-env-resolver-vite';\n *\n * const result = safeResolve({\n * server: {\n * DATABASE_URL: url(),\n * API_SECRET: string(),\n * PORT: 'port:5173'\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * }\n * });\n *\n * if (result.success) {\n * export const env = result.data;\n * } else {\n * console.error('Environment validation failed:', result.error);\n * process.exit(1);\n * }\n * ```\n */\nexport function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'resolvers'> & { resolvers?: never } = {}\n): SafeResolveResultType<{\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n}> {\n try {\n const result = resolve(config, options);\n return { success: true, data: result };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\n// Utility for runtime environment detection\nexport const isServer = typeof window === 'undefined';\nexport const isClient = !isServer;\n\n","/**\n * Vite plugin for node-env-resolver\n * \n * Validates environment variables at config resolution time and\n * optionally injects validated env vars into Vite's define config.\n */\n\nimport type { Plugin } from 'vite';\nimport { writeFileSync, existsSync, readFileSync } from 'fs';\nimport { dirname } from 'path';\nimport { mkdirSync } from 'fs';\nimport { resolve, type ViteEnvConfig, type ViteOptions } from './index';\nimport type { SimpleEnvSchema } from 'node-env-resolver';\n\nexport interface PluginOptions<_TServer extends SimpleEnvSchema = SimpleEnvSchema, _TClient extends SimpleEnvSchema = SimpleEnvSchema> extends ViteOptions {\n /**\n * Whether to inject client env vars into Vite's define config\n * This makes them available as import.meta.env.VITE_* in the browser\n * @default true\n */\n injectClientEnv?: boolean;\n\n /**\n * Auto-generate TypeScript definitions for import.meta.env\n * Provide a file path (e.g., 'src/vite-env.d.ts') to enable\n * @default undefined (disabled)\n */\n generateTypes?: string;\n}\n\n/**\n * Infer TypeScript type from schema definition\n */\nfunction inferType(definition: unknown): string {\n // Handle literal values (defaults)\n if (typeof definition === 'number') return 'number';\n if (typeof definition === 'boolean') return 'boolean';\n \n // Handle array oneOf\n if (Array.isArray(definition)) {\n const values = definition.map(v => `'${v}'`).join(' | ');\n return values;\n }\n\n // Handle string type definitions\n if (typeof definition === 'string') {\n // Check if it's a literal default value\n if (!definition.includes(':') && !definition.endsWith('?') && \n !['string', 'number', 'boolean', 'url', 'email', 'postgres', 'mysql', \n 'mongodb', 'redis', 'http', 'https', 'port', 'json', 'date', 'timestamp',\n 'duration', 'file', 'string[]', 'number[]', 'url[]'].includes(definition)) {\n return 'string';\n }\n \n const isOptional = definition.endsWith('?');\n const baseType = definition.replace('?', '').split(':')[0];\n \n let tsType: string;\n if (baseType === 'string' || baseType === 'url' || baseType === 'email' || \n baseType === 'postgres' || baseType === 'mysql' || baseType === 'mongodb' || \n baseType === 'redis' || baseType === 'http' || baseType === 'https' ||\n baseType === 'date' || baseType === 'file') {\n tsType = 'string';\n } else if (baseType === 'number' || baseType === 'port' || baseType === 'timestamp' || baseType === 'duration') {\n tsType = 'number';\n } else if (baseType === 'boolean') {\n tsType = 'boolean';\n } else if (baseType === 'json') {\n tsType = 'unknown';\n } else if (baseType === 'string[]') {\n tsType = 'string[]';\n } else if (baseType === 'number[]') {\n tsType = 'number[]';\n } else if (baseType === 'url[]') {\n tsType = 'string[]';\n } else {\n tsType = 'string';\n }\n \n return isOptional ? `${tsType} | undefined` : tsType;\n }\n\n // Handle object form\n if (typeof definition === 'object' && definition !== null && 'type' in definition) {\n const def = definition as { type: string; optional?: boolean };\n const baseType = def.type.replace('?', '');\n let tsType: string;\n \n if (['string', 'url', 'email', 'postgres', 'mysql', 'mongodb', 'redis', 'http', 'https', 'date', 'file'].includes(baseType)) {\n tsType = 'string';\n } else if (['number', 'port', 'timestamp', 'duration'].includes(baseType)) {\n tsType = 'number';\n } else if (baseType === 'boolean') {\n tsType = 'boolean';\n } else if (baseType === 'json') {\n tsType = 'unknown';\n } else if (baseType === 'string[]') {\n tsType = 'string[]';\n } else if (baseType === 'number[]') {\n tsType = 'number[]';\n } else {\n tsType = 'string';\n }\n \n return def.optional ? `${tsType} | undefined` : tsType;\n }\n\n // Handle custom validator functions\n if (typeof definition === 'function') {\n const func = definition as unknown as Record<string, unknown>;\n const isOptional = func.optional === true;\n \n // Try to infer type from function name or return type\n const funcStr = definition.toString();\n \n let tsType = 'string'; // Default\n \n // Check if it's a typed validator by checking the function body or attached metadata\n if (funcStr.includes('parseFloat') || funcStr.includes('parseInt') || funcStr.includes('Number(')) {\n tsType = 'number';\n } else if (funcStr.includes('Boolean') || funcStr.includes('=== \\'true\\'')) {\n tsType = 'boolean';\n } else if (funcStr.includes('JSON.parse')) {\n tsType = 'unknown';\n } else if (funcStr.includes('Array.isArray')) {\n tsType = 'string[]';\n }\n \n return isOptional ? `${tsType} | undefined` : tsType;\n }\n\n return 'string';\n}\n\n/**\n * Generate TypeScript definition file content\n */\nfunction generateTypeDefinitions(clientSchema: SimpleEnvSchema): string {\n const lines: string[] = [\n '/// <reference types=\"vite/client\" />',\n '',\n '/**',\n ' * Auto-generated by node-env-resolver-vite',\n ' * DO NOT EDIT MANUALLY - Changes will be overwritten',\n ' */',\n '',\n 'interface ImportMetaEnv {'\n ];\n\n // Generate interface properties\n for (const [key, definition] of Object.entries(clientSchema)) {\n const tsType = inferType(definition);\n const readonly = ' readonly ';\n lines.push(`${readonly}${key}: ${tsType}`);\n }\n\n lines.push('}');\n lines.push('');\n lines.push('interface ImportMeta {');\n lines.push(' readonly env: ImportMetaEnv');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Vite plugin for environment variable validation and injection\n * \n * @example\n * ```typescript\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { nodeEnvResolverPlugin } from 'node-env-resolver-vite/plugin';\n *\n * export default defineConfig({\n * plugins: [\n * nodeEnvResolverPlugin({\n * server: {\n * DATABASE_URL: postgres(),\n * API_SECRET: string(),\n * },\n * client: {\n * VITE_API_URL: url(),\n * VITE_ENABLE_ANALYTICS: false,\n * },\n * generateTypes: 'src/vite-env.d.ts' // Auto-generate types!\n * })\n * ]\n * });\n * ```\n */\nexport function nodeEnvResolverPlugin<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: PluginOptions<TServer, TClient> = {}\n): Plugin {\n const {\n injectClientEnv = true,\n generateTypes,\n ...resolveOptions\n } = options;\n\n let env: ReturnType<typeof resolve<TServer, TClient>>;\n\n return {\n name: 'node-env-resolver-vite',\n \n // Validate environment variables early in the config resolution\n config() {\n try {\n // Resolve and validate env vars\n env = resolve(config, resolveOptions);\n \n // Log validation success\n console.log('✅ Environment variables validated successfully');\n } catch (error) {\n // Throw to prevent Vite from starting with invalid config\n console.error('❌ Environment validation failed:');\n throw error;\n }\n\n // Inject client env vars into Vite's define if enabled\n if (injectClientEnv) {\n const define: Record<string, string> = {};\n \n for (const [key, value] of Object.entries(env.client)) {\n // Convert values to JSON strings for Vite's define\n const jsonValue = JSON.stringify(value);\n define[`import.meta.env.${key}`] = jsonValue;\n }\n\n return {\n define\n };\n }\n },\n\n configResolved(resolvedConfig) {\n // Log environment info in dev mode\n if (resolvedConfig.command === 'serve' && resolvedConfig.mode === 'development') {\n console.log('\\n📦 Environment Configuration:');\n console.log(` • Mode: ${resolvedConfig.mode}`);\n console.log(` • Server vars: ${Object.keys(config.server).length}`);\n console.log(` • Client vars: ${Object.keys(config.client).length}`);\n \n // Generate TypeScript definitions if requested\n if (generateTypes) {\n try {\n const typePath = generateTypes.startsWith('/') \n ? generateTypes \n : `${resolvedConfig.root}/${generateTypes}`;\n \n // Check if file exists and contains custom content\n let shouldGenerate = true;\n if (existsSync(typePath)) {\n const existingContent = readFileSync(typePath, 'utf-8');\n // Only regenerate if it's our auto-generated file\n if (!existingContent.includes('Auto-generated by node-env-resolver-vite')) {\n shouldGenerate = false;\n console.log(` ⚠️ Skipping type generation: ${generateTypes} contains custom content`);\n }\n }\n \n if (shouldGenerate) {\n const typeDefinitions = generateTypeDefinitions(config.client);\n \n // Ensure directory exists\n const dir = dirname(typePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n \n writeFileSync(typePath, typeDefinitions, 'utf-8');\n console.log(` ✅ Generated TypeScript definitions: ${generateTypes}`);\n }\n } catch (error) {\n console.error(' ⚠️ Failed to generate types:', error instanceof Error ? error.message : String(error));\n }\n }\n \n console.log('');\n }\n }\n };\n}\n\n/**\n * Type-only export for plugin configuration\n */\nexport type { ViteEnvConfig, ViteOptions };\n\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-env-resolver-vite",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "Zero-config Vite integration for node-env-resolver with client/server split",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
}
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"node-env-resolver": "
|
|
55
|
+
"node-env-resolver": "6.0.1"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@types/node": "^24.7.2",
|