@jutaru-dev/envsonar 0.1.0 → 0.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/README.md +188 -176
- package/bin/envsonar.js +2 -0
- package/package.json +57 -46
- package/src/check.js +157 -146
- package/src/cli.js +303 -298
- package/src/parse.js +99 -98
- package/src/scan.js +272 -33
- package/types/check.d.ts +66 -0
- package/types/cli.d.ts +34 -0
- package/types/index.d.ts +4 -0
- package/types/parse.d.ts +26 -0
- package/types/profiles.d.ts +15 -0
- package/types/scan.d.ts +156 -0
package/src/scan.js
CHANGED
|
@@ -4,30 +4,38 @@ import { basename, extname, join, relative, sep } from "node:path";
|
|
|
4
4
|
import { PROFILES } from "./profiles.js";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* @typedef {{ optional?: boolean, ci?: boolean }} Flags
|
|
7
|
+
* @typedef {{ optional?: boolean, ci?: boolean, schema?: boolean }} Flags
|
|
8
8
|
* optional — the code has a fallback value; ci — the name is matched case-insensitively (.NET config, pydantic)
|
|
9
9
|
* @typedef {{ file: string, line: number } & Flags} Usage
|
|
10
10
|
* @typedef {{ key: string, line: number } & Flags} Found
|
|
11
11
|
* @typedef {{ file: string, line: number, expr: string }} DynamicRead
|
|
12
12
|
* @typedef {{ source: string, keys: string[] }} Implicit
|
|
13
|
+
* @typedef {{ key: string, source: string, base: boolean }} Provided
|
|
14
|
+
* base — the value applies in every environment (appsettings.json, compose); false for appsettings.<Environment>.json
|
|
15
|
+
* @typedef {{ cls: string, line: number, section?: string, sectionOf?: string }} Binding
|
|
16
|
+
* @typedef {{ name: string, line: number, optional: boolean }} OptionProp
|
|
17
|
+
* @typedef {{ props: OptionProp[], sectionName?: string }} OptionClass
|
|
13
18
|
* @typedef {{
|
|
14
19
|
* files: number,
|
|
15
20
|
* usages: Map<string, Usage[]>,
|
|
16
21
|
* sections: Map<string, Usage[]>,
|
|
17
22
|
* dynamic: DynamicRead[],
|
|
18
|
-
* provided: Map<string,
|
|
23
|
+
* provided: Map<string, Provided>,
|
|
19
24
|
* implicit: Implicit[],
|
|
20
25
|
* }} ScanResult
|
|
21
26
|
* @typedef {{
|
|
22
27
|
* add: (key: string, line: number, flags?: Flags) => void,
|
|
23
28
|
* section: (prefix: string, line: number) => void,
|
|
24
29
|
* dynamic: (expr: string, line: number) => void,
|
|
25
|
-
* provide: (key: string, source: string) => void,
|
|
30
|
+
* provide: (key: string, source: string, base?: boolean) => void,
|
|
31
|
+
* bind: (binding: Binding) => void,
|
|
32
|
+
* optionClass: (name: string, cls: OptionClass) => void,
|
|
26
33
|
* mark: (marker: string) => void,
|
|
27
34
|
* lineAt: (offset: number) => number,
|
|
28
35
|
* }} Sink
|
|
29
36
|
* @typedef {{ re: RegExp, call?: boolean, member?: boolean, optional?: boolean }} Pattern
|
|
30
|
-
* @typedef {{
|
|
37
|
+
* @typedef {{ line: string[], block: [string, string][], quotes: string, multiline?: string, triple?: boolean, lineAfterSpace?: boolean }} CommentStyle
|
|
38
|
+
* @typedef {{ name: string, test: (file: string) => boolean, comments?: CommentStyle, patterns: Pattern[], extra?: (text: string, sink: Sink, file: string) => void }} Language
|
|
31
39
|
*/
|
|
32
40
|
|
|
33
41
|
const K = String.raw`(?<key>[A-Za-z_][A-Za-z0-9_]*)`;
|
|
@@ -47,6 +55,97 @@ const byName = (pattern) => (/** @type {string} */ file) => pattern.test(basenam
|
|
|
47
55
|
const CALL_DEFAULT = /^\s*(?:,\s*[^\s)]|\)\s*(?:\?\?|\|\||or\b|\.unwrap_or|\.or\b|\{))/;
|
|
48
56
|
/** a fallback after a property read: `process.env.X ?? "a"`, `ENV["X"] || "a"` */
|
|
49
57
|
const MEMBER_DEFAULT = /^\s*(?:\?\?|\|\|)/;
|
|
58
|
+
/** a write, not a read: `process.env.X = "1"`, `os.environ["X"] += ...`, `process.env.X ??= ...` */
|
|
59
|
+
const ASSIGNMENT = /^\s*(?:=(?![=>])|[-+*%&|^]=|\/=|\?\?=|\|\|=|&&=|\+\+|--)/;
|
|
60
|
+
/** `delete process.env.X`, `del os.environ["X"]` */
|
|
61
|
+
const DELETION = /\b(?:delete|del)\s+(?:os\.)?$/;
|
|
62
|
+
|
|
63
|
+
/** @type {Record<string, CommentStyle>} */
|
|
64
|
+
export const COMMENT_STYLES = {
|
|
65
|
+
c: { line: ["//"], block: [["/*", "*/"]], quotes: "'\"`", multiline: "`" },
|
|
66
|
+
rust: { line: ["//"], block: [["/*", "*/"]], quotes: '"' },
|
|
67
|
+
python: { line: ["#"], block: [], quotes: "'\"", triple: true },
|
|
68
|
+
ruby: { line: ["#"], block: [], quotes: "'\"" },
|
|
69
|
+
php: { line: ["//", "#"], block: [["/*", "*/"]], quotes: "'\"" },
|
|
70
|
+
yaml: { line: ["#"], block: [], quotes: "'\"", lineAfterSpace: true },
|
|
71
|
+
html: { line: [], block: [["<!--", "-->"]], quotes: "" },
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Blanks out comments (and Python docstrings) so reads inside them don't count. Strings are kept, so
|
|
76
|
+
* `"http://x"` isn't mistaken for a comment; newlines are kept, so line numbers don't move.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} text
|
|
79
|
+
* @param {CommentStyle} style
|
|
80
|
+
*/
|
|
81
|
+
export function stripComments(text, style) {
|
|
82
|
+
const n = text.length;
|
|
83
|
+
let out = "";
|
|
84
|
+
let start = 0;
|
|
85
|
+
let i = 0;
|
|
86
|
+
const blank = (/** @type {number} */ from, /** @type {number} */ to) => {
|
|
87
|
+
out += text.slice(start, from) + text.slice(from, to).replace(/[^\n]/g, " ");
|
|
88
|
+
start = to;
|
|
89
|
+
};
|
|
90
|
+
scan: while (i < n) {
|
|
91
|
+
const ch = text[i];
|
|
92
|
+
if (style.triple && (text.startsWith('"""', i) || text.startsWith("'''", i))) {
|
|
93
|
+
const end = text.indexOf(text.slice(i, i + 3), i + 3);
|
|
94
|
+
const to = end < 0 ? n : end + 3;
|
|
95
|
+
blank(i, to);
|
|
96
|
+
i = to;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (style.quotes.includes(ch)) {
|
|
100
|
+
const multi = style.multiline?.includes(ch);
|
|
101
|
+
let j = i + 1;
|
|
102
|
+
while (j < n && text[j] !== ch && (multi || text[j] !== "\n")) j += text[j] === "\\" ? 2 : 1;
|
|
103
|
+
i = j + 1;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
for (const open of style.line) {
|
|
107
|
+
if (text.startsWith(open, i) && (!style.lineAfterSpace || i === 0 || /\s/.test(text[i - 1]))) {
|
|
108
|
+
const end = text.indexOf("\n", i);
|
|
109
|
+
const to = end < 0 ? n : end;
|
|
110
|
+
blank(i, to);
|
|
111
|
+
i = to;
|
|
112
|
+
continue scan;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const [open, close] of style.block) {
|
|
116
|
+
if (text.startsWith(open, i)) {
|
|
117
|
+
const end = text.indexOf(close, i + open.length);
|
|
118
|
+
const to = end < 0 ? n : end + close.length;
|
|
119
|
+
blank(i, to);
|
|
120
|
+
i = to;
|
|
121
|
+
continue scan;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
i++;
|
|
125
|
+
}
|
|
126
|
+
return out + text.slice(start);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The expression that starts at `from` and runs to the next top-level `,` or the closing bracket:
|
|
131
|
+
* `z.coerce\n .number()\n .default(3000)` as one piece, however a formatter wrapped it.
|
|
132
|
+
*
|
|
133
|
+
* @param {string} text
|
|
134
|
+
* @param {number} from
|
|
135
|
+
*/
|
|
136
|
+
function expressionAt(text, from) {
|
|
137
|
+
let depth = 0;
|
|
138
|
+
const limit = Math.min(text.length, from + 2000);
|
|
139
|
+
for (let i = from; i < limit; i++) {
|
|
140
|
+
const ch = text[i];
|
|
141
|
+
if (ch === "(" || ch === "[" || ch === "{") depth++;
|
|
142
|
+
else if (ch === ")" || ch === "]" || ch === "}") {
|
|
143
|
+
if (depth === 0) return text.slice(from, i);
|
|
144
|
+
depth--;
|
|
145
|
+
} else if (ch === "," && depth === 0) return text.slice(from, i);
|
|
146
|
+
}
|
|
147
|
+
return text.slice(from, limit);
|
|
148
|
+
}
|
|
50
149
|
|
|
51
150
|
/**
|
|
52
151
|
* Reads through a local alias of the environment: `const env = process.env; env.KEY`, `env = dict(os.environ); env.get("KEY")`.
|
|
@@ -97,14 +196,17 @@ function jsExtra(text, sink) {
|
|
|
97
196
|
|
|
98
197
|
// envalid: cleanEnv(process.env, { PORT: port({ default: 3000 }) })
|
|
99
198
|
if (/\bcleanEnv\s*\(/.test(text)) {
|
|
100
|
-
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*(?:str|num|bool|port|url|email|host|json)\s*\(
|
|
101
|
-
|
|
199
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*(?:str|num|bool|port|url|email|host|json)\s*\(/g)) {
|
|
200
|
+
const expr = expressionAt(text, (m.index ?? 0) + m[0].length);
|
|
201
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\bdefault\s*:/.test(expr), schema: true });
|
|
102
202
|
}
|
|
103
203
|
}
|
|
104
204
|
// zod schemas parsed from the environment, and @t3-oss/env: createEnv({ server: { DATABASE_URL: z.string() } })
|
|
105
205
|
if (/\bcreateEnv\s*\(|\b(?:safeParse|parse)\(\s*(?:process\.env|import\.meta\.env)\b/.test(text)) {
|
|
106
|
-
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*z\s
|
|
107
|
-
|
|
206
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*z\s*\./g)) {
|
|
207
|
+
const expr = expressionAt(text, (m.index ?? 0) + m[0].length);
|
|
208
|
+
// the schema decides: t3-env's `runtimeEnv: { PORT: process.env.PORT }` only passes the value through
|
|
209
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\.\s*(?:default|optional)\s*\(/.test(expr), schema: true });
|
|
108
210
|
}
|
|
109
211
|
}
|
|
110
212
|
}
|
|
@@ -149,16 +251,21 @@ function pydanticSettings(text, sink) {
|
|
|
149
251
|
if (indentOf(l) !== fieldIndent) continue;
|
|
150
252
|
const f = /^\s*([A-Za-z_]\w*)\s*:\s*([^=]*?)\s*(?:=\s*(.*))?$/.exec(l);
|
|
151
253
|
if (!f || f[1] === "model_config" || f[1].startsWith("_") || /\bClassVar\b/.test(f[2])) continue;
|
|
152
|
-
|
|
254
|
+
let value = f[3]?.trim();
|
|
255
|
+
// Field( spread over several lines by a formatter: read on until the parentheses balance
|
|
256
|
+
for (let k = j + 1; value !== undefined && k < lines.length && balance(value) > 0; k++) value = `${value} ${lines[k].trim()}`;
|
|
153
257
|
const alias = /\b(?:validation_)?alias\s*=\s*['"]([^'"]+)['"]/.exec(value ?? "")?.[1];
|
|
154
258
|
const optional =
|
|
155
259
|
value !== undefined &&
|
|
156
|
-
(!value.startsWith("Field(") || /\bdefault(?:_factory)?\s*=/.test(value) || /^Field\(\s*(
|
|
260
|
+
(!value.startsWith("Field(") || /\bdefault(?:_factory)?\s*=/.test(value) || /^Field\(\s*(?=[^\s.)])(?!\w+\s*=)/.test(value));
|
|
157
261
|
sink.add(alias ?? (prefix + f[1]).toUpperCase(), j + 1, { ci: true, optional });
|
|
158
262
|
}
|
|
159
263
|
}
|
|
160
264
|
}
|
|
161
265
|
|
|
266
|
+
/** @param {string} s */
|
|
267
|
+
const balance = (s) => (s.match(/\(/g)?.length ?? 0) - (s.match(/\)/g)?.length ?? 0);
|
|
268
|
+
|
|
162
269
|
/** @param {string} path */
|
|
163
270
|
const netKey = (path) => path.replace(/:/g, "__");
|
|
164
271
|
|
|
@@ -186,6 +293,62 @@ function csExtra(text, sink) {
|
|
|
186
293
|
for (const m of text.matchAll(re(String.raw`\.(?:GetSection|GetRequiredSection|BindConfiguration)\(\s*"${NET_PATH}"`))) {
|
|
187
294
|
sink.section(`${netKey(m.groups?.path ?? "")}__`, sink.lineAt(m.index ?? 0));
|
|
188
295
|
}
|
|
296
|
+
optionsPattern(text, sink);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** @param {string} suffix */
|
|
300
|
+
const sectionArg = (suffix) => String.raw`(?:"(?<path${suffix}>[A-Za-z_][\w.:-]*)"|(?<owner${suffix}>\w+)\.SectionName)`;
|
|
301
|
+
/** non-nullable value types have a default (0, false) even without an initializer */
|
|
302
|
+
const VALUE_TYPE = /^(?:int|long|short|byte|bool|double|float|decimal|TimeSpan|DateTime|DateTimeOffset|Guid)$/;
|
|
303
|
+
const SIMPLE_TYPE = /^(?:string|String|int|long|short|byte|bool|double|float|decimal|TimeSpan|DateTime|DateTimeOffset|Guid|Uri)\??$/;
|
|
304
|
+
/** `= ""`, `= string.Empty`, `= null!` mean "must be configured", not a real default */
|
|
305
|
+
const PLACEHOLDER = /^(?:""|string\.Empty|String\.Empty|null!?|default!?)$/;
|
|
306
|
+
const OPTION_BINDINGS = [
|
|
307
|
+
re(String.raw`\bConfigure<(?<cls>\w+)>\([^;]*?\bGet(?:Required)?Section\(\s*${sectionArg("")}\s*\)`),
|
|
308
|
+
re(String.raw`\bGet(?:Required)?Section\(\s*${sectionArg("")}\s*\)\s*\.\s*Get<(?<cls>\w+)>`),
|
|
309
|
+
re(String.raw`\bAddOptions<(?<cls>\w+)>\(\s*\)[^;]*?\.\s*(?:BindConfiguration\(\s*${sectionArg("")}|Bind\([^;]*?\bGet(?:Required)?Section\(\s*${sectionArg("2")})`),
|
|
310
|
+
];
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The options pattern: `Configure<JwtOptions>(config.GetSection("Jwt"))`, `GetSection("Jwt").Get<JwtOptions>()`,
|
|
314
|
+
* `AddOptions<JwtOptions>().BindConfiguration("Jwt")` read every property of JwtOptions as `Jwt__<Property>`.
|
|
315
|
+
* Bindings and classes usually live in different files; scanProject matches them up.
|
|
316
|
+
*
|
|
317
|
+
* @param {string} text
|
|
318
|
+
* @param {Sink} sink
|
|
319
|
+
*/
|
|
320
|
+
function optionsPattern(text, sink) {
|
|
321
|
+
for (const pattern of OPTION_BINDINGS) {
|
|
322
|
+
for (const m of text.matchAll(pattern)) {
|
|
323
|
+
const g = m.groups ?? {};
|
|
324
|
+
const path = g.path ?? g.path2;
|
|
325
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
326
|
+
sink.bind(path ? { cls: g.cls, line, section: netKey(path) } : { cls: g.cls, line, sectionOf: g.owner ?? g.owner2 });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const classes = [...text.matchAll(/\b(?:class|record)\s+(\w+)/g)];
|
|
330
|
+
for (let c = 0; c < classes.length; c++) {
|
|
331
|
+
const begin = classes[c].index ?? 0;
|
|
332
|
+
const body = text.slice(begin, classes[c + 1]?.index ?? text.length);
|
|
333
|
+
/** @type {OptionProp[]} */
|
|
334
|
+
const props = [];
|
|
335
|
+
for (const m of body.matchAll(/(?<attrs>(?:\[[^\]]*\]\s*)*)\bpublic\s+(?<req>required\s+)?(?<type>[\w.?]+)\s+(?<name>[A-Z]\w*)\s*\{\s*get;\s*(?:set|init);\s*\}(?:\s*=\s*(?<init>[^;]+);)?/g)) {
|
|
336
|
+
const g = m.groups ?? {};
|
|
337
|
+
if (!SIMPLE_TYPE.test(g.type)) continue; // nested option classes and collections aren't followed
|
|
338
|
+
const init = g.init?.trim();
|
|
339
|
+
const required = Boolean(g.req) || /\bRequired\b/.test(g.attrs);
|
|
340
|
+
const optional = !required && (g.type.endsWith("?") || VALUE_TYPE.test(g.type) || (init !== undefined && !PLACEHOLDER.test(init)));
|
|
341
|
+
props.push({ name: g.name, line: sink.lineAt(begin + (m.index ?? 0) + g.attrs.length), optional });
|
|
342
|
+
}
|
|
343
|
+
// positional records: record JwtOptions(string Key, int Ttl = 60)
|
|
344
|
+
const positional = /^record\s+\w+\s*\(([^)]*)\)/.exec(body);
|
|
345
|
+
for (const param of positional?.[1].split(",") ?? []) {
|
|
346
|
+
const pm = /^\s*(?:\[[^\]]*\]\s*)*([\w.?]+)\s+([A-Z]\w*)\s*(=\s*.+)?$/.exec(param);
|
|
347
|
+
if (pm && SIMPLE_TYPE.test(pm[1])) props.push({ name: pm[2], line: sink.lineAt(begin), optional: Boolean(pm[3]) || pm[1].endsWith("?") });
|
|
348
|
+
}
|
|
349
|
+
const sectionName = /\bconst\s+string\s+SectionName\s*=\s*"([^"]+)"/.exec(body)?.[1];
|
|
350
|
+
if (props.length || sectionName) sink.optionClass(classes[c][1], { props, ...(sectionName ? { sectionName: netKey(sectionName) } : {}) });
|
|
351
|
+
}
|
|
189
352
|
}
|
|
190
353
|
|
|
191
354
|
/** Struct tags of caarlos0/env and kelseyhightower/envconfig: `env:"PORT" envDefault:"3000"`. @param {string} text @param {Sink} sink */
|
|
@@ -219,7 +382,7 @@ function composeExtra(text, sink, file) {
|
|
|
219
382
|
if (!l.trim() || l.trim().startsWith("#")) continue;
|
|
220
383
|
if (l.length - l.trimStart().length <= head[1].length) break;
|
|
221
384
|
const entry = /^\s*-?\s*["']?([A-Za-z_][\w.]*)["']?\s*[:=]\s*\S/.exec(l);
|
|
222
|
-
if (entry) sink.provide(entry[1], file);
|
|
385
|
+
if (entry) sink.provide(entry[1], file, true);
|
|
223
386
|
}
|
|
224
387
|
}
|
|
225
388
|
}
|
|
@@ -229,6 +392,7 @@ export const LANGUAGES = [
|
|
|
229
392
|
{
|
|
230
393
|
name: "JavaScript / TypeScript",
|
|
231
394
|
test: byExt(".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte", ".astro"),
|
|
395
|
+
comments: COMMENT_STYLES.c,
|
|
232
396
|
patterns: [
|
|
233
397
|
{ re: re(String.raw`\b${JS_ENV}\.${K}\b(?!\s*\()`), member: true },
|
|
234
398
|
{ re: re(String.raw`\b${JS_ENV}\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
@@ -236,10 +400,11 @@ export const LANGUAGES = [
|
|
|
236
400
|
],
|
|
237
401
|
extra: jsExtra,
|
|
238
402
|
},
|
|
239
|
-
{ name: "Vite index.html", test: byName(/^index\.html$/i), patterns: [{ re: /%(?<key>[A-Z][A-Z0-9_]*)%/g }] },
|
|
403
|
+
{ name: "Vite index.html", test: byName(/^index\.html$/i), comments: COMMENT_STYLES.html, patterns: [{ re: /%(?<key>[A-Z][A-Z0-9_]*)%/g }] },
|
|
240
404
|
{
|
|
241
405
|
name: "Python",
|
|
242
406
|
test: byExt(".py"),
|
|
407
|
+
comments: COMMENT_STYLES.python,
|
|
243
408
|
patterns: [
|
|
244
409
|
{ re: re(String.raw`\b(?:getenv|environ\.get|environ\.setdefault|environ\.pop)\(\s*${Q}${K}${QS}`), call: true },
|
|
245
410
|
{ re: re(String.raw`\benviron\[\s*${Q}${K}${QS}\s*\]`) },
|
|
@@ -249,12 +414,14 @@ export const LANGUAGES = [
|
|
|
249
414
|
{
|
|
250
415
|
name: "C# / .NET",
|
|
251
416
|
test: byExt(".cs"),
|
|
417
|
+
comments: COMMENT_STYLES.c,
|
|
252
418
|
patterns: [{ re: re(String.raw`\bGetEnvironmentVariable\(\s*@?"${K}"`), call: true }],
|
|
253
419
|
extra: csExtra,
|
|
254
420
|
},
|
|
255
421
|
{
|
|
256
422
|
name: "PHP / Laravel",
|
|
257
423
|
test: byExt(".php"),
|
|
424
|
+
comments: COMMENT_STYLES.php,
|
|
258
425
|
patterns: [
|
|
259
426
|
{ re: re(String.raw`(?<![\w$>:])(?:env|getenv)\(\s*${Q}${K}${QS}`), call: true },
|
|
260
427
|
{ re: re(String.raw`\$_ENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
@@ -263,12 +430,14 @@ export const LANGUAGES = [
|
|
|
263
430
|
{
|
|
264
431
|
name: "Go",
|
|
265
432
|
test: byExt(".go"),
|
|
433
|
+
comments: COMMENT_STYLES.c,
|
|
266
434
|
patterns: [{ re: re(String.raw`\bos\.Getenv\(\s*"${K}"`) }, { re: re(String.raw`\bos\.LookupEnv\(\s*"${K}"`), optional: true }],
|
|
267
435
|
extra: goExtra,
|
|
268
436
|
},
|
|
269
437
|
{
|
|
270
438
|
name: "Ruby",
|
|
271
439
|
test: byExt(".rb", ".rake"),
|
|
440
|
+
comments: COMMENT_STYLES.ruby,
|
|
272
441
|
patterns: [
|
|
273
442
|
{ re: re(String.raw`\bENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
274
443
|
{ re: re(String.raw`\bENV\.fetch\(\s*${Q}${K}${QS}`), call: true },
|
|
@@ -277,6 +446,7 @@ export const LANGUAGES = [
|
|
|
277
446
|
{
|
|
278
447
|
name: "Rust",
|
|
279
448
|
test: byExt(".rs"),
|
|
449
|
+
comments: COMMENT_STYLES.rust,
|
|
280
450
|
patterns: [
|
|
281
451
|
{ re: re(String.raw`\b(?:env|dotenvy?)::var(?:_os)?\(\s*"${K}"`), call: true },
|
|
282
452
|
{ re: re(String.raw`\benv!\(\s*"${K}"`) },
|
|
@@ -286,11 +456,13 @@ export const LANGUAGES = [
|
|
|
286
456
|
{
|
|
287
457
|
name: "Prisma",
|
|
288
458
|
test: (file) => extname(file).toLowerCase() === ".prisma" || /^prisma\.config\.[cm]?[jt]s$/i.test(basename(file)),
|
|
459
|
+
comments: COMMENT_STYLES.c,
|
|
289
460
|
patterns: [{ re: re(String.raw`\benv\(\s*${Q}${K}${QS}\s*\)`) }],
|
|
290
461
|
},
|
|
291
462
|
{
|
|
292
463
|
name: "Docker Compose",
|
|
293
464
|
test: byName(/^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i),
|
|
465
|
+
comments: COMMENT_STYLES.yaml,
|
|
294
466
|
patterns: [{ re: /\$\{(?<key>[A-Za-z_][A-Za-z0-9_]*)(?:(?<def>:?[-?+])|(?=}))/g }, { re: /(?<![$\w])\$(?<key>[A-Za-z_][A-Za-z0-9_]*)/g }],
|
|
295
467
|
extra: composeExtra,
|
|
296
468
|
},
|
|
@@ -298,7 +470,7 @@ export const LANGUAGES = [
|
|
|
298
470
|
|
|
299
471
|
export const DEFAULT_IGNORE_DIRS = [
|
|
300
472
|
"node_modules", ".git", ".hg", ".svn", "dist", "build", "out", ".next", ".nuxt", ".output", ".svelte-kit",
|
|
301
|
-
".vercel", ".netlify", ".turbo", ".cache", "coverage", "vendor", "
|
|
473
|
+
".vercel", ".netlify", ".turbo", ".cache", "coverage", "vendor", "target", ".venv", "venv",
|
|
302
474
|
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".idea", ".vscode", ".worktrees",
|
|
303
475
|
".claude", ".pnpm-store", ".yarn", ".expo", ".angular", ".gradle", "Pods", "DerivedData",
|
|
304
476
|
];
|
|
@@ -312,6 +484,14 @@ export const DEFAULT_IGNORE_KEYS = [
|
|
|
312
484
|
|
|
313
485
|
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
314
486
|
|
|
487
|
+
/** Test code sets and mocks variables; it isn't what the app needs at runtime. `--include-tests` scans it anyway. */
|
|
488
|
+
export const TEST_DIRS = ["test", "tests", "__tests__", "__mocks__", "spec", "specs", "e2e", "cypress"];
|
|
489
|
+
const TEST_PROJECT = /\.Tests?$/; // .NET test projects: Api.Tests
|
|
490
|
+
const TEST_FILE = /(?:\.(?:test|spec)\.[^.]+$|_test\.(?:go|py)$|^test_.*\.py$|^conftest\.py$|Tests?\.cs$)/;
|
|
491
|
+
/** .NET build output; skipped only next to a project file, so a Node or Go `bin/` is still read */
|
|
492
|
+
const NET_OUTPUT = new Set(["bin", "obj"]);
|
|
493
|
+
const NET_PROJECT = /\.(?:cs|fs|vb)proj$/i;
|
|
494
|
+
|
|
315
495
|
/**
|
|
316
496
|
* @param {string[]} patterns exact names or prefixes ending with `*`
|
|
317
497
|
* @returns {(key: string) => boolean}
|
|
@@ -335,6 +515,7 @@ function applyPatterns(text, patterns, sink) {
|
|
|
335
515
|
const end = (m.index ?? 0) + m[0].length;
|
|
336
516
|
const after = text.slice(end, end + 40);
|
|
337
517
|
const def = m.groups?.def;
|
|
518
|
+
if (ASSIGNMENT.test(after) || DELETION.test(text.slice(Math.max(0, (m.index ?? 0) - 12), m.index ?? 0))) continue;
|
|
338
519
|
const optional =
|
|
339
520
|
Boolean(p.optional) || (def !== undefined && /^:?[-+]/.test(def)) || (p.call === true && CALL_DEFAULT.test(after)) || (p.member === true && MEMBER_DEFAULT.test(after));
|
|
340
521
|
sink.add(key, sink.lineAt(m.index ?? 0), { optional });
|
|
@@ -355,8 +536,12 @@ export function extractFile(text, file) {
|
|
|
355
536
|
const sections = [];
|
|
356
537
|
/** @type {{ expr: string, line: number }[]} */
|
|
357
538
|
const dynamic = [];
|
|
358
|
-
/** @type {
|
|
539
|
+
/** @type {Provided[]} */
|
|
359
540
|
const provided = [];
|
|
541
|
+
/** @type {Binding[]} */
|
|
542
|
+
const bindings = [];
|
|
543
|
+
/** @type {Map<string, OptionClass>} */
|
|
544
|
+
const optionClasses = new Map();
|
|
360
545
|
/** @type {Set<string>} */
|
|
361
546
|
const markers = new Set();
|
|
362
547
|
const langs = LANGUAGES.filter((l) => l.test(file));
|
|
@@ -366,20 +551,29 @@ export function extractFile(text, file) {
|
|
|
366
551
|
add(key, line, flags = {}) {
|
|
367
552
|
const id = `${key}:${line}`;
|
|
368
553
|
if (found.has(id)) return;
|
|
369
|
-
found.set(id, { key, line, ...(flags.optional ? { optional: true } : {}), ...(flags.ci ? { ci: true } : {}) });
|
|
554
|
+
found.set(id, { key, line, ...(flags.optional ? { optional: true } : {}), ...(flags.ci ? { ci: true } : {}), ...(flags.schema ? { schema: true } : {}) });
|
|
370
555
|
},
|
|
371
556
|
section: (key, line) => sections.push({ key, line }),
|
|
372
557
|
dynamic: (expr, line) => dynamic.push({ expr, line }),
|
|
373
|
-
provide: (key, source) => provided.push({ key, source }),
|
|
558
|
+
provide: (key, source, base = true) => provided.push({ key, source, base }),
|
|
559
|
+
bind: (binding) => bindings.push(binding),
|
|
560
|
+
optionClass: (name, cls) => optionClasses.set(name, cls),
|
|
374
561
|
mark: (marker) => markers.add(marker),
|
|
375
562
|
lineAt: lineIndex(text),
|
|
376
563
|
};
|
|
377
564
|
for (const lang of langs) {
|
|
378
|
-
|
|
379
|
-
lang.
|
|
565
|
+
const code = lang.comments ? stripComments(text, lang.comments) : text;
|
|
566
|
+
applyPatterns(code, lang.patterns, sink);
|
|
567
|
+
lang.extra?.(code, sink, file);
|
|
380
568
|
}
|
|
381
569
|
}
|
|
382
|
-
|
|
570
|
+
// a key defined by an env schema (zod, envalid, t3-env) takes its optionality from the schema alone
|
|
571
|
+
const fromSchema = new Set([...found.values()].filter((f) => f.schema).map((f) => f.key));
|
|
572
|
+
const result = [...found.values()]
|
|
573
|
+
.filter((f) => f.schema || !fromSchema.has(f.key))
|
|
574
|
+
.map(({ key, line, optional, ci }) => ({ key, line, ...(optional ? { optional } : {}), ...(ci ? { ci } : {}) }))
|
|
575
|
+
.sort((a, b) => a.line - b.line);
|
|
576
|
+
return { found: result, sections, dynamic, provided, markers, bindings, optionClasses };
|
|
383
577
|
}
|
|
384
578
|
|
|
385
579
|
/**
|
|
@@ -398,16 +592,23 @@ export function extractKeys(text, file) {
|
|
|
398
592
|
* SDKs, compose files and appsettings.json provide or read on their own.
|
|
399
593
|
*
|
|
400
594
|
* @param {string} root
|
|
401
|
-
* @param {{ ignoreDirs?: string[], ignoreKeys?: string[] }} [options]
|
|
595
|
+
* @param {{ ignoreDirs?: string[], ignoreKeys?: string[], includeTests?: boolean }} [options]
|
|
402
596
|
* @returns {ScanResult}
|
|
403
597
|
*/
|
|
404
598
|
export function scanProject(root, options = {}) {
|
|
405
|
-
const
|
|
599
|
+
const gitignore = gitignoreRules(root);
|
|
600
|
+
const ignoreDirs = new Set([...DEFAULT_IGNORE_DIRS, ...gitignore.names, ...(options.ignoreDirs ?? []), ...(options.includeTests ? [] : TEST_DIRS)]);
|
|
601
|
+
const skipDir = (/** @type {string} */ name, /** @type {string} */ rel, /** @type {boolean} */ netProject) =>
|
|
602
|
+
ignoreDirs.has(name) || gitignore.paths.has(rel) || (netProject && NET_OUTPUT.has(name)) || (!options.includeTests && TEST_PROJECT.test(name));
|
|
406
603
|
const ignored = keyMatcher([...DEFAULT_IGNORE_KEYS, ...(options.ignoreKeys ?? [])]);
|
|
407
604
|
/** @type {ScanResult} */
|
|
408
605
|
const result = { files: 0, usages: new Map(), sections: new Map(), dynamic: [], provided: new Map(), implicit: [] };
|
|
409
606
|
/** @type {Set<string>} */
|
|
410
607
|
const markers = new Set();
|
|
608
|
+
/** @type {(Binding & { file: string })[]} */
|
|
609
|
+
const bindings = [];
|
|
610
|
+
/** @type {Map<string, OptionClass & { file: string }>} */
|
|
611
|
+
const optionClasses = new Map();
|
|
411
612
|
|
|
412
613
|
/** @param {Map<string, Usage[]>} map @param {string} key @param {Usage} usage */
|
|
413
614
|
const push = (map, key, usage) => {
|
|
@@ -424,28 +625,44 @@ export function scanProject(root, options = {}) {
|
|
|
424
625
|
} catch {
|
|
425
626
|
return; // unreadable directory: skip it rather than fail the whole scan
|
|
426
627
|
}
|
|
628
|
+
const netProject = entries.some((e) => e.isFile() && NET_PROJECT.test(e.name));
|
|
427
629
|
for (const entry of entries) {
|
|
428
630
|
const full = join(dir, entry.name);
|
|
631
|
+
const rel = relative(root, full).split(sep).join("/");
|
|
429
632
|
if (entry.isDirectory()) {
|
|
430
|
-
if (!
|
|
633
|
+
if (!skipDir(entry.name, rel, netProject) && !existsSync(join(full, "pyvenv.cfg"))) walk(full);
|
|
431
634
|
continue;
|
|
432
635
|
}
|
|
433
636
|
if (!entry.isFile()) continue;
|
|
434
|
-
const rel = relative(root, full).split(sep).join("/");
|
|
435
637
|
readManifest(entry.name, full, rel, markers, result.provided);
|
|
436
638
|
if (entry.name.includes(".min.") || !LANGUAGES.some((l) => l.test(entry.name))) continue;
|
|
639
|
+
if (!options.includeTests && TEST_FILE.test(entry.name)) continue;
|
|
437
640
|
if (statSync(full).size > MAX_FILE_BYTES) continue;
|
|
438
641
|
result.files++;
|
|
439
642
|
const r = extractFile(readFileSync(full, "utf8"), rel);
|
|
440
643
|
for (const { key, line, ...flags } of r.found) if (!ignored(key)) push(result.usages, key, { file: rel, line, ...flags });
|
|
441
644
|
for (const { key, line } of r.sections) push(result.sections, key, { file: rel, line });
|
|
442
645
|
for (const { expr, line } of r.dynamic) result.dynamic.push({ file: rel, line, expr });
|
|
443
|
-
for (const
|
|
646
|
+
for (const p of r.provided) provide(result.provided, p);
|
|
444
647
|
for (const m of r.markers) markers.add(m);
|
|
648
|
+
for (const b of r.bindings) bindings.push({ ...b, file: rel });
|
|
649
|
+
for (const [name, cls] of r.optionClasses) optionClasses.set(name, { ...cls, file: rel });
|
|
445
650
|
}
|
|
446
651
|
};
|
|
447
652
|
walk(root);
|
|
448
653
|
|
|
654
|
+
// options classes bound to a section: every property is a key under it
|
|
655
|
+
for (const b of bindings) {
|
|
656
|
+
const cls = optionClasses.get(b.cls);
|
|
657
|
+
const section = b.section ?? (b.sectionOf ? optionClasses.get(b.sectionOf)?.sectionName : undefined);
|
|
658
|
+
if (!cls || !section) continue;
|
|
659
|
+
push(result.sections, `${section}__`, { file: b.file, line: b.line });
|
|
660
|
+
for (const prop of cls.props) {
|
|
661
|
+
const key = `${section}__${prop.name}`;
|
|
662
|
+
if (!ignored(key)) push(result.usages, key, { file: cls.file, line: prop.line, ci: true, ...(prop.optional ? { optional: true } : {}) });
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
449
666
|
const all = [...markers];
|
|
450
667
|
for (const profile of PROFILES) {
|
|
451
668
|
const hit = keyMatcher(profile.markers);
|
|
@@ -462,7 +679,7 @@ export function scanProject(root, options = {}) {
|
|
|
462
679
|
* @param {string} full
|
|
463
680
|
* @param {string} rel
|
|
464
681
|
* @param {Set<string>} markers
|
|
465
|
-
* @param {Map<string,
|
|
682
|
+
* @param {Map<string, Provided>} provided
|
|
466
683
|
*/
|
|
467
684
|
function readManifest(name, full, rel, markers, provided) {
|
|
468
685
|
const lower = name.toLowerCase();
|
|
@@ -489,12 +706,26 @@ function readManifest(name, full, rel, markers, provided) {
|
|
|
489
706
|
/** @type {string[]} */
|
|
490
707
|
const keys = [];
|
|
491
708
|
flatten(parseJson(text.replace(/^\s*\/\/.*$/gm, "")), "", keys);
|
|
492
|
-
|
|
709
|
+
// appsettings.Development.json / .Local.json don't exist in production: they don't excuse a missing .env.example entry
|
|
710
|
+
const base = lower === "appsettings.json";
|
|
711
|
+
for (const key of keys) provide(provided, { key, source: rel, base });
|
|
493
712
|
} else {
|
|
494
713
|
for (const dep of pythonDeps(text)) markers.add(`py:${dep}`);
|
|
495
714
|
}
|
|
496
715
|
}
|
|
497
716
|
|
|
717
|
+
/**
|
|
718
|
+
* A value that applies everywhere wins over one for a single environment.
|
|
719
|
+
*
|
|
720
|
+
* @param {Map<string, Provided>} map
|
|
721
|
+
* @param {Provided} entry
|
|
722
|
+
*/
|
|
723
|
+
function provide(map, entry) {
|
|
724
|
+
const lower = entry.key.toLowerCase();
|
|
725
|
+
const prev = map.get(lower);
|
|
726
|
+
if (!prev || (!prev.base && entry.base)) map.set(lower, entry);
|
|
727
|
+
}
|
|
728
|
+
|
|
498
729
|
/** @param {string} text @returns {any} */
|
|
499
730
|
function parseJson(text) {
|
|
500
731
|
try {
|
|
@@ -523,21 +754,29 @@ function pythonDeps(text) {
|
|
|
523
754
|
}
|
|
524
755
|
|
|
525
756
|
/**
|
|
526
|
-
* Plain
|
|
757
|
+
* Plain directories listed in the root .gitignore; glob patterns are left alone.
|
|
758
|
+
* `dist/` matches a directory of that name anywhere; `/storage` and `app/cache` only that path from the root, as git does.
|
|
527
759
|
*
|
|
528
760
|
* @param {string} root
|
|
529
761
|
*/
|
|
530
|
-
function
|
|
762
|
+
function gitignoreRules(root) {
|
|
763
|
+
/** @type {{ names: string[], paths: Set<string> }} */
|
|
764
|
+
const rules = { names: [], paths: new Set() };
|
|
531
765
|
let text;
|
|
532
766
|
try {
|
|
533
767
|
text = readFileSync(join(root, ".gitignore"), "utf8");
|
|
534
768
|
} catch {
|
|
535
|
-
return
|
|
769
|
+
return rules; // no .gitignore
|
|
770
|
+
}
|
|
771
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
772
|
+
const line = raw.trim();
|
|
773
|
+
if (!line || line.startsWith("#") || line.startsWith("!") || line.startsWith(".env")) continue;
|
|
774
|
+
const path = line.replace(/\/$/, "");
|
|
775
|
+
if (!/^\/?[\w.-]+(?:\/[\w.-]+)*$/.test(path)) continue;
|
|
776
|
+
if (path.includes("/")) rules.paths.add(path.replace(/^\//, ""));
|
|
777
|
+
else rules.names.push(path);
|
|
536
778
|
}
|
|
537
|
-
return
|
|
538
|
-
.split(/\r?\n/)
|
|
539
|
-
.map((l) => l.trim().replace(/^\//, "").replace(/\/$/, ""))
|
|
540
|
-
.filter((l) => l && !l.startsWith("#") && !l.startsWith("!") && /^[\w.-]+$/.test(l) && !l.startsWith(".env"));
|
|
779
|
+
return rules;
|
|
541
780
|
}
|
|
542
781
|
|
|
543
782
|
/** @param {string} text */
|
package/types/check.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {import("./parse.js").ParsedEnv} ParsedEnv
|
|
3
|
+
* @typedef {import("./scan.js").Usage} Usage
|
|
4
|
+
* @typedef {import("./scan.js").ScanResult} ScanResult
|
|
5
|
+
* @typedef {"error" | "warning"} Severity
|
|
6
|
+
* @typedef {"undocumented" | "defaulted" | "unused" | "missing" | "empty" | "extra" | "duplicate" | "syntax"} Code
|
|
7
|
+
* @typedef {{
|
|
8
|
+
* severity: Severity,
|
|
9
|
+
* code: Code,
|
|
10
|
+
* key?: string,
|
|
11
|
+
* file: string,
|
|
12
|
+
* line?: number,
|
|
13
|
+
* message: string,
|
|
14
|
+
* usages?: Usage[],
|
|
15
|
+
* }} Finding
|
|
16
|
+
* @typedef {{
|
|
17
|
+
* example: ParsedEnv,
|
|
18
|
+
* exampleFile: string,
|
|
19
|
+
* env?: ParsedEnv | null,
|
|
20
|
+
* envFile?: string,
|
|
21
|
+
* scan?: ScanResult | null,
|
|
22
|
+
* strict?: boolean,
|
|
23
|
+
* }} CheckInput
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Cross-checks three sources of truth: the code, .env.example and (when present) .env.
|
|
27
|
+
* Findings carry key names, files and line numbers only — values are never copied,
|
|
28
|
+
* so a report can't leak a secret.
|
|
29
|
+
*
|
|
30
|
+
* Reads with a fallback in code come back as `defaulted` (a warning) instead of `undocumented`;
|
|
31
|
+
* callers decide whether to show them.
|
|
32
|
+
*
|
|
33
|
+
* @param {CheckInput} input
|
|
34
|
+
* @returns {Finding[]}
|
|
35
|
+
*/
|
|
36
|
+
export function check({ example, exampleFile, env, envFile, scan, strict }: CheckInput): Finding[];
|
|
37
|
+
/**
|
|
38
|
+
* Text to append to .env.example so every given key gets an empty entry,
|
|
39
|
+
* each with a comment pointing at where the code reads it.
|
|
40
|
+
*
|
|
41
|
+
* @param {Finding[]} findings `undocumented` (and, if wanted, `defaulted`) findings
|
|
42
|
+
* @param {boolean} fileIsEmpty
|
|
43
|
+
*/
|
|
44
|
+
export function fixText(findings: Finding[], fileIsEmpty: boolean): string;
|
|
45
|
+
export type ParsedEnv = import("./parse.js").ParsedEnv;
|
|
46
|
+
export type Usage = import("./scan.js").Usage;
|
|
47
|
+
export type ScanResult = import("./scan.js").ScanResult;
|
|
48
|
+
export type Severity = "error" | "warning";
|
|
49
|
+
export type Code = "undocumented" | "defaulted" | "unused" | "missing" | "empty" | "extra" | "duplicate" | "syntax";
|
|
50
|
+
export type Finding = {
|
|
51
|
+
severity: Severity;
|
|
52
|
+
code: Code;
|
|
53
|
+
key?: string;
|
|
54
|
+
file: string;
|
|
55
|
+
line?: number;
|
|
56
|
+
message: string;
|
|
57
|
+
usages?: Usage[];
|
|
58
|
+
};
|
|
59
|
+
export type CheckInput = {
|
|
60
|
+
example: ParsedEnv;
|
|
61
|
+
exampleFile: string;
|
|
62
|
+
env?: ParsedEnv | null;
|
|
63
|
+
envFile?: string;
|
|
64
|
+
scan?: ScanResult | null;
|
|
65
|
+
strict?: boolean;
|
|
66
|
+
};
|
package/types/cli.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {{ out: (s: string) => void, err: (s: string) => void, cwd: string, color: boolean, githubActions?: boolean, githubOutput?: (s: string) => void }} Io
|
|
3
|
+
* githubOutput — appends step outputs (`errors=…`) on GitHub Actions
|
|
4
|
+
* @typedef {{ example?: string, env?: string, ignore?: string[], ignoreKeys?: string[], includeTests?: boolean, strict?: boolean, optional?: boolean }} Config
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Runs the CLI and returns the exit code; all output goes through `io`, so tests can capture it.
|
|
8
|
+
*
|
|
9
|
+
* @param {string[]} argv
|
|
10
|
+
* @param {Io} io
|
|
11
|
+
* @returns {number}
|
|
12
|
+
*/
|
|
13
|
+
export function run(argv: string[], io: Io): number;
|
|
14
|
+
export const VERSION: "0.2.0";
|
|
15
|
+
/**
|
|
16
|
+
* githubOutput — appends step outputs (`errors=…`) on GitHub Actions
|
|
17
|
+
*/
|
|
18
|
+
export type Io = {
|
|
19
|
+
out: (s: string) => void;
|
|
20
|
+
err: (s: string) => void;
|
|
21
|
+
cwd: string;
|
|
22
|
+
color: boolean;
|
|
23
|
+
githubActions?: boolean;
|
|
24
|
+
githubOutput?: (s: string) => void;
|
|
25
|
+
};
|
|
26
|
+
export type Config = {
|
|
27
|
+
example?: string;
|
|
28
|
+
env?: string;
|
|
29
|
+
ignore?: string[];
|
|
30
|
+
ignoreKeys?: string[];
|
|
31
|
+
includeTests?: boolean;
|
|
32
|
+
strict?: boolean;
|
|
33
|
+
optional?: boolean;
|
|
34
|
+
};
|
package/types/index.d.ts
ADDED