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,7 +3,7 @@
3
3
  // lenses over the Language Server Protocol on stdin and stdout.
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
6
- import { packageManifest } from '../shared/package-root.js';
6
+ import { packageManifest, packagePath } from '../shared/package-root.js';
7
7
  import { CodeActionKind, CodeLensRefreshRequest, DidChangeConfigurationNotification, DidChangeWatchedFilesNotification, FileChangeType, TextDocumentSyncKind, TextDocuments, createConnection, } from 'vscode-languageserver/node';
8
8
  import { TextDocument } from 'vscode-languageserver-textdocument';
9
9
  import { codeActions, codeLenses, commands, fixAllKind } from './actions.js';
@@ -13,10 +13,10 @@ import { createEditorDocument, readDiskDocument } from './editor-document.js';
13
13
  import { createScanSession } from './scan-session.js';
14
14
  import { classifyChange, watchedGlobs } from './workspace-files.js';
15
15
  import { runCommand } from './server-commands.js';
16
- import { isInside } from './workspace-paths.js';
16
+ import { isInside, isRealPathInside } from './workspace-paths.js';
17
17
  import { isRecord } from '../shared/system/is-record.js';
18
18
  const usage = 'Usage: loadwise lsp [--stdio]';
19
- const defaultCli = path.resolve(import.meta.dirname, '../../bin/loadwise.js');
19
+ const defaultCli = packagePath('dist/bin/loadwise.js');
20
20
  const severities = new Set(['default', 'error', 'warning', 'information', 'hint']);
21
21
  const defaultSettings = { enabled: true, project: '', cli: '', severity: 'default', codeLens: true };
22
22
  // Only these change what the checkers report; severity and code lenses only change how it is shown.
@@ -88,8 +88,10 @@ function serverCapabilities() {
88
88
  }
