loadwise 0.6.2 → 0.7.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 (86) hide show
  1. package/README.md +152 -100
  2. package/dist/bin/loadwise.js +126 -49
  3. package/dist/lib/accessibility/frontend-detect.js +6 -5
  4. package/dist/lib/accessibility/usage.js +10 -2
  5. package/dist/lib/editor/configured-setup.js +61 -0
  6. package/dist/lib/editor/editor-launcher.js +165 -0
  7. package/dist/lib/editor/fix-edits.js +19 -0
  8. package/dist/lib/editor/jetbrains-setup.js +53 -0
  9. package/dist/lib/editor/language-server.js +31 -14
  10. package/dist/lib/editor/managed-config.js +37 -0
  11. package/dist/lib/editor/native-setup.js +85 -0
  12. package/dist/lib/editor/release-vsix.js +61 -0
  13. package/dist/lib/editor/server-commands.js +2 -0
  14. package/dist/lib/editor/setup-server.js +87 -0
  15. package/dist/lib/editor/setup-vim.js +61 -0
  16. package/dist/lib/editor/setup.js +131 -0
  17. package/dist/lib/editor/stdio-setup.js +6 -0
  18. package/dist/lib/maintainability/cli/inputs.js +3 -2
  19. package/dist/lib/maintainability/cli.js +14 -5
  20. package/dist/lib/maintainability/examples.js +4 -0
  21. package/dist/lib/maintainability/rule-ids.js +3 -0
  22. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  23. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  24. package/dist/lib/performance/cli/changed-lines.js +8 -1
  25. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  26. package/dist/lib/performance/cli/cli-output.js +3 -0
  27. package/dist/lib/performance/cli.js +8 -4
  28. package/dist/lib/performance/datastores/pg-integrity.js +7 -0
  29. package/dist/lib/performance/datastores/pooling.js +6 -1
  30. package/dist/lib/performance/engine/native-syntax.js +3 -0
  31. package/dist/lib/performance/frontend/frontend-perf.js +80 -20
  32. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  33. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  34. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  35. package/dist/lib/performance/request/mongoose-lean.js +140 -53
  36. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  37. package/dist/lib/performance/request/phase5-ast.js +6 -7
  38. package/dist/lib/performance/request/phase5-rules.js +133 -13
  39. package/dist/lib/performance/request/request-handlers.js +120 -23
  40. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  41. package/dist/lib/performance/site-fixes/collections.js +1 -2
  42. package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
  43. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  44. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  45. package/dist/lib/reliability/react-bugs.js +11 -3
  46. package/dist/lib/reliability/usage.js +16 -5
  47. package/dist/lib/security/cli.js +15 -4
  48. package/dist/lib/shared/agent/agent-init.js +26 -4
  49. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  50. package/dist/lib/shared/agent/agent-session.js +6 -1
  51. package/dist/lib/shared/agent/agent-verify.js +54 -10
  52. package/dist/lib/shared/agent/review-delivery.js +1 -1
  53. package/dist/lib/shared/analysis/scan-cache.js +3 -2
  54. package/dist/lib/shared/check.js +172 -20
  55. package/dist/lib/shared/fix/fix-convergence.js +15 -29
  56. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  57. package/dist/lib/shared/fix/fix-imports.js +47 -38
  58. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  59. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  60. package/dist/lib/shared/fix/fix-presentation.js +4 -3
  61. package/dist/lib/shared/fix/fix-safety.js +26 -1
  62. package/dist/lib/shared/fix/fix-scope.js +82 -0
  63. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  64. package/dist/lib/shared/fix/project-file-access.js +17 -26
  65. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  66. package/dist/lib/shared/fix.js +215 -102
  67. package/dist/lib/shared/report-fp.js +93 -0
  68. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  69. package/dist/lib/shared/reporting/check-text.js +50 -0
  70. package/dist/lib/shared/reporting/pillars.js +45 -16
  71. package/dist/lib/shared/reporting/source-report.js +2 -0
  72. package/dist/lib/shared/system/atomic-write.js +5 -2
  73. package/dist/lib/shared/system/sentry.js +203 -0
  74. package/dist/lib/shared/system/shell-argument.js +5 -1
  75. package/dist/lib/shared/system/terminal-safe.js +3 -2
  76. package/dist/lib/shared/system/terminal-style.js +131 -0
  77. package/docs/assets/cli-workflow.gif +0 -0
  78. package/integrations/sublime/plugin.py +22 -0
  79. package/integrations/zed/Cargo.lock +845 -0
  80. package/integrations/zed/Cargo.toml +11 -0
  81. package/integrations/zed/extension.toml +11 -0
  82. package/integrations/zed/src/lib.rs +25 -0
  83. package/package.json +11 -3
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/commands/loadwise.md +11 -6
  86. package/schema/loadwise.config.schema.json +2 -0
