loadwise 0.7.0 → 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 (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  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/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -8,6 +8,19 @@ const alreadyApplied = 'already applied';
8
8
  function splitLines(text) {
9
9
  return text.split(/\r?\n/);
10
10
  }
11
+ function splitLinesWithEndings(text) {
12
+ const result = [];
13
+ let start = 0;
14
+ for (let index = 0; index < text.length; index++) {
15
+ if (text[index] !== '\n')
16
+ continue;
17
+ const end = index > start && text[index - 1] === '\r' ? index - 1 : index;
18
+ result.push({ content: text.slice(start, end), eol: text.slice(end, index + 1) });
19
+ start = index + 1;
20
+ }
21
+ result.push({ content: text.slice(start), eol: '' });
22
+ return result;
23
+ }
11
24
  // Prefer the reported row. After a shift, only a unique nearby match identifies the intended edit.
12
25
  function locateChange(lines, change) {
13
26
  const expected = splitLines(change.before);
@@ -71,15 +84,64 @@ function mergeNamedImport(lines, change) {
71
84
  const added = wanted.names.filter((name) => !current.names.includes(name));
72
85
  if (!added.length)
73
86
  return { applied: true };
87
+ if (!current.names.length)
88
+ return { row, line: current.head + wanted.namesText + current.tail };
74
89
  const trailingSpace = /\s*$/.exec(current.namesText)?.[0] ?? '';
75
90
  const keptNames = current.namesText.trimEnd().replace(/,$/, '');
76
91
  return { row, line: `${current.head}${keptNames}, ${added.join(', ')}${trailingSpace}${current.tail}` };
77
92
  }
78
93
  }
94
+ // The lines that replace `removed` lines at `row`, keeping each line's own terminator where it can.
95
+ function buildReplacement(lineEntries, row, removed, added, fallbackEol) {
96
+ const removedEntries = lineEntries.slice(row, row + removed);
97
+ const defaultEol = removedEntries.find((entry) => entry.eol)?.eol ||
98
+ lineEntries[row - 1]?.eol ||
99
+ lineEntries[row + removed]?.eol ||
100
+ fallbackEol;
101
+ // Unchanged lines keep their own ending wherever they land; only the rest take it by position.
102
+ const matchedRemoved = new Map();
103
+ let nextRemoved = 0;
104
+ for (const [index, content] of added.entries()) {
105
+ const found = removedEntries.findIndex((entry, at) => at >= nextRemoved && entry.content === content);
106
+ if (found === -1)
107
+ continue;
108
+ matchedRemoved.set(index, found);
109
+ nextRemoved = found + 1;
110
+ }
111
+ const matchedRows = new Set(matchedRemoved.values());
112
+ const replacement = added.map((content, index) => {
113
+ if (!removed)
114
+ return { content, eol: defaultEol };
115
+ const matchedRow = matchedRemoved.get(index);
116
+ if (matchedRow !== undefined)
117
+ return { content, eol: removedEntries[matchedRow].eol };
118
+ if (index === added.length - 1)
119
+ return { content, eol: removedEntries[removed - 1].eol };
120
+ if (index < removed - 1 && !matchedRows.has(index))
121
+ return { content, eol: removedEntries[index].eol };
122
+ return { content, eol: undefined };
123
+ });
124
+ // An inserted line takes the terminator of its neighbour in the replacement, not a distant one.
125
+ for (const [index, entry] of replacement.entries()) {
126
+ if (entry.eol !== undefined)
127
+ continue;
128
+ entry.eol =
129
+ replacement[index - 1]?.eol || replacement.slice(index + 1).find((later) => later.eol)?.eol || defaultEol;
130
+ }
131
+ // Only the file's last line may lack a terminator; one kept mid-replacement would join its neighbour.
132
+ for (const entry of replacement.slice(0, -1))
133
+ entry.eol ||= defaultEol;
134
+ // A block that ends at an unterminated EOF keeps its last line unterminated, even if that line was retained from earlier.
135
+ if (removed && !removedEntries[removed - 1].eol && row + removed === lineEntries.length && replacement.length) {
136
+ replacement[replacement.length - 1].eol = '';
137
+ }
138
+ return replacement.map(({ content, eol }) => ({ content, eol: eol ?? defaultEol }));
139
+ }
79
140
  // Returns the new text, or { error } when the code no longer matches the scan.
80
141
  function applyChangesToText(text, changes, { exactLocation = false, capture } = {}) {
81
- const newline = text.includes('\r\n') ? '\r\n' : '\n';
82
- const lines = splitLines(text);
142
+ const fallbackEol = text.includes('\r\n') ? '\r\n' : '\n';
143
+ const lineEntries = splitLinesWithEndings(text);
144
+ const lines = lineEntries.map((entry) => entry.content);
83
145
  const located = [];
84
146
  for (const change of changes) {
85
147
  const row = locateChange(lines, change);
@@ -110,10 +172,13 @@ function applyChangesToText(text, changes, { exactLocation = false, capture } =
110
172
  return { error: 'overlapping changes' };
111
173
  }
112
174
  for (const { row, removed, added } of located) {
113
- const original = lines.splice(row, removed, ...added);
175
+ const removedEntries = lineEntries.slice(row, row + removed);
176
+ const replacement = buildReplacement(lineEntries, row, removed, added, fallbackEol);
177
+ lineEntries.splice(row, removed, ...replacement);
178
+ const original = removedEntries.map((entry) => entry.content);
114
179
  capture?.({ file: changes[0].file, line: row + 1, before: original.join('\n'), after: added.join('\n') });
115
180
  }
116
- return { text: lines.join(newline) };
181
+ return { text: lineEntries.map((entry) => entry.content + entry.eol).join('') };
117
182
  }
118
183
  // A change with `create: true` holds a whole new file. It refuses to overwrite a different existing
119
184
  // file, and an identical one means the fix was already applied.
@@ -3,7 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { packagePath } from '../shared/package-root.js';
5
5
  import { writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
6
- import { editorDataDirectory, ensureEditorServer } from './setup-server.js';
6
+ import { absoluteSetting, editorDataDirectory, ensureEditorServer } from './setup-server.js';
7
7
  function copyTemplate(relative, destination) {
8
8
  const content = fs.readFileSync(packagePath('integrations', relative), 'utf8');
9
9
  writeResolvedFileAtomic(destination, content);
@@ -23,10 +23,10 @@ function prepareZed(directory, server) {
23
23
  function sublimePackages() {
24
24
  const home = os.homedir();
25
25
  if (process.platform === 'win32')
26
- return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Sublime Text', 'Packages');
26
+ return path.join(absoluteSetting(process.env.APPDATA) || path.join(home, 'AppData', 'Roaming'), 'Sublime Text', 'Packages');
27
27
  if (process.platform === 'darwin')
28
28
  return path.join(home, 'Library', 'Application Support', 'Sublime Text', 'Packages');
29
- return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'sublime-text', 'Packages');
29
+ return path.join(absoluteSetting(process.env.XDG_CONFIG_HOME) || path.join(home, '.config'), 'sublime-text', 'Packages');
30
30
  }
31
31
  const sublimePackage = 'LSP-loadwise';
32
32
  function prepareSublime(directory, server, packages) {
@@ -48,6 +48,8 @@ function prepareSublime(directory, server, packages) {
48
48
  const existing = fs.lstatSync(target, { throwIfNoEntry: false });
49
49
  if (!existing)
50
50
  fs.symlinkSync(directory, target, process.platform === 'win32' ? 'junction' : 'dir');
51
+ else if (existing.isSymbolicLink() && !fs.statSync(target, { throwIfNoEntry: false }))
52
+ throw new Error(`The Sublime package link at ${target} has a missing target. Remove the stale link and rerun setup. The generated Loadwise package is at ${directory}.`);
51
53
  else if (!existing.isSymbolicLink() || fs.realpathSync(target) !== fs.realpathSync(directory))
52
54
  throw new Error(`Another Sublime package already exists at ${target}. The generated Loadwise package is at ${directory}.`);
53
55
  return `Registered ${sublimePackage} in ${packages}.\n${prerequisite}`;
@@ -1,8 +1,10 @@
1
1
  // Turns checker reports into language server diagnostics and hovers. Each published diagnostic keeps
2
2
  // an anchor with what the code actions, code lenses and hovers need: the reported site, the
3
3
  // scanner's fix and the dismissal entry.
4
+ import { createHash } from 'node:crypto';
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
7
+ import * as ts from 'typescript';
6
8
  import { pathToFileURL } from 'node:url';
7
9
  import { DiagnosticSeverity } from 'vscode-languageserver';
8
10
  import { exampleFor as reliabilityExample } from './reliability-examples.js';
@@ -169,14 +171,64 @@ function insideRoot(rootPath, file) {
169
171
  function defaultUri(filename) {
170
172
  return pathToFileURL(filename).href;
171
173
  }
172
- function location(rootPath, site, options) {
174
+ const dirtyLineMaps = new WeakMap();
175
+ // A report may stay published over several saves. Keep the original snapshot per reported site,
176
+ // retaining text only for findings of open buffers and only while their report is alive.
177
+ const reportedSources = new WeakMap();
178
+ const publishedSources = new WeakMap();
179
+ function liveLine(document, line, original, root) {
180
+ if (!document || (!document.isDirty && (!original || original.document === document)))
181
+ return line;
182
+ if (!original || (original.root !== root && !isRealPathInside(root, document.filename)))
183
+ return;
184
+ const saved = original.document;
185
+ let map = dirtyLineMaps.get(document);
186
+ if (map?.source !== saved) {
187
+ let prefix = 0;
188
+ let savedEnd = saved.lineCount;
189
+ let liveEnd = document.lineCount;
190
+ while (prefix < savedEnd && prefix < liveEnd && saved.lineAt(prefix).text === document.lineAt(prefix).text)
191
+ prefix++;
192
+ while (savedEnd > 0 && liveEnd > 0 && saved.lineAt(savedEnd - 1).text === document.lineAt(liveEnd - 1).text) {
193
+ savedEnd--;
194
+ liveEnd--;
195
+ }
196
+ // Equal lines at an insertion or deletion can belong to either side.
197
+ // Only positions common to both alignments have an unambiguous counterpart.
198
+ const overlap = saved.lineCount === document.lineCount ? 0 : Math.max(0, prefix - Math.min(savedEnd, liveEnd));
199
+ map = { source: saved, prefix: prefix - overlap, savedEnd: savedEnd + overlap, liveEnd: liveEnd + overlap };
200
+ dirtyLineMaps.set(document, map);
201
+ }
202
+ if (line <= map.prefix)
203
+ return line;
204
+ if (line > saved.lineCount)
205
+ return;
206
+ if (line > map.savedEnd)
207
+ return line + map.liveEnd - map.savedEnd;
208
+ if (map.savedEnd === map.prefix + 1 && map.liveEnd === map.prefix + 1)
209
+ return line;
210
+ }
211
+ function location(rootPath, site, options, reported) {
173
212
  if (!isLocatedSite(site))
174
213
  return;
175
214
  const filename = insideRoot(rootPath, site.file);
176
215
  if (filename === undefined)
177
216
  return;
178
217
  const uri = (options.uriFor ?? defaultUri)(filename);
179
- return { filename, uri, range: sourceRange(site, options.documentFor(filename)) };
218
+ const document = options.documentFor(filename);
219
+ const identity = reported ?? site;
220
+ let original = reportedSources.get(identity);
221
+ if (!original && document && document.version !== null && isRealPathInside(rootPath, filename)) {
222
+ const saved = document.isDirty ? options.savedDocumentFor?.(filename) : document;
223
+ if (saved) {
224
+ original = { root: rootPath, document: saved };
225
+ reportedSources.set(identity, original);
226
+ }
227
+ }
228
+ const line = liveLine(document, site.line, original, rootPath);
229
+ if (line === undefined)
230
+ return;
231
+ return { filename, uri, range: sourceRange({ line, column: site.column }, document), original };
180
232
  }
181
233
  // Resolves each change of a site fix inside the workspace folder; a path outside it, also through a
182
234
  // symbolic link, drops the whole fix.
@@ -212,6 +264,8 @@ function severityFor(finding, setting) {
212
264
  }
213
265
  function readSavedLines(filename) {
214
266
  try {
267
+ if (!fs.statSync(filename).isFile())
268
+ return [];
215
269
  return fs.readFileSync(filename, 'utf8').split(/\r?\n/);
216
270
  }
217
271
  catch {
@@ -222,6 +276,8 @@ function readSavedLines(filename) {
222
276
  // The trimmed text of the reported line identifies a dismissed finding. An edited buffer no longer
223
277
  // matches the scan, so its line is read from the saved file.
224
278
  function flaggedLineText(filename, line, options, savedLines) {
279
+ if (line < 1)
280
+ return '';
225
281
  const document = options.documentFor(filename);
226
282
  if (document && !document.isDirty)
227
283
  return line <= document.lineCount ? document.lineAt(line - 1).text.trim() : '';
@@ -251,9 +307,13 @@ function buildDiagnostic(site, finding, anchor, options) {
251
307
  const diagnostic = {
252
308
  range: site.range,
253
309
  message: preview ? preview + '\n' + anchor.message : anchor.message,
254
- severity: severityFor(finding, options.severity),
310
+ severity: severityFor(finding, options.severityFor ? options.severityFor(site.filename) : options.severity),
255
311
  source: anchor.source,
256
312
  code: finding.ruleId,
313
+ // LSP clients can preserve this identity while their tracked ranges move in an unsaved buffer.
314
+ data: createHash('sha256')
315
+ .update(JSON.stringify([anchor.line, anchor.column, anchor.dismissal.lineText, anchor.message]))
316
+ .digest('hex'),
257
317
  };
258
318
  const documentation = ruleDocUrl(finding.ruleId);
259
319
  if (documentation)
@@ -264,17 +324,16 @@ function publishedFinding(rootPath, source, reported, options, savedLines) {
264
324
  const finding = databaseFinding(reported);
265
325
  if (!isLocatedSite(finding) || typeof finding.message !== 'string' || typeof finding.ruleId !== 'string')
266
326
  return;
267
- const site = location(rootPath, finding, options);
327
+ const site = location(rootPath, finding, options, reported);
268
328
  if (!site)
269
329
  return;
270
330
  const lineText = finding === reported
271
- ? flaggedLineText(site.filename, finding.line, options, savedLines)
331
+ ? (site.original?.document.lineAt(finding.line - 1).text.trim() ??
332
+ flaggedLineText(site.filename, finding.line, options, savedLines))
272
333
  : typeof finding.target === 'string'
273
334
  ? finding.target
274
335
  : undefined;
275
336
  const dismissal = { file: site.filename, ruleId: finding.ruleId, lineText };
276
- if (options.isDismissed?.(dismissal))
277
- return;
278
337
  const anchor = {
279
338
  source,
280
339
  ruleId: finding.ruleId,
@@ -290,12 +349,122 @@ function publishedFinding(rootPath, source, reported, options, savedLines) {
290
349
  const related = relatedInformation(rootPath, finding, options);
291
350
  if (related)
292
351
  diagnostic.relatedInformation = related;
293
- return { filename: site.filename, uri: site.uri, diagnostic, anchor };
352
+ const entry = { filename: site.filename, uri: site.uri, diagnostic, anchor };
353
+ if (site.original)
354
+ publishedSources.set(entry, site.original);
355
+ return entry;
356
+ }
357
+ // Python reports use source lines rather than TypeScript nodes. Keep the enclosing declaration
358
+ // headers in the fingerprint so replacing the first function also invalidates its dismissal.
359
+ function indexPythonScopes(text) {
360
+ const declarations = [];
361
+ const scopes = text.split(/\r?\n/).map((line) => {
362
+ const code = line.trimStart();
363
+ const indent = line.length - code.length;
364
+ // A closing delimiter on a continuation line can align with its enclosing declaration.
365
+ if (code && !/^[#)\]}]/.test(code)) {
366
+ while (declarations.length && declarations[declarations.length - 1].indent >= indent)
367
+ declarations.pop();
368
+ }
369
+ const header = /^(?:(?:async\s+)?def|class)\s+([^\s(:[]+)/u.exec(code);
370
+ if (header) {
371
+ const names = [...(declarations.at(-1)?.names ?? []), header[1]];
372
+ declarations.push({ indent, names });
373
+ }
374
+ return declarations.at(-1)?.names ?? [];
375
+ });
376
+ return (line) => scopes[line - 1] ?? [];
377
+ }
378
+ // Walk a repeated-finding file once. Every named scope records its entry and exit offsets in
379
+ // source order, so lookups never rescan all sibling declarations for each diagnostic.
380
+ function indexScopes(file, text) {
381
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
382
+ const boundaries = [];
383
+ function visit(node, parents) {
384
+ const named = ts.isFunctionLike(node) ||
385
+ ts.isClassLike(node) ||
386
+ ts.isModuleDeclaration(node) ||
387
+ ts.isVariableDeclaration(node) ||
388
+ ts.isPropertyAssignment(node);
389
+ const names = named && node.name ? [...parents, node.name.getText(source)] : parents;
390
+ if (names !== parents)
391
+ boundaries.push({ offset: node.getStart(source), names });
392
+ ts.forEachChild(node, (child) => visit(child, names));
393
+ if (names !== parents)
394
+ boundaries.push({ offset: node.end, names: parents });
395
+ }
396
+ visit(source, []);
397
+ const starts = source.getLineStarts();
398
+ return (line, column) => {
399
+ const start = starts[line - 1];
400
+ if (start === undefined)
401
+ return [];
402
+ const offset = start + column - 1;
403
+ let lower = 0;
404
+ let upper = boundaries.length;
405
+ while (lower < upper) {
406
+ const middle = Math.floor((lower + upper) / 2);
407
+ if (boundaries[middle].offset <= offset)
408
+ lower = middle + 1;
409
+ else
410
+ upper = middle;
411
+ }
412
+ return boundaries[lower - 1]?.names ?? [];
413
+ };
414
+ }
415
+ function identifyOccurrences(matches, options, savedLines, scopesByFile) {
416
+ if (matches.length === 1) {
417
+ matches[0].dismissal.occurrence = '1/1';
418
+ return;
419
+ }
420
+ matches.sort((left, right) => left.line - right.line || left.column - right.column);
421
+ const file = matches[0].dismissal.file;
422
+ if (!scopesByFile.has(file) && /\.(?:[cm]?[jt]sx?|py)$/i.test(file)) {
423
+ const document = options.documentFor(file);
424
+ const text = document && !document.isDirty ? document.getText() : (savedLines.get(file) ?? []).join('\n');
425
+ scopesByFile.set(file, /\.py$/i.test(file) ? indexPythonScopes(text) : indexScopes(file, text));
426
+ }
427
+ const scopesAt = scopesByFile.get(file);
428
+ const contexts = matches.map(({ line, column }) => JSON.stringify([
429
+ scopesAt?.(line, column),
430
+ flaggedLineText(file, line - 1, options, savedLines),
431
+ column,
432
+ flaggedLineText(file, line + 1, options, savedLines),
433
+ ]));
434
+ const groupHash = createHash('sha256').update(JSON.stringify(contexts));
435
+ if (new Set(contexts).size < matches.length) {
436
+ // The intervening source distinguishes otherwise identical sites in separate scopes, without
437
+ // binding the dismissal to unrelated lines above or below the matching group.
438
+ const document = options.documentFor(file);
439
+ const lineCount = document && !document.isDirty ? document.lineCount : (savedLines.get(file)?.length ?? 0);
440
+ const lastLine = Math.min(matches[matches.length - 1].line, lineCount);
441
+ for (let line = matches[0].line; line <= lastLine; line++) {
442
+ groupHash.update('\n').update(flaggedLineText(file, line, options, savedLines));
443
+ }
444
+ }
445
+ const group = groupHash.digest('hex');
446
+ for (const [index, anchor] of matches.entries()) {
447
+ anchor.dismissal.occurrence = index + 1 + '/' + matches.length + '#' + group;
448
+ }
294
449
  }
295
450
  /** The diagnostics of one checker report, skipping findings outside the folder or dismissed. */
296
451
  function buildDiagnostics(rootPath, source, findings, options) {
297
452
  const savedLines = new Map();
298
- return findings.flatMap((finding) => publishedFinding(rootPath, source, finding, options, savedLines) ?? []);
453
+ const entries = findings.flatMap((finding) => publishedFinding(rootPath, source, finding, options, savedLines) ?? []);
454
+ const matchingLines = new Map();
455
+ for (const { anchor } of entries) {
456
+ const { file, ruleId, lineText } = anchor.dismissal;
457
+ const key = JSON.stringify([file, ruleId, lineText]);
458
+ const matches = matchingLines.get(key);
459
+ if (matches)
460
+ matches.push(anchor);
461
+ else
462
+ matchingLines.set(key, [anchor]);
463
+ }
464
+ const scopesByFile = new Map();
465
+ for (const matches of matchingLines.values())
466
+ identifyOccurrences(matches, options, savedLines, scopesByFile);
467
+ return entries.filter(({ anchor }) => !options.isDismissed?.(anchor.dismissal));
299
468
  }
300
469
  // The editor renders hovers as markdown; finding text is shown literally.
301
470
  function escapeMarkdown(text) {
@@ -320,13 +489,12 @@ function comparisonMarkdown(comparison, example, document, ruleId) {
320
489
  }
321
490
  return parts;
322
491
  }
323
- function hoverMarkdown(document, entry) {
324
- const { anchor, diagnostic } = entry;
325
- const { example, comparison } = examplesFor(document, diagnostic.range, anchor);
326
- if (!comparison && !example)
492
+ function hoverMarkdown(document, { anchor, diagnostic }, range) {
493
+ const { example, comparison } = examplesFor(document, range, anchor);
494
+ if (!comparison && !example && !anchor.message)
327
495
  return;
328
496
  const parts = [];
329
- const firstLine = recommendation(document, diagnostic.range, anchor);
497
+ const firstLine = recommendation(document, range, anchor);
330
498
  if (firstLine)
331
499
  parts.push('**' + escapeMarkdown(firstLine) + '**');
332
500
  parts.push(paragraphs(anchor.message));
@@ -338,20 +506,41 @@ function hoverMarkdown(document, entry) {
338
506
  const note = comparison ? comparison.note : example?.note;
339
507
  if (note)
340
508
  parts.push(paragraphs(note));
509
+ const docsHref = diagnostic.codeDescription?.href;
510
+ if (!comparison && !example && docsHref)
511
+ parts.push(`[${escapeMarkdown(anchor.ruleId)}](${docsHref})`);
341
512
  return parts.join('\n\n');
342
513
  }
514
+ function indentation(text) {
515
+ return text.length - text.trimStart().length;
516
+ }
343
517
  /** The hover for a position: one section per rule flagged there, or undefined. */
344
- function hoverFor(document, entries, position) {
518
+ function hoverFor(document, entries, position, root) {
345
519
  const sections = [];
346
520
  const shown = new Set();
347
521
  let hoverRange;
348
522
  const word = wordRangeAt(document, position);
523
+ const currentLine = document.lineAt(position.line).text.trim();
349
524
  for (const entry of entries) {
350
- const issueRange = entry.diagnostic.range;
525
+ let issueRange = entry.diagnostic.range;
526
+ const original = publishedSources.get(entry);
527
+ if (document.isDirty || (original && original.document !== document)) {
528
+ const originalText = original?.document.lineAt(entry.anchor.line - 1).text;
529
+ if (originalText?.trim() !== currentLine)
530
+ continue;
531
+ const line = liveLine(document, entry.anchor.line, original, root);
532
+ if (line !== position.line + 1)
533
+ continue;
534
+ // Indentation edits move the flagged token, so shift the saved column by the indent change.
535
+ const column = entry.anchor.column + indentation(document.lineAt(position.line).text) - indentation(originalText);
536
+ if (column < 1)
537
+ continue;
538
+ issueRange = sourceRange({ line, column }, document);
539
+ }
351
540
  const range = word && samePosition(word.start, issueRange.start) ? word : issueRange;
352
541
  if (!rangeContains(range, position) || shown.has(entry.anchor.ruleId))
353
542
  continue;
354
- const markdown = hoverMarkdown(document, entry);
543
+ const markdown = hoverMarkdown(document, entry, issueRange);
355
544
  if (!markdown)
356
545
  continue;
357
546
  sections.push(markdown);
@@ -5,16 +5,40 @@
5
5
  // can be shared through version control.
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
- import { writeFileAtomic } from '../shared/system/atomic-write.js';
9
- import { errorMessage } from '../shared/system/error-code.js';
8
+ import { unlinkWithRetry, writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
9
+ import { realTarget } from '../shared/system/real-target.js';
10
+ import { errorCode, errorMessage } from '../shared/system/error-code.js';
10
11
  import { isRecord } from '../shared/system/is-record.js';
11
- import { isRealPathInside } from './workspace-paths.js';
12
+ import { isInside, samePathSpelling } from './workspace-paths.js';
12
13
  const dismissalsPath = path.join('.loadwise', 'dismissed.json');
13
14
  // The file is read synchronously on every change to it; a file this large is not a list of
14
15
  // dismissals anyone curates, and parsing it would stall the server.
15
16
  const maxDismissalBytes = 4 * 1024 * 1024;
16
- function keyOf({ file, ruleId, lineText }) {
17
- return JSON.stringify([file, ruleId, lineText ?? null]);
17
+ // A real source line never contains a newline. Older clients preserve this string through writes,
18
+ // but cannot mistake an occurrence-specific dismissal for every statement with the same text.
19
+ const occurrenceMarker = '\nloadwise-occurrence:';
20
+ function keyOf({ file, ruleId, lineText, occurrence }) {
21
+ return JSON.stringify([file.toLowerCase(), ruleId, lineText ?? null, occurrence ?? null]);
22
+ }
23
+ function dismissalIndex(entries) {
24
+ const pathsByKey = new Map();
25
+ for (const entry of entries) {
26
+ const key = keyOf(entry);
27
+ const files = pathsByKey.get(key) ?? new Set();
28
+ files.add(entry.file);
29
+ pathsByKey.set(key, files);
30
+ }
31
+ return (entry) => {
32
+ const files = pathsByKey.get(keyOf(entry));
33
+ if (!files)
34
+ return false;
35
+ if (files.has(entry.file))
36
+ return true;
37
+ for (const file of files)
38
+ if (samePathSpelling(file, entry.file))
39
+ return true;
40
+ return false;
41
+ };
18
42
  }
19
43
  function storedEntry(root, stored) {
20
44
  if (!isRecord(stored) || typeof stored.file !== 'string' || typeof stored.ruleId !== 'string')
@@ -22,8 +46,17 @@ function storedEntry(root, stored) {
22
46
  if (stored.file.includes('\0'))
23
47
  return;
24
48
  const entry = { file: path.resolve(root, stored.file), ruleId: stored.ruleId };
25
- if (typeof stored.lineText === 'string')
26
- entry.lineText = stored.lineText;
49
+ if (typeof stored.lineText === 'string') {
50
+ const marker = stored.lineText.lastIndexOf(occurrenceMarker);
51
+ entry.lineText = marker < 0 ? stored.lineText : stored.lineText.slice(0, marker);
52
+ if (marker >= 0)
53
+ entry.occurrence = stored.lineText.slice(marker + occurrenceMarker.length);
54
+ }
55
+ if (stored.occurrence !== undefined) {
56
+ if (entry.lineText === undefined || typeof stored.occurrence !== 'string')
57
+ return;
58
+ entry.occurrence = stored.occurrence;
59
+ }
27
60
  return entry;
28
61
  }
29
62
  function readEntries(filename, root) {
@@ -44,10 +77,12 @@ function readEntries(filename, root) {
44
77
  return { entries: stored.flatMap((item) => storedEntry(root, item) ?? []) };
45
78
  }
46
79
  function serialize(root, entries) {
47
- const stored = entries.map(({ file, ruleId, lineText }) => ({
80
+ const stored = entries.map(({ file, ruleId, lineText, occurrence }) => ({
48
81
  file: path.relative(root, file).split(path.sep).join('/'),
49
82
  ruleId,
50
- ...(typeof lineText === 'string' ? { lineText } : {}),
83
+ ...(typeof lineText === 'string'
84
+ ? { lineText: occurrence ? lineText + occurrenceMarker + occurrence : lineText }
85
+ : {}),
51
86
  }));
52
87
  return JSON.stringify(stored, null, 2) + '\n';
53
88
  }
@@ -55,11 +90,11 @@ function createDismissals(root, { onProblem }) {
55
90
  const filename = path.join(root, dismissalsPath);
56
91
  const describe = (problem) => dismissalsPath.split(path.sep).join('/') + ' in ' + root + ' ' + problem + '.';
57
92
  let current = [];
58
- let keys = new Set();
93
+ let matches = dismissalIndex([]);
59
94
  let pendingWrite = Promise.resolve();
60
95
  function replace(next) {
61
96
  current = next;
62
- keys = new Set(current.map(keyOf));
97
+ matches = dismissalIndex(current);
63
98
  }
64
99
  // A file that does not parse keeps the dismissals already shown: it may be mid-rewrite by a
65
100
  // checkout, and an edit the user is still making should not flood the editor with findings.
@@ -74,19 +109,40 @@ function createDismissals(root, { onProblem }) {
74
109
  // one. The shown state changes only once the file holds it.
75
110
  function update(transform) {
76
111
  const next = pendingWrite
77
- .catch(() => { })
112
+ .catch(() => {
113
+ // A failed earlier write already reported its error to its own caller; this one starts afresh.
114
+ })
78
115
  .then(() => {
79
- const stored = readEntries(filename, root);
80
- if (stored.entries === undefined) {
81
- throw new Error(describe(stored.problem) + ' Fix or remove it, then try again; it was left unchanged.');
82
- }
83
- if (!isRealPathInside(root, filename)) {
116
+ const target = realTarget(filename);
117
+ if (!isInside(realTarget(root), target)) {
84
118
  throw new Error(describe('resolves outside the workspace folder') + ' Nothing was written.');
85
119
  }
86
- const entries = transform(stored.entries);
87
- fs.mkdirSync(path.dirname(filename), { recursive: true });
88
- writeFileAtomic(filename, serialize(root, entries));
89
- replace(entries);
120
+ fs.mkdirSync(path.dirname(target), { recursive: true });
121
+ const lock = target + '.lock';
122
+ let descriptor;
123
+ try {
124
+ descriptor = fs.openSync(lock, 'wx', 0o600);
125
+ }
126
+ catch (error) {
127
+ if (errorCode(error) !== 'EEXIST')
128
+ throw error;
129
+ throw new Error('A dismissal update is already locked. Retry after the other editor finishes. If all editors are closed, remove the stale lock at ' +
130
+ lock +
131
+ '.');
132
+ }
133
+ try {
134
+ const stored = readEntries(target, root);
135
+ if (stored.entries === undefined) {
136
+ throw new Error(describe(stored.problem) + ' Fix or remove it, then try again; it was left unchanged.');
137
+ }
138
+ const entries = transform(stored.entries);
139
+ writeResolvedFileAtomic(target, serialize(root, entries));
140
+ replace(entries);
141
+ }
142
+ finally {
143
+ fs.closeSync(descriptor);
144
+ unlinkWithRetry(lock);
145
+ }
90
146
  });
91
147
  pendingWrite = next;
92
148
  return next;
@@ -95,15 +151,18 @@ function createDismissals(root, { onProblem }) {
95
151
  return {
96
152
  entries: () => [...current],
97
153
  has(site) {
98
- return keys.has(keyOf(site)) || keys.has(keyOf({ file: site.file, ruleId: site.ruleId }));
154
+ if (matches(site) || matches({ file: site.file, ruleId: site.ruleId }))
155
+ return true;
156
+ // Older line-only entries are safe only when exactly one finding currently matches.
157
+ return site.occurrence === '1/1' && matches({ ...site, occurrence: undefined });
99
158
  },
100
159
  add(entry) {
101
- const key = keyOf(entry);
102
- return update((entries) => [...entries.filter((existing) => keyOf(existing) !== key), entry]);
160
+ const matchesNew = dismissalIndex([entry]);
161
+ return update((entries) => (entries.some(matchesNew) ? entries : [...entries, entry]));
103
162
  },
104
163
  remove(removed) {
105
- const gone = new Set(removed.map(keyOf));
106
- return update((entries) => entries.filter((entry) => !gone.has(keyOf(entry))));
164
+ const matchesRemoved = dismissalIndex(removed);
165
+ return update((entries) => entries.filter((entry) => !matchesRemoved(entry)));
107
166
  },
108
167
  reload: load,
109
168
  };
@@ -44,7 +44,7 @@ function createEditorDocument(filename, text, { languageId = languageIdOf(filena
44
44
  const lines = text.split(/\r?\n/);
45
45
  return {
46
46
  filename,
47
- languageId,
47
+ languageId: languageId === 'cs' ? 'csharp' : languageId,
48
48
  version,
49
49
  isDirty,
50
50
  eol: text.includes('\r\n') ? '\r\n' : '\n',
@@ -53,8 +53,11 @@ function createEditorDocument(filename, text, { languageId = languageIdOf(filena
53
53
  getText: () => text,
54
54
  };
55
55
  }
56
- function readDiskDocument(filename) {
56
+ function readDiskDocument(filename, maxBytes = Infinity) {
57
57
  try {
58
+ const stats = fs.statSync(filename);
59
+ if (!stats.isFile() || stats.size > maxBytes)
60
+ return;
58
61
  return createEditorDocument(filename, fs.readFileSync(filename, 'utf8'));
59
62
  }
60
63
  catch {
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
+ import { absoluteSetting } from './setup-server.js';
5
6
  const products = {
6
7
  'antigravity-ide': { folder: 'Antigravity IDE', app: 'Antigravity IDE.app', exe: 'Antigravity IDE.exe' },
7
8
  cursor: { folder: 'cursor', app: 'Cursor.app', exe: 'Cursor.exe' },
@@ -15,8 +16,12 @@ function pathDirectories() {
15
16
  function binDirectories(product) {
16
17
  const directories = pathDirectories();
17
18
  if (process.platform === 'win32') {
18
- const local = process.env.LOCALAPPDATA;
19
- const bases = [local && path.join(local, 'Programs'), process.env.ProgramFiles, process.env['ProgramFiles(x86)']];
19
+ const local = absoluteSetting(process.env.LOCALAPPDATA);
20
+ const bases = [
21
+ local && path.join(local, 'Programs'),
22
+ absoluteSetting(process.env.ProgramFiles),
23
+ absoluteSetting(process.env['ProgramFiles(x86)']),
24
+ ];
20
25
  for (const base of bases) {
21
26
  if (!base)
22
27
  continue;