node-env-resolver-vite 2.4.2 → 2.4.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/README.md +116 -78
- package/dist/index.d.ts +11 -94
- package/dist/index.js +1 -8
- package/dist/index.js.map +1 -1
- package/dist/plugin.d.ts +0 -2
- package/dist/plugin.js +3 -10
- package/dist/plugin.js.map +1 -1
- package/package.json +9 -9
- package/binding.gyp +0 -9
- package/index.js +0 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Vite integration with automatic client/server environment variable splitting.
|
|
|
10
10
|
- ✅ Runtime protection to prevent leaking server vars to client
|
|
11
11
|
- ✅ Full TypeScript support with IntelliSense
|
|
12
12
|
- ✅ **Auto-generate TypeScript definitions** for `import.meta.env`
|
|
13
|
-
- ✅ Works with Vite 4.x, 5.x, 6.x,
|
|
13
|
+
- ✅ Works with Vite 4.x, 5.x, 6.x, 7.x, 8.x
|
|
14
14
|
- ✅ Framework agnostic (Vue, React, Svelte, Solid, Astro)
|
|
15
15
|
- ✅ Zero configuration required
|
|
16
16
|
- ✅ Supports all validator types (basic and advanced)
|
|
@@ -42,8 +42,8 @@ export const env = resolve({
|
|
|
42
42
|
client: {
|
|
43
43
|
VITE_API_URL: url(),
|
|
44
44
|
VITE_ENABLE_ANALYTICS: false,
|
|
45
|
-
VITE_GA_ID: string({optional:true}),
|
|
46
|
-
}
|
|
45
|
+
VITE_GA_ID: string({ optional: true }),
|
|
46
|
+
},
|
|
47
47
|
});
|
|
48
48
|
```
|
|
49
49
|
|
|
@@ -53,16 +53,16 @@ Use in your app:
|
|
|
53
53
|
// Server code (vite.config.ts, SSR, Node.js)
|
|
54
54
|
import { env } from './env';
|
|
55
55
|
|
|
56
|
-
console.log(env.server.DATABASE_URL);
|
|
57
|
-
console.log(env.client.VITE_API_URL);
|
|
56
|
+
console.log(env.server.DATABASE_URL); // ✅ Works
|
|
57
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
58
58
|
```
|
|
59
59
|
|
|
60
60
|
```typescript
|
|
61
61
|
// Client code (browser)
|
|
62
62
|
import { env } from './env';
|
|
63
63
|
|
|
64
|
-
console.log(env.client.VITE_API_URL);
|
|
65
|
-
console.log(env.server.DATABASE_URL);
|
|
64
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
65
|
+
console.log(env.server.DATABASE_URL); // ❌ Throws error
|
|
66
66
|
```
|
|
67
67
|
|
|
68
68
|
## Safe Resolve (Zod-like Pattern)
|
|
@@ -80,7 +80,7 @@ export const env = resolve({
|
|
|
80
80
|
},
|
|
81
81
|
client: {
|
|
82
82
|
VITE_API_URL: url(),
|
|
83
|
-
}
|
|
83
|
+
},
|
|
84
84
|
});
|
|
85
85
|
|
|
86
86
|
// ✅ Returns result object (like Zod's safeParse())
|
|
@@ -91,7 +91,7 @@ const result = safeResolve({
|
|
|
91
91
|
},
|
|
92
92
|
client: {
|
|
93
93
|
VITE_API_URL: url(),
|
|
94
|
-
}
|
|
94
|
+
},
|
|
95
95
|
});
|
|
96
96
|
|
|
97
97
|
if (result.success) {
|
|
@@ -104,6 +104,7 @@ if (result.success) {
|
|
|
104
104
|
```
|
|
105
105
|
|
|
106
106
|
**Use cases:**
|
|
107
|
+
|
|
107
108
|
- `resolve()` - Throws on error (simpler, fail-fast)
|
|
108
109
|
- `safeResolve()` - Returns `{ success, data?, error? }` (graceful error handling)
|
|
109
110
|
|
|
@@ -144,29 +145,29 @@ export const env = resolve({
|
|
|
144
145
|
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
145
146
|
API_KEY: string(),
|
|
146
147
|
MAX_CONNECTIONS: 'number',
|
|
147
|
-
TIMEOUT: 'duration',
|
|
148
|
+
TIMEOUT: 'duration', // e.g., '30s', '5m'
|
|
148
149
|
},
|
|
149
150
|
client: {
|
|
150
151
|
VITE_API_URL: url(),
|
|
151
152
|
VITE_ENABLE_ANALYTICS: false,
|
|
152
|
-
VITE_GA_ID: string({optional:true}),
|
|
153
|
-
VITE_FEATURE_FLAGS: 'string[]',
|
|
154
|
-
}
|
|
153
|
+
VITE_GA_ID: string({ optional: true }),
|
|
154
|
+
VITE_FEATURE_FLAGS: 'string[]', // Comma-separated
|
|
155
|
+
},
|
|
155
156
|
});
|
|
156
157
|
```
|
|
157
158
|
|
|
158
159
|
TypeScript knows all the types:
|
|
159
160
|
|
|
160
161
|
```typescript
|
|
161
|
-
env.server.PORT;
|
|
162
|
-
env.server.DATABASE_URL;
|
|
163
|
-
env.server.NODE_ENV;
|
|
164
|
-
env.server.MAX_CONNECTIONS;
|
|
165
|
-
env.server.TIMEOUT;
|
|
166
|
-
env.client.VITE_API_URL;
|
|
167
|
-
env.client.VITE_ENABLE_ANALYTICS;
|
|
168
|
-
env.client.VITE_GA_ID;
|
|
169
|
-
env.client.VITE_FEATURE_FLAGS;
|
|
162
|
+
env.server.PORT; // number
|
|
163
|
+
env.server.DATABASE_URL; // string
|
|
164
|
+
env.server.NODE_ENV; // 'development' | 'production' | 'test'
|
|
165
|
+
env.server.MAX_CONNECTIONS; // number
|
|
166
|
+
env.server.TIMEOUT; // number (milliseconds)
|
|
167
|
+
env.client.VITE_API_URL; // string
|
|
168
|
+
env.client.VITE_ENABLE_ANALYTICS; // boolean
|
|
169
|
+
env.client.VITE_GA_ID; // string | undefined
|
|
170
|
+
env.client.VITE_FEATURE_FLAGS; // string[]
|
|
170
171
|
```
|
|
171
172
|
|
|
172
173
|
## Runtime Protection
|
|
@@ -188,6 +189,24 @@ console.log(env.server.DATABASE_URL);
|
|
|
188
189
|
|
|
189
190
|
This protection works in both development and production.
|
|
190
191
|
|
|
192
|
+
You can disable runtime protection if needed:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
export const env = resolve(
|
|
196
|
+
{
|
|
197
|
+
server: {
|
|
198
|
+
DATABASE_URL: postgres(),
|
|
199
|
+
},
|
|
200
|
+
client: {
|
|
201
|
+
VITE_API_URL: url(),
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
runtimeProtection: false, // Disable server var protection
|
|
206
|
+
}
|
|
207
|
+
);
|
|
208
|
+
```
|
|
209
|
+
|
|
191
210
|
## TypeScript IntelliSense
|
|
192
211
|
|
|
193
212
|
### Auto-Generate Types (Recommended)
|
|
@@ -209,11 +228,11 @@ export default defineConfig({
|
|
|
209
228
|
client: {
|
|
210
229
|
VITE_API_URL: url(),
|
|
211
230
|
VITE_ENABLE_ANALYTICS: false,
|
|
212
|
-
VITE_GA_ID: string({optional:true}),
|
|
231
|
+
VITE_GA_ID: string({ optional: true }),
|
|
213
232
|
},
|
|
214
|
-
generateTypes: 'src/vite-env.d.ts'
|
|
215
|
-
})
|
|
216
|
-
]
|
|
233
|
+
generateTypes: 'src/vite-env.d.ts', // ✨ Auto-generates types!
|
|
234
|
+
}),
|
|
235
|
+
],
|
|
217
236
|
});
|
|
218
237
|
```
|
|
219
238
|
|
|
@@ -228,17 +247,18 @@ This automatically generates `src/vite-env.d.ts` with proper TypeScript types:
|
|
|
228
247
|
*/
|
|
229
248
|
|
|
230
249
|
interface ImportMetaEnv {
|
|
231
|
-
readonly VITE_API_URL: string
|
|
232
|
-
readonly VITE_ENABLE_ANALYTICS: boolean
|
|
233
|
-
readonly VITE_GA_ID: string | undefined
|
|
250
|
+
readonly VITE_API_URL: string;
|
|
251
|
+
readonly VITE_ENABLE_ANALYTICS: boolean;
|
|
252
|
+
readonly VITE_GA_ID: string | undefined;
|
|
234
253
|
}
|
|
235
254
|
|
|
236
255
|
interface ImportMeta {
|
|
237
|
-
readonly env: ImportMetaEnv
|
|
256
|
+
readonly env: ImportMetaEnv;
|
|
238
257
|
}
|
|
239
258
|
```
|
|
240
259
|
|
|
241
260
|
**Features:**
|
|
261
|
+
|
|
242
262
|
- ✅ Types auto-update when you change your schema
|
|
243
263
|
- ✅ Proper type inference (url → string, false → boolean, etc.)
|
|
244
264
|
- ✅ Won't overwrite files with custom content
|
|
@@ -252,13 +272,13 @@ You can also manually create `vite-env.d.ts`:
|
|
|
252
272
|
/// <reference types="vite/client" />
|
|
253
273
|
|
|
254
274
|
interface ImportMetaEnv {
|
|
255
|
-
readonly VITE_API_URL: string
|
|
256
|
-
readonly VITE_ENABLE_ANALYTICS: boolean
|
|
257
|
-
readonly VITE_GA_ID?: string
|
|
275
|
+
readonly VITE_API_URL: string;
|
|
276
|
+
readonly VITE_ENABLE_ANALYTICS: boolean;
|
|
277
|
+
readonly VITE_GA_ID?: string;
|
|
258
278
|
}
|
|
259
279
|
|
|
260
280
|
interface ImportMeta {
|
|
261
|
-
readonly env: ImportMetaEnv
|
|
281
|
+
readonly env: ImportMetaEnv;
|
|
262
282
|
}
|
|
263
283
|
```
|
|
264
284
|
|
|
@@ -285,13 +305,14 @@ export default defineConfig({
|
|
|
285
305
|
VITE_ENABLE_ANALYTICS: false,
|
|
286
306
|
},
|
|
287
307
|
// Auto-generate TypeScript definitions (optional)
|
|
288
|
-
generateTypes: 'src/vite-env.d.ts'
|
|
289
|
-
})
|
|
290
|
-
]
|
|
308
|
+
generateTypes: 'src/vite-env.d.ts',
|
|
309
|
+
}),
|
|
310
|
+
],
|
|
291
311
|
});
|
|
292
312
|
```
|
|
293
313
|
|
|
294
314
|
**Plugin Features:**
|
|
315
|
+
|
|
295
316
|
- ✅ Validates env vars at config resolution time
|
|
296
317
|
- ✅ Fails fast if validation errors occur
|
|
297
318
|
- ✅ Logs validation status
|
|
@@ -301,14 +322,21 @@ export default defineConfig({
|
|
|
301
322
|
## Options
|
|
302
323
|
|
|
303
324
|
```typescript
|
|
304
|
-
export const env = resolve(
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}
|
|
325
|
+
export const env = resolve(
|
|
326
|
+
{
|
|
327
|
+
server: {
|
|
328
|
+
/* ... */
|
|
329
|
+
},
|
|
330
|
+
client: {
|
|
331
|
+
/* ... */
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
clientPrefix: 'VITE_', // Default prefix
|
|
336
|
+
runtimeProtection: true, // Enable runtime checks (default: true)
|
|
337
|
+
expandVars: true, // Enable ${VAR} expansion (default: true)
|
|
338
|
+
}
|
|
339
|
+
);
|
|
312
340
|
```
|
|
313
341
|
|
|
314
342
|
## Framework Examples
|
|
@@ -365,16 +393,19 @@ import { env } from './env';
|
|
|
365
393
|
// env.ts
|
|
366
394
|
import { resolve } from 'node-env-resolver-vite';
|
|
367
395
|
|
|
368
|
-
export const env = resolve(
|
|
369
|
-
|
|
370
|
-
|
|
396
|
+
export const env = resolve(
|
|
397
|
+
{
|
|
398
|
+
server: {
|
|
399
|
+
DATABASE_URL: postgres(),
|
|
400
|
+
},
|
|
401
|
+
client: {
|
|
402
|
+
VITE_PUBLIC_API_URL: url(),
|
|
403
|
+
},
|
|
371
404
|
},
|
|
372
|
-
|
|
373
|
-
|
|
405
|
+
{
|
|
406
|
+
clientPrefix: 'VITE_PUBLIC_', // SvelteKit uses PUBLIC_ internally
|
|
374
407
|
}
|
|
375
|
-
|
|
376
|
-
clientPrefix: 'VITE_PUBLIC_' // SvelteKit uses PUBLIC_ internally
|
|
377
|
-
});
|
|
408
|
+
);
|
|
378
409
|
```
|
|
379
410
|
|
|
380
411
|
### Solid + Vite
|
|
@@ -404,16 +435,19 @@ function App() {
|
|
|
404
435
|
// env.ts
|
|
405
436
|
import { resolve } from 'node-env-resolver-vite';
|
|
406
437
|
|
|
407
|
-
export const env = resolve(
|
|
408
|
-
|
|
409
|
-
|
|
438
|
+
export const env = resolve(
|
|
439
|
+
{
|
|
440
|
+
server: {
|
|
441
|
+
DATABASE_URL: postgres(),
|
|
442
|
+
},
|
|
443
|
+
client: {
|
|
444
|
+
VITE_PUBLIC_API_URL: url(),
|
|
445
|
+
},
|
|
410
446
|
},
|
|
411
|
-
|
|
412
|
-
|
|
447
|
+
{
|
|
448
|
+
clientPrefix: 'VITE_PUBLIC_', // Astro convention
|
|
413
449
|
}
|
|
414
|
-
|
|
415
|
-
clientPrefix: 'VITE_PUBLIC_' // Astro convention
|
|
416
|
-
});
|
|
450
|
+
);
|
|
417
451
|
```
|
|
418
452
|
|
|
419
453
|
## SSR Support
|
|
@@ -425,14 +459,14 @@ Works seamlessly with Vite's SSR mode:
|
|
|
425
459
|
import { env } from './env';
|
|
426
460
|
|
|
427
461
|
// Both server and client vars accessible in SSR context
|
|
428
|
-
console.log(env.server.DATABASE_URL);
|
|
429
|
-
console.log(env.client.VITE_API_URL);
|
|
462
|
+
console.log(env.server.DATABASE_URL); // ✅ Works
|
|
463
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
430
464
|
|
|
431
465
|
// client.ts (browser entry)
|
|
432
466
|
import { env } from './env';
|
|
433
467
|
|
|
434
|
-
console.log(env.server.DATABASE_URL);
|
|
435
|
-
console.log(env.client.VITE_API_URL);
|
|
468
|
+
console.log(env.server.DATABASE_URL); // ❌ Throws error
|
|
469
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
436
470
|
```
|
|
437
471
|
|
|
438
472
|
## Production Security
|
|
@@ -447,11 +481,12 @@ export const env = resolve({
|
|
|
447
481
|
},
|
|
448
482
|
client: {
|
|
449
483
|
VITE_API_URL: url(),
|
|
450
|
-
}
|
|
484
|
+
},
|
|
451
485
|
});
|
|
452
486
|
```
|
|
453
487
|
|
|
454
488
|
**Best practices:**
|
|
489
|
+
|
|
455
490
|
- Never commit `.env.local` files
|
|
456
491
|
- Use platform environment variables in production (Vercel, Netlify, AWS, etc.)
|
|
457
492
|
- Keep server secrets in `server` schema only
|
|
@@ -472,7 +507,7 @@ export const env = resolve({
|
|
|
472
507
|
// External APIs
|
|
473
508
|
STRIPE_SECRET_KEY: string(),
|
|
474
509
|
OPENAI_API_KEY: string(),
|
|
475
|
-
|
|
510
|
+
|
|
476
511
|
// App configuration
|
|
477
512
|
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
478
513
|
PORT: 'port:5173',
|
|
@@ -482,41 +517,45 @@ export const env = resolve({
|
|
|
482
517
|
// Public API endpoints
|
|
483
518
|
VITE_API_URL: url(),
|
|
484
519
|
VITE_WS_URL: url(),
|
|
485
|
-
|
|
520
|
+
|
|
486
521
|
// Feature flags
|
|
487
522
|
VITE_ENABLE_ANALYTICS: false,
|
|
488
523
|
VITE_ENABLE_DARK_MODE: true,
|
|
489
524
|
VITE_FEATURE_FLAGS: 'string[]',
|
|
490
|
-
|
|
525
|
+
|
|
491
526
|
// Public keys
|
|
492
527
|
VITE_STRIPE_PUBLISHABLE_KEY: string(),
|
|
493
|
-
VITE_GA_ID: string({optional:true}),
|
|
494
|
-
|
|
528
|
+
VITE_GA_ID: string({ optional: true }),
|
|
529
|
+
|
|
495
530
|
// App info
|
|
496
531
|
VITE_APP_VERSION: string(),
|
|
497
|
-
}
|
|
532
|
+
},
|
|
498
533
|
});
|
|
499
534
|
```
|
|
500
535
|
|
|
501
536
|
## Troubleshooting
|
|
502
537
|
|
|
503
538
|
**Variables not loading?**
|
|
539
|
+
|
|
504
540
|
- Check file names and locations
|
|
505
541
|
- Ensure client variables have `VITE_` prefix
|
|
506
542
|
- Restart dev server after adding new variables
|
|
507
543
|
- Verify `.env` files are in project root
|
|
508
544
|
|
|
509
545
|
**TypeScript errors?**
|
|
546
|
+
|
|
510
547
|
- Verify schema matches `.env` files
|
|
511
548
|
- Restart TypeScript server in your editor
|
|
512
549
|
- Check for typos in variable names
|
|
513
550
|
|
|
514
551
|
**Runtime errors in browser?**
|
|
552
|
+
|
|
515
553
|
- Don't access `env.server.*` in client code
|
|
516
554
|
- Use `env.client.*` for browser-accessible values
|
|
517
555
|
- Check browser console for helpful error messages
|
|
518
556
|
|
|
519
557
|
**Production issues?**
|
|
558
|
+
|
|
520
559
|
- Verify platform environment variables are set
|
|
521
560
|
- Ensure secrets aren't sourced from `.env` files
|
|
522
561
|
- Confirm client variables are properly prefixed with `VITE_`
|
|
@@ -527,8 +566,8 @@ Before (Vite built-in):
|
|
|
527
566
|
|
|
528
567
|
```typescript
|
|
529
568
|
// No validation, no types
|
|
530
|
-
const apiUrl = import.meta.env.VITE_API_URL;
|
|
531
|
-
const port = import.meta.env.PORT;
|
|
569
|
+
const apiUrl = import.meta.env.VITE_API_URL; // string | undefined
|
|
570
|
+
const port = import.meta.env.PORT; // string | undefined
|
|
532
571
|
```
|
|
533
572
|
|
|
534
573
|
After (node-env-resolver-vite):
|
|
@@ -542,12 +581,12 @@ export const env = resolve({
|
|
|
542
581
|
},
|
|
543
582
|
client: {
|
|
544
583
|
VITE_API_URL: url(),
|
|
545
|
-
}
|
|
584
|
+
},
|
|
546
585
|
});
|
|
547
586
|
|
|
548
587
|
// Fully typed, validated at startup
|
|
549
|
-
env.server.PORT;
|
|
550
|
-
env.client.VITE_API_URL;
|
|
588
|
+
env.server.PORT; // number
|
|
589
|
+
env.client.VITE_API_URL; // string (validated URL)
|
|
551
590
|
```
|
|
552
591
|
|
|
553
592
|
## Related Packages
|
|
@@ -559,4 +598,3 @@ env.client.VITE_API_URL; // string (validated URL)
|
|
|
559
598
|
## License
|
|
560
599
|
|
|
561
600
|
MIT
|
|
562
|
-
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
|
-
import { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';
|
|
2
|
-
export { EnvDefinition } from 'node-env-resolver';
|
|
1
|
+
import { SimpleEnvSchema, ResolveOptions, ReferenceHandler, InferSimpleSchema } from 'node-env-resolver';
|
|
2
|
+
export { EnvDefinition, ReferenceHandler } from 'node-env-resolver';
|
|
3
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
|
|
7
7
|
* Zero-config Vite integration with automatic client/server split
|
|
8
|
-
*
|
|
9
|
-
* Vite handles .env files via process.env automatically.
|
|
10
|
-
* resolve() is synchronous and works with ALL validator types:
|
|
11
|
-
* - Basic types: string, number, boolean, oneOf, pattern, custom
|
|
12
|
-
* - Advanced types: postgres, url, email, json, port, etc.
|
|
13
8
|
*/
|
|
14
9
|
|
|
15
10
|
interface SafeResolveResult<T> {
|
|
@@ -26,103 +21,25 @@ interface ViteEnvConfig<TServer extends SimpleEnvSchema, TClient extends SimpleE
|
|
|
26
21
|
client: TClient;
|
|
27
22
|
}
|
|
28
23
|
interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {
|
|
29
|
-
/**
|
|
30
|
-
* Prefix for client environment variables
|
|
31
|
-
* @default 'VITE_'
|
|
32
|
-
*/
|
|
33
24
|
clientPrefix?: string;
|
|
34
|
-
/**
|
|
35
|
-
* Enable variable expansion in .env files
|
|
36
|
-
* @default true
|
|
37
|
-
*/
|
|
38
25
|
expandVars?: boolean;
|
|
39
|
-
/**
|
|
40
|
-
* Enable runtime protection for server variables in client components
|
|
41
|
-
* @default true
|
|
42
|
-
*/
|
|
43
26
|
runtimeProtection?: boolean;
|
|
27
|
+
async?: boolean;
|
|
28
|
+
referenceHandlers?: Record<string, ReferenceHandler>;
|
|
44
29
|
}
|
|
45
|
-
|
|
46
|
-
* Create type-safe environment configuration for Vite with automatic client/server split
|
|
47
|
-
*
|
|
48
|
-
* Vite handles .env files automatically.
|
|
49
|
-
* This function is synchronous and supports ALL validator types:
|
|
50
|
-
* - Basic types: string, number, boolean, oneOf, pattern, custom
|
|
51
|
-
* - Advanced types: postgres, url, email, json, port, date, etc.
|
|
52
|
-
*
|
|
53
|
-
* @example
|
|
54
|
-
* ```typescript
|
|
55
|
-
* // env.ts
|
|
56
|
-
* import { resolve } from 'node-env-resolver-vite';
|
|
57
|
-
*
|
|
58
|
-
* export const env = resolve({
|
|
59
|
-
* server: {
|
|
60
|
-
* DATABASE_URL: url(),
|
|
61
|
-
* API_SECRET: string(),
|
|
62
|
-
* PORT: 'port:5173',
|
|
63
|
-
* NODE_ENV: ['development', 'production'] as const
|
|
64
|
-
* },
|
|
65
|
-
* client: {
|
|
66
|
-
* VITE_API_URL: url(),
|
|
67
|
-
* VITE_ENABLE_ANALYTICS: false,
|
|
68
|
-
* VITE_GA_ID: string({optional:true})
|
|
69
|
-
* }
|
|
70
|
-
* });
|
|
71
|
-
*
|
|
72
|
-
* // In server/build code (vite.config.ts, SSR)
|
|
73
|
-
* import { env } from './env';
|
|
74
|
-
*
|
|
75
|
-
* console.log(env.server.DATABASE_URL); // ✅ Works, type: URL
|
|
76
|
-
* console.log(env.client.VITE_API_URL); // ✅ Works, type: URL
|
|
77
|
-
*
|
|
78
|
-
* // In browser code
|
|
79
|
-
* console.log(env.server.DATABASE_URL); // ❌ Throws helpful error in dev
|
|
80
|
-
* console.log(env.client.VITE_API_URL); // ✅ Works, type: URL
|
|
81
|
-
* ```
|
|
82
|
-
*/
|
|
83
|
-
declare function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: Omit<ViteOptions, 'resolvers'> & {
|
|
84
|
-
resolvers?: never;
|
|
85
|
-
}): {
|
|
30
|
+
declare function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: Omit<ViteOptions, 'async' | 'referenceHandlers'>): {
|
|
86
31
|
server: InferSimpleSchema<TServer>;
|
|
87
32
|
client: InferSimpleSchema<TClient>;
|
|
88
33
|
};
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
* @example
|
|
95
|
-
* ```typescript
|
|
96
|
-
* // env.ts
|
|
97
|
-
* import { safeResolve } from 'node-env-resolver-vite';
|
|
98
|
-
*
|
|
99
|
-
* const result = safeResolve({
|
|
100
|
-
* server: {
|
|
101
|
-
* DATABASE_URL: url(),
|
|
102
|
-
* API_SECRET: string(),
|
|
103
|
-
* PORT: 'port:5173'
|
|
104
|
-
* },
|
|
105
|
-
* client: {
|
|
106
|
-
* VITE_API_URL: url(),
|
|
107
|
-
* VITE_ENABLE_ANALYTICS: false,
|
|
108
|
-
* }
|
|
109
|
-
* });
|
|
110
|
-
*
|
|
111
|
-
* if (result.success) {
|
|
112
|
-
* export const env = result.data;
|
|
113
|
-
* } else {
|
|
114
|
-
* console.error('Environment validation failed:', result.error);
|
|
115
|
-
* process.exit(1);
|
|
116
|
-
* }
|
|
117
|
-
* ```
|
|
118
|
-
*/
|
|
119
|
-
declare function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: Omit<ViteOptions, 'resolvers'> & {
|
|
120
|
-
resolvers?: never;
|
|
121
|
-
}): SafeResolveResultType<{
|
|
34
|
+
declare function resolveAsyncFn<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: ViteOptions): Promise<{
|
|
35
|
+
server: InferSimpleSchema<TServer>;
|
|
36
|
+
client: InferSimpleSchema<TClient>;
|
|
37
|
+
}>;
|
|
38
|
+
declare function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: Omit<ViteOptions, 'async' | 'referenceHandlers'>): SafeResolveResultType<{
|
|
122
39
|
server: InferSimpleSchema<TServer>;
|
|
123
40
|
client: InferSimpleSchema<TClient>;
|
|
124
41
|
}>;
|
|
125
42
|
declare const isServer: boolean;
|
|
126
43
|
declare const isClient: boolean;
|
|
127
44
|
|
|
128
|
-
export { type SafeResolveError, type SafeResolveResult, type SafeResolveResultType, type ViteEnvConfig, type ViteOptions, isClient, isServer, resolve, safeResolve };
|
|
45
|
+
export { type SafeResolveError, type SafeResolveResult, type SafeResolveResultType, type ViteEnvConfig, type ViteOptions, isClient, isServer, resolve, resolveAsyncFn, safeResolve };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
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
|
|
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
|
-
\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
|
-
\u{1F4A1} Server variables are only available in server context (vite.config.ts, SSR, build scripts).
|
|
5
|
-
\u{1F4A1} If you need this data on the client, consider:
|
|
6
|
-
- Moving it to the client schema with ${e} prefix
|
|
7
|
-
- Fetching it via an API endpoint
|
|
8
|
-
- Using SSR to pass data to client components`);return t[o]}}),client:v}}function x(r,s={}){try{return {success:!0,data:p(r,s)}}catch(e){return {success:false,error:e instanceof Error?e.message:String(e)}}}var S=typeof window>"u",T=!S;export{T as isClient,S as isServer,p as resolve,x as safeResolve};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {resolveAsync,resolve}from'node-env-resolver';import {dotenv}from'node-env-resolver/resolvers';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 d(){let n=globalThis.__NODE_ENV_RESOLVER_VITE_IS_BROWSER;return typeof n=="function"?n:()=>typeof window<"u"}function u(r,n){let e=Object.keys(r.client).filter(t=>!t.startsWith(n));if(e.length>0)return `Client env vars must be prefixed '${n}': ${e.join(", ")}`;let s=Object.keys(r.server).filter(t=>t.startsWith(n));return s.length>0?`Server env vars should not be prefixed '${n}': ${s.join(", ")}`:null}function T(r,n){try{let{clientPrefix:e="VITE_",runtimeProtection:s=!0}=n,t=u(r,e);if(t)return {error:t};let i=resolve(r.server),l=resolve(r.client),o=d();return {data:{server:s?new Proxy(i,{get(v,c){if(o())throw new Error(`Cannot access server env var '${String(c)}' in client code`);return i[c]}}):i,client:l}}}catch(e){return {error:e instanceof Error?e.message:String(e)}}}function E(r,n={}){let e=T(r,n);if("error"in e)throw new Error(e.error);return e.data}async function g(r,n={}){let{clientPrefix:e="VITE_",runtimeProtection:s=true,referenceHandlers:t}=n,i=u(r,e);if(i)throw new Error(i);let l=t?{handlers:t}:void 0,[o,a]=await Promise.all([resolveAsync({resolvers:[[dotenv(),r.server]],references:l}),resolveAsync({resolvers:[[dotenv(),r.client]],references:l})]),v=d();return {server:s?new Proxy(o,{get(c,S){if(v())throw new Error(`Cannot access server env var '${String(S)}' in client code`);return o[S]}}):o,client:a}}function C(r,n={}){try{return {success:!0,data:E(r,n)}}catch(e){return {success:false,error:e instanceof Error?e.message:String(e)}}}var h=typeof window>"u",R=!h;export{R as isClient,h as isServer,E as resolve,g as resolveAsyncFn,C as safeResolve};//# sourceMappingURL=index.js.map
|
|
9
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["createIsBrowser","isBrowserOverride","validatePrefixes","config","clientPrefix","badClientKeys","k","badServerKeys","resolveInternal","options","runtimeProtection","prefixError","serverResult","nodeEnvResolve","clientResult","isBrowser","_target","prop","error","resolve","result","resolveAsyncFn","referenceHandlers","referenceOptions","resolveAsync","dotenv","safeResolve","isServer","isClient"],"mappings":"oTAqEA,SAASA,CAAAA,EAAiC,CAGxC,IAAMC,CAAAA,CADY,UAAA,CACkB,oCACpC,OAAI,OAAOA,GAAsB,UAAA,CACxBA,CAAAA,CAEF,IAAM,OAAO,MAAA,CAAW,GACjC,CAEA,SAASC,CAAAA,CAG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ACH,CAAC,CAAA,CAEKR,CAAAA,CAAYf,CAAAA,EAAgB,CAElC,OAAO,CACL,MAAA,CAAQU,CAAAA,CACJ,IAAI,KAAA,CAAME,CAAAA,CAAc,CACtB,GAAA,CAAII,CAAAA,CAASC,CAAAA,CAAM,CACjB,GAAIF,CAAAA,GACF,MAAM,IAAI,KAAA,CAAM,CAAA,8BAAA,EAAiC,MAAA,CAAOE,CAAI,CAAC,CAAA,gBAAA,CAAkB,CAAA,CAEjF,OAAQL,CAAAA,CAAyCK,CAAc,CACjE,CACF,CAAC,CAAA,CACDL,EACJ,MAAA,CAAQE,CACV,CACF,CAEO,SAASY,CAAAA,CACdvB,CAAAA,CACAM,CAAAA,CAA4D,GAI3D,CACD,GAAI,CACF,OAAO,CAAE,QAAS,CAAA,CAAA,CAAM,IAAA,CAAMU,CAAAA,CAAQhB,CAAAA,CAAQM,CAAO,CAAE,CACzD,CAAA,MAASS,CAAAA,CAAO,CACd,OAAO,CAAE,QAAS,KAAA,CAAO,KAAA,CAAOA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,OAAOA,CAAK,CAAE,CACzF,CACF,CAEO,IAAMS,EAAW,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\nimport { resolve as nodeEnvResolve, resolveAsync } from 'node-env-resolver';\nimport { dotenv } from 'node-env-resolver/resolvers';\nimport type {\n SimpleEnvSchema,\n ResolveOptions,\n InferSimpleSchema,\n ReferenceHandler,\n} from 'node-env-resolver';\n\nexport type { ReferenceHandler };\n\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\nexport type { EnvDefinition } from 'node-env-resolver';\n\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 clientPrefix?: string;\n expandVars?: boolean;\n runtimeProtection?: boolean;\n async?: boolean;\n referenceHandlers?: Record<string, ReferenceHandler>;\n}\n\nfunction createIsBrowser(): () => boolean {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalAny = globalThis as any;\n const isBrowserOverride = globalAny.__NODE_ENV_RESOLVER_VITE_IS_BROWSER;\n if (typeof isBrowserOverride === 'function') {\n return isBrowserOverride;\n }\n return () => typeof window !== 'undefined';\n}\n\nfunction validatePrefixes<\n TServer extends SimpleEnvSchema,\n TClient extends SimpleEnvSchema,\n>(config: ViteEnvConfig<TServer, TClient>, clientPrefix: string): string | null {\n const badClientKeys = Object.keys(config.client).filter((k) => !k.startsWith(clientPrefix));\n if (badClientKeys.length > 0) {\n return `Client env vars must be prefixed '${clientPrefix}': ${badClientKeys.join(', ')}`;\n }\n const badServerKeys = Object.keys(config.server).filter((k) => k.startsWith(clientPrefix));\n if (badServerKeys.length > 0) {\n return `Server env vars should not be prefixed '${clientPrefix}': ${badServerKeys.join(', ')}`;\n }\n return null;\n}\n\nfunction resolveInternal<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'async' | 'referenceHandlers'>\n) {\n try {\n const { clientPrefix = 'VITE_', runtimeProtection = true } = options;\n\n const prefixError = validatePrefixes(config, clientPrefix);\n if (prefixError) return { error: prefixError };\n\n const serverResult = nodeEnvResolve(config.server);\n const clientResult = nodeEnvResolve(config.client);\n\n const isBrowser = createIsBrowser();\n\n const protectedEnv = {\n server: runtimeProtection\n ? new Proxy(serverResult, {\n get(_target, prop) {\n if (isBrowser()) {\n throw new Error(`Cannot access server env var '${String(prop)}' in client code`);\n }\n return (serverResult as Record<string, unknown>)[prop as string];\n },\n })\n : serverResult,\n client: clientResult,\n };\n\n return { data: protectedEnv };\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport function resolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'async' | 'referenceHandlers'> = {}\n): { server: InferSimpleSchema<TServer>; client: InferSimpleSchema<TClient> } {\n const result = resolveInternal(config, options);\n if ('error' in result) {\n throw new Error(result.error);\n }\n return result.data as { server: InferSimpleSchema<TServer>; client: InferSimpleSchema<TClient> };\n}\n\nexport async function resolveAsyncFn<\n TServer extends SimpleEnvSchema,\n TClient extends SimpleEnvSchema,\n>(\n config: ViteEnvConfig<TServer, TClient>,\n options: ViteOptions = {}\n): Promise<{ server: InferSimpleSchema<TServer>; client: InferSimpleSchema<TClient> }> {\n const { clientPrefix = 'VITE_', runtimeProtection = true, referenceHandlers } = options;\n\n const prefixError = validatePrefixes(config, clientPrefix);\n if (prefixError) throw new Error(prefixError);\n\n const referenceOptions = referenceHandlers ? { handlers: referenceHandlers } : undefined;\n\n // Resolve server and client independently so they stay isolated\n const [serverResult, clientResult] = await Promise.all([\n resolveAsync({\n resolvers: [[dotenv(), config.server]],\n references: referenceOptions,\n }),\n resolveAsync({\n resolvers: [[dotenv(), config.client]],\n references: referenceOptions,\n }),\n ]);\n\n const isBrowser = createIsBrowser();\n\n return {\n server: runtimeProtection\n ? new Proxy(serverResult, {\n get(_target, prop) {\n if (isBrowser()) {\n throw new Error(`Cannot access server env var '${String(prop)}' in client code`);\n }\n return (serverResult as Record<string, unknown>)[prop as string];\n },\n })\n : serverResult,\n client: clientResult,\n } as { server: InferSimpleSchema<TServer>; client: InferSimpleSchema<TClient> };\n}\n\nexport function safeResolve<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(\n config: ViteEnvConfig<TServer, TClient>,\n options: Omit<ViteOptions, 'async' | 'referenceHandlers'> = {}\n): SafeResolveResultType<{\n server: InferSimpleSchema<TServer>;\n client: InferSimpleSchema<TClient>;\n}> {\n try {\n return { success: true, data: resolve(config, options) };\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport const isServer = typeof window === 'undefined';\nexport const isClient = !isServer;\n"]}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -13,13 +13,11 @@ import 'node-env-resolver/validators';
|
|
|
13
13
|
interface PluginOptions<_TServer extends SimpleEnvSchema = SimpleEnvSchema, _TClient extends SimpleEnvSchema = SimpleEnvSchema> extends ViteOptions {
|
|
14
14
|
/**
|
|
15
15
|
* Whether to inject client env vars into Vite's define config
|
|
16
|
-
* This makes them available as import.meta.env.VITE_* in the browser
|
|
17
16
|
* @default true
|
|
18
17
|
*/
|
|
19
18
|
injectClientEnv?: boolean;
|
|
20
19
|
/**
|
|
21
20
|
* Auto-generate TypeScript definitions for import.meta.env
|
|
22
|
-
* Provide a file path (e.g., 'src/vite-env.d.ts') to enable
|
|
23
21
|
* @default undefined (disabled)
|
|
24
22
|
*/
|
|
25
23
|
generateTypes?: string;
|