@mrclrchtr/supi-code-intelligence 11.0.1 → 11.1.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 (100) hide show
  1. package/README.md +41 -4
  2. package/gradle-helper/README.md +48 -0
  3. package/gradle-helper/build.sh +73 -0
  4. package/gradle-helper/lib/gradle-tooling-api-9.4.0.jar +0 -0
  5. package/gradle-helper/lib/slf4j-api-2.0.17.jar +0 -0
  6. package/gradle-helper/lib/slf4j-simple-2.0.17.jar +0 -0
  7. package/gradle-helper/lib/supi-gradle-observation.jar +0 -0
  8. package/gradle-helper/licenses/DEPENDENCIES.md +11 -0
  9. package/gradle-helper/licenses/LICENSE-gradle-tooling-api.txt +422 -0
  10. package/gradle-helper/licenses/LICENSE-slf4j.txt +21 -0
  11. package/gradle-helper/licenses/NOTICE-gradle.txt +21 -0
  12. package/gradle-helper/src/GradleObservation.java +597 -0
  13. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  14. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  15. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  16. package/node_modules/@mrclrchtr/supi-lsp/README.md +1 -1
  17. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  18. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  19. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  20. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/README.md +5 -0
  21. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/browser/ril.js +8 -0
  22. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/connection.js +7 -2
  23. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/ral.d.ts +8 -0
  24. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.d.ts +14 -0
  25. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.js +6 -4
  26. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/ril.js +5 -1
  27. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/package.json +4 -2
  28. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/package.json +4 -3
  29. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/lib/esm/main.js +2 -2
  30. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/lib/umd/main.js +2 -2
  31. package/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/package.json +2 -1
  32. package/node_modules/@mrclrchtr/supi-lsp/package.json +6 -6
  33. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +21 -0
  34. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +1 -1
  35. package/node_modules/@mrclrchtr/supi-tree-sitter/README.md +1 -0
  36. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  37. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  38. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +41 -1
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +5 -3
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/LICENSE +21 -0
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm +0 -0
  42. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm.json +19 -2
  43. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/LICENSE +21 -0
  44. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm +0 -0
  45. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm.json +19 -2
  46. package/node_modules/ignore/README.md +36 -10
  47. package/node_modules/ignore/index.d.ts +3 -2
  48. package/node_modules/ignore/index.js +57 -53
  49. package/node_modules/ignore/legacy.js +50 -46
  50. package/node_modules/ignore/package.json +1 -1
  51. package/package.json +11 -6
  52. package/src/analysis/gradle/query.ts +273 -0
  53. package/src/analysis/gradle/runtime.ts +173 -0
  54. package/src/analysis/gradle/types.ts +65 -0
  55. package/src/analysis/read-next.ts +1 -4
  56. package/src/analysis/refactor/apply.ts +2 -2
  57. package/src/analysis/refactor/mutation-authority.ts +4 -1
  58. package/src/analysis/search/ast-scan.ts +143 -18
  59. package/src/analysis/workspace/safe-path.ts +14 -2
  60. package/src/analysis/workspace/types.ts +2 -0
  61. package/src/extension.ts +10 -1
  62. package/src/gradle/consent.ts +279 -0
  63. package/src/headless.ts +3 -0
  64. package/src/overview/collect.ts +11 -3
  65. package/src/session/orientation/workspace-context.ts +49 -28
  66. package/src/session/orientation-types.ts +11 -1
  67. package/src/session/orientation-workflow.ts +2 -0
  68. package/src/session/session.ts +8 -0
  69. package/src/tool/code_find/execute.ts +1 -1
  70. package/src/tool/code_find/markdown.ts +24 -17
  71. package/src/tool/code_find/result.ts +18 -5
  72. package/src/tool/code_find/spec.ts +2 -0
  73. package/src/tool/code_find/structured.ts +161 -0
  74. package/src/tool/code_graph/result.ts +32 -15
  75. package/src/tool/code_graph/spec.ts +2 -0
  76. package/src/tool/code_graph/structured.ts +142 -0
  77. package/src/tool/code_health/markdown.ts +5 -15
  78. package/src/tool/code_inspect/markdown.ts +19 -11
  79. package/src/tool/code_inspect/result.ts +1 -0
  80. package/src/tool/code_orientation/directory-navigation.ts +66 -0
  81. package/src/tool/code_orientation/gradle-sections.ts +68 -0
  82. package/src/tool/code_orientation/markdown.ts +19 -8
  83. package/src/tool/code_orientation/result.ts +89 -11
  84. package/src/tool/code_orientation/workspace-format.ts +2 -1
  85. package/src/tool/code_orientation/workspace-output.ts +40 -13
  86. package/src/tool/code_orientation/workspace-projects.ts +170 -50
  87. package/src/tool/code_orientation/workspace-sections.ts +3 -1
  88. package/src/tool/code_resolve/markdown.ts +4 -10
  89. package/src/tool/code_resolve/result.ts +2 -0
  90. package/src/tool/code_resolve/spec.ts +2 -0
  91. package/src/tool/code_resolve/structured.ts +103 -0
  92. package/src/tool/infra/truncate.ts +12 -4
  93. package/src/tool/register.ts +10 -6
  94. package/src/tool/result/display.ts +17 -0
  95. package/src/tool/result/model-budget.ts +195 -0
  96. package/src/tool/result/structured.ts +62 -0
  97. package/src/tool/result/types.ts +10 -2
  98. package/src/tool/specs.ts +2 -0
  99. package/src/types/execution.ts +5 -1
  100. package/src/ui/tui/display.ts +10 -4