@@ -3,47 +3,73 @@ import { packageManifest } from '../lib/shared/package-root.js';
3
3
  import { terminalSafe } from '../lib/shared/system/terminal-safe.js';
4
4
  const { version } = packageManifest;
5
5
  import { respawnWithLargerHeap, shouldRespawnWithLargerHeap } from '../lib/shared/system/heap-limit.js';
6
- const usage = `Usage:
7
- loadwise [check] [directory] [--only perf,rel,maint,sec,a11y | --skip perf,rel,maint,sec,a11y] [--json | --format text|json|sarif|github] [--include-contextual] [--staged | --changed-since git-ref] [--fail-on contract|all] [--min-impact low|medium|high|critical] [--config loadwise.config.json] [--ignore rule-id] [--workspace name|path ...] [--online] [--baseline [file] | --write-baseline [file]]
8
- loadwise perf [args...]
9
- loadwise rel [args...]
10
- loadwise maint [args...]
11
- loadwise sec [args...]
12
- loadwise a11y [args...]
13
- loadwise fix --yes [--json]
14
- loadwise fix --all [performance] [reliability] [maintainability] [security] [accessibility] [--json]
15
- loadwise fix --handoff [performance] [reliability] [maintainability] [security] [accessibility]
16
- loadwise explain <rule-id>
17
- loadwise lsp [--stdio]
18
- loadwise --version
19
- loadwise agent init [--mode ask|auto] [--hook [block|warn|off]]
20
- loadwise agent instructions
21
- loadwise agent mcp [directory] [--print-config]
22
- loadwise agent pending
23
- loadwise agent history [performance] [reliability] [maintainability] [security] [accessibility]
24
- loadwise agent verify [--save] [--checker perf|rel|maint|sec|a11y] --outcomes outcomes.json report.json [more-reports.json ...]
6
+ const crashReportOption = '--report-crashes';
7
+ const usage = `Usage: loadwise [command] [options]
25
8
 
26
- check, the default command, runs every checker (perf: performance, rel: reliability, maint: maintainability, sec: security, a11y: accessibility) on one directory (default: the current folder) and prints one titled report per checker, in that order. The accessibility checker reads JSX, HTML, Vue, Svelte and Angular templates and skips itself on a project without any.
27
- --only runs just the listed checkers and --skip runs all but them; both take a comma-separated list, and they cannot be combined.
28
- loadwise.config.json in the directory (or --config <file>) sets the default checkers, ignored paths, per-rule levels (off, warn, error) and each checker's policy; flags beat it. --ignore drops a rule's findings and can repeat.
29
- The performance, reliability and security checkers use the directory's tsconfig.json or jsconfig.json; in a monorepo root without one it checks every workspace package's config in one report (--workspace limits the checkers to named packages or folders); standalone JavaScript-only packages can use check and fix without a source config.
30
- --json prints one key per selected checker, { "performance": report, "reliability": report, "maintainability": report, "security": report, "accessibility": report }; a skipped or failed checker's report is null.
31
- --online adds the security checker's dependency vulnerability check, which sends package names and versions from the lockfile to the OSV database; without it the check is skipped with a note.
32
- --format sarif prints SARIF 2.1.0 with one run per checker for GitHub code scanning; --format github prints workflow annotations (::warning, ::error); --json is --format json.
33
- --include-contextual, --staged, --changed-since, --fail-on and --min-impact apply to every selected checker; without --fail-on each keeps its own default.
34
- --write-baseline records every selected checker's current findings in one file (default loadwise-baseline.json in the checked directory, a section per checker); --baseline reports only findings not in it and prints how many were hidden ("baselineHidden" in --json). Fixed findings leave the file on the next --write-baseline.
35
- check never changes source files: apply fixes with the printed \`loadwise perf --fix --only id\`, \`loadwise rel --fix --only id\`, \`loadwise maint --fix --only id\` \`loadwise sec --fix --only id\` and \`loadwise a11y --fix --only id\` commands.
36
- fix --yes applies automatic edits. fix --all also applies edits marked for review. Both accept checker names, for example loadwise fix --all performance security. With no names, both use the project's configured checkers.
37
- fix --json with --yes or --all records the applied hunks and outstanding findings in its output for review.
38
- perf, rel, maint, sec and a11y run one checker with its full command set; \`loadwise perf --help\`, \`loadwise rel --help\`, \`loadwise maint --help\` \`loadwise sec --help\` and \`loadwise a11y --help\` list their commands and flags.
39
- explain prints the rule's default impact, description and an illustrative change when available.
40
- lsp runs the language server on stdin and stdout for any editor with a Language Server Protocol client: findings from every checker as diagnostics, with hovers, fixes, dismissals and code lenses.
41
- Recognized coding-agent sessions receive review instructions automatically. agent instructions prints the review workflow. Optional agent init writes it into AGENTS.md and imports it from CLAUDE.md.
42
- An active agent can run check --json directly or use the loadwise_check MCP tool for a fresh offline report.
43
- Add --review to a combined check or bulk fix to keep its original report and print the same handoff for any coding agent. agent pending lists saved handoffs for this project.
44
- agent init --hook installs one git pre-commit hook that runs \`loadwise check --staged\`: block fails the commit on findings, warn only prints them, off removes the hook. --hook alone means warn.
45
- Exit codes: 0 passed, 1 a checker met its exit threshold, 2 invalid input or configuration in any checker.
9
+ Start here
10
+ loadwise check Scan the current project
11
+ loadwise check --uncommitted Scan your local changes
12
+ loadwise fix Preview automatic fixes
13
+ loadwise fix --apply Apply automatic fixes
14
+ loadwise explain <rule-id> Read about a finding's rule
15
+
16
+ Command help
17
+ loadwise check --help Scan scope, filters, and output
18
+ loadwise fix --help Fix selection and review modes
19
+ loadwise agent --help Agent setup, reports, and MCP
20
+ loadwise editor setup Set up editor diagnostics (see editor --help)
21
+ loadwise lsp [--stdio] Start the editor language server
22
+ loadwise report-fp --help Report a false positive
23
+
24
+ Checker help
25
+ loadwise perf --help Performance, databases, traces, and plans
26
+ loadwise rel --help Reliability, migrations, and API contracts
27
+ loadwise maint --help Maintainability and dependency graphs
28
+ loadwise sec --help Security and dependency advisories
29
+ loadwise a11y --help Accessibility
30
+
31
+ Running loadwise without a command runs check.
32
+ Use --version (or -v) for the installed version.
33
+ Prefix a command with ${crashReportOption} to opt in to crash reporting.
46
34
  Documentation: ${packageManifest.homepage}`;
