codeveto 0.1.0__py3-none-any.whl

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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/js.py ADDED
@@ -0,0 +1,768 @@
1
+ """JavaScript and TypeScript pack (SPEC 6.1): language bug patterns.
2
+
3
+ Runs on ``javascript`` and ``typescript`` files: ``.js``/``.mjs``/``.cjs``/
4
+ ``.jsx``, ``.ts``/``.mts``/``.cts``/``.tsx`` and the ``<script>`` blocks of
5
+ ``.vue`` and ``.svelte`` files (``masked_code`` blanks their templates). Every
6
+ code pattern runs on ``masked_code`` or ``statements()``, so strings, template
7
+ literal text, regex literals and comments never match; only interpolation
8
+ code inside template literals stays visible. JSX text between tags is not
9
+ masked by the lexer, so patterns that could appear in prose (``debugger``)
10
+ also check their statement shape.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ import re
17
+ from collections.abc import Iterator
18
+
19
+ from codeveto.languages import shebang_language
20
+ from codeveto.model import git_lines
21
+ from codeveto.rules.base import FileContext, Hit, LineText, line_windows, rule
22
+
23
+ _JS = frozenset({"javascript", "typescript"})
24
+ _SOURCE = frozenset({"source", "agent-config"})
25
+ """Non-test classes a JavaScript file can have that the pack runs on."""
26
+
27
+ _SCAN_LIMIT = 20_000
28
+ """Most characters a bracket scan walks forward from one match."""
29
+
30
+
31
+ def _masked_lines(ctx: FileContext) -> tuple[str, ...]:
32
+ return git_lines(ctx.masked_code)
33
+
34
+
35
+ def _changed_masked(ctx: FileContext) -> Iterator[tuple[int, LineText]]:
36
+ """``(number, masked text)`` of each changed line, long lines as windows."""
37
+ lines = _masked_lines(ctx)
38
+ for number in sorted(ctx.added_lines):
39
+ if number <= len(lines):
40
+ for window in line_windows(lines[number - 1]):
41
+ yield number, window
42
+
43
+
44
+ def _position(ctx: FileContext, offset: int) -> tuple[int, int]:
45
+ return ctx.line_index.position(offset)
46
+
47
+
48
+ def _matching(masked: str, open_at: int, opener: str, closer: str) -> int | None:
49
+ """Offset of the bracket closing ``masked[open_at]``, within :data:`_SCAN_LIMIT`."""
50
+ depth = 0
51
+ stop = min(len(masked), open_at + _SCAN_LIMIT)
52
+ for i in range(open_at, stop):
53
+ c = masked[i]
54
+ if c == opener:
55
+ depth += 1
56
+ elif c == closer:
57
+ depth -= 1
58
+ if depth == 0:
59
+ return i
60
+ return None
61
+
62
+
63
+ def _skip_ws(masked: str, i: int) -> int:
64
+ stop = min(len(masked), i + _SCAN_LIMIT)
65
+ while i < stop and masked[i] in " \t\r\n\f\v":
66
+ i += 1
67
+ return i
68
+
69
+
70
+ # --- debugger ---------------------------------------------------------------------
71
+
72
+ _DEBUGGER = re.compile(r"(?<![\w$.])debugger(?![\w$])")
73
+ _DEBUGGER_BEFORE = re.compile(r"(?:^|[);:{}]|(?<![\w$])(?:else|do))$")
74
+
75
+
76
+ @rule(
77
+ id="js/debugger",
78
+ severity="error",
79
+ title="debugger statement",
80
+ languages=_JS,
81
+ classes=_SOURCE,
82
+ scope="line",
83
+ rationale=(
84
+ "A debugger statement pauses execution whenever developer tools are open and is "
85
+ "almost always a leftover from a debugging session."
86
+ ),
87
+ hint="Remove the debugger statement.",
88
+ tags={"js", "hygiene"},
89
+ )
90
+ def debugger(ctx: FileContext) -> Iterator[Hit]:
91
+ """A ``debugger`` statement in code of a non-test file.
92
+
93
+ The keyword must stand as a statement: alone (optionally with ``;``), or
94
+ after an ``if``/``while`` header, ``else``, ``do`` or a label. So a
95
+ property (``opts.debugger``), an object key (``{ debugger: true }``), the
96
+ word in a string, comment, regex literal or JSX text, and test files
97
+ (class ``test``) are not hits.
98
+ """
99
+ if not ctx.added_lines:
100
+ return
101
+ for st in ctx.statements():
102
+ masked = st.masked
103
+ for match in _DEBUGGER.finditer(masked):
104
+ after = masked[match.end() :].strip().lstrip(";").strip(" \t\r\n/*")
105
+ if after:
106
+ continue
107
+ before = masked[: match.start()].rstrip()
108
+ if not _DEBUGGER_BEFORE.search(before[-8:] if before else ""):
109
+ continue
110
+ line, column = _position(ctx, st.start + match.start())
111
+ yield Hit(line, column=column, evidence="debugger")
112
+
113
+
114
+ # --- public-env-secret --------------------------------------------------------------
115
+
116
+ _PUBLIC_NAME = re.compile(
117
+ r"(?<![\w$])((?:NEXT_PUBLIC|NUXT_PUBLIC|EXPO_PUBLIC|REACT_APP|VITE|GATSBY|PUBLIC)_"
118
+ r"([A-Z0-9_]{1,200}))(?![\w$])"
119
+ )
120
+ _STRONG = re.compile(r"SECRET|PRIVATE|PASSWORD|PASSWD|SERVICE_ROLE")
121
+ _SAFE = re.compile(r"PUBLISHABLE|ANON|PUBLIC|SITE_?KEY|DSN")
122
+ _CREDENTIAL_TAILS = frozenset(
123
+ {
124
+ "KEY",
125
+ "SECRET",
126
+ "TOKEN",
127
+ "PASSWORD",
128
+ "PASSWD",
129
+ "PASS",
130
+ "PWD",
131
+ "ROLE",
132
+ "CREDENTIAL",
133
+ "CREDENTIALS",
134
+ "JWT",
135
+ "SIGNATURE",
136
+ "CERT",
137
+ "PEM",
138
+ }
139
+ )
140
+ _CREDENTIAL_ENDINGS = ("KEY", "SECRET", "TOKEN", "PASSWORD")
141
+ _VERSION = re.compile(r"V?[0-9]{1,6}")
142
+ _ENV_LINE = re.compile(r"\s{0,64}(?:export\s{1,16})?([A-Z][A-Z0-9_]{0,250})\s{0,16}=")
143
+ _ENV_STRING = re.compile(r"(?:^|\benv\.)([A-Z][A-Z0-9_]{0,250})$")
144
+ _MEMBER_BEFORE = re.compile(r"[\w$)\]]\s{0,16}(?:\?\.)?\s{0,16}\[\s{0,16}$")
145
+
146
+
147
+ def public_name_severity(name: str) -> str | None:
148
+ """``"error"``, ``"warning"`` or ``None`` for a browser-exposed variable ``name``.
149
+
150
+ The prefix (``NEXT_PUBLIC_``, ``VITE_``, ...) is cut off first, so the
151
+ ``PUBLIC`` in it does not count as a safe word. A rest with a safe word
152
+ (PUBLISHABLE, ANON, PUBLIC, SITE_KEY, DSN) is public by design: ``None``.
153
+ Otherwise the name must end in a credential word (KEY, SECRET, TOKEN,
154
+ PASSWORD, ...; a trailing version segment such as ``_V2`` is skipped) to
155
+ count at all, so ``NEXT_PUBLIC_PASSWORD_RESET_URL`` and
156
+ ``VITE_PRIVATE_BETA_ENABLED`` are not reported. Such a name is an
157
+ ``error`` when it also contains a strong word (SECRET, PRIVATE, PASSWORD,
158
+ PASSWD, SERVICE_ROLE), else a ``warning`` (``NEXT_PUBLIC_API_KEY``).
159
+ """
160
+ match = _PUBLIC_NAME.fullmatch(name)
161
+ if match is None:
162
+ return None
163
+ rest = match.group(2)
164
+ if _SAFE.search(rest):
165
+ return None
166
+ segments = [s for s in rest.split("_") if s]
167
+ while segments and _VERSION.fullmatch(segments[-1]):
168
+ segments.pop()
169
+ if not segments:
170
+ return None
171
+ last = segments[-1]
172
+ if last not in _CREDENTIAL_TAILS and not last.endswith(_CREDENTIAL_ENDINGS):
173
+ return None
174
+ return "error" if _STRONG.search(rest) else "warning"
175
+
176
+
177
+ def _is_env_file(path: str) -> bool:
178
+ name = path.rsplit("/", 1)[-1]
179
+ return name == ".env" or name.startswith(".env.")
180
+
181
+
182
+ def _env_file_hits(ctx: FileContext) -> Iterator[Hit]:
183
+ for number, text in ctx.changed_lines():
184
+ if not text.at_line_start:
185
+ continue
186
+ match = _ENV_LINE.match(text)
187
+ if match is None:
188
+ continue
189
+ hit = _env_hit(number, text.column(match.start(1)), match.group(1))
190
+ if hit is not None:
191
+ yield hit
192
+
193
+
194
+ def _env_hit(line: int, column: int, name: str) -> Hit | None:
195
+ severity = public_name_severity(name)
196
+ if severity is None:
197
+ return None
198
+ if severity == "error":
199
+ return Hit(
200
+ line,
201
+ column=column,
202
+ evidence=name,
203
+ message=f"{name} is exposed to the browser but named like a secret",
204
+ )
205
+ return Hit(
206
+ line,
207
+ column=column,
208
+ evidence=name,
209
+ message=f"{name} is exposed to the browser and named like a credential",
210
+ severity="warning",
211
+ )
212
+
213
+
214
+ @rule(
215
+ id="js/public-env-secret",
216
+ severity="error",
217
+ title="Secret in a browser-exposed environment variable",
218
+ languages={"javascript", "typescript", "text"},
219
+ classes={"source", "agent-config", "text"},
220
+ scope="line",
221
+ rationale=(
222
+ "Bundlers inline variables with a public prefix (NEXT_PUBLIC_, VITE_, PUBLIC_, "
223
+ "REACT_APP_, EXPO_PUBLIC_, NUXT_PUBLIC_, GATSBY_) into the client bundle, so a "
224
+ "secret, private key, password or service-role key named that way ships to every "
225
+ "visitor. A name that clearly holds a secret is an error; one that only ends like "
226
+ "a credential (API_KEY, TOKEN) is a warning, since some such keys are meant to be "
227
+ "public; publishable, anon and site keys and DSNs are designed to be public and "
228
+ "not reported."
229
+ ),
230
+ hint=(
231
+ "Rename the variable without the public prefix and read it only in server code; "
232
+ "rotate the secret if it was ever deployed."
233
+ ),
234
+ tags={"js", "security", "secrets"},
235
+ )
236
+ def public_env_secret(ctx: FileContext) -> Iterator[Hit]:
237
+ """A public-prefixed variable with a secret's or credential's name, read or defined.
238
+
239
+ Severity per hit comes from :func:`public_name_severity`: ``error`` for a
240
+ secret's name, ``warning`` for a name that only ends in a credential word.
241
+
242
+ In JavaScript and TypeScript: any such name in code (``process.env.X``,
243
+ ``import.meta.env.X``, destructuring from ``process.env``, imports from
244
+ ``$env/static/public``, keys of ``env``/``define`` blocks in framework
245
+ configs), a string ``"X"`` used as an index (``env["X"]``) or as an object
246
+ key, and a ``define`` key string ending in ``env.X``. In ``.env`` and
247
+ ``.env.*`` files: a ``X=`` definition. Mentions in comments and in other
248
+ strings (error messages, lists of forbidden names) are not hits.
249
+ """
250
+ if not ctx.added_lines:
251
+ return
252
+ if ctx.language == "text":
253
+ if _is_env_file(ctx.path):
254
+ yield from _env_file_hits(ctx)
255
+ return
256
+ for number, text in _changed_masked(ctx):
257
+ for match in _PUBLIC_NAME.finditer(text):
258
+ hit = _env_hit(number, text.column(match.start(1)), match.group(1))
259
+ if hit is not None:
260
+ yield hit
261
+ source = ctx.new_text or ""
262
+ masked = ctx.masked_code
263
+ added = ctx.added_lines
264
+ for span in ctx.strings():
265
+ if span.interpolations or span.content_end - span.content_start > 300:
266
+ continue
267
+ line, column = _position(ctx, span.content_start)
268
+ if line not in added:
269
+ continue
270
+ match = _ENV_STRING.search(source[span.content_start : span.content_end])
271
+ if match is None or public_name_severity(match.group(1)) is None:
272
+ continue
273
+ if match.start(1) == 0:
274
+ before = masked[max(0, span.start - 64) : span.start]
275
+ after = masked[span.end : span.end + 16].lstrip()
276
+ if not (_MEMBER_BEFORE.search(before) or after.startswith(":")):
277
+ continue
278
+ hit = _env_hit(line, column + match.start(1), match.group(1))
279
+ if hit is not None:
280
+ yield hit
281
+
282
+
283
+ # --- empty-catch ----------------------------------------------------------------------
284
+
285
+ _CATCH = re.compile(r"(?<![\w$.])catch(?![\w$])")
286
+
287
+
288
+ @rule(
289
+ id="js/empty-catch",
290
+ severity="warning",
291
+ title="Empty catch block",
292
+ languages=_JS,
293
+ scope="line",
294
+ rationale=(
295
+ "An empty catch block swallows every error, including ones nobody anticipated, "
296
+ "so failures disappear without a trace."
297
+ ),
298
+ hint=(
299
+ "Handle or log the error, rethrow it, or leave a comment saying why ignoring it is safe."
300
+ ),
301
+ tags={"js", "error-handling"},
302
+ )
303
+ def empty_catch(ctx: FileContext) -> Iterator[Hit]:
304
+ """``catch (e) {}`` or ``catch {}`` with nothing but whitespace in the block.
305
+
306
+ A block holding a comment documents an intentional ignore and is not a
307
+ hit, nor is a promise's ``.catch(() => {})``. Reported from ``catch`` to
308
+ the closing brace, so a change to any of those lines counts, a removed
309
+ block body included (reported at its deletion point).
310
+ """
311
+ if not ctx.added_lines and not ctx.deletion_points:
312
+ return
313
+ masked = ctx.masked_code
314
+ index = ctx.line_index
315
+ for number, line in enumerate(_masked_lines(ctx), start=1):
316
+ if "catch" not in line:
317
+ continue
318
+ base = index.line_start(number)
319
+ for match in _CATCH.finditer(line):
320
+ i = _skip_ws(masked, base + match.end())
321
+ if i < len(masked) and masked[i] == "(":
322
+ close = _matching(masked, i, "(", ")")
323
+ if close is None:
324
+ continue
325
+ i = _skip_ws(masked, close + 1)
326
+ if i >= len(masked) or masked[i] != "{":
327
+ continue
328
+ j = _skip_ws(masked, i + 1)
329
+ if j >= len(masked) or masked[j] != "}":
330
+ continue
331
+ yield Hit(
332
+ number,
333
+ end_line=index.line_of(j),
334
+ column=match.start() + 1,
335
+ evidence="catch {}",
336
+ )
337
+
338
+
339
+ # --- console-log ----------------------------------------------------------------------
340
+
341
+ _CONSOLE = re.compile(r"(?<![\w$])console\s{0,16}\.\s{0,16}(log|debug|trace)\s{0,16}\(")
342
+
343
+
344
+ def _cli_file(ctx: FileContext) -> bool:
345
+ segments = ctx.path.split("/")[:-1]
346
+ if "scripts" in segments or "bin" in segments:
347
+ return True
348
+ lines = ctx.lines
349
+ return bool(lines) and shebang_language(lines[0]) in _JS
350
+
351
+
352
+ @rule(
353
+ id="js/console-log",
354
+ severity="warning",
355
+ title="console.log left in source",
356
+ languages=_JS,
357
+ classes=_SOURCE,
358
+ scope="line",
359
+ rationale=(
360
+ "console.log, console.debug and console.trace in application code are usually "
361
+ "debugging leftovers that clutter output and can leak data into browser consoles "
362
+ "or logs."
363
+ ),
364
+ hint="Remove the call or use the project's logger; console.error and console.warn are fine.",
365
+ tags={"js", "hygiene"},
366
+ )
367
+ def console_log(ctx: FileContext) -> Iterator[Hit]:
368
+ """``console.log``/``console.debug``/``console.trace`` calls in non-test source.
369
+
370
+ ``console.error``, ``console.warn`` and ``console.info`` are deliberate
371
+ output and not hits. Exempt: test files (class ``test``), files under a
372
+ ``scripts/`` or ``bin/`` directory and files with a ``node`` (or ``bun``,
373
+ ``deno``, ``tsx``) shebang, where printing is the job.
374
+ """
375
+ if not ctx.added_lines or _cli_file(ctx):
376
+ return
377
+ for number, text in _changed_masked(ctx):
378
+ for match in _CONSOLE.finditer(text):
379
+ method = match.group(1)
380
+ yield Hit(
381
+ number,
382
+ column=text.column(match.start()),
383
+ evidence=f"console.{method}",
384
+ message=f"console.{method} left in source",
385
+ )
386
+
387
+
388
+ # --- ts-ignore ----------------------------------------------------------------------
389
+
390
+ _TS_DIRECTIVE = re.compile(r"[\s*/]{0,64}@(ts-ignore|ts-nocheck|ts-expect-error)(?![\w-])")
391
+
392
+
393
+ @rule(
394
+ id="js/ts-ignore",
395
+ severity="warning",
396
+ title="TypeScript check suppressed",
397
+ languages=_JS,
398
+ scope="line",
399
+ rationale=(
400
+ "@ts-ignore and @ts-nocheck silence type errors without saying which, and keep "
401
+ "silencing them after the code changes. @ts-expect-error fails once the error is "
402
+ "gone, so with a reason it is the accepted way to suppress one."
403
+ ),
404
+ hint="Fix the type error, or use @ts-expect-error followed by the reason.",
405
+ tags={"js", "typescript", "suppression"},
406
+ )
407
+ def ts_ignore(ctx: FileContext) -> Iterator[Hit]:
408
+ """``@ts-ignore`` or ``@ts-nocheck`` at the start of a comment.
409
+
410
+ A bare ``@ts-expect-error`` with no description is reported too; one
411
+ followed by any text is fine. The directive elsewhere in a comment (prose
412
+ about it) or in a string is not a hit. Runs on JavaScript as well, which
413
+ TypeScript checks with ``checkJs``.
414
+ """
415
+ added = ctx.added_lines
416
+ if not added:
417
+ return
418
+ source = ctx.new_text or ""
419
+ for comment in ctx.comments():
420
+ content = source[comment.content_start : comment.content_end]
421
+ match = _TS_DIRECTIVE.match(content)
422
+ if match is None:
423
+ continue
424
+ line, column = _position(ctx, comment.content_start + match.start(1) - 1)
425
+ if line not in added:
426
+ continue
427
+ directive = match.group(1)
428
+ if directive == "ts-expect-error":
429
+ if content[match.end() :].strip(" \t\r\n*/:-"):
430
+ continue
431
+ message = "@ts-expect-error without a description"
432
+ else:
433
+ message = f"@{directive} suppresses type checking"
434
+ yield Hit(line, column=column, evidence=f"@{directive}", message=message)
435
+
436
+
437
+ # --- loose-equality -------------------------------------------------------------------
438
+
439
+ _LOOSE = re.compile(r"(?<![=!])(==|!=)(?!=)")
440
+ _NULL_AFTER = re.compile(r"\s{0,16}null(?![\w$])")
441
+ _NULL_BEFORE = re.compile(r"(?<![\w$.])null\s{0,16}$")
442
+ _TYPEOF_AFTER = re.compile(r"\s{0,16}typeof(?![\w$])")
443
+ _TYPEOF_BEFORE = re.compile(r"(?<![\w$.])typeof\s{1,16}[\w$.]{1,200}\s{0,16}$")
444
+ _LEFT = re.compile(r"[^\s(]{1,60}\s{0,16}$")
445
+ _RIGHT = re.compile(r"\s{0,16}[^\s)]{1,60}")
446
+
447
+
448
+ @rule(
449
+ id="js/loose-equality",
450
+ severity="warning",
451
+ title="Loose equality (== or !=)",
452
+ languages=_JS,
453
+ scope="line",
454
+ rationale=(
455
+ "== and != convert types before comparing ('' == 0, '1' == 1, [] == false), "
456
+ "which hides bugs; === and !== compare without conversion."
457
+ ),
458
+ hint="Use === or !==; x == null is fine for 'null or undefined'.",
459
+ tags={"js", "correctness"},
460
+ )
461
+ def loose_equality(ctx: FileContext) -> Iterator[Hit]:
462
+ """``==`` or ``!=`` in code.
463
+
464
+ Not hits: a comparison with ``null`` on either side (the idiom for "null
465
+ or undefined") and one with a ``typeof`` operand, which always yields a
466
+ string (ESLint's ``eqeqeq: smart``). Operators in strings, regex literals
467
+ and comments are masked.
468
+ """
469
+ for number, text in _changed_masked(ctx):
470
+ for match in _LOOSE.finditer(text):
471
+ before = text[: match.start()]
472
+ after = text[match.end() :]
473
+ if _NULL_AFTER.match(after) or _NULL_BEFORE.search(before):
474
+ continue
475
+ if _TYPEOF_AFTER.match(after) or _TYPEOF_BEFORE.search(before[-240:]):
476
+ continue
477
+ left = _LEFT.search(before[-80:])
478
+ right = _RIGHT.match(after)
479
+ evidence = " ".join(
480
+ part
481
+ for part in (
482
+ left.group().strip() if left else "",
483
+ match.group(1),
484
+ right.group().strip() if right else "",
485
+ )
486
+ if part
487
+ )
488
+ yield Hit(
489
+ number,
490
+ column=text.column(match.start()),
491
+ evidence=evidence,
492
+ message=f"Loose equality {match.group(1)}",
493
+ )
494
+
495
+
496
+ # --- async-foreach ------------------------------------------------------------------
497
+
498
+ _ASYNC_FOREACH = re.compile(r"\.\s{0,16}forEach\s{0,16}\(\s{0,64}async(?![\w$])")
499
+
500
+
501
+ @rule(
502
+ id="js/async-foreach",
503
+ severity="warning",
504
+ title="async callback passed to forEach",
505
+ languages=_JS,
506
+ scope="line",
507
+ rationale=(
508
+ "forEach ignores the promises an async callback returns: the loop does not wait "
509
+ "for them, the code after it runs too early, and their rejections go unhandled."
510
+ ),
511
+ hint="Use for...of with await, or await Promise.all(items.map(async ...)).",
512
+ tags={"js", "async", "correctness"},
513
+ )
514
+ def async_foreach(ctx: FileContext) -> Iterator[Hit]:
515
+ """``.forEach(async ...)``, the callback possibly on the next line."""
516
+ if not ctx.added_lines:
517
+ return
518
+ for st in ctx.statements():
519
+ for match in _ASYNC_FOREACH.finditer(st.masked):
520
+ line, column = _position(ctx, st.start + match.start())
521
+ yield Hit(line, column=column, evidence="forEach(async")
522
+
523
+
524
+ # --- react-index-key ----------------------------------------------------------------
525
+
526
+ _MAP_CALL = re.compile(r"\.\s{0,16}map\s{0,16}\(")
527
+ _IDENT = re.compile(r"[A-Za-z_$][\w$]{0,100}")
528
+ _WORD_CHAR = re.compile(r"[\w$]")
529
+
530
+
531
+ def _index_param(masked: str, i: int) -> str | None:
532
+ """Name of the second parameter of the callback starting at ``masked[i]``."""
533
+ i = _skip_ws(masked, i)
534
+ for word in ("async", "function"):
535
+ nxt = masked[i + len(word) : i + len(word) + 1]
536
+ if masked.startswith(word, i) and not _WORD_CHAR.match(nxt):
537
+ i = _skip_ws(masked, i + len(word))
538
+ if i >= len(masked) or masked[i] != "(":
539
+ return None
540
+ close = _matching(masked, i, "(", ")")
541
+ if close is None or close - i > 400:
542
+ return None
543
+ params: list[str] = []
544
+ depth = 0
545
+ current: list[str] = []
546
+ for c in masked[i + 1 : close]:
547
+ if c in "([{<":
548
+ depth += 1
549
+ elif c in ")]}>":
550
+ depth -= 1
551
+ if c == "," and depth == 0:
552
+ params.append("".join(current))
553
+ current = []
554
+ else:
555
+ current.append(c)
556
+ params.append("".join(current))
557
+ if len(params) < 2:
558
+ return None
559
+ name = params[1].split(":", 1)[0].split("=", 1)[0].strip()
560
+ return name if _IDENT.fullmatch(name) else None
561
+
562
+
563
+ @rule(
564
+ id="js/react-index-key",
565
+ severity="warning",
566
+ title="React key from the array index",
567
+ languages=_JS,
568
+ scope="line",
569
+ rationale=(
570
+ "A key built from the map callback's index changes when items are inserted, "
571
+ "removed or reordered, so React reuses the wrong component state and DOM nodes."
572
+ ),
573
+ hint="Key each element by a stable ID from the data.",
574
+ tags={"js", "react", "correctness"},
575
+ )
576
+ def react_index_key(ctx: FileContext) -> Iterator[Hit]:
577
+ """``key={i}`` where ``i`` is the index parameter of the enclosing ``.map`` callback.
578
+
579
+ Also ``key={String(i)}``, ``key={i.toString()}`` and template keys whose
580
+ only interpolation is the index (```key={`row-${i}`}```). A key from the
581
+ data (``key={item.id}``) or from a variable that is not the callback's
582
+ index is not a hit. Vue and Svelte templates are not scanned.
583
+ """
584
+ if not ctx.added_lines:
585
+ return
586
+ masked = ctx.masked_code
587
+ index = ctx.line_index
588
+ for number, line in enumerate(_masked_lines(ctx), start=1):
589
+ if "map" not in line:
590
+ continue
591
+ base = index.line_start(number)
592
+ for match in _MAP_CALL.finditer(line):
593
+ open_at = base + match.end() - 1
594
+ name = _index_param(masked, open_at + 1)
595
+ if name is None:
596
+ continue
597
+ close = _matching(masked, open_at, "(", ")")
598
+ end = close if close is not None else min(len(masked), open_at + _SCAN_LIMIT)
599
+ n = re.escape(name)
600
+ key = re.compile(
601
+ r"(?<![\w$])key\s{0,16}=\s{0,16}\{\s{0,16}(?:"
602
+ rf"{n}|String\(\s{{0,16}}{n}\s{{0,16}}\)|{n}\.toString\(\s{{0,16}}\)"
603
+ rf"|`\s{{0,200}}{n}\s{{0,16}}`)"
604
+ r"\s{0,16}\}"
605
+ )
606
+ for found in key.finditer(masked, open_at, end):
607
+ key_line, column = index.position(found.start())
608
+ yield Hit(key_line, column=column, evidence=f"key={{{name}}}")
609
+
610
+
611
+ # --- async-use-effect ---------------------------------------------------------------
612
+
613
+ _ASYNC_EFFECT = re.compile(r"(?<![\w$])useEffect\s{0,16}\(\s{0,64}async(?![\w$])")
614
+
615
+
616
+ @rule(
617
+ id="js/async-use-effect",
618
+ severity="warning",
619
+ title="async function passed to useEffect",
620
+ languages=_JS,
621
+ scope="line",
622
+ rationale=(
623
+ "useEffect expects its callback to return nothing or a cleanup function; an async "
624
+ "callback returns a promise, so cleanup never runs and React warns."
625
+ ),
626
+ hint="Define an async function inside the effect and call it.",
627
+ tags={"js", "react", "correctness"},
628
+ )
629
+ def async_use_effect(ctx: FileContext) -> Iterator[Hit]:
630
+ """``useEffect(async () => ...)`` or ``React.useEffect(async function ...)``."""
631
+ if not ctx.added_lines:
632
+ return
633
+ for st in ctx.statements():
634
+ for match in _ASYNC_EFFECT.finditer(st.masked):
635
+ line, column = _position(ctx, st.start + match.start())
636
+ yield Hit(line, column=column, evidence="useEffect(async")
637
+
638
+
639
+ # --- explicit-any -------------------------------------------------------------------
640
+
641
+ _ANY = re.compile(r"(?<![\w$.])any(?![\w$])")
642
+ _ANY_BEFORE = re.compile(
643
+ r"(?:[:<|&]|(?<![\w$])(?:as|extends|keyof|readonly)|^\s{0,64}(?:export\s{1,16})?type\s{1,16}"
644
+ r"[\w$]{1,100}(?:<[^>]{0,200}>)?\s{0,16}=)\s{0,16}$"
645
+ )
646
+ _ANY_GENERIC_ARG = re.compile(r",\s{0,16}$")
647
+ _DECLARATION_FILES = (".d.ts", ".d.mts", ".d.cts")
648
+ _ANY_AFTER_GENERIC = re.compile(r"\s{0,16}(?:\[\s{0,16}\])*\s{0,16}[>,]")
649
+ _ANY_ARRAY = re.compile(r"\s{0,16}\[\s{0,16}\]")
650
+
651
+
652
+ @rule(
653
+ id="js/explicit-any",
654
+ severity="note",
655
+ title="Explicit any type",
656
+ languages={"typescript"},
657
+ scope="line",
658
+ rationale=(
659
+ "any turns type checking off for the value and everything derived from it; "
660
+ "unknown or a real type keeps the checker useful. Declaration files (.d.ts) are not "
661
+ "checked: they describe untyped JavaScript, where any is often the honest type, and "
662
+ "held half of the hits in node_modules."
663
+ ),
664
+ hint="Use a specific type, a generic, or unknown with a type guard.",
665
+ tags={"js", "typescript", "types"},
666
+ )
667
+ def explicit_any(ctx: FileContext) -> Iterator[Hit]:
668
+ """``any`` in a type position of TypeScript code.
669
+
670
+ Type positions: after ``:``, ``<``, ``|``, ``&``, ``as``, ``extends``,
671
+ ``keyof``, ``readonly``, ``type X =``, before ``[]``, and as a later
672
+ generic argument (``Record<string, any>``). A variable or property named
673
+ ``any`` (``items.any``, ``any(xs)``) is not a hit, and declaration files
674
+ (``.d.ts``, ``.d.mts``, ``.d.cts``) are not checked.
675
+ """
676
+ if ctx.path.endswith(_DECLARATION_FILES):
677
+ return
678
+ for number, text in _changed_masked(ctx):
679
+ for match in _ANY.finditer(text):
680
+ before = text[max(0, match.start() - 320) : match.start()]
681
+ after = text[match.end() : match.end() + 64]
682
+ if not (
683
+ _ANY_BEFORE.search(before)
684
+ or _ANY_ARRAY.match(after)
685
+ or (_ANY_GENERIC_ARG.search(before) and _ANY_AFTER_GENERIC.match(after))
686
+ ):
687
+ continue
688
+ yield Hit(number, column=text.column(match.start()), evidence="any")
689
+
690
+
691
+ # --- var-declaration ----------------------------------------------------------------
692
+
693
+ _VAR = re.compile(r"(?<![\w$.])var\s{1,16}[\w$\[{]")
694
+ _BLOCK_SCOPED = re.compile(r"(?<![\w$.])(?:let|const)\s{1,16}[\w$\[{]")
695
+ _VAR_LINES = 10
696
+ """More changed var lines than this in one file are a style (often compiled output): one note."""
697
+ _DECLARE = re.compile(r"(?<![\w$.])declare(?![\w$])")
698
+
699
+
700
+ def _declare_lines(ctx: FileContext) -> frozenset[int]:
701
+ """Lines of statements inside ``declare global { ... }`` and ``declare module`` blocks."""
702
+ inside: set[int] = set()
703
+ stack: list[bool] = []
704
+ for st in ctx.statements():
705
+ text = st.masked.strip()
706
+ ambient = bool(stack) and stack[-1]
707
+ if ambient:
708
+ inside.update(range(st.start_line, st.end_line + 1))
709
+ opened = text.count("{") - text.count("}")
710
+ if text.startswith("}"):
711
+ if stack:
712
+ stack.pop()
713
+ opened += 1
714
+ if text.endswith("{") and opened > 0:
715
+ stack.append(ambient or bool(_DECLARE.search(text)))
716
+ return frozenset(inside)
717
+
718
+
719
+ @rule(
720
+ id="js/var-declaration",
721
+ severity="note",
722
+ title="var declaration",
723
+ languages=_JS,
724
+ scope="line",
725
+ rationale=(
726
+ "var is function-scoped and hoisted, so it leaks out of blocks and loops; let and "
727
+ "const are block-scoped and catch use before declaration. A file that declares "
728
+ "nothing with let or const (ES5 style), or adds var on more than ten lines (often "
729
+ "compiled output), is reported once, not on every line: 11 per 1,000 lines of "
730
+ "node_modules were such files."
731
+ ),
732
+ hint="Use const, or let when the variable is reassigned.",
733
+ tags={"js", "style"},
734
+ )
735
+ def var_declaration(ctx: FileContext) -> Iterator[Hit]:
736
+ """A ``var`` declaration in code.
737
+
738
+ Ambient declarations are not hits: ``declare var``, ``var`` inside
739
+ ``declare global { ... }`` or ``declare module`` blocks, and ``.d.ts``
740
+ files, where ``var`` is the only way to declare a global. In a file
741
+ without any ``let`` or ``const`` declaration, or when more than
742
+ :data:`_VAR_LINES` changed lines declare with ``var``, only the first one
743
+ is reported, with the count of the others.
744
+ """
745
+ if not ctx.added_lines or ctx.path.endswith(_DECLARATION_FILES):
746
+ return
747
+ ambient: frozenset[int] | None = None
748
+ hits: dict[int, Hit] = {}
749
+ for number, text in _changed_masked(ctx):
750
+ for match in _VAR.finditer(text):
751
+ if number in hits or _DECLARE.search(text[: match.start()]):
752
+ continue
753
+ if ambient is None:
754
+ ambient = _declare_lines(ctx)
755
+ if number in ambient:
756
+ continue
757
+ hits[number] = Hit(number, column=text.column(match.start()), evidence="var")
758
+ if not hits:
759
+ return
760
+ modern = any(_BLOCK_SCOPED.search(line) for line in _masked_lines(ctx))
761
+ if modern and len(hits) <= _VAR_LINES:
762
+ yield from hits.values()
763
+ return
764
+ first, more = hits[min(hits)], len(hits) - 1
765
+ message = "var declarations" + ("" if modern else " in a file without let or const")
766
+ if more:
767
+ message += f" ({more} more changed line{'s' if more > 1 else ''})"
768
+ yield dataclasses.replace(first, message=message)