89
89
  function startServer(connection) {
90
90
  const documents = new TextDocuments(TextDocument);
91
+ let openSnapshots = new WeakMap();
91
92
  const openUris = new Map();
92
93
  const savedVersions = new Map();
94
+ const pendingDiskChecks = new Map();
93
95
  const folders = new Map();
94
96
  // The latest workspace/configuration request per folder; an older answer arriving later is dropped.
95
97
  const settingsRequests = new Map();
@@ -105,18 +107,35 @@ function startServer(connection) {
105
107
  }
106
108
  function documentFor(filename) {
107
109
  const key = fileKey(filename);
108
- const uri = openUris.get(key);
110
+ const uri = openUris.get(key)?.at(-1);
109
111
  const open = uri === undefined ? undefined : documents.get(uri);
110
112
  if (!open)
111
113
  return readDiskDocument(filename);
112
- return createEditorDocument(filename, open.getText(), {
114
+ const previous = openSnapshots.get(open);
115
+ const dirty = savedVersions.get(open.uri) !== open.version;
116
+ if (previous?.version === open.version && previous.isDirty === dirty)
117
+ return previous;
118
+ const text = open.getText();
119
+ const initialVersion = pendingDiskChecks.get(open.uri);
120
+ if (initialVersion !== undefined) {
121
+ pendingDiskChecks.delete(open.uri);
122
+ if (initialVersion === open.version) {
123
+ const owner = folderFor(filename);
124
+ const saved = owner && isRealPathInside(owner.root, filename) ? readDiskDocument(filename) : undefined;
125
+ if (saved?.getText() === text)
126
+ savedVersions.set(open.uri, initialVersion);
127
+ }
128
+ }
129
+ const snapshot = createEditorDocument(filename, text, {
113
130
  languageId: open.languageId,
114
131
  version: open.version,
115
- isDirty: savedVersions.get(key) !== open.version,
132
+ isDirty: savedVersions.get(open.uri) !== open.version,
116
133
  });
134
+ openSnapshots.set(open, snapshot);
135
+ return snapshot;
117
136
  }
118
137
  function uriFor(filename) {
119
- return openUris.get(fileKey(filename)) ?? pathToFileURL(filename).href;
138
+ return openUris.get(fileKey(filename))?.at(-1) ?? pathToFileURL(filename).href;
120
139
  }
121
140
  function deepestFirst() {
122
141
  return [...folders.values()].sort((left, right) => right.root.length - left.root.length);
@@ -184,6 +203,7 @@ function startServer(connection) {
184
203
  }
185
204
  refreshCodeLenses();
186
205
  }
206
+ const maxDirtySnapshotBytes = 4 * 1024 * 1024;
187
207
  function republish(folder) {
188
208
  const settings = settingsFor(folder);
189
209
  // One read per file for the whole report, however many findings it has.
@@ -194,11 +214,20 @@ function startServer(connection) {
194
214
  read.set(key, documentFor(filename));
195
215
  return read.get(key);
196
216
  };
217
+ const saved = new Map();
218
+ const savedDocumentFor = (filename) => {
219
+ const key = fileKey(filename);
220
+ if (!saved.has(key))
221
+ saved.set(key, readDiskDocument(filename, maxDirtySnapshotBytes));
222
+ return saved.get(key);
223
+ };
197
224
  folder.entries = [...folder.session.reports()].flatMap(({ source, findings }) => buildDiagnostics(folder.root, source, findings, {
198
225
  // A nested folder's own dismissal file decides for its files.
199
226
  isDismissed: (entry) => (folderFor(entry.file) ?? folder).dismissals.has(entry),
200
227
  severity: settings.severity,
228
+ severityFor: (filename) => settingsFor(folderFor(filename) ?? folder).severity,
201
229
  documentFor: cachedDocumentFor,
230
+ savedDocumentFor,
202
231
  uriFor,
203
232
  }));
204
233
  sendDiagnostics();
@@ -257,7 +286,10 @@ function startServer(connection) {
257
286
  settings: () => settingsFor(folder),
258
287
  log: (text) => connection.console.info(text),
259
288
  logError: (text) => connection.console.error(text),
260
- onReports: () => republish(folder),
289
+ onReports: () => {
290
+ openSnapshots = new WeakMap();
291
+ republish(folder);
292
+ },
261
293
  onStatus: updateProgress,
262
294
  }),
263
295
  };
@@ -294,7 +326,7 @@ function startServer(connection) {
294
326
  let dismissalsChanged = false;
295
327
  for (const { filename, type } of changes) {
296
328
  for (const folder of foldersFor(filename)) {
297
- const kind = classifyChange(folder.root, filename, settingsFor(folder).project);
329
+ const kind = classifyChange(folder.root, filename, settingsFor(folder).project, type === FileChangeType.Deleted);
298
330
  if (kind === 'ignored')
299
331
  continue;
300
332
  if (kind === 'dismissals') {
@@ -320,26 +352,34 @@ function startServer(connection) {
320
352
  return filename === undefined ? [] : [{ filename, type }];
321
353
  });
322
354
  }
323
- // An editor can open a buffer with unsaved edits, such as one restored from a previous session;
324
- // only a buffer that matches the file on disk counts as saved.
355
+ // Editors can restore unsaved buffers. Check the unchanged initial version against disk when a
356
+ // finding needs it, so opening an unrelated document does not read it again.
325
357
  function documentOpened(document) {
326
358
  const filename = filenameOf(document.uri);
327
359
  if (filename === undefined)
328
360
  return;
329
- openUris.set(fileKey(filename), document.uri);
330
- if (readDiskDocument(filename)?.getText() === document.getText())
331
- savedVersions.set(fileKey(filename), document.version);
332
- else
333
- savedVersions.delete(fileKey(filename));
361
+ const key = fileKey(filename);
362
+ const aliases = openUris.get(key) ?? [];
363
+ openUris.set(key, [...aliases.filter((uri) => uri !== document.uri), document.uri]);
364
+ pendingDiskChecks.set(document.uri, document.version);
365
+ savedVersions.delete(document.uri);
334
366
  foldersFor(filename).forEach(republish);
335
367
  }
336
368
  function documentClosed(uri) {
337
369
  const filename = filenameOf(uri);
338
370
  if (filename === undefined)
339
371
  return;
340
- openUris.delete(fileKey(filename));
341
- savedVersions.delete(fileKey(filename));
342
- foldersFor(filename).forEach(republish);
372
+ const key = fileKey(filename);
373
+ const aliases = openUris.get(key) ?? [];
374
+ const remaining = aliases.filter((open) => open !== uri);
375
+ if (remaining.length)
376
+ openUris.set(key, remaining);
377
+ else
378
+ openUris.delete(key);
379
+ pendingDiskChecks.delete(uri);
380
+ savedVersions.delete(uri);
381
+ if (aliases.at(-1) === uri)
382
+ foldersFor(filename).forEach(republish);
343
383
  }
344
384
  const context = {
345
385
  connection,
@@ -353,8 +393,10 @@ function startServer(connection) {
353
393
  connection.onInitialize((params) => {
354
394
  capabilities = params.capabilities;
355
395
  initialSettings = settingsFrom(params.initializationOptions);
356
- const rootFilename = params.rootUri ? filenameOf(params.rootUri) : undefined;
357
- const rootFolder = params.rootUri && rootFilename ? [{ uri: params.rootUri, name: path.basename(rootFilename) }] : [];
396
+ const legacyRoot = params.rootPath && path.isAbsolute(params.rootPath) ? params.rootPath : undefined;
397
+ const rootUri = params.rootUri ?? (legacyRoot && pathToFileURL(legacyRoot).href);
398
+ const rootFilename = rootUri ? filenameOf(rootUri) : undefined;
399
+ const rootFolder = rootUri && rootFilename ? [{ uri: rootUri, name: path.basename(rootFilename) }] : [];
358
400
  const initialFolders = params.workspaceFolders ?? rootFolder;
359
401
  connection.onInitialized(async () => {
360
402
  // A client that advertises dynamic registration can still refuse it; the folders are scanned either way.
@@ -387,7 +429,15 @@ function startServer(connection) {
387
429
  const filename = filenameOf(document.uri);
388
430
  if (filename === undefined)
389
431
  return;
390
- savedVersions.set(fileKey(filename), document.version);
432
+ // Another alias of the file may hold different text, so its saved record no longer matches disk.
433
+ for (const alias of openUris.get(fileKey(filename)) ?? []) {
434
+ if (alias === document.uri)
435
+ continue;
436
+ pendingDiskChecks.delete(alias);
437
+ savedVersions.delete(alias);
438
+ }
439
+ pendingDiskChecks.delete(document.uri);
440
+ savedVersions.set(document.uri, document.version);
391
441
  filesChanged([{ filename, type: FileChangeType.Changed }]);
392
442
  });
393
443
  connection.onDidChangeWatchedFiles(({ changes }) => filesChanged(watchedFileEvents(changes)));
@@ -406,14 +456,20 @@ function startServer(connection) {
406
456
  }
407
457
  });
408
458
  connection.onHover(({ textDocument, position }) => {
459
+ const findings = entriesFor(textDocument.uri);
460
+ if (!findings.length)
461
+ return null;
409
462
  const filename = filenameOf(textDocument.uri);
410
463
  const document = filename === undefined ? undefined : documentFor(filename);
411
464
  if (!document)
412
465
  return null;
413
- const hover = hoverFor(document, entriesFor(textDocument.uri), position);
466
+ const folder = folderFor(document.filename);
467
+ if (!folder)
468
+ return null;
469
+ const hover = hoverFor(document, findings, position, folder.root);
414
470
  return hover ? { contents: { kind: 'markdown', value: hover.markdown }, range: hover.range } : null;
415
471
  });
416
- connection.onCodeAction(({ textDocument, range, context: actionContext }) => codeActions(entriesFor(textDocument.uri), range, actionContext.only, textDocument.uri, fixWorkspace()));
472
+ connection.onCodeAction((params) => codeActions(entriesFor(params.textDocument.uri), params, fixWorkspace()));
417
473
  connection.onCodeLens(({ textDocument }) => {
418
474
  const filename = filenameOf(textDocument.uri);
419
475
  const folder = filename === undefined ? undefined : folderFor(filename);
@@ -0,0 +1,37 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
5
+ import { errorCode } from '../shared/system/error-code.js';
6
+ function digest(content) {
7
+ return createHash('sha256').update(content).digest('hex');
8
+ }
9
+ // The checksum lets setup upgrade its own configuration after the server moves, while
10
+ // preserving custom edits even when the user kept the original generated header.
11
+ export function writeManagedConfig(file, comment, content) {
12
+ const header = comment + ' Generated by Loadwise editor setup.';
13
+ const signature = header + ' sha256=';
14
+ const generated = signature + digest(content) + '\n' + content;
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ try {
17
+ fs.writeFileSync(file, generated, { flag: 'wx' });
18
+ return 'created';
19
+ }
20
+ catch (error) {
21
+ if (errorCode(error) !== 'EEXIST')
22
+ throw error;
23
+ }
24
+ const existing = fs.lstatSync(file);
25
+ if (!existing.isFile() || existing.nlink !== 1)
26
+ return 'conflict';
27
+ const previous = fs.readFileSync(file, 'utf8');
28
+ if (previous === generated)
29
+ return 'unchanged';
30
+ const newline = previous.indexOf('\n');
31
+ const verified = newline >= 0 && previous.slice(0, newline) === signature + digest(previous.slice(newline + 1));
32
+ // Early Vim setup wrote an unsigned header. Migrate only an exact copy of the generated plugin.
33
+ if (!verified && previous !== header + '\n' + content)
34
+ return 'conflict';
35
+ writeResolvedFileAtomic(file, generated);
36
+ return 'updated';
37
+ }
@@ -0,0 +1,86 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { writeManagedConfig } from './managed-config.js';
4
+ import { absoluteSetting } from './setup-server.js';
5
+ function configDirectory(editor) {
6
+ const windows = process.platform === 'win32';
7
+ if (editor === 'nvim') {
8
+ const base = absoluteSetting(process.env.XDG_CONFIG_HOME) || (windows ? absoluteSetting(process.env.LOCALAPPDATA) : undefined);
9
+ return path.join(base || path.join(os.homedir(), windows ? 'AppData/Local' : '.config'), process.env.NVIM_APPNAME || 'nvim');
10
+ }
11
+ const base = windows ? absoluteSetting(process.env.APPDATA) : absoluteSetting(process.env.XDG_CONFIG_HOME);
12
+ return path.join(base || path.join(os.homedir(), windows ? 'AppData/Roaming' : '.config'), editor === 'helix' ? 'helix' : 'loadwise');
13
+ }
14
+ function luaString(value) {
15
+ // Lua accepts three-digit decimal byte escapes on every supported runtime.
16
+ const escaped = value.replaceAll(/["\\\p{Cc}]/gu, (character) => Array.from(Buffer.from(character), (byte) => '\\' + String(byte).padStart(3, '0')).join(''));
17
+ return '"' + escaped + '"';
18
+ }
19
+ function nvimSetup(server) {
20
+ const content = `if vim.fn.has('nvim-0.11') == 0 then return end
21
+ if not vim.lsp.config.loadwise then
22
+ vim.lsp.config('loadwise', {
23
+ cmd = { ${[server.command, ...server.args].map(luaString).join(', ')} },
24
+ filetypes = { 'javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'html', 'vue', 'svelte', 'python', 'go', 'java', 'cs', 'rust' },
25
+ root_markers = { 'loadwise.config.json', 'tsconfig.json', 'jsconfig.json', 'package.json', '.git' },
26
+ })
27
+ end
28
+ vim.lsp.enable('loadwise')
29
+ `;
30
+ return {
31
+ file: path.join(configDirectory('nvim'), 'plugin', 'loadwise.lua'),
32
+ comment: '--',
33
+ content,
34
+ next: 'Restart Neovim 0.11+ in your project and open a source file. Check :checkhealth vim.lsp.',
35
+ };
36
+ }
37
+ function helixSetup(server) {
38
+ const serverTable = `[language-server.loadwise]
39
+ command = ${JSON.stringify(server.command)}
40
+ args = ${JSON.stringify(server.args)}`;
41
+ const languages = ['javascript', 'jsx', 'typescript', 'tsx'].map((name) => `[[language]]\nname = "${name}"\nlanguage-servers = ["typescript-language-server", "loadwise"]`);
42
+ return {
43
+ file: path.join(configDirectory('helix'), 'languages.toml'),
44
+ comment: '#',
45
+ content: [serverTable, ...languages, ''].join('\n\n'),
46
+ next: 'Restart Helix 23.10+ and open a JavaScript or TypeScript file. Check hx --health typescript.',
47
+ merge: 'Add the server table once and append "loadwise" to the enabled server lists for your languages. Keep each existing language table and its other servers.',
48
+ };
49
+ }
50
+ function emacsSetup(server) {
51
+ const file = path.join(configDirectory('emacs'), 'loadwise-eglot.el');
52
+ const content = `(require 'eglot)
53
+
54
+ (defun loadwise-eglot ()
55
+ "Start Loadwise with Eglot in this buffer's project."
56
+ (interactive)
57
+ (when (eglot-current-server)
58
+ (user-error "This buffer already has an Eglot server. Use M-x eglot-shutdown to switch"))
59
+ (let ((eglot-server-programs
60
+ (cons (cons major-mode '(${[server.command, ...server.args].map((value) => JSON.stringify(value)).join(' ')}))
61
+ eglot-server-programs)))
62
+ (call-interactively #'eglot)))
63
+
64
+ (provide 'loadwise-eglot)
65
+ `;
66
+ return {
67
+ file,
68
+ comment: ';;',
69
+ content,
70
+ next: `Add (load ${JSON.stringify(file)}) to your Emacs init file. Open a project file and run M-x loadwise-eglot with Eglot (bundled in Emacs 29+). Eglot uses one server per buffer. To switch an active buffer, use M-x eglot-shutdown first.`,
71
+ };
72
+ }
73
+ export function setupNativeEditor(editor, server) {
74
+ const setup = editor === 'nvim' ? nvimSetup(server) : editor === 'helix' ? helixSetup(server) : emacsSetup(server);
75
+ const { file, comment, content, next } = setup;
76
+ const status = writeManagedConfig(file, comment, content);
77
+ if (status === 'unchanged')
78
+ return `Already configured in ${file}.\n${next}`;
79
+ if (status === 'updated')
80
+ return `Updated ${file}.\n${next}`;
81
+ if (status === 'conflict') {
82
+ const merge = 'merge' in setup ? setup.merge : 'Merge the following configuration manually.';
83
+ return `Existing configuration at ${file} requires a manual merge. ${merge}\n\n${content}\n${next}`;
84
+ }
85
+ return `Configured ${file}.\n${next}`;
86
+ }
@@ -5,7 +5,7 @@ import { spawn } from 'node:child_process';
5
5
  function startPerfWatch({ script, project, cwd, env, onFindings, onError, onExit }) {
6
6
  const child = spawn(process.execPath, [script, 'perf', '-p', project, '--watch', '--json'], {
7
7
  cwd,
8
- env,
8
+ env: { ...env, LOADWISE_EDITOR_WATCH_EVENTS: '1' },
9
9
  windowsHide: true,
10
10
  stdio: ['ignore', 'pipe', 'pipe'],
11
11
  });
@@ -18,13 +18,15 @@ function startPerfWatch({ script, project, cwd, env, onFindings, onError, onExit
18
18
  report = JSON.parse(line);
19
19
  }
20
20
  catch (error) {
21
- onError(new Error('Watch mode printed an unreadable report: ' + (error instanceof Error ? error.message : String(error))));
21
+ onError(new Error('Watch mode printed an unreadable report: ' + (error instanceof Error ? error.message : String(error))), true);
22
22
  return;
23
23
  }
24
- if (report && Array.isArray(report.findings))
24
+ if (typeof report?.watchError === 'string')
25
+ onError(new Error(report.watchError), true);
26
+ else if (report && Array.isArray(report.findings))
25
27
  onFindings(report.findings);
26
28
  else
27
- onError(new Error('Watch mode returned an invalid findings report.'));
29
+ onError(new Error('Watch mode returned an invalid findings report.'), true);
28
30
  }
29
31
  child.stdout.setEncoding('utf8');
30
32
  child.stdout.on('data', (chunk) => {
@@ -32,7 +34,7 @@ function startPerfWatch({ script, project, cwd, env, onFindings, onError, onExit
32
34
  return;
33
35
  if (pending.length + chunk.length > maxPendingBytes) {
34
36
  pending = '';
35
- onError(new Error('Watch mode output exceeded maximum buffer size.'));
37
+ onError(new Error('Watch mode output exceeded maximum buffer size.'), true);
36
38
  child.kill('SIGKILL');
37
39
  return;
38
40
  }
@@ -50,7 +52,7 @@ function startPerfWatch({ script, project, cwd, env, onFindings, onError, onExit
50
52
  if (child.killed)
51
53
  return;
52
54
  if (text.trim())
53
- onError(new Error(text.trim()));
55
+ onError(new Error(text.trim()), false);
54
56
  });
55
57
  function finish(error) {
56
58
  if (stopped)
@@ -0,0 +1,61 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { open } from 'node:fs/promises';
3
+ import { isRecord } from '../shared/system/is-record.js';
4
+ const repository = 'IbrahimHafez1/loadwise';
5
+ const metadataTimeoutMs = 30_000;
6
+ const downloadTimeoutMs = 300_000;
7
+ export function currentTarget(architecture = process.arch) {
8
+ if (!['win32', 'darwin', 'linux'].includes(process.platform) || !['x64', 'arm64'].includes(architecture))
9
+ throw new Error(`No official Loadwise editor package for ${process.platform}-${architecture}.`);
10
+ if (process.platform === 'linux') {
11
+ const report = process.report.getReport();
12
+ if (!(isRecord(report) && isRecord(report.header) && report.header.glibcVersionRuntime))
13
+ throw new Error('The official Linux editor package requires glibc.');
14
+ }
15
+ return `${process.platform}-${architecture}`;
16
+ }
17
+ export function vsixFilename(version, target = currentTarget()) {
18
+ return `loadwise-${version}-${target}.vsix`;
19
+ }
20
+ export async function downloadVsix(destination, version, target, request = fetch) {
21
+ const tag = 'v' + version;
22
+ const filename = vsixFilename(version, target);
23
+ const release = await request(`https://api.github.com/repos/${repository}/releases/tags/${encodeURIComponent(tag)}`, {
24
+ headers: { Accept: 'application/vnd.github+json' },
25
+ signal: AbortSignal.timeout(metadataTimeoutMs),
26
+ });
27
+ if (!release.ok)
28
+ throw new Error(`Cannot read Loadwise release ${tag} (GitHub HTTP ${release.status}). Use --vsix <file> with a local build or release asset.`);
29
+ const metadata = await release.json();
30
+ const asset = isRecord(metadata) && metadata.tag_name === tag && Array.isArray(metadata.assets)
31
+ ? metadata.assets.find((item) => isRecord(item) && item.name === filename)
32
+ : undefined;
33
+ if (!isRecord(asset))
34
+ throw new Error(`Release ${tag} has no ${filename}. Use --vsix <file> with a matching local build.`);
35
+ if (typeof asset.digest !== 'string' ||
36
+ !/^sha256:[a-f0-9]{64}$/i.test(asset.digest) ||
37
+ typeof asset.size !== 'number' ||
38
+ !Number.isSafeInteger(asset.size) ||
39
+ asset.size <= 0)
40
+ throw new Error(`GitHub did not provide a valid SHA-256 digest and size for ${filename}.`);
41
+ const download = await request(`https://github.com/${repository}/releases/download/${encodeURIComponent(tag)}/${encodeURIComponent(filename)}`, { signal: AbortSignal.timeout(downloadTimeoutMs) });
42
+ if (!download.ok || !download.body)
43
+ throw new Error(`Cannot download ${filename} (GitHub HTTP ${download.status}).`);
44
+ const hash = createHash('sha256');
45
+ const file = await open(destination, 'wx', 0o600);
46
+ let size = 0;
47
+ try {
48
+ for await (const chunk of download.body) {
49
+ size += chunk.length;
50
+ if (size > asset.size)
51
+ throw new Error(`Downloaded size exceeds the release size for ${filename}.`);
52
+ hash.update(chunk);
53
+ await file.writeFile(chunk);
54
+ }
55
+ }
56
+ finally {
57
+ await file.close();
58
+ }
59
+ if (size !== asset.size || 'sha256:' + hash.digest('hex') !== asset.digest.toLowerCase())
60
+ throw new Error(`Release integrity check failed for ${filename}.`);
61
+ }
@@ -23,6 +23,11 @@ const examples = {
23
23
  code: "const lines = fs.readFileSync(path, 'utf8').split(/\\r?\\n/);\nconst start = lines.indexOf('## [Unreleased]');",
24
24
  note: "With CRLF line endings terminated lines keep a trailing '\\r', so the exact match never finds the heading.",
25
25
  },
26
+ 'db-pool-client-not-released': {
27
+ before: 'const client = await pool.connect();\nawait readOrders(client);\nclient.release();',
28
+ code: 'const client = await pool.connect();\ntry {\n await readOrders(client);\n} finally {\n client.release();\n}',
29
+ note: 'A failure before release can leave one of the pool connections checked out.',
30
+ },
26
31
  'error-logged-without-stack': {
27
32
  before: 'try {\n await sync();\n} catch (error) {\n logger.error(error.message);\n}',
28
33
  code: "try {\n await sync();\n} catch (error) {\n logger.error({ err: error }, 'sync failed');\n}",
@@ -68,6 +73,16 @@ const examples = {
68
73
  code: "let entries = [];\ntry {\n entries = JSON.parse(fs.readFileSync(file, 'utf8'));\n} catch (error) {\n if (error.code !== 'ENOENT') throw error; }\nfs.writeFileSync(file, JSON.stringify([...entries, entry]));",
69
74
  note: 'A file that fails to parse would be overwritten with the default, losing everything it held.',
70
75
  },
76
+ 'pg-advisory-lock-session': {
77
+ before: "await pool.query('SELECT pg_advisory_lock($1)', [key]);\nawait updateOrders();",
78
+ code: "const client = await pool.connect();\ntry { await client.query('SELECT pg_advisory_lock($1)', [key]); await updateOrders(); }\nfinally {\n try { await client.query('SELECT pg_advisory_unlock($1)', [key]); }\n catch (error) { client.release(true); throw error; }\n client.release(); }",
79
+ note: 'Use the same PostgreSQL connection for the lock and its cleanup.',
80
+ },
81
+ 'pg-listen-session': {
82
+ before: "await pool.query('LISTEN jobs');",
83
+ code: "const client = await pool.connect();\ntry { await client.query('LISTEN jobs'); await listenUntilStopped(client); }\nfinally {\n try { await client.query('UNLISTEN jobs'); }\n catch (error) { client.release(true); throw error; }\n client.release(); }",
84
+ note: 'Retain the client until the listener stops, then unsubscribe before returning it.',
85
+ },
71
86
  'pool-without-connection-timeout': {
72
87
  before: 'const pool = new Pool({ connectionString });',
73
88
  code: 'const pool = new Pool({ connectionString, connectionTimeoutMillis: 5000 });',
@@ -13,6 +13,7 @@ import { isMarkupFile } from '../accessibility/markup-files.js';
13
13
  import { listenForEditorRefresh } from '../performance/cli/editor-signal.js';
14
14
  import { hasInfrastructureFiles } from '../security/files/index.js';
15
15
  import { configlessSources, coveringConfig, hasWorkspaceSources } from '../shared/workspaces.js';
16
+ import { isRecord } from '../shared/system/is-record.js';
16
17
  const run = promisify(execFile);
17
18
  const debounceMs = 650;
18
19
  const maxReportBytes = 64 * 1024 * 1024;
@@ -42,6 +43,13 @@ async function firstExisting(root, names) {
42
43
  if (await exists(path.join(root, name)))
43
44
  return name;
44
45
  }
46
+ function parseFindings(stdout) {
47
+ const report = JSON.parse(stdout);
48
+ if (!Array.isArray(report?.findings) ||
49
+ !report.findings.every((item) => isRecord(item) && typeof item.ruleId === 'string' && typeof item.message === 'string'))
50
+ throw new Error('Checker returned an invalid findings report.');
51
+ return report.findings;
52
+ }
45
53
  async function readFindings(script, args, cwd, signal) {
46
54
  const options = {
47
55
  cwd,
@@ -57,15 +65,24 @@ async function readFindings(script, args, cwd, signal) {
57
65
  }
58
66
  catch (error) {
59
67
  const failure = execFailureOf(error);
60
- // Exit code 1 means findings met the exit threshold; the report is still complete.
68
+ if (failure.code === 2) {
69
+ // Exit 2 can mean partial coverage or a failed invocation. Only a valid report is usable.
70
+ try {
71
+ return {
72
+ findings: parseFindings(failure.stdout ?? ''),
73
+ coverageNote: failure.stderr?.trim() || 'The checker reported incomplete coverage.',
74
+ };
75
+ }
76
+ catch (parseError) {
77
+ throw new Error(failure.stderr?.trim() || messageOf(parseError), { cause: error });
78
+ }
79
+ }
80
+ // Exit 1 means findings met the exit threshold; the report is complete.
61
81
  if (failure.code !== 1)
62
82
  throw new Error(failure.stderr?.trim() || failure.message, { cause: error });
63
83
  stdout = failure.stdout ?? '';
64
84
  }
65
- const report = JSON.parse(stdout);
66
- if (!Array.isArray(report.findings))
67
- throw new Error('Checker returned an invalid findings report.');
68
- return report.findings;
85
+ return { findings: parseFindings(stdout) };
69
86
  }
70
87
  // A project setting is used only when it stays inside the folder and cannot be read as a flag.
71
88
  function explicitProject(root, setting) {
@@ -182,10 +199,11 @@ function createScanSession(options) {
182
199
  current.pending = false;
183
200
  show(perf, perf, findings);
184
201
  },
185
- onError(error) {
202
+ onError(error, reportUnavailable) {
186
203
  if (perfWatch !== current)
187
204
  return;
188
- // A config or project error produces no report; stop showing the scan as in progress.
205
+ if (reportUnavailable)
206
+ clear(perf);
189
207
  current.pending = false;
190
208
  logError(perf, error.message);
191
209
  options.onStatus();
@@ -195,6 +213,7 @@ function createScanSession(options) {
195
213
  return;
196
214
  perfWatch = undefined;
197
215
  watchUnavailable = true;
216
+ clear(perf);
198
217
  logError(perf, error.message + ' Falling back to full rescans after each change.');
199
218
  schedule();
200
219
  },
@@ -225,9 +244,11 @@ function createScanSession(options) {
225
244
  throw new Error('The loadwise.cli setting must be an absolute path.');
226
245
  if (task.watchProject !== undefined)
227
246
  return ensureWatch(script, task.watchProject, restart);
228
- const findings = await readFindings(script, task.args, root, scanSignal);
247
+ const { findings, coverageNote } = await readFindings(script, task.args, root, scanSignal);
229
248
  if (scanSignal.aborted || disposed.signal.aborted)
230
249
  return;
250
+ if (coverageNote)
251
+ logError(task.id, coverageNote);
231
252
  show(task.id, task.source, task.markupOnly ? findings.filter(({ file }) => file !== undefined && isMarkupFile(file)) : findings);
232
253
  }
233
254
  async function scan(version, scanSignal) {
@@ -51,6 +51,8 @@ function dismissalArgument(context, value) {
51
51
  const entry = { file: value.file, ruleId: value.ruleId };
52
52
  if (typeof value.lineText === 'string')
53
53
  entry.lineText = value.lineText;
54
+ if (typeof value.occurrence === 'string' && typeof value.lineText === 'string')
55
+ entry.occurrence = value.occurrence;
54
56
  return { folder, entry };
55
57
  }
56
58
  // Returns the folders it made, so a rejected edit leaves none behind.
@@ -137,6 +139,8 @@ async function applyAllFixes(context, value) {
137
139
  if (!eligible.length && !reviewCount)
138
140
  return window.showInformationMessage('Loadwise has no fixes for this file.');
139
141
  const planned = fixAllEdit(eligible, context.fixWorkspace());
142
+ if (planned.error)
143
+ return window.showWarningMessage(planned.error);
140
144
  const { applied, skipped } = planned;
141
145
  if (applied && !(await applyEdit(context, planned, 'Loadwise could not apply the selected fixes.')))
142
146
  return;
@@ -180,7 +184,15 @@ async function restore(context, restored) {
180
184
  function describe({ folder, entry }, index) {
181
185
  const file = path.relative(folder.root, entry.file).split(path.sep).join('/');
182
186
  const line = typeof entry.lineText === 'string' ? entry.lineText || '(blank line)' : 'Whole file';
183
- return index + 1 + '. ' + entry.ruleId + ' — ' + file + ' — ' + line;
187
+ return (index +
188
+ 1 +
189
+ '. ' +
190
+ entry.ruleId +
191
+ ' — ' +
192
+ file +
193
+ ' — ' +
194
+ line +
195
+ (entry.occurrence && entry.occurrence !== '1/1' ? ' (' + entry.occurrence.split('#')[0] + ')' : ''));
184
196
  }
185
197
  async function showDismissed(context) {
186
198
  const { window } = context.connection;
@@ -188,16 +200,33 @@ async function showDismissed(context) {
188
200
  if (!dismissed.length)
189
201
  return window.showInformationMessage('No Loadwise findings are dismissed.');
190
202
  const restoreAll = { title: 'Restore all (' + dismissed.length + ')' };
191
- const restoreOne = dismissed.slice(0, maxRestoreButtons).map((_item, index) => ({ title: 'Restore ' + (index + 1) }));
192
203
  const message = ['Dismissed Loadwise findings:', ...dismissed.map(describe)].join('\n');
193
- const picked = await window.showInformationMessage(message, restoreAll, ...restoreOne);
194
- if (!picked)
204
+ let offset = 0;
205
+ for (;;) {
206
+ const page = dismissed.slice(offset, offset + maxRestoreButtons);
207
+ const restoreOne = page.map((_item, index) => ({ title: 'Restore ' + (offset + index + 1) }));
208
+ const navButtons = [
209
+ ...(offset > 0 ? [{ title: 'Previous' }] : []),
210
+ ...(offset + maxRestoreButtons < dismissed.length ? [{ title: 'Next' }] : []),
211
+ ];
212
+ const picked = await window.showInformationMessage(message, restoreAll, ...restoreOne, ...navButtons);
213
+ if (!picked)
214
+ return;
215
+ if (picked === restoreAll || picked.title === restoreAll.title)
216
+ return restore(context, dismissed);
217
+ if (picked.title === 'Next') {
218
+ offset += maxRestoreButtons;
219
+ continue;
220
+ }
221
+ if (picked.title === 'Previous') {
222
+ offset = Math.max(0, offset - maxRestoreButtons);
223
+ continue;
224
+ }
225
+ const index = restoreOne.findIndex((action) => action.title === picked.title);
226
+ if (index !== -1)
227
+ return restore(context, [dismissed[offset + index]]);
195
228
  return;
196
- if (picked === restoreAll || picked.title === restoreAll.title)
197
- return restore(context, dismissed);
198
- const index = restoreOne.findIndex((action) => action.title === picked.title);
199
- if (index !== -1)
200
- await restore(context, [dismissed[index]]);
229
+ }
201
230
  }
202
231
  // With a dismissal entry it restores that one; without arguments it restores every dismissal.
203
232
  async function restoreDismissed(context, value) {