zod-envkit 1.0.0 → 1.0.2
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/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/README.md +104 -66
- package/dist/cli.cjs +104 -5
- package/dist/cli.js +104 -5
- package/package.json +22 -9
- package/.env.example +0 -8
- package/ENV.md +0 -7
- package/env.meta.json +0 -5
- package/src/cli.ts +0 -26
- package/src/generate.ts +0 -130
- package/src/index.ts +0 -23
- package/test/basic.test.ts +0 -15
- package/tsconfig.json +0 -10
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
This project follows [Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## [1.0.0] – 2026-01-26
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- Initial release of **zod-envkit**
|
|
13
|
+
- Type-safe environment variable validation using Zod
|
|
14
|
+
- `loadEnv` helper for safe runtime parsing of `process.env`
|
|
15
|
+
- `formatZodError` for human-readable error output
|
|
16
|
+
- CLI tool to generate:
|
|
17
|
+
- `.env.example`
|
|
18
|
+
- `ENV.md` documentation
|
|
19
|
+
- Automatic type inference for validated environment variables
|
|
20
|
+
- Support for ESM and CommonJS builds
|
|
21
|
+
- TypeScript declaration files (`.d.ts`) included
|
|
22
|
+
- Basic test suite using Vitest
|
|
23
|
+
- Clear and documented API surface
|
|
24
|
+
- MIT license
|
|
25
|
+
|
|
26
|
+
### Design Decisions
|
|
27
|
+
- Explicit configuration over magic
|
|
28
|
+
- No automatic schema introspection for documentation generation
|
|
29
|
+
- Environment variables treated as an explicit runtime contract
|
|
30
|
+
- Small, framework-agnostic core
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
[1.0.0]: https://www.npmjs.com/package/zod-envkit/v/1.0.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## [1.0.1] – 2026-01-26
|
|
38
|
+
|
|
39
|
+
### Changed
|
|
40
|
+
- Documentation and packaging improvements
|
|
41
|
+
- Minor CLI/docs adjustments
|
|
42
|
+
|
|
43
|
+
[1.0.1]: https://www.npmjs.com/package/zod-envkit/v/1.0.1
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nxtxe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
-
|
|
1
|
+
<div align="center">
|
|
2
|
+
<br />
|
|
3
|
+
<p>
|
|
4
|
+
<img src="./zod-envkit.svg" width="546" alt="zod-envkit" />
|
|
5
|
+
</p>
|
|
6
|
+
<br />
|
|
7
|
+
<p>
|
|
8
|
+
<a href="https://www.npmjs.com/package/zod-envkit">
|
|
9
|
+
<img src="https://img.shields.io/npm/v/zod-envkit.svg?maxAge=100" alt="npm version" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://www.npmjs.com/package/zod-envkit">
|
|
12
|
+
<img src="https://img.shields.io/npm/dt/zod-envkit.svg?maxAge=100" alt="npm downloads" />
|
|
13
|
+
</a>
|
|
14
|
+
</p>
|
|
15
|
+
</div>
|
|
16
|
+
|
|
17
|
+
Type-safe environment variable validation and documentation using **Zod**.
|
|
18
|
+
|
|
19
|
+
**zod-envkit** is a small library + CLI that helps you treat environment variables as an **explicit runtime contract**, not an implicit guessing game.
|
|
20
|
+
|
|
21
|
+
- validate `process.env` at startup
|
|
22
|
+
- get fully typed environment variables
|
|
23
|
+
- generate `.env.example`
|
|
24
|
+
- generate readable documentation (`ENV.md`)
|
|
25
|
+
- inspect and verify env state via CLI
|
|
9
26
|
|
|
10
27
|
No cloud. No magic. Just code.
|
|
11
28
|
|
|
@@ -13,18 +30,19 @@ No cloud. No magic. Just code.
|
|
|
13
30
|
|
|
14
31
|
## Why
|
|
15
32
|
|
|
16
|
-
|
|
33
|
+
Environment variables are critical, but usually poorly handled.
|
|
34
|
+
|
|
35
|
+
The usual problems:
|
|
17
36
|
- `process.env` is just `string | undefined`
|
|
18
|
-
-
|
|
19
|
-
- `.env.example` and
|
|
37
|
+
- missing or invalid variables fail **at runtime**
|
|
38
|
+
- `.env.example` and docs get outdated
|
|
39
|
+
- CI/CD breaks late and unpredictably
|
|
20
40
|
|
|
21
|
-
|
|
22
|
-
-
|
|
23
|
-
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
- up-to-date `.env.example`
|
|
27
|
-
- up-to-date documentation
|
|
41
|
+
**zod-envkit** solves this by making env:
|
|
42
|
+
- validated early
|
|
43
|
+
- typed
|
|
44
|
+
- documented
|
|
45
|
+
- checkable in CI
|
|
28
46
|
|
|
29
47
|
---
|
|
30
48
|
|
|
@@ -42,7 +60,9 @@ pnpm add zod-envkit
|
|
|
42
60
|
|
|
43
61
|
---
|
|
44
62
|
|
|
45
|
-
##
|
|
63
|
+
## Library usage (runtime validation)
|
|
64
|
+
|
|
65
|
+
Create a single file responsible for loading and validating env.
|
|
46
66
|
|
|
47
67
|
```ts
|
|
48
68
|
import "dotenv/config";
|
|
@@ -52,7 +72,7 @@ import { loadEnv, formatZodError } from "zod-envkit";
|
|
|
52
72
|
const EnvSchema = z.object({
|
|
53
73
|
NODE_ENV: z.enum(["development", "test", "production"]),
|
|
54
74
|
PORT: z.coerce.number().int().min(1).max(65535),
|
|
55
|
-
DATABASE_URL: z.string().url()
|
|
75
|
+
DATABASE_URL: z.string().url(),
|
|
56
76
|
});
|
|
57
77
|
|
|
58
78
|
const result = loadEnv(EnvSchema);
|
|
@@ -70,86 +90,102 @@ Now:
|
|
|
70
90
|
* `env.PORT` is a **number**
|
|
71
91
|
* `env.DATABASE_URL` is a **string**
|
|
72
92
|
* TypeScript knows everything at compile time
|
|
93
|
+
* your app fails fast if env is invalid
|
|
73
94
|
|
|
74
95
|
---
|
|
75
96
|
|
|
76
|
-
## CLI
|
|
97
|
+
## CLI usage
|
|
98
|
+
|
|
99
|
+
The CLI works from a simple metadata file: `env.meta.json`.
|
|
100
|
+
|
|
101
|
+
By default, it is searched in:
|
|
77
102
|
|
|
78
|
-
|
|
103
|
+
* `./env.meta.json`
|
|
104
|
+
* `./examples/env.meta.json`
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
### Example `env.meta.json`
|
|
79
109
|
|
|
80
110
|
```json
|
|
81
111
|
{
|
|
82
112
|
"NODE_ENV": {
|
|
83
|
-
"description": "
|
|
84
|
-
"example": "development"
|
|
113
|
+
"description": "Runtime mode",
|
|
114
|
+
"example": "development",
|
|
115
|
+
"required": true
|
|
85
116
|
},
|
|
86
117
|
"PORT": {
|
|
87
|
-
"description": "HTTP
|
|
88
|
-
"example": "3000"
|
|
118
|
+
"description": "HTTP port",
|
|
119
|
+
"example": "3000",
|
|
120
|
+
"required": true
|
|
89
121
|
},
|
|
90
122
|
"DATABASE_URL": {
|
|
91
|
-
"description": "
|
|
92
|
-
"example": "postgresql://user:pass@localhost:5432/db"
|
|
123
|
+
"description": "Postgres connection string",
|
|
124
|
+
"example": "postgresql://user:pass@localhost:5432/db",
|
|
125
|
+
"required": true
|
|
93
126
|
}
|
|
94
127
|
}
|
|
95
128
|
```
|
|
96
129
|
|
|
97
130
|
---
|
|
98
131
|
|
|
99
|
-
|
|
132
|
+
## CLI commands
|
|
133
|
+
|
|
134
|
+
### Generate `.env.example` and `ENV.md`
|
|
135
|
+
|
|
136
|
+
(Default behavior)
|
|
100
137
|
|
|
101
138
|
```bash
|
|
102
139
|
npx zod-envkit
|
|
103
140
|
```
|
|
104
141
|
|
|
105
|
-
|
|
142
|
+
or explicitly:
|
|
106
143
|
|
|
107
144
|
```bash
|
|
108
|
-
|
|
145
|
+
npx zod-envkit generate
|
|
109
146
|
```
|
|
110
147
|
|
|
111
148
|
---
|
|
112
149
|
|
|
113
|
-
###
|
|
150
|
+
### Show current environment status
|
|
114
151
|
|
|
115
|
-
|
|
152
|
+
Loads `.env`, masks secrets, and displays a readable table.
|
|
116
153
|
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
|
|
154
|
+
```bash
|
|
155
|
+
npx zod-envkit show
|
|
156
|
+
```
|
|
120
157
|
|
|
121
|
-
|
|
122
|
-
PORT=3000
|
|
158
|
+
Example output:
|
|
123
159
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
160
|
+
* which variables are required
|
|
161
|
+
* which are present
|
|
162
|
+
* masked values for secrets
|
|
127
163
|
|
|
128
|
-
|
|
164
|
+
---
|
|
129
165
|
|
|
130
|
-
|
|
131
|
-
# Environment variables
|
|
166
|
+
### Validate required variables (CI-friendly)
|
|
132
167
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
| NODE_ENV | yes | development | Application runtime environment |
|
|
136
|
-
| PORT | yes | 3000 | HTTP server port |
|
|
137
|
-
| DATABASE_URL | yes | postgresql://... | PostgreSQL connection string |
|
|
168
|
+
```bash
|
|
169
|
+
npx zod-envkit check
|
|
138
170
|
```
|
|
139
171
|
|
|
172
|
+
* exits with code `1` if any required variable is missing
|
|
173
|
+
* perfect for CI/CD pipelines and pre-deploy checks
|
|
174
|
+
|
|
140
175
|
---
|
|
141
176
|
|
|
142
|
-
|
|
177
|
+
### CLI options
|
|
143
178
|
|
|
144
179
|
```bash
|
|
145
180
|
zod-envkit --help
|
|
146
181
|
```
|
|
147
182
|
|
|
183
|
+
Common flags:
|
|
184
|
+
|
|
148
185
|
```bash
|
|
149
|
-
zod-envkit \
|
|
150
|
-
--config env.meta.json \
|
|
151
|
-
--
|
|
152
|
-
--out-docs ENV.md
|
|
186
|
+
zod-envkit show \
|
|
187
|
+
--config examples/env.meta.json \
|
|
188
|
+
--env-file .env
|
|
153
189
|
```
|
|
154
190
|
|
|
155
191
|
---
|
|
@@ -161,6 +197,7 @@ zod-envkit \
|
|
|
161
197
|
* ❌ no validation
|
|
162
198
|
* ❌ no types
|
|
163
199
|
* ❌ no documentation
|
|
200
|
+
* ❌ no CI checks
|
|
164
201
|
|
|
165
202
|
`zod-envkit`:
|
|
166
203
|
|
|
@@ -169,39 +206,40 @@ zod-envkit \
|
|
|
169
206
|
* ✅ documentation
|
|
170
207
|
* ✅ CLI tooling
|
|
171
208
|
|
|
172
|
-
They
|
|
209
|
+
They are designed to be used **together**.
|
|
173
210
|
|
|
174
211
|
---
|
|
175
212
|
|
|
176
|
-
## Design
|
|
213
|
+
## Design principles
|
|
177
214
|
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
215
|
+
* explicit configuration over magic
|
|
216
|
+
* no framework coupling
|
|
217
|
+
* small and predictable API
|
|
218
|
+
* library and CLI are independent but complementary
|
|
219
|
+
* environment variables are a runtime contract
|
|
183
220
|
|
|
184
221
|
---
|
|
185
222
|
|
|
186
223
|
## Roadmap
|
|
187
224
|
|
|
188
225
|
* [ ] schema ↔ meta consistency checks
|
|
189
|
-
* [ ]
|
|
190
|
-
* [ ]
|
|
191
|
-
* [ ] prettier, human-friendly error output
|
|
226
|
+
* [ ] grouped sections in generated docs
|
|
227
|
+
* [ ] prettier, more human-friendly error output
|
|
192
228
|
* [ ] JSON schema export
|
|
229
|
+
* [ ] stricter validation modes for production
|
|
193
230
|
|
|
194
231
|
---
|
|
195
232
|
|
|
196
233
|
## Who is this for?
|
|
197
234
|
|
|
198
235
|
* backend and fullstack projects
|
|
199
|
-
* Node.js
|
|
236
|
+
* Node.js and Bun services
|
|
200
237
|
* CI/CD pipelines
|
|
201
|
-
* teams that
|
|
238
|
+
* teams that want env errors to fail fast, not late
|
|
202
239
|
|
|
203
240
|
---
|
|
204
241
|
|
|
205
242
|
## License
|
|
206
243
|
|
|
207
244
|
MIT
|
|
245
|
+
|
package/dist/cli.cjs
CHANGED
|
@@ -27,6 +27,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
27
27
|
var import_node_fs = __toESM(require("fs"), 1);
|
|
28
28
|
var import_node_path = __toESM(require("path"), 1);
|
|
29
29
|
var import_commander = require("commander");
|
|
30
|
+
var import_dotenv = __toESM(require("dotenv"), 1);
|
|
30
31
|
|
|
31
32
|
// src/generate.ts
|
|
32
33
|
function strLen(s) {
|
|
@@ -98,13 +99,111 @@ function generateEnvDocs(meta) {
|
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
// src/cli.ts
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const
|
|
102
|
+
function maskValue(key, value) {
|
|
103
|
+
const k = key.toUpperCase();
|
|
104
|
+
const isSecret = k.includes("TOKEN") || k.includes("SECRET") || k.includes("PASSWORD") || k.includes("API_KEY") || k.includes("KEY");
|
|
105
|
+
if (!isSecret) return value;
|
|
106
|
+
if (value.length <= 4) return "*".repeat(value.length);
|
|
107
|
+
return value.slice(0, 2) + "*".repeat(Math.max(1, value.length - 4)) + value.slice(-2);
|
|
108
|
+
}
|
|
109
|
+
function padCenter2(text, width) {
|
|
110
|
+
const t = text ?? "";
|
|
111
|
+
const diff = width - t.length;
|
|
112
|
+
if (diff <= 0) return t;
|
|
113
|
+
const left = Math.floor(diff / 2);
|
|
114
|
+
const right = diff - left;
|
|
115
|
+
return " ".repeat(left) + t + " ".repeat(right);
|
|
116
|
+
}
|
|
117
|
+
function printTable(rows, headers) {
|
|
118
|
+
const widths = {};
|
|
119
|
+
for (const h of headers) widths[h] = h.length;
|
|
120
|
+
for (const row of rows) {
|
|
121
|
+
for (const h of headers) {
|
|
122
|
+
widths[h] = Math.max(widths[h], (row[h] ?? "").length);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
for (const h of headers) widths[h] += 2;
|
|
126
|
+
const line = "|" + headers.map((h) => " " + padCenter2(h, widths[h]) + " ").join("|") + "|";
|
|
127
|
+
const sep = "|" + headers.map((h) => ":" + "-".repeat(Math.max(3, widths[h])) + ":").join("|") + "|";
|
|
128
|
+
console.log(line);
|
|
129
|
+
console.log(sep);
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
const rowLine = "|" + headers.map((h) => " " + padCenter2(row[h] ?? "", widths[h]) + " ").join("|") + "|";
|
|
132
|
+
console.log(rowLine);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function loadMeta(configFile) {
|
|
136
|
+
const cwd = process.cwd();
|
|
137
|
+
const candidates = [
|
|
138
|
+
import_node_path.default.resolve(cwd, configFile),
|
|
139
|
+
// ./env.meta.json (по умолчанию)
|
|
140
|
+
import_node_path.default.resolve(cwd, "examples", configFile),
|
|
141
|
+
// ./examples/env.meta.json
|
|
142
|
+
import_node_path.default.resolve(cwd, "examples", "env.meta.json")
|
|
143
|
+
// явный fallback
|
|
144
|
+
];
|
|
145
|
+
const configPath = candidates.find((p) => import_node_fs.default.existsSync(p));
|
|
146
|
+
if (!configPath) {
|
|
147
|
+
console.error("\u274C env meta file not found.");
|
|
148
|
+
console.error("Tried:");
|
|
149
|
+
for (const p of candidates) console.error(`- ${p}`);
|
|
150
|
+
console.error("\nTip:");
|
|
151
|
+
console.error(" zod-envkit show -c examples/env.meta.json");
|
|
152
|
+
process.exit(1);
|
|
153
|
+
}
|
|
104
154
|
const raw = import_node_fs.default.readFileSync(configPath, "utf8");
|
|
105
|
-
|
|
155
|
+
return JSON.parse(raw);
|
|
156
|
+
}
|
|
157
|
+
var program = new import_commander.Command();
|
|
158
|
+
program.name("zod-envkit").description("Env docs + runtime checks for Node.js projects");
|
|
159
|
+
program.command("generate").description("Generate .env.example and ENV.md from env.meta.json").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--out-example <file>", "Output file for .env.example", ".env.example").option("--out-docs <file>", "Output file for docs", "ENV.md").action((opts) => {
|
|
160
|
+
const meta = loadMeta(opts.config);
|
|
106
161
|
import_node_fs.default.writeFileSync(opts.outExample, generateEnvExample(meta), "utf8");
|
|
107
162
|
import_node_fs.default.writeFileSync(opts.outDocs, generateEnvDocs(meta), "utf8");
|
|
108
163
|
console.log(`Generated: ${opts.outExample}, ${opts.outDocs}`);
|
|
109
164
|
});
|
|
110
|
-
program.
|
|
165
|
+
program.option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--out-example <file>", "Output file for .env.example", ".env.example").option("--out-docs <file>", "Output file for docs", "ENV.md");
|
|
166
|
+
program.command("show").description("Show current env status (loads .env, masks secrets)").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--env-file <file>", "Path to .env file", ".env").action((opts) => {
|
|
167
|
+
import_dotenv.default.config({ path: import_node_path.default.resolve(process.cwd(), opts.envFile), quiet: true });
|
|
168
|
+
const meta = loadMeta(opts.config);
|
|
169
|
+
const rows = Object.entries(meta).map(([key, m]) => {
|
|
170
|
+
const required = m.required === false ? "no" : "yes";
|
|
171
|
+
const raw = process.env[key];
|
|
172
|
+
const present = raw && raw.length > 0 ? "yes" : "no";
|
|
173
|
+
const value = raw ? maskValue(key, raw) : "";
|
|
174
|
+
return {
|
|
175
|
+
Key: key,
|
|
176
|
+
Required: required,
|
|
177
|
+
Present: present,
|
|
178
|
+
Value: value,
|
|
179
|
+
Description: m.description ?? ""
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
printTable(rows, ["Key", "Required", "Present", "Value", "Description"]);
|
|
183
|
+
});
|
|
184
|
+
program.command("check").description("Exit with code 1 if any required env var is missing (loads .env)").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--env-file <file>", "Path to .env file", ".env").action((opts) => {
|
|
185
|
+
import_dotenv.default.config({ path: import_node_path.default.resolve(process.cwd(), opts.envFile) });
|
|
186
|
+
const meta = loadMeta(opts.config);
|
|
187
|
+
const missing = [];
|
|
188
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
189
|
+
const required = m.required !== false;
|
|
190
|
+
if (!required) continue;
|
|
191
|
+
const raw = process.env[key];
|
|
192
|
+
if (!raw || raw.length === 0) missing.push(key);
|
|
193
|
+
}
|
|
194
|
+
if (missing.length) {
|
|
195
|
+
console.error("\u274C Missing required environment variables:");
|
|
196
|
+
for (const k of missing) console.error(`- ${k}`);
|
|
197
|
+
process.exit(1);
|
|
198
|
+
}
|
|
199
|
+
console.log("\u2705 Environment looks good.");
|
|
200
|
+
});
|
|
201
|
+
program.parse(process.argv);
|
|
202
|
+
var hasSubcommand = process.argv.slice(2).some((a) => ["generate", "show", "check"].includes(a));
|
|
203
|
+
if (!hasSubcommand) {
|
|
204
|
+
const opts = program.opts();
|
|
205
|
+
const meta = loadMeta(opts.config ?? "env.meta.json");
|
|
206
|
+
import_node_fs.default.writeFileSync(opts.outExample ?? ".env.example", generateEnvExample(meta), "utf8");
|
|
207
|
+
import_node_fs.default.writeFileSync(opts.outDocs ?? "ENV.md", generateEnvDocs(meta), "utf8");
|
|
208
|
+
console.log(`Generated: ${opts.outExample ?? ".env.example"}, ${opts.outDocs ?? "ENV.md"}`);
|
|
209
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { Command } from "commander";
|
|
7
|
+
import dotenv from "dotenv";
|
|
7
8
|
|
|
8
9
|
// src/generate.ts
|
|
9
10
|
function strLen(s) {
|
|
@@ -75,13 +76,111 @@ function generateEnvDocs(meta) {
|
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
// src/cli.ts
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
79
|
+
function maskValue(key, value) {
|
|
80
|
+
const k = key.toUpperCase();
|
|
81
|
+
const isSecret = k.includes("TOKEN") || k.includes("SECRET") || k.includes("PASSWORD") || k.includes("API_KEY") || k.includes("KEY");
|
|
82
|
+
if (!isSecret) return value;
|
|
83
|
+
if (value.length <= 4) return "*".repeat(value.length);
|
|
84
|
+
return value.slice(0, 2) + "*".repeat(Math.max(1, value.length - 4)) + value.slice(-2);
|
|
85
|
+
}
|
|
86
|
+
function padCenter2(text, width) {
|
|
87
|
+
const t = text ?? "";
|
|
88
|
+
const diff = width - t.length;
|
|
89
|
+
if (diff <= 0) return t;
|
|
90
|
+
const left = Math.floor(diff / 2);
|
|
91
|
+
const right = diff - left;
|
|
92
|
+
return " ".repeat(left) + t + " ".repeat(right);
|
|
93
|
+
}
|
|
94
|
+
function printTable(rows, headers) {
|
|
95
|
+
const widths = {};
|
|
96
|
+
for (const h of headers) widths[h] = h.length;
|
|
97
|
+
for (const row of rows) {
|
|
98
|
+
for (const h of headers) {
|
|
99
|
+
widths[h] = Math.max(widths[h], (row[h] ?? "").length);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
for (const h of headers) widths[h] += 2;
|
|
103
|
+
const line = "|" + headers.map((h) => " " + padCenter2(h, widths[h]) + " ").join("|") + "|";
|
|
104
|
+
const sep = "|" + headers.map((h) => ":" + "-".repeat(Math.max(3, widths[h])) + ":").join("|") + "|";
|
|
105
|
+
console.log(line);
|
|
106
|
+
console.log(sep);
|
|
107
|
+
for (const row of rows) {
|
|
108
|
+
const rowLine = "|" + headers.map((h) => " " + padCenter2(row[h] ?? "", widths[h]) + " ").join("|") + "|";
|
|
109
|
+
console.log(rowLine);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function loadMeta(configFile) {
|
|
113
|
+
const cwd = process.cwd();
|
|
114
|
+
const candidates = [
|
|
115
|
+
path.resolve(cwd, configFile),
|
|
116
|
+
// ./env.meta.json (по умолчанию)
|
|
117
|
+
path.resolve(cwd, "examples", configFile),
|
|
118
|
+
// ./examples/env.meta.json
|
|
119
|
+
path.resolve(cwd, "examples", "env.meta.json")
|
|
120
|
+
// явный fallback
|
|
121
|
+
];
|
|
122
|
+
const configPath = candidates.find((p) => fs.existsSync(p));
|
|
123
|
+
if (!configPath) {
|
|
124
|
+
console.error("\u274C env meta file not found.");
|
|
125
|
+
console.error("Tried:");
|
|
126
|
+
for (const p of candidates) console.error(`- ${p}`);
|
|
127
|
+
console.error("\nTip:");
|
|
128
|
+
console.error(" zod-envkit show -c examples/env.meta.json");
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
81
131
|
const raw = fs.readFileSync(configPath, "utf8");
|
|
82
|
-
|
|
132
|
+
return JSON.parse(raw);
|
|
133
|
+
}
|
|
134
|
+
var program = new Command();
|
|
135
|
+
program.name("zod-envkit").description("Env docs + runtime checks for Node.js projects");
|
|
136
|
+
program.command("generate").description("Generate .env.example and ENV.md from env.meta.json").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--out-example <file>", "Output file for .env.example", ".env.example").option("--out-docs <file>", "Output file for docs", "ENV.md").action((opts) => {
|
|
137
|
+
const meta = loadMeta(opts.config);
|
|
83
138
|
fs.writeFileSync(opts.outExample, generateEnvExample(meta), "utf8");
|
|
84
139
|
fs.writeFileSync(opts.outDocs, generateEnvDocs(meta), "utf8");
|
|
85
140
|
console.log(`Generated: ${opts.outExample}, ${opts.outDocs}`);
|
|
86
141
|
});
|
|
87
|
-
program.
|
|
142
|
+
program.option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--out-example <file>", "Output file for .env.example", ".env.example").option("--out-docs <file>", "Output file for docs", "ENV.md");
|
|
143
|
+
program.command("show").description("Show current env status (loads .env, masks secrets)").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--env-file <file>", "Path to .env file", ".env").action((opts) => {
|
|
144
|
+
dotenv.config({ path: path.resolve(process.cwd(), opts.envFile), quiet: true });
|
|
145
|
+
const meta = loadMeta(opts.config);
|
|
146
|
+
const rows = Object.entries(meta).map(([key, m]) => {
|
|
147
|
+
const required = m.required === false ? "no" : "yes";
|
|
148
|
+
const raw = process.env[key];
|
|
149
|
+
const present = raw && raw.length > 0 ? "yes" : "no";
|
|
150
|
+
const value = raw ? maskValue(key, raw) : "";
|
|
151
|
+
return {
|
|
152
|
+
Key: key,
|
|
153
|
+
Required: required,
|
|
154
|
+
Present: present,
|
|
155
|
+
Value: value,
|
|
156
|
+
Description: m.description ?? ""
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
printTable(rows, ["Key", "Required", "Present", "Value", "Description"]);
|
|
160
|
+
});
|
|
161
|
+
program.command("check").description("Exit with code 1 if any required env var is missing (loads .env)").option("-c, --config <file>", "Path to env meta json", "env.meta.json").option("--env-file <file>", "Path to .env file", ".env").action((opts) => {
|
|
162
|
+
dotenv.config({ path: path.resolve(process.cwd(), opts.envFile) });
|
|
163
|
+
const meta = loadMeta(opts.config);
|
|
164
|
+
const missing = [];
|
|
165
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
166
|
+
const required = m.required !== false;
|
|
167
|
+
if (!required) continue;
|
|
168
|
+
const raw = process.env[key];
|
|
169
|
+
if (!raw || raw.length === 0) missing.push(key);
|
|
170
|
+
}
|
|
171
|
+
if (missing.length) {
|
|
172
|
+
console.error("\u274C Missing required environment variables:");
|
|
173
|
+
for (const k of missing) console.error(`- ${k}`);
|
|
174
|
+
process.exit(1);
|
|
175
|
+
}
|
|
176
|
+
console.log("\u2705 Environment looks good.");
|
|
177
|
+
});
|
|
178
|
+
program.parse(process.argv);
|
|
179
|
+
var hasSubcommand = process.argv.slice(2).some((a) => ["generate", "show", "check"].includes(a));
|
|
180
|
+
if (!hasSubcommand) {
|
|
181
|
+
const opts = program.opts();
|
|
182
|
+
const meta = loadMeta(opts.config ?? "env.meta.json");
|
|
183
|
+
fs.writeFileSync(opts.outExample ?? ".env.example", generateEnvExample(meta), "utf8");
|
|
184
|
+
fs.writeFileSync(opts.outDocs ?? "ENV.md", generateEnvDocs(meta), "utf8");
|
|
185
|
+
console.log(`Generated: ${opts.outExample ?? ".env.example"}, ${opts.outDocs ?? "ENV.md"}`);
|
|
186
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zod-envkit",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "Validate environment variables with Zod and generate .env.example",
|
|
5
5
|
"type": "module",
|
|
6
|
-
|
|
7
6
|
"main": "dist/index.cjs",
|
|
8
7
|
"module": "dist/index.js",
|
|
9
8
|
"types": "dist/index.d.ts",
|
|
10
|
-
|
|
11
9
|
"exports": {
|
|
12
10
|
".": {
|
|
13
11
|
"types": "./dist/index.d.ts",
|
|
@@ -15,28 +13,43 @@
|
|
|
15
13
|
"require": "./dist/index.cjs"
|
|
16
14
|
}
|
|
17
15
|
},
|
|
18
|
-
|
|
19
16
|
"bin": {
|
|
20
17
|
"zod-envkit": "dist/cli.js"
|
|
21
18
|
},
|
|
22
|
-
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md",
|
|
22
|
+
"CHANGELOG.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/nxtxe/zod-envkit.git"
|
|
28
|
+
},
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/nxtxe/zod-envkit/issues"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/nxtxe/zod-envkit#readme",
|
|
23
33
|
"scripts": {
|
|
24
34
|
"build": "tsup src/index.ts src/cli.ts --format esm,cjs --dts",
|
|
25
35
|
"dev": "tsup src/index.ts src/cli.ts --watch --dts",
|
|
26
36
|
"test": "vitest run",
|
|
27
37
|
"prepublishOnly": "npm run test && npm run build"
|
|
28
38
|
},
|
|
29
|
-
|
|
30
|
-
|
|
39
|
+
"keywords": [
|
|
40
|
+
"env",
|
|
41
|
+
"dotenv",
|
|
42
|
+
"zod",
|
|
43
|
+
"validation",
|
|
44
|
+
"cli"
|
|
45
|
+
],
|
|
31
46
|
"author": "",
|
|
32
47
|
"license": "MIT",
|
|
33
|
-
|
|
34
48
|
"dependencies": {
|
|
35
49
|
"commander": "^13.1.0",
|
|
36
50
|
"dotenv": "^17.2.3",
|
|
37
51
|
"zod": "^4.3.6"
|
|
38
52
|
},
|
|
39
|
-
|
|
40
53
|
"devDependencies": {
|
|
41
54
|
"@types/node": "^25.0.10",
|
|
42
55
|
"eslint": "^9.39.2",
|
package/.env.example
DELETED
package/ENV.md
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
# Environment variables
|
|
2
|
-
|
|
3
|
-
| Key | Required | Example | Description |
|
|
4
|
-
| :------------: | :--------: | :----------------------------------------: | :--------------------------: |
|
|
5
|
-
| NODE_ENV | yes | development | Runtime mode |
|
|
6
|
-
| PORT | yes | 3000 | HTTP port |
|
|
7
|
-
| DATABASE_URL | yes | postgresql://user:pass@localhost:5432/db | Postgres connection string |
|
package/env.meta.json
DELETED
package/src/cli.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { Command } from "commander";
|
|
5
|
-
import { generateEnvDocs, generateEnvExample, type EnvMeta } from "./generate.js";
|
|
6
|
-
|
|
7
|
-
const program = new Command();
|
|
8
|
-
|
|
9
|
-
program
|
|
10
|
-
.name("zod-envkit")
|
|
11
|
-
.description("Generate .env.example and ENV.md from env.meta.json")
|
|
12
|
-
.option("-c, --config <file>", "Path to env meta json", "env.meta.json")
|
|
13
|
-
.option("--out-example <file>", "Output file for .env.example", ".env.example")
|
|
14
|
-
.option("--out-docs <file>", "Output file for docs", "ENV.md")
|
|
15
|
-
.action((opts) => {
|
|
16
|
-
const configPath = path.resolve(process.cwd(), opts.config);
|
|
17
|
-
const raw = fs.readFileSync(configPath, "utf8");
|
|
18
|
-
const meta: EnvMeta = JSON.parse(raw);
|
|
19
|
-
|
|
20
|
-
fs.writeFileSync(opts.outExample, generateEnvExample(meta), "utf8");
|
|
21
|
-
fs.writeFileSync(opts.outDocs, generateEnvDocs(meta), "utf8");
|
|
22
|
-
|
|
23
|
-
console.log(`Generated: ${opts.outExample}, ${opts.outDocs}`);
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
program.parse();
|
package/src/generate.ts
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
// src/generate.ts
|
|
2
|
-
|
|
3
|
-
export type EnvMeta = Record<
|
|
4
|
-
string,
|
|
5
|
-
{
|
|
6
|
-
description?: string;
|
|
7
|
-
example?: string;
|
|
8
|
-
required?: boolean; // default: true
|
|
9
|
-
}
|
|
10
|
-
>;
|
|
11
|
-
|
|
12
|
-
function strLen(s: string): number {
|
|
13
|
-
return s.length;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function padCenter(text: string, width: number): string {
|
|
17
|
-
const t = text ?? "";
|
|
18
|
-
const diff = width - strLen(t);
|
|
19
|
-
if (diff <= 0) return t;
|
|
20
|
-
|
|
21
|
-
const left = Math.floor(diff / 2);
|
|
22
|
-
const right = diff - left;
|
|
23
|
-
return " ".repeat(left) + t + " ".repeat(right);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function padRight(text: string, width: number): string {
|
|
27
|
-
const t = text ?? "";
|
|
28
|
-
const diff = width - strLen(t);
|
|
29
|
-
if (diff <= 0) return t;
|
|
30
|
-
return t + " ".repeat(diff);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function makeDivider(width: number, align: "left" | "center" | "right"): string {
|
|
34
|
-
// Markdown alignment:
|
|
35
|
-
// left : ---
|
|
36
|
-
// center : :---:
|
|
37
|
-
// right : ---:
|
|
38
|
-
if (width < 3) width = 3;
|
|
39
|
-
|
|
40
|
-
if (align === "center") return ":" + "-".repeat(width - 2) + ":";
|
|
41
|
-
if (align === "right") return "-".repeat(width - 1) + ":";
|
|
42
|
-
return "-".repeat(width);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Генерит .env.example красиво:
|
|
47
|
-
* - комментарий с description
|
|
48
|
-
* - KEY=example
|
|
49
|
-
*/
|
|
50
|
-
export function generateEnvExample(meta: EnvMeta): string {
|
|
51
|
-
const lines: string[] = [];
|
|
52
|
-
|
|
53
|
-
for (const [key, m] of Object.entries(meta)) {
|
|
54
|
-
if (m.description) lines.push(`# ${m.description}`);
|
|
55
|
-
lines.push(`${key}=${m.example ?? ""}`);
|
|
56
|
-
lines.push("");
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
return lines.join("\n").trim() + "\n";
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Генерит ENV.md как ровную таблицу:
|
|
64
|
-
* - вычисляет ширины колонок по максимальной длине
|
|
65
|
-
* - паддит значения пробелами
|
|
66
|
-
* - ставит выравнивание :---: чтобы центрировалось в Markdown
|
|
67
|
-
*/
|
|
68
|
-
export function generateEnvDocs(meta: EnvMeta): string {
|
|
69
|
-
const headers = ["Key", "Required", "Example", "Description"] as const;
|
|
70
|
-
|
|
71
|
-
const rows = Object.entries(meta).map(([key, m]) => {
|
|
72
|
-
const req = m.required === false ? "no" : "yes";
|
|
73
|
-
return {
|
|
74
|
-
Key: key,
|
|
75
|
-
Required: req,
|
|
76
|
-
Example: m.example ?? "",
|
|
77
|
-
Description: m.description ?? "",
|
|
78
|
-
};
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
const widths = {
|
|
82
|
-
Key: headers[0].length,
|
|
83
|
-
Required: headers[1].length,
|
|
84
|
-
Example: headers[2].length,
|
|
85
|
-
Description: headers[3].length,
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
for (const r of rows) {
|
|
89
|
-
widths.Key = Math.max(widths.Key, strLen(r.Key));
|
|
90
|
-
widths.Required = Math.max(widths.Required, strLen(r.Required));
|
|
91
|
-
widths.Example = Math.max(widths.Example, strLen(r.Example));
|
|
92
|
-
widths.Description = Math.max(widths.Description, strLen(r.Description));
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
widths.Key += 2;
|
|
96
|
-
widths.Required += 2;
|
|
97
|
-
widths.Example += 2;
|
|
98
|
-
widths.Description += 2;
|
|
99
|
-
|
|
100
|
-
const headerLine =
|
|
101
|
-
`| ${padCenter(headers[0], widths.Key)} ` +
|
|
102
|
-
`| ${padCenter(headers[1], widths.Required)} ` +
|
|
103
|
-
`| ${padCenter(headers[2], widths.Example)} ` +
|
|
104
|
-
`| ${padCenter(headers[3], widths.Description)} |`;
|
|
105
|
-
|
|
106
|
-
const dividerLine =
|
|
107
|
-
`| ${makeDivider(widths.Key, "center")} ` +
|
|
108
|
-
`| ${makeDivider(widths.Required, "center")} ` +
|
|
109
|
-
`| ${makeDivider(widths.Example, "center")} ` +
|
|
110
|
-
`| ${makeDivider(widths.Description, "center")} |`;
|
|
111
|
-
|
|
112
|
-
const bodyLines = rows.map((r) => {
|
|
113
|
-
return (
|
|
114
|
-
`| ${padCenter(r.Key, widths.Key)} ` +
|
|
115
|
-
`| ${padCenter(r.Required, widths.Required)} ` +
|
|
116
|
-
`| ${padCenter(r.Example, widths.Example)} ` +
|
|
117
|
-
`| ${padCenter(r.Description, widths.Description)} |`
|
|
118
|
-
);
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
return [
|
|
123
|
-
`# Environment variables`,
|
|
124
|
-
``,
|
|
125
|
-
headerLine,
|
|
126
|
-
dividerLine,
|
|
127
|
-
...bodyLines,
|
|
128
|
-
``,
|
|
129
|
-
].join("\n");
|
|
130
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
|
|
3
|
-
export type EnvResult<T extends z.ZodTypeAny> = z.infer<T>;
|
|
4
|
-
|
|
5
|
-
export function loadEnv<T extends z.ZodTypeAny>(
|
|
6
|
-
schema: T,
|
|
7
|
-
opts?: { throwOnError?: boolean }
|
|
8
|
-
):
|
|
9
|
-
| { ok: true; env: z.infer<T> }
|
|
10
|
-
| { ok: false; error: z.ZodError } {
|
|
11
|
-
const parsed = schema.safeParse(process.env);
|
|
12
|
-
|
|
13
|
-
if (parsed.success) return { ok: true, env: parsed.data };
|
|
14
|
-
|
|
15
|
-
if (opts?.throwOnError) throw parsed.error;
|
|
16
|
-
return { ok: false, error: parsed.error };
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function formatZodError(err: z.ZodError): string {
|
|
20
|
-
return err.issues
|
|
21
|
-
.map((i) => `- ${i.path.join(".") || "(root)"}: ${i.message}`)
|
|
22
|
-
.join("\n");
|
|
23
|
-
}
|
package/test/basic.test.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect } from "vitest";
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
import { loadEnv } from "../src/index";
|
|
4
|
-
|
|
5
|
-
describe("loadEnv", () => {
|
|
6
|
-
it("parses valid env", () => {
|
|
7
|
-
process.env.PORT = "3000";
|
|
8
|
-
const schema = z.object({ PORT: z.coerce.number() });
|
|
9
|
-
|
|
10
|
-
const res = loadEnv(schema);
|
|
11
|
-
expect(res.ok).toBe(true);
|
|
12
|
-
|
|
13
|
-
if (res.ok) expect(res.env.PORT).toBe(3000);
|
|
14
|
-
});
|
|
15
|
-
});
|