35
+ const checkUsage = `Usage: loadwise check [directory] [options]
36
+
37
+ Scan the current directory or a project directory you supply.
38
+ The scan leaves source files untouched.
39
+
40
+ Examples
41
+ loadwise check
42
+ loadwise check --uncommitted
43
+ loadwise check --only perf,rel
44
+ loadwise check --changed-since origin/main --min-impact high
45
+
46
+ Scope and configuration
47
+ --only <checkers> Run the listed checkers
48
+ --skip <checkers> Run every other checker
49
+ --workspace <name|path> Scope the scan to a workspace (repeatable)
50
+ --uncommitted Check staged, unstaged and untracked changes since HEAD
51
+ --staged Check lines changed in the Git index
52
+ --changed-since <git-ref> Check lines changed since a Git ref
53
+ --config <file> Use a different Loadwise configuration
54
+ --online Query OSV with lockfile package names and versions
55
+
56
+ Reports and thresholds
57
+ --json Output JSON grouped by checker, with _coverage for skipped or partial checks
58
+ --format <text|json|sarif|github> Choose a report format
59
+ --include-contextual Show contextual findings and their reasons
60
+ --ignore <rule-id> Hide findings for a rule (repeatable)
61
+ --min-impact <level> Select low, medium, high, or critical and above
62
+ --fail-on <contract|all> Override each checker's exit threshold
63
+ --baseline [file] Report findings new since the baseline
64
+ --write-baseline [file] Record the current findings
65
+ --review Save the report and print an agent handoff
66
+
67
+ Use either --only or --skip with comma-separated checker names.
68
+ Checkers: perf, rel, maint, sec, a11y. Full names work too.
69
+ The default baseline path is loadwise-baseline.json.
70
+
71
+ Exit codes: 0 passed, 1 findings met the threshold, 2 incomplete scan or invalid input.
72
+ Use loadwise fix --help for fix options.`;
47
73
  // Each command loads only the code it needs, so a quick `--version` or `explain` does not pay for
48
74
  // the scanners.
