@subramanyaks/env-drift 1.1.0 → 1.2.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/CHANGELOG.md +13 -0
- package/README.md +21 -5
- package/dist/cli.js +590 -35
- package/dist/index.cjs +524 -31
- package/dist/index.d.cts +81 -1
- package/dist/index.d.ts +81 -1
- package/dist/index.js +513 -29
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { realpathSync } from "fs";
|
|
5
|
-
import { resolve as
|
|
5
|
+
import { resolve as resolve5 } from "path";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
7
|
import { parseArgs } from "util";
|
|
8
8
|
import pc2 from "picocolors";
|
|
@@ -10,7 +10,7 @@ import pc2 from "picocolors";
|
|
|
10
10
|
// package.json
|
|
11
11
|
var package_default = {
|
|
12
12
|
name: "@subramanyaks/env-drift",
|
|
13
|
-
version: "1.
|
|
13
|
+
version: "1.2.0",
|
|
14
14
|
description: "Zero-config CLI and library to detect environment variable drift, missing keys, dead vars, and accidental public secret exposure.",
|
|
15
15
|
type: "module",
|
|
16
16
|
publishConfig: {
|
|
@@ -85,28 +85,31 @@ import { resolve } from "path";
|
|
|
85
85
|
// src/envParser.ts
|
|
86
86
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
87
87
|
var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
|
88
|
+
function parseDoubleQuotedValue(raw) {
|
|
89
|
+
let result = "";
|
|
90
|
+
for (let i = 1; i < raw.length; i++) {
|
|
91
|
+
const ch = raw[i];
|
|
92
|
+
if (ch === "\\" && i + 1 < raw.length) {
|
|
93
|
+
const next = raw[i + 1];
|
|
94
|
+
if (next === "n") result += "\n";
|
|
95
|
+
else if (next === "r") result += "\r";
|
|
96
|
+
else if (next === "t") result += " ";
|
|
97
|
+
else result += next;
|
|
98
|
+
i++;
|
|
99
|
+
} else if (ch === '"') {
|
|
100
|
+
return { value: result, closed: true };
|
|
101
|
+
} else {
|
|
102
|
+
result += ch;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { value: result, closed: false };
|
|
106
|
+
}
|
|
88
107
|
function parseValue(raw) {
|
|
89
108
|
const trimmed = raw.trim();
|
|
90
109
|
if (!trimmed) return "";
|
|
91
110
|
const quote = trimmed[0];
|
|
92
111
|
if (quote === '"') {
|
|
93
|
-
|
|
94
|
-
for (let i = 1; i < trimmed.length; i++) {
|
|
95
|
-
const ch = trimmed[i];
|
|
96
|
-
if (ch === "\\" && i + 1 < trimmed.length) {
|
|
97
|
-
const next = trimmed[i + 1];
|
|
98
|
-
if (next === "n") result += "\n";
|
|
99
|
-
else if (next === "r") result += "\r";
|
|
100
|
-
else if (next === "t") result += " ";
|
|
101
|
-
else result += next;
|
|
102
|
-
i++;
|
|
103
|
-
} else if (ch === '"') {
|
|
104
|
-
return result;
|
|
105
|
-
} else {
|
|
106
|
-
result += ch;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return result;
|
|
112
|
+
return parseDoubleQuotedValue(trimmed).value;
|
|
110
113
|
}
|
|
111
114
|
if (quote === "'") {
|
|
112
115
|
const closingIdx = trimmed.indexOf("'", 1);
|
|
@@ -137,14 +140,28 @@ function parseEnvContent(content) {
|
|
|
137
140
|
const key = match[1];
|
|
138
141
|
const rawValue = match[2] ?? "";
|
|
139
142
|
if (!key) continue;
|
|
143
|
+
const startLine = i + 1;
|
|
140
144
|
if (seen.has(key)) {
|
|
141
145
|
duplicateSet.add(key);
|
|
142
146
|
} else {
|
|
143
147
|
seen.add(key);
|
|
144
148
|
keys.push(key);
|
|
145
149
|
}
|
|
146
|
-
|
|
147
|
-
|
|
150
|
+
const trimmedVal = rawValue.trimStart();
|
|
151
|
+
if (trimmedVal.startsWith('"')) {
|
|
152
|
+
let combined = trimmedVal;
|
|
153
|
+
let parsed = parseDoubleQuotedValue(combined);
|
|
154
|
+
while (!parsed.closed && i + 1 < lines.length) {
|
|
155
|
+
i++;
|
|
156
|
+
combined += `
|
|
157
|
+
${lines[i]}`;
|
|
158
|
+
parsed = parseDoubleQuotedValue(combined);
|
|
159
|
+
}
|
|
160
|
+
values[key] = parsed.value;
|
|
161
|
+
} else {
|
|
162
|
+
values[key] = parseValue(rawValue);
|
|
163
|
+
}
|
|
164
|
+
keyLines[key] = startLine;
|
|
148
165
|
}
|
|
149
166
|
return {
|
|
150
167
|
keys,
|
|
@@ -229,12 +246,109 @@ var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
229
246
|
".svelte",
|
|
230
247
|
".astro"
|
|
231
248
|
]);
|
|
249
|
+
var REGEX_PRECEDING_KEYWORDS = /* @__PURE__ */ new Set([
|
|
250
|
+
"return",
|
|
251
|
+
"case",
|
|
252
|
+
"throw",
|
|
253
|
+
"in",
|
|
254
|
+
"of",
|
|
255
|
+
"typeof",
|
|
256
|
+
"void",
|
|
257
|
+
"delete",
|
|
258
|
+
"await",
|
|
259
|
+
"yield",
|
|
260
|
+
"else",
|
|
261
|
+
"do"
|
|
262
|
+
]);
|
|
232
263
|
function stripCommentsPreservingLines(source) {
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
264
|
+
const out = [];
|
|
265
|
+
const len = source.length;
|
|
266
|
+
let i = 0;
|
|
267
|
+
let prevSignificant = "";
|
|
268
|
+
let prevWord = "";
|
|
269
|
+
while (i < len) {
|
|
270
|
+
const ch = source[i];
|
|
271
|
+
const next = i + 1 < len ? source[i + 1] : "";
|
|
272
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
273
|
+
const quote = ch;
|
|
274
|
+
out.push(ch);
|
|
275
|
+
i++;
|
|
276
|
+
while (i < len) {
|
|
277
|
+
const c = source[i];
|
|
278
|
+
out.push(c);
|
|
279
|
+
i++;
|
|
280
|
+
if (c === "\\" && i < len) {
|
|
281
|
+
out.push(source[i]);
|
|
282
|
+
i++;
|
|
283
|
+
} else if (c === quote) {
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
prevSignificant = quote;
|
|
288
|
+
prevWord = "";
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
if (ch === "/" && next === "/") {
|
|
292
|
+
out.push(" ", " ");
|
|
293
|
+
i += 2;
|
|
294
|
+
while (i < len && source[i] !== "\n" && source[i] !== "\r") {
|
|
295
|
+
out.push(" ");
|
|
296
|
+
i++;
|
|
297
|
+
}
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (ch === "/" && next === "*") {
|
|
301
|
+
out.push(" ", " ");
|
|
302
|
+
i += 2;
|
|
303
|
+
while (i < len) {
|
|
304
|
+
if (source[i] === "*" && i + 1 < len && source[i + 1] === "/") {
|
|
305
|
+
out.push(" ", " ");
|
|
306
|
+
i += 2;
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
const c = source[i];
|
|
310
|
+
out.push(c === "\n" || c === "\r" ? c : " ");
|
|
311
|
+
i++;
|
|
312
|
+
}
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (ch === "/" && (prevSignificant === "" || "=([{,;:!&|?+-*%^~<>".includes(prevSignificant) || REGEX_PRECEDING_KEYWORDS.has(prevWord))) {
|
|
316
|
+
out.push(ch);
|
|
317
|
+
i++;
|
|
318
|
+
let inCharClass = false;
|
|
319
|
+
while (i < len) {
|
|
320
|
+
const c = source[i];
|
|
321
|
+
out.push(c);
|
|
322
|
+
i++;
|
|
323
|
+
if (c === "\\" && i < len) {
|
|
324
|
+
out.push(source[i]);
|
|
325
|
+
i++;
|
|
326
|
+
} else if (c === "[") {
|
|
327
|
+
inCharClass = true;
|
|
328
|
+
} else if (c === "]") {
|
|
329
|
+
inCharClass = false;
|
|
330
|
+
} else if (c === "/" && !inCharClass) {
|
|
331
|
+
break;
|
|
332
|
+
} else if (c === "\n" || c === "\r") {
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
prevSignificant = "/";
|
|
337
|
+
prevWord = "";
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
out.push(ch);
|
|
341
|
+
if (!/\s/.test(ch)) {
|
|
342
|
+
if (/[A-Za-z0-9_$]/.test(ch)) {
|
|
343
|
+
prevWord = /[A-Za-z0-9_$]/.test(prevSignificant) ? prevWord + ch : ch;
|
|
344
|
+
} else {
|
|
345
|
+
prevWord = "";
|
|
346
|
+
}
|
|
347
|
+
prevSignificant = ch;
|
|
348
|
+
}
|
|
349
|
+
i++;
|
|
350
|
+
}
|
|
351
|
+
return out.join("");
|
|
238
352
|
}
|
|
239
353
|
function getLineNumber(source, index) {
|
|
240
354
|
let line = 1;
|
|
@@ -579,6 +693,9 @@ function normalizeConfig(raw) {
|
|
|
579
693
|
if (publicPrefixes) config.publicPrefixes = publicPrefixes;
|
|
580
694
|
const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
|
|
581
695
|
if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
|
|
696
|
+
if (typeof obj.strict === "boolean") {
|
|
697
|
+
config.strict = obj.strict;
|
|
698
|
+
}
|
|
582
699
|
return config;
|
|
583
700
|
}
|
|
584
701
|
function loadConfig(rootDir) {
|
|
@@ -605,7 +722,45 @@ function loadConfig(rootDir) {
|
|
|
605
722
|
return {};
|
|
606
723
|
}
|
|
607
724
|
|
|
725
|
+
// src/diff.ts
|
|
726
|
+
import { resolve as resolve3 } from "path";
|
|
727
|
+
function diffEnvFiles(fileA, fileB, options = {}) {
|
|
728
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
729
|
+
const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
|
|
730
|
+
const parsedA = parseEnvFile(resolve3(rootDir, fileA));
|
|
731
|
+
const parsedB = parseEnvFile(resolve3(rootDir, fileB));
|
|
732
|
+
const keysA = parsedA.keys.filter((k) => !ignoreSet.has(k));
|
|
733
|
+
const keysB = parsedB.keys.filter((k) => !ignoreSet.has(k));
|
|
734
|
+
const setA = new Set(keysA);
|
|
735
|
+
const setB = new Set(keysB);
|
|
736
|
+
const onlyInA = keysA.filter((k) => !setB.has(k)).sort();
|
|
737
|
+
const onlyInB = keysB.filter((k) => !setA.has(k)).sort();
|
|
738
|
+
const inBoth = keysA.filter((k) => setB.has(k)).sort();
|
|
739
|
+
const emptyInA = keysA.filter((k) => (parsedA.values[k] ?? "").trim() === "").sort();
|
|
740
|
+
const emptyInB = keysB.filter((k) => (parsedB.values[k] ?? "").trim() === "").sort();
|
|
741
|
+
return {
|
|
742
|
+
fileA,
|
|
743
|
+
fileB,
|
|
744
|
+
fileAExists: parsedA.exists,
|
|
745
|
+
fileBExists: parsedB.exists,
|
|
746
|
+
onlyInA,
|
|
747
|
+
onlyInB,
|
|
748
|
+
inBoth,
|
|
749
|
+
emptyInA,
|
|
750
|
+
emptyInB
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
function hasDiffIssues(diff, options = {}) {
|
|
754
|
+
if (!diff.fileAExists || !diff.fileBExists) return true;
|
|
755
|
+
if (diff.onlyInA.length > 0 || diff.onlyInB.length > 0) return true;
|
|
756
|
+
if (options.strict && (diff.emptyInA.length > 0 || diff.emptyInB.length > 0)) {
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
|
|
608
762
|
// src/reporter.ts
|
|
763
|
+
import { relative as relative2 } from "path";
|
|
609
764
|
import pc from "picocolors";
|
|
610
765
|
function formatRefs(refs) {
|
|
611
766
|
if (!refs || refs.length === 0) return "";
|
|
@@ -615,7 +770,12 @@ function formatRefs(refs) {
|
|
|
615
770
|
}
|
|
616
771
|
function hasBlockingIssues(result, options = {}) {
|
|
617
772
|
const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
|
|
618
|
-
|
|
773
|
+
const baseBlocking = checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
|
|
774
|
+
if (baseBlocking) return true;
|
|
775
|
+
if (options.strict) {
|
|
776
|
+
return result.emptyInEnv.length > 0 || result.unusedInEnv.length > 0 || result.unusedInExample.length > 0 || result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0;
|
|
777
|
+
}
|
|
778
|
+
return false;
|
|
619
779
|
}
|
|
620
780
|
function formatAuditReport(result, options = {}) {
|
|
621
781
|
const envFile = options.envFile ?? ".env";
|
|
@@ -843,10 +1003,164 @@ function formatGitHubAnnotations(result, options = {}) {
|
|
|
843
1003
|
}
|
|
844
1004
|
return lines.join("\n");
|
|
845
1005
|
}
|
|
1006
|
+
function formatDiffReport(diff) {
|
|
1007
|
+
const lines = [];
|
|
1008
|
+
lines.push("");
|
|
1009
|
+
lines.push(
|
|
1010
|
+
`${pc.bold(pc.cyan("env-drift diff"))} ${pc.dim(`\u2014 ${diff.fileA} \u2194 ${diff.fileB}`)}`
|
|
1011
|
+
);
|
|
1012
|
+
lines.push("");
|
|
1013
|
+
if (!diff.fileAExists) {
|
|
1014
|
+
lines.push(pc.red(`\u2716 File not found: ${diff.fileA}`));
|
|
1015
|
+
}
|
|
1016
|
+
if (!diff.fileBExists) {
|
|
1017
|
+
lines.push(pc.red(`\u2716 File not found: ${diff.fileB}`));
|
|
1018
|
+
}
|
|
1019
|
+
if (!diff.fileAExists || !diff.fileBExists) {
|
|
1020
|
+
lines.push("");
|
|
1021
|
+
return lines.join("\n");
|
|
1022
|
+
}
|
|
1023
|
+
const totalIssues = diff.onlyInA.length + diff.onlyInB.length + diff.emptyInA.length + diff.emptyInB.length;
|
|
1024
|
+
if (totalIssues === 0) {
|
|
1025
|
+
lines.push(
|
|
1026
|
+
pc.green(
|
|
1027
|
+
`\u2714 No drift between ${diff.fileA} and ${diff.fileB} (${diff.inBoth.length} shared key${diff.inBoth.length === 1 ? "" : "s"}).`
|
|
1028
|
+
)
|
|
1029
|
+
);
|
|
1030
|
+
lines.push("");
|
|
1031
|
+
return lines.join("\n");
|
|
1032
|
+
}
|
|
1033
|
+
if (diff.onlyInA.length > 0) {
|
|
1034
|
+
lines.push(
|
|
1035
|
+
pc.bold(pc.red(`\u2716 Only in ${diff.fileA} (missing in ${diff.fileB}) (${diff.onlyInA.length})`))
|
|
1036
|
+
);
|
|
1037
|
+
for (const key of diff.onlyInA) {
|
|
1038
|
+
lines.push(` ${pc.red("\u2022")} ${key}`);
|
|
1039
|
+
}
|
|
1040
|
+
lines.push("");
|
|
1041
|
+
}
|
|
1042
|
+
if (diff.onlyInB.length > 0) {
|
|
1043
|
+
lines.push(
|
|
1044
|
+
pc.bold(pc.red(`\u2716 Only in ${diff.fileB} (missing in ${diff.fileA}) (${diff.onlyInB.length})`))
|
|
1045
|
+
);
|
|
1046
|
+
for (const key of diff.onlyInB) {
|
|
1047
|
+
lines.push(` ${pc.red("\u2022")} ${key}`);
|
|
1048
|
+
}
|
|
1049
|
+
lines.push("");
|
|
1050
|
+
}
|
|
1051
|
+
if (diff.emptyInA.length > 0) {
|
|
1052
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileA} (${diff.emptyInA.length})`)));
|
|
1053
|
+
for (const key of diff.emptyInA) {
|
|
1054
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}`);
|
|
1055
|
+
}
|
|
1056
|
+
lines.push("");
|
|
1057
|
+
}
|
|
1058
|
+
if (diff.emptyInB.length > 0) {
|
|
1059
|
+
lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileB} (${diff.emptyInB.length})`)));
|
|
1060
|
+
for (const key of diff.emptyInB) {
|
|
1061
|
+
lines.push(` ${pc.yellow("\u2022")} ${key}`);
|
|
1062
|
+
}
|
|
1063
|
+
lines.push("");
|
|
1064
|
+
}
|
|
1065
|
+
lines.push(pc.dim(`Shared keys in both files: ${diff.inBoth.length}`));
|
|
1066
|
+
lines.push("");
|
|
1067
|
+
return lines.join("\n");
|
|
1068
|
+
}
|
|
1069
|
+
function formatWorkspaceReport(wsResult, options = {}) {
|
|
1070
|
+
const lines = [];
|
|
1071
|
+
lines.push("");
|
|
1072
|
+
lines.push(
|
|
1073
|
+
`${pc.bold(pc.cyan("env-drift workspaces"))} ${pc.dim(
|
|
1074
|
+
`\u2014 audited ${wsResult.workspaces.length} workspace${wsResult.workspaces.length === 1 ? "" : "s"}`
|
|
1075
|
+
)}`
|
|
1076
|
+
);
|
|
1077
|
+
if (wsResult.workspaces.length === 0) {
|
|
1078
|
+
lines.push("");
|
|
1079
|
+
lines.push(pc.yellow("\u26A0 No workspaces found in package.json or pnpm-workspace.yaml."));
|
|
1080
|
+
lines.push("");
|
|
1081
|
+
return lines.join("\n");
|
|
1082
|
+
}
|
|
1083
|
+
for (const ws of wsResult.workspaces) {
|
|
1084
|
+
const rel = relative2(wsResult.rootDir, ws.path).replace(/\\/g, "/");
|
|
1085
|
+
lines.push("");
|
|
1086
|
+
lines.push(pc.bold(pc.white(`\u25B8 ${ws.name}`)) + pc.dim(` (${rel})`));
|
|
1087
|
+
lines.push(formatAuditReport(ws.result, options).trimEnd());
|
|
1088
|
+
}
|
|
1089
|
+
lines.push("");
|
|
1090
|
+
return lines.join("\n");
|
|
1091
|
+
}
|
|
846
1092
|
|
|
847
|
-
// src/
|
|
1093
|
+
// src/schemagen.ts
|
|
848
1094
|
import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
|
|
849
1095
|
import { dirname } from "path";
|
|
1096
|
+
function inferZodRule(key) {
|
|
1097
|
+
if (key === "NODE_ENV") {
|
|
1098
|
+
return 'z.enum(["development", "production", "test"]).default("development")';
|
|
1099
|
+
}
|
|
1100
|
+
if (/(?:^|_)(?:URL|URI|ENDPOINT)$/i.test(key)) {
|
|
1101
|
+
return "z.string().url()";
|
|
1102
|
+
}
|
|
1103
|
+
if (/^(?:PORT|.*_PORT|.*_TIMEOUT|.*_MS|.*_SECONDS)$/i.test(key)) {
|
|
1104
|
+
return "z.coerce.number()";
|
|
1105
|
+
}
|
|
1106
|
+
if (/^(?:ENABLE|DISABLE|IS|HAS|USE)_|_(?:ENABLED|DISABLED)$/i.test(key)) {
|
|
1107
|
+
return "z.coerce.boolean()";
|
|
1108
|
+
}
|
|
1109
|
+
return "z.string().min(1)";
|
|
1110
|
+
}
|
|
1111
|
+
function generateZodSchema(result) {
|
|
1112
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1113
|
+
let hasProcessOrServer = false;
|
|
1114
|
+
let hasImportMeta = false;
|
|
1115
|
+
for (const [key, refs] of Object.entries(result.usedInCode)) {
|
|
1116
|
+
if (BUILTIN_ENV_VARS.has(key)) continue;
|
|
1117
|
+
keys.add(key);
|
|
1118
|
+
for (const ref of refs) {
|
|
1119
|
+
if (ref.source === "import.meta.env") {
|
|
1120
|
+
hasImportMeta = true;
|
|
1121
|
+
} else {
|
|
1122
|
+
hasProcessOrServer = true;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
for (const key of result.unusedInExample) {
|
|
1127
|
+
if (!BUILTIN_ENV_VARS.has(key)) {
|
|
1128
|
+
keys.add(key);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
const sortedKeys = Array.from(keys).sort();
|
|
1132
|
+
const sourceExpr = hasImportMeta && !hasProcessOrServer ? "import.meta.env" : "process.env";
|
|
1133
|
+
const lines = [
|
|
1134
|
+
"// Auto-generated by env-drift. Customize validators as needed.",
|
|
1135
|
+
'import { z } from "zod";',
|
|
1136
|
+
"",
|
|
1137
|
+
"export const envSchema = z.object({"
|
|
1138
|
+
];
|
|
1139
|
+
for (const key of sortedKeys) {
|
|
1140
|
+
lines.push(` ${key}: ${inferZodRule(key)},`);
|
|
1141
|
+
}
|
|
1142
|
+
lines.push("});");
|
|
1143
|
+
lines.push("");
|
|
1144
|
+
lines.push("export type Env = z.infer<typeof envSchema>;");
|
|
1145
|
+
lines.push("");
|
|
1146
|
+
lines.push(`export const env = envSchema.parse(${sourceExpr});`);
|
|
1147
|
+
lines.push("");
|
|
1148
|
+
return lines.join("\n");
|
|
1149
|
+
}
|
|
1150
|
+
function writeZodSchema(outputPath, result) {
|
|
1151
|
+
const content = generateZodSchema(result);
|
|
1152
|
+
mkdirSync(dirname(outputPath), { recursive: true });
|
|
1153
|
+
writeFileSync2(outputPath, content, "utf-8");
|
|
1154
|
+
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
1155
|
+
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
1156
|
+
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
1157
|
+
]);
|
|
1158
|
+
return { outputPath, count: uniqueKeys.size };
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
// src/typegen.ts
|
|
1162
|
+
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
1163
|
+
import { dirname as dirname2 } from "path";
|
|
850
1164
|
function generateEnvTypes(result) {
|
|
851
1165
|
const processKeys = /* @__PURE__ */ new Set();
|
|
852
1166
|
const importMetaKeys = /* @__PURE__ */ new Set();
|
|
@@ -901,8 +1215,8 @@ function generateEnvTypes(result) {
|
|
|
901
1215
|
}
|
|
902
1216
|
function writeEnvTypes(outputPath, result) {
|
|
903
1217
|
const content = generateEnvTypes(result);
|
|
904
|
-
|
|
905
|
-
|
|
1218
|
+
mkdirSync2(dirname2(outputPath), { recursive: true });
|
|
1219
|
+
writeFileSync3(outputPath, content, "utf-8");
|
|
906
1220
|
const uniqueKeys = /* @__PURE__ */ new Set([
|
|
907
1221
|
...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
|
|
908
1222
|
...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
|
|
@@ -910,6 +1224,167 @@ function writeEnvTypes(outputPath, result) {
|
|
|
910
1224
|
return { outputPath, count: uniqueKeys.size };
|
|
911
1225
|
}
|
|
912
1226
|
|
|
1227
|
+
// src/workspaces.ts
|
|
1228
|
+
import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
|
|
1229
|
+
import { join as join2, relative as relative3, resolve as resolve4 } from "path";
|
|
1230
|
+
function readWorkspacePatterns(rootDir) {
|
|
1231
|
+
const pkgPath = resolve4(rootDir, "package.json");
|
|
1232
|
+
if (existsSync3(pkgPath)) {
|
|
1233
|
+
try {
|
|
1234
|
+
const parsed = JSON.parse(readFileSync4(pkgPath, "utf-8"));
|
|
1235
|
+
if (Array.isArray(parsed.workspaces)) {
|
|
1236
|
+
return parsed.workspaces.filter((p) => typeof p === "string");
|
|
1237
|
+
}
|
|
1238
|
+
if (parsed.workspaces && typeof parsed.workspaces === "object" && Array.isArray(parsed.workspaces.packages)) {
|
|
1239
|
+
return parsed.workspaces.packages.filter((p) => typeof p === "string");
|
|
1240
|
+
}
|
|
1241
|
+
} catch {
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
const pnpmPath = resolve4(rootDir, "pnpm-workspace.yaml");
|
|
1245
|
+
if (existsSync3(pnpmPath)) {
|
|
1246
|
+
const content = readFileSync4(pnpmPath, "utf-8");
|
|
1247
|
+
const patterns = [];
|
|
1248
|
+
let inPackages = false;
|
|
1249
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
1250
|
+
const line = rawLine.trim();
|
|
1251
|
+
if (!line || line.startsWith("#")) continue;
|
|
1252
|
+
if (/^packages\s*:/.test(line)) {
|
|
1253
|
+
inPackages = true;
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
if (inPackages) {
|
|
1257
|
+
if (line.startsWith("-")) {
|
|
1258
|
+
const item = line.slice(1).trim().replace(/^["']|["']$/g, "");
|
|
1259
|
+
if (item) patterns.push(item);
|
|
1260
|
+
} else if (/^[A-Za-z0-9_-]+\s*:/.test(line)) {
|
|
1261
|
+
inPackages = false;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
if (patterns.length > 0) return patterns;
|
|
1266
|
+
}
|
|
1267
|
+
return [];
|
|
1268
|
+
}
|
|
1269
|
+
function expandPattern(rootDir, pattern) {
|
|
1270
|
+
const cleaned = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
1271
|
+
const segments = cleaned.split("/").filter(Boolean);
|
|
1272
|
+
let currentDirs = [rootDir];
|
|
1273
|
+
for (const seg of segments) {
|
|
1274
|
+
const nextDirs = [];
|
|
1275
|
+
if (seg === "*" || seg === "**") {
|
|
1276
|
+
for (const dir of currentDirs) {
|
|
1277
|
+
if (!existsSync3(dir)) continue;
|
|
1278
|
+
for (const entry of readdirSync2(dir, { withFileTypes: true })) {
|
|
1279
|
+
if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
|
|
1280
|
+
nextDirs.push(join2(dir, entry.name));
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
} else if (seg.includes("*")) {
|
|
1285
|
+
const regex = new RegExp(
|
|
1286
|
+
"^" + seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"
|
|
1287
|
+
);
|
|
1288
|
+
for (const dir of currentDirs) {
|
|
1289
|
+
if (!existsSync3(dir)) continue;
|
|
1290
|
+
for (const entry of readdirSync2(dir, { withFileTypes: true })) {
|
|
1291
|
+
if (entry.isDirectory() && regex.test(entry.name)) {
|
|
1292
|
+
nextDirs.push(join2(dir, entry.name));
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
} else {
|
|
1297
|
+
for (const dir of currentDirs) {
|
|
1298
|
+
const candidate = join2(dir, seg);
|
|
1299
|
+
if (existsSync3(candidate) && statSync2(candidate).isDirectory()) {
|
|
1300
|
+
nextDirs.push(candidate);
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
currentDirs = nextDirs;
|
|
1305
|
+
}
|
|
1306
|
+
return currentDirs;
|
|
1307
|
+
}
|
|
1308
|
+
function discoverWorkspaces(rootDir) {
|
|
1309
|
+
const resolvedRoot = resolve4(rootDir);
|
|
1310
|
+
const patterns = readWorkspacePatterns(resolvedRoot);
|
|
1311
|
+
if (patterns.length === 0) return [];
|
|
1312
|
+
const included = /* @__PURE__ */ new Set();
|
|
1313
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
1314
|
+
for (const pattern of patterns) {
|
|
1315
|
+
if (pattern.startsWith("!")) {
|
|
1316
|
+
for (const dir of expandPattern(resolvedRoot, pattern.slice(1))) {
|
|
1317
|
+
excluded.add(resolve4(dir));
|
|
1318
|
+
}
|
|
1319
|
+
} else {
|
|
1320
|
+
for (const dir of expandPattern(resolvedRoot, pattern)) {
|
|
1321
|
+
included.add(resolve4(dir));
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
const results = [];
|
|
1326
|
+
for (const dir of included) {
|
|
1327
|
+
if (excluded.has(dir)) continue;
|
|
1328
|
+
const relPath = relative3(resolvedRoot, dir).replace(/\\/g, "/");
|
|
1329
|
+
let name = relPath;
|
|
1330
|
+
const pkgPath = join2(dir, "package.json");
|
|
1331
|
+
if (existsSync3(pkgPath)) {
|
|
1332
|
+
try {
|
|
1333
|
+
const pkg = JSON.parse(readFileSync4(pkgPath, "utf-8"));
|
|
1334
|
+
if (typeof pkg.name === "string" && pkg.name.trim()) {
|
|
1335
|
+
name = pkg.name.trim();
|
|
1336
|
+
}
|
|
1337
|
+
} catch {
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
results.push({ name, path: dir });
|
|
1341
|
+
}
|
|
1342
|
+
results.sort((a, b) => a.path.localeCompare(b.path));
|
|
1343
|
+
return results;
|
|
1344
|
+
}
|
|
1345
|
+
function auditWorkspaces(rootDir, options = {}) {
|
|
1346
|
+
const resolvedRoot = resolve4(rootDir);
|
|
1347
|
+
const discovered = discoverWorkspaces(resolvedRoot);
|
|
1348
|
+
const workspaces = [];
|
|
1349
|
+
for (const ws of discovered) {
|
|
1350
|
+
const wsConfig = loadConfig(ws.path);
|
|
1351
|
+
const mergedIgnore = [
|
|
1352
|
+
...options.ignore ?? [],
|
|
1353
|
+
...wsConfig.ignore ?? []
|
|
1354
|
+
];
|
|
1355
|
+
const mergedIgnoreDirs = [
|
|
1356
|
+
...options.ignoreDirs ?? [],
|
|
1357
|
+
...wsConfig.ignoreDirs ?? []
|
|
1358
|
+
];
|
|
1359
|
+
const mergedPrefixes = [
|
|
1360
|
+
...options.publicPrefixes ?? [],
|
|
1361
|
+
...wsConfig.publicPrefixes ?? []
|
|
1362
|
+
];
|
|
1363
|
+
const mergedKeywords = [
|
|
1364
|
+
...options.sensitiveKeywords ?? [],
|
|
1365
|
+
...wsConfig.sensitiveKeywords ?? []
|
|
1366
|
+
];
|
|
1367
|
+
const result = auditEnv({
|
|
1368
|
+
rootDir: ws.path,
|
|
1369
|
+
envFile: options.envFile ?? wsConfig.envFile,
|
|
1370
|
+
exampleFile: options.exampleFile ?? wsConfig.exampleFile,
|
|
1371
|
+
ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
|
|
1372
|
+
ignoreDirs: mergedIgnoreDirs.length > 0 ? mergedIgnoreDirs : void 0,
|
|
1373
|
+
publicPrefixes: mergedPrefixes.length > 0 ? mergedPrefixes : void 0,
|
|
1374
|
+
sensitiveKeywords: mergedKeywords.length > 0 ? mergedKeywords : void 0
|
|
1375
|
+
});
|
|
1376
|
+
workspaces.push({
|
|
1377
|
+
name: ws.name,
|
|
1378
|
+
path: ws.path,
|
|
1379
|
+
result
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
return {
|
|
1383
|
+
rootDir: resolvedRoot,
|
|
1384
|
+
workspaces
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
|
|
913
1388
|
// src/cli.ts
|
|
914
1389
|
var VERSION = package_default.version;
|
|
915
1390
|
var HELP_TEXT = `
|
|
@@ -917,6 +1392,7 @@ ${pc2.bold(pc2.cyan("@subramanyaks/env-drift"))} v${VERSION} \u2014 Detect envir
|
|
|
917
1392
|
|
|
918
1393
|
${pc2.bold("Usage:")}
|
|
919
1394
|
npx @subramanyaks/env-drift [options]
|
|
1395
|
+
npx @subramanyaks/env-drift --diff <fileA> <fileB> [options]
|
|
920
1396
|
|
|
921
1397
|
${pc2.bold("Options:")}
|
|
922
1398
|
-d, --dir <path> Project directory to scan (default: ".")
|
|
@@ -926,7 +1402,12 @@ ${pc2.bold("Options:")}
|
|
|
926
1402
|
--sync Safely append missing keys to .env.example as KEY=
|
|
927
1403
|
--types Generate env.d.ts for detected env variables
|
|
928
1404
|
--types-out <path> Output path for --types (default: "env.d.ts")
|
|
929
|
-
--
|
|
1405
|
+
--schema Generate Zod validation schema (env.schema.ts)
|
|
1406
|
+
--schema-out <path> Output path for --schema (default: "env.schema.ts")
|
|
1407
|
+
--diff Compare keys across two env files (e.g. --diff .env.staging .env.production)
|
|
1408
|
+
--workspaces Audit all monorepo workspaces (package.json / pnpm-workspace.yaml)
|
|
1409
|
+
--ci Exit with code 1 if blocking issues are found
|
|
1410
|
+
--strict In --ci mode, also fail on empty values, unused keys, and duplicates
|
|
930
1411
|
--format <type> Output format: text, json, or github (default: "text")
|
|
931
1412
|
--json Output audit results as JSON (alias for --format json)
|
|
932
1413
|
-v, --version Show version
|
|
@@ -934,6 +1415,7 @@ ${pc2.bold("Options:")}
|
|
|
934
1415
|
`;
|
|
935
1416
|
function runCli(argv = process.argv.slice(2)) {
|
|
936
1417
|
let values;
|
|
1418
|
+
let positionals;
|
|
937
1419
|
try {
|
|
938
1420
|
const parsed = parseArgs({
|
|
939
1421
|
args: argv,
|
|
@@ -945,15 +1427,22 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
945
1427
|
sync: { type: "boolean", default: false },
|
|
946
1428
|
types: { type: "boolean", default: false },
|
|
947
1429
|
"types-out": { type: "string" },
|
|
1430
|
+
schema: { type: "boolean", default: false },
|
|
1431
|
+
"schema-out": { type: "string" },
|
|
1432
|
+
diff: { type: "boolean", default: false },
|
|
1433
|
+
workspaces: { type: "boolean", default: false },
|
|
948
1434
|
ci: { type: "boolean", default: false },
|
|
1435
|
+
strict: { type: "boolean", default: false },
|
|
949
1436
|
format: { type: "string" },
|
|
950
1437
|
json: { type: "boolean", default: false },
|
|
951
1438
|
version: { type: "boolean", short: "v", default: false },
|
|
952
1439
|
help: { type: "boolean", short: "h", default: false }
|
|
953
1440
|
},
|
|
1441
|
+
allowPositionals: true,
|
|
954
1442
|
strict: true
|
|
955
1443
|
});
|
|
956
1444
|
values = parsed.values;
|
|
1445
|
+
positionals = parsed.positionals;
|
|
957
1446
|
} catch (err) {
|
|
958
1447
|
const msg = err instanceof Error ? err.message : String(err);
|
|
959
1448
|
console.error(pc2.red(`Error: ${msg}`));
|
|
@@ -975,7 +1464,7 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
975
1464
|
);
|
|
976
1465
|
return 1;
|
|
977
1466
|
}
|
|
978
|
-
const rootDir =
|
|
1467
|
+
const rootDir = resolve5(typeof values.dir === "string" ? values.dir : process.cwd());
|
|
979
1468
|
let fileConfig;
|
|
980
1469
|
try {
|
|
981
1470
|
fileConfig = loadConfig(rootDir);
|
|
@@ -986,8 +1475,66 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
986
1475
|
}
|
|
987
1476
|
const envFile = typeof values.env === "string" ? values.env : fileConfig.envFile;
|
|
988
1477
|
const exampleFile = typeof values.example === "string" ? values.example : fileConfig.exampleFile ?? ".env.example";
|
|
1478
|
+
const strict = Boolean(values.strict || fileConfig.strict);
|
|
989
1479
|
const cliIgnore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
990
1480
|
const mergedIgnore = [...fileConfig.ignore ?? [], ...cliIgnore];
|
|
1481
|
+
if (values.diff) {
|
|
1482
|
+
if (positionals.length < 2) {
|
|
1483
|
+
console.error(
|
|
1484
|
+
pc2.red("Error: --diff requires two file paths (e.g. `env-drift --diff .env.staging .env.production`).")
|
|
1485
|
+
);
|
|
1486
|
+
return 1;
|
|
1487
|
+
}
|
|
1488
|
+
const diffResult = diffEnvFiles(positionals[0], positionals[1], {
|
|
1489
|
+
rootDir,
|
|
1490
|
+
ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0
|
|
1491
|
+
});
|
|
1492
|
+
if (format === "json") {
|
|
1493
|
+
console.log(JSON.stringify(diffResult, null, 2));
|
|
1494
|
+
} else {
|
|
1495
|
+
console.log(formatDiffReport(diffResult));
|
|
1496
|
+
}
|
|
1497
|
+
if (values.ci && hasDiffIssues(diffResult, { strict })) {
|
|
1498
|
+
return 1;
|
|
1499
|
+
}
|
|
1500
|
+
return 0;
|
|
1501
|
+
}
|
|
1502
|
+
if (values.workspaces) {
|
|
1503
|
+
const wsResult = auditWorkspaces(rootDir, {
|
|
1504
|
+
envFile,
|
|
1505
|
+
exampleFile,
|
|
1506
|
+
ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
|
|
1507
|
+
ignoreDirs: fileConfig.ignoreDirs,
|
|
1508
|
+
publicPrefixes: fileConfig.publicPrefixes,
|
|
1509
|
+
sensitiveKeywords: fileConfig.sensitiveKeywords
|
|
1510
|
+
});
|
|
1511
|
+
if (format === "json") {
|
|
1512
|
+
console.log(JSON.stringify(wsResult, null, 2));
|
|
1513
|
+
} else if (format === "github") {
|
|
1514
|
+
const blocks = wsResult.workspaces.map(
|
|
1515
|
+
(ws) => formatGitHubAnnotations(ws.result, {
|
|
1516
|
+
envFile: envFile ?? ".env",
|
|
1517
|
+
exampleFile,
|
|
1518
|
+
ci: Boolean(values.ci)
|
|
1519
|
+
})
|
|
1520
|
+
).filter(Boolean);
|
|
1521
|
+
if (blocks.length > 0) {
|
|
1522
|
+
console.log(blocks.join("\n"));
|
|
1523
|
+
}
|
|
1524
|
+
} else {
|
|
1525
|
+
console.log(
|
|
1526
|
+
formatWorkspaceReport(wsResult, {
|
|
1527
|
+
envFile: envFile ?? ".env",
|
|
1528
|
+
exampleFile,
|
|
1529
|
+
ci: Boolean(values.ci)
|
|
1530
|
+
})
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
if (values.ci && wsResult.workspaces.some((ws) => hasBlockingIssues(ws.result, { strict }))) {
|
|
1534
|
+
return 1;
|
|
1535
|
+
}
|
|
1536
|
+
return 0;
|
|
1537
|
+
}
|
|
991
1538
|
const result = auditEnv({
|
|
992
1539
|
rootDir,
|
|
993
1540
|
envFile,
|
|
@@ -998,7 +1545,7 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
998
1545
|
sensitiveKeywords: fileConfig.sensitiveKeywords
|
|
999
1546
|
});
|
|
1000
1547
|
if (values.sync && result.missingInExample.length > 0) {
|
|
1001
|
-
const examplePath =
|
|
1548
|
+
const examplePath = resolve5(rootDir, exampleFile);
|
|
1002
1549
|
const synced = syncEnvExample(examplePath, result.missingInExample);
|
|
1003
1550
|
if (synced.added.length > 0) {
|
|
1004
1551
|
const addedSet = new Set(synced.added);
|
|
@@ -1014,12 +1561,20 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
1014
1561
|
}
|
|
1015
1562
|
if (values.types || typeof values["types-out"] === "string") {
|
|
1016
1563
|
const outFile = typeof values["types-out"] === "string" ? values["types-out"] : "env.d.ts";
|
|
1017
|
-
const outputPath =
|
|
1564
|
+
const outputPath = resolve5(rootDir, outFile);
|
|
1018
1565
|
const generated = writeEnvTypes(outputPath, result);
|
|
1019
1566
|
if (format === "text") {
|
|
1020
1567
|
console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
|
|
1021
1568
|
}
|
|
1022
1569
|
}
|
|
1570
|
+
if (values.schema || typeof values["schema-out"] === "string") {
|
|
1571
|
+
const outFile = typeof values["schema-out"] === "string" ? values["schema-out"] : "env.schema.ts";
|
|
1572
|
+
const outputPath = resolve5(rootDir, outFile);
|
|
1573
|
+
const generated = writeZodSchema(outputPath, result);
|
|
1574
|
+
if (format === "text") {
|
|
1575
|
+
console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1023
1578
|
if (format === "json") {
|
|
1024
1579
|
console.log(JSON.stringify(result, null, 2));
|
|
1025
1580
|
} else if (format === "github") {
|
|
@@ -1040,7 +1595,7 @@ function runCli(argv = process.argv.slice(2)) {
|
|
|
1040
1595
|
})
|
|
1041
1596
|
);
|
|
1042
1597
|
}
|
|
1043
|
-
if (values.ci && hasBlockingIssues(result)) {
|
|
1598
|
+
if (values.ci && hasBlockingIssues(result, { strict })) {
|
|
1044
1599
|
return 1;
|
|
1045
1600
|
}
|
|
1046
1601
|
return 0;
|