node-env-resolver-vite 1.1.0
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 +562 -0
- package/dist/index.d.ts +129 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin.d.ts +55 -0
- package/dist/plugin.js +11 -0
- package/dist/plugin.js.map +1 -0
- package/package.json +78 -0
package/README.md
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
# node-env-resolver-vite
|
|
2
|
+
|
|
3
|
+
Vite integration with automatic client/server environment variable splitting.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/node-env-resolver-vite)
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- ✅ Automatic client/server split
|
|
10
|
+
- ✅ Runtime protection to prevent leaking server vars to client
|
|
11
|
+
- ✅ Full TypeScript support with IntelliSense
|
|
12
|
+
- ✅ **Auto-generate TypeScript definitions** for `import.meta.env`
|
|
13
|
+
- ✅ Works with Vite 4.x, 5.x, 6.x, and 7.x
|
|
14
|
+
- ✅ Framework agnostic (Vue, React, Svelte, Solid, Astro)
|
|
15
|
+
- ✅ Zero configuration required
|
|
16
|
+
- ✅ Supports all validator types (basic and advanced)
|
|
17
|
+
- ✅ Optional Vite plugin for config-time integration
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install node-env-resolver-vite
|
|
23
|
+
# or
|
|
24
|
+
pnpm add node-env-resolver-vite
|
|
25
|
+
# or
|
|
26
|
+
yarn add node-env-resolver-vite
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
Create `env.ts` in your project root:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
35
|
+
|
|
36
|
+
export const env = resolve({
|
|
37
|
+
server: {
|
|
38
|
+
DATABASE_URL: postgres(),
|
|
39
|
+
API_SECRET: string(),
|
|
40
|
+
PORT: 'port:5173',
|
|
41
|
+
},
|
|
42
|
+
client: {
|
|
43
|
+
VITE_API_URL: url(),
|
|
44
|
+
VITE_ENABLE_ANALYTICS: false,
|
|
45
|
+
VITE_GA_ID: string({optional:true}),
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Use in your app:
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
// Server code (vite.config.ts, SSR, Node.js)
|
|
54
|
+
import { env } from './env';
|
|
55
|
+
|
|
56
|
+
console.log(env.server.DATABASE_URL); // ✅ Works
|
|
57
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
// Client code (browser)
|
|
62
|
+
import { env } from './env';
|
|
63
|
+
|
|
64
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
65
|
+
console.log(env.server.DATABASE_URL); // ❌ Throws error
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Safe Resolve (Zod-like Pattern)
|
|
69
|
+
|
|
70
|
+
Like Zod's `parse()` vs `safeParse()`, you can choose between throwing errors or getting result objects:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import { resolve, safeResolve } from 'node-env-resolver-vite';
|
|
74
|
+
|
|
75
|
+
// ❌ Throws on validation failure (like Zod's parse())
|
|
76
|
+
export const env = resolve({
|
|
77
|
+
server: {
|
|
78
|
+
DATABASE_URL: postgres(),
|
|
79
|
+
API_SECRET: string(),
|
|
80
|
+
},
|
|
81
|
+
client: {
|
|
82
|
+
VITE_API_URL: url(),
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// ✅ Returns result object (like Zod's safeParse())
|
|
87
|
+
const result = safeResolve({
|
|
88
|
+
server: {
|
|
89
|
+
DATABASE_URL: postgres(),
|
|
90
|
+
API_SECRET: string(),
|
|
91
|
+
},
|
|
92
|
+
client: {
|
|
93
|
+
VITE_API_URL: url(),
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
if (result.success) {
|
|
98
|
+
export const env = result.data;
|
|
99
|
+
// env.server and env.client are fully typed
|
|
100
|
+
} else {
|
|
101
|
+
console.error('Environment validation failed:', result.error);
|
|
102
|
+
process.exit(1);
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**Use cases:**
|
|
107
|
+
- `resolve()` - Throws on error (simpler, fail-fast)
|
|
108
|
+
- `safeResolve()` - Returns `{ success, data?, error? }` (graceful error handling)
|
|
109
|
+
|
|
110
|
+
## Environment Files
|
|
111
|
+
|
|
112
|
+
The package automatically loads from Vite's standard env files:
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
.env # Loaded in all cases
|
|
116
|
+
.env.local # Local overrides (gitignored)
|
|
117
|
+
.env.[mode] # Mode-specific (e.g., .env.development)
|
|
118
|
+
.env.[mode].local # Mode-specific local overrides
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Example `.env.local`:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
# Server-only (no VITE_ prefix)
|
|
125
|
+
DATABASE_URL=postgres://localhost:5432/myapp
|
|
126
|
+
API_SECRET=secret123
|
|
127
|
+
PORT=5173
|
|
128
|
+
|
|
129
|
+
# Client-accessible (VITE_ prefix required)
|
|
130
|
+
VITE_API_URL=https://api.example.com
|
|
131
|
+
VITE_ENABLE_ANALYTICS=false
|
|
132
|
+
VITE_GA_ID=GA-123456
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Validation
|
|
136
|
+
|
|
137
|
+
Use the same shorthand syntax as the core package:
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
export const env = resolve({
|
|
141
|
+
server: {
|
|
142
|
+
PORT: 'port:5173',
|
|
143
|
+
DATABASE_URL: postgres(),
|
|
144
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
145
|
+
API_KEY: string(),
|
|
146
|
+
MAX_CONNECTIONS: 'number',
|
|
147
|
+
TIMEOUT: 'duration', // e.g., '30s', '5m'
|
|
148
|
+
},
|
|
149
|
+
client: {
|
|
150
|
+
VITE_API_URL: url(),
|
|
151
|
+
VITE_ENABLE_ANALYTICS: false,
|
|
152
|
+
VITE_GA_ID: string({optional:true}),
|
|
153
|
+
VITE_FEATURE_FLAGS: 'string[]', // Comma-separated
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
TypeScript knows all the types:
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
env.server.PORT; // number
|
|
162
|
+
env.server.DATABASE_URL; // string
|
|
163
|
+
env.server.NODE_ENV; // 'development' | 'production' | 'test'
|
|
164
|
+
env.server.MAX_CONNECTIONS; // number
|
|
165
|
+
env.server.TIMEOUT; // number (milliseconds)
|
|
166
|
+
env.client.VITE_API_URL; // string
|
|
167
|
+
env.client.VITE_ENABLE_ANALYTICS; // boolean
|
|
168
|
+
env.client.VITE_GA_ID; // string | undefined
|
|
169
|
+
env.client.VITE_FEATURE_FLAGS; // string[]
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## Runtime Protection
|
|
173
|
+
|
|
174
|
+
The package prevents server variables from being accessed in client code:
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
// Client code (browser)
|
|
178
|
+
import { env } from './env';
|
|
179
|
+
|
|
180
|
+
console.log(env.server.DATABASE_URL);
|
|
181
|
+
// Error: Cannot access server environment variable 'DATABASE_URL' in client-side code.
|
|
182
|
+
// Server variables are only available in server context (vite.config.ts, SSR, build scripts).
|
|
183
|
+
// If you need this data on the client, consider:
|
|
184
|
+
// - Moving it to the client schema with VITE_ prefix
|
|
185
|
+
// - Fetching it via an API endpoint
|
|
186
|
+
// - Using SSR to pass data to client components
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
This protection works in both development and production.
|
|
190
|
+
|
|
191
|
+
## TypeScript IntelliSense
|
|
192
|
+
|
|
193
|
+
### Auto-Generate Types (Recommended)
|
|
194
|
+
|
|
195
|
+
Use the Vite plugin to automatically generate TypeScript definitions:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
// vite.config.ts
|
|
199
|
+
import { defineConfig } from 'vite';
|
|
200
|
+
import { nodeEnvResolverPlugin } from 'node-env-resolver-vite/plugin';
|
|
201
|
+
|
|
202
|
+
export default defineConfig({
|
|
203
|
+
plugins: [
|
|
204
|
+
nodeEnvResolverPlugin({
|
|
205
|
+
server: {
|
|
206
|
+
DATABASE_URL: postgres(),
|
|
207
|
+
API_SECRET: string(),
|
|
208
|
+
},
|
|
209
|
+
client: {
|
|
210
|
+
VITE_API_URL: url(),
|
|
211
|
+
VITE_ENABLE_ANALYTICS: false,
|
|
212
|
+
VITE_GA_ID: string({optional:true}),
|
|
213
|
+
},
|
|
214
|
+
generateTypes: 'src/vite-env.d.ts' // ✨ Auto-generates types!
|
|
215
|
+
})
|
|
216
|
+
]
|
|
217
|
+
});
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
This automatically generates `src/vite-env.d.ts` with proper TypeScript types:
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
/// <reference types="vite/client" />
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Auto-generated by node-env-resolver-vite
|
|
227
|
+
* DO NOT EDIT MANUALLY - Changes will be overwritten
|
|
228
|
+
*/
|
|
229
|
+
|
|
230
|
+
interface ImportMetaEnv {
|
|
231
|
+
readonly VITE_API_URL: string
|
|
232
|
+
readonly VITE_ENABLE_ANALYTICS: boolean
|
|
233
|
+
readonly VITE_GA_ID: string | undefined
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
interface ImportMeta {
|
|
237
|
+
readonly env: ImportMetaEnv
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
**Features:**
|
|
242
|
+
- ✅ Types auto-update when you change your schema
|
|
243
|
+
- ✅ Proper type inference (url → string, false → boolean, etc.)
|
|
244
|
+
- ✅ Won't overwrite files with custom content
|
|
245
|
+
- ✅ Only runs in development mode
|
|
246
|
+
|
|
247
|
+
### Manual Types (Alternative)
|
|
248
|
+
|
|
249
|
+
You can also manually create `vite-env.d.ts`:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
/// <reference types="vite/client" />
|
|
253
|
+
|
|
254
|
+
interface ImportMetaEnv {
|
|
255
|
+
readonly VITE_API_URL: string
|
|
256
|
+
readonly VITE_ENABLE_ANALYTICS: boolean
|
|
257
|
+
readonly VITE_GA_ID?: string
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
interface ImportMeta {
|
|
261
|
+
readonly env: ImportMetaEnv
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
This gives you autocomplete for `import.meta.env.VITE_*` in your IDE.
|
|
266
|
+
|
|
267
|
+
## Vite Plugin
|
|
268
|
+
|
|
269
|
+
For config-time integration and auto-generated types, use the Vite plugin:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
// vite.config.ts
|
|
273
|
+
import { defineConfig } from 'vite';
|
|
274
|
+
import { nodeEnvResolverPlugin } from 'node-env-resolver-vite/plugin';
|
|
275
|
+
|
|
276
|
+
export default defineConfig({
|
|
277
|
+
plugins: [
|
|
278
|
+
nodeEnvResolverPlugin({
|
|
279
|
+
server: {
|
|
280
|
+
DATABASE_URL: postgres(),
|
|
281
|
+
API_SECRET: string(),
|
|
282
|
+
},
|
|
283
|
+
client: {
|
|
284
|
+
VITE_API_URL: url(),
|
|
285
|
+
VITE_ENABLE_ANALYTICS: false,
|
|
286
|
+
},
|
|
287
|
+
// Auto-generate TypeScript definitions (optional)
|
|
288
|
+
generateTypes: 'src/vite-env.d.ts'
|
|
289
|
+
})
|
|
290
|
+
]
|
|
291
|
+
});
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
**Plugin Features:**
|
|
295
|
+
- ✅ Validates env vars at config resolution time
|
|
296
|
+
- ✅ Fails fast if validation errors occur
|
|
297
|
+
- ✅ Logs validation status
|
|
298
|
+
- ✅ Auto-generates TypeScript definitions
|
|
299
|
+
- ✅ Optionally injects client vars into Vite's define
|
|
300
|
+
|
|
301
|
+
## Options
|
|
302
|
+
|
|
303
|
+
```typescript
|
|
304
|
+
export const env = resolve({
|
|
305
|
+
server: { /* ... */ },
|
|
306
|
+
client: { /* ... */ }
|
|
307
|
+
}, {
|
|
308
|
+
clientPrefix: 'VITE_', // Default prefix
|
|
309
|
+
runtimeProtection: true, // Enable runtime checks (default: true)
|
|
310
|
+
expandVars: true, // Enable ${VAR} expansion (default: true)
|
|
311
|
+
});
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
## Framework Examples
|
|
315
|
+
|
|
316
|
+
### React + Vite
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
// env.ts
|
|
320
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
321
|
+
|
|
322
|
+
export const env = resolve({
|
|
323
|
+
server: {
|
|
324
|
+
DATABASE_URL: postgres(),
|
|
325
|
+
},
|
|
326
|
+
client: {
|
|
327
|
+
VITE_API_URL: url(),
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
// App.tsx
|
|
332
|
+
import { env } from './env';
|
|
333
|
+
|
|
334
|
+
function App() {
|
|
335
|
+
return <div>API: {env.client.VITE_API_URL}</div>;
|
|
336
|
+
}
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
### Vue + Vite
|
|
340
|
+
|
|
341
|
+
```typescript
|
|
342
|
+
// env.ts
|
|
343
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
344
|
+
|
|
345
|
+
export const env = resolve({
|
|
346
|
+
server: {},
|
|
347
|
+
client: {
|
|
348
|
+
VITE_API_URL: url(),
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// App.vue
|
|
353
|
+
<script setup lang="ts">
|
|
354
|
+
import { env } from './env';
|
|
355
|
+
</script>
|
|
356
|
+
|
|
357
|
+
<template>
|
|
358
|
+
<div>API: {{ env.client.VITE_API_URL }}</div>
|
|
359
|
+
</template>
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### SvelteKit + Vite
|
|
363
|
+
|
|
364
|
+
```typescript
|
|
365
|
+
// env.ts
|
|
366
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
367
|
+
|
|
368
|
+
export const env = resolve({
|
|
369
|
+
server: {
|
|
370
|
+
DATABASE_URL: postgres(),
|
|
371
|
+
},
|
|
372
|
+
client: {
|
|
373
|
+
VITE_PUBLIC_API_URL: url(),
|
|
374
|
+
}
|
|
375
|
+
}, {
|
|
376
|
+
clientPrefix: 'VITE_PUBLIC_' // SvelteKit uses PUBLIC_ internally
|
|
377
|
+
});
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
### Solid + Vite
|
|
381
|
+
|
|
382
|
+
```typescript
|
|
383
|
+
// env.ts
|
|
384
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
385
|
+
|
|
386
|
+
export const env = resolve({
|
|
387
|
+
server: {},
|
|
388
|
+
client: {
|
|
389
|
+
VITE_API_URL: url(),
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
// App.tsx
|
|
394
|
+
import { env } from './env';
|
|
395
|
+
|
|
396
|
+
function App() {
|
|
397
|
+
return <div>API: {env.client.VITE_API_URL}</div>;
|
|
398
|
+
}
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
### Astro + Vite
|
|
402
|
+
|
|
403
|
+
```typescript
|
|
404
|
+
// env.ts
|
|
405
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
406
|
+
|
|
407
|
+
export const env = resolve({
|
|
408
|
+
server: {
|
|
409
|
+
DATABASE_URL: postgres(),
|
|
410
|
+
},
|
|
411
|
+
client: {
|
|
412
|
+
VITE_PUBLIC_API_URL: url(),
|
|
413
|
+
}
|
|
414
|
+
}, {
|
|
415
|
+
clientPrefix: 'VITE_PUBLIC_' // Astro convention
|
|
416
|
+
});
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
## SSR Support
|
|
420
|
+
|
|
421
|
+
Works seamlessly with Vite's SSR mode:
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
// server.ts (SSR entry)
|
|
425
|
+
import { env } from './env';
|
|
426
|
+
|
|
427
|
+
// Both server and client vars accessible in SSR context
|
|
428
|
+
console.log(env.server.DATABASE_URL); // ✅ Works
|
|
429
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
430
|
+
|
|
431
|
+
// client.ts (browser entry)
|
|
432
|
+
import { env } from './env';
|
|
433
|
+
|
|
434
|
+
console.log(env.server.DATABASE_URL); // ❌ Throws error
|
|
435
|
+
console.log(env.client.VITE_API_URL); // ✅ Works
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
## Production Security
|
|
439
|
+
|
|
440
|
+
In production, `.env` files are automatically ignored. Production platforms inject variables via `process.env`.
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
export const env = resolve({
|
|
444
|
+
server: {
|
|
445
|
+
DATABASE_URL: postgres(),
|
|
446
|
+
API_SECRET: string(),
|
|
447
|
+
},
|
|
448
|
+
client: {
|
|
449
|
+
VITE_API_URL: url(),
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
**Best practices:**
|
|
455
|
+
- Never commit `.env.local` files
|
|
456
|
+
- Use platform environment variables in production (Vercel, Netlify, AWS, etc.)
|
|
457
|
+
- Keep server secrets in `server` schema only
|
|
458
|
+
- Only expose public data in `client` schema
|
|
459
|
+
|
|
460
|
+
## Complete Example
|
|
461
|
+
|
|
462
|
+
```typescript
|
|
463
|
+
// env.ts
|
|
464
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
465
|
+
|
|
466
|
+
export const env = resolve({
|
|
467
|
+
server: {
|
|
468
|
+
// Database
|
|
469
|
+
DATABASE_URL: postgres(),
|
|
470
|
+
DB_POOL_SIZE: 10,
|
|
471
|
+
|
|
472
|
+
// External APIs
|
|
473
|
+
STRIPE_SECRET_KEY: string(),
|
|
474
|
+
OPENAI_API_KEY: string(),
|
|
475
|
+
|
|
476
|
+
// App configuration
|
|
477
|
+
NODE_ENV: ['development', 'production', 'test'] as const,
|
|
478
|
+
PORT: 'port:5173',
|
|
479
|
+
LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const,
|
|
480
|
+
},
|
|
481
|
+
client: {
|
|
482
|
+
// Public API endpoints
|
|
483
|
+
VITE_API_URL: url(),
|
|
484
|
+
VITE_WS_URL: url(),
|
|
485
|
+
|
|
486
|
+
// Feature flags
|
|
487
|
+
VITE_ENABLE_ANALYTICS: false,
|
|
488
|
+
VITE_ENABLE_DARK_MODE: true,
|
|
489
|
+
VITE_FEATURE_FLAGS: 'string[]',
|
|
490
|
+
|
|
491
|
+
// Public keys
|
|
492
|
+
VITE_STRIPE_PUBLISHABLE_KEY: string(),
|
|
493
|
+
VITE_GA_ID: string({optional:true}),
|
|
494
|
+
|
|
495
|
+
// App info
|
|
496
|
+
VITE_APP_VERSION: string(),
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
## Troubleshooting
|
|
502
|
+
|
|
503
|
+
**Variables not loading?**
|
|
504
|
+
- Check file names and locations
|
|
505
|
+
- Ensure client variables have `VITE_` prefix
|
|
506
|
+
- Restart dev server after adding new variables
|
|
507
|
+
- Verify `.env` files are in project root
|
|
508
|
+
|
|
509
|
+
**TypeScript errors?**
|
|
510
|
+
- Verify schema matches `.env` files
|
|
511
|
+
- Restart TypeScript server in your editor
|
|
512
|
+
- Check for typos in variable names
|
|
513
|
+
|
|
514
|
+
**Runtime errors in browser?**
|
|
515
|
+
- Don't access `env.server.*` in client code
|
|
516
|
+
- Use `env.client.*` for browser-accessible values
|
|
517
|
+
- Check browser console for helpful error messages
|
|
518
|
+
|
|
519
|
+
**Production issues?**
|
|
520
|
+
- Verify platform environment variables are set
|
|
521
|
+
- Ensure secrets aren't sourced from `.env` files
|
|
522
|
+
- Confirm client variables are properly prefixed with `VITE_`
|
|
523
|
+
|
|
524
|
+
## Migration from Vite Built-in
|
|
525
|
+
|
|
526
|
+
Before (Vite built-in):
|
|
527
|
+
|
|
528
|
+
```typescript
|
|
529
|
+
// No validation, no types
|
|
530
|
+
const apiUrl = import.meta.env.VITE_API_URL; // string | undefined
|
|
531
|
+
const port = import.meta.env.PORT; // string | undefined
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
After (node-env-resolver-vite):
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
import { resolve } from 'node-env-resolver-vite';
|
|
538
|
+
|
|
539
|
+
export const env = resolve({
|
|
540
|
+
server: {
|
|
541
|
+
PORT: 'port:5173',
|
|
542
|
+
},
|
|
543
|
+
client: {
|
|
544
|
+
VITE_API_URL: url(),
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
// Fully typed, validated at startup
|
|
549
|
+
env.server.PORT; // number
|
|
550
|
+
env.client.VITE_API_URL; // string (validated URL)
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
## Related Packages
|
|
554
|
+
|
|
555
|
+
- [node-env-resolver](https://www.npmjs.com/package/node-env-resolver) - Core package
|
|
556
|
+
- [node-env-resolver-nextjs](https://www.npmjs.com/package/node-env-resolver-nextjs) - Next.js integration
|
|
557
|
+
- [node-env-resolver-aws](https://www.npmjs.com/package/node-env-resolver-aws) - AWS Secrets Manager & SSM
|
|
558
|
+
|
|
559
|
+
## License
|
|
560
|
+
|
|
561
|
+
MIT
|
|
562
|
+
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { SimpleEnvSchema, ResolveOptions, InferSimpleSchema } from 'node-env-resolver';
|
|
2
|
+
export { EnvDefinition, SimpleEnvSchema } from 'node-env-resolver';
|
|
3
|
+
export { boolean, custom, date, duration, email, enums, file, http, https, json, mongodb, mysql, number, numberArray, port, postgres, redis, secret, string, stringArray, timestamp, url, urlArray } from 'node-env-resolver/resolvers';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* node-env-resolver/vite
|
|
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, enums, pattern, custom
|
|
12
|
+
* - Advanced types: postgres, url, email, json, port, etc.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
interface SafeResolveResult<T> {
|
|
16
|
+
success: true;
|
|
17
|
+
data: T;
|
|
18
|
+
}
|
|
19
|
+
interface SafeResolveError {
|
|
20
|
+
success: false;
|
|
21
|
+
error: string;
|
|
22
|
+
}
|
|
23
|
+
type SafeResolveResultType<T> = SafeResolveResult<T> | SafeResolveError;
|
|
24
|
+
interface ViteEnvConfig<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema> {
|
|
25
|
+
server: TServer;
|
|
26
|
+
client: TClient;
|
|
27
|
+
}
|
|
28
|
+
interface ViteOptions extends Omit<ResolveOptions, 'resolvers'> {
|
|
29
|
+
/**
|
|
30
|
+
* Prefix for client environment variables
|
|
31
|
+
* @default 'VITE_'
|
|
32
|
+
*/
|
|
33
|
+
clientPrefix?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Enable variable expansion in .env files
|
|
36
|
+
* @default true
|
|
37
|
+
*/
|
|
38
|
+
expandVars?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Enable runtime protection for server variables in client components
|
|
41
|
+
* @default true
|
|
42
|
+
*/
|
|
43
|
+
runtimeProtection?: boolean;
|
|
44
|
+
}
|
|
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, enums, 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
|
+
}): {
|
|
86
|
+
server: InferSimpleSchema<TServer>;
|
|
87
|
+
client: InferSimpleSchema<TClient>;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Safe version of resolve() - returns result object instead of throwing (Zod-like pattern)
|
|
91
|
+
*
|
|
92
|
+
* Supports all validator types (basic and advanced).
|
|
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<{
|
|
122
|
+
server: InferSimpleSchema<TServer>;
|
|
123
|
+
client: InferSimpleSchema<TClient>;
|
|
124
|
+
}>;
|
|
125
|
+
|
|
126
|
+
declare const isServer: boolean;
|
|
127
|
+
declare const isClient: boolean;
|
|
128
|
+
|
|
129
|
+
export { type SafeResolveError, type SafeResolveResult, type SafeResolveResultType, type ViteEnvConfig, type ViteOptions, isClient, isServer, resolve, safeResolve };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {resolve}from'node-env-resolver';export{boolean,custom,date,duration,email,enums,file,http,https,json,mongodb,mysql,number,numberArray,port,postgres,redis,secret,string,stringArray,timestamp,url,urlArray}from'node-env-resolver/resolvers';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
|
+
\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
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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":"qPAyFO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CAAkE,GAIlE,CACA,GAAM,CACJ,YAAA,CAAAC,CAAAA,CAAe,QACf,iBAAA,CAAAC,CAAAA,CAAoB,IACtB,CAAA,C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,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,CAOO,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, 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"]}
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { Plugin } from 'vite';
|
|
2
|
+
import { ViteOptions, ViteEnvConfig } from './index.js';
|
|
3
|
+
import { SimpleEnvSchema } from 'node-env-resolver';
|
|
4
|
+
import 'node-env-resolver/resolvers';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Vite plugin for node-env-resolver
|
|
8
|
+
*
|
|
9
|
+
* Validates environment variables at config resolution time and
|
|
10
|
+
* optionally injects validated env vars into Vite's define config.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface PluginOptions<_TServer extends SimpleEnvSchema = SimpleEnvSchema, _TClient extends SimpleEnvSchema = SimpleEnvSchema> extends ViteOptions {
|
|
14
|
+
/**
|
|
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
|
+
* @default true
|
|
18
|
+
*/
|
|
19
|
+
injectClientEnv?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Auto-generate TypeScript definitions for import.meta.env
|
|
22
|
+
* Provide a file path (e.g., 'src/vite-env.d.ts') to enable
|
|
23
|
+
* @default undefined (disabled)
|
|
24
|
+
*/
|
|
25
|
+
generateTypes?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Vite plugin for environment variable validation and injection
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* // vite.config.ts
|
|
33
|
+
* import { defineConfig } from 'vite';
|
|
34
|
+
* import { nodeEnvResolverPlugin } from 'node-env-resolver-vite/plugin';
|
|
35
|
+
*
|
|
36
|
+
* export default defineConfig({
|
|
37
|
+
* plugins: [
|
|
38
|
+
* nodeEnvResolverPlugin({
|
|
39
|
+
* server: {
|
|
40
|
+
* DATABASE_URL: postgres(),
|
|
41
|
+
* API_SECRET: string(),
|
|
42
|
+
* },
|
|
43
|
+
* client: {
|
|
44
|
+
* VITE_API_URL: url(),
|
|
45
|
+
* VITE_ENABLE_ANALYTICS: false,
|
|
46
|
+
* },
|
|
47
|
+
* generateTypes: 'src/vite-env.d.ts' // Auto-generate types!
|
|
48
|
+
* })
|
|
49
|
+
* ]
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
declare function nodeEnvResolverPlugin<TServer extends SimpleEnvSchema, TClient extends SimpleEnvSchema>(config: ViteEnvConfig<TServer, TClient>, options?: PluginOptions<TServer, TClient>): Plugin;
|
|
54
|
+
|
|
55
|
+
export { type PluginOptions, ViteEnvConfig, ViteOptions, nodeEnvResolverPlugin };
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {existsSync,readFileSync,mkdirSync,writeFileSync}from'fs';import {dirname}from'path';import {resolve}from'node-env-resolver';import'node-env-resolver/resolvers';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
|
+
\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
|
+
\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
|
+
\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 p[v]}}),client:c}}function b(t){if(typeof t=="number")return "number";if(typeof t=="boolean")return "boolean";if(Array.isArray(t))return t.map(e=>`'${e}'`).join(" | ");if(typeof t=="string"){if(!t.includes(":")&&!t.endsWith("?")&&!["string","number","boolean","url","email","postgres","mysql","mongodb","redis","http","https","port","json","date","timestamp","duration","file","string[]","number[]","url[]"].includes(t))return "string";let r=t.endsWith("?"),e=t.replace("?","").split(":")[0],n;return e==="string"||e==="url"||e==="email"||e==="postgres"||e==="mysql"||e==="mongodb"||e==="redis"||e==="http"||e==="https"||e==="date"||e==="file"?n="string":e==="number"||e==="port"||e==="timestamp"||e==="duration"?n="number":e==="boolean"?n="boolean":e==="json"?n="unknown":e==="string[]"?n="string[]":e==="number[]"?n="number[]":e==="url[]"?n="string[]":n="string",r?`${n} | undefined`:n}if(typeof t=="object"&&t!==null&&"type"in t){let r=t,e=r.type.replace("?",""),n;return ["string","url","email","postgres","mysql","mongodb","redis","http","https","date","file"].includes(e)?n="string":["number","port","timestamp","duration"].includes(e)?n="number":e==="boolean"?n="boolean":e==="json"?n="unknown":e==="string[]"?n="string[]":e==="number[]"?n="number[]":n="string",r.optional?`${n} | undefined`:n}if(typeof t=="function"){let e=t.optional===true,n=t.toString(),o="string";return n.includes("parseFloat")||n.includes("parseInt")||n.includes("Number(")?o="number":n.includes("Boolean")||n.includes("=== 'true'")?o="boolean":n.includes("JSON.parse")?o="unknown":n.includes("Array.isArray")&&(o="string[]"),e?`${o} | undefined`:o}return "string"}function T(t){let r=['/// <reference types="vite/client" />',"","/**"," * Auto-generated by node-env-resolver-vite"," * DO NOT EDIT MANUALLY - Changes will be overwritten"," */","","interface ImportMetaEnv {"];for(let[e,n]of Object.entries(t)){let o=b(n);r.push(` readonly ${e}: ${o}`);}return r.push("}"),r.push(""),r.push("interface ImportMeta {"),r.push(" readonly env: ImportMetaEnv"),r.push("}"),r.push(""),r.join(`
|
|
9
|
+
`)}function Z(t,r={}){let{injectClientEnv:e=true,generateTypes:n,...o}=r,l;return {name:"node-env-resolver-vite",config(){try{l=f(t,o),console.log("\u2705 Environment variables validated successfully");}catch(i){throw console.error("\u274C Environment validation failed:"),i}if(e){let i={};for(let[s,a]of Object.entries(l.client)){let c=JSON.stringify(a);i[`import.meta.env.${s}`]=c;}return {define:i}}},configResolved(i){if(i.command==="serve"&&i.mode==="development"){if(console.log(`
|
|
10
|
+
\u{1F4E6} Environment Configuration:`),console.log(` \u2022 Mode: ${i.mode}`),console.log(` \u2022 Server vars: ${Object.keys(t.server).length}`),console.log(` \u2022 Client vars: ${Object.keys(t.client).length}`),n)try{let s=n.startsWith("/")?n:`${i.root}/${n}`,a=!0;if(existsSync(s)&&(readFileSync(s,"utf-8").includes("Auto-generated by node-env-resolver-vite")||(a=!1,console.log(` \u26A0\uFE0F Skipping type generation: ${n} contains custom content`))),a){let c=T(t.client),m=dirname(s);existsSync(m)||mkdirSync(m,{recursive:!0}),writeFileSync(s,c,"utf-8"),console.log(` \u2705 Generated TypeScript definitions: ${n}`);}}catch(s){console.error(" \u26A0\uFE0F Failed to generate types:",s instanceof Error?s.message:String(s));}console.log("");}}}}export{Z as nodeEnvResolverPlugin};//# sourceMappingURL=plugin.js.map
|
|
11
|
+
//# sourceMappingURL=plugin.js.map
|
|
@@ -0,0 +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,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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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"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "node-env-resolver-vite",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Zero-config Vite integration for node-env-resolver with client/server split",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
},
|
|
13
|
+
"./plugin": {
|
|
14
|
+
"import": "./dist/plugin.js",
|
|
15
|
+
"types": "./dist/plugin.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"vite",
|
|
24
|
+
"environment",
|
|
25
|
+
"env",
|
|
26
|
+
"config",
|
|
27
|
+
"typescript",
|
|
28
|
+
"type-safe",
|
|
29
|
+
"zero-config",
|
|
30
|
+
"vue",
|
|
31
|
+
"react",
|
|
32
|
+
"svelte",
|
|
33
|
+
"solid",
|
|
34
|
+
"astro"
|
|
35
|
+
],
|
|
36
|
+
"author": {
|
|
37
|
+
"name": "Jagvinder Singh Reehal",
|
|
38
|
+
"email": "jag@jagreehal.com",
|
|
39
|
+
"url": "https://jagreehal.com"
|
|
40
|
+
},
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"sideEffects": false,
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"vite": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
|
|
48
|
+
},
|
|
49
|
+
"peerDependenciesMeta": {
|
|
50
|
+
"vite": {
|
|
51
|
+
"optional": true
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"node-env-resolver": "5.0.0"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@types/node": "^24.7.2",
|
|
59
|
+
"eslint": "^9.37.0",
|
|
60
|
+
"prettier": "^3.6.2",
|
|
61
|
+
"tsup": "^8.5.0",
|
|
62
|
+
"typescript": "^5.9.3",
|
|
63
|
+
"vite": "^7.1.10",
|
|
64
|
+
"vitest": "^3.2.4"
|
|
65
|
+
},
|
|
66
|
+
"engines": {
|
|
67
|
+
"node": ">=18"
|
|
68
|
+
},
|
|
69
|
+
"scripts": {
|
|
70
|
+
"build": "NODE_ENV=production tsup",
|
|
71
|
+
"build:dev": "tsup",
|
|
72
|
+
"build:dts": "tsc --emitDeclarationOnly",
|
|
73
|
+
"type-check": "tsc -p tsconfig.json --noEmit",
|
|
74
|
+
"lint": "eslint src/",
|
|
75
|
+
"test": "vitest run",
|
|
76
|
+
"dev": "tsup --watch"
|
|
77
|
+
}
|
|
78
|
+
}
|