loadwise 0.6.2 → 0.8.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.
Files changed (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -3,102 +3,167 @@ import { packageManifest } from '../lib/shared/package-root.js';
3
3
  import { terminalSafe } from '../lib/shared/system/terminal-safe.js';
4
4
  const { version } = packageManifest;
5
5
  import { respawnWithLargerHeap, shouldRespawnWithLargerHeap } from '../lib/shared/system/heap-limit.js';
6
- const usage = `Usage:
7
- loadwise [check] [directory] [--only perf,rel,maint,sec,a11y | --skip perf,rel,maint,sec,a11y] [--json | --format text|json|sarif|github] [--include-contextual] [--staged | --changed-since git-ref] [--fail-on contract|all] [--min-impact low|medium|high|critical] [--config loadwise.config.json] [--ignore rule-id] [--workspace name|path ...] [--online] [--baseline [file] | --write-baseline [file]]
8
- loadwise perf [args...]
9
- loadwise rel [args...]
10
- loadwise maint [args...]
11
- loadwise sec [args...]
12
- loadwise a11y [args...]
13
- loadwise fix --yes [--json]
14
- loadwise fix --all [performance] [reliability] [maintainability] [security] [accessibility] [--json]
15
- loadwise fix --handoff [performance] [reliability] [maintainability] [security] [accessibility]
16
- loadwise explain <rule-id>
17
- loadwise lsp [--stdio]
18
- loadwise --version
19
- loadwise agent init [--mode ask|auto] [--hook [block|warn|off]]
20
- loadwise agent instructions
21
- loadwise agent mcp [directory] [--print-config]
22
- loadwise agent pending
23
- loadwise agent history [performance] [reliability] [maintainability] [security] [accessibility]
24
- loadwise agent verify [--save] [--checker perf|rel|maint|sec|a11y] --outcomes outcomes.json report.json [more-reports.json ...]
6
+ const crashReportOption = '--report-crashes';
7
+ const usage = `Usage: loadwise [command] [options]
25
8
 
26
- check, the default command, runs every checker (perf: performance, rel: reliability, maint: maintainability, sec: security, a11y: accessibility) on one directory (default: the current folder) and prints one titled report per checker, in that order. The accessibility checker reads JSX, HTML, Vue, Svelte and Angular templates and skips itself on a project without any.
27
- --only runs just the listed checkers and --skip runs all but them; both take a comma-separated list, and they cannot be combined.
28
- loadwise.config.json in the directory (or --config <file>) sets the default checkers, ignored paths, per-rule levels (off, warn, error) and each checker's policy; flags beat it. --ignore drops a rule's findings and can repeat.
29
- The performance, reliability and security checkers use the directory's tsconfig.json or jsconfig.json; in a monorepo root without one it checks every workspace package's config in one report (--workspace limits the checkers to named packages or folders); standalone JavaScript-only packages can use check and fix without a source config.
30
- --json prints one key per selected checker, { "performance": report, "reliability": report, "maintainability": report, "security": report, "accessibility": report }; a skipped or failed checker's report is null.
31
- --online adds the security checker's dependency vulnerability check, which sends package names and versions from the lockfile to the OSV database; without it the check is skipped with a note.
32
- --format sarif prints SARIF 2.1.0 with one run per checker for GitHub code scanning; --format github prints workflow annotations (::warning, ::error); --json is --format json.
33
- --include-contextual, --staged, --changed-since, --fail-on and --min-impact apply to every selected checker; without --fail-on each keeps its own default.
34
- --write-baseline records every selected checker's current findings in one file (default loadwise-baseline.json in the checked directory, a section per checker); --baseline reports only findings not in it and prints how many were hidden ("baselineHidden" in --json). Fixed findings leave the file on the next --write-baseline.
35
- check never changes source files: apply fixes with the printed \`loadwise perf --fix --only id\`, \`loadwise rel --fix --only id\`, \`loadwise maint --fix --only id\` \`loadwise sec --fix --only id\` and \`loadwise a11y --fix --only id\` commands.
36
- fix --yes applies automatic edits. fix --all also applies edits marked for review. Both accept checker names, for example loadwise fix --all performance security. With no names, both use the project's configured checkers.
37
- fix --json with --yes or --all records the applied hunks and outstanding findings in its output for review.
38
- perf, rel, maint, sec and a11y run one checker with its full command set; \`loadwise perf --help\`, \`loadwise rel --help\`, \`loadwise maint --help\` \`loadwise sec --help\` and \`loadwise a11y --help\` list their commands and flags.
39
- explain prints the rule's default impact, description and an illustrative change when available.
40
- lsp runs the language server on stdin and stdout for any editor with a Language Server Protocol client: findings from every checker as diagnostics, with hovers, fixes, dismissals and code lenses.
41
- Recognized coding-agent sessions receive review instructions automatically. agent instructions prints the review workflow. Optional agent init writes it into AGENTS.md and imports it from CLAUDE.md.
42
- An active agent can run check --json directly or use the loadwise_check MCP tool for a fresh offline report.
43
- Add --review to a combined check or bulk fix to keep its original report and print the same handoff for any coding agent. agent pending lists saved handoffs for this project.
44
- agent init --hook installs one git pre-commit hook that runs \`loadwise check --staged\`: block fails the commit on findings, warn only prints them, off removes the hook. --hook alone means warn.
45
- Exit codes: 0 passed, 1 a checker met its exit threshold, 2 invalid input or configuration in any checker.
9
+ Start here
10
+ loadwise check Scan the current project
11
+ loadwise check --uncommitted Scan your local changes
12
+ loadwise fix Preview automatic fixes
13
+ loadwise fix --apply Apply automatic fixes
14
+ loadwise explain <rule-id> Read about a finding's rule
15
+
16
+ Command help
17
+ loadwise check --help Scan scope, filters, and output
18
+ loadwise fix --help Fix selection and review modes
19
+ loadwise agent --help Agent setup, reports, and MCP
20
+ loadwise editor setup Set up editor diagnostics (see editor --help)
21
+ loadwise lsp [--stdio] Start the editor language server
22
+ loadwise report-fp --help Report a false positive
23
+
24
+ Checker help
25
+ loadwise perf --help Performance, databases, traces, and plans
26
+ loadwise rel --help Reliability, migrations, and API contracts
27
+ loadwise maint --help Maintainability and dependency graphs
28
+ loadwise sec --help Security and dependency advisories
29
+ loadwise a11y --help Accessibility
30
+
31
+ Running loadwise without a command runs check.
32
+ Use --version (or -v) for the installed version.
33
+ Prefix a command with ${crashReportOption} to opt in to crash reporting.
46
34
  Documentation: ${packageManifest.homepage}`;
35
+ const checkUsage = `Usage: loadwise check [directory] [options]
36
+
37
+ Scan the current directory or a project directory you supply.
38
+ The scan leaves source files untouched.
39
+
40
+ Examples
41
+ loadwise check
42
+ loadwise check --uncommitted
43
+ loadwise check --only perf,rel
44
+ loadwise check --changed-since origin/main --min-impact high
45
+
46
+ Scope and configuration
47
+ --only <checkers> Run the listed checkers
48
+ --skip <checkers> Run every other checker
49
+ --workspace <name|path> Scope the scan to a workspace (repeatable)
50
+ --uncommitted Check staged, unstaged and untracked changes since HEAD
51
+ --staged Check lines changed in the Git index
52
+ --changed-since <git-ref> Check lines changed since a Git ref
53
+ --config <file> Use a different Loadwise configuration
54
+ --online Query OSV with lockfile package names and versions
55
+
56
+ Reports and thresholds
57
+ --json Output JSON grouped by checker, with _coverage for skipped or partial checks
58
+ --format <text|json|sarif|github> Choose a report format
59
+ --include-contextual Show contextual findings and their reasons
60
+ --ignore <rule-id> Hide findings for a rule (repeatable)
61
+ --min-impact <level> Select low, medium, high, or critical and above
62
+ --fail-on <contract|all> Override each checker's exit threshold
63
+ --baseline [file] Report findings new since the baseline
64
+ --write-baseline [file] Record the current findings
65
+ --review Save the report and print an agent handoff
66
+
67
+ Use either --only or --skip with comma-separated checker names.
68
+ Checkers: perf, rel, maint, sec, a11y. Full names work too.
69
+ The default baseline path is loadwise-baseline.json.
70
+
71
+ Exit codes: 0 passed, 1 findings met the threshold, 2 incomplete scan or invalid input.
72
+ Use loadwise fix --help for fix options.`;
47
73
  // Each command loads only the code it needs, so a quick `--version` or `explain` does not pay for
48
74
  // the scanners.
49
75
  async function main(args) {
50
76
  const [command, ...rest] = args;
51
- if (command === 'perf')
52
- return (await import('../lib/performance/cli.js')).main(rest);
53
- if (command === 'rel')
54
- return (await import('../lib/reliability/cli.js')).main(rest);
55
- if (command === 'maint')
56
- return (await import('../lib/maintainability/cli.js')).main(rest);
57
- if (command === 'sec')
58
- return (await import('../lib/security/cli.js')).main(rest);
59
- if (command === 'a11y')
60
- return (await import('../lib/accessibility/cli.js')).main(rest);
61
- if (command === 'fix')
62
- return (await import('../lib/shared/fix.js')).runFix(rest);
63
- if (command === 'explain')
64
- return (await import('../lib/shared/explain.js')).runExplain(rest);
65
- if (command === 'lsp')
66
- return (await import('../lib/editor/language-server.js')).runLanguageServer(rest);
67
77
  if (command === '--version' || command === '-v') {
68
78
  if (rest.length)
69
79
  throw new Error('Usage: loadwise --version');
70
80
  console.log(version);
71
81
  return 0;
72
82
  }
73
- if (command === 'agent')
74
- return (await import('../lib/shared/agent/agent-init.js')).runAgentCommand(rest);
75
83
  if (command === '--help' || command === '-h') {
76
84
  console.log(usage);
77
85
  return 0;
78
86
  }
79
- return (await import('../lib/shared/check.js')).runCheck(command === 'check' ? rest : args, usage);
87
+ if (command === 'check' && (rest.includes('--help') || rest.includes('-h'))) {
88
+ console.log(checkUsage);
89
+ return 0;
90
+ }
91
+ if (command === 'explain')
92
+ return (await import('../lib/shared/explain.js')).runExplain(rest);
93
+ if (command === 'report-fp')
94
+ return (await import('../lib/shared/report-fp.js')).runReportFp(rest);
95
+ if (command === 'lsp')
96
+ return (await import('../lib/editor/language-server.js')).runLanguageServer(rest);
97
+ if (command === 'editor')
98
+ return (await import('../lib/editor/setup.js')).runEditor(rest);
99
+ if (command === 'agent')
100
+ return (await import('../lib/shared/agent/agent-init.js')).runAgentCommand(rest);
101
+ return (await import('../lib/shared/cli-dispatch.js')).dispatch(args, checkUsage);
80
102
  }
81
103
  // perf, rel, maint, sec and a11y run in this process, whose default heap limit is too small for very large
82
104
  // projects. One re-spawn with a larger limit keeps their output and exit code the same; a limit the
83
105
  // user set is never replaced.
84
106
  const inProcessCheckers = new Set(['perf', 'rel', 'maint', 'sec', 'a11y']);
85
- function respawnIfHeapTooSmall(commandArgs) {
86
- if (!inProcessCheckers.has(commandArgs[0]) || !shouldRespawnWithLargerHeap())
87
- return false;
88
- respawnWithLargerHeap(import.meta.filename, commandArgs);
89
- return true;
107
+ const recognizedCommands = new Set([
108
+ 'check',
109
+ 'perf',
110
+ 'rel',
111
+ 'maint',
112
+ 'sec',
113
+ 'a11y',
114
+ 'fix',
115
+ 'explain',
116
+ 'report-fp',
117
+ 'lsp',
118
+ 'editor',
119
+ 'agent',
120
+ '--version',
121
+ '-v',
122
+ '--help',
123
+ '-h',
124
+ ]);
125
+ function normalizeCommandTag(rawCommand) {
126
+ return rawCommand && recognizedCommands.has(rawCommand) ? rawCommand : 'check';
90
127
  }
91
- function runMain(commandArgs) {
128
+ async function runMain(commandArgs, reportCrashesFlag) {
129
+ const command = normalizeCommandTag(commandArgs[0]);
130
+ const crashReportingRequested = reportCrashesFlag ||
131
+ Boolean(process.env.LOADWISE_SENTRY_DSN) ||
132
+ process.env.LOADWISE_CRASH_REPORTS === '1' ||
133
+ process.env.LOADWISE_CRASH_REPORTS === 'true';
134
+ if (crashReportingRequested) {
135
+ const { installGlobalCrashHandlers, resolveCrashReportTarget } = await import('../lib/shared/system/sentry.js');
136
+ installGlobalCrashHandlers(command, resolveCrashReportTarget({ flagEnabled: reportCrashesFlag }));
137
+ }
92
138
  main(commandArgs)
93
139
  .then(async (code) => {
94
140
  process.exitCode = code;
95
141
  (await import('../lib/shared/agent/agent-session.js')).promptReview(commandArgs);
96
142
  })
97
- .catch((error) => {
143
+ .catch(async (error) => {
98
144
  console.error(terminalSafe(error instanceof Error ? error.message : String(error)));
145
+ const { isExpectedCliError, reportCrash, resolveCrashReportTarget } = await import('../lib/shared/system/sentry.js');
146
+ if (!isExpectedCliError(error)) {
147
+ const target = resolveCrashReportTarget({ flagEnabled: reportCrashesFlag });
148
+ if (target) {
149
+ const sent = await reportCrash(error, command, target);
150
+ if (sent) {
151
+ console.error('Sent a crash report with Loadwise diagnostic metadata.');
152
+ }
153
+ }
154
+ else {
155
+ console.error('Unexpected Loadwise error. Prefix the command with --report-crashes (or set LOADWISE_CRASH_REPORTS=1) to send a crash report with Loadwise diagnostic metadata.');
156
+ }
157
+ }
99
158
  process.exitCode = 2;
100
159
  });
101
160
  }
102
161
  const args = process.argv.slice(2);
103
- if (!respawnIfHeapTooSmall(args))
104
- runMain(args);
162
+ const reportCrashesFlag = args[0] === crashReportOption;
163
+ const commandArgs = reportCrashesFlag ? args.slice(1) : args;
164
+ if (inProcessCheckers.has(commandArgs[0] ?? '') && shouldRespawnWithLargerHeap()) {
165
+ respawnWithLargerHeap(import.meta.filename, args);
166
+ }
167
+ else {
168
+ void runMain(commandArgs, reportCrashesFlag);
169
+ }
@@ -2,21 +2,23 @@ import { isVendoredMinified } from '../shared/analysis/execution-context.js';
2
2
  import { relativeToProject, reviewedReason, reviewMarkers } from '../performance/analysis/review-context.js';
3
3
  import { jsxDocument } from './jsx-elements.js';
4
4
  import { inlineAngularTemplates } from './angular-inline.js';
5
+ import { contextualizeFrameViewports } from './frame-viewport.js';
5
6
  import { checkMarkup } from './rules.js';
6
- const angularDecorator = '@Component';
7
7
  function analyzeFile(program, sourceFile) {
8
8
  if (sourceFile.isDeclarationFile || isVendoredMinified(sourceFile.fileName))
9
9
  return [];
10
10
  const hasJsx = /\.[jt]sx$/i.test(sourceFile.fileName);
11
- const hasAngularComponent = sourceFile.text.includes(angularDecorator);
11
+ const hasAngularComponent = sourceFile.text.includes('@angular/core') && sourceFile.text.includes('template');
12
12
  if (!hasJsx && !hasAngularComponent)
13
13
  return [];
14
14
  const file = relativeToProject(sourceFile.fileName).split('\\').join('/');
15
15
  const documents = [
16
16
  ...(hasJsx ? [jsxDocument(sourceFile, file, program.getTypeChecker())] : []),
17
- ...(hasAngularComponent ? inlineAngularTemplates(sourceFile, file) : []),
17
+ ...(hasAngularComponent ? inlineAngularTemplates(sourceFile, file, program.getTypeChecker()) : []),
18
18
  ];
19
19
  const findings = documents.flatMap((document) => checkMarkup(document));
20
+ if (hasJsx)
21
+ contextualizeFrameViewports(findings, sourceFile, program);
20
22
  const hasReviewComments = reviewMarkers.some((marker) => sourceFile.text.includes(marker));
21
23
  return findings.map((finding) => {
22
24
  const reason = hasReviewComments ? reviewedReason(sourceFile, (finding.line ?? 1) - 1, finding.ruleId) : undefined;
@@ -1,12 +1,12 @@
1
1
  import { ts } from '../performance/engine/compiler.js';
2
2
  import { walkNodes } from '../reliability/walk.js';
3
- import { templateDocument } from './template-elements.js';
4
- const componentDecoratorName = 'Component';
5
- function componentOptions(node) {
3
+ import { angularLiteralDocument } from './angular-literal.js';
4
+ import { ANGULAR_MODULES, importedName } from '../performance/frontend/frontend-helpers.js';
5
+ function componentOptions(node, checker) {
6
6
  if (!ts.isDecorator(node) || !ts.isCallExpression(node.expression))
7
7
  return undefined;
8
8
  const call = node.expression;
9
- if (!ts.isIdentifier(call.expression) || call.expression.text !== componentDecoratorName)
9
+ if (importedName(call.expression, checker, ANGULAR_MODULES) !== 'Component')
10
10
  return undefined;
11
11
  return call.arguments[0];
12
12
  }
@@ -25,18 +25,16 @@ function templateLiteral(options) {
25
25
  }
26
26
  return undefined;
27
27
  }
28
- /**
29
- * Parses each static inline template with the Angular dialect. The region is the literal's raw source between its
30
- * quotes, so positions point into the .ts file.
31
- */
32
- function inlineAngularTemplates(sourceFile, file) {
28
+ function inlineAngularTemplates(sourceFile, file, checker) {
33
29
  const documents = [];
34
30
  walkNodes(sourceFile, (node) => {
35
- const options = componentOptions(node);
31
+ const options = componentOptions(node, checker);
36
32
  const literal = options && templateLiteral(options);
37
33
  if (!literal)
38
34
  return;
39
- documents.push(templateDocument(file, sourceFile.text, 'angular', literal.getStart(sourceFile) + 1, literal.getEnd() - 1));
35
+ const document = angularLiteralDocument(file, sourceFile, literal);
36
+ if (document)
37
+ documents.push(document);
40
38
  });
41
39
  return documents;
42
40
  }
@@ -0,0 +1,39 @@
1
+ import { mappedAngularDocument, templateDocument } from './template-elements.js';
2
+ // A TypeScript escape consumes one cooked UTF-16 unit except for line continuations (zero)
3
+ // and a braced Unicode code point outside the BMP (two). CRLF in a template cooks to LF.
4
+ const sourceEscape = /\\(?:\r\n|u\{[\da-fA-F]+\}|u[\da-fA-F]{4}|x[\da-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|[\s\S])|\r\n?/g;
5
+ function cookedWidth(spelling) {
6
+ if (/^\\[\r\n\u2028\u2029]/.test(spelling))
7
+ return 0;
8
+ if (spelling.startsWith('\\u{') && Number.parseInt(spelling.slice(3, -1), 16) > 0xffff)
9
+ return 2;
10
+ return 1;
11
+ }
12
+ function angularLiteralDocument(file, sourceFile, literal) {
13
+ const start = literal.getStart(sourceFile) + 1;
14
+ const end = literal.getEnd() - 1;
15
+ const raw = sourceFile.text.slice(start, end);
16
+ if (raw === literal.text)
17
+ return templateDocument(file, sourceFile.text, 'angular', start, end);
18
+ const sourceOffsets = [];
19
+ let rawOffset = 0;
20
+ for (const escape of raw.matchAll(sourceEscape)) {
21
+ while (rawOffset < escape.index)
22
+ sourceOffsets.push(start + rawOffset++);
23
+ for (let unit = 0; unit < cookedWidth(escape[0]); unit++)
24
+ sourceOffsets.push(start + rawOffset);
25
+ rawOffset += escape[0].length;
26
+ }
27
+ while (rawOffset < raw.length)
28
+ sourceOffsets.push(start + rawOffset++);
29
+ // Invalid/unfinished literals can appear in editor buffers. Suppress uncertain locations.
30
+ if (sourceOffsets.length !== literal.text.length)
31
+ return;
32
+ sourceOffsets.push(end);
33
+ const positionAt = (cookedOffset) => {
34
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(sourceOffsets[cookedOffset]);
35
+ return { line: line + 1, column: character + 1 };
36
+ };
37
+ return mappedAngularDocument(file, literal.text, positionAt);
38
+ }
39
+ export { angularLiteralDocument };
@@ -0,0 +1,36 @@
1
+ import { attributeNamed, staticAttributeText, walkElements } from './markup.js';
2
+ function isLabelLike(element) {
3
+ return element.tagName === 'label' || !element.isIntrinsic;
4
+ }
5
+ // Labels of components count too: a `<Label htmlFor="x">` names the control with that id just as a `<label>` does.
6
+ function formAndLabelTargets(document) {
7
+ const formsById = new Map();
8
+ const labelledIds = new Set();
9
+ let hasDynamicLabelFor = false;
10
+ for (const element of walkElements(document.roots)) {
11
+ if (element.isIntrinsic && element.tagName === 'form') {
12
+ const id = staticAttributeText(element, 'id');
13
+ if (id)
14
+ formsById.set(id, formsById.has(id) ? undefined : element);
15
+ }
16
+ const target = isLabelLike(element) ? attributeNamed(element, 'for') : undefined;
17
+ if (target?.value.kind === 'static')
18
+ labelledIds.add(target.value.text);
19
+ else if (target)
20
+ hasDynamicLabelFor = true;
21
+ }
22
+ return { labelledIds, hasDynamicLabelFor, formsById };
23
+ }
24
+ function formMayDisableAutocomplete(element, { ancestors, formsById }) {
25
+ const form = attributeNamed(element, 'form');
26
+ if (form?.value.kind === 'dynamic')
27
+ return true;
28
+ const owner = form?.value.kind === 'static'
29
+ ? formsById.get(form.value.text)
30
+ : ancestors.findLast((ancestor) => ancestor.isIntrinsic && ancestor.tagName === 'form');
31
+ if (!owner)
32
+ return !!form;
33
+ const policy = attributeNamed(owner, 'autocomplete');
34
+ return (owner.hasSpreadAttributes || policy?.value.kind === 'dynamic' || policy?.value.text.trim().toLowerCase() === 'off');
35
+ }
36
+ export { formAndLabelTargets, formMayDisableAutocomplete };
@@ -0,0 +1,92 @@
1
+ import { ts } from '../performance/engine/compiler.js';
2
+ import { importedFrom } from '../security/bindings.js';
3
+ import { walkNodes } from '../reliability/walk.js';
4
+ function isContentDocument(value) {
5
+ return ts.isPropertyAccessExpression(value) && value.name.text === 'contentDocument';
6
+ }
7
+ function initializedFromFrame(value, checker) {
8
+ if (isContentDocument(value))
9
+ return true;
10
+ if (!ts.isIdentifier(value))
11
+ return false;
12
+ const declaration = checker.getSymbolAtLocation(value)?.valueDeclaration;
13
+ return (!!declaration &&
14
+ ts.isVariableDeclaration(declaration) &&
15
+ !!(declaration.parent.flags & ts.NodeFlags.Const) &&
16
+ !!declaration.initializer &&
17
+ isContentDocument(declaration.initializer));
18
+ }
19
+ function stateInitializer(binding, checker) {
20
+ if (!ts.isVariableDeclaration(binding) || !binding.initializer || !ts.isCallExpression(binding.initializer))
21
+ return;
22
+ const hook = importedFrom(binding.initializer.expression, checker);
23
+ if (hook?.exported !== 'useState' || !['react', 'preact/hooks'].includes(hook.module))
24
+ return;
25
+ const initial = binding.initializer.arguments[0];
26
+ return !initial || initial.kind === ts.SyntaxKind.NullKeyword ? null : initial;
27
+ }
28
+ function frameDocumentState(value, component, checker) {
29
+ if (!ts.isIdentifier(value))
30
+ return false;
31
+ const binding = checker.getSymbolAtLocation(value)?.valueDeclaration;
32
+ if (!binding || !ts.isBindingElement(binding) || !ts.isArrayBindingPattern(binding.parent))
33
+ return false;
34
+ const [document, setter] = binding.parent.elements;
35
+ if (binding !== document || !setter || !ts.isBindingElement(setter) || !ts.isIdentifier(setter.name))
36
+ return false;
37
+ const setterSymbol = checker.getSymbolAtLocation(setter.name);
38
+ const initial = stateInitializer(binding.parent.parent, checker);
39
+ if (initial === undefined || (initial && !initializedFromFrame(initial, checker)))
40
+ return false;
41
+ let assignedFrame = !!initial;
42
+ let assignedOther = false;
43
+ walkNodes(component, (node) => {
44
+ if (!ts.isIdentifier(node) || node === setter.name || checker.getSymbolAtLocation(node) !== setterSymbol)
45
+ return;
46
+ const call = node.parent;
47
+ if (!ts.isCallExpression(call) || call.expression !== node) {
48
+ assignedOther = true;
49
+ return;
50
+ }
51
+ const [next] = call.arguments;
52
+ if (next && initializedFromFrame(next, checker))
53
+ assignedFrame = true;
54
+ else
55
+ assignedOther = true;
56
+ });
57
+ return assignedFrame && !assignedOther;
58
+ }
59
+ function frameHeadProperty(value) {
60
+ return ts.isPropertyAccessExpression(value) && value.name.text === 'head' && isContentDocument(value.expression);
61
+ }
62
+ function frameHeadField(component, field) {
63
+ const property = component.members.find((member) => ts.isPropertyDeclaration(member) && ts.isIdentifier(member.name) && member.name.text === field);
64
+ const initial = property && ts.isPropertyDeclaration(property) ? property.initializer : undefined;
65
+ if (initial && initial.kind !== ts.SyntaxKind.NullKeyword && !frameHeadProperty(initial))
66
+ return false;
67
+ let assignedFrame = !!initial && frameHeadProperty(initial);
68
+ let assignedOther = false;
69
+ walkNodes(component, (node) => {
70
+ if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
71
+ return;
72
+ const { left, right } = node;
73
+ if (!ts.isPropertyAccessExpression(left) ||
74
+ left.expression.kind !== ts.SyntaxKind.ThisKeyword ||
75
+ left.name.text !== field)
76
+ return;
77
+ if (frameHeadProperty(right))
78
+ assignedFrame = true;
79
+ else
80
+ assignedOther = true;
81
+ });
82
+ return assignedFrame && !assignedOther;
83
+ }
84
+ export function isFrameHead(value, component, checker) {
85
+ if (!ts.isPropertyAccessExpression(value))
86
+ return false;
87
+ if (value.name.text === 'head')
88
+ return initializedFromFrame(value.expression, checker) || frameDocumentState(value.expression, component, checker);
89
+ return (ts.isClassDeclaration(component) &&
90
+ value.expression.kind === ts.SyntaxKind.ThisKeyword &&
91
+ frameHeadField(component, value.name.text));
92
+ }
@@ -0,0 +1,149 @@
1
+ import path from 'node:path';
2
+ import { ts } from '../performance/engine/compiler.js';
3
+ import { importedFrom } from '../security/bindings.js';
4
+ import { walkNodes } from '../reliability/walk.js';
5
+ import { isFrameHead } from './frame-head.js';
6
+ function defaultComponent(file, checker) {
7
+ for (const statement of file.statements) {
8
+ if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement)) &&
9
+ statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword))
10
+ return statement;
11
+ if (!ts.isExportAssignment(statement) || !ts.isIdentifier(statement.expression))
12
+ continue;
13
+ const declaration = checker.getSymbolAtLocation(statement.expression)?.valueDeclaration;
14
+ if (!declaration || declaration.getSourceFile() !== file)
15
+ return;
16
+ if (ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration))
17
+ return declaration;
18
+ if (!ts.isVariableDeclaration(declaration) || !declaration.initializer)
19
+ return;
20
+ const initializer = declaration.initializer;
21
+ if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))
22
+ return initializer;
23
+ if (!ts.isCallExpression(initializer))
24
+ return;
25
+ const wrapper = importedFrom(initializer.expression, checker);
26
+ const render = initializer.arguments[0];
27
+ if (wrapper?.module !== 'react' || wrapper.exported !== 'forwardRef' || !render || !ts.isFunctionExpression(render))
28
+ return;
29
+ const [returned] = render.body.statements;
30
+ if (render.body.statements.length !== 1 || !ts.isReturnStatement(returned) || !returned.expression)
31
+ return;
32
+ const element = ts.skipOuterExpressions(returned.expression);
33
+ if (!ts.isJsxSelfClosingElement(element) || !ts.isIdentifier(element.tagName))
34
+ return;
35
+ const inner = checker.getSymbolAtLocation(element.tagName)?.valueDeclaration;
36
+ if (inner?.getSourceFile() === file && (ts.isClassDeclaration(inner) || ts.isFunctionDeclaration(inner)))
37
+ return inner;
38
+ }
39
+ }
40
+ function belongsToComponent(node, component) {
41
+ for (let parent = node.parent; parent && parent !== component; parent = parent.parent) {
42
+ if (ts.isFunctionDeclaration(parent) || ts.isClassLike(parent))
43
+ return false;
44
+ if ((ts.isFunctionExpression(parent) || ts.isArrowFunction(parent)) && ts.isVariableDeclaration(parent.parent))
45
+ return false;
46
+ }
47
+ return true;
48
+ }
49
+ const viewportRule = 'a11y-viewport-zoom-disabled';
50
+ function isFrameModule(module, sourceFile, program) {
51
+ if (module === 'react-frame-component')
52
+ return true;
53
+ if (!module.startsWith('.'))
54
+ return false;
55
+ const target = path.resolve(path.dirname(sourceFile.fileName), module).replace(/\.[cm]?[jt]sx?$/, '');
56
+ const implementation = program
57
+ .getSourceFiles?.()
58
+ .find((candidate) => path.normalize(candidate.fileName).replace(/\.[cm]?[jt]sx?$/, '') === target);
59
+ if (!implementation || !implementation.text.includes('iframe'))
60
+ return false;
61
+ const checker = program.getTypeChecker();
62
+ const component = defaultComponent(implementation, checker);
63
+ if (!component)
64
+ return false;
65
+ let hasIframe = false;
66
+ let rendersHead = false;
67
+ walkNodes(component, (node) => {
68
+ if (!belongsToComponent(node, component))
69
+ return;
70
+ if ((ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
71
+ ts.isIdentifier(node.tagName) &&
72
+ node.tagName.text === 'iframe')
73
+ hasIframe = true;
74
+ if (!ts.isCallExpression(node) || node.arguments.length < 2)
75
+ return;
76
+ const [head, container] = node.arguments;
77
+ if (!ts.isIdentifier(head) || head.text !== 'head' || !isFrameHead(container, component, checker))
78
+ return;
79
+ const render = importedFrom(node.expression, checker);
80
+ if ((render?.module === 'react-dom' && render.exported === 'createPortal') ||
81
+ (render?.module === 'preact' && render.exported === 'render'))
82
+ rendersHead = true;
83
+ });
84
+ return hasIframe && rendersHead;
85
+ }
86
+ // Common head slots contain a JSX literal, a local fragment variable, or a local method/component result.
87
+ function headSource(value, checker, sourceFile) {
88
+ const expression = ts.skipOuterExpressions(value);
89
+ const reference = ts.isCallExpression(expression)
90
+ ? expression.expression
91
+ : ts.isJsxSelfClosingElement(expression)
92
+ ? expression.tagName
93
+ : expression;
94
+ const name = ts.isPropertyAccessExpression(reference) ? reference.name : reference;
95
+ if (!ts.isIdentifier(name))
96
+ return expression;
97
+ const declaration = checker.getSymbolAtLocation(name)?.declarations?.[0];
98
+ if (!declaration || declaration.getSourceFile() !== sourceFile)
99
+ return;
100
+ // A value also consumed by ordinary page code is not exclusively a frame head.
101
+ let shared = false;
102
+ walkNodes(sourceFile, (use) => {
103
+ if (shared || use === name || use.parent === declaration || !ts.isIdentifier(use) || use.text !== name.text)
104
+ return;
105
+ if (checker.getSymbolAtLocation(use)?.declarations?.includes(declaration))
106
+ shared = true;
107
+ });
108
+ if (shared)
109
+ return;
110
+ if (ts.isVariableDeclaration(declaration) && declaration.parent.flags & ts.NodeFlags.Const)
111
+ return declaration.initializer;
112
+ if (ts.isMethodDeclaration(declaration) || ts.isFunctionDeclaration(declaration)) {
113
+ const returned = declaration.body?.statements.filter(ts.isReturnStatement);
114
+ if (returned?.length === 1)
115
+ return returned[0].expression;
116
+ }
117
+ }
118
+ function contextualizeFrameViewports(findings, sourceFile, program) {
119
+ const viewports = findings.filter((finding) => finding.ruleId === viewportRule);
120
+ if (!viewports.length || !sourceFile.text.includes('head'))
121
+ return;
122
+ const checker = program.getTypeChecker();
123
+ const headSources = [];
124
+ walkNodes(sourceFile, (node) => {
125
+ if (!ts.isJsxAttribute(node) || node.name.getText(sourceFile) !== 'head')
126
+ return;
127
+ const owner = node.parent.parent.tagName;
128
+ const binding = importedFrom(owner, checker);
129
+ if (binding?.exported !== 'default' || !isFrameModule(binding.module, sourceFile, program))
130
+ return;
131
+ const value = node.initializer;
132
+ if (!value || !ts.isJsxExpression(value) || !value.expression)
133
+ return;
134
+ const head = headSource(value.expression, checker, sourceFile);
135
+ if (head)
136
+ headSources.push(head);
137
+ });
138
+ for (const finding of viewports) {
139
+ if (!finding.line || !finding.column)
140
+ continue;
141
+ const position = sourceFile.getPositionOfLineAndCharacter(finding.line - 1, finding.column - 1);
142
+ if (!headSources.some((head) => head.pos <= position && position < head.end))
143
+ continue;
144
+ finding.contextualReason = 'This viewport declaration is supplied to a frame component’s head.';
145
+ finding.message +=
146
+ ' This head is passed to a frame component. Check the embedded document independently of its host page.';
147
+ }
148
+ }
149
+ export { contextualizeFrameViewports };