49
75
  async function main(args) {
@@ -62,8 +88,12 @@ async function main(args) {
62
88
  return (await import('../lib/shared/fix.js')).runFix(rest);
63
89
  if (command === 'explain')
64
90
  return (await import('../lib/shared/explain.js')).runExplain(rest);
91
+ if (command === 'report-fp')
92
+ return (await import('../lib/shared/report-fp.js')).runReportFp(rest);
65
93
  if (command === 'lsp')
66
94
  return (await import('../lib/editor/language-server.js')).runLanguageServer(rest);
95
+ if (command === 'editor')
96
+ return (await import('../lib/editor/setup.js')).runEditor(rest);
67
97
  if (command === '--version' || command === '-v') {
68
98
  if (rest.length)
69
99
  throw new Error('Usage: loadwise --version');
@@ -76,29 +106,76 @@ async function main(args) {
76
106
  console.log(usage);
77
107
  return 0;
78
108
  }
79
- return (await import('../lib/shared/check.js')).runCheck(command === 'check' ? rest : args, usage);
109
+ if (command === 'check' && rest.length === 1 && (rest[0] === '--help' || rest[0] === '-h')) {
110
+ console.log(checkUsage);
111
+ return 0;
112
+ }
113
+ return (await import('../lib/shared/check.js')).runCheck(command === 'check' ? rest : args, checkUsage);
80
114
  }
81
115
  // perf, rel, maint, sec and a11y run in this process, whose default heap limit is too small for very large
82
116
  // projects. One re-spawn with a larger limit keeps their output and exit code the same; a limit the
83
117
  // user set is never replaced.
84
118
  const inProcessCheckers = new Set(['perf', 'rel', 'maint', 'sec', 'a11y']);
85
- function respawnIfHeapTooSmall(commandArgs) {
86
- if (!inProcessCheckers.has(commandArgs[0]) || !shouldRespawnWithLargerHeap())
87
- return false;
88
- respawnWithLargerHeap(import.meta.filename, commandArgs);
89
- return true;
119
+ const recognizedCommands = new Set([
120
+ 'check',
121
+ 'perf',
122
+ 'rel',
123
+ 'maint',
124
+ 'sec',
125
+ 'a11y',
126
+ 'fix',
127
+ 'explain',
128
+ 'report-fp',
129
+ 'lsp',
130
+ 'editor',
131
+ 'agent',
132
+ '--version',
133
+ '-v',
134
+ '--help',
135
+ '-h',
136
+ ]);
137
+ function normalizeCommandTag(rawCommand) {
138
+ return rawCommand && recognizedCommands.has(rawCommand) ? rawCommand : 'check';
90
139
  }
91
- function runMain(commandArgs) {
140
+ async function runMain(commandArgs, reportCrashesFlag) {
141
+ const command = normalizeCommandTag(commandArgs[0]);
142
+ const crashReportingRequested = reportCrashesFlag ||
143
+ Boolean(process.env.LOADWISE_SENTRY_DSN) ||
144
+ process.env.LOADWISE_CRASH_REPORTS === '1' ||
145
+ process.env.LOADWISE_CRASH_REPORTS === 'true';
146
+ if (crashReportingRequested) {
147
+ const { installGlobalCrashHandlers, resolveCrashReportTarget } = await import('../lib/shared/system/sentry.js');
148
+ installGlobalCrashHandlers(command, resolveCrashReportTarget({ flagEnabled: reportCrashesFlag }));
149
+ }
92
150
  main(commandArgs)
93
151
  .then(async (code) => {
94
152
  process.exitCode = code;
95
153
  (await import('../lib/shared/agent/agent-session.js')).promptReview(commandArgs);
96
154
  })
97
- .catch((error) => {
155
+ .catch(async (error) => {
98
156
  console.error(terminalSafe(error instanceof Error ? error.message : String(error)));
157
+ const { isExpectedCliError, reportCrash, resolveCrashReportTarget } = await import('../lib/shared/system/sentry.js');
158
+ if (!isExpectedCliError(error)) {
159
+ const target = resolveCrashReportTarget({ flagEnabled: reportCrashesFlag });
160
+ if (target) {
161
+ const sent = await reportCrash(error, command, target);
162
+ if (sent) {
163
+ console.error('Sent a crash report with Loadwise diagnostic metadata.');
164
+ }
165
+ }
166
+ else {
167
+ console.error('Unexpected Loadwise error. Prefix the command with --report-crashes (or set LOADWISE_CRASH_REPORTS=1) to send a crash report with Loadwise diagnostic metadata.');
168
+ }
169
+ }
99
170
  process.exitCode = 2;
100
171
  });
101
172
  }
102
173
  const args = process.argv.slice(2);
103
- if (!respawnIfHeapTooSmall(args))
104
- runMain(args);
174
+ const reportCrashesFlag = args[0] === crashReportOption;
175
+ const commandArgs = reportCrashesFlag ? args.slice(1) : args;
176
+ if (inProcessCheckers.has(commandArgs[0] ?? '') && shouldRespawnWithLargerHeap()) {
177
+ respawnWithLargerHeap(import.meta.filename, args);
178
+ }
179
+ else {
180
+ void runMain(commandArgs, reportCrashesFlag);
181
+ }
@@ -22,16 +22,17 @@ const frontendPackages = new Set([
22
22
  'lit',
23
23
  ]);
24
24
  const dependencyFields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
25
- function dependsOnFrontendPackage(manifestFile) {
25
+ function mayDependOnFrontendPackage(manifestFile) {
26
26
  let manifest;
27
27
  try {
28
28
  manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
29
29
  }
30
30
  catch {
31
- return false;
31
+ // Unreadable dependencies cannot establish that accessibility is inapplicable.
32
+ return true;
32
33
  }
33
34
  if (!isRecord(manifest))
34
- return false;
35
+ return true;
35
36
  return dependencyFields.some((field) => {
36
37
  const dependencies = manifest[field];
37
38
  return isRecord(dependencies) && Object.keys(dependencies).some((name) => frontendPackages.has(name));
@@ -78,7 +79,7 @@ function hasFrontendSources(directory) {
78
79
  if (known !== undefined)
79
80
  return known;
80
81
  const found = listFrontendCandidateFiles(resolved).some((file) => frontendFilePattern.test(file) ||
81
- (path.posix.basename(file) === 'package.json' && dependsOnFrontendPackage(path.join(resolved, file))));
82
+ (path.posix.basename(file) === 'package.json' && mayDependOnFrontendPackage(path.join(resolved, file))));
82
83
  frontendByDirectory.set(resolved, found);
83
84
  return found;
84
85
  }
@@ -93,7 +94,7 @@ function hasFrontendSourcesInWorkspaces(directory, selectors) {
93
94
  }
94
95
  catch {
95
96
  // An unmatched selector is reported by the checker itself.
96
- return hasFrontendSources(directory);
97
+ return true;
97
98
  }
98
99
  }
99
100
  export { hasFrontendSources, hasFrontendSourcesInWorkspaces, listFrontendCandidateFiles };
@@ -1,6 +1,14 @@
1
1
  const accessibilityUsage = `Usage:
2
- loadwise a11y [-p tsconfig.json | -p monorepo-root [--workspace name|path ...] | file.tsx file.html file.vue ...] [--engine auto|native|js] [--loadwise-config loadwise.config.json] [--json | --format text|json|sarif|github] [--include-contextual] [--ignore rule-id] [--min-impact low|medium|high|critical] [--fail-on all|contract] [--baseline [file] | --write-baseline [file]] [--fix [--yes | --only id,...] [--no-comments] [--no-format]]
3
- loadwise a11y [-p tsconfig.json] (--staged | --changed-since git-ref) [--json] [--include-contextual] [--ignore rule-id]
2
+ loadwise a11y [-p <project> | <files...>] [options]
3
+
4
+ Scan options
5
+ -p <project> --workspace <name|path> --engine <auto|native|js>
6
+ --loadwise-config <file> --ignore <rule-id>
7
+ --staged | --changed-since <git-ref>
8
+ --json | --format <text|json|sarif|github> --include-contextual
9
+ --min-impact <low|medium|high|critical> --fail-on <all|contract>
10
+ --baseline [file] | --write-baseline [file]
11
+ --fix [--yes | --only <ids>] [--no-comments] [--no-format]
4
12
 
5
13
  The accessibility checker finds markup that people using screen readers, keyboards or zoom cannot use: images without alt text, unlabelled form controls, click handlers on non-interactive elements, invalid ARIA, missing page language and similar.
6
14
  It reads JSX and inline Angular templates from the TypeScript program, and .html, .htm, .vue and .svelte files from the project folders (ignored folders, build output and the config's "ignore" paths are left out). Name markup files on the command line to check just those.
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { packagePath } from '../shared/package-root.js';
5
+ import { writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
6
+ import { editorDataDirectory, ensureEditorServer } from './setup-server.js';
7
+ function copyTemplate(relative, destination) {
8
+ const content = fs.readFileSync(packagePath('integrations', relative), 'utf8');
9
+ writeResolvedFileAtomic(destination, content);
10
+ }
11
+ function prepareZed(directory, server) {
12
+ fs.mkdirSync(path.join(directory, 'src'), { recursive: true });
13
+ for (const file of ['extension.toml', 'Cargo.toml', 'Cargo.lock', 'src/lib.rs']) {
14
+ copyTemplate('zed/' + file, path.join(directory, file));
15
+ }
16
+ writeResolvedFileAtomic(path.join(directory, 'server.json'), JSON.stringify([server.command, server.args[0]]));
17
+ return [
18
+ 'In Zed run “zed: install dev extension” and select:',
19
+ directory,
20
+ 'Zed compiles the extension using Rust installed via rustup. Open a supported file in a project folder.',
21
+ ].join('\n');
22
+ }
23
+ function sublimePackages() {
24
+ const home = os.homedir();
25
+ if (process.platform === 'win32')
26
+ return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Sublime Text', 'Packages');
27
+ if (process.platform === 'darwin')
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');
30
+ }
31
+ const sublimePackage = 'LSP-loadwise';
32
+ function prepareSublime(directory, server, packages) {
33
+ fs.mkdirSync(directory, { recursive: true });
34
+ const settings = {
35
+ command: ['${loadwise_node}', '${loadwise_cli}', 'lsp', '--stdio'],
36
+ selector: 'source.js, source.jsx, source.ts, source.tsx, text.html, source.vue, source.svelte, source.python, source.go, source.java, source.cs, source.rust',
37
+ schemes: ['file'],
38
+ };
39
+ writeResolvedFileAtomic(path.join(directory, sublimePackage + '.sublime-settings'), JSON.stringify(settings, null, 2));
40
+ writeResolvedFileAtomic(path.join(directory, 'runtime.json'), JSON.stringify({ loadwise_node: server.command, loadwise_cli: server.args[0] }));
41
+ // Sublime isolates Python hosts. LSP and its helper must load in the same host.
42
+ writeResolvedFileAtomic(path.join(directory, '.python-version'), '3.8\n');
43
+ copyTemplate('sublime/plugin.py', path.join(directory, 'plugin.py'));
44
+ const prerequisite = 'Install LSP with Package Control, then open a project folder and a supported source file.';
45
+ if (!fs.statSync(packages, { throwIfNoEntry: false })?.isDirectory())
46
+ return `In Sublime Text open Preferences > Browse Packages and copy this folder there:\n${directory}\n${prerequisite}`;
47
+ const target = path.join(packages, sublimePackage);
48
+ const existing = fs.lstatSync(target, { throwIfNoEntry: false });
49
+ if (!existing)
50
+ fs.symlinkSync(directory, target, process.platform === 'win32' ? 'junction' : 'dir');
51
+ else if (!existing.isSymbolicLink() || fs.realpathSync(target) !== fs.realpathSync(directory))
52
+ throw new Error(`Another Sublime package already exists at ${target}. The generated Loadwise package is at ${directory}.`);
53
+ return `Registered ${sublimePackage} in ${packages}.\n${prerequisite}`;
54
+ }
55
+ export async function setupConfiguredEditor(editor) {
56
+ const server = await ensureEditorServer();
57
+ const root = editorDataDirectory();
58
+ return editor === 'zed'
59
+ ? prepareZed(path.join(root, 'zed'), server)
60
+ : prepareSublime(path.join(root, 'sublime', sublimePackage), server, sublimePackages());
61
+ }
@@ -0,0 +1,165 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ const products = {
6
+ 'antigravity-ide': { folder: 'Antigravity IDE', app: 'Antigravity IDE.app', exe: 'Antigravity IDE.exe' },
7
+ cursor: { folder: 'cursor', app: 'Cursor.app', exe: 'Cursor.exe' },
8
+ windsurf: { folder: 'Windsurf', app: 'Windsurf.app', exe: 'Windsurf.exe' },
9
+ code: { folder: 'Microsoft VS Code', app: 'Visual Studio Code.app', exe: 'Code.exe' },
10
+ codium: { folder: 'VSCodium', app: 'VSCodium.app', exe: 'VSCodium.exe' },
11
+ };
12
+ function pathDirectories() {
13
+ return (process.env.PATH ?? '').split(path.delimiter).filter((dir) => path.isAbsolute(dir));
14
+ }
15
+ function binDirectories(product) {
16
+ const directories = pathDirectories();
17
+ 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)']];
20
+ for (const base of bases) {
21
+ if (!base)
22
+ continue;
23
+ const root = path.join(base, products[product].folder);
24
+ directories.push(path.join(root, 'bin'), path.join(root, 'resources', 'app', 'bin'));
25
+ }
26
+ }
27
+ if (process.platform === 'darwin') {
28
+ for (const base of ['/Applications', path.join(os.homedir(), 'Applications')])
29
+ directories.push(path.join(base, products[product].app, 'Contents', 'Resources', 'app', 'bin'));
30
+ }
31
+ return directories;
32
+ }
33
+ function locate(product) {
34
+ for (const directory of binDirectories(product)) {
35
+ const file = path.join(directory, process.platform === 'win32' ? product + '.cmd' : product);
36
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile())
37
+ continue;
38
+ if (process.platform !== 'win32') {
39
+ if (fs.statSync(file).mode & 0o111)
40
+ return { product, executable: file, args: [] };
41
+ continue;
42
+ }
43
+ // Windows distributions may move the CLI under a build hash. Read the official
44
+ // launcher's relative path, then execute Electron directly with an argument array.
45
+ const launch = /^"%~dp0((?:\.\.\\){1,3}[^"\\]+\.exe)"\s+"%~dp0((?:\.\.\\){1,3}(?:[\da-f]+\\)?(?:resources\\app\\)?out\\cli\.js)"(?:\s|$)/im.exec(fs.readFileSync(file, 'utf8'));
46
+ if (!launch || path.basename(launch[1]).toLowerCase() !== products[product].exe.toLowerCase())
47
+ continue;
48
+ const executable = path.resolve(directory, launch[1]);
49
+ const script = path.resolve(directory, launch[2]);
50
+ if (fs.existsSync(executable) && fs.existsSync(script))
51
+ return { product, executable, args: [script] };
52
+ }
53
+ }
54
+ function terminalProduct() {
55
+ const evidence = [
56
+ process.env.VSCODE_GIT_ASKPASS_NODE,
57
+ process.env.VSCODE_GIT_ASKPASS_MAIN,
58
+ process.env.__CFBundleIdentifier,
59
+ process.env.TERM_PROGRAM,
60
+ ]
61
+ .filter(Boolean)
62
+ .join('\n');
63
+ if (/antigravity[ -]ide/i.test(evidence))
64
+ return 'antigravity-ide';
65
+ if (/windsurf/i.test(evidence))
66
+ return 'windsurf';
67
+ if (/cursor/i.test(evidence))
68
+ return 'cursor';
69
+ if (/vscodium|com\.vscodium\.codium|[/\\]codium[/\\]/i.test(evidence))
70
+ return 'codium';
71
+ if (/visual studio code|microsoft vs code|com\.microsoft\.vscode|[/\\]code(?:\.exe|[/\\]resources)/i.test(evidence))
72
+ return 'code';
73
+ // Both products set TERM_PROGRAM=vscode in integrated terminals.
74
+ }
75
+ export function isProduct(value) {
76
+ return Object.hasOwn(products, value);
77
+ }
78
+ async function chooseEditor(available) {
79
+ const names = available.join(', ');
80
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
81
+ throw new Error(`Choose one of the detected editors with --editor: ${names}. See loadwise editor --help for all integrations.`);
82
+ const input = createInterface({ input: process.stdin, output: process.stdout });
83
+ try {
84
+ const choices = available.map((product, index) => `${index + 1}) ${product}`).join(' ');
85
+ process.stdout.write(`Install Loadwise in which editor? ${choices}\nEnter a name or number: `);
86
+ for await (const line of input) {
87
+ const answer = line.trim().toLowerCase();
88
+ const selected = available.find((product, index) => answer === product || answer === String(index + 1));
89
+ if (selected)
90
+ return selected;
91
+ break;
92
+ }
93
+ throw new Error(`Invalid editor selection. Use --editor with one of: ${names}.`);
94
+ }
95
+ finally {
96
+ input.close();
97
+ }
98
+ }
99
+ export function editorLauncher(product) {
100
+ const launcher = locate(product);
101
+ if (launcher)
102
+ return launcher;
103
+ throw new Error(`Cannot find the ${product} editor CLI. Add its bin directory to PATH or use Install from VSIX in the editor.`);
104
+ }
105
+ const nativeCommands = {
106
+ nvim: ['nvim'],
107
+ helix: ['hx', 'helix'],
108
+ vim: ['vim', 'gvim'],
109
+ emacs: ['emacs', 'emacsclient'],
110
+ jetbrains: [
111
+ 'idea',
112
+ 'idea64',
113
+ 'pycharm',
114
+ 'pycharm64',
115
+ 'webstorm',
116
+ 'goland',
117
+ 'clion',
118
+ 'rider',
119
+ 'rustrover',
120
+ 'rubymine',
121
+ 'phpstorm',
122
+ 'datagrip',
123
+ ],
124
+ zed: ['zed'],
125
+ sublime: ['subl', 'sublime_text'],
126
+ };
127
+ function hasNativeExecutable(command, directories) {
128
+ const suffixes = process.platform === 'win32' ? ['.exe', '.cmd', '.bat'] : [''];
129
+ return directories.some((directory) => suffixes.some((suffix) => {
130
+ const file = fs.statSync(path.join(directory, command + suffix), { throwIfNoEntry: false });
131
+ return file?.isFile() && (process.platform === 'win32' || (file.mode & 0o111) !== 0);
132
+ }));
133
+ }
134
+ export async function detectEditor(vsixOnly) {
135
+ const preferred = (!vsixOnly && nativeTerminal()) || terminalProduct();
136
+ if (preferred)
137
+ return preferred;
138
+ const available = Object.keys(products)
139
+ .filter(isProduct)
140
+ .filter((product) => locate(product));
141
+ if (!vsixOnly) {
142
+ const directories = pathDirectories();
143
+ for (const [editor, commands] of Object.entries(nativeCommands)) {
144
+ if (commands.some((command) => hasNativeExecutable(command, directories)))
145
+ available.push(editor);
146
+ }
147
+ }
148
+ if (available.length === 1)
149
+ return available[0];
150
+ if (available.length > 1)
151
+ return chooseEditor(available);
152
+ throw new Error('--editor must be supplied when no supported editor is detected. See loadwise editor --help for the full --editor list.');
153
+ }
154
+ function nativeTerminal() {
155
+ if (process.env.NVIM)
156
+ return 'nvim';
157
+ if (process.env.VIM_TERMINAL)
158
+ return 'vim';
159
+ if (process.env.INSIDE_EMACS)
160
+ return 'emacs';
161
+ if (process.env.TERM_PROGRAM?.toLowerCase() === 'zed')
162
+ return 'zed';
163
+ if (process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm')
164
+ return 'jetbrains';
165
+ }
@@ -4,6 +4,8 @@
4
4
  // editor, so undo restores the original code.
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import { currentText } from '../shared/fix/read-fix-text.js';
8
+ import { errorMessage } from '../shared/system/error-code.js';
7
9
  import { isChangeApplied, locateChange } from './apply-fix.js';
8
10
  const staleFixMessage = 'The code changed since the last scan. Save the file to rescan, then try again.';
9
11
  const noCreateMessage = 'This editor cannot create files through the language server, so the fix was not applied.';
@@ -125,8 +127,22 @@ function workspaceEdit(operations, workspace) {
125
127
  }
126
128
  return { edit: { changes: plainChanges(operations, workspace) }, createdFiles };
127
129
  }
130
+ // The editor may supply a decoded buffer even if the original bytes cannot be saved as UTF-8.
131
+ function fixTargetError(fixes) {
132
+ const targets = new Set(fixes.flatMap((fix) => fix.changes.map((change) => change.filename)));
133
+ try {
134
+ for (const file of targets)
135
+ currentText(file);
136
+ }
137
+ catch (error) {
138
+ return errorMessage(error);
139
+ }
140
+ }
128
141
  /** The edit applying one fix, or why it cannot apply. */
129
142
  function fixEdit(fix, workspace) {
143
+ const error = fixTargetError([fix]);
144
+ if (error)
145
+ return { error };
130
146
  const plan = planFix(fix, workspace);
131
147
  if (plan.operations === undefined)
132
148
  return plan;
@@ -169,6 +185,9 @@ function bulkFixesFor(entries) {
169
185
  // Every applicable fix in one edit, so one undo reverts them all. Stale fixes, fixes that would
170
186
  // create an existing file, and fixes overlapping an earlier one are skipped whole.
171
187
  function fixAllEdit(fixes, workspace) {
188
+ const error = fixTargetError(fixes);
189
+ if (error)
190
+ return { ...workspaceEdit([], workspace), applied: 0, skipped: fixes.length, error };
172
191
  const claimed = new Map();
173
192
  const operations = [];
174
193
  let applied = 0;
@@ -0,0 +1,53 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
4
+ import { editorDataDirectory, ensureEditorServer } from './setup-server.js';
5
+ const languageExtensions = {
6
+ javascript: ['js', 'mjs', 'cjs'],
7
+ javascriptreact: ['jsx'],
8
+ typescript: ['ts', 'mts', 'cts'],
9
+ typescriptreact: ['tsx'],
10
+ html: ['html', 'htm'],
11
+ vue: ['vue'],
12
+ svelte: ['svelte'],
13
+ python: ['py'],
14
+ go: ['go'],
15
+ java: ['java'],
16
+ csharp: ['cs'],
17
+ rust: ['rs'],
18
+ ruby: ['rb'],
19
+ php: ['php'],
20
+ kotlin: ['kt', 'kts'],
21
+ c: ['c', 'h'],
22
+ cpp: ['cc', 'cpp', 'cxx', 'hh', 'hpp', 'hxx'],
23
+ };
24
+ // LSP4IJ accepts a command line, and starts it directly. Quote paths for IntelliJ's argument parser.
25
+ function quotePath(filename) {
26
+ const portable = filename.split(path.sep).join('/');
27
+ return '"' + portable.replaceAll('"', '\\"') + '"';
28
+ }
29
+ export function writeJetBrainsTemplate(directory, node, cli) {
30
+ const template = {
31
+ id: 'loadwise',
32
+ name: 'Loadwise',
33
+ programArgs: { default: `${quotePath(node)} ${quotePath(cli)} lsp --stdio` },
34
+ fileTypeMappings: Object.entries(languageExtensions).map(([languageId, extensions]) => ({
35
+ fileType: { patterns: extensions.map((extension) => '*.' + extension) },
36
+ languageId,
37
+ })),
38
+ };
39
+ fs.mkdirSync(directory, { recursive: true });
40
+ writeResolvedFileAtomic(path.join(directory, 'template.json'), JSON.stringify(template, null, 2) + '\n');
41
+ }
42
+ export async function setupJetBrains() {
43
+ const { command, args } = await ensureEditorServer();
44
+ const directory = path.join(editorDataDirectory(), 'jetbrains', 'loadwise');
45
+ writeJetBrainsTemplate(directory, command, args[0]);
46
+ return [
47
+ 'Install the LSP4IJ plugin from Settings > Plugins in your JetBrains IDE.',
48
+ 'In the LSP4IJ language server settings, choose +, then Template > Import from custom template.',
49
+ 'Select this folder and confirm the Loadwise server:',
50
+ directory,
51
+ 'Open a supported source file and check the Loadwise server in the LSP Consoles tool window.',
52
+ ].join('\n');
53
+ }