diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 31a3cdf..9c6bfc2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -26,8 +26,12 @@ jobs:
with:
distribution: temurin
java-version: 17
+ - name: Verify vendored Java SDK sources
+ run: node scripts/sdk/verify-sdk.mjs
- name: Check manifest and build the archive
run: node scripts/package.mjs
+ - name: Test the settings backend
+ run: node scripts/test-backend.mjs
- name: Download Gradle ${{ matrix.gradle }}
env:
VERSION: ${{ matrix.gradle }}
diff --git a/.gitignore b/.gitignore
index aaf4bbd..89f36d5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,4 @@ dist/
.gradle/
build/
.DS_Store
+backend/target/
diff --git a/NOTICE b/NOTICE
index 1a58410..b89a079 100644
--- a/NOTICE
+++ b/NOTICE
@@ -12,5 +12,10 @@ Version 2.0, at revision 158b854d47ac9af2bbd99c0d7c354a5875cb6f81:
Copyright 2000-2023 JetBrains s.r.o. and contributors.
+The official Java SDK sources in vendor/lithe-plugin-sdk-java/ come from
+Lithe-IDEA/lithe-plugin-docs at the revision pinned in sdk.lock.json (some with
+local changes recorded there), licensed under the Apache License, Version 2.0.
+They are compiled into lib/lithe-gradle-backend.jar.
+
Gradle is a trademark of Gradle, Inc. This plugin is not affiliated with or
endorsed by Gradle, Inc.
diff --git a/README.md b/README.md
index a725487..fa01caf 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、应用和测试。
这是一个**社区插件**,用 Lithe 的声明式构建系统接口(插件 API 3 的 `buildSystems`)实现,
只带一个 Gradle 初始化脚本,没有任何宿主代码。工具窗口由 macOS 宿主用 SwiftUI 原生渲染,插件不提供 Web 入口;
-`languageImport` 把 Offline 和 Gradle User Home 选项传给 Java 语言服务器的 Gradle 导入。
+插件另带一个很小的 Java 后端,向 Java Support 提供 Gradle 的导入设置(见下文“Java 语言服务器的导入设置”)。
> English: Gradle support for Lithe through the declarative `buildSystems` plugin API — projects with their tasks by
> group, JavaExec tasks as run entries, test runs with JUnit reports, compiler diagnostics and per-configuration
@@ -33,6 +33,22 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、
以及 GroupId 和 ArtifactId。模板在 `io.github.lithe-idea.gradle-build/templates/java/`,从 Java Support 插件移来,
生成的文件与原来相同。条目要求 `java` 语言和 `gradle` 构建系统同时可用,所以生成的项目需要安装 Java Support 插件提供 Java 语言支持。
+## Java 语言服务器的导入设置
+
+旧版清单里的 `buildSystems[].languageImport` 已从插件契约删除。现在 Gradle 插件导出插件函数 `languageImport.settings`
+(版本 1,`context: "workspace"`),Java Support 在启动 JDT LS 前调用它,只接受 `java.import.gradle.` 等白名单前缀内的键。
+后端只读取工作区里的文件,不运行 Gradle、不写任何文件:
+
+| 来源 | 导出的键 |
+| --- | --- |
+| 环境变量 `GRADLE_USER_HOME`(绝对路径) | `java.import.gradle.user.home` |
+| `gradle.properties` 的 `org.gradle.java.home`(绝对路径) | `java.import.gradle.java.home` |
+| `gradle.properties` 的 `org.gradle.jvmargs` | `java.import.gradle.jvmArguments` |
+
+`gradle.properties` 先读 Gradle User Home 里的,再读项目根的,项目根优先。`workspaceRoot` 必须落在已打开的本地工作区文件夹内,
+否则函数拒绝(`gradle.invalidRoot`)。工具栏的 Offline 与 Gradle User Home 选项只保存在宿主里,插件后端读不到,
+所以它们不再传给 JDT LS,需要宿主把已存选项交给插件函数后才能恢复。后端用 Lithe 找到的 Java(8 或更新版本)运行,Gradle 本身也需要它,所以不增加新的运行时要求。
+
## 依赖的程序
插件不带 Gradle,使用你项目或电脑上的 Gradle,按以下顺序查找:
@@ -59,7 +75,7 @@ IntelliJ IDEA 一样按项目列出任务分组和依赖配置,运行任务、
## 安装
-`v0.1.1` 修复重复运行测试时报告显示为零的问题,需要兼容 `buildSystems` 插件 API 3 的 Lithe preview 开发版。
+`v0.1.2` 移除宿主已删除的 `languageImport` 字段并改用插件函数提供导入设置;`v0.1.1` 修复重复运行测试时报告显示为零的问题。均需要兼容 `buildSystems` 插件 API 3 的 Lithe preview 开发版。
Lithe Store 条目合并后,可在 **设置 → 插件 → 插件市场** 搜索 “Gradle”,安装并按提示重启;
条目合并前可下载 Release 的 ZIP,从 Lithe 开发版的 **⚙ → 从磁盘安装插件…** 安装。
Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先在 **⚙ → 管理插件仓库…** 中重新添加
@@ -72,16 +88,19 @@ Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先
```text
io.github.lithe-idea.gradle-build/plugin.json # 插件描述,目录名必须等于插件 id
io.github.lithe-idea.gradle-build/lithe.init.gradle # 初始化脚本,导出模型和依赖树
+backend/ # languageImport.settings 后端(Java),打包成 lib/lithe-gradle-backend.jar
+vendor/lithe-plugin-sdk-java/ # 固定版本的官方 Java SDK 源码(sdk.lock.json 逐文件校验,编译进后端 jar)
io.github.lithe-idea.gradle-build/icons/ # 工具窗口和工具栏图标(来源见 NOTICE)
io.github.lithe-idea.gradle-build/templates/java/ # New Project 的 Gradle Java 项目模板(Kotlin/Groovy DSL、示例代码)
test/fixtures/multi/ # 两个子项目的示例构建,供集成测试使用
scripts/package.mjs # 打包成 dist/gradle-build-<版本>-darwin.zip
scripts/test.mjs # 用真实 Gradle 运行清单里的命令并检查输出
+scripts/test-backend.mjs # 经 stdio 驱动后端 jar,测试 languageImport.settings(不需要 Gradle)
.github/workflows/ci.yml # PR 时打包、用 Gradle 7.6 和 9.6.1 测试,并用 Lithe Store 的规则检查
.github/workflows/release.yml # 推送 v<版本> 标签时发布 GitHub Release
```
-本地需要 Node.js 22+、JDK 17+ 和 Gradle(还需要 `zip`):
+本地需要 Node.js 22+(只运行脚本)、JDK 17+ 和 Gradle(还需要 `zip`);打包用 JDK 自带的 `javac` 和 `jar` 编译后端,不需要 Maven:
```bash
node scripts/package.mjs
@@ -105,7 +124,7 @@ GRADLE=/path/to/gradle node scripts/test.mjs
## 诊断日志
-此插件只声明 Gradle 命令及模型导出脚本,没有独立的常驻后端或日志 writer。
+此插件的 Gradle 命令及模型导出脚本由宿主执行,后端只在 Java Support 调用 `languageImport.settings` 时启动,用官方 SDK 自动记录该函数的结构化操作事实(不含路径和属性值)。
启用结构化日志 v2 的 Lithe macOS preview 由宿主将构建、运行与测试的进程终态、退出码和耗时
记录到当前会话的 `run` 通道;Gradle 的编译输出和测试报告继续留在 Build Output 与测试界面。
模型与依赖树 JSON 是工作流数据,不是日志,仍通过宿主提供的临时输出文件返回。
diff --git a/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java b/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java
new file mode 100644
index 0000000..1f85928
--- /dev/null
+++ b/backend/src/main/java/io/github/litheidea/gradle/backend/GradleBackend.java
@@ -0,0 +1,23 @@
+package io.github.litheidea.gradle.backend;
+
+import io.github.litheidea.plugin.sdk.Backend;
+
+/**
+ * The plugin backend of the Gradle plugin. It only exports plugin functions to
+ * other plugins ({@code languageImport.settings}, see {@link LanguageImport});
+ * Gradle itself is run by the host from the commands in plugin.json.
+ */
+public final class GradleBackend {
+ private GradleBackend() {}
+
+ public static void main(String[] arguments) {
+ Backend backend = Backend.create("lithe-gradle-backend", version());
+ backend.function(LanguageImport.FUNCTION, (params, context) -> LanguageImport.handle(params, context, System.getenv()));
+ backend.listen();
+ }
+
+ private static String version() {
+ String version = GradleBackend.class.getPackage().getImplementationVersion();
+ return version == null ? "development" : version;
+ }
+}
diff --git a/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java b/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java
new file mode 100644
index 0000000..47927be
--- /dev/null
+++ b/backend/src/main/java/io/github/litheidea/gradle/backend/LanguageImport.java
@@ -0,0 +1,113 @@
+package io.github.litheidea.gradle.backend;
+
+import io.github.litheidea.plugin.sdk.CallContext;
+import io.github.litheidea.plugin.sdk.Json;
+import io.github.litheidea.plugin.sdk.PluginError;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * The plugin function {@code languageImport.settings} (version 1) that Java
+ * Support calls before it starts JDT LS: the import settings Gradle's own
+ * configuration files imply. Nothing here runs Gradle or writes a file; the
+ * workspace root it is asked about must lie inside an open local workspace
+ * folder. {@code gradle.properties} of the project wins over the one in the
+ * Gradle user home, as in Gradle itself.
+ *
+ *
{@code GRADLE_USER_HOME} (absolute) becomes {@code java.import.gradle.user.home},
+ * {@code org.gradle.java.home} (absolute) {@code java.import.gradle.java.home} and
+ * {@code org.gradle.jvmargs} {@code java.import.gradle.jvmArguments}.
+ */
+final class LanguageImport {
+ static final String FUNCTION = "languageImport.settings";
+ private static final long MAX_PROPERTIES_BYTES = 256 * 1024;
+
+ private LanguageImport() {}
+
+ /** The function handler. */
+ static Object handle(Map params, CallContext context, Map environment) throws Exception {
+ String requested = Json.string(params, "workspaceRoot");
+ if (requested == null || !Paths.get(requested).isAbsolute()) {
+ throw new PluginError("gradle.invalidRoot", "workspaceRoot must be an absolute path.");
+ }
+ Map workspace = context.workspaceContext();
+ if (workspace == null) {
+ throw new PluginError("gradle.noWorkspaceContext", "The call carries no workspace context.");
+ }
+ Path root = Paths.get(requested).toRealPath();
+ Map answer = context.host().workspace().getFolders(workspace).get(10, TimeUnit.SECONDS);
+ if (!insideFolder(root, answer.get("folders"))) {
+ throw new PluginError("gradle.invalidRoot", "workspaceRoot is not inside an open workspace folder.");
+ }
+ context.throwIfCancelled();
+ return settings(root, environment);
+ }
+
+ private static boolean insideFolder(Path root, Object folders) throws IOException {
+ if (!(folders instanceof List)) {
+ return false;
+ }
+ for (Object folder : (List>) folders) {
+ Object path = folder instanceof Map ? ((Map, ?>) folder).get("path") : null;
+ if (path instanceof String && root.startsWith(Paths.get((String) path).toRealPath())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** The Gradle user home as Gradle resolves it without a command line. */
+ static Path userHome(Map environment) {
+ String value = environment.get("GRADLE_USER_HOME");
+ if (value != null && !value.isEmpty() && Paths.get(value).isAbsolute()) {
+ return Paths.get(value);
+ }
+ return Paths.get(System.getProperty("user.home"), ".gradle");
+ }
+
+ /** {@code { settings }} for the Gradle build at {@code root}. */
+ static Map settings(Path root, Map environment) {
+ Path home = userHome(environment);
+ Properties merged = new Properties();
+ load(merged, home.resolve("gradle.properties"));
+ load(merged, root.resolve("gradle.properties"));
+ Map settings = new LinkedHashMap<>();
+ String explicitHome = environment.get("GRADLE_USER_HOME");
+ if (explicitHome != null && !explicitHome.isEmpty() && Paths.get(explicitHome).isAbsolute()) {
+ settings.put("java.import.gradle.user.home", home.toString());
+ }
+ String javaHome = merged.getProperty("org.gradle.java.home");
+ if (javaHome != null && !javaHome.isEmpty() && Paths.get(javaHome).isAbsolute()) {
+ settings.put("java.import.gradle.java.home", javaHome);
+ }
+ String jvmArguments = merged.getProperty("org.gradle.jvmargs");
+ if (jvmArguments != null && !jvmArguments.isEmpty()) {
+ settings.put("java.import.gradle.jvmArguments", jvmArguments);
+ }
+ Map result = new LinkedHashMap<>();
+ result.put("settings", settings);
+ return result;
+ }
+
+ /** Adds the entries of a properties file; a missing, unreadable or oversized file adds nothing. */
+ private static void load(Properties target, Path file) {
+ try {
+ if (!Files.isRegularFile(file) || Files.size(file) > MAX_PROPERTIES_BYTES) {
+ return;
+ }
+ try (InputStream input = Files.newInputStream(file)) {
+ target.load(input);
+ }
+ } catch (IOException | IllegalArgumentException ignored) {
+ // The file contributes nothing; JDT LS then imports with its defaults.
+ }
+ }
+}
diff --git a/io.github.lithe-idea.gradle-build/plugin.json b/io.github.lithe-idea.gradle-build/plugin.json
index 34e9550..175c041 100644
--- a/io.github.lithe-idea.gradle-build/plugin.json
+++ b/io.github.lithe-idea.gradle-build/plugin.json
@@ -2,17 +2,23 @@
"schemaVersion": 2,
"id": "io.github.lithe-idea.gradle-build",
"displayName": "Gradle",
- "version": "0.1.1",
+ "version": "0.1.2",
"pluginAPIVersion": 3,
- "requires": { "buildSystems": 1, "projectGenerators": 1 },
+ "requires": { "backend": 2, "buildSystems": 1, "pluginFunctions": 1, "projectGenerators": 1, "serverProcess": 1 },
"vendor": {
"id": "io.github.lithe-idea",
"displayName": "Lithe Community",
"signatureRequirement": "none"
},
- "permissions": ["process.build", "project.generate"],
+ "permissions": ["backend.launch", "process.build", "project.generate", "workspace.metadata"],
"activationEvents": ["onBuildSystem:gradle"],
"languages": [],
+ "backend": {
+ "launch": { "kind": "runtime", "tool": "java", "minimumVersion": "8", "entry": "lib/lithe-gradle-backend.jar" }
+ },
+ "pluginFunctions": {
+ "exports": [{ "id": "languageImport.settings", "version": 1, "context": "workspace" }]
+ },
"buildSystems": [
{
"id": "gradle",
@@ -170,8 +176,7 @@
"settings.gradle.kts"
]
},
- "layout": { "excluded": [".gradle", "build"] },
- "languageImport": { "kind": "gradle", "options": { "offline": "offline", "gradleUserHome": "gradleUserHome" } }
+ "layout": { "excluded": [".gradle", "build"] }
}
],
"projectGenerators": [
diff --git a/scripts/backend-client.mjs b/scripts/backend-client.mjs
new file mode 100644
index 0000000..1cf5288
--- /dev/null
+++ b/scripts/backend-client.mjs
@@ -0,0 +1,153 @@
+// Talks to lib/lithe-maven-backend.jar the way Lithe does: LSP base-protocol
+// frames over the process's stdio, `initialize` offering litheBuild 1, then
+// lithe/build/* requests. Every wait is bounded, and the backend runs in its
+// own process group so a test can always end whatever it left behind.
+import { spawn } from "node:child_process";
+import { pathToFileURL } from "node:url";
+
+export const WAIT_MS = 20_000;
+
+export class BackendClient {
+ #buffer = Buffer.alloc(0);
+ #pending = new Map();
+ #nextId = 1;
+ stderr = "";
+ diagnostics = [];
+
+ /** Starts `java -jar --state ` (or `args`); `javaOptions` go before `-jar`. */
+ constructor({ java = "java", jar, state, env = process.env, javaOptions = [], timeoutMs = WAIT_MS, args, hostRequests = {} }) {
+ this.timeoutMs = timeoutMs;
+ // Answers to requests the backend sends to the host, keyed by method.
+ this.hostRequests = hostRequests;
+ this.child = spawn(java, [...javaOptions, "-jar", jar, ...(args ?? ["--state", state])], {
+ env, stdio: ["pipe", "pipe", "pipe"], detached: true,
+ });
+ this.exited = new Promise((resolve) => this.child.once("exit", (code, signal) => {
+ this.#fail(`the backend exited with ${signal ?? `status ${code}`}`);
+ resolve(signal ?? code);
+ }));
+ this.child.once("error", (error) => this.#fail(`cannot start the backend: ${error.message}`));
+ this.child.stdout.on("data", (chunk) => this.#read(chunk));
+ this.child.stderr.on("data", (chunk) => { this.stderr += chunk; });
+ this.child.stdin.on("error", () => {});
+ }
+
+ /** Sends a request; `response` settles with the whole response message. */
+ send(method, params) {
+ const id = this.#nextId++;
+ const response = new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.#pending.delete(id);
+ reject(new Error(`no response to ${method} #${id} within ${this.timeoutMs} ms\nbackend stderr:\n${this.stderr}`));
+ }, this.timeoutMs);
+ this.#pending.set(id, (message) => {
+ clearTimeout(timer);
+ if (message instanceof Error) reject(message);
+ else resolve(message);
+ });
+ });
+ this.#write({ jsonrpc: "2.0", id, method, params });
+ return { id, response };
+ }
+
+ /** Sends a request and resolves with its result, or rejects with its error. */
+ async request(method, params) {
+ const message = await this.send(method, params).response;
+ if (message.error) {
+ const error = new Error(`${method} failed: ${message.error.message}`);
+ error.response = message.error;
+ throw error;
+ }
+ return message.result;
+ }
+
+ notify(method, params) {
+ this.#write({ jsonrpc: "2.0", method, params });
+ }
+
+ cancel(id) {
+ this.notify("$/cancelRequest", { id });
+ }
+
+ async initialize(root, { functions = false } = {}) {
+ const result = await this.request("initialize", {
+ processId: process.pid,
+ rootUri: pathToFileURL(root).href,
+ capabilities: { experimental: {
+ ...(functions ? { litheFunctions: { versions: [1, 2, 3] } } : { litheBuild: { versions: [1] } }),
+ litheLogging: { versions: [1] },
+ } },
+ });
+ this.notify("initialized", {});
+ return result;
+ }
+
+ /** `shutdown` and `exit`; resolves with the exit code. */
+ async close() {
+ if (this.child.exitCode === null && this.child.signalCode === null) {
+ await this.request("shutdown", null);
+ this.notify("exit", null);
+ this.child.stdin.end();
+ }
+ return bounded(this.exited, "the backend to exit");
+ }
+
+ /** Ends the backend's whole process group, for teardown after a failure. */
+ kill() {
+ if (!this.child.pid) return;
+ // macOS answers EPERM for a group whose members already exited but are not reaped yet.
+ try { process.kill(-this.child.pid, "SIGKILL"); }
+ catch (error) { if (error.code !== "ESRCH" && error.code !== "EPERM") throw error; }
+ }
+
+ #write(message) {
+ const body = Buffer.from(JSON.stringify(message), "utf8");
+ this.child.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body]));
+ }
+
+ /** Rejects every waiting request; nothing more will answer them. */
+ #fail(reason) {
+ const error = new Error(`${reason}\nbackend stderr:\n${this.stderr}`);
+ for (const settle of this.#pending.values()) settle(error);
+ this.#pending.clear();
+ }
+
+ #read(chunk) {
+ this.#buffer = Buffer.concat([this.#buffer, chunk]);
+ for (;;) {
+ const headerEnd = this.#buffer.indexOf("\r\n\r\n");
+ if (headerEnd < 0) return;
+ const length = Number(/Content-Length: *(\d+)/i.exec(this.#buffer.subarray(0, headerEnd).toString("ascii"))?.[1]);
+ if (!Number.isSafeInteger(length)) return this.#broken("a frame without Content-Length");
+ if (this.#buffer.length < headerEnd + 4 + length) return;
+ let message;
+ try { message = JSON.parse(this.#buffer.subarray(headerEnd + 4, headerEnd + 4 + length).toString("utf8")); }
+ catch { return this.#broken("a frame that is not JSON"); }
+ this.#buffer = this.#buffer.subarray(headerEnd + 4 + length);
+ if (message.method === "lithe/log") {
+ this.diagnostics.push(message.params);
+ } else if (message.id !== undefined && message.method !== undefined) {
+ const answer = this.hostRequests[message.method];
+ this.#write(answer === undefined
+ ? { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } }
+ : { jsonrpc: "2.0", id: message.id, result: answer(message.params) });
+ } else if (message.id !== undefined && message.method === undefined) {
+ this.#pending.get(message.id)?.(message);
+ this.#pending.delete(message.id);
+ }
+ }
+ }
+
+ #broken(what) {
+ this.#fail(`the backend wrote ${what}`);
+ this.kill();
+ }
+}
+
+export function bounded(promise, description, timeoutMs = WAIT_MS) {
+ let timer;
+ return Promise.race([
+ promise,
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${description}`)), timeoutMs); }),
+ ]).finally(() => clearTimeout(timer));
+}
diff --git a/scripts/package.mjs b/scripts/package.mjs
index 5a3f35e..434bdc3 100644
--- a/scripts/package.mjs
+++ b/scripts/package.mjs
@@ -3,16 +3,17 @@
// Lithe Store's release tracker recognizes (docs/publishing.md there).
//
// The package is plain data: plugin.json, icons, New Project templates, and
-// the init script that runs inside the user's own Gradle, so one archive
-// serves every Mac. The
+// the init script that runs inside the user's own Gradle, and the Java backend
+// jar (lib/lithe-gradle-backend.jar), so one archive serves every Mac. The
// unpacked package stays in dist/package/ for installing a local
// development copy into Lithe.
//
// Usage: node scripts/package.mjs [--expect-tag ]
import { execFileSync } from "node:child_process";
+import { verifySdk } from "./sdk/verify-sdk.mjs";
import { createHash } from "node:crypto";
-import { cpSync, lstatSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { isAbsolute, join, resolve } from "node:path";
const PACKAGE_DIR = "io.github.lithe-idea.gradle-build";
@@ -79,9 +80,32 @@ function assertNoLinks(directory) {
}
}
+// The backend (backend/) and the vendored official Java SDK (vendor/, pinned by
+// sdk.lock.json) are compiled together for Java 8 with the JDK's own javac and
+// jar, so building needs no Maven. A fixed timestamp makes the jar reproducible.
+await verifySdk();
+const BACKEND_BUILD = join("backend", "target");
+const BACKEND_JAR = join(BACKEND_BUILD, "lithe-gradle-backend.jar");
+function sourcesUnder(directory) {
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(directory, entry.name);
+ return entry.isDirectory() ? sourcesUnder(path) : entry.name.endsWith(".java") ? [path] : [];
+ });
+}
+rmSync(BACKEND_BUILD, { recursive: true, force: true });
+mkdirSync(join(BACKEND_BUILD, "classes"), { recursive: true });
+const javaSources = [...sourcesUnder("backend/src/main/java"), ...sourcesUnder("vendor/lithe-plugin-sdk-java/src/main/java")];
+execFileSync("javac", ["-encoding", "UTF-8", "--release", "8", "-Xlint:-options", "-d", join(BACKEND_BUILD, "classes"), ...javaSources], { stdio: "inherit", timeout: 120_000 });
+writeFileSync(join(BACKEND_BUILD, "MANIFEST.MF"), `Main-Class: io.github.litheidea.gradle.backend.GradleBackend\nImplementation-Version: ${manifest.version}\n`);
+execFileSync("jar", ["--create", "--file", BACKEND_JAR, "--manifest", join(BACKEND_BUILD, "MANIFEST.MF"), "--date", "2026-10-20T00:00:00Z", "-C", join(BACKEND_BUILD, "classes"), "."], { stdio: "inherit", timeout: 60_000 });
+if (!existsSync(BACKEND_JAR)) throw new Error(`${BACKEND_JAR} was not built`);
+
rmSync("dist", { recursive: true, force: true });
const packageRoot = join(PACKAGE_ROOT, PACKAGE_DIR);
cpSync(PACKAGE_DIR, packageRoot, { recursive: true });
+mkdirSync(join(packageRoot, "lib"), { recursive: true });
+cpSync(BACKEND_JAR, join(packageRoot, "lib", "lithe-gradle-backend.jar"));
+cpSync("vendor/LICENSE", join(packageRoot, "SDK-LICENSE"));
cpSync("LICENSE", join(packageRoot, "LICENSE"));
cpSync("NOTICE", join(packageRoot, "NOTICE"));
assertNoLinks(packageRoot);
diff --git a/scripts/sdk/verify-sdk.mjs b/scripts/sdk/verify-sdk.mjs
new file mode 100644
index 0000000..b352bb4
--- /dev/null
+++ b/scripts/sdk/verify-sdk.mjs
@@ -0,0 +1,42 @@
+import { createHash } from 'node:crypto';
+import { lstat, readFile, readdir } from 'node:fs/promises';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const repository = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+
+/** Verify every vendored production source before building the backend. */
+export async function verifySdk(root = repository) {
+ const lock = JSON.parse(await readFile(join(root, 'sdk.lock.json'), 'utf8'));
+ if (lock.schemaVersion !== 1 || !/^[0-9a-f]{40}$/.test(lock.source?.revision) || !Array.isArray(lock.files) || lock.source.repository !== 'https://github.com/Lithe-IDEA/lithe-plugin-docs') {
+ throw new Error('The SDK lock must identify its upstream base and every source hash.');
+ }
+ const expected = new Set();
+ for (const entry of lock.files) {
+ if (!entry.path?.startsWith('vendor/') || entry.path.includes('\\')
+ || entry.path.split('/').some((part) => !part || part === '.' || part === '..')
+ || !/^[0-9a-f]{64}$/.test(entry.sha256) || expected.has(entry.path)
+ || (entry.localChanges === true && (!Object.hasOwn(entry, 'upstreamSha256') || (entry.upstreamSha256 !== null && !/^[0-9a-f]{64}$/.test(entry.upstreamSha256))))) {
+ throw new Error('Invalid or duplicate SDK source lock entry.');
+ }
+ const file = join(root, entry.path);
+ if (!(await lstat(file)).isFile()) throw new Error(`SDK input is not a regular file: ${entry.path}`);
+ const digest = createHash('sha256').update(await readFile(file)).digest('hex');
+ if (digest !== entry.sha256) throw new Error(`SDK SHA-256 mismatch: ${entry.path}`);
+ expected.add(entry.path);
+ }
+ async function walk(directory, prefix) {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const name = `${prefix}/${entry.name}`;
+ if (entry.isDirectory()) await walk(join(directory, entry.name), name);
+ else if (!expected.delete(name)) throw new Error(`Unpinned SDK input: ${name}`);
+ }
+ }
+ await walk(join(root, 'vendor'), 'vendor');
+ if (expected.size) throw new Error('A pinned SDK source is missing.');
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ await verifySdk();
+ console.log('Vendored Java SDK source hashes verified.');
+}
diff --git a/scripts/test-backend.mjs b/scripts/test-backend.mjs
new file mode 100644
index 0000000..8913b0f
--- /dev/null
+++ b/scripts/test-backend.mjs
@@ -0,0 +1,74 @@
+#!/usr/bin/env node
+// Drives lib/lithe-gradle-backend.jar from dist/package over its stdio, as
+// Lithe does: `languageImport.settings` for roots inside and outside an open
+// workspace folder. No Gradle or network is needed.
+//
+// Run scripts/package.mjs first. LITHE_TEST_JAVA selects the Java that runs the
+// backend (default `java`), so CI also checks Java 8.
+//
+// Usage: node scripts/test-backend.mjs
+
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { BackendClient, bounded } from "./backend-client.mjs";
+
+const jar = resolve("dist", "package", "io.github.lithe-idea.gradle-build", "lib", "lithe-gradle-backend.jar");
+if (!existsSync(jar)) {
+ console.error("✗ dist/package is missing the backend; run node scripts/package.mjs first");
+ process.exit(1);
+}
+const java = process.env.LITHE_TEST_JAVA ?? "java";
+const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-gradle-backend-test-")));
+const workspace = join(scratch, "workspace");
+const outside = join(scratch, "outside");
+const gradleHome = join(scratch, "gradle-home");
+const home = join(scratch, "home");
+for (const directory of [join(workspace, "app"), outside, gradleHome, home]) mkdirSync(directory, { recursive: true });
+writeFileSync(join(gradleHome, "gradle.properties"), "org.gradle.jvmargs=-Xmx1g\norg.gradle.java.home=/jdk/home\norg.gradle.parallel=true\n");
+writeFileSync(join(workspace, "app", "gradle.properties"), "org.gradle.jvmargs=-Xmx4g \\\n -Dfile.encoding=UTF-8\norg.gradle.java.home=relative/jdk\n");
+symlinkSync(outside, join(workspace, "escape"));
+
+let client;
+let failed = false;
+const step = async (name, body) => {
+ try { await body(); console.log(`✓ ${name}`); }
+ catch (error) { failed = true; console.error(`✗ ${name}\n${error.stack}`); }
+};
+try {
+ client = new BackendClient({
+ java, jar, args: [], javaOptions: [`-Duser.home=${home}`],
+ env: { ...process.env, GRADLE_USER_HOME: gradleHome },
+ hostRequests: { "lithe/host/workspace/getFolders": () => ({ folders: [{ rootID: "r", name: "w", path: workspace }] }) },
+ });
+ const initialized = await client.initialize(workspace, { functions: true });
+ assert.deepEqual(initialized.capabilities.experimental.litheFunctions.functions, [{ id: "languageImport.settings" }]);
+ const invoke = (workspaceRoot, context = { contextID: "ctx", generation: 1 }) => client.send("lithe/function/invoke", {
+ functionID: "languageImport.settings", operationID: `op-${Math.random()}`, params: { workspaceRoot }, ...(context ? { context } : {}),
+ }).response;
+
+ await step("the project's gradle.properties overrides the Gradle user home and only known keys are exported", async () => {
+ assert.deepEqual((await invoke(join(workspace, "app"))).result, { settings: {
+ "java.import.gradle.user.home": gradleHome,
+ "java.import.gradle.jvmArguments": "-Xmx4g -Dfile.encoding=UTF-8",
+ } });
+ });
+ await step("a root outside the open workspace folders, through a link, relative or without a context is refused", async () => {
+ for (const root of [outside, join(workspace, "escape"), "relative"]) {
+ assert.equal((await invoke(root)).error?.data?.code, "gradle.invalidRoot", root);
+ }
+ assert.equal((await invoke(workspace, null)).error?.data?.code, "gradle.noWorkspaceContext");
+ });
+ await step("the backend exits on shutdown", async () => {
+ assert.equal(await client.close(), 0, `the backend exits cleanly\n${client.stderr}`);
+ client = undefined;
+ });
+} finally {
+ if (client) {
+ client.kill();
+ await bounded(client.exited, "the backend to be killed").catch(() => {});
+ }
+ rmSync(scratch, { recursive: true, force: true });
+}
+process.exitCode = failed ? 1 : 0;
diff --git a/sdk.lock.json b/sdk.lock.json
new file mode 100644
index 0000000..453b59b
--- /dev/null
+++ b/sdk.lock.json
@@ -0,0 +1,104 @@
+{
+ "schemaVersion": 1,
+ "source": {
+ "repository": "https://github.com/Lithe-IDEA/lithe-plugin-docs",
+ "revision": "29b245c0e1d77c761d9032a3144a301d1818bfc7",
+ "localChanges": "Structured logging lithe/log implementation from the accompanying SDK working tree. Per-file hashes identify these reviewed inputs; no published release is claimed."
+ },
+ "files": [
+ {
+ "upstream": "LICENSE",
+ "path": "vendor/LICENSE",
+ "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java",
+ "sha256": "c5430ea55f5ee73a88b8c6c3517cf6bc2237827b009ae1844c105254b7f48a24",
+ "localChanges": true,
+ "upstreamSha256": "c1943d63121ce20dfadf24dfcac50581da4371356fb5f7ee30962b41b2fd04a2"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java",
+ "sha256": "c41fcc2cbc6533215ee9034409292ddeb6237d6c3defdd65b2cdfb8fb848dde8",
+ "localChanges": true,
+ "upstreamSha256": "8157d980a585b85ed31b96ad974fe980e167b6c0b7701b2636328ba84c0b62af"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java",
+ "sha256": "826c246360a607eb40ce950202db0988a465718082dc22be539f045139671db3",
+ "localChanges": true,
+ "upstreamSha256": "87eb1a9b673f59774ac1688393f62f8aa5379ead1ed2464b50ab64a0d6ad80d9"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java",
+ "sha256": "699c054b1857a0518fd244ff193bc87445495ae40cbf7cc34436ac92ba42973e"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java",
+ "sha256": "e6b70f167f1b030509fccf399745bc7693023eabeff1201696e866340d546ec9",
+ "localChanges": true,
+ "upstreamSha256": null
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Framing.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java",
+ "sha256": "510a82f0c29e634d4235326ed9abccc2c618f795e9aca6c354d516c7dce278db"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java",
+ "sha256": "ff2cc8830645722173a257aec66adec94cfae7d5a91501b1024e2843954dc8f1"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java",
+ "sha256": "79e337d8fc495c1c993d33205f70d79a0baa5fe49c054ef7032f02ce500f147c",
+ "localChanges": true,
+ "upstreamSha256": "1830ac36651759f3b4f77bda5fb23fd4b478a2c153671fc01920af38faefd09f"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java",
+ "sha256": "8072d652209042f578c3eaf49600f8797ed19662b8119581772f60a3b972fa96"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java",
+ "sha256": "7ff4a54ab5003cd86046db3b35110b4906b97fc56b8d934f33e6f51eb96dd5ed"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java",
+ "sha256": "882485659c7e77833ebb383dd8175b7eede292596696f63678fbcd868c029806",
+ "localChanges": true,
+ "upstreamSha256": "33dec00015fc1611084bd99063e90dbce3c306e99b83faed1cd6a2f8cab24de7"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java",
+ "sha256": "ced28c084e0f0d1d5c42d29d1c85b6528e065b9a933f7a6ab0a4eae1bcd6a520"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Processes.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java",
+ "sha256": "86b50e196fb23ccd28e576b524a8da2d8928ac3113bbcd105180ceaef9981319",
+ "localChanges": true,
+ "upstreamSha256": "e1a499d9fc526179c624be1084188e2a394e46f5d5c512cc5c3e3b3d39661aeb"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java",
+ "sha256": "b491ba1a55f869bf29ba337684fe0a1c42c00b9ae8887dac508cc508748d419d"
+ },
+ {
+ "upstream": "sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java",
+ "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java",
+ "sha256": "c56519730a9243d5ce9e8333025456bd934890bd7ad134de3b8e8fb9fd28bfe4"
+ }
+ ]
+}
diff --git a/vendor/LICENSE b/vendor/LICENSE
new file mode 100644
index 0000000..69bef1d
--- /dev/null
+++ b/vendor/LICENSE
@@ -0,0 +1,203 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or
+ Object form, that is based on (or derived from) the Work and
+ for which the editorial revisions, annotations, elaborations,
+ or other modifications represent, as a whole, an original work
+ of authorship. For the purposes of this License, Derivative Works
+ shall not include works that remain separable from, or merely link
+ (or bind by name) to the interfaces of, the Work and Derivative Works
+ thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of
+ its distribution, then any Derivative Works that You
+ distribute must include a readable copy of the attribution
+ notices contained within such NOTICE file, excluding those
+ notices that do not pertain to any part of the Derivative
+ Works, in at least one of the following places: within a
+ NOTICE text file distributed as part of the Derivative Works;
+ within the Source form or documentation, if provided along with
+ the Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or as an addendum to
+ the NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing
+ the origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as
+ a result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[ ]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java
new file mode 100644
index 0000000..b71b683
--- /dev/null
+++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java
@@ -0,0 +1,1417 @@
+package io.github.litheidea.plugin.sdk;
+
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+
+/**
+ * The plugin backend session: one process the host starts from the plugin's
+ * manifest and talks to over stdio with the LSP base protocol.
+ *
+ *
The SDK owns everything Lithe manages uniformly -- the lifecycle, protocol
+ * negotiation, cancellation, error codes, and the {@code lithe/*} namespace --
+ * and leaves the plugin free to decide what its handlers do. Declare handlers,
+ * then call {@link #listen()}. Handlers run on their own threads, so several
+ * calls can be in flight at once; shared plugin state needs its own locking.
+ *
+ *
Host services ({@code lithe/host/*}) of plugin-function protocols 2 and 3
+ * are in {@link #host()}, or a handler's {@link CallContext#host()}.
+ *
+ *
Contract: {@code contract/v1/README.md} ("Build providers"
+ * and "Plugin functions"). Behaviour and error codes match the Node.js SDK.
+ */
+public final class Backend {
+ /** Answers a typed build request or a plugin function. */
+ @FunctionalInterface
+ public interface Handler {
+ Object handle(Map params, CallContext context) throws Exception;
+ }
+
+ /** Answers a standard LSP request, for a backend that is also a language server. */
+ @FunctionalInterface
+ public interface RequestHandler {
+ Object handle(Object params, CallContext context) throws Exception;
+ }
+
+ /** Handles a standard LSP notification. */
+ @FunctionalInterface
+ public interface NotificationHandler {
+ void handle(Object params) throws Exception;
+ }
+
+ /**
+ * Handles {@code lithe/host/commands/didRun} for one of the plugin's
+ * commands. {@code workspaceContext} is the {@code { contextID, generation }}
+ * of the window the command ran in, or null.
+ */
+ @FunctionalInterface
+ public interface CommandHandler {
+ void handle(String commandId, Map workspaceContext) throws Exception;
+ }
+
+ /** Runs before the {@code initialize} answer. */
+ @FunctionalInterface
+ public interface InitializeHook {
+ void run(Map params, Negotiated negotiated) throws Exception;
+ }
+
+ /** Runs on {@code shutdown}, after running calls were cancelled. */
+ @FunctionalInterface
+ public interface ShutdownHook {
+ void run() throws Exception;
+ }
+
+ /** Protocols the host agreed to in {@code initialize}. */
+ public static final class Negotiated {
+ static final Negotiated NONE = new Negotiated(0, 0);
+
+ private final int functionsVersion;
+ private final int buildVersion;
+
+ Negotiated(int functionsVersion, int buildVersion) {
+ this.functionsVersion = functionsVersion;
+ this.buildVersion = buildVersion;
+ }
+
+ /** Whether the host negotiated plugin functions ({@code litheFunctions}). */
+ public boolean functions() {
+ return functionsVersion > 0;
+ }
+
+ /**
+ * Selected plugin-function version (1-3), or zero when unavailable.
+ * Version 2 adds host credentials; version 3 workspace contexts, the
+ * other host services, and host notifications.
+ */
+ public int functionsVersion() {
+ return functionsVersion;
+ }
+
+ /** Whether the host negotiated typed build requests. */
+ public boolean build() {
+ return buildVersion > 0;
+ }
+
+ /** Selected build protocol version, or zero when unavailable. */
+ public int buildVersion() {
+ return buildVersion;
+ }
+ }
+
+ private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED }
+
+ /** Canonical result format of each typed build request. */
+ private static final Map BUILD_FORMATS;
+
+ static {
+ Map formats = new HashMap<>();
+ formats.put(Protocol.BUILD_MODEL, "litheBuildModel");
+ formats.put(Protocol.BUILD_DEPENDENCIES, "litheDependencies");
+ formats.put(Protocol.BUILD_DISCOVER_TESTS, "litheTestDiscovery");
+ BUILD_FORMATS = Collections.unmodifiableMap(formats);
+ }
+
+ private volatile boolean logging;
+ private boolean loggingReady;
+ private final List