@sagudelo01/vigil 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Santiago Agudelo
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,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @sagudelo01/vigil
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Static analysis for JavaScript and TypeScript focused on security and bug
4
+ patterns. This package is the analyzer and the `vigil` command-line tool.
5
+
6
+ ## Usage
7
+
8
+ Run it without installing:
9
+
10
+ ```bash
11
+ npx @sagudelo01/vigil analyze src
12
+ ```
13
+
14
+ Or install it as a dev dependency:
15
+
16
+ ```bash
17
+ npm install -D @sagudelo01/vigil
18
+ ```
19
+
20
+ ```bash
21
+ vigil analyze src --format sarif > vigil.sarif
22
+ ```
23
+
24
+ The command exits with code `1` when a finding reaches the fail threshold
25
+ (`error` by default), `2` on a usage or configuration error, and `0`
26
+ otherwise. Use `--format` for `terminal`, `json`, or `sarif`, `--config` for a
27
+ configuration file, and `--fail-on` to set the lowest severity that fails.
28
+
29
+ ## Library
30
+
31
+ ```ts
32
+ import { analyzeContent, rules } from '@sagudelo01/vigil';
33
+
34
+ const result = analyzeContent([{ path: 'a.ts', content: 'const x = eval(a);' }]);
35
+ ```
36
+
37
+ See the full documentation at https://github.com/Sagudelo01/vigil.
38
+
39
+ ## License
40
+
41
+ MIT
@@ -0,0 +1,762 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/parser/parser.ts
4
+ import ts from "typescript";
5
+ var SCRIPT_KIND_BY_EXT = {
6
+ ".ts": ts.ScriptKind.TS,
7
+ ".tsx": ts.ScriptKind.TSX,
8
+ ".mts": ts.ScriptKind.TS,
9
+ ".cts": ts.ScriptKind.TS,
10
+ ".js": ts.ScriptKind.JS,
11
+ ".jsx": ts.ScriptKind.JSX,
12
+ ".mjs": ts.ScriptKind.JS,
13
+ ".cjs": ts.ScriptKind.JS
14
+ };
15
+ function scriptKindFor(filePath) {
16
+ const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
17
+ return SCRIPT_KIND_BY_EXT[ext] ?? ts.ScriptKind.TS;
18
+ }
19
+ function parse(filePath, source) {
20
+ const sourceFile = ts.createSourceFile(
21
+ filePath,
22
+ source,
23
+ ts.ScriptTarget.Latest,
24
+ /* setParentNodes */
25
+ true,
26
+ scriptKindFor(filePath)
27
+ );
28
+ return { filePath, sourceFile };
29
+ }
30
+ function walk(node, visit) {
31
+ visit(node);
32
+ node.forEachChild((child) => walk(child, visit));
33
+ }
34
+
35
+ // src/core/engine.ts
36
+ function lineSnippet(sourceFile, start) {
37
+ const text = sourceFile.getFullText();
38
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
39
+ let lineEnd = text.indexOf("\n", start);
40
+ if (lineEnd === -1) lineEnd = text.length;
41
+ return text.slice(lineStart, lineEnd).trim();
42
+ }
43
+ function isEnabled(config, rule) {
44
+ return config.rules?.[rule.id]?.enabled !== false;
45
+ }
46
+ function severityFor(config, rule) {
47
+ return config.rules?.[rule.id]?.severity ?? rule.severity;
48
+ }
49
+ function analyzeSource(parsed, rules2, config = {}) {
50
+ const findings = [];
51
+ for (const rule of rules2) {
52
+ if (!isEnabled(config, rule)) continue;
53
+ const severity = severityFor(config, rule);
54
+ const context = {
55
+ filePath: parsed.filePath,
56
+ sourceFile: parsed.sourceFile,
57
+ report(node, options = {}) {
58
+ const start = node.getStart(parsed.sourceFile);
59
+ const { line, character } = parsed.sourceFile.getLineAndCharacterOfPosition(start);
60
+ findings.push({
61
+ ruleId: rule.id,
62
+ severity,
63
+ message: options.message ?? rule.message,
64
+ file: parsed.filePath,
65
+ line: line + 1,
66
+ column: character + 1,
67
+ snippet: lineSnippet(parsed.sourceFile, start),
68
+ ...options.suggestion !== void 0 ? { suggestion: options.suggestion } : {}
69
+ });
70
+ }
71
+ };
72
+ rule.check(context);
73
+ }
74
+ findings.sort((a, b) => a.line - b.line || a.column - b.column);
75
+ return findings;
76
+ }
77
+
78
+ // src/core/config.ts
79
+ import { readFileSync } from "fs";
80
+ import { resolve } from "path";
81
+ var CONFIG_FILENAME = "vigil.config.json";
82
+ var DEFAULT_IGNORE = ["node_modules", "dist", "build", "coverage", ".git"];
83
+ var SEVERITIES = ["error", "warning", "info"];
84
+ var ConfigError = class extends Error {
85
+ };
86
+ function assertConfigShape(value) {
87
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
88
+ throw new ConfigError("Configuration must be a JSON object.");
89
+ }
90
+ const config = value;
91
+ if (config.failOn !== void 0 && !SEVERITIES.includes(config.failOn)) {
92
+ throw new ConfigError(`"failOn" must be one of: ${SEVERITIES.join(", ")}.`);
93
+ }
94
+ if (config.ignore !== void 0 && !Array.isArray(config.ignore)) {
95
+ throw new ConfigError('"ignore" must be an array of strings.');
96
+ }
97
+ }
98
+ function parseConfig(raw, source) {
99
+ let parsed;
100
+ try {
101
+ parsed = JSON.parse(raw);
102
+ } catch (error) {
103
+ throw new ConfigError(`Invalid JSON in ${source}: ${error.message}`);
104
+ }
105
+ assertConfigShape(parsed);
106
+ return parsed;
107
+ }
108
+ function loadConfig(cwd = process.cwd()) {
109
+ const path = resolve(cwd, CONFIG_FILENAME);
110
+ let raw;
111
+ try {
112
+ raw = readFileSync(path, "utf8");
113
+ } catch {
114
+ return {};
115
+ }
116
+ return parseConfig(raw, CONFIG_FILENAME);
117
+ }
118
+ function loadConfigFile(path) {
119
+ let raw;
120
+ try {
121
+ raw = readFileSync(path, "utf8");
122
+ } catch {
123
+ throw new ConfigError(`Configuration file not found: ${path}`);
124
+ }
125
+ return parseConfig(raw, path);
126
+ }
127
+ function resolveIgnore(config) {
128
+ return [...DEFAULT_IGNORE, ...config.ignore ?? []];
129
+ }
130
+
131
+ // src/rules/no-hardcoded-secrets.ts
132
+ import ts2 from "typescript";
133
+ var SECRET_NAME = /^(?:.*[_-])?(password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|client[_-]?secret|auth)$/i;
134
+ var KNOWN_TOKEN_PATTERNS = [
135
+ /AKIA[0-9A-Z]{16}/,
136
+ // AWS access key id
137
+ /gh[pousr]_[A-Za-z0-9]{36,}/,
138
+ // GitHub tokens
139
+ /sk-[A-Za-z0-9]{20,}/,
140
+ // OpenAI-style secret keys
141
+ /AIza[0-9A-Za-z_-]{35}/,
142
+ // Google API key
143
+ /xox[baprs]-[A-Za-z0-9-]{10,}/
144
+ // Slack tokens
145
+ ];
146
+ function assignedName(node) {
147
+ if (ts2.isVariableDeclaration(node) && ts2.isIdentifier(node.name)) return node.name.text;
148
+ if (ts2.isPropertyAssignment(node) && ts2.isIdentifier(node.name)) return node.name.text;
149
+ if (ts2.isBinaryExpression(node) && node.operatorToken.kind === ts2.SyntaxKind.EqualsToken) {
150
+ if (ts2.isPropertyAccessExpression(node.left)) return node.left.name.text;
151
+ if (ts2.isIdentifier(node.left)) return node.left.text;
152
+ }
153
+ return void 0;
154
+ }
155
+ function stringValueOf(node) {
156
+ const value = ts2.isVariableDeclaration(node) ? node.initializer : ts2.isPropertyAssignment(node) ? node.initializer : ts2.isBinaryExpression(node) ? node.right : void 0;
157
+ return value && ts2.isStringLiteral(value) ? value : void 0;
158
+ }
159
+ var noHardcodedSecrets = {
160
+ id: "no-hardcoded-secrets",
161
+ severity: "error",
162
+ description: "Flags credentials and API keys embedded directly in source code.",
163
+ message: "Hardcoded secret. Load it from an environment variable or a secrets manager.",
164
+ check(context) {
165
+ walk(context.sourceFile, (node) => {
166
+ if (ts2.isStringLiteral(node) && KNOWN_TOKEN_PATTERNS.some((p) => p.test(node.text))) {
167
+ context.report(node);
168
+ return;
169
+ }
170
+ const name = assignedName(node);
171
+ const value = stringValueOf(node);
172
+ if (name && value && SECRET_NAME.test(name) && value.text.trim().length > 0 && // The literal branch already reports values that match a token shape.
173
+ !KNOWN_TOKEN_PATTERNS.some((p) => p.test(value.text))) {
174
+ context.report(value);
175
+ }
176
+ });
177
+ }
178
+ };
179
+
180
+ // src/rules/no-eval.ts
181
+ import ts4 from "typescript";
182
+
183
+ // src/rules/ast-utils.ts
184
+ import ts3 from "typescript";
185
+ function propertyAccessName(node) {
186
+ const left = ts3.isPropertyAccessExpression(node.expression) ? propertyAccessName(node.expression) : ts3.isIdentifier(node.expression) ? node.expression.text : node.expression.kind === ts3.SyntaxKind.ThisKeyword ? "this" : "";
187
+ return left ? `${left}.${node.name.text}` : node.name.text;
188
+ }
189
+ function isCallTo(node, callee) {
190
+ return ts3.isCallExpression(node) && ts3.isIdentifier(node.expression) && node.expression.text === callee;
191
+ }
192
+ function chainMethodNames(node) {
193
+ const names = [];
194
+ let current = node;
195
+ while (ts3.isCallExpression(current) && ts3.isPropertyAccessExpression(current.expression)) {
196
+ names.push(current.expression.name.text);
197
+ current = current.expression.expression;
198
+ }
199
+ return names;
200
+ }
201
+
202
+ // src/rules/no-eval.ts
203
+ var noEval = {
204
+ id: "no-eval",
205
+ severity: "error",
206
+ description: "Flags eval and the Function constructor, which execute arbitrary strings as code.",
207
+ message: "Avoid eval and new Function: they run arbitrary code and enable injection.",
208
+ check(context) {
209
+ walk(context.sourceFile, (node) => {
210
+ if (isCallTo(node, "eval")) {
211
+ context.report(node, {
212
+ suggestion: "Parse the input or use a safe, explicit alternative."
213
+ });
214
+ return;
215
+ }
216
+ if ((ts4.isNewExpression(node) || ts4.isCallExpression(node)) && ts4.isIdentifier(node.expression) && node.expression.text === "Function") {
217
+ context.report(node, {
218
+ message: "Avoid the Function constructor: it runs arbitrary code like eval.",
219
+ suggestion: "Define the function directly instead of building it from a string."
220
+ });
221
+ }
222
+ });
223
+ }
224
+ };
225
+
226
+ // src/rules/no-sql-concatenation.ts
227
+ import ts5 from "typescript";
228
+ var SQL_STATEMENT = /^\s*(select\b[\s\S]*\bfrom\b|insert\s+into\b|update\b[\s\S]*\bset\b|delete\s+from\b|drop\s+table\b|truncate\s+table\b)/i;
229
+ function looksLikeSql(text) {
230
+ return SQL_STATEMENT.test(text);
231
+ }
232
+ function hasJsxAncestor(node) {
233
+ for (let current = node.parent; current; current = current.parent) {
234
+ switch (current.kind) {
235
+ case ts5.SyntaxKind.JsxAttribute:
236
+ case ts5.SyntaxKind.JsxExpression:
237
+ case ts5.SyntaxKind.JsxElement:
238
+ case ts5.SyntaxKind.JsxSelfClosingElement:
239
+ case ts5.SyntaxKind.JsxFragment:
240
+ return true;
241
+ }
242
+ }
243
+ return false;
244
+ }
245
+ function collectConcat(node) {
246
+ let text = "";
247
+ let hasDynamic = false;
248
+ const visit = (expr) => {
249
+ if (ts5.isBinaryExpression(expr) && expr.operatorToken.kind === ts5.SyntaxKind.PlusToken) {
250
+ visit(expr.left);
251
+ visit(expr.right);
252
+ } else if (ts5.isStringLiteral(expr)) {
253
+ text += `${expr.text} `;
254
+ } else {
255
+ hasDynamic = true;
256
+ }
257
+ };
258
+ visit(node);
259
+ return { text, hasDynamic };
260
+ }
261
+ function isConcatWithSql(node) {
262
+ if (node.operatorToken.kind !== ts5.SyntaxKind.PlusToken) return false;
263
+ const { text, hasDynamic } = collectConcat(node);
264
+ return hasDynamic && looksLikeSql(text);
265
+ }
266
+ function isSqlTemplate(node) {
267
+ if (node.templateSpans.length === 0) return false;
268
+ const text = node.head.text + node.templateSpans.map((span) => span.literal.text).join(" ");
269
+ return looksLikeSql(text);
270
+ }
271
+ var noSqlConcatenation = {
272
+ id: "no-sql-concatenation",
273
+ severity: "error",
274
+ description: "Flags SQL queries built by string concatenation or interpolation.",
275
+ message: "SQL built from untrusted input. Use parameterized queries or prepared statements.",
276
+ check(context) {
277
+ walk(context.sourceFile, (node) => {
278
+ if (hasJsxAncestor(node)) return;
279
+ if (ts5.isBinaryExpression(node) && isConcatWithSql(node)) {
280
+ const parent = node.parent;
281
+ const isInnerConcat = ts5.isBinaryExpression(parent) && parent.operatorToken.kind === ts5.SyntaxKind.PlusToken;
282
+ if (!isInnerConcat) context.report(node);
283
+ } else if (ts5.isTemplateExpression(node) && isSqlTemplate(node)) {
284
+ context.report(node);
285
+ }
286
+ });
287
+ }
288
+ };
289
+
290
+ // src/rules/no-unsanitized-html.ts
291
+ import ts6 from "typescript";
292
+ var SINK_PROPERTIES = /* @__PURE__ */ new Set(["innerHTML", "outerHTML"]);
293
+ function isUnsafeHtmlAssignment(node) {
294
+ if (node.operatorToken.kind !== ts6.SyntaxKind.EqualsToken) return false;
295
+ if (!ts6.isPropertyAccessExpression(node.left)) return false;
296
+ if (!SINK_PROPERTIES.has(node.left.name.text)) return false;
297
+ return !ts6.isStringLiteral(node.right);
298
+ }
299
+ function jsxAttributeName(node) {
300
+ return ts6.isIdentifier(node.name) ? node.name.text : node.name.name.text;
301
+ }
302
+ var noUnsanitizedHtml = {
303
+ id: "no-unsanitized-html",
304
+ severity: "error",
305
+ description: "Flags raw HTML sinks such as innerHTML and dangerouslySetInnerHTML.",
306
+ message: "Unsanitized HTML sink. Sanitize the value or render it as text to avoid XSS.",
307
+ check(context) {
308
+ walk(context.sourceFile, (node) => {
309
+ if (ts6.isBinaryExpression(node) && isUnsafeHtmlAssignment(node)) {
310
+ context.report(node);
311
+ } else if (ts6.isJsxAttribute(node) && jsxAttributeName(node) === "dangerouslySetInnerHTML") {
312
+ context.report(node, {
313
+ message: "dangerouslySetInnerHTML renders raw HTML. Sanitize the value first."
314
+ });
315
+ }
316
+ });
317
+ }
318
+ };
319
+
320
+ // src/rules/no-loose-equality.ts
321
+ import ts7 from "typescript";
322
+ var noLooseEquality = {
323
+ id: "no-loose-equality",
324
+ severity: "warning",
325
+ description: "Flags == and != comparisons, which coerce operands.",
326
+ message: "Use === or !== to avoid type coercion.",
327
+ check(context) {
328
+ walk(context.sourceFile, (node) => {
329
+ if (!ts7.isBinaryExpression(node)) return;
330
+ const kind = node.operatorToken.kind;
331
+ if (kind === ts7.SyntaxKind.EqualsEqualsToken) {
332
+ context.report(node.operatorToken, { suggestion: "Replace == with ===." });
333
+ } else if (kind === ts7.SyntaxKind.ExclamationEqualsToken) {
334
+ context.report(node.operatorToken, {
335
+ message: "Use !== to avoid type coercion.",
336
+ suggestion: "Replace != with !==."
337
+ });
338
+ }
339
+ });
340
+ }
341
+ };
342
+
343
+ // src/rules/no-floating-promises.ts
344
+ import ts8 from "typescript";
345
+ function isFloatingThen(statement) {
346
+ const expression = statement.expression;
347
+ if (!ts8.isCallExpression(expression)) return false;
348
+ const methods = chainMethodNames(expression);
349
+ return methods.includes("then") && !methods.includes("catch");
350
+ }
351
+ var noFloatingPromises = {
352
+ id: "no-floating-promises",
353
+ severity: "warning",
354
+ description: "Flags promise chains that are neither awaited nor given a catch handler.",
355
+ message: "Floating promise: await it or add a .catch so rejections are handled.",
356
+ check(context) {
357
+ walk(context.sourceFile, (node) => {
358
+ if (ts8.isExpressionStatement(node) && isFloatingThen(node)) {
359
+ context.report(node);
360
+ }
361
+ });
362
+ }
363
+ };
364
+
365
+ // src/rules/no-empty-catch.ts
366
+ import ts9 from "typescript";
367
+ function isSilentCatch(clause, sourceFile) {
368
+ if (clause.block.statements.length > 0) return false;
369
+ const inner = clause.block.getText(sourceFile).slice(1, -1);
370
+ return inner.trim().length === 0;
371
+ }
372
+ var noEmptyCatch = {
373
+ id: "no-empty-catch",
374
+ severity: "warning",
375
+ description: "Flags catch blocks that swallow errors without handling or logging them.",
376
+ message: "Empty catch block swallows the error. Handle it, rethrow, or log why it is ignored.",
377
+ check(context) {
378
+ walk(context.sourceFile, (node) => {
379
+ if (ts9.isCatchClause(node) && isSilentCatch(node, context.sourceFile)) {
380
+ context.report(node);
381
+ }
382
+ });
383
+ }
384
+ };
385
+
386
+ // src/rules/no-console-log.ts
387
+ import ts10 from "typescript";
388
+ var FLAGGED_METHODS = /* @__PURE__ */ new Set(["console.log", "console.debug"]);
389
+ var noConsoleLog = {
390
+ id: "no-console-log",
391
+ severity: "info",
392
+ description: "Flags leftover console.log and console.debug calls.",
393
+ message: "Leftover console call. Remove it or use a configurable logger.",
394
+ check(context) {
395
+ walk(context.sourceFile, (node) => {
396
+ if (!ts10.isCallExpression(node)) return;
397
+ if (!ts10.isPropertyAccessExpression(node.expression)) return;
398
+ if (FLAGGED_METHODS.has(propertyAccessName(node.expression))) {
399
+ context.report(node);
400
+ }
401
+ });
402
+ }
403
+ };
404
+
405
+ // src/rules/no-unused-variables.ts
406
+ import ts11 from "typescript";
407
+ function countIdentifiers(sourceFile) {
408
+ const counts = /* @__PURE__ */ new Map();
409
+ walk(sourceFile, (node) => {
410
+ if (ts11.isIdentifier(node)) {
411
+ counts.set(node.text, (counts.get(node.text) ?? 0) + 1);
412
+ }
413
+ });
414
+ return counts;
415
+ }
416
+ function isExported(declaration) {
417
+ const statement = declaration.parent.parent;
418
+ return ts11.isVariableStatement(statement) && (statement.modifiers?.some((m) => m.kind === ts11.SyntaxKind.ExportKeyword) ?? false);
419
+ }
420
+ var noUnusedVariables = {
421
+ id: "no-unused-variables",
422
+ severity: "info",
423
+ description: "Flags local variable declarations that are never referenced.",
424
+ message: "Unused variable. Remove it or prefix it with an underscore if intentional.",
425
+ check(context) {
426
+ const counts = countIdentifiers(context.sourceFile);
427
+ walk(context.sourceFile, (node) => {
428
+ if (!ts11.isVariableDeclaration(node)) return;
429
+ if (!ts11.isIdentifier(node.name)) return;
430
+ const name = node.name.text;
431
+ if (name.startsWith("_")) return;
432
+ if (isExported(node)) return;
433
+ if ((counts.get(name) ?? 0) > 1) return;
434
+ context.report(node.name, {
435
+ message: `Unused variable "${name}". Remove it or prefix it with an underscore.`
436
+ });
437
+ });
438
+ }
439
+ };
440
+
441
+ // src/rules/no-complex-functions.ts
442
+ import ts12 from "typescript";
443
+ var MAX_COMPLEXITY = 10;
444
+ var MAX_LINES = 50;
445
+ function isFunctionLike(node) {
446
+ return ts12.isFunctionDeclaration(node) || ts12.isFunctionExpression(node) || ts12.isArrowFunction(node) || ts12.isMethodDeclaration(node) || ts12.isConstructorDeclaration(node) || ts12.isGetAccessor(node) || ts12.isSetAccessor(node);
447
+ }
448
+ var DECISION_KINDS = /* @__PURE__ */ new Set([
449
+ ts12.SyntaxKind.IfStatement,
450
+ ts12.SyntaxKind.ForStatement,
451
+ ts12.SyntaxKind.ForInStatement,
452
+ ts12.SyntaxKind.ForOfStatement,
453
+ ts12.SyntaxKind.WhileStatement,
454
+ ts12.SyntaxKind.DoStatement,
455
+ ts12.SyntaxKind.CaseClause,
456
+ ts12.SyntaxKind.CatchClause,
457
+ ts12.SyntaxKind.ConditionalExpression
458
+ ]);
459
+ var LOGICAL_OPERATORS = /* @__PURE__ */ new Set([
460
+ ts12.SyntaxKind.AmpersandAmpersandToken,
461
+ ts12.SyntaxKind.BarBarToken,
462
+ ts12.SyntaxKind.QuestionQuestionToken
463
+ ]);
464
+ function addsComplexity(node) {
465
+ if (DECISION_KINDS.has(node.kind)) return true;
466
+ return ts12.isBinaryExpression(node) && LOGICAL_OPERATORS.has(node.operatorToken.kind);
467
+ }
468
+ function complexityOf(fn) {
469
+ let complexity = 1;
470
+ const visit = (node) => {
471
+ if (node !== fn && isFunctionLike(node)) return;
472
+ if (addsComplexity(node)) complexity += 1;
473
+ node.forEachChild(visit);
474
+ };
475
+ fn.forEachChild(visit);
476
+ return complexity;
477
+ }
478
+ function lineSpan(fn, sourceFile) {
479
+ const start = sourceFile.getLineAndCharacterOfPosition(fn.getStart(sourceFile)).line;
480
+ const end = sourceFile.getLineAndCharacterOfPosition(fn.getEnd()).line;
481
+ return end - start + 1;
482
+ }
483
+ function reportTarget(fn) {
484
+ return "name" in fn && fn.name ? fn.name : fn;
485
+ }
486
+ var noComplexFunctions = {
487
+ id: "no-complex-functions",
488
+ severity: "warning",
489
+ description: "Flags functions that are too long or have high cyclomatic complexity.",
490
+ message: "Function is too complex. Split it into smaller, focused functions.",
491
+ check(context) {
492
+ walk(context.sourceFile, (node) => {
493
+ if (!isFunctionLike(node)) return;
494
+ const complexity = complexityOf(node);
495
+ const lines = lineSpan(node, context.sourceFile);
496
+ if (complexity <= MAX_COMPLEXITY && lines <= MAX_LINES) return;
497
+ const reasons = [];
498
+ if (complexity > MAX_COMPLEXITY) {
499
+ reasons.push(`cyclomatic complexity ${complexity} (max ${MAX_COMPLEXITY})`);
500
+ }
501
+ if (lines > MAX_LINES) {
502
+ reasons.push(`${lines} lines (max ${MAX_LINES})`);
503
+ }
504
+ context.report(reportTarget(node), {
505
+ message: `Function is too complex: ${reasons.join(", ")}. Split it into smaller functions.`
506
+ });
507
+ });
508
+ }
509
+ };
510
+
511
+ // src/rules/index.ts
512
+ var rules = [
513
+ noHardcodedSecrets,
514
+ noEval,
515
+ noSqlConcatenation,
516
+ noUnsanitizedHtml,
517
+ noLooseEquality,
518
+ noFloatingPromises,
519
+ noEmptyCatch,
520
+ noConsoleLog,
521
+ noUnusedVariables,
522
+ noComplexFunctions
523
+ ];
524
+
525
+ // src/core/analyzer.ts
526
+ import { readFileSync as readFileSync2 } from "fs";
527
+
528
+ // src/core/files.ts
529
+ import { readdirSync, statSync } from "fs";
530
+ import { join } from "path";
531
+ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
532
+ ".ts",
533
+ ".tsx",
534
+ ".mts",
535
+ ".cts",
536
+ ".js",
537
+ ".jsx",
538
+ ".mjs",
539
+ ".cjs"
540
+ ]);
541
+ function hasSupportedExtension(filePath) {
542
+ const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
543
+ return SUPPORTED_EXTENSIONS.has(ext);
544
+ }
545
+ function isIgnored(path, ignore) {
546
+ const normalized = path.split("\\").join("/");
547
+ return ignore.some((fragment) => fragment.length > 0 && normalized.includes(fragment));
548
+ }
549
+ function collectFiles(target, ignore = []) {
550
+ const stats = statSync(target);
551
+ if (stats.isFile()) {
552
+ return hasSupportedExtension(target) && !isIgnored(target, ignore) ? [target] : [];
553
+ }
554
+ const found = [];
555
+ for (const entry of readdirSync(target, { withFileTypes: true })) {
556
+ const entryPath = join(target, entry.name);
557
+ if (isIgnored(entryPath, ignore)) continue;
558
+ if (entry.isDirectory()) {
559
+ found.push(...collectFiles(entryPath, ignore));
560
+ } else if (entry.isFile() && hasSupportedExtension(entryPath)) {
561
+ found.push(entryPath);
562
+ }
563
+ }
564
+ return found;
565
+ }
566
+
567
+ // src/core/analyzer.ts
568
+ var SEVERITY_ORDER = { info: 0, warning: 1, error: 2 };
569
+ function emptyCounts() {
570
+ return { error: 0, warning: 0, info: 0 };
571
+ }
572
+ function analyzeContent(inputs, options = {}) {
573
+ const config = options.config ?? {};
574
+ const rules2 = options.rules ?? rules;
575
+ const findings = [];
576
+ for (const input of inputs) {
577
+ findings.push(...analyzeSource(parse(input.path, input.content), rules2, config));
578
+ }
579
+ const counts = emptyCounts();
580
+ for (const finding of findings) counts[finding.severity] += 1;
581
+ return { findings, filesAnalyzed: inputs.length, counts };
582
+ }
583
+ function analyze(target, options = {}) {
584
+ const config = options.config ?? {};
585
+ const files = collectFiles(target, resolveIgnore(config));
586
+ const inputs = [];
587
+ for (const file of files) {
588
+ try {
589
+ inputs.push({ path: file, content: readFileSync2(file, "utf8") });
590
+ } catch {
591
+ continue;
592
+ }
593
+ }
594
+ return analyzeContent(inputs, options);
595
+ }
596
+ function hasFailures(result, failOn = "error") {
597
+ const threshold = SEVERITY_ORDER[failOn];
598
+ return result.findings.some((finding) => SEVERITY_ORDER[finding.severity] >= threshold);
599
+ }
600
+
601
+ // src/reporters/terminal.ts
602
+ import pc from "picocolors";
603
+ import { relative } from "path";
604
+ var SEVERITY_LABEL = {
605
+ error: (t) => pc.red(t),
606
+ warning: (t) => pc.yellow(t),
607
+ info: (t) => pc.blue(t)
608
+ };
609
+ function groupByFile(findings) {
610
+ const groups = /* @__PURE__ */ new Map();
611
+ for (const finding of findings) {
612
+ const group = groups.get(finding.file) ?? [];
613
+ group.push(finding);
614
+ groups.set(finding.file, group);
615
+ }
616
+ return groups;
617
+ }
618
+ function renderFinding(finding) {
619
+ const location = pc.dim(`${finding.line}:${finding.column}`);
620
+ const label = SEVERITY_LABEL[finding.severity](finding.severity);
621
+ const rule = pc.dim(finding.ruleId);
622
+ const lines = [` ${location} ${label} ${finding.message} ${rule}`];
623
+ if (finding.snippet) lines.push(` ${pc.dim(finding.snippet)}`);
624
+ if (finding.suggestion) lines.push(` ${pc.green("fix")} ${finding.suggestion}`);
625
+ return lines.join("\n");
626
+ }
627
+ function renderSummary(result) {
628
+ const { error, warning, info } = result.counts;
629
+ const total = error + warning + info;
630
+ if (total === 0) {
631
+ return pc.green(`No issues found in ${result.filesAnalyzed} file(s).`);
632
+ }
633
+ const parts = [
634
+ SEVERITY_LABEL.error(`${error} error(s)`),
635
+ SEVERITY_LABEL.warning(`${warning} warning(s)`),
636
+ SEVERITY_LABEL.info(`${info} info`)
637
+ ];
638
+ return `${pc.bold(`${total} issue(s)`)} in ${result.filesAnalyzed} file(s): ${parts.join(", ")}`;
639
+ }
640
+ function createTerminalReporter(cwd = process.cwd()) {
641
+ return {
642
+ render(result) {
643
+ const blocks = [];
644
+ for (const [file, findings] of groupByFile(result.findings)) {
645
+ blocks.push(pc.underline(relative(cwd, file) || file));
646
+ blocks.push(findings.map(renderFinding).join("\n"));
647
+ blocks.push("");
648
+ }
649
+ blocks.push(renderSummary(result));
650
+ return blocks.join("\n");
651
+ }
652
+ };
653
+ }
654
+
655
+ // src/reporters/json.ts
656
+ function createJsonReporter() {
657
+ return {
658
+ render(result) {
659
+ return JSON.stringify(
660
+ {
661
+ filesAnalyzed: result.filesAnalyzed,
662
+ counts: result.counts,
663
+ findings: result.findings
664
+ },
665
+ null,
666
+ 2
667
+ );
668
+ }
669
+ };
670
+ }
671
+
672
+ // src/reporters/sarif.ts
673
+ import { relative as relative2 } from "path";
674
+ var SARIF_LEVEL = {
675
+ error: "error",
676
+ warning: "warning",
677
+ info: "note"
678
+ };
679
+ var SCHEMA = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json";
680
+ function toUri(file, cwd) {
681
+ return (relative2(cwd, file) || file).split("\\").join("/");
682
+ }
683
+ function ruleDescriptors(rules2) {
684
+ return rules2.map((rule) => ({
685
+ id: rule.id,
686
+ name: rule.id,
687
+ shortDescription: { text: rule.description },
688
+ defaultConfiguration: { level: SARIF_LEVEL[rule.severity] }
689
+ }));
690
+ }
691
+ function resultFor(finding, cwd) {
692
+ return {
693
+ ruleId: finding.ruleId,
694
+ level: SARIF_LEVEL[finding.severity],
695
+ message: { text: finding.message },
696
+ locations: [
697
+ {
698
+ physicalLocation: {
699
+ artifactLocation: { uri: toUri(finding.file, cwd) },
700
+ region: {
701
+ startLine: finding.line,
702
+ startColumn: finding.column,
703
+ snippet: { text: finding.snippet }
704
+ }
705
+ }
706
+ }
707
+ ]
708
+ };
709
+ }
710
+ function createSarifReporter(cwd = process.cwd(), rules2 = rules) {
711
+ return {
712
+ render(result) {
713
+ const sarif = {
714
+ $schema: SCHEMA,
715
+ version: "2.1.0",
716
+ runs: [
717
+ {
718
+ tool: {
719
+ driver: {
720
+ name: "Vigil",
721
+ informationUri: "https://github.com/Sagudelo01/vigil",
722
+ rules: ruleDescriptors(rules2)
723
+ }
724
+ },
725
+ results: result.findings.map((finding) => resultFor(finding, cwd))
726
+ }
727
+ ]
728
+ };
729
+ return JSON.stringify(sarif, null, 2);
730
+ }
731
+ };
732
+ }
733
+
734
+ // src/reporters/index.ts
735
+ function createReporter(format, cwd = process.cwd()) {
736
+ switch (format) {
737
+ case "json":
738
+ return createJsonReporter();
739
+ case "sarif":
740
+ return createSarifReporter(cwd);
741
+ case "terminal":
742
+ default:
743
+ return createTerminalReporter(cwd);
744
+ }
745
+ }
746
+
747
+ export {
748
+ parse,
749
+ walk,
750
+ analyzeSource,
751
+ CONFIG_FILENAME,
752
+ ConfigError,
753
+ loadConfig,
754
+ loadConfigFile,
755
+ resolveIgnore,
756
+ rules,
757
+ analyzeContent,
758
+ analyze,
759
+ hasFailures,
760
+ createReporter
761
+ };
762
+ //# sourceMappingURL=chunk-IUUQ5FY3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser/parser.ts","../src/core/engine.ts","../src/core/config.ts","../src/rules/no-hardcoded-secrets.ts","../src/rules/no-eval.ts","../src/rules/ast-utils.ts","../src/rules/no-sql-concatenation.ts","../src/rules/no-unsanitized-html.ts","../src/rules/no-loose-equality.ts","../src/rules/no-floating-promises.ts","../src/rules/no-empty-catch.ts","../src/rules/no-console-log.ts","../src/rules/no-unused-variables.ts","../src/rules/no-complex-functions.ts","../src/rules/index.ts","../src/core/analyzer.ts","../src/core/files.ts","../src/reporters/terminal.ts","../src/reporters/json.ts","../src/reporters/sarif.ts","../src/reporters/index.ts"],"sourcesContent":["import ts from 'typescript';\n\nexport interface ParsedSource {\n filePath: string;\n sourceFile: ts.SourceFile;\n}\n\nconst SCRIPT_KIND_BY_EXT: Record<string, ts.ScriptKind> = {\n '.ts': ts.ScriptKind.TS,\n '.tsx': ts.ScriptKind.TSX,\n '.mts': ts.ScriptKind.TS,\n '.cts': ts.ScriptKind.TS,\n '.js': ts.ScriptKind.JS,\n '.jsx': ts.ScriptKind.JSX,\n '.mjs': ts.ScriptKind.JS,\n '.cjs': ts.ScriptKind.JS,\n};\n\nfunction scriptKindFor(filePath: string): ts.ScriptKind {\n const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();\n return SCRIPT_KIND_BY_EXT[ext] ?? ts.ScriptKind.TS;\n}\n\n/**\n * Builds a TypeScript AST from source text. Parsing is syntactic only:\n * no type checker and no program, so a single file is analyzed in\n * isolation and without resolving imports.\n */\nexport function parse(filePath: string, source: string): ParsedSource {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n scriptKindFor(filePath),\n );\n return { filePath, sourceFile };\n}\n\n/** Depth-first walk of every node in the tree, root included. */\nexport function walk(node: ts.Node, visit: (node: ts.Node) => void): void {\n visit(node);\n node.forEachChild((child) => walk(child, visit));\n}\n","import type ts from 'typescript';\nimport type { Finding, ReportOptions, Rule, RuleContext, Severity, VigilConfig } from './types.js';\nimport type { ParsedSource } from '../parser/parser.js';\n\nfunction lineSnippet(sourceFile: ts.SourceFile, start: number): string {\n const text = sourceFile.getFullText();\n const lineStart = text.lastIndexOf('\\n', start - 1) + 1;\n let lineEnd = text.indexOf('\\n', start);\n if (lineEnd === -1) lineEnd = text.length;\n return text.slice(lineStart, lineEnd).trim();\n}\n\nfunction isEnabled(config: VigilConfig, rule: Rule): boolean {\n return config.rules?.[rule.id]?.enabled !== false;\n}\n\nfunction severityFor(config: VigilConfig, rule: Rule): Severity {\n return config.rules?.[rule.id]?.severity ?? rule.severity;\n}\n\n/**\n * Runs the enabled rules against one parsed file and returns every\n * finding. Each rule receives its own context, so a rule cannot see or\n * disturb another rule's state.\n */\nexport function analyzeSource(\n parsed: ParsedSource,\n rules: readonly Rule[],\n config: VigilConfig = {},\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const rule of rules) {\n if (!isEnabled(config, rule)) continue;\n\n const severity = severityFor(config, rule);\n const context: RuleContext = {\n filePath: parsed.filePath,\n sourceFile: parsed.sourceFile,\n report(node: ts.Node, options: ReportOptions = {}): void {\n const start = node.getStart(parsed.sourceFile);\n const { line, character } = parsed.sourceFile.getLineAndCharacterOfPosition(start);\n findings.push({\n ruleId: rule.id,\n severity,\n message: options.message ?? rule.message,\n file: parsed.filePath,\n line: line + 1,\n column: character + 1,\n snippet: lineSnippet(parsed.sourceFile, start),\n ...(options.suggestion !== undefined ? { suggestion: options.suggestion } : {}),\n });\n },\n };\n\n rule.check(context);\n }\n\n findings.sort((a, b) => a.line - b.line || a.column - b.column);\n return findings;\n}\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { Severity, VigilConfig } from './types.js';\n\nexport const CONFIG_FILENAME = 'vigil.config.json';\n\nexport const DEFAULT_IGNORE = ['node_modules', 'dist', 'build', 'coverage', '.git'];\n\nconst SEVERITIES: readonly Severity[] = ['error', 'warning', 'info'];\n\nexport class ConfigError extends Error {}\n\nfunction assertConfigShape(value: unknown): asserts value is VigilConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ConfigError('Configuration must be a JSON object.');\n }\n const config = value as Record<string, unknown>;\n if (config.failOn !== undefined && !SEVERITIES.includes(config.failOn as Severity)) {\n throw new ConfigError(`\"failOn\" must be one of: ${SEVERITIES.join(', ')}.`);\n }\n if (config.ignore !== undefined && !Array.isArray(config.ignore)) {\n throw new ConfigError('\"ignore\" must be an array of strings.');\n }\n}\n\nfunction parseConfig(raw: string, source: string): VigilConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new ConfigError(`Invalid JSON in ${source}: ${(error as Error).message}`);\n }\n assertConfigShape(parsed);\n return parsed;\n}\n\n/**\n * Loads configuration from `vigil.config.json` in `cwd`. A missing file\n * is not an error: the caller gets an empty config and built-in defaults.\n */\nexport function loadConfig(cwd: string = process.cwd()): VigilConfig {\n const path = resolve(cwd, CONFIG_FILENAME);\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n return {};\n }\n return parseConfig(raw, CONFIG_FILENAME);\n}\n\n/** Loads configuration from an explicit path. A missing file is an error. */\nexport function loadConfigFile(path: string): VigilConfig {\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n throw new ConfigError(`Configuration file not found: ${path}`);\n }\n return parseConfig(raw, path);\n}\n\n/** Merges the configured ignore list with the built-in defaults. */\nexport function resolveIgnore(config: VigilConfig): string[] {\n return [...DEFAULT_IGNORE, ...(config.ignore ?? [])];\n}\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\nconst SECRET_NAME =\n /^(?:.*[_-])?(password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|client[_-]?secret|auth)$/i;\n\nconst KNOWN_TOKEN_PATTERNS: RegExp[] = [\n /AKIA[0-9A-Z]{16}/, // AWS access key id\n /gh[pousr]_[A-Za-z0-9]{36,}/, // GitHub tokens\n /sk-[A-Za-z0-9]{20,}/, // OpenAI-style secret keys\n /AIza[0-9A-Za-z_-]{35}/, // Google API key\n /xox[baprs]-[A-Za-z0-9-]{10,}/, // Slack tokens\n];\n\nfunction assignedName(node: ts.Node): string | undefined {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) return node.name.text;\n if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) return node.name.text;\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {\n if (ts.isPropertyAccessExpression(node.left)) return node.left.name.text;\n if (ts.isIdentifier(node.left)) return node.left.text;\n }\n return undefined;\n}\n\nfunction stringValueOf(node: ts.Node): ts.StringLiteral | undefined {\n const value = ts.isVariableDeclaration(node)\n ? node.initializer\n : ts.isPropertyAssignment(node)\n ? node.initializer\n : ts.isBinaryExpression(node)\n ? node.right\n : undefined;\n return value && ts.isStringLiteral(value) ? value : undefined;\n}\n\nexport const noHardcodedSecrets: Rule = {\n id: 'no-hardcoded-secrets',\n severity: 'error',\n description: 'Flags credentials and API keys embedded directly in source code.',\n message: 'Hardcoded secret. Load it from an environment variable or a secrets manager.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (ts.isStringLiteral(node) && KNOWN_TOKEN_PATTERNS.some((p) => p.test(node.text))) {\n context.report(node);\n return;\n }\n\n const name = assignedName(node);\n const value = stringValueOf(node);\n if (\n name &&\n value &&\n SECRET_NAME.test(name) &&\n value.text.trim().length > 0 &&\n // The literal branch already reports values that match a token shape.\n !KNOWN_TOKEN_PATTERNS.some((p) => p.test(value.text))\n ) {\n context.report(value);\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\nimport { isCallTo } from './ast-utils.js';\n\nexport const noEval: Rule = {\n id: 'no-eval',\n severity: 'error',\n description: 'Flags eval and the Function constructor, which execute arbitrary strings as code.',\n message: 'Avoid eval and new Function: they run arbitrary code and enable injection.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (isCallTo(node, 'eval')) {\n context.report(node, {\n suggestion: 'Parse the input or use a safe, explicit alternative.',\n });\n return;\n }\n if (\n (ts.isNewExpression(node) || ts.isCallExpression(node)) &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === 'Function'\n ) {\n context.report(node, {\n message: 'Avoid the Function constructor: it runs arbitrary code like eval.',\n suggestion: 'Define the function directly instead of building it from a string.',\n });\n }\n });\n },\n};\n","import ts from 'typescript';\n\n/** Resolves the dotted name of a property access, e.g. `console.log`. */\nexport function propertyAccessName(node: ts.PropertyAccessExpression): string {\n const left = ts.isPropertyAccessExpression(node.expression)\n ? propertyAccessName(node.expression)\n : ts.isIdentifier(node.expression)\n ? node.expression.text\n : node.expression.kind === ts.SyntaxKind.ThisKeyword\n ? 'this'\n : '';\n return left ? `${left}.${node.name.text}` : node.name.text;\n}\n\n/** True when the call is `callee(...)`, e.g. `eval(...)`. */\nexport function isCallTo(node: ts.Node, callee: string): node is ts.CallExpression {\n return (\n ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === callee\n );\n}\n\n/** Walks a `.then().catch()` style chain and lists the method names in it. */\nexport function chainMethodNames(node: ts.Expression): string[] {\n const names: string[] = [];\n let current: ts.Expression = node;\n while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {\n names.push(current.expression.name.text);\n current = current.expression.expression;\n }\n return names;\n}\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\n/**\n * Matches text that begins with a real SQL statement: a command followed\n * by its defining clause. Requiring the structure keeps class names and\n * other prose that merely contain a keyword (for example \"select-none\")\n * from being treated as SQL.\n */\nconst SQL_STATEMENT =\n /^\\s*(select\\b[\\s\\S]*\\bfrom\\b|insert\\s+into\\b|update\\b[\\s\\S]*\\bset\\b|delete\\s+from\\b|drop\\s+table\\b|truncate\\s+table\\b)/i;\n\nfunction looksLikeSql(text: string): boolean {\n return SQL_STATEMENT.test(text);\n}\n\n/** True when the node sits inside JSX, where strings are markup, not SQL. */\nfunction hasJsxAncestor(node: ts.Node): boolean {\n for (let current = node.parent; current; current = current.parent) {\n switch (current.kind) {\n case ts.SyntaxKind.JsxAttribute:\n case ts.SyntaxKind.JsxExpression:\n case ts.SyntaxKind.JsxElement:\n case ts.SyntaxKind.JsxSelfClosingElement:\n case ts.SyntaxKind.JsxFragment:\n return true;\n }\n }\n return false;\n}\n\n/** Concatenates the string literals of a `+` chain and notes dynamic parts. */\nfunction collectConcat(node: ts.BinaryExpression): { text: string; hasDynamic: boolean } {\n let text = '';\n let hasDynamic = false;\n const visit = (expr: ts.Expression): void => {\n if (ts.isBinaryExpression(expr) && expr.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n visit(expr.left);\n visit(expr.right);\n } else if (ts.isStringLiteral(expr)) {\n text += `${expr.text} `;\n } else {\n hasDynamic = true;\n }\n };\n visit(node);\n return { text, hasDynamic };\n}\n\n/** A `+` chain that builds a real SQL statement from a dynamic value. */\nfunction isConcatWithSql(node: ts.BinaryExpression): boolean {\n if (node.operatorToken.kind !== ts.SyntaxKind.PlusToken) return false;\n const { text, hasDynamic } = collectConcat(node);\n return hasDynamic && looksLikeSql(text);\n}\n\n/** A template literal with `${...}` holes whose text is a real SQL statement. */\nfunction isSqlTemplate(node: ts.TemplateExpression): boolean {\n if (node.templateSpans.length === 0) return false;\n const text = node.head.text + node.templateSpans.map((span) => span.literal.text).join(' ');\n return looksLikeSql(text);\n}\n\nexport const noSqlConcatenation: Rule = {\n id: 'no-sql-concatenation',\n severity: 'error',\n description: 'Flags SQL queries built by string concatenation or interpolation.',\n message: 'SQL built from untrusted input. Use parameterized queries or prepared statements.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (hasJsxAncestor(node)) return;\n\n if (ts.isBinaryExpression(node) && isConcatWithSql(node)) {\n // Report only the outermost `+` of a concatenation chain.\n const parent = node.parent;\n const isInnerConcat =\n ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.PlusToken;\n if (!isInnerConcat) context.report(node);\n } else if (ts.isTemplateExpression(node) && isSqlTemplate(node)) {\n context.report(node);\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\nconst SINK_PROPERTIES = new Set(['innerHTML', 'outerHTML']);\n\n/** `el.innerHTML = value` where value is not a plain string literal. */\nfunction isUnsafeHtmlAssignment(node: ts.BinaryExpression): boolean {\n if (node.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return false;\n if (!ts.isPropertyAccessExpression(node.left)) return false;\n if (!SINK_PROPERTIES.has(node.left.name.text)) return false;\n return !ts.isStringLiteral(node.right);\n}\n\nfunction jsxAttributeName(node: ts.JsxAttribute): string {\n return ts.isIdentifier(node.name) ? node.name.text : node.name.name.text;\n}\n\nexport const noUnsanitizedHtml: Rule = {\n id: 'no-unsanitized-html',\n severity: 'error',\n description: 'Flags raw HTML sinks such as innerHTML and dangerouslySetInnerHTML.',\n message: 'Unsanitized HTML sink. Sanitize the value or render it as text to avoid XSS.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (ts.isBinaryExpression(node) && isUnsafeHtmlAssignment(node)) {\n context.report(node);\n } else if (ts.isJsxAttribute(node) && jsxAttributeName(node) === 'dangerouslySetInnerHTML') {\n context.report(node, {\n message: 'dangerouslySetInnerHTML renders raw HTML. Sanitize the value first.',\n });\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\nexport const noLooseEquality: Rule = {\n id: 'no-loose-equality',\n severity: 'warning',\n description: 'Flags == and != comparisons, which coerce operands.',\n message: 'Use === or !== to avoid type coercion.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (!ts.isBinaryExpression(node)) return;\n const kind = node.operatorToken.kind;\n if (kind === ts.SyntaxKind.EqualsEqualsToken) {\n context.report(node.operatorToken, { suggestion: 'Replace == with ===.' });\n } else if (kind === ts.SyntaxKind.ExclamationEqualsToken) {\n context.report(node.operatorToken, {\n message: 'Use !== to avoid type coercion.',\n suggestion: 'Replace != with !==.',\n });\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\nimport { chainMethodNames } from './ast-utils.js';\n\n/**\n * A promise chain used as a statement, so its result is neither awaited\n * nor returned nor assigned. When the chain also lacks a `.catch`, a\n * rejection goes unhandled.\n */\nfunction isFloatingThen(statement: ts.ExpressionStatement): boolean {\n const expression = statement.expression;\n if (!ts.isCallExpression(expression)) return false;\n const methods = chainMethodNames(expression);\n return methods.includes('then') && !methods.includes('catch');\n}\n\nexport const noFloatingPromises: Rule = {\n id: 'no-floating-promises',\n severity: 'warning',\n description: 'Flags promise chains that are neither awaited nor given a catch handler.',\n message: 'Floating promise: await it or add a .catch so rejections are handled.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (ts.isExpressionStatement(node) && isFloatingThen(node)) {\n context.report(node);\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\n/** An empty catch block with no statements and no explanatory comment. */\nfunction isSilentCatch(clause: ts.CatchClause, sourceFile: ts.SourceFile): boolean {\n if (clause.block.statements.length > 0) return false;\n const inner = clause.block.getText(sourceFile).slice(1, -1);\n return inner.trim().length === 0;\n}\n\nexport const noEmptyCatch: Rule = {\n id: 'no-empty-catch',\n severity: 'warning',\n description: 'Flags catch blocks that swallow errors without handling or logging them.',\n message: 'Empty catch block swallows the error. Handle it, rethrow, or log why it is ignored.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (ts.isCatchClause(node) && isSilentCatch(node, context.sourceFile)) {\n context.report(node);\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\nimport { propertyAccessName } from './ast-utils.js';\n\nconst FLAGGED_METHODS = new Set(['console.log', 'console.debug']);\n\nexport const noConsoleLog: Rule = {\n id: 'no-console-log',\n severity: 'info',\n description: 'Flags leftover console.log and console.debug calls.',\n message: 'Leftover console call. Remove it or use a configurable logger.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (!ts.isCallExpression(node)) return;\n if (!ts.isPropertyAccessExpression(node.expression)) return;\n if (FLAGGED_METHODS.has(propertyAccessName(node.expression))) {\n context.report(node);\n }\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\nfunction countIdentifiers(sourceFile: ts.SourceFile): Map<string, number> {\n const counts = new Map<string, number>();\n walk(sourceFile, (node) => {\n if (ts.isIdentifier(node)) {\n counts.set(node.text, (counts.get(node.text) ?? 0) + 1);\n }\n });\n return counts;\n}\n\nfunction isExported(declaration: ts.VariableDeclaration): boolean {\n const statement = declaration.parent.parent;\n return (\n ts.isVariableStatement(statement) &&\n (statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)\n );\n}\n\n/**\n * Reports local variables that are never read. Detection is name-based\n * and intentionally conservative: a name reused anywhere else in the\n * file counts as used, so the rule favors silence over false positives.\n */\nexport const noUnusedVariables: Rule = {\n id: 'no-unused-variables',\n severity: 'info',\n description: 'Flags local variable declarations that are never referenced.',\n message: 'Unused variable. Remove it or prefix it with an underscore if intentional.',\n check(context: RuleContext): void {\n const counts = countIdentifiers(context.sourceFile);\n\n walk(context.sourceFile, (node) => {\n if (!ts.isVariableDeclaration(node)) return;\n if (!ts.isIdentifier(node.name)) return;\n\n const name = node.name.text;\n if (name.startsWith('_')) return;\n if (isExported(node)) return;\n if ((counts.get(name) ?? 0) > 1) return;\n\n context.report(node.name, {\n message: `Unused variable \"${name}\". Remove it or prefix it with an underscore.`,\n });\n });\n },\n};\n","import ts from 'typescript';\nimport type { Rule, RuleContext } from '../core/types.js';\nimport { walk } from '../parser/parser.js';\n\nexport const MAX_COMPLEXITY = 10;\nexport const MAX_LINES = 50;\n\ntype FunctionLike =\n | ts.FunctionDeclaration\n | ts.FunctionExpression\n | ts.ArrowFunction\n | ts.MethodDeclaration\n | ts.ConstructorDeclaration\n | ts.GetAccessorDeclaration\n | ts.SetAccessorDeclaration;\n\nfunction isFunctionLike(node: ts.Node): node is FunctionLike {\n return (\n ts.isFunctionDeclaration(node) ||\n ts.isFunctionExpression(node) ||\n ts.isArrowFunction(node) ||\n ts.isMethodDeclaration(node) ||\n ts.isConstructorDeclaration(node) ||\n ts.isGetAccessor(node) ||\n ts.isSetAccessor(node)\n );\n}\n\nconst DECISION_KINDS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.IfStatement,\n ts.SyntaxKind.ForStatement,\n ts.SyntaxKind.ForInStatement,\n ts.SyntaxKind.ForOfStatement,\n ts.SyntaxKind.WhileStatement,\n ts.SyntaxKind.DoStatement,\n ts.SyntaxKind.CaseClause,\n ts.SyntaxKind.CatchClause,\n ts.SyntaxKind.ConditionalExpression,\n]);\n\nconst LOGICAL_OPERATORS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.AmpersandAmpersandToken,\n ts.SyntaxKind.BarBarToken,\n ts.SyntaxKind.QuestionQuestionToken,\n]);\n\nfunction addsComplexity(node: ts.Node): boolean {\n if (DECISION_KINDS.has(node.kind)) return true;\n return ts.isBinaryExpression(node) && LOGICAL_OPERATORS.has(node.operatorToken.kind);\n}\n\n/** Counts decision points in a function without descending into nested functions. */\nfunction complexityOf(fn: FunctionLike): number {\n let complexity = 1;\n const visit = (node: ts.Node): void => {\n if (node !== fn && isFunctionLike(node)) return;\n if (addsComplexity(node)) complexity += 1;\n node.forEachChild(visit);\n };\n fn.forEachChild(visit);\n return complexity;\n}\n\nfunction lineSpan(fn: FunctionLike, sourceFile: ts.SourceFile): number {\n const start = sourceFile.getLineAndCharacterOfPosition(fn.getStart(sourceFile)).line;\n const end = sourceFile.getLineAndCharacterOfPosition(fn.getEnd()).line;\n return end - start + 1;\n}\n\nfunction reportTarget(fn: FunctionLike): ts.Node {\n return 'name' in fn && fn.name ? fn.name : fn;\n}\n\nexport const noComplexFunctions: Rule = {\n id: 'no-complex-functions',\n severity: 'warning',\n description: 'Flags functions that are too long or have high cyclomatic complexity.',\n message: 'Function is too complex. Split it into smaller, focused functions.',\n check(context: RuleContext): void {\n walk(context.sourceFile, (node) => {\n if (!isFunctionLike(node)) return;\n\n const complexity = complexityOf(node);\n const lines = lineSpan(node, context.sourceFile);\n if (complexity <= MAX_COMPLEXITY && lines <= MAX_LINES) return;\n\n const reasons: string[] = [];\n if (complexity > MAX_COMPLEXITY) {\n reasons.push(`cyclomatic complexity ${complexity} (max ${MAX_COMPLEXITY})`);\n }\n if (lines > MAX_LINES) {\n reasons.push(`${lines} lines (max ${MAX_LINES})`);\n }\n\n context.report(reportTarget(node), {\n message: `Function is too complex: ${reasons.join(', ')}. Split it into smaller functions.`,\n });\n });\n },\n};\n","import type { Rule } from '../core/types.js';\nimport { noHardcodedSecrets } from './no-hardcoded-secrets.js';\nimport { noEval } from './no-eval.js';\nimport { noSqlConcatenation } from './no-sql-concatenation.js';\nimport { noUnsanitizedHtml } from './no-unsanitized-html.js';\nimport { noLooseEquality } from './no-loose-equality.js';\nimport { noFloatingPromises } from './no-floating-promises.js';\nimport { noEmptyCatch } from './no-empty-catch.js';\nimport { noConsoleLog } from './no-console-log.js';\nimport { noUnusedVariables } from './no-unused-variables.js';\nimport { noComplexFunctions } from './no-complex-functions.js';\n\n/** Every rule shipped with Vigil, in a stable order. */\nexport const rules: readonly Rule[] = [\n noHardcodedSecrets,\n noEval,\n noSqlConcatenation,\n noUnsanitizedHtml,\n noLooseEquality,\n noFloatingPromises,\n noEmptyCatch,\n noConsoleLog,\n noUnusedVariables,\n noComplexFunctions,\n];\n\nexport {\n noHardcodedSecrets,\n noEval,\n noSqlConcatenation,\n noUnsanitizedHtml,\n noLooseEquality,\n noFloatingPromises,\n noEmptyCatch,\n noConsoleLog,\n noUnusedVariables,\n noComplexFunctions,\n};\n","import { readFileSync } from 'node:fs';\nimport type { Finding, Rule, Severity, VigilConfig } from './types.js';\nimport { parse } from '../parser/parser.js';\nimport { analyzeSource } from './engine.js';\nimport { collectFiles } from './files.js';\nimport { resolveIgnore } from './config.js';\nimport { rules as defaultRules } from '../rules/index.js';\n\nexport interface AnalyzeOptions {\n config?: VigilConfig;\n rules?: readonly Rule[];\n}\n\n/** A single source given by its path and its contents, held in memory. */\nexport interface SourceInput {\n path: string;\n content: string;\n}\n\nexport interface AnalysisResult {\n findings: Finding[];\n filesAnalyzed: number;\n counts: Record<Severity, number>;\n}\n\nconst SEVERITY_ORDER: Record<Severity, number> = { info: 0, warning: 1, error: 2 };\n\nfunction emptyCounts(): Record<Severity, number> {\n return { error: 0, warning: 0, info: 0 };\n}\n\n/**\n * Analyzes in-memory sources and returns every finding plus a summary.\n * This is the single aggregation path: the disk-based `analyze` reads\n * files and delegates here, and other front ends can call it directly.\n */\nexport function analyzeContent(\n inputs: readonly SourceInput[],\n options: AnalyzeOptions = {},\n): AnalysisResult {\n const config = options.config ?? {};\n const rules = options.rules ?? defaultRules;\n\n const findings: Finding[] = [];\n for (const input of inputs) {\n findings.push(...analyzeSource(parse(input.path, input.content), rules, config));\n }\n\n const counts = emptyCounts();\n for (const finding of findings) counts[finding.severity] += 1;\n\n return { findings, filesAnalyzed: inputs.length, counts };\n}\n\n/**\n * Analyzes a file or directory and returns every finding plus a summary.\n * Files that cannot be read are skipped rather than aborting the run.\n */\nexport function analyze(target: string, options: AnalyzeOptions = {}): AnalysisResult {\n const config = options.config ?? {};\n const files = collectFiles(target, resolveIgnore(config));\n\n const inputs: SourceInput[] = [];\n for (const file of files) {\n try {\n inputs.push({ path: file, content: readFileSync(file, 'utf8') });\n } catch {\n continue;\n }\n }\n\n return analyzeContent(inputs, options);\n}\n\n/** True when any finding meets or exceeds the `failOn` severity. */\nexport function hasFailures(result: AnalysisResult, failOn: Severity = 'error'): boolean {\n const threshold = SEVERITY_ORDER[failOn];\n return result.findings.some((finding) => SEVERITY_ORDER[finding.severity] >= threshold);\n}\n","import { readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst SUPPORTED_EXTENSIONS = new Set([\n '.ts',\n '.tsx',\n '.mts',\n '.cts',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n]);\n\nfunction hasSupportedExtension(filePath: string): boolean {\n const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();\n return SUPPORTED_EXTENSIONS.has(ext);\n}\n\nfunction isIgnored(path: string, ignore: readonly string[]): boolean {\n const normalized = path.split('\\\\').join('/');\n return ignore.some((fragment) => fragment.length > 0 && normalized.includes(fragment));\n}\n\n/**\n * Returns every supported source file under `target`. `target` may be a\n * single file or a directory, which is scanned recursively. Paths whose\n * text contains any `ignore` fragment are skipped.\n */\nexport function collectFiles(target: string, ignore: readonly string[] = []): string[] {\n const stats = statSync(target);\n\n if (stats.isFile()) {\n return hasSupportedExtension(target) && !isIgnored(target, ignore) ? [target] : [];\n }\n\n const found: string[] = [];\n for (const entry of readdirSync(target, { withFileTypes: true })) {\n const entryPath = join(target, entry.name);\n if (isIgnored(entryPath, ignore)) continue;\n\n if (entry.isDirectory()) {\n found.push(...collectFiles(entryPath, ignore));\n } else if (entry.isFile() && hasSupportedExtension(entryPath)) {\n found.push(entryPath);\n }\n }\n return found;\n}\n","import pc from 'picocolors';\nimport { relative } from 'node:path';\nimport type { Finding, Severity } from '../core/types.js';\nimport type { AnalysisResult } from '../core/analyzer.js';\nimport type { Reporter } from './types.js';\n\nconst SEVERITY_LABEL: Record<Severity, (text: string) => string> = {\n error: (t) => pc.red(t),\n warning: (t) => pc.yellow(t),\n info: (t) => pc.blue(t),\n};\n\nfunction groupByFile(findings: readonly Finding[]): Map<string, Finding[]> {\n const groups = new Map<string, Finding[]>();\n for (const finding of findings) {\n const group = groups.get(finding.file) ?? [];\n group.push(finding);\n groups.set(finding.file, group);\n }\n return groups;\n}\n\nfunction renderFinding(finding: Finding): string {\n const location = pc.dim(`${finding.line}:${finding.column}`);\n const label = SEVERITY_LABEL[finding.severity](finding.severity);\n const rule = pc.dim(finding.ruleId);\n const lines = [` ${location} ${label} ${finding.message} ${rule}`];\n if (finding.snippet) lines.push(` ${pc.dim(finding.snippet)}`);\n if (finding.suggestion) lines.push(` ${pc.green('fix')} ${finding.suggestion}`);\n return lines.join('\\n');\n}\n\nfunction renderSummary(result: AnalysisResult): string {\n const { error, warning, info } = result.counts;\n const total = error + warning + info;\n if (total === 0) {\n return pc.green(`No issues found in ${result.filesAnalyzed} file(s).`);\n }\n const parts = [\n SEVERITY_LABEL.error(`${error} error(s)`),\n SEVERITY_LABEL.warning(`${warning} warning(s)`),\n SEVERITY_LABEL.info(`${info} info`),\n ];\n return `${pc.bold(`${total} issue(s)`)} in ${result.filesAnalyzed} file(s): ${parts.join(', ')}`;\n}\n\nexport function createTerminalReporter(cwd: string = process.cwd()): Reporter {\n return {\n render(result: AnalysisResult): string {\n const blocks: string[] = [];\n for (const [file, findings] of groupByFile(result.findings)) {\n blocks.push(pc.underline(relative(cwd, file) || file));\n blocks.push(findings.map(renderFinding).join('\\n'));\n blocks.push('');\n }\n blocks.push(renderSummary(result));\n return blocks.join('\\n');\n },\n };\n}\n","import type { AnalysisResult } from '../core/analyzer.js';\nimport type { Reporter } from './types.js';\n\n/**\n * Emits the result as formatted JSON. The shape is stable and intended\n * for consumption by other tools.\n */\nexport function createJsonReporter(): Reporter {\n return {\n render(result: AnalysisResult): string {\n return JSON.stringify(\n {\n filesAnalyzed: result.filesAnalyzed,\n counts: result.counts,\n findings: result.findings,\n },\n null,\n 2,\n );\n },\n };\n}\n","import { relative } from 'node:path';\nimport type { Finding, Rule, Severity } from '../core/types.js';\nimport type { AnalysisResult } from '../core/analyzer.js';\nimport { rules as defaultRules } from '../rules/index.js';\nimport type { Reporter } from './types.js';\n\nconst SARIF_LEVEL: Record<Severity, 'error' | 'warning' | 'note'> = {\n error: 'error',\n warning: 'warning',\n info: 'note',\n};\n\nconst SCHEMA =\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json';\n\nfunction toUri(file: string, cwd: string): string {\n return (relative(cwd, file) || file).split('\\\\').join('/');\n}\n\nfunction ruleDescriptors(rules: readonly Rule[]) {\n return rules.map((rule) => ({\n id: rule.id,\n name: rule.id,\n shortDescription: { text: rule.description },\n defaultConfiguration: { level: SARIF_LEVEL[rule.severity] },\n }));\n}\n\nfunction resultFor(finding: Finding, cwd: string) {\n return {\n ruleId: finding.ruleId,\n level: SARIF_LEVEL[finding.severity],\n message: { text: finding.message },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: toUri(finding.file, cwd) },\n region: {\n startLine: finding.line,\n startColumn: finding.column,\n snippet: { text: finding.snippet },\n },\n },\n },\n ],\n };\n}\n\n/** Emits SARIF 2.1.0, consumable by GitHub code scanning. */\nexport function createSarifReporter(\n cwd: string = process.cwd(),\n rules: readonly Rule[] = defaultRules,\n): Reporter {\n return {\n render(result: AnalysisResult): string {\n const sarif = {\n $schema: SCHEMA,\n version: '2.1.0',\n runs: [\n {\n tool: {\n driver: {\n name: 'Vigil',\n informationUri: 'https://github.com/Sagudelo01/vigil',\n rules: ruleDescriptors(rules),\n },\n },\n results: result.findings.map((finding) => resultFor(finding, cwd)),\n },\n ],\n };\n return JSON.stringify(sarif, null, 2);\n },\n };\n}\n","import type { Reporter, ReportFormat } from './types.js';\nimport { createTerminalReporter } from './terminal.js';\nimport { createJsonReporter } from './json.js';\nimport { createSarifReporter } from './sarif.js';\n\nexport type { Reporter, ReportFormat } from './types.js';\nexport { createTerminalReporter } from './terminal.js';\nexport { createJsonReporter } from './json.js';\nexport { createSarifReporter } from './sarif.js';\n\n/** Returns the reporter for a format, defaulting to terminal output. */\nexport function createReporter(format: ReportFormat, cwd: string = process.cwd()): Reporter {\n switch (format) {\n case 'json':\n return createJsonReporter();\n case 'sarif':\n return createSarifReporter(cwd);\n case 'terminal':\n default:\n return createTerminalReporter(cwd);\n }\n}\n"],"mappings":";;;AAAA,OAAO,QAAQ;AAOf,IAAM,qBAAoD;AAAA,EACxD,OAAO,GAAG,WAAW;AAAA,EACrB,QAAQ,GAAG,WAAW;AAAA,EACtB,QAAQ,GAAG,WAAW;AAAA,EACtB,QAAQ,GAAG,WAAW;AAAA,EACtB,OAAO,GAAG,WAAW;AAAA,EACrB,QAAQ,GAAG,WAAW;AAAA,EACtB,QAAQ,GAAG,WAAW;AAAA,EACtB,QAAQ,GAAG,WAAW;AACxB;AAEA,SAAS,cAAc,UAAiC;AACtD,QAAM,MAAM,SAAS,MAAM,SAAS,YAAY,GAAG,CAAC,EAAE,YAAY;AAClE,SAAO,mBAAmB,GAAG,KAAK,GA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AQ;AAAA,QACZ,SAAS;AAAA,QACT,SAAS;AAAA,QACT,MAAM;AAAA,UACJ;AAAA,YACE,MAAM;AAAA,cACJ,QAAQ;AAAA,gBACN,MAAM;AAAA,gBACN,gBAAgB;AAAA,gBAChB,OAAO,gBAAgBA,MAAK;AAAA,cAC9B;AAAA,YACF;AAAA,YACA,SAAS,OAAO,SAAS,IAAI,CAAC,YAAY,UAAU,SAAS,GAAG,CAAC;AAAA,UACnE;AAAA,QACF;AAAA,MACF;AACA,aAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AAAA,IACtC;AAAA,EACF;AACF;;;AC/DO,SAAS,eAAe,QAAsB,MAAc,QAAQ,IAAI,GAAa;AAC1F,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO,mBAAmB;AAAA,IAC5B,KAAK;AACH,aAAO,oBAAoB,GAAG;AAAA,IAChC,KAAK;AAAA,IACL;AACE,aAAO,uBAAuB,GAAG;AAAA,EACrC;AACF;","names":["rules","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","ts","readFileSync","rules","readFileSync","relative","relative","rules"]}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { Command } from 'commander';
2
+
3
+ interface CliIo {
4
+ cwd: string;
5
+ stdout: (text: string) => void;
6
+ stderr: (text: string) => void;
7
+ }
8
+
9
+ interface ProgramHandle {
10
+ program: Command;
11
+ /** Exit code of the last command run, available after parsing. */
12
+ getExitCode: () => number;
13
+ }
14
+ declare function buildProgram(io: CliIo): ProgramHandle;
15
+
16
+ export { type ProgramHandle, buildProgram };
package/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ConfigError,
4
+ analyze,
5
+ createReporter,
6
+ hasFailures,
7
+ loadConfig,
8
+ loadConfigFile
9
+ } from "./chunk-IUUQ5FY3.js";
10
+
11
+ // src/cli/cli.ts
12
+ import { Command } from "commander";
13
+
14
+ // src/cli/run.ts
15
+ import { existsSync } from "fs";
16
+ import { resolve } from "path";
17
+ var EXIT_OK = 0;
18
+ var EXIT_FINDINGS = 1;
19
+ var EXIT_ERROR = 2;
20
+ var FORMATS = ["terminal", "json", "sarif"];
21
+ var SEVERITIES = ["error", "warning", "info"];
22
+ function resolveFailOn(cli, config) {
23
+ return cli.failOn ?? config.failOn ?? "error";
24
+ }
25
+ function runAnalyze(target, options, io2) {
26
+ if (!FORMATS.includes(options.format)) {
27
+ io2.stderr(`Unknown format "${options.format}". Use one of: ${FORMATS.join(", ")}.`);
28
+ return EXIT_ERROR;
29
+ }
30
+ if (options.failOn && !SEVERITIES.includes(options.failOn)) {
31
+ io2.stderr(`Unknown severity "${options.failOn}". Use one of: ${SEVERITIES.join(", ")}.`);
32
+ return EXIT_ERROR;
33
+ }
34
+ const targetPath = resolve(io2.cwd, target);
35
+ if (!existsSync(targetPath)) {
36
+ io2.stderr(`Path not found: ${target}`);
37
+ return EXIT_ERROR;
38
+ }
39
+ let config;
40
+ try {
41
+ config = options.config ? loadConfigFile(resolve(io2.cwd, options.config)) : loadConfig(io2.cwd);
42
+ } catch (error) {
43
+ if (error instanceof ConfigError) {
44
+ io2.stderr(error.message);
45
+ return EXIT_ERROR;
46
+ }
47
+ throw error;
48
+ }
49
+ const result = analyze(targetPath, { config });
50
+ io2.stdout(createReporter(options.format, io2.cwd).render(result));
51
+ return hasFailures(result, resolveFailOn(options, config)) ? EXIT_FINDINGS : EXIT_OK;
52
+ }
53
+
54
+ // src/cli/cli.ts
55
+ function buildProgram(io2) {
56
+ const program2 = new Command();
57
+ let exitCode = 0;
58
+ program2.name("vigil").description("Static analysis for JavaScript and TypeScript focused on security and bugs.").version("0.1.0");
59
+ program2.command("analyze").description("Analyze a file or directory for security and bug patterns.").argument("<path>", "file or directory to analyze").option("-f, --format <format>", "output format: terminal, json, or sarif", "terminal").option("-c, --config <file>", "path to a configuration file").option("--fail-on <severity>", "lowest severity that fails the run: error, warning, info").action((path, options) => {
60
+ exitCode = runAnalyze(
61
+ path,
62
+ {
63
+ format: options.format,
64
+ ...options.config !== void 0 ? { config: options.config } : {},
65
+ ...options.failOn !== void 0 ? { failOn: options.failOn } : {}
66
+ },
67
+ io2
68
+ );
69
+ });
70
+ return { program: program2, getExitCode: () => exitCode };
71
+ }
72
+ var io = {
73
+ cwd: process.cwd(),
74
+ stdout: (text) => process.stdout.write(`${text}
75
+ `),
76
+ stderr: (text) => process.stderr.write(`${text}
77
+ `)
78
+ };
79
+ var { program, getExitCode } = buildProgram(io);
80
+ try {
81
+ program.parse(process.argv);
82
+ process.exit(getExitCode());
83
+ } catch {
84
+ process.exit(EXIT_ERROR);
85
+ }
86
+ export {
87
+ buildProgram
88
+ };
89
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/cli.ts","../src/cli/run.ts"],"sourcesContent":["import { Command } from 'commander';\nimport type { ReportFormat } from '../reporters/types.js';\nimport type { Severity } from '../core/types.js';\nimport { runAnalyze, EXIT_ERROR, type CliIo } from './run.js';\n\nexport interface ProgramHandle {\n program: Command;\n /** Exit code of the last command run, available after parsing. */\n getExitCode: () => number;\n}\n\nexport function buildProgram(io: CliIo): ProgramHandle {\n const program = new Command();\n let exitCode = 0;\n\n program\n .name('vigil')\n .description('Static analysis for JavaScript and TypeScript focused on security and bugs.')\n .version('0.1.0');\n\n program\n .command('analyze')\n .description('Analyze a file or directory for security and bug patterns.')\n .argument('<path>', 'file or directory to analyze')\n .option('-f, --format <format>', 'output format: terminal, json, or sarif', 'terminal')\n .option('-c, --config <file>', 'path to a configuration file')\n .option('--fail-on <severity>', 'lowest severity that fails the run: error, warning, info')\n .action((path: string, options: { format: string; config?: string; failOn?: string }) => {\n exitCode = runAnalyze(\n path,\n {\n format: options.format as ReportFormat,\n ...(options.config !== undefined ? { config: options.config } : {}),\n ...(options.failOn !== undefined ? { failOn: options.failOn as Severity } : {}),\n },\n io,\n );\n });\n\n return { program, getExitCode: () => exitCode };\n}\n\nconst io: CliIo = {\n cwd: process.cwd(),\n stdout: (text) => process.stdout.write(`${text}\\n`),\n stderr: (text) => process.stderr.write(`${text}\\n`),\n};\n\nconst { program, getExitCode } = buildProgram(io);\n\ntry {\n program.parse(process.argv);\n process.exit(getExitCode());\n} catch {\n process.exit(EXIT_ERROR);\n}\n","import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { Severity, VigilConfig } from '../core/types.js';\nimport { analyze, hasFailures } from '../core/analyzer.js';\nimport { loadConfig, loadConfigFile, ConfigError } from '../core/config.js';\nimport { createReporter } from '../reporters/index.js';\nimport type { ReportFormat } from '../reporters/types.js';\n\nexport interface CliIo {\n cwd: string;\n stdout: (text: string) => void;\n stderr: (text: string) => void;\n}\n\nexport interface AnalyzeCliOptions {\n format: ReportFormat;\n config?: string;\n failOn?: Severity;\n}\n\nexport const EXIT_OK = 0;\nexport const EXIT_FINDINGS = 1;\nexport const EXIT_ERROR = 2;\n\nconst FORMATS: readonly ReportFormat[] = ['terminal', 'json', 'sarif'];\nconst SEVERITIES: readonly Severity[] = ['error', 'warning', 'info'];\n\nfunction resolveFailOn(cli: AnalyzeCliOptions, config: VigilConfig): Severity {\n return cli.failOn ?? config.failOn ?? 'error';\n}\n\n/**\n * Runs the `analyze` command and returns a process exit code: 0 when the\n * run is clean, 1 when findings reach the fail threshold, 2 on usage or\n * configuration errors. All output goes through `io`, never directly to\n * the console, which keeps the command testable.\n */\nexport function runAnalyze(target: string, options: AnalyzeCliOptions, io: CliIo): number {\n if (!FORMATS.includes(options.format)) {\n io.stderr(`Unknown format \"${options.format}\". Use one of: ${FORMATS.join(', ')}.`);\n return EXIT_ERROR;\n }\n if (options.failOn && !SEVERITIES.includes(options.failOn)) {\n io.stderr(`Unknown severity \"${options.failOn}\". Use one of: ${SEVERITIES.join(', ')}.`);\n return EXIT_ERROR;\n }\n\n const targetPath = resolve(io.cwd, target);\n if (!existsSync(targetPath)) {\n io.stderr(`Path not found: ${target}`);\n return EXIT_ERROR;\n }\n\n let config: VigilConfig;\n try {\n config = options.config ? loadConfigFile(resolve(io.cwd, options.config)) : loadConfig(io.cwd);\n } catch (error) {\n if (error instanceof ConfigError) {\n io.stderr(error.message);\n return EXIT_ERROR;\n }\n throw error;\n }\n\n const result = analyze(targetPath, { config });\n io.stdout(createReporter(options.format, io.cwd).render(result));\n\n return hasFailures(result, resolveFailOn(options, config)) ? EXIT_FINDINGS : EXIT_OK;\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAe;;;ACAxB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAmBjB,IAAM,UAAU;AAChB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AAE1B,IAAM,UAAmC,CAAC,YAAY,QAAQ,OAAO;AACrE,IAAM,aAAkC,CAAC,SAAS,WAAW,MAAM;AAEnE,SAAS,cAAc,KAAwB,QAA+B;AAC5E,SAAO,IAAI,UAAU,OAAO,UAAU;AACxC;AAQO,SAAS,WAAW,QAAgB,SAA4BA,KAAmB;AACxF,MAAI,CAAC,QAAQ,SAAS,QAAQ,MAAM,GAAG;AACrC,IAAAA,IAAG,OAAO,mBAAmB,QAAQ,MAAM,kBAAkB,QAAQ,KAAK,IAAI,CAAC,GAAG;AAClF,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,UAAU,CAAC,WAAW,SAAS,QAAQ,MAAM,GAAG;AAC1D,IAAAA,IAAG,OAAO,qBAAqB,QAAQ,MAAM,kBAAkB,WAAW,KAAK,IAAI,CAAC,GAAG;AACvF,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,QAAQA,IAAG,KAAK,MAAM;AACzC,MAAI,CAAC,WAAW,UAAU,GAAG;AAC3B,IAAAA,IAAG,OAAO,mBAAmB,MAAM,EAAE;AACrC,WAAO;AAAA,EACT;AAEA,MAAI;AACJ,MAAI;AACF,aAAS,QAAQ,SAAS,eAAe,QAAQA,IAAG,KAAK,QAAQ,MAAM,CAAC,IAAI,WAAWA,I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,IAAM,EAAE,SAAS,YAAY,IAAI,aAAa,EAAE;AAEhD,IAAI;AACF,UAAQ,MAAM,QAAQ,IAAI;AAC1B,UAAQ,KAAK,YAAY,CAAC;AAC5B,QAAQ;AACN,UAAQ,KAAK,UAAU;AACzB;","names":["io","io","program"]}
@@ -0,0 +1,127 @@
1
+ import ts from 'typescript';
2
+
3
+ type Severity = 'error' | 'warning' | 'info';
4
+ /** A single issue found in a source file. Positions are 1-based. */
5
+ interface Finding {
6
+ ruleId: string;
7
+ severity: Severity;
8
+ message: string;
9
+ file: string;
10
+ line: number;
11
+ column: number;
12
+ snippet: string;
13
+ suggestion?: string;
14
+ }
15
+ /** Options accepted when a rule reports a finding. */
16
+ interface ReportOptions {
17
+ /** Overrides the rule's default message. */
18
+ message?: string;
19
+ /** How to fix the issue. */
20
+ suggestion?: string;
21
+ }
22
+ /**
23
+ * Passed to a rule while it analyzes one file. The rule walks
24
+ * `sourceFile` and calls `report` for each issue it detects.
25
+ */
26
+ interface RuleContext {
27
+ readonly filePath: string;
28
+ readonly sourceFile: ts.SourceFile;
29
+ report(node: ts.Node, options?: ReportOptions): void;
30
+ }
31
+ /**
32
+ * A rule is a self-contained check. It owns its traversal of the AST,
33
+ * which keeps rules independent from the engine and from each other.
34
+ */
35
+ interface Rule {
36
+ readonly id: string;
37
+ readonly severity: Severity;
38
+ readonly description: string;
39
+ readonly message: string;
40
+ check(context: RuleContext): void;
41
+ }
42
+ /** Per-rule overrides read from the configuration file. */
43
+ interface RuleSetting {
44
+ enabled?: boolean;
45
+ severity?: Severity;
46
+ }
47
+ interface VigilConfig {
48
+ /** Keyed by rule id. */
49
+ rules?: Record<string, RuleSetting>;
50
+ /** Glob-like path fragments to skip. */
51
+ ignore?: string[];
52
+ /** Highest severity that still exits with code 0. */
53
+ failOn?: Severity;
54
+ }
55
+
56
+ interface AnalyzeOptions {
57
+ config?: VigilConfig;
58
+ rules?: readonly Rule[];
59
+ }
60
+ /** A single source given by its path and its contents, held in memory. */
61
+ interface SourceInput {
62
+ path: string;
63
+ content: string;
64
+ }
65
+ interface AnalysisResult {
66
+ findings: Finding[];
67
+ filesAnalyzed: number;
68
+ counts: Record<Severity, number>;
69
+ }
70
+ /**
71
+ * Analyzes in-memory sources and returns every finding plus a summary.
72
+ * This is the single aggregation path: the disk-based `analyze` reads
73
+ * files and delegates here, and other front ends can call it directly.
74
+ */
75
+ declare function analyzeContent(inputs: readonly SourceInput[], options?: AnalyzeOptions): AnalysisResult;
76
+ /**
77
+ * Analyzes a file or directory and returns every finding plus a summary.
78
+ * Files that cannot be read are skipped rather than aborting the run.
79
+ */
80
+ declare function analyze(target: string, options?: AnalyzeOptions): AnalysisResult;
81
+ /** True when any finding meets or exceeds the `failOn` severity. */
82
+ declare function hasFailures(result: AnalysisResult, failOn?: Severity): boolean;
83
+
84
+ type ReportFormat = 'terminal' | 'json' | 'sarif';
85
+ interface Reporter {
86
+ /** Renders a full analysis result as a string ready to print. */
87
+ render(result: AnalysisResult): string;
88
+ }
89
+
90
+ interface ParsedSource {
91
+ filePath: string;
92
+ sourceFile: ts.SourceFile;
93
+ }
94
+ /**
95
+ * Builds a TypeScript AST from source text. Parsing is syntactic only:
96
+ * no type checker and no program, so a single file is analyzed in
97
+ * isolation and without resolving imports.
98
+ */
99
+ declare function parse(filePath: string, source: string): ParsedSource;
100
+ /** Depth-first walk of every node in the tree, root included. */
101
+ declare function walk(node: ts.Node, visit: (node: ts.Node) => void): void;
102
+
103
+ /**
104
+ * Runs the enabled rules against one parsed file and returns every
105
+ * finding. Each rule receives its own context, so a rule cannot see or
106
+ * disturb another rule's state.
107
+ */
108
+ declare function analyzeSource(parsed: ParsedSource, rules: readonly Rule[], config?: VigilConfig): Finding[];
109
+
110
+ declare const CONFIG_FILENAME = "vigil.config.json";
111
+ declare class ConfigError extends Error {
112
+ }
113
+ /**
114
+ * Loads configuration from `vigil.config.json` in `cwd`. A missing file
115
+ * is not an error: the caller gets an empty config and built-in defaults.
116
+ */
117
+ declare function loadConfig(cwd?: string): VigilConfig;
118
+ /** Merges the configured ignore list with the built-in defaults. */
119
+ declare function resolveIgnore(config: VigilConfig): string[];
120
+
121
+ /** Every rule shipped with Vigil, in a stable order. */
122
+ declare const rules: readonly Rule[];
123
+
124
+ /** Returns the reporter for a format, defaulting to terminal output. */
125
+ declare function createReporter(format: ReportFormat, cwd?: string): Reporter;
126
+
127
+ export { type AnalysisResult, type AnalyzeOptions, CONFIG_FILENAME, ConfigError, type Finding, type ReportFormat, type ReportOptions, type Reporter, type Rule, type RuleContext, type RuleSetting, type Severity, type SourceInput, type VigilConfig, analyze, analyzeContent, analyzeSource, createReporter, hasFailures, loadConfig, parse, resolveIgnore, rules, walk };
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_FILENAME,
4
+ ConfigError,
5
+ analyze,
6
+ analyzeContent,
7
+ analyzeSource,
8
+ createReporter,
9
+ hasFailures,
10
+ loadConfig,
11
+ parse,
12
+ resolveIgnore,
13
+ rules,
14
+ walk
15
+ } from "./chunk-IUUQ5FY3.js";
16
+ export {
17
+ CONFIG_FILENAME,
18
+ ConfigError,
19
+ analyze,
20
+ analyzeContent,
21
+ analyzeSource,
22
+ createReporter,
23
+ hasFailures,
24
+ loadConfig,
25
+ parse,
26
+ resolveIgnore,
27
+ rules,
28
+ walk
29
+ };
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@sagudelo01/vigil",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Static analysis for JavaScript and TypeScript focused on security and bug patterns",
5
+ "license": "MIT",
6
+ "author": "Santiago Agudelo",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "bin": {
12
+ "vigil": "dist/cli.js"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/Sagudelo01/vigil.git",
28
+ "directory": "packages/core"
29
+ },
30
+ "homepage": "https://github.com/Sagudelo01/vigil#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/Sagudelo01/vigil/issues"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "dev": "tsup --watch",
40
+ "lint": "eslint .",
41
+ "typecheck": "tsc --noEmit",
42
+ "test": "vitest run",
43
+ "test:watch": "vitest",
44
+ "test:coverage": "vitest run --coverage",
45
+ "prepublishOnly": "pnpm build"
46
+ },
47
+ "keywords": [
48
+ "static-analysis",
49
+ "linter",
50
+ "security",
51
+ "sast",
52
+ "typescript",
53
+ "javascript",
54
+ "sarif",
55
+ "cli"
56
+ ],
57
+ "dependencies": {
58
+ "commander": "^12.1.0",
59
+ "picocolors": "^1.1.1",
60
+ "typescript": "^5.6.3"
61
+ },
62
+ "devDependencies": {
63
+ "@types/node": "^20.17.6",
64
+ "@vitest/coverage-v8": "^2.1.5",
65
+ "eslint": "^9.14.0",
66
+ "tsup": "^8.3.5",
67
+ "typescript-eslint": "^8.14.0",
68
+ "vitest": "^2.1.5"
69
+ }
70
+ }