@@ -26,6 +26,8 @@ var ESCAPE = '\\';
26
26
  var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
27
27
  var BOM = "\uFEFF";
28
28
  var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
29
+ // A run of two or more asterisks is a globstar (#175)
30
+ var REGEX_ANCHORED_GLOBSTAR = /^\/\*{2,}$/;
29
31
  var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
30
32
  var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
31
33
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
@@ -386,6 +388,18 @@ var REPLACERS = [
386
388
  /(\\+)( ?)/g, function (_, run, space) {
387
389
  return space ? run.slice(0, run.length - run.length % 2) + SPACE : run;
388
390
  }, ESCAPE + SPACE],
391
+ // git's wildmatch() reads a run of two or more asterisks as one globstar
392
+ // whenever the run fills a path segment: it starts the pattern or follows
393
+ // a `/`, and it ends the pattern or comes before a `/`. A run of two is
394
+ // already `**`; a longer one is folded into `**` here, so the steps
395
+ // below only ever have to know `**`.
396
+ // `***/foo` -> `**/foo`, `a/***/b` -> `a/**/b`, `a/***` -> `a/**`
397
+ // git also takes a run beside a literal prefix (`a***/b`) or beside an
398
+ // escaped slash (`***\/b`) as a globstar, and this does not; the README
399
+ // lists both, under "A run of asterisks".
400
+ [/(^|\/)\*{3,}(?=\/|$)/g, function (_, start) {
401
+ return "".concat(start, "**");
402
+ }, '*'],
389
403
  // Escape metacharacters
390
404
  // which is written down by users but means special for regular expressions.
391
405
 
@@ -754,6 +768,14 @@ var pinWildcards = function pinWildcards(source) {
754
768
 
755
769
  // @param {pattern}
756
770
  var makeRegexPrefix = function makeRegexPrefix(pattern) {
771
+ // `/**` matches every path, as `**` does. The translation below only finds
772
+ // a globstar beside a slash it keeps, and the leading one is turned into
773
+ // an anchor, so `/**` would come out as `/*` and match one level only.
774
+ // Here rather than in `createRule`, so that `checkSourceOf`, which
775
+ // compiles `/**/` again without its trailing slash, gets it too.
776
+ if (REGEX_ANCHORED_GLOBSTAR.test(pattern)) {
777
+ pattern = '**';
778
+ }
757
779
  var _extractBrackets = extractBrackets(pattern),
758
780
  source = _extractBrackets.source,
759
781
  sources = _extractBrackets.sources;
@@ -1081,19 +1103,12 @@ var RuleManager = /*#__PURE__*/function () {
1081
1103
 
1082
1104
  // Test one single path without recursively checking parent directories
1083
1105
  //
1084
- // - checkUnignored `boolean` whether should check if the path is unignored,
1085
- // setting `checkUnignored` to `false` could reduce additional
1086
- // path matching.
1087
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
1106
+ // - mode `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
1088
1107
 
1089
- // @returns {TestResult} true if a file is ignored
1108
+ // @returns {TestResult}
1090
1109
  }, {
1091
1110
  key: "test",
1092
- value: function test(path, checkUnignored, mode) {
1093
- var ignored = false;
1094
- var unignored = false;
1095
- var matchedRule;
1096
-
1111
+ value: function test(path, mode) {
1097
1112
  // Most of a .gitignore is patterns with no slash in them, and running
1098
1113
  // those against the whole path makes the regular expression engine walk
1099
1114
  // every directory name on the way to the only segment that could match.
@@ -1104,40 +1119,31 @@ var RuleManager = /*#__PURE__*/function () {
1104
1119
  var shortcut = this._basenameCount * 2 >= length;
1105
1120
  var basename = shortcut ? basenameOf(path) : path;
1106
1121
 
1122
+ // The last rule to match decides, as in git, and it is the rule
1123
+ // `git check-ignore -v` reports, so the scan runs from the end and stops
1124
+ // at the first match.
1107
1125
  // A plain loop rather than `forEach`, so that `path`, `basename` and
1108
1126
  // `shortcut` are locals. As a callback they became closure variables,
1109
1127
  // and reaching for one of those once per rule cost 10% of a scan over a
1110
1128
  // large rule set -- more than the shortcut they were there to serve.
1111
- for (var index = 0; index < length; index++) {
1129
+ for (var index = length - 1; index >= 0; index--) {
1112
1130
  var rule = rules[index];
1113
- var negative = rule.negative;
1114
-
1115
- // | ignored : unignored
1116
- // -------- | ---------------------------------------
1117
- // negative | 0:0 | 0:1 | 1:0 | 1:1
1118
- // -------- | ------- | ------- | ------- | --------
1119
- // 0 | TEST | TEST | SKIP | X
1120
- // 1 | TESTIF | SKIP | TEST | X
1121
-
1122
- // - SKIP: always skip
1123
- // - TEST: always test
1124
- // - TESTIF: only test if checkUnignored
1125
- // - X: that never happen
1126
- var skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
1127
- if (!skip && rule[mode].test(shortcut && rule._basenameOnly ? basename : path)) {
1128
- ignored = !negative;
1129
- unignored = negative;
1130
- matchedRule = negative ? UNDEFINED : rule;
1131
+ if (rule[mode].test(shortcut && rule._basenameOnly ? basename : path)) {
1132
+ var negative = rule.negative;
1133
+ var ret = {
1134
+ ignored: !negative,
1135
+ unignored: negative
1136
+ };
1137
+ if (!negative) {
1138
+ ret.rule = rule;
1139
+ }
1140
+ return ret;
1131
1141
  }
1132
1142
  }
1133
- var ret = {
1134
- ignored: ignored,
1135
- unignored: unignored
1143
+ return {
1144
+ ignored: false,
1145
+ unignored: false
1136
1146
  };
1137
- if (matchedRule) {
1138
- ret.rule = matchedRule;
1139
- }
1140
- return ret;
1141
1147
  }
1142
1148
  }]);
1143
1149
  return RuleManager;
@@ -1249,12 +1255,12 @@ var Ignore = /*#__PURE__*/function () {
1249
1255
  // @returns {TestResult}
1250
1256
  }, {
1251
1257
  key: "_test",
1252
- value: function _test(originalPath, cache, checkUnignored) {
1258
+ value: function _test(originalPath, cache) {
1253
1259
  var path = originalPath
1254
1260
  // Supports nullable path
1255
1261
  && checkPath.convert(originalPath);
1256
1262
  checkPath(path, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE);
1257
- return this._t(path, cache, checkUnignored);
1263
+ return this._t(path, cache);
1258
1264
  }
1259
1265
  }, {
1260
1266
  key: "checkIgnore",
@@ -1268,7 +1274,7 @@ var Ignore = /*#__PURE__*/function () {
1268
1274
  // Like `git check-ignore`: a directory excluded by itself or by an
1269
1275
  // ancestor settles it, and only then is the literal 'abc/' matched
1270
1276
  // against the rules (see `checkSourceOf`).
1271
- var dir = this._t(path, this._testCache, true);
1277
+ var dir = this._t(path, this._testCache);
1272
1278
  if (dir.ignored) {
1273
1279
  return dir;
1274
1280
  }
@@ -1281,25 +1287,23 @@ var Ignore = /*#__PURE__*/function () {
1281
1287
  // The path to be tested
1282
1288
  path,
1283
1289
  // The cache for the result of a certain checking
1284
- cache,
1285
- // Whether should check if the path is unignored
1286
- checkUnignored) {
1290
+ cache) {
1287
1291
  if (path in cache) {
1288
1292
  return cache[path];
1289
1293
  }
1290
1294
  var parentPath = parentOf(path);
1291
1295
 
1292
1296
  // If the path contains a parent directory, check the parent first
1293
- var parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
1297
+ var parent = parentPath ? this._t(parentPath, cache) : UNDEFINED;
1294
1298
  return cache[path] = parent && parent.ignored
1295
1299
  // > It is not possible to re-include a file if a parent directory of
1296
1300
  // > that file is excluded.
1297
- ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
1301
+ ? parent : this._rules.test(path, MODE_IGNORE);
1298
1302
  }
1299
1303
  }, {
1300
1304
  key: "ignores",
1301
1305
  value: function ignores(path) {
1302
- return this._test(path, this._ignoreCache, false).ignored;
1306
+ return this._test(path, this._ignoreCache).ignored;
1303
1307
  }
1304
1308
  }, {
1305
1309
  key: "createFilter",
@@ -1319,7 +1323,7 @@ var Ignore = /*#__PURE__*/function () {
1319
1323
  }, {
1320
1324
  key: "test",
1321
1325
  value: function test(path) {
1322
- return this._test(path, this._testCache, true);
1326
+ return this._test(path, this._testCache);
1323
1327
  }
1324
1328
  }]);
1325
1329
  return Ignore;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ignore",
3
- "version": "7.0.13",
3
+ "version": "7.0.14",
4
4
  "description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.",
5
5
  "types": "index.d.ts",
6
6
  "files": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-code-intelligence",
3
- "version": "11.0.1",
3
+ "version": "11.1.0",
4
4
  "description": "LSP and AST navigation, search, diagnostics, and refactoring",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,16 +31,21 @@
31
31
  ],
32
32
  "type": "module",
33
33
  "files": [
34
- "src/**/*.ts"
34
+ "src/**/*.ts",
35
+ "gradle-helper/lib/*.jar",
36
+ "gradle-helper/licenses/**",
37
+ "gradle-helper/src/*.java",
38
+ "gradle-helper/build.sh",
39
+ "gradle-helper/README.md"
35
40
  ],
36
41
  "dependencies": {
37
42
  "ignore": "^7.0.12",
38
43
  "smol-toml": "^1.9.1",
39
44
  "yaml": "^2.9.0",
40
- "@mrclrchtr/supi-code-runtime": "11.0.1",
41
- "@mrclrchtr/supi-lsp": "11.0.1",
42
- "@mrclrchtr/supi-tree-sitter": "11.0.1",
43
- "@mrclrchtr/supi-core": "11.0.1"
45
+ "@mrclrchtr/supi-code-runtime": "11.1.0",
46
+ "@mrclrchtr/supi-lsp": "11.1.0",
47
+ "@mrclrchtr/supi-core": "11.1.0",
48
+ "@mrclrchtr/supi-tree-sitter": "11.1.0"
44
49
  },
45
50
  "bundledDependencies": [
46
51
  "@mrclrchtr/supi-code-runtime",
@@ -0,0 +1,273 @@
1
+ import { spawn } from "node:child_process";
2
+ import { promises as fs } from "node:fs";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type { CodeRequestControl } from "@mrclrchtr/supi-code-runtime/api";
6
+ import { findExecutable, GradlePrerequisiteError, requireGradle9 } from "./runtime.ts";
7
+ import type {
8
+ GradleFailureStage,
9
+ GradleModelQuery,
10
+ GradleObservation,
11
+ GradleProjectObservation,
12
+ GradleRuntime,
13
+ } from "./types.ts";
14
+
15
+ const helperDirectory = fileURLToPath(new URL("../../../gradle-helper/lib/", import.meta.url));
16
+ const failureStates = new Set([
17
+ "unavailable",
18
+ "unsupported",
19
+ "failed",
20
+ "interrupted",
21
+ "timeout",
22
+ "oversized",
23
+ ]);
24
+
25
+ /** Launch only the bundled Tooling API helper, with bounded pipes and the caller's deadline. */
26
+ export const queryGradleModel: GradleModelQuery = async (root, runtime, control) => {
27
+ const base = { selectedRoot: root, query: "GradleBuild/BasicGradleProject" as const, runtime };
28
+ const deadline = control?.deadline ?? Date.now() + 30_000;
29
+ let stage: GradleFailureStage = "prerequisites";
30
+ try {
31
+ const java = await selectJava({ ...control, deadline });
32
+ const output = await runProcess(
33
+ java,
34
+ [
35
+ "-cp",
36
+ `${helperDirectory}*`,
37
+ "GradleObservation",
38
+ root,
39
+ runtime.kind,
40
+ runtime.value,
41
+ String(deadline),
42
+ ],
43
+ { ...control, deadline },
44
+ {
45
+ onSpawn: () => {
46
+ stage = "unknown";
47
+ },
48
+ },
49
+ );
50
+ const result: unknown = JSON.parse(output);
51
+ return validateModel(result, base, await fs.realpath(root));
52
+ } catch (error) {
53
+ return {
54
+ ...base,
55
+ stage,
56
+ status:
57
+ error instanceof ProcessFailure || error instanceof GradlePrerequisiteError
58
+ ? error.status
59
+ : "failed",
60
+ reason: error instanceof Error ? error.message.slice(0, 500) : "Gradle model query failed.",
61
+ };
62
+ }
63
+ };
64
+
65
+ async function selectJava(control: CodeRequestControl): Promise<string> {
66
+ const candidates = [
67
+ process.env.JAVA_HOME
68
+ ? path.join(process.env.JAVA_HOME, "bin", process.platform === "win32" ? "java.exe" : "java")
69
+ : undefined,
70
+ await findExecutable("java"),
71
+ ];
72
+ for (const candidate of new Set(candidates)) {
73
+ if (!candidate) continue;
74
+ try {
75
+ const version = await runProcess(candidate, ["-version"], control, { captureError: true });
76
+ const major = Number(version.match(/(?:openjdk|java) version "(\d+)/)?.[1]);
77
+ // This conservative intersection is compatible with the Gradle 9 runtime family.
78
+ if (major >= 17 && major <= 24) return candidate;
79
+ } catch (error) {
80
+ if (error instanceof ProcessFailure && ["timeout", "interrupted"].includes(error.status))
81
+ throw error;
82
+ }
83
+ }
84
+ throw new GradlePrerequisiteError(
85
+ "unavailable",
86
+ "No compatible installed Java runtime (17–24) found through JAVA_HOME or PATH. No JDK was installed.",
87
+ );
88
+ }
89
+
90
+ class ProcessFailure extends Error {
91
+ constructor(
92
+ readonly status: "failed" | "interrupted" | "timeout" | "oversized",
93
+ message: string,
94
+ ) {
95
+ super(message);
96
+ }
97
+ }
98
+
99
+ function runProcess(
100
+ command: string,
101
+ args: string[],
102
+ control: CodeRequestControl,
103
+ options: { readonly captureError?: boolean; readonly onSpawn?: () => void } = {},
104
+ ): Promise<string> {
105
+ return new Promise((resolve, reject) => {
106
+ if (control.signal?.aborted)
107
+ return reject(new ProcessFailure("interrupted", "Gradle observation was cancelled."));
108
+ const remaining = (control.deadline ?? Date.now() + 30_000) - Date.now();
109
+ if (remaining <= 0)
110
+ return reject(new ProcessFailure("timeout", "Gradle observation deadline expired."));
111
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], shell: false });
112
+ child.once("spawn", () => options.onSpawn?.());
113
+ const chunks: Buffer[] = [];
114
+ let bytes = 0;
115
+ let settled = false;
116
+ const finish = (error?: Error) => {
117
+ if (settled) return;
118
+ settled = true;
119
+ clearTimeout(timer);
120
+ control.signal?.removeEventListener("abort", abort);
121
+ if (error) reject(error);
122
+ else resolve(Buffer.concat(chunks).toString("utf8"));
123
+ };
124
+ const stop = (error: ProcessFailure) => {
125
+ child.stdin.end("cancel\n");
126
+ // Only this owned helper is killed; cancellation does not undo build side effects or stop daemons.
127
+ const kill = setTimeout(() => child.kill("SIGKILL"), 250);
128
+ kill.unref();
129
+ child.once("close", () => clearTimeout(kill));
130
+ finish(error);
131
+ };
132
+ const abort = () =>
133
+ stop(
134
+ new ProcessFailure(
135
+ "interrupted",
136
+ "Gradle observation was cancelled; prior side effects may remain.",
137
+ ),
138
+ );
139
+ const timer = setTimeout(
140
+ () =>
141
+ stop(
142
+ new ProcessFailure(
143
+ "timeout",
144
+ "Gradle observation deadline expired; cancellation was requested.",
145
+ ),
146
+ ),
147
+ remaining,
148
+ );
149
+ control.signal?.addEventListener("abort", abort, { once: true });
150
+ if (control.signal?.aborted) abort();
151
+ const collect = (chunk: Buffer) => {
152
+ if (settled) return;
153
+ bytes += chunk.length;
154
+ if (bytes > 1_048_576) {
155
+ stop(
156
+ new ProcessFailure(
157
+ "oversized",
158
+ "Gradle helper output exceeded 1 MiB; no model was retained.",
159
+ ),
160
+ );
161
+ return;
162
+ }
163
+ chunks.push(chunk);
164
+ };
165
+ child.stdout.on("data", collect);
166
+ child.stderr.on("data", options.captureError ? collect : () => {});
167
+ child.stdin.on("error", () => {});
168
+ child.once("error", (error) => finish(error));
169
+ child.once("close", (code) =>
170
+ finish(
171
+ code === 0
172
+ ? undefined
173
+ : new ProcessFailure("failed", `Gradle helper exited with code ${code ?? "unknown"}.`),
174
+ ),
175
+ );
176
+ });
177
+ }
178
+
179
+ function validateModel(
180
+ value: unknown,
181
+ base: { selectedRoot: string; query: "GradleBuild/BasicGradleProject"; runtime: GradleRuntime },
182
+ canonicalRoot: string,
183
+ ): GradleObservation {
184
+ if (!isRecord(value)) throw new Error("Gradle helper returned a non-object result.");
185
+ if (failureStates.has(String(value.status)) && typeof value.reason === "string") {
186
+ if (value.stage !== "prerequisites" && value.stage !== "query")
187
+ throw new Error("Gradle helper returned an invalid failure stage.");
188
+ return {
189
+ ...base,
190
+ status: value.status as "failed",
191
+ stage: value.stage,
192
+ reason: value.reason.slice(0, 500),
193
+ gradleVersion: validateFailureVersion(value),
194
+ };
195
+ }
196
+ if (
197
+ value.status !== "complete" ||
198
+ typeof value.gradleVersion !== "string" ||
199
+ value.buildRoot !== canonicalRoot ||
200
+ !Array.isArray(value.projects) ||
201
+ !Array.isArray(value.includedBuilds)
202
+ )
203
+ throw new Error("Gradle helper returned an invalid model envelope.");
204
+ requireGradle9(value.gradleVersion);
205
+ const projects = validateProjects(value.projects, canonicalRoot);
206
+ for (const included of value.includedBuilds)
207
+ if (
208
+ !isRecord(included) ||
209
+ typeof included.buildRoot !== "string" ||
210
+ !path.isAbsolute(included.buildRoot)
211
+ )
212
+ throw new Error("Gradle helper returned an invalid included-build reference.");
213
+ return {
214
+ ...base,
215
+ status: "complete",
216
+ gradleVersion: value.gradleVersion,
217
+ buildRoot: canonicalRoot,
218
+ projects,
219
+ includedBuilds: value.includedBuilds as { buildRoot: string }[],
220
+ };
221
+ }
222
+
223
+ function validateFailureVersion(value: Record<string, unknown>): string | undefined {
224
+ if (value.gradleVersion === undefined) return undefined;
225
+ if (
226
+ value.stage !== "query" ||
227
+ typeof value.gradleVersion !== "string" ||
228
+ value.gradleVersion.length === 0 ||
229
+ value.gradleVersion.length > 100
230
+ )
231
+ throw new Error("Gradle helper returned an invalid runtime version.");
232
+ return value.gradleVersion;
233
+ }
234
+
235
+ function validateProjects(projects: unknown[], canonicalRoot: string): GradleProjectObservation[] {
236
+ if (projects.length === 0 || projects.length > 10_000)
237
+ throw new Error("Gradle helper returned an invalid project count.");
238
+ const paths = new Set<string>();
239
+ const validated: GradleProjectObservation[] = [];
240
+ for (const project of projects) {
241
+ assertProject(project, canonicalRoot);
242
+ if (paths.has(project.path))
243
+ throw new Error("Gradle helper returned a duplicate project identity.");
244
+ paths.add(project.path);
245
+ validated.push(project);
246
+ }
247
+ for (const project of validated) {
248
+ const parent =
249
+ project.path === ":" ? null : project.path.slice(0, project.path.lastIndexOf(":")) || ":";
250
+ if (project.parentPath !== parent || (parent !== null && !paths.has(parent)))
251
+ throw new Error("Gradle helper returned an invalid parent hierarchy.");
252
+ }
253
+ if (!paths.has(":")) throw new Error("Gradle helper omitted the root project.");
254
+ return validated;
255
+ }
256
+
257
+ function assertProject(value: unknown, root: string): asserts value is GradleProjectObservation {
258
+ if (
259
+ !isRecord(value) ||
260
+ value.buildRoot !== root ||
261
+ typeof value.path !== "string" ||
262
+ !/^:(?:[^:]+(?::[^:]+)*)?$/.test(value.path) ||
263
+ typeof value.name !== "string" ||
264
+ typeof value.directory !== "string" ||
265
+ !path.isAbsolute(value.directory) ||
266
+ !(value.parentPath === null || typeof value.parentPath === "string")
267
+ )
268
+ throw new Error("Gradle helper returned an invalid project identity or directory.");
269
+ }
270
+
271
+ function isRecord(value: unknown): value is Record<string, unknown> {
272
+ return typeof value === "object" && value !== null && !Array.isArray(value);
273
+ }
@@ -0,0 +1,173 @@
1
+ import { constants, promises as fs } from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { assertUnlinkedPath } from "../workspace/safe-path.ts";
5
+ import type { GradleRuntime } from "./types.ts";
6
+
7
+ /** A missing/incompatible prerequisite is evidence, not an empty Gradle build. */
8
+ export class GradlePrerequisiteError extends Error {
9
+ constructor(
10
+ readonly status: "unavailable" | "unsupported",
11
+ message: string,
12
+ options?: ErrorOptions,
13
+ ) {
14
+ super(message, options);
15
+ }
16
+ }
17
+
18
+ /** Require a settings file at exactly this root; never search ancestors or follow links. */
19
+ export async function hasGradleSettings(root: string): Promise<boolean> {
20
+ for (const name of ["settings.gradle", "settings.gradle.kts"]) {
21
+ try {
22
+ await assertUnlinkedPath(root, name, true);
23
+ if ((await fs.lstat(path.join(root, name))).isFile()) return true;
24
+ } catch (error) {
25
+ if (!isMissing(error)) throw error;
26
+ }
27
+ }
28
+ return false;
29
+ }
30
+
31
+ /** Select the wrapper distribution first, or a real PATH installation, without executing scripts. */
32
+ export async function selectGradleRuntime(
33
+ root: string,
34
+ searchPath = process.env.PATH ?? "",
35
+ ): Promise<GradleRuntime> {
36
+ return (await wrapperRuntime(root)) ?? pathRuntime(searchPath);
37
+ }
38
+
39
+ async function wrapperRuntime(root: string): Promise<GradleRuntime | undefined> {
40
+ const relative = "gradle/wrapper/gradle-wrapper.properties";
41
+ const properties = path.join(root, relative);
42
+ try {
43
+ await assertUnlinkedPath(root, relative, true);
44
+ const info = await fs.lstat(properties);
45
+ if (!info.isFile() || info.size > 1_048_576)
46
+ throw new GradlePrerequisiteError(
47
+ "unavailable",
48
+ "Wrapper properties must be a regular file no larger than 1 MiB.",
49
+ );
50
+ const values = parseProperties(await fs.readFile(properties, "latin1"));
51
+ const distribution = values.get("distributionUrl");
52
+ if (!distribution)
53
+ throw new GradlePrerequisiteError(
54
+ "unavailable",
55
+ "Wrapper properties have no distributionUrl; no PATH substitution was attempted.",
56
+ );
57
+ let url: URL;
58
+ try {
59
+ url = new URL(distribution, pathToFileURL(properties));
60
+ } catch (error) {
61
+ // biome-ignore lint/style/useErrorCause: This typed error accepts ErrorOptions as its third argument.
62
+ throw new GradlePrerequisiteError("unavailable", "Wrapper distributionUrl is unresolvable.", {
63
+ cause: error,
64
+ });
65
+ }
66
+ if (!["https:", "http:", "file:"].includes(url.protocol))
67
+ throw new GradlePrerequisiteError(
68
+ "unavailable",
69
+ "Wrapper distribution protocol is unsupported.",
70
+ );
71
+ const version = decodeURIComponent(url.pathname).match(
72
+ /(?:^|\/)gradle-(\d+\.\d+(?:\.\d+)?(?:-[A-Za-z0-9.-]+)?)-(?:bin|all)\.zip$/,
73
+ )?.[1];
74
+ if (!version)
75
+ throw new GradlePrerequisiteError(
76
+ "unavailable",
77
+ "Wrapper distribution version cannot be established from its URL; no fallback was used.",
78
+ );
79
+ requireGradle9(version);
80
+ if (url.protocol === "file:") await fs.access(fileURLToPath(url));
81
+ return { kind: "distribution", value: url.href, source: properties, version };
82
+ } catch (error) {
83
+ if (!isMissing(error)) throw error;
84
+ // A missing archive is not the same as missing wrapper properties.
85
+ if (await fs.lstat(properties).catch(() => null))
86
+ // biome-ignore lint/style/useErrorCause: This typed error accepts ErrorOptions as its third argument.
87
+ throw new GradlePrerequisiteError(
88
+ "unavailable",
89
+ "Wrapper distribution archive is missing; no fallback was used.",
90
+ { cause: error },
91
+ );
92
+ return undefined;
93
+ }
94
+ }
95
+
96
+ async function pathRuntime(searchPath: string): Promise<GradleRuntime> {
97
+ const executable = await findExecutable("gradle", searchPath);
98
+ if (!executable)
99
+ throw new GradlePrerequisiteError(
100
+ "unavailable",
101
+ "No wrapper properties or Gradle installation on PATH.",
102
+ );
103
+ const real = await fs.realpath(executable);
104
+ const home = path.dirname(path.dirname(real));
105
+ if (path.basename(path.dirname(real)) !== "bin")
106
+ throw new GradlePrerequisiteError(
107
+ "unavailable",
108
+ `PATH Gradle is not a resolvable installation: ${executable}. Put the selected installation's bin directory on PATH; shims are not executed.`,
109
+ );
110
+ const libs = await fs.readdir(path.join(home, "lib")).catch(() => []);
111
+ const versions = libs.flatMap((name) => name.match(/^gradle-launcher-(.+)\.jar$/)?.[1] ?? []);
112
+ if (versions.length !== 1)
113
+ throw new GradlePrerequisiteError(
114
+ "unavailable",
115
+ `PATH Gradle installation cannot be resolved: ${executable}. Version-manager shims are not executed.`,
116
+ );
117
+ requireGradle9(versions[0]);
118
+ return { kind: "installation", value: home, source: executable, version: versions[0] };
119
+ }
120
+
121
+ /** Resolve only existing executable files, preserving PATH precedence. */
122
+ export async function findExecutable(
123
+ name: string,
124
+ searchPath = process.env.PATH ?? "",
125
+ ): Promise<string | undefined> {
126
+ for (const directory of searchPath.split(path.delimiter)) {
127
+ if (!directory) continue;
128
+ const candidate = path.resolve(directory, process.platform === "win32" ? `${name}.exe` : name);
129
+ try {
130
+ await fs.access(candidate, constants.X_OK);
131
+ if ((await fs.stat(candidate)).isFile()) return candidate;
132
+ } catch {
133
+ /* Try the next PATH entry. */
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ /** Only Gradle 9 is supported, including when an explicit wrapper names another major. */
140
+ export function requireGradle9(version: string): void {
141
+ if (!/^9\./.test(version))
142
+ throw new GradlePrerequisiteError(
143
+ "unsupported",
144
+ `Gradle ${version} is unsupported; only Gradle 9 is supported. No fallback was used.`,
145
+ );
146
+ }
147
+
148
+ function isMissing(error: unknown): boolean {
149
+ return (error as NodeJS.ErrnoException).code === "ENOENT";
150
+ }
151
+
152
+ /** Java properties escapes and continuations, not a Groovy/Kotlin settings interpreter. */
153
+ function parseProperties(text: string): Map<string, string> {
154
+ const values = new Map<string, string>();
155
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
156
+ const decode = (value: string) =>
157
+ value.replace(
158
+ /\\u([0-9a-fA-F]{4})|\\(.)/g,
159
+ (_match, hex: string | undefined, escaped: string) =>
160
+ hex
161
+ ? String.fromCharCode(Number.parseInt(hex, 16))
162
+ : ({ t: "\t", r: "\r", n: "\n", f: "\f" }[escaped] ?? escaped),
163
+ );
164
+ for (let i = 0; i < lines.length; i++) {
165
+ let line = lines[i].trimStart();
166
+ if (/^[#!]/.test(line)) continue;
167
+ while ((line.match(/\\+$/)?.[0].length ?? 0) % 2 === 1 && i + 1 < lines.length)
168
+ line = line.slice(0, -1) + lines[++i].trimStart();
169
+ const match = line.match(/^((?:\\.|[^\s:=\\])+)(?:\s*[:=]\s*|\s+)?(.*)$/);
170
+ if (match) values.set(decode(match[1]), decode(match[2]));
171
+ }
172
+ return values;
173
+ }