diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d5a749..19a56dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,7 @@ name: CI on: pull_request: + types: [opened, synchronize, reopened, ready_for_review] push: branches: [main] @@ -50,6 +51,18 @@ jobs: # The oldest Maven also runs on the oldest Java. JAVA_HOME: ${{ matrix.maven == 'runner' && env.JAVA_HOME || env[format('JAVA_HOME_8_{0}', runner.arch)] }} run: node scripts/test.mjs + - name: Verify native compiler targets and local JARs + if: matrix.maven == 'runner' + run: | + node --test --test-timeout=15000 scripts/compiler/process.test.mjs + node scripts/compiler/test.mjs + - name: Upload native compiler projections + if: matrix.os == 'ubuntu-latest' && matrix.maven == 'runner' + uses: actions/upload-artifact@v4 + with: + name: native-compiler-projection + path: .artifacts/compiler/visual-*.json + if-no-files-found: error - name: Verify Linux and Windows release archives run: node --test --test-timeout=60000 scripts/package/*.test.mjs - name: Hand the Windows archive to the Windows job @@ -84,6 +97,45 @@ jobs: path: .artifacts/test-stability/ if-no-files-found: warn + native-settings-visual: + name: Native compiler settings screenshots + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + needs: package + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: native-compiler-projection + path: .artifacts/compiler + - name: Read pinned host revision + id: host + run: echo "revision=$(node -p 'JSON.parse(require("fs").readFileSync("compiler-host.json")).revision')" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: 1lck/Lithe-IDEA + ref: ${{ steps.host.outputs.revision }} + path: .artifacts/host + - uses: actions/setup-go@v5 + with: + go-version-file: .artifacts/host/desktop/go.mod + cache: false + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.100.0 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Render actual compiler projections through the native host + run: node scripts/compiler/visual.mjs .artifacts/host + - uses: actions/upload-artifact@v4 + with: + name: native-compiler-settings-screenshots + path: .artifacts/compiler/visual/ + if-no-files-found: error + retention-days: 14 + # The Windows archive built above, unpacked the way Lithe installs it (under # a path with a space), runs the declared commands through mvn.cmd. windows: @@ -138,6 +190,11 @@ jobs: run: | if ($env:MVN) { & $env:MVN --version } else { mvn --version } node scripts/test.mjs + - name: Verify native compiler settings and JARs in the installed Windows archive + if: matrix.maven == 'runner' + run: | + node --test --test-timeout=15000 scripts/compiler/process.test.mjs + node scripts/compiler/test.mjs - name: Upload script timing reports if: always() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1960a37..2361939 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -51,7 +51,7 @@ jobs: if [[ "$tag" == "$GITHUB_REF_NAME" ]]; then prerelease=true; fi done { - echo "兼容性:按插件契约 v0(schemaVersion 0、pluginAPIVersion 0)编写,需要新版 Lithe 桌面端(desktop-v* 预发布)。旧版 macOS Lithe 无法安装。" + echo "兼容性:按插件契约 v0(schemaVersion 0、pluginAPIVersion 0)编写,需要支持 sourceSettings 0 的 Lithe 桌面端。请先升级宿主;旧版宿主继续使用原有兼容插件版本。" echo if [[ -s "docs/releases/$GITHUB_REF_NAME.md" ]]; then cat "docs/releases/$GITHUB_REF_NAME.md" @@ -72,4 +72,4 @@ jobs: if [[ "$prerelease" == true ]]; then release_flags+=(--prerelease) fi - gh release create "$GITHUB_REF_NAME" dist/*.zip --title "Maven $GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/notes.md" "${release_flags[@]}" + gh release create "$GITHUB_REF_NAME" dist/*.zip --draft --title "Maven $GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/notes.md" "${release_flags[@]}" diff --git a/.gitignore b/.gitignore index f743058..a53e981 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ dist/ extension/target/ .DS_Store .cache/ +settings-backend/target/ diff --git a/compiler-host.json b/compiler-host.json new file mode 100644 index 0000000..1ee8332 --- /dev/null +++ b/compiler-host.json @@ -0,0 +1,6 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA", + "revision": "e9ce7781f1a9635ced8a090b45a159af4f5ce959", + "coreRevision": "5802c42b5766df7375bd427c54203db415ff72d7", + "package": "io.github.lithe-idea.maven-build" +} diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 34041ab..c608d94 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -177,6 +177,15 @@ ArtifactId);Maven Archetype 用内置或自定义原型,由 `mvn archetype 跨架构本地包检查通过不等于原生工作流验收。既有平台验证记录保持不变。 +## 原生编译设置与本地 JAR + +| 能力 | macOS | Windows | 证据 | +| --- | --- | --- | --- | +| 项目默认目标、按模块字节码、继承与显式保存 | implemented / pending | implemented / pending | `scripts/compiler/` 真实引擎回归,检查 class major 52/55;原生完整 UI 验收仍 pending | +| 原生 JAR 引用与编译运行 | implemented / pending | implemented / pending | `scripts/compiler/` 编译外部 JAR 并运行引用它的程序;配置与包的只读边界见 native-settings.md | + +2026-11-15:本地 macOS 自动化已通过,不将脚本通过等同于所有交互场景验收。Windows 的实机结果另随 PR 补充。 + ## Windows 安装包 | 能力 | Windows ARM64 | Windows x64 | 验证入口 | diff --git a/docs/native-settings.md b/docs/native-settings.md new file mode 100644 index 0000000..817dc9c --- /dev/null +++ b/docs/native-settings.md @@ -0,0 +1,15 @@ +# Maven 编译设置与本地 JAR + +在设置的“构建、执行、部署”中打开插件提供的编译器页,点击“读取编译设置”(构建工具会显示“使用项目工具读取编译设置”)。读取会使用项目工具,可能执行项目脚本或下载依赖。项目默认目标与模块覆盖分别显示;移除模块覆盖后继承项目配置。只有点击“保存”才写入 所选模块的 `pom.xml`,外部修改会要求重新读取。 + +管理 JDK:在“构建、执行、部署”的工具链区使用“全局默认”,选择自动识别结果,或从磁盘添加多个 JDK,核对版本后保存;无需先打开项目。个别项目可切换到“当前项目”单独覆盖。已启动的进程需重启后采用新版本。JDK 是运行编译器的程序;目标字节码决定生成的 class 版本,两者分别设置。构建工具自己的显式 Java 环境或工具链配置仍按该工具的规则生效。 + +本地 JAR 入口在插件的语言/构建工具设置页,点击“读取本地 JAR 依赖”,选择目标模块并浏览文件后保存。每行一个路径,空格属于路径内容。模块与有效值来自 Maven 的实际项目模型,包含启用的 Profiles。每个模块可单独覆盖目标字节码。新增本地 JAR 使用原生 system 作用域依赖;团队共享项目优先在 POM 中添加仓库依赖。 + +运行时状态和暂存放在宿主提供的用户状态/临时目录;插件安装包始终只读。暂存文件由一次保存拥有,完成或取消时删除,不跨工作树共享。新后端与翻译由各平台构建入口打入同一版本包并校验。 + +## Compatibility + +This version requires a desktop host advertising `sourceSettings: 0`. Older hosts retain their previous compatible plugin version. Read compiler settings under Build, Execution, Deployment; read local JAR dependencies on the language/build-system page. Save changes only the listed native sources and rejects a changed baseline. JDK selection and target bytecode are separate settings. + +Tests in `scripts/compiler/` execute the real upstream engine, inspect class-file major versions and run code using an external JAR. HTML and JUnit timing reports are written to `.artifacts/test-stability/`; tests own and clean their temporary workspaces and processes. diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md new file mode 100644 index 0000000..0031f5e --- /dev/null +++ b/docs/releases/v1.0.0.md @@ -0,0 +1,23 @@ +# Maven 1.0.0 + +## 中文 + +- 新增真实项目编译设置、项目默认目标与按模块字节码覆盖,保存后重新读取生效配置。 +- 新增本地 JAR 引用入口,保留无关的项目配置与注释。 +- 保留 0.2.1 已提供的 Windows 安装包与路径兼容修复。 + +### 兼容性 + +此主版本新增 `sourceSettings: 0` 宿主要求;旧宿主无法安装,应继续使用上一兼容版本或先升级桌面端。读取项目工具可能执行项目代码及下载依赖;仅明确保存才修改列出的配置文件。详见 [编译设置说明](../native-settings.md)。 + +--- + +## English + +- Add native compiler settings with project defaults, per-module bytecode overrides and effective-value readback. +- Add local JAR dependencies while preserving unrelated project configuration and comments. +- Retain the Windows archives and native path fixes already available in 0.2.1. + +### Compatibility + +This major release requires `sourceSettings: 0`. Upgrade the desktop host first, or keep the previous compatible plugin version. Reading project tools may execute project code and download dependencies. Only explicit Save changes the displayed native sources. diff --git a/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go new file mode 100644 index 0000000..a8b3fab --- /dev/null +++ b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go @@ -0,0 +1,134 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/headless" +) + +// This plugin-owned overlay renders the public projection captured from its real +// engine tests. It does not publish files; native publication is tested separately. +type pluginNativeVisualSource struct { + store *pluginsettings.Store + manifest json.RawMessage + packageRoot, workspace string + sources pluginsettings.SourceEditor +} + +func (s *pluginNativeVisualSource) Load(ctx context.Context, _ string, language i18n.Language) (pluginservice.SettingsEditor, error) { + snapshot, err := s.store.LoadPresented(ctx, s.manifest, s.workspace, pluginsettings.Presentation{Package: s.packageRoot, Language: language.Code()}) + return pluginservice.SettingsEditor{Snapshot: snapshot}, err +} +func (s *pluginNativeVisualSource) Save(context.Context, pluginservice.SettingsEditor, string, []core.PluginSettingEdit) (pluginsettings.SaveResult, error) { + return pluginsettings.SaveResult{}, errors.New("visual capture never publishes") +} +func (s *pluginNativeVisualSource) Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) { + return pluginservice.SettingsActionResult{Plan: core.PluginSettingsActionPlan{Kind: "invoke", ActionID: "compiler", SourceEditor: true}, Sources: &s.sources}, nil +} +func (s *pluginNativeVisualSource) SaveSources(context.Context, pluginservice.SettingsEditor, string, pluginsettings.SourceEditor, []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) { + return s.sources, errors.New("visual capture never publishes") +} + +func TestPluginNativeSourceVisual(t *testing.T) { + packageRoot, input, out := os.Getenv("LITHE_NATIVE_PACKAGE"), os.Getenv("LITHE_NATIVE_SNAPSHOTS"), os.Getenv("LITHE_NATIVE_OUTPUT") + if packageRoot == "" || input == "" || out == "" { + t.Fatal("run the plugin's scripts/compiler/visual.mjs") + } + manifest, err := os.ReadFile(filepath.Join(packageRoot, "plugin.json")) + if err != nil { + t.Fatal(err) + } + var metadata struct { + ID, DisplayName, Version string + SettingActions []struct { + ID string + Page struct{ CompilerID string } + } + } + if err = json.Unmarshal(manifest, &metadata); err != nil { + t.Fatal(err) + } + admission, cancelAdmission := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelAdmission() + if _, err = core.NewClient().ValidatePluginManifest(admission, manifest, pluginhost.Declared()); err != nil { + t.Fatal(err) + } + compilerID := "" + for _, action := range metadata.SettingActions { + if action.ID == "compiler" { + compilerID = action.Page.CompilerID + } + } + if compilerID == "" { + t.Fatal("compiler action missing") + } + if err = os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"-"+theme, func(t *testing.T) { + code := "en" + if language == i18n.Chinese { + code = "zh" + } + raw, err := os.ReadFile(filepath.Join(input, "visual-"+code+".json")) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + state, err := core.NewClient().ReadSourceSettings(ctx, raw) + if err != nil { + t.Fatal(err) + } + source := &pluginNativeVisualSource{store: pluginsettings.New(core.NewClient(), t.TempDir()), manifest: manifest, packageRoot: packageRoot, workspace: t.TempDir(), sources: pluginsettings.SourceEditor{State: state}} + fetch := func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: []core.MarketplacePlugin{{ID: metadata.ID, Name: metadata.DisplayName, LatestVersion: metadata.Version}}}}, nil + } + w := newWindow(NewController(Options{Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, PluginSettings: source, SettingsNavigation: core.NewClient().SettingsNavigation, SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { + return core.NewClient().SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: metadata.ID, Version: metadata.Version}, Enabled: true}}) + }, Marketplace: fetch, MarketplaceInstalled: fetch, PluginState: func(string) PluginState { + return PluginState{Installed: true, Enabled: true, Version: metadata.Version} + }}), Values{Theme: theme, Language: language.Code()}) + config := w.config() + config.Width, config.Height = 1120, 900 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.until("compiler contribution", func() bool { return len(w.dynamic.pages) > 0 }) + w.selectSettingsPage(pageBuild, "compiler:"+compilerID) + d.until("compiler read action", func() bool { return w.pluginSettings.pageKey == w.dynamicPage && w.pluginSettings.loaded }) + title := "" + for _, action := range w.pluginSettings.editor.Snapshot.State.Actions { + if action.ID == "compiler" { + title = action.Title + } + } + d.click(title) + d.until("native compiler form", func() bool { return w.pluginSettings.sources != nil }) + d.pump() + if err = session.Screenshot(filepath.Join(out, "compiler-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/extension/pom.xml b/extension/pom.xml index d02a14b..f058e3c 100644 --- a/extension/pom.xml +++ b/extension/pom.xml @@ -15,7 +15,7 @@ io.github.lithe-idea lithe-maven-extension - 0.2.1 + 1.0.0 jar Lithe Maven extension diff --git a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java index 36a778a..1a685c9 100644 --- a/extension/src/main/java/io/github/litheidea/maven/ModelExport.java +++ b/extension/src/main/java/io/github/litheidea/maven/ModelExport.java @@ -74,6 +74,11 @@ Map document() { properties.put("artifactId", project.getArtifactId()); properties.put("version", project.getVersion()); properties.put("packaging", project.getPackaging()); + compilerFacts(project, properties); + if(project.getParent()!=null){ + Map inherited=new LinkedHashMap<>();compilerFacts(project.getParent(),inherited); + for(String key:new String[]{"target","releaseEnabled","debug","showDeprecation","showWarnings","arguments"})if(inherited.containsKey("compiler."+key))properties.put("compiler.inherited."+key,inherited.get("compiler."+key)); + } entry.put("properties", properties); projects.add(entry); if (!"pom".equals(project.getPackaging())) { @@ -183,6 +188,49 @@ private void addGoals(MavenProject project, String owner, List tasks) { } } + /** Query Maven's merged plugin model and native parameter evaluator. No + * module/configuration model is inferred by the desktop or the backend. */ + private void compilerFacts(MavenProject project, Map output) { + Plugin compiler=null; + for(Plugin candidate:project.getBuildPlugins()) if("maven-compiler-plugin".equals(candidate.getArtifactId())) {compiler=candidate.clone();break;} + if(compiler==null) return; + try { + if(compiler.getVersion()==null) compiler.setVersion(versionResolver.resolve(new DefaultPluginVersionRequest(compiler,session)).getVersion()); + PluginDescriptor descriptor=pluginManager.getPluginDescriptor(compiler,project.getRemotePluginRepositories(),session.getRepositorySession()); + MojoDescriptor mojo=descriptor.getMojo("compile"); + org.apache.maven.plugin.MojoExecution execution=new org.apache.maven.plugin.MojoExecution(mojo,"default-compile"); + org.codehaus.plexus.util.xml.Xpp3Dom merged=project.getGoalConfiguration("org.apache.maven.plugins","maven-compiler-plugin","default-compile","compile"); + execution.setConfiguration(merged); + org.apache.maven.plugin.PluginParameterExpressionEvaluator evaluator=new org.apache.maven.plugin.PluginParameterExpressionEvaluator(session,execution); + for(String key:new String[]{"source","target","release","debug","showDeprecation","showWarnings"}) { + org.codehaus.plexus.util.xml.Xpp3Dom node=merged==null?null:merged.getChild(key); + Object value=node==null?null:evaluator.evaluate(node.getValue()); + if(value==null) value=project.getProperties().getProperty("maven.compiler."+key); + if(value==null && mojo.getMojoConfiguration()!=null) { + org.codehaus.plexus.configuration.PlexusConfiguration defaults=mojo.getMojoConfiguration().getChild(key,false); + if(defaults!=null) { + String expression=defaults.getValue(null); + if(expression!=null) value=evaluator.evaluate(expression); + if(value==null || value.toString().contains("${")) value=defaults.getAttribute("default-value",null); + } + } + if(value!=null&&!value.toString().contains("${")) output.put("compiler."+key,value.toString()); + } + List arguments=new ArrayList<>(); + org.codehaus.plexus.util.xml.Xpp3Dom args=merged==null?null:merged.getChild("compilerArgs"); + if(args!=null) for(org.codehaus.plexus.util.xml.Xpp3Dom arg:args.getChildren()) { + Object evaluated=evaluator.evaluate(arg.getValue()); + if(evaluated!=null) arguments.add(evaluated.toString()); + } + output.put("compiler.arguments",Json.write(arguments)); + Object release=output.get("compiler.release"); + output.put("compiler.releaseEnabled",Boolean.toString(release!=null&&!release.toString().isEmpty())); + if(release!=null&&!release.toString().isEmpty()) output.put("compiler.target",release.toString()); + } catch(Exception failure) { + throw new IllegalStateException("Maven compiler settings could not be evaluated.",failure); + } + } + /** * The goal prefix and goals of a plugin. The descriptor needs the plugin * jar, which Maven downloads like any build would; offline or without diff --git a/io.github.lithe-idea.maven-build/l10n/zh-Hans.json b/io.github.lithe-idea.maven-build/l10n/zh-Hans.json new file mode 100644 index 0000000..b3530d6 --- /dev/null +++ b/io.github.lithe-idea.maven-build/l10n/zh-Hans.json @@ -0,0 +1,12 @@ +{ + "settingActions": { + "compiler": { + "title": "使用项目工具读取编译设置", + "description": "读取工具的实际配置;保存时写入页面列出的原生配置文件。读取可能执行项目代码并下载依赖。" + }, + "libraries": { + "title": "读取本地 JAR 依赖", + "description": "读取项目实际引用的 JAR;保存时更新页面列出的原生配置文件。读取可能执行项目代码并下载依赖。" + } + } +} diff --git a/io.github.lithe-idea.maven-build/plugin.json b/io.github.lithe-idea.maven-build/plugin.json index 77c1951..8de588b 100644 --- a/io.github.lithe-idea.maven-build/plugin.json +++ b/io.github.lithe-idea.maven-build/plugin.json @@ -2,11 +2,11 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.maven-build", "displayName": "Maven", - "version": "0.2.1", + "version": "1.0.0", "pluginAPIVersion": 0, - "requires": {"buildSystems": 0, "projectGenerators": 0, "settings": 0}, + "requires": {"buildSystems": 0, "projectGenerators": 0, "settings": 0, "backend": 0, "sourceSettings": 0}, "vendor": {"id": "io.github.lithe-idea", "displayName": "Lithe Community", "signatureRequirement": "none"}, - "permissions": ["process.build", "project.generate"], + "permissions": ["process.build", "project.generate", "backend.launch", "workspace.metadata"], "activationEvents": ["onBuildSystem:maven"], "settings": [ { @@ -28,6 +28,7 @@ "icon": {"path": "icons/maven.svg"}, "detection": {"markers": ["pom.xml"], "nesting": "outermost"}, "invocation": { + "runtimeDependencies": [{"id": "java", "minimumVersion": "8", "executables": [{"kind": "toolchain", "toolchainID": "java"}, {"kind": "environment", "variable": "JAVA_HOME", "path": "bin/java", "platforms": ["macos", "linux"]}, {"kind": "environment", "variable": "JAVA_HOME", "path": "bin/java.exe", "platforms": ["windows"]}, {"kind": "command", "command": "java"}], "version": {"arguments": ["-version"], "pattern": "version \"(?:1\\.)?(\\d+(?:\\.\\d+)*)"}}], "executables": [ {"id": "selected", "kind": "setting", "settingID": "mavenExecutable"}, { @@ -51,7 +52,7 @@ {"kind": "environment", "variable": "MAVEN_HOME", "path": "bin/mvn.cmd", "platforms": ["windows"]}, {"kind": "command", "command": "mvn"} ], - "environmentInputs": ["MAVEN_HOME"], + "environmentInputs": ["MAVEN_HOME", "JAVA_HOME"], "globalArguments": [ "-B", "-ntp", @@ -529,5 +530,8 @@ ], "openFiles": ["pom.xml"] } - ] + ], + "requiresTools": ["java"], + "backend": {"launch": {"kind": "runtime", "tool": "java", "minimumVersion": "8", "entry": "lib/lithe-maven-settings.jar", "runtimeArguments": ["-Xms16m", "-Xmx96m"]}}, + "settingActions": [{"id": "compiler", "title": "Read compiler settings", "description": "Read actual project settings using the project tool. This can execute project code and download dependencies. Save writes the displayed native configuration files.", "function": "compiler.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "buildSystemID": "maven"}, "page": {"compilerID": "maven"}}, {"id": "libraries", "title": "Read local JAR dependencies", "description": "Read actual project settings using the project tool. This can execute project code and download dependencies. Save writes the displayed native configuration files.", "function": "libraries.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "buildSystemID": "maven"}, "page": {"buildSystemID": "maven"}}] } diff --git a/scripts/compiler/backend-client.mjs b/scripts/compiler/backend-client.mjs new file mode 100644 index 0000000..27c70a1 --- /dev/null +++ b/scripts/compiler/backend-client.mjs @@ -0,0 +1,175 @@ +// Talks to lib/lithe-maven-settings.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 { execFileSync, spawn } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export const WAIT_MS = 20_000; +const MAX_FRAME_BYTES = 16 * 1024 * 1024; +const MAX_HEADER_BYTES = 8 * 1024; +const MAX_STDERR_BYTES = 64 * 1024; +const MAX_DIAGNOSTICS = 1000; + +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: process.platform !== "win32", windowsHide: 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 = Buffer.concat([Buffer.from(this.stderr), chunk]).subarray(-MAX_STDERR_BYTES).toString("utf8"); + }); + 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: [0] } } : { litheBuild: { versions: [0] } }), + litheLogging: { versions: [0] }, + } }, + }); + 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 || this.child.exitCode !== null || this.child.signalCode !== null) return; + if (process.platform === "win32") { + try { + execFileSync("taskkill.exe", ["/PID", String(this.child.pid), "/T", "/F"], {timeout: 5000, windowsHide: true, stdio: "ignore"}); + } catch (error) { + // taskkill returns 128 when the owned process exited before it ran. + if (error.status !== 128) throw error; + } + 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) { + if (this.#buffer.length + chunk.length > MAX_FRAME_BYTES + MAX_HEADER_BYTES) return this.#broken("an oversized input buffer"); + this.#buffer = Buffer.concat([this.#buffer, chunk]); + for (;;) { + const headerEnd = this.#buffer.indexOf("\r\n\r\n"); + if (headerEnd < 0) { + if (this.#buffer.length > MAX_HEADER_BYTES) return this.#broken("an oversized frame header"); + return; + } + if (headerEnd > MAX_HEADER_BYTES) return this.#broken("an oversized frame header"); + const length = Number(/Content-Length: *(\d+)/i.exec(this.#buffer.subarray(0, headerEnd).toString("ascii"))?.[1]); + if (length > MAX_FRAME_BYTES) return this.#broken("an oversized frame"); + 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") { + if (this.diagnostics.length >= MAX_DIAGNOSTICS) return this.#broken("too many diagnostic facts"); + 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/compiler/capture.mjs b/scripts/compiler/capture.mjs new file mode 100644 index 0000000..61c4dae --- /dev/null +++ b/scripts/compiler/capture.mjs @@ -0,0 +1,7 @@ +// Captures only the public non-sensitive projection for plugin-owned visual checks. +import {mkdirSync,writeFileSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +export function capture(language,snapshot){ + const root=resolve('.artifacts/compiler');mkdirSync(root,{recursive:true}); + writeFileSync(join(root,`visual-${language}.json`),JSON.stringify(snapshot,null,2)); +} diff --git a/scripts/compiler/process.mjs b/scripts/compiler/process.mjs new file mode 100644 index 0000000..1af2ac4 --- /dev/null +++ b/scripts/compiler/process.mjs @@ -0,0 +1,37 @@ +// Integration-test tools run in owned process trees with bounded output and cleanup. +import {spawn,execFile} from 'node:child_process'; +import {windowsCommandLine} from '../process.mjs'; +const LIMIT=2*1024*1024; +export function runTool(tool,args,{cwd,env=process.env,timeout=120000}={}) { + let command=tool,parameters=args,verbatim=false; + if(process.platform==='win32'&&(/\.(cmd|bat)$/i.test(tool)||!/[.][^\\/]+$/.test(tool))) { + command=process.env.ComSpec??'cmd.exe';parameters=['/d','/v:off','/s','/c',`"${windowsCommandLine(tool,args)}"`];verbatim=true; + } + return new Promise((resolve,reject)=>{ + const child=spawn(command,parameters,{cwd,env,detached:process.platform!=='win32',windowsHide:true,windowsVerbatimArguments:verbatim,stdio:['ignore','pipe','pipe']}); + let output=Buffer.alloc(0),errorOutput=Buffer.alloc(0),failure,done=false,stopping=false,cleanup; + const kill=()=>{ + if(!child.pid)return; + if(process.platform==='win32') { + if(child.exitCode!==null)return; + execFile('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{timeout:5000,windowsHide:true},error=>{if(error&&child.exitCode===null)failure??=error;}); + } else {try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')failure??=error;}} + }; + const finish=()=>{ + if(done)return;done=true;clearTimeout(timer);clearTimeout(cleanup); + process.off('SIGINT',interrupt);process.off('SIGTERM',interrupt); + if(failure)reject(failure);else if(child.exitCode!==0)reject(Error(`Tool failed (${child.exitCode}): ${errorOutput.toString()}\n${output.toString()}`));else resolve(output); + }; + const stop=error=>{ + failure??=error;if(stopping)return;stopping=true;kill(); + cleanup=setTimeout(()=>{kill();child.stdout.destroy();child.stderr.destroy();child.unref();failure=Error('Tool cleanup timed out',{cause:failure});finish();},6000); + }; + const interrupt=()=>stop(Error('Tool interrupted')); + const timer=setTimeout(()=>stop(Error('Tool timed out')),timeout); + process.once('SIGINT',interrupt);process.once('SIGTERM',interrupt); + child.stdout.on('data',bytes=>{if(output.length+bytes.length>LIMIT)stop(Error('Tool output exceeds limit'));else output=Buffer.concat([output,bytes]);}); + child.stderr.on('data',bytes=>{if(errorOutput.length+bytes.length>LIMIT)stop(Error('Tool error output exceeds limit'));else errorOutput=Buffer.concat([errorOutput,bytes]);}); + child.once('error',error=>stop(error)); + child.once('close',()=>{kill();finish();}); + }); +} diff --git a/scripts/compiler/process.test.mjs b/scripts/compiler/process.test.mjs new file mode 100644 index 0000000..014a15a --- /dev/null +++ b/scripts/compiler/process.test.mjs @@ -0,0 +1,22 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {runTool} from './process.mjs'; +import {mkdtempSync,writeFileSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +test('Windows resolves a bare batch launcher through PATH and preserves spaces',{skip:process.platform!=='win32'},async()=>{ + const root=mkdtempSync(join(tmpdir(),'lithe batch-')); + try{ + writeFileSync(join(root,'lithe-fixture.cmd'),'@echo off\r\necho %~1\r\n'); + const output=await runTool('lithe-fixture',['space inside'],{env:{...process.env,PATH:root+';'+process.env.PATH},timeout:5000}); + assert.equal(output.toString().trim(),'space inside'); + }finally{rmSync(root,{recursive:true,force:true});} +}); +test('bounded tool runner returns output and rejects a failed command',async()=>{ + assert.equal((await runTool(process.execPath,['-e','process.stdout.write("ready")'])).toString(),'ready'); + await assert.rejects(runTool(process.execPath,['-e','process.exit(3)']),/Tool failed/); +}); +test('a tool deadline terminates an owned tree including its descendant',async()=>{ + const code=`const {spawn}=require('node:child_process');spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});setInterval(()=>{},1000);`; + await assert.rejects(runTool(process.execPath,['-e',code],{timeout:2500}),/Tool timed out/); +}); diff --git a/scripts/compiler/test.mjs b/scripts/compiler/test.mjs new file mode 100644 index 0000000..26be85c --- /dev/null +++ b/scripts/compiler/test.mjs @@ -0,0 +1,44 @@ +// Real Maven + packaged SDK backend: native inheritance, a module override, +// local JAR compilation, external edits and cancellation-free process cleanup. +import assert from 'node:assert/strict'; +import {createReport} from '../report.mjs'; +import {capture} from './capture.mjs'; +import {mkdtempSync,realpathSync,mkdirSync,writeFileSync,readFileSync,renameSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join,resolve,relative} from 'node:path'; +import {runTool} from './process.mjs'; +import {createHash} from 'node:crypto'; +import {BackendClient,bounded} from './backend-client.mjs'; +const scratch=realpathSync.native(mkdtempSync(join(tmpdir(),'lithe-maven-compiler-'))); +const pkg=resolve(process.env.LITHE_TEST_PLUGIN_DIR??'dist/package/io.github.lithe-idea.maven-build'); +const maven=process.env.MVN??'mvn'; +const root=join(scratch,'workspace');mkdirSync(root); +const command=(tool,args,cwd=root)=>runTool(tool,args,{cwd,timeout:120000}); +const pom=(body)=>`4.0.0${body}`; +const file=join(root,'pom.xml'); +writeFileSync(file,pom('fixtureparent1pomabnever-export-thisorg.apache.maven.pluginsmaven-compiler-plugin3.13.011-parameters')); +for(const name of ['a','b']) {mkdirSync(join(root,name,'src/main/java'),{recursive:true});writeFileSync(join(root,name,'pom.xml'),pom(`fixtureparent1${name}`));writeFileSync(join(root,name,'src/main/java/Main.java'),'public class Main { public static void main(String[] args) { System.out.print("ok"); } }');} +const digest=bytes=>'sha256:'+createHash('sha256').update(bytes).digest('hex'); +let client; +const report=createReport('native-compiler'); +const step=report.step; +async function model(){const output=join(scratch,'model.json');await command(maven,['-B','-ntp','-q',`-Dmaven.ext.class.path=${join(pkg,'lib/lithe-maven-extension.jar')}`,`-Dlithe.modelOutput=${output}`,'pre-clean']);const model=JSON.parse(readFileSync(output));for(const project of model.projects)project.path=relative(root,project.path).replaceAll('\\','/')||'.';return model;} +try{ + client=new BackendClient({java:process.env.LITHE_TEST_JAVA??'java',jar:join(pkg,'lib/lithe-maven-settings.jar'),args:[],hostRequests:{'lithe/host/workspace/getFolders':()=>({folders:[{rootID:'r',name:'workspace',path:root}]})}}); + await client.initialize(root,{functions:true}); + let operation=0; + const invoke=async(functionID,params)=>client.request('lithe/function/invoke',{functionID,operationID:`compiler-${++operation}`,params,context:{contextID:'compiler',generation:1}}); + const read=async(language='zh-CN')=>invoke('compiler.settings',{context:{language,builds:[{root:'.',options:{},tool:{executable:maven},model:await model()}]}}); + let snapshot; + await step('Read actual Maven inheritance without modifying a POM or exposing private fields',async()=>{const original=readFileSync(file);snapshot=await read();assert.deepEqual(readFileSync(file),original);assert.equal(JSON.stringify(snapshot).includes('never-export-this'),false);assert.equal(snapshot.sources.length,3);assert.deepEqual(snapshot.sources.find(s=>s.path==='pom.xml').fields.find(f=>f.id==='arguments').effectiveValue,['-parameters']);for(const source of snapshot.sources)assert.equal(source.fields.find(f=>f.id==='target').effectiveValue,'11');assert.equal(snapshot.sources.find(s=>s.path==='a/pom.xml').fields.find(f=>f.id==='target').value,null);}); + await step('Save only module a bytecode override, compile and inspect the class header',async()=>{const source=snapshot.sources.find(s=>s.path==='a/pom.xml');const stage=join(scratch,'staged-pom.xml');writeFileSync(stage,'');const reply=await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{target:'8'},outputFile:stage});assert.equal(reply.revision,digest(readFileSync(stage)));assert.equal(readFileSync(join(root,'a/pom.xml'),'utf8').includes('8'),false,'backend must not publish');renameSync(stage,join(root,'a/pom.xml'));await command(maven,['-B','-ntp','-q','compile']);assert.equal(readFileSync(join(root,'a/target/classes/Main.class')).readUInt16BE(6),52);assert.equal(readFileSync(join(root,'b/target/classes/Main.class')).readUInt16BE(6),55);snapshot=await read();assert.equal(snapshot.sources.find(s=>s.path==='a/pom.xml').fields.find(f=>f.id==='target').effectiveValue,'8');assert.equal(snapshot.sources.find(s=>s.path==='a/pom.xml').fields.find(f=>f.id==='target').inheritedValue,'11');assert.match(readFileSync(file,'utf8'),/keep-comment/);}); + capture('zh',snapshot);capture('en',await read('en')); + await step('A local JAR is written as a native dependency and used by Maven compilation',async()=>{const dir=join(scratch,'jar');mkdirSync(dir);writeFileSync(join(dir,'Library.java'),'package fixture; public class Library { public static String value() { return "jar-ok"; } }');await command('javac',['--release','8','-d',dir,join(dir,'Library.java')]);const jar=join(scratch,'External Library.jar');await command('jar',['--create','--file',jar,'-C',dir,'fixture']);const source=snapshot.sources.find(s=>s.path==='a/pom.xml'),stage=join(scratch,'library-pom.xml');writeFileSync(stage,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{libraries:[jar]},outputFile:stage});renameSync(stage,join(root,'a/pom.xml'));writeFileSync(join(root,'a/src/main/java/Main.java'),'public class Main { public static void main(String[] args) { System.out.print(fixture.Library.value()); } }');await command(maven,['-B','-ntp','-q','compile']);assert.equal((await command('java',['-cp',join(root,'a/target/classes')+requirePathSeparator()+jar,'Main'])).toString(),'jar-ok');snapshot=await read();}); + await step('A changed POM and a removed staging file are rejected without overwriting project content',async()=>{const source=snapshot.sources.find(s=>s.path==='a/pom.xml');const original=readFileSync(join(root,'a/pom.xml'));writeFileSync(join(root,'a/pom.xml'),Buffer.concat([original,Buffer.from('\n')]));const stage=join(scratch,'conflict.xml');writeFileSync(stage,'');await assert.rejects(invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{target:'11'},outputFile:stage}));assert.equal(readFileSync(stage).length,0);assert.match(readFileSync(join(root,'a/pom.xml'),'utf8'),/external/);}); + await step('SDK successes distinguish native saves from read projections',async()=>{assert.equal(client.diagnostics.some(f=>f.operation==='compiler.settings'&&f.kind==='operationFinished'),false);assert.equal(client.diagnostics.some(f=>f.operation==='compiler.prepareSettings'&&f.kind==='operationFinished'),true);assert.equal(JSON.stringify(client.diagnostics).includes('never-export-this'),false);}); + assert.equal(await client.close(),0);client=undefined; +}finally{ + if(client){client.kill();await bounded(client.exited,'compiler backend cleanup');} + report.write();rmSync(scratch,{recursive:true,force:true}); +} +function requirePathSeparator(){return process.platform==='win32'?';':':';} diff --git a/scripts/compiler/visual.mjs b/scripts/compiler/visual.mjs new file mode 100644 index 0000000..d612300 --- /dev/null +++ b/scripts/compiler/visual.mjs @@ -0,0 +1,16 @@ +// Plugin-owned tests are injected through a Go overlay; no test or plugin data +// is copied into the host repository. Pass an explicit host checkout to validate. +import {readFileSync,writeFileSync,mkdirSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {runTool} from './process.mjs'; +const root=fileURLToPath(new URL('../..',import.meta.url)); +const host=resolve(process.argv[2]??'');if(!process.argv[2])throw Error('Usage: node scripts/compiler/visual.mjs '); +const manifest=JSON.parse(readFileSync(join(root,'compiler-host.json'))); +const stage=join(root,'.artifacts/compiler');mkdirSync(stage,{recursive:true}); +const target=join(host,'desktop/internal/settingswindow/plugin_native_source_test.go'); +const overlay=join(stage,'overlay.json');writeFileSync(overlay,JSON.stringify({Replace:{[target]:join(root,'e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go')}})); +const revision=(await runTool('git',['-C',host,'rev-parse','HEAD'])).toString().trim(); +writeFileSync(join(stage,'visual-host.json'),JSON.stringify({repository:manifest.repository,revision,core:process.env.LITHE_CORE_RUST_DIR??'host pin'},null,2)); +const result=await runTool(process.env.LITHE_TEST_BASH??'bash',['scripts/desktop/desktop-go.sh','test','-overlay',overlay,'-tags','vivahead lithevisual','./internal/settingswindow','-run','^TestPluginNativeSourceVisual$','-count=1','-timeout=120s'],{cwd:host,env:{...process.env,LITHE_NATIVE_PACKAGE:join(root,manifest.package),LITHE_NATIVE_SNAPSHOTS:stage,LITHE_NATIVE_OUTPUT:join(stage,'visual')},timeout:1200000}); +process.stdout.write(result); diff --git a/scripts/package.mjs b/scripts/package.mjs index 5c48dca..191792d 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -15,9 +15,10 @@ // Usage: node scripts/package.mjs [--expect-tag ] import { mavenTimeout, runCommand, withInterrupts, ZIP_TIMEOUT_MS } from "./process.mjs"; +import { verifySdk } from "./sdk/verify-sdk.mjs"; import { createReport } from "./report.mjs"; import { createHash } from "node:crypto"; -import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; @@ -83,6 +84,13 @@ function assertNoLinks(directory) { const report = createReport("package"); const timeoutMs = mavenTimeout(); await withInterrupts(async (signal) => { + await verifySdk(); + const build = "settings-backend/target"; + function sources(path) {return readdirSync(path,{withFileTypes:true}).flatMap(e=>e.isDirectory()?sources(join(path,e.name)):e.name.endsWith(".java")?[join(path,e.name)]:[]);} + rmSync(build,{recursive:true,force:true});mkdirSync(join(build,"classes"),{recursive:true}); + await runCommand("javac",["--release","8","-encoding","UTF-8","-d",join(build,"classes"),...sources("settings-backend/src/main/java"),...sources("vendor/lithe-plugin-sdk-java/src/main/java")],{timeoutMs,signal}); + writeFileSync(join(build,"MANIFEST.MF"),`Main-Class: io.github.litheidea.maven.settings.MavenSettings\nImplementation-Version: ${manifest.version}\n`); + await runCommand("jar",["--create","--file",join(build,"lithe-maven-settings.jar"),"--manifest",join(build,"MANIFEST.MF"),"--date","2026-11-15T00:00:00Z","-C",join(build,"classes"),"."],{timeoutMs,signal}); try { await report.step("build the Maven extension", async () => { await runCommand(process.env.MVN ?? "mvn", ["-B", "-ntp", "-q", "-f", "extension/pom.xml", "clean", "package"], { timeoutMs, signal }); @@ -96,6 +104,8 @@ await withInterrupts(async (signal) => { cpSync(PACKAGE_DIR, packageRoot, { recursive: true }); mkdirSync(join(packageRoot, "lib"), { recursive: true }); cpSync(EXTENSION_JAR, join(packageRoot, "lib", "lithe-maven-extension.jar")); + cpSync("settings-backend/target/lithe-maven-settings.jar",join(packageRoot,"lib","lithe-maven-settings.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..78028b8 --- /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-core-rust') { + 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) + || Object.hasOwn(entry, 'localChanges') || !entry.upstream?.startsWith('shared/plugins/')) { + 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.mjs b/scripts/test.mjs index 1ddccad..012472e 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -130,7 +130,7 @@ async function test(signal) { assert.deepEqual(model.projects.map((project) => project.name), ["reactor", "core", "app"]); assert.equal(byName("reactor").displayName, "Demo Reactor"); assert.equal(byName("core").parent, byName("reactor").path); - assert.deepEqual(byName("app").properties, { + assert.deepEqual(Object.fromEntries(["groupId","artifactId","version","packaging"].map(key=>[key,byName("app").properties[key]])), { groupId: "demo", artifactId: "app", version: "1.0.0-SNAPSHOT", diff --git a/sdk.lock.json b/sdk.lock.json new file mode 100644 index 0000000..e3ea8ae --- /dev/null +++ b/sdk.lock.json @@ -0,0 +1,89 @@ +{ + "schemaVersion": 1, + "source": { + "repository": "https://github.com/Lithe-IDEA/Lithe-core-rust", + "revision": "9425469bdaa5a8195d9cdf5e9f440165c9e79810" + }, + "files": [ + { + "upstream": "shared/plugins/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": "3be1cee3007bc55786ae62894d2366aabce2a9af0669acfbc030e0afe3d90c9e" + }, + { + "upstream": "shared/plugins/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": "eb25a8b572de751411eab4380d044907b8fe40acf33889fa759e3b6be325ef45" + }, + { + "upstream": "shared/plugins/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" + }, + { + "upstream": "shared/plugins/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": "shared/plugins/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": "1268691d9cb950776e9f659d11d9480e51069e90aa6437f2809ac0e00c3a57d4" + }, + { + "upstream": "shared/plugins/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": "shared/plugins/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": "974c51e84638f5e708cab471100d9cfcc7f7ff9af568f309c8285bd4c5e9455d" + }, + { + "upstream": "shared/plugins/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": "7c3e15d5ea79f17374371cc32c4b983f1274289cc0741870f6cccc9c55ff5553" + }, + { + "upstream": "shared/plugins/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": "fc24c7ede0363c32c11b4bea6b879401524267b90f2db9930fda1338b32e4bf3" + }, + { + "upstream": "shared/plugins/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": "shared/plugins/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" + }, + { + "upstream": "shared/plugins/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": "shared/plugins/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": "a8ab4b1e5dc2d4eac2cbe90eb302517cab6f0283c210f8c64f2e01edaceb318d" + }, + { + "upstream": "shared/plugins/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": "c6e2fa8db5ffec78e757f3bdc4622e2beb6f697178f3631fd53e29e9237e29b7" + }, + { + "upstream": "shared/plugins/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" + }, + { + "upstream": "shared/plugins/LICENSE", + "path": "vendor/LICENSE", + "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" + } + ] +} diff --git a/settings-backend/src/main/java/io/github/litheidea/maven/settings/MavenSettings.java b/settings-backend/src/main/java/io/github/litheidea/maven/settings/MavenSettings.java new file mode 100644 index 0000000..e75879b --- /dev/null +++ b/settings-backend/src/main/java/io/github/litheidea/maven/settings/MavenSettings.java @@ -0,0 +1,599 @@ +package io.github.litheidea.maven.settings; + +import io.github.litheidea.plugin.sdk.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.security.MessageDigest; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import javax.xml.XMLConstants; +import javax.xml.parsers.*; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.*; + +/** + * Native POM settings. Maven owns module discovery and effective compiler facts; this backend + * projects an allowlist and prepares replacements without publishing. + */ +public final class MavenSettings { + private static final int LIMIT = 2 * 1024 * 1024; + private static final Map> BINDINGS = new ConcurrentHashMap<>(); + + private static final class Binding { + final Path path; + final boolean release; + + Binding(Path path, boolean release) { + this.path = path; + this.release = release; + } + } + + private MavenSettings() {} + + public static void main(String[] args) { + Backend backend = Backend.create("lithe-maven-settings", "development"); + backend.function("compiler.settings", (params, context) -> read(params, context, false)); + backend.function("libraries.settings", (params, context) -> read(params, context, true)); + backend.suppressSuccessDiagnostics("libraries.settings"); + backend.suppressSuccessDiagnostics("compiler.settings"); + backend.function("compiler.prepareSettings", MavenSettings::edit); + backend.listen(); + } + + static Map object(Object value) { + if (!(value instanceof Map)) + throw new PluginError("maven.invalidSettings", "Expected an object."); + return (Map) value; + } + + static List list(Object value) { + return value instanceof List ? (List) value : Collections.emptyList(); + } + + static String text(Object value) { + return value == null ? "" : value.toString(); + } + + static Map map(Object... values) { + Map result = new LinkedHashMap<>(); + for (int i = 0; i < values.length; i += 2) result.put((String) values[i], values[i + 1]); + return result; + } + + static String local(boolean zh, String en, String cn) { + return zh ? cn : en; + } + + static Path root(CallContext context) throws Exception { + if (context.workspaceContext() == null) + throw new PluginError("maven.noWorkspace", "A workspace is required."); + Object folders = + context + .host() + .workspace() + .getFolders(context.workspaceContext()) + .get(10, TimeUnit.SECONDS) + .get("folders"); + if (list(folders).isEmpty()) + throw new PluginError("maven.noWorkspace", "A local workspace is required."); + return Paths.get(text(object(list(folders).get(0)).get("path"))).toRealPath(); + } + + static byte[] bytes(Path path) throws Exception { + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return new byte[0]; + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > LIMIT) + throw new IOException("POM source is not a bounded regular file."); + try (InputStream in = Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) != -1) { + if (out.size() + n > LIMIT) throw new IOException("POM exceeds the source limit."); + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } + + static String digest(byte[] bytes) throws Exception { + StringBuilder out = new StringBuilder("sha256:"); + for (byte b : MessageDigest.getInstance("SHA-256").digest(bytes)) + out.append(String.format(Locale.ROOT, "%02x", b & 255)); + return out.toString(); + } + + static Document parse(byte[] bytes) throws Exception { + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + f.setFeature("http://xml.org/sax/features/external-general-entities", false); + f.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + f.setXIncludeAware(false); + f.setExpandEntityReferences(false); + f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + DocumentBuilder builder = f.newDocumentBuilder(); + builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler()); + return builder.parse(new ByteArrayInputStream(bytes)); + } + + static Element child(Element parent, String name) { + if (parent == null) return null; + for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element + && name.equals(n.getLocalName() == null ? n.getNodeName() : n.getLocalName())) + return (Element) n; + return null; + } + + static Element ensure(Element parent, String name) { + Element value = child(parent, name); + if (value == null) { + value = parent.getOwnerDocument().createElementNS(parent.getNamespaceURI(), name); + parent.appendChild(value); + } + return value; + } + + static String value(Element parent, String name) { + Element value = child(parent, name); + return value == null ? null : value.getTextContent().trim(); + } + + static void set(Element parent, String name, String value) { + Element current = child(parent, name); + if (value == null) { + if (current != null) parent.removeChild(current); + } else ensure(parent, name).setTextContent(value); + } + + static Element compiler(Document doc, boolean create) { + Element project = doc.getDocumentElement(), + build = child(project, "build"), + plugins = child(build, "plugins"); + if (plugins != null) + for (Node n = plugins.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element + && "maven-compiler-plugin".equals(value((Element) n, "artifactId")) + && (value((Element) n, "groupId") == null + || "org.apache.maven.plugins".equals(value((Element) n, "groupId")))) + return (Element) n; + if (!create) return null; + plugins = ensure(ensure(project, "build"), "plugins"); + Element plugin = doc.createElementNS(project.getNamespaceURI(), "plugin"); + plugins.appendChild(plugin); + set(plugin, "groupId", "org.apache.maven.plugins"); + set(plugin, "artifactId", "maven-compiler-plugin"); + set(plugin, "version", "3.13.0"); + return plugin; + } + + static Object nativeTarget(Document doc) { + Element config = child(compiler(doc, false), "configuration"); + String release = value(config, "release"), target = value(config, "target"); + if (release != null && !release.isEmpty()) return normalize(release); + if (target != null) return normalize(target); + Element props = child(doc.getDocumentElement(), "properties"); + release = value(props, "maven.compiler.release"); + target = value(props, "maven.compiler.target"); + return release != null ? normalize(release) : target == null ? null : normalize(target); + } + + static String normalize(String value) { + return value != null && value.startsWith("1.") ? value.substring(2) : value; + } + + static Map field( + boolean zh, + String id, + String en, + String cn, + String kind, + Object raw, + Object effective, + String origin, + List options, + String help) { + if ("enum".equals(kind)) { + choice(options, raw); + choice(options, effective); + } + return map( + "id", + id, + "title", + local(zh, en, cn), + "description", + help, + "kind", + kind, + "value", + raw, + "effectiveValue", + effective, + "effectiveSource", + origin, + "options", + options); + } + + static Object read(Map params, CallContext context, boolean libraryView) + throws Exception { + Path root = root(context); + Map environment = object(params.get("context")); + boolean zh = text(environment.get("language")).startsWith("zh"); + List sources = new ArrayList<>(); + Map bindings = new LinkedHashMap<>(); + Set seen = new HashSet<>(); + long total = 0; + for (Object build : list(environment.get("builds"))) { + Map b = object(build), model = object(b.get("model")); + for (Object projectValue : list(model.get("projects"))) { + context.throwIfCancelled(); + Map project = object(projectValue); + String relative = text(project.get("path")); + Path path = root.resolve(relative).resolve("pom.xml").normalize(); + if (!path.startsWith(root) + || !Files.isRegularFile(path) + || !path.toRealPath().startsWith(root)) + throw new IOException("Maven returned a project outside this workspace."); + if (!seen.add(path)) continue; + if (seen.size() > 1024) throw new IOException("Too many Maven modules."); + byte[] raw = bytes(path); + total += raw.length; + if (total > 8L * 1024 * 1024) + throw new IOException("Project settings exceed the total read limit."); + Document doc = parse(raw); + String id = + "pom" + + digest(root.relativize(path).toString().getBytes(StandardCharsets.UTF_8)) + .substring(7); + Map properties = object(project.get("properties")); + bindings.put( + id, + new Binding( + path, Boolean.parseBoolean(text(properties.get("compiler.releaseEnabled"))))); + Element config = child(compiler(doc, false), "configuration"); + List fields = new ArrayList<>(), choices = new ArrayList<>(); + for (int target = 1; target <= 26; target++) + choices.add(map("value", Integer.toString(target), "title", Integer.toString(target))); + String origin = local(zh, "Maven effective project", "Maven 生效项目配置"); + fields.add( + field( + zh, + "target", + "Target bytecode", + "目标字节码", + "enum", + nativeTarget(doc), + nullable(normalize(text(properties.get("compiler.target")))), + origin, + choices, + local( + zh, + "Writes the native compiler configuration. The selected compiler JDK must" + + " support this target. Module overrides remain in their own POM.", + "写入原生编译器配置;所选编译 JDK 必须支持此目标。模块覆盖保存在各自 POM 中。"))); + String release = value(config, "release"); + fields.add( + field( + zh, + "release", + "Use --release", + "使用 --release", + "boolean", + release == null ? null : !release.isEmpty(), + Boolean.parseBoolean(text(properties.get("compiler.releaseEnabled"))), + origin, + Collections.emptyList(), + local( + zh, + "Requires Maven Compiler Plugin 3.6 or newer. When disabled, source and target" + + " are set together.", + "需要 Maven Compiler Plugin 3.6 或更高版本;关闭后同时设置 source 与 target。"))); + for (String[] f : + new String[][] { + {"debug", "Generate debugging information", "生成调试信息"}, + {"deprecation", "Report deprecated features", "报告已弃用的功能"}, + {"warnings", "Report warnings", "报告警告"} + }) { + String v = value(config, nativeName(f[0])); + fields.add( + field( + zh, + f[0], + f[1], + f[2], + "boolean", + v == null ? null : Boolean.valueOf(v), + nullableBoolean(properties.get("compiler." + nativeName(f[0]))), + origin, + Collections.emptyList(), + "")); + } + List args = new ArrayList<>(); + Element argsElement = child(config, "compilerArgs"); + if (argsElement != null) + for (Node n = argsElement.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element) args.add(n.getTextContent()); + fields.add( + field( + zh, + "arguments", + "Additional compiler arguments", + "附加编译参数", + "stringList", + argsElement == null ? null : args, + properties.containsKey("compiler.arguments") + ? Json.parse(text(properties.get("compiler.arguments"))) + : null, + origin, + Collections.emptyList(), + local( + zh, + "One compiler argument per line. Project-specific arguments remain in the POM.", + "每行一个编译参数;项目参数保存在 POM 中。"))); + List libs = libraries(doc); + fields.add( + field( + zh, + "libraries", + "Local JAR files", + "本地 JAR 文件", + "fileList", + libs, + libs, + origin, + Collections.emptyList(), + local( + zh, + "Adds native system-scope dependencies. Prefer repository dependencies for" + + " portable builds; existing dependencies are preserved.", + "添加原生 system 作用域依赖。可移植构建优先使用仓库依赖;保留已有其他依赖。"))); + String nativePath = root.relativize(path).toString().replace(File.separatorChar, '/'); + boolean projectDefault = + relative.equals(".") || relative.isEmpty() || relative.equals(text(b.get("root"))); + for (Object fieldValue : fields) { + Map f = object(fieldValue); + String fieldID = text(f.get("id")); + Object inherited = + properties.get( + "compiler.inherited." + + (fieldID.equals("release") ? "releaseEnabled" : nativeName(fieldID))); + if (inherited != null) { + if ("boolean".equals(f.get("kind"))) inherited = Boolean.valueOf(inherited.toString()); + if ("stringList".equals(f.get("kind"))) inherited = Json.parse(inherited.toString()); + if ("target".equals(fieldID)) inherited = normalize(inherited.toString()); + f.put("inheritedValue", inherited); + if ("enum".equals(f.get("kind"))) choice((List) f.get("options"), inherited); + } + } + if (libraryView) fields.removeIf(f -> !"libraries".equals(object(f).get("id"))); + else + fields.removeIf( + f -> + "libraries".equals(object(f).get("id")) + || (!projectDefault && !"target".equals(object(f).get("id")))); + sources.add( + map( + "id", + id, + "group", + libraryView ? "libraries" : projectDefault ? "project" : "modules", + "title", + project.get("name"), + "path", + nativePath, + "revision", + digest(raw), + "writable", + true, + "fields", + fields)); + } + } + if (sources.isEmpty()) + throw new PluginError("maven.noProject", "No Maven project is available."); + synchronized (BINDINGS) { + if (BINDINGS.size() >= 32 && !BINDINGS.containsKey(root.toString())) + throw new IOException("Too many workspace settings sessions."); + BINDINGS.put(root.toString(), bindings); + } + return map( + "format", + "litheSettingsSources", + "version", + 0, + "title", + (libraryView + ? local(zh, "Maven Libraries", "Maven 库") + : local(zh, "Maven Java Compiler", "Maven Java 编译器")), + "groups", + libraryView + ? Collections.singletonList( + map( + "id", + "libraries", + "title", + local(zh, "Local JAR dependencies", "本地 JAR 依赖"), + "layout", + "form")) + : Arrays.asList( + map( + "id", + "project", + "title", + local(zh, "Project defaults", "项目默认设置"), + "layout", + "form"), + map( + "id", + "modules", + "title", + local(zh, "Per-module bytecode", "按模块设置字节码"), + "rowTitle", + local(zh, "Module", "模块"), + "layout", + "table")), + "sources", + sources); + } + + static void choice(List options, Object value) { + if (value != null + && !value.toString().isEmpty() + && options.stream().noneMatch(option -> value.equals(object(option).get("value")))) + options.add(map("value", value, "title", value.toString())); + } + + static String nativeName(String id) { + return id.equals("deprecation") + ? "showDeprecation" + : id.equals("warnings") ? "showWarnings" : id; + } + + static Object nullable(String value) { + return value == null || value.isEmpty() ? null : value; + } + + static Object nullableBoolean(Object value) { + return value == null ? null : Boolean.valueOf(value.toString()); + } + + static List libraries(Document doc) { + List result = new ArrayList<>(); + Element deps = child(doc.getDocumentElement(), "dependencies"); + if (deps != null) + for (Node n = deps.getFirstChild(); n != null; n = n.getNextSibling()) + if (n instanceof Element + && "local.lithe.jar".equals(value((Element) n, "groupId")) + && "system".equals(value((Element) n, "scope"))) + result.add(value((Element) n, "systemPath")); + return result; + } + + static Object edit(Map params, CallContext context) throws Exception { + Path root = root(context); + String id = text(params.get("sourceID")); + Map bindings = BINDINGS.get(root.toString()); + Binding binding = bindings == null ? null : bindings.get(id); + Path path = binding == null ? null : binding.path; + if (path == null || !path.toRealPath().startsWith(root)) + throw new IOException("Reload the native settings before saving."); + byte[] original = bytes(path); + if (!digest(original).equals(params.get("revision"))) + throw new IOException("The POM changed outside this editor."); + Map values = object(params.get("values")); + Document doc = parse(original); + Element config = ensure(compiler(doc, true), "configuration"); + Object targetValue = values.containsKey("target") ? values.get("target") : nativeTarget(doc); + String target = targetValue == null ? null : text(targetValue); + boolean useRelease = + values.containsKey("release") + ? Boolean.TRUE.equals(values.get("release")) + : binding.release; + if (values.containsKey("target") || values.containsKey("release")) { + if (target != null + && !target.equals(nativeTarget(doc)) + && !target.matches("(?:[1-9]|1[0-9]|2[0-6])")) + throw new IOException("Choose a supported Java target."); + set(config, "release", useRelease ? target : target == null ? null : ""); + if (!useRelease && target != null) + ensure(config, "release").setAttribute("combine.self", "override"); + set(config, "source", useRelease ? null : target); + set(config, "target", useRelease ? null : target); + if (target == null) { + Element props = child(doc.getDocumentElement(), "properties"); + if (props != null) + for (String key : + new String[] { + "maven.compiler.source", "maven.compiler.target", "maven.compiler.release" + }) set(props, key, null); + } + } + for (Map.Entry edit : values.entrySet()) { + context.throwIfCancelled(); + String key = edit.getKey(); + Object v = edit.getValue(); + if (Arrays.asList("target", "release").contains(key)) continue; + if (Arrays.asList("debug", "deprecation", "warnings").contains(key)) + set(config, nativeName(key), v == null ? null : v.toString()); + else if (key.equals("arguments")) { + Element old = child(config, "compilerArgs"); + if (old != null) config.removeChild(old); + if (v != null) { + Element args = ensure(config, "compilerArgs"); + for (Object arg : list(v)) { + Element a = doc.createElementNS(config.getNamespaceURI(), "arg"); + a.setTextContent(text(arg)); + args.appendChild(a); + } + } + } else if (key.equals("libraries")) { + Element deps = ensure(doc.getDocumentElement(), "dependencies"); + for (Node n = deps.getFirstChild(); n != null; ) { + Node next = n.getNextSibling(); + if (n instanceof Element + && "local.lithe.jar".equals(value((Element) n, "groupId")) + && "system".equals(value((Element) n, "scope"))) deps.removeChild(n); + n = next; + } + for (Object jar : list(v)) { + String location = text(jar); + Path input = Paths.get(location); + if (!input.isAbsolute()) input = path.getParent().resolve(input); + if (!Files.isRegularFile(input) || !location.toLowerCase(Locale.ROOT).endsWith(".jar")) + throw new IOException("Choose an existing JAR file."); + Element dep = doc.createElementNS(deps.getNamespaceURI(), "dependency"); + deps.appendChild(dep); + set(dep, "groupId", "local.lithe.jar"); + set( + dep, + "artifactId", + "jar-" + digest(location.getBytes(StandardCharsets.UTF_8)).substring(7, 23)); + set(dep, "version", "1"); + set(dep, "scope", "system"); + set(dep, "systemPath", input.toAbsolutePath().normalize().toString()); + } + } else throw new IOException("Unknown native setting."); + } + context.throwIfCancelled(); + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(doc), new StreamResult(out)); + byte[] replacement = out.toByteArray(); + if (replacement.length > LIMIT) throw new IOException("POM exceeds the source limit."); + Path stage = Paths.get(text(params.get("outputFile"))); + if (!Files.isRegularFile(stage, LinkOption.NOFOLLOW_LINKS)) + throw new IOException("The staging file no longer exists."); + context.throwIfCancelled(); + try (OutputStream stream = + Files.newOutputStream( + stage, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING, + LinkOption.NOFOLLOW_LINKS)) { + stream.write(replacement); + } + return map( + "format", + "litheSettingsSourceEdit", + "version", + 0, + "sourceID", + id, + "revision", + digest(replacement), + "changed", + !Arrays.equals(original, replacement)); + } +} 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..1e0b49e --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -0,0 +1,1556 @@ +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.Set; +import java.util.TreeSet; +import java.util.Base64; +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/*}) 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 an independently negotiated shortcut import request. */ + @FunctionalInterface + public interface KeymapImportHandler { + Object handle(KeymapSnapshot snapshot, CallContext context) throws Exception; + } + + /** One file within the user's selected source; its path is a relative label. */ + public static final class KeymapSourceFile { + private final String id; + private final String path; + private final long byteCount; + KeymapSourceFile(String id, String path, long byteCount) { this.id = id; this.path = path; this.byteCount = byteCount; } + public String id() { return id; } + public String path() { return path; } + public long byteCount() { return byteCount; } + } + + /** Opaque selected source scoped to one import and backend session. */ + public static final class KeymapSnapshot { + private final String providerId; + private final String snapshotId; + private final Host host; + KeymapSnapshot(String providerId, String snapshotId, Host host) { + this.providerId = providerId; this.snapshotId = snapshotId; this.host = host; + } + public String providerId() { return providerId; } + public String snapshotId() { return snapshotId; } + private Map scope() { + Map result = singleton("providerID", providerId); + result.put("snapshotID", snapshotId); + return result; + } + public CompletableFuture> listInputs() { + return host.request("lithe/host/keymapImport/listInputs", scope()).thenApply(raw -> { + Object files = raw instanceof Map ? ((Map) raw).get("files") : null; + if (!(files instanceof List) || ((List) files).size() > 128) throw invalidKeymapResponse(); + List result = new ArrayList<>(); + for (Object item : (List) files) { + if (!(item instanceof Map)) throw invalidKeymapResponse(); + Map file = (Map) item; + Object id = file.get("id"), path = file.get("path"), count = file.get("byteCount"); + if (!(id instanceof String) || !validSnapshotToken((String) id) || !(path instanceof String) + || ((String) path).isEmpty() || ((String) path).getBytes(StandardCharsets.UTF_8).length > 4096 + || !(count instanceof Number) || ((Number) count).doubleValue() != ((Number) count).longValue() + || ((Number) count).longValue() < 0 || ((Number) count).longValue() > 1048576) throw invalidKeymapResponse(); + result.add(new KeymapSourceFile((String) id, (String) path, ((Number) count).longValue())); + } + return result; + }); + } + public CompletableFuture readChunk(String fileId, long offset, int maximumBytes) { + if (!validSnapshotToken(fileId) || offset < 0 || offset > 1048576 || maximumBytes < 1 || maximumBytes > 131072) { + throw invalidKeymapResponse(); + } + Map params = scope(); + params.put("fileID", fileId); params.put("offset", offset); params.put("maximumBytes", maximumBytes); + return host.request("lithe/host/keymapImport/readChunk", params).thenApply(raw -> { + Object encoded = raw instanceof Map ? ((Map) raw).get("data") : null; + if (!(encoded instanceof String) || ((String) encoded).length() > 174764) throw invalidKeymapResponse(); + final byte[] bytes; + try { bytes = Base64.getDecoder().decode((String) encoded); } + catch (IllegalArgumentException error) { throw invalidKeymapResponse(); } + if (bytes.length > maximumBytes || !Base64.getEncoder().encodeToString(bytes).equals(encoded)) throw invalidKeymapResponse(); + return bytes; + }); + } + } + + /** 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(false, false); + + private final boolean functions; + private final boolean build; + + Negotiated(boolean functions, boolean build) { + this.functions = functions; + this.build = build; + } + + /** + * Whether the host negotiated plugin functions ({@code litheFunctions}), + * which also carry the host services, the workspace contexts, the host + * notifications, and the calls to other plugins' functions. + */ + public boolean functions() { + return functions; + } + + /** Whether the host negotiated typed build requests and this backend declared a build handler. */ + public boolean build() { + return build; + } + } + + private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED } + + /** The {@code version} every build result document carries. */ + private static final long BUILD_DOCUMENT_VERSION = 0; + + /** 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> earlyDiagnostics = new ArrayList<>(); + private final java.util.Set quietSuccess = new java.util.HashSet<>(); + private final String name; + private final String version; + private final Map capabilities; + private final Object lock = new Object(); + private final Object writeLock = new Object(); + private final Map functions = new HashMap<>(); + private final Map keymapProviders = new HashMap<>(); + private final Set selectedKeymapProviders = new TreeSet<>(); + private final Map buildHandlers = new HashMap<>(); + private final Map requestHandlers = new HashMap<>(); + private final Map notificationHandlers = new HashMap<>(); + private final Map commandHandlers = new HashMap<>(); + private final Map hostNotificationHandlers = new HashMap<>(); + private NotificationHandler contextsHandler; + private final List initializeHooks = new ArrayList<>(); + private final List shutdownHooks = new ArrayList<>(); + /** Host requests being handled, by JSON-RPC ID. */ + private final Map incoming = new HashMap<>(); + /** Requests this backend sent to the host, by JSON-RPC ID. */ + private final Map outgoing = new HashMap<>(); + private final AtomicInteger nextRequestId = new AtomicInteger(1); + private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadNamer()); + private final HostChannel channel = new HostChannel(new Wire()); + private final Host host = new Host(channel, Collections.emptyList(), null); + /** Serializes register/unregister so the host sees them in call order. */ + private CompletableFuture registrations = CompletableFuture.completedFuture(null); + private volatile Phase phase = Phase.IDLE; + private volatile Negotiated negotiated = Negotiated.NONE; + private volatile Map initializeParams; + private volatile OutputStream output; + private volatile PrintStream errorOutput = System.err; + private int exitCode = 1; + + private Backend(String name, String version, Map capabilities) { + Object experimental = capabilities.get("experimental"); + if (experimental instanceof Map + && (((Map) experimental).containsKey("litheBuild") + || ((Map) experimental).containsKey("litheFunctions") + || ((Map) experimental).containsKey("litheKeymapImport") + || ((Map) experimental).containsKey("litheLogging"))) { + throw new PluginSdkError("sdk.capabilities.reserved", + "litheBuild, litheFunctions, litheKeymapImport and litheLogging are negotiated by the SDK; declare handlers instead."); + } + this.name = name == null ? "lithe-plugin-backend" : name; + this.version = version; + this.capabilities = new LinkedHashMap<>(capabilities); + } + + /** + * Creates a backend. + * + * @param name reported as {@code serverInfo.name} and used as the log prefix + * @param version reported as {@code serverInfo.version}; may be null + */ + public static Backend create(String name, String version) { + return new Backend(name, version, Collections.emptyMap()); + } + + /** + * Creates a backend that also declares standard LSP server capabilities. + * {@code experimental.litheBuild} and {@code experimental.litheFunctions} + * are negotiated by the SDK and cannot be set here. + */ + public static Backend create(String name, String version, Map capabilities) { + return new Backend(name, version, capabilities == null ? Collections.emptyMap() : capabilities); + } + + /** Protocols the host agreed to in {@code initialize}; both false before it. */ + public Negotiated negotiated() { + return negotiated; + } + + /** + * Host services, usable once the session is ready. Prefer a handler's {@link CallContext#host()}, whose + * requests end with the call; this one belongs to no call, so its calls to + * other plugins name no parent call unless the call says one. + */ + public Host host() { + return host; + } + + /** The host's {@code initialize} params, or null before it arrives. */ + public Map initializeParams() { + return initializeParams; + } + + /** IDs of the functions this backend currently serves, sorted. */ + public List functionIds() { + synchronized (lock) { + List ids = new ArrayList<>(functions.keySet()); + Collections.sort(ids); + return ids; + } + } + + /** Answers {@code lithe/build/model} with a {@code litheBuildModel} document. */ + public Backend onModel(Handler handler) { + return declareBuild(Protocol.BUILD_MODEL, handler); + } + + /** Answers {@code lithe/build/dependencies} with a {@code litheDependencies} document. */ + public Backend onDependencies(Handler handler) { + return declareBuild(Protocol.BUILD_DEPENDENCIES, handler); + } + + /** Executes a bounded provider task. */ + public Backend onExecute(Handler handler) { + return declareBuild(Protocol.BUILD_EXECUTE, handler); + } + + /** Runs exact test selectors. */ + public Backend onTest(Handler handler) { + return declareBuild(Protocol.BUILD_TEST, handler); + } + + /** Returns the upstream engine's runnable test selectors, with the format stamped. */ + public Backend onDiscoverTests(Handler handler) { + return declareBuild(Protocol.BUILD_DISCOVER_TESTS, handler); + } + + /** Prepares native executable target facts. */ + public Backend onPrepareDebug(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_DEBUG, handler); + } + + /** Prepares a portable application launch. */ + public Backend onPrepareRun(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_RUN, handler); + } + + /** + * Declares a plugin function offered from the start, in the {@code initialize} + * answer. To add one later, use {@link #registerFunction}. + * + * @param id dot-separated lowerCamelCase segments, such as {@code snapshot.refresh} + */ + public Backend function(String id, Handler handler) { + synchronized (lock) { + if (!beforeAnswer()) { + throw new PluginSdkError("sdk.function.lateDeclaration", + "After initialize, add functions with registerFunction()."); + } + checkNewFunction(id, handler); + functions.put(id, handler); + } + return this; + } + + /** Declares a shortcut import provider before initialization. */ + public Backend keymapImportProvider(String id, KeymapImportHandler handler) { + synchronized (lock) { + if (!beforeAnswer() || !validKeymapProvider(id) || handler == null + || keymapProviders.containsKey(id) || keymapProviders.size() >= 8) { + throw new PluginSdkError("sdk.keymap.invalidRegistration", "Invalid or duplicate shortcut import provider."); + } + keymapProviders.put(id, handler); + } + return this; + } + + /** Handles a standard LSP request, for a backend that is also a language server. */ + public Backend onRequest(String method, RequestHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + requestHandlers.put(method, handler); + } + return this; + } + + /** Handles a standard LSP notification. */ + public Backend onNotification(String method, NotificationHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + notificationHandlers.put(method, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/commands/didRun} for one of the plugin's + * commands. It is an event: the host waits for no result. + * + * @param commandId the command's ID from the manifest, 1-128 of {@code [a-z0-9.-]} + */ + public Backend onCommand(String commandId, CommandHandler handler) { + if (!Protocol.isCommandId(commandId)) { + throw new PluginSdkError("sdk.command.invalidID", "Command ID \"" + commandId + "\" must be 1-128 of [a-z0-9.-]."); + } + if (handler == null) { + throw new IllegalArgumentException("A command handler must not be null."); + } + synchronized (lock) { + commandHandlers.put(commandId, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/workspace/didChangeContexts} with + * {@code { revision }}; call {@code host().workspace().listContexts()} for + * the contexts. + */ + public Backend onContextsChanged(NotificationHandler handler) { + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + contextsHandler = handler; + } + return this; + } + + /** + * Handles a {@code lithe/host/*} notification a later host adds. Commands, + * context changes, and subscription events have their own APIs. + */ + public Backend onHostNotification(String method, NotificationHandler handler) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + throw new PluginSdkError("sdk.method.invalid", method + " is not a host notification."); + } + if (method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) || method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY) + || method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + throw new PluginSdkError("sdk.method.reserved", + method + " is routed by the SDK; use onCommand, onContextsChanged, or Host.subscribe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + hostNotificationHandlers.put(method, handler); + } + return this; + } + + /** Runs before the {@code initialize} answer, with the host's params and the negotiation. */ + public Backend onInitialize(InitializeHook hook) { + synchronized (lock) { + initializeHooks.add(hook); + } + return this; + } + + /** Runs on {@code shutdown}, after running calls were cancelled. */ + public Backend onShutdown(ShutdownHook hook) { + synchronized (lock) { + shutdownHooks.add(hook); + } + return this; + } + + /** + * Adds a function. Before the {@code initialize} answer (including from an + * {@link #onInitialize} hook) it joins the initial list; afterwards the host + * must accept it first. The future completes once the function is served. + */ + public CompletableFuture registerFunction(String id, Handler handler) { + synchronized (lock) { + if (beforeAnswer()) { + try { + checkNewFunction(id, handler); + functions.put(id, handler); + return CompletableFuture.completedFuture(null); + } catch (RuntimeException error) { + return failed(error); + } + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + checkNewFunction(id, handler); + // Installed before the request: the host may invoke it as soon as + // its registry changed, before this backend reads the reply. + functions.put(id, handler); + } + Map entry = new LinkedHashMap<>(); + entry.put("id", id); + Map params = new LinkedHashMap<>(); + params.put("functions", Collections.singletonList(entry)); + return request(Protocol.FUNCTION_REGISTER, params).handle((result, error) -> { + if (error != null) { + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + } + throw new CompletionException(unwrap(error)); + } + return null; + }); + }); + } + + /** Withdraws a function. The host ends its running calls as revoked. */ + public CompletableFuture unregisterFunction(String id) { + synchronized (lock) { + if (beforeAnswer()) { + if (functions.remove(id) == null) { + return failed(unknownFunction(id)); + } + quietSuccess.remove(id); + return CompletableFuture.completedFuture(null); + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + if (!functions.containsKey(id)) { + throw unknownFunction(id); + } + } + Map params = new LinkedHashMap<>(); + params.put("ids", Collections.singletonList(id)); + return request(Protocol.FUNCTION_UNREGISTER, params).thenApply(result -> { + List running = new ArrayList<>(); + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + for (Call call : incoming.values()) { + if (id.equals(call.functionId)) { + running.add(call); + } + } + } + for (Call call : running) { + call.cancellation.cancel("The function was withdrawn."); + } + return null; + }); + }); + } + + /** Sends a standard LSP request to the host. {@code lithe/*} methods are reserved. */ + public CompletableFuture sendRequest(String method, Object params) { + checkOutgoing(method); + return request(method, params); + } + + /** Sends a standard LSP notification to the host. {@code lithe/*} methods are reserved. */ + public void sendNotification(String method, Object params) { + checkOutgoing(method); + Map message = message(null, method); + if (params != null) { + message.put("params", params); + } + write(message); + } + + public Diagnostics diagnostics() { return new Diagnostics(this, null); } + + public Backend suppressSuccessDiagnostics(String operation) { + if (!loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Suppress a registered operation."); + synchronized (lock) { quietSuccess.add(operation); } + return this; + } + + boolean loggingOperation(String operation) { + synchronized (lock) { return Diagnostics.OPERATIONS.contains(operation) || functions.containsKey(operation); } + } + + void logFact(Map params) { + synchronized (lock) { + if (!logging) return; + if (!loggingReady) { if (earlyDiagnostics.size() < 8) earlyDiagnostics.add(params); return; } + } + Map notification = message(null, "lithe/log"); + notification.put("params", params); + write(notification); + } + + /** + * Serves the host over stdio until it sends {@code exit} or closes stdin, + * then exits the process with the session's exit code: 0 after a + * {@code shutdown}, 1 otherwise. {@code System.out} is redirected to stderr + * first, because stdout carries the protocol and a stray line there would + * end the session. + */ + public void listen() { + OutputStream protocol = new FileOutputStream(FileDescriptor.out); + System.setOut(System.err); + int code = listen(System.in, protocol, System.err); + System.exit(code); + } + + /** + * Serves the host over the given streams and returns the exit code once the + * session ended, without exiting the process. Blocks the calling thread. + */ + public int listen(InputStream input, OutputStream output, PrintStream errorOutput) { + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.listen.repeated", "A backend listens once."); + } + phase = Phase.LISTENING; + this.output = output; + this.errorOutput = errorOutput; + } + Framing.Decoder decoder = new Framing.Decoder(); + byte[] chunk = new byte[64 * 1024]; + try { + while (phase != Phase.EXITED) { + int count = input.read(chunk); + if (count < 0) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + break; + } + List messages; + try { + messages = decoder.push(chunk, 0, count); + } catch (Framing.FramingException error) { + diagnostics().terminal("notification", new IllegalStateException(), System.nanoTime()); + finish(1); + break; + } + for (Object message : messages) { + if (phase == Phase.EXITED) { + break; + } + dispatch(message); + } + } + } catch (IOException error) { + finish(1); + } + synchronized (lock) { + return exitCode; + } + } + + private void dispatch(Object message) { + if (message == Framing.MALFORMED) { + respond(null, null, error(Protocol.PARSE_ERROR, "The message is not valid JSON.")); + return; + } + // Valid JSON that is not a message object, such as `null` or a batch. + if (!(message instanceof Map)) { + respond(null, null, error(Protocol.INVALID_REQUEST, "The message is not a JSON-RPC object.")); + return; + } + Map object = Json.object(message); + Object id = object.get("id"); + Object method = object.get("method"); + if (!(method instanceof String)) { + if (id != null) { + settleOutgoing(object); + } + return; + } + if (id != null) { + handleRequest(id, (String) method, object.get("params")); + } else { + handleNotification((String) method, object.get("params")); + } + } + + private void handleRequest(Object id, String method, Object params) { + if (method.equals(Protocol.INITIALIZE)) { + initialize(id, params instanceof Map ? Json.object(params) : new LinkedHashMap<>()); + return; + } + if (method.equals(Protocol.SHUTDOWN)) { + shutdown(id); + return; + } + Phase current = phase; + if (current == Phase.LISTENING || current == Phase.INITIALIZING) { + respond(id, null, error(Protocol.SERVER_NOT_INITIALIZED, "The backend is not initialized.")); + return; + } + if (current != Phase.READY) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The backend is shutting down.")); + return; + } + if (method.equals(Protocol.FUNCTION_INVOKE)) { + invokeFunction(id, params); + return; + } + if (method.equals("lithe/keymap/import")) { + invokeKeymap(id, params); + return; + } + Handler build; + RequestHandler handler; + synchronized (lock) { + build = negotiated.build() ? buildHandlers.get(method) : null; + handler = requestHandlers.get(method); + } + if (build != null) { + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, method + " params must be an object.")); + return; + } + Map arguments = Json.object(params); + invokeBuild(id, method, arguments, build); + return; + } + if (handler != null) { + run(id, null, null, context -> handler.handle(params, context), result -> result, null); + return; + } + respond(id, null, error(Protocol.METHOD_NOT_FOUND, "Unsupported method: " + method)); + } + + private void handleNotification(String method, Object params) { + if (method.equals(Protocol.EXIT)) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + return; + } + if (method.equals(Protocol.CANCEL_REQUEST)) { + Object id = params instanceof Map ? ((Map) params).get("id") : null; + Call call; + synchronized (lock) { + call = incoming.get(requestKey(id)); + } + if (call != null) { + call.cancellation.cancel("The request was cancelled."); + } + return; + } + if (phase != Phase.READY || method.equals(Protocol.INITIALIZED)) { + return; + } + if (method.startsWith(Protocol.HOST_PREFIX)) { + hostNotification(method, params); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = notificationHandlers.get(method); + } + if (handler == null) { + return; + } + notifyHandler(method, () -> handler.handle(params)); + } + + /** + * Routes a host notification. Core checked its shape and the session's + * grant; one this SDK does not know is ignored, as the contract asks. + */ + private void hostNotification(String method, Object raw) { + if (!negotiated.functions() || !(raw instanceof Map)) { + return; + } + Map params = Json.object(raw); + if (method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY)) { + channel.deliver(params); + return; + } + if (method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + Object commandId = params.get("commandID"); + CommandHandler handler; + synchronized (lock) { + handler = commandId instanceof String ? commandHandlers.get(commandId) : null; + } + if (handler == null) { + diagnostics().degraded("notification", "command_unhandled"); + return; + } + Map context = workspaceContext(params.get("context")); + notifyHandler(method, () -> handler.handle((String) commandId, context)); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) ? contextsHandler : hostNotificationHandlers.get(method); + } + if (handler != null) { + notifyHandler(method, () -> handler.handle(params)); + } + } + + private interface Notified { + void run() throws Exception; + } + + /** Runs a notification handler off the reader thread; a failure is logged. */ + private void notifyHandler(String method, Notified handler) { + executor.execute(() -> { + try { + handler.run(); + } catch (Throwable error) { + diagnostics().terminal("notification", error, System.nanoTime()); + } + }); + } + + private void initialize(Object id, Map params) { + Negotiated agreed; + List hooks; + synchronized (lock) { + if (phase != Phase.LISTENING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "initialize was already received.")); + return; + } + phase = Phase.INITIALIZING; + initializeParams = params; + Map offered = experimental(params.get("capabilities")); + loggingReady = false; + earlyDiagnostics.clear(); + logging = offers(offered.get("litheLogging"), Protocol.LOGGING_VERSION); + if (!logging) { + phase = Phase.LISTENING; + respond(id, null, error(Protocol.INVALID_REQUEST, + "The backend requires litheLogging version " + Protocol.LOGGING_VERSION + ".")); + return; + } + agreed = new Negotiated( + offers(offered.get("litheFunctions"), Protocol.FUNCTIONS_VERSION), + !buildHandlers.isEmpty() && offers(offered.get("litheBuild"), Protocol.BUILD_VERSION)); + negotiated = agreed; + hooks = new ArrayList<>(initializeHooks); + } + executor.execute(() -> { + try { + for (InitializeHook hook : hooks) { + hook.run(params, agreed); + } + } catch (Throwable failure) { + synchronized (lock) { + if (phase == Phase.INITIALIZING) { + phase = Phase.LISTENING; + } + } + respond(id, null, toResponseError(failure, null)); + return; + } + synchronized (lock) { + // A shutdown or exit that arrived while a hook ran ended the + // session; finishing initialize must not reopen it. + if (phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The session ended during initialize.")); + return; + } + if (!agreed.functions() && !functions.isEmpty()) { + diagnostics().degraded("initialize", "functions_unavailable"); + } + Map experimental = new LinkedHashMap<>(experimental(capabilities)); + experimental.put("litheLogging", singleton("version", Protocol.LOGGING_VERSION)); + Map offeredCapabilities = experimental(params.get("capabilities")); + Object keymap = offeredCapabilities.get("litheKeymapImport"); + if (offers(keymap, Protocol.KEYMAP_IMPORT_VERSION) && keymap instanceof Map) { + Object providers = ((Map) keymap).get("providers"); + if (providers instanceof List && ((List) providers).size() <= 8) { + selectedKeymapProviders.clear(); + for (Object provider : (List) providers) { + if (provider instanceof String && keymapProviders.containsKey(provider)) selectedKeymapProviders.add((String) provider); + } + if (!selectedKeymapProviders.isEmpty()) { + Map entry = singleton("version", Protocol.KEYMAP_IMPORT_VERSION); + entry.put("providers", new ArrayList<>(selectedKeymapProviders)); + experimental.put("litheKeymapImport", entry); + } + } + } + if (agreed.build()) { + experimental.put("litheBuild", singleton("version", Protocol.BUILD_VERSION)); + } + if (agreed.functions()) { + List offered = new ArrayList<>(); + for (String functionId : functionIds()) { + offered.add(singleton("id", functionId)); + } + Map entry = singleton("version", Protocol.FUNCTIONS_VERSION); + entry.put("functions", offered); + experimental.put("litheFunctions", entry); + } + Map answered = new LinkedHashMap<>(capabilities); + answered.put("experimental", experimental); + Map serverInfo = singleton("name", name); + if (version != null) { + serverInfo.put("version", version); + } + Map result = singleton("capabilities", answered); + result.put("serverInfo", serverInfo); + phase = Phase.READY; + respond(id, result, null); + loggingReady = true; + List> early = new ArrayList<>(earlyDiagnostics); + earlyDiagnostics.clear(); + for (Map fact : early) logFact(fact); + } + }); + } + + private void shutdown(Object id) { + List hooks; + synchronized (lock) { + if (phase != Phase.READY && phase != Phase.LISTENING && phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "shutdown was already received.")); + return; + } + phase = Phase.SHUTTING_DOWN; + hooks = new ArrayList<>(shutdownHooks); + } + cancelAll("The backend is shutting down."); + executor.execute(() -> { + for (ShutdownHook hook : hooks) { + try { + hook.run(); + } catch (Throwable error) { + diagnostics().terminal("shutdown", error, System.nanoTime()); + } + } + Processes.killAll(); + respond(id, null, null); + }); + } + + private void invokeKeymap(Object id, Object raw) { + Map params = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); + Object provider = params.get("providerID"), snapshot = params.get("snapshotID"); + KeymapImportHandler handler; + synchronized (lock) { + handler = provider instanceof String && selectedKeymapProviders.contains(provider) ? keymapProviders.get(provider) : null; + } + if (params.size() != 2 || !(provider instanceof String) || !validKeymapProvider((String) provider) + || !(snapshot instanceof String) || !validSnapshotToken((String) snapshot) || handler == null) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Invalid shortcut import request.")); + return; + } + run(id, null, null, null, context -> handler.handle(new KeymapSnapshot((String) provider, (String) snapshot, context.host()), context), + Backend::functionResult, null, null, "lithe/keymap/import", null, null); + } + + private static boolean validKeymapProvider(String id) { + return id != null && id.matches("[a-z][a-z0-9-]{0,63}"); + } + + private static boolean validSnapshotToken(String id) { + return id != null && id.matches("[a-zA-Z0-9_-]{1,128}"); + } + + private static PluginSdkError invalidKeymapResponse() { + return new PluginSdkError("sdk.keymap.invalidResponse", "Invalid shortcut source response."); + } + + private void invokeFunction(Object id, Object raw) { + Map invocation = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); + Object functionId = invocation.get("functionID"); + Object operationId = invocation.get("operationID"); + Object params = invocation.get("params"); + Map workspaceContext = workspaceContext(invocation.get("context")); + Map caller = callerReference(invocation.get("caller")); + Handler handler; + synchronized (lock) { + handler = negotiated.functions() && functionId instanceof String ? functions.get(functionId) : null; + } + if (handler == null) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " is not registered.")); + return; + } + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " params must be an object.")); + return; + } + String function = (String) functionId; + String operation = operationId instanceof String ? (String) operationId : null; + Map arguments = Json.object(params); + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = (message, percentage) -> { + if (!reporting.get()) { + return; + } + Map report = new LinkedHashMap<>(); + report.put("operationID", operationId); + if (message != null) { + report.put("message", Protocol.boundedText(message)); + } + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.FUNCTION_PROGRESS); + notification.put("params", report); + write(notification); + }; + // The call's wire operation ID is the parent of the calls it makes to other plugins. + String parentOperationId = Protocol.isParentOperationId(operation) ? operation : null; + run(id, function, operation, workspaceContext, context -> handler.handle(arguments, context), + Backend::functionResult, () -> reporting.set(false), progress, function, caller, parentOperationId); + } + + private void invokeBuild(Object id, String method, Map arguments, Handler handler) { + if (!Protocol.buildProgress(method)) { + run(id, null, null, null, context -> handler.handle(arguments, context), result -> buildResult(method, result), null, null, method, + null, null); + return; + } + Object wireId = arguments.get("operationID"); + if (!(wireId instanceof String)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "A build request needs its wire operationID.")); + return; + } + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = new CallContext.ProgressSink() { + @Override + public void report(String message, Double percentage) { report(message, percentage, null); } + @Override + public void report(String text, Double percentage, String output) { + if (!reporting.get()) return; + Map report = singleton("operationID", wireId); + if (text != null) report.put("message", Protocol.boundedText(text, Protocol.MAX_BUILD_MESSAGE_BYTES)); + if (output != null) report.put("output", Protocol.boundedText(output, Protocol.MAX_BUILD_OUTPUT_BYTES)); + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.BUILD_PROGRESS); + notification.put("params", report); + write(notification); + } + }; + run(id, null, (String) wireId, null, context -> handler.handle(arguments, context), + result -> buildResult(method, result), () -> reporting.set(false), progress, method, null, null); + } + + private interface Invocation { + Object invoke(CallContext context) throws Exception; + } + + private interface Shape { + Object apply(Object result); + } + + private void run(Object id, String functionId, String operationId, Invocation invoke, Shape shape, Runnable onSettled) { + run(id, functionId, operationId, null, invoke, shape, onSettled, null); + } + + /** Runs one handler with its own cancellation and answers exactly once. */ + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress) { + run(id, functionId, operationId, workspaceContext, invoke, shape, onSettled, progress, + functionId == null ? "function-call" : functionId, null, null); + } + + /** + * {@code caller} is the plugin that called a function through the relay and + * {@code parentOperationId} the wire operation ID calls to other plugins + * name as their parent; both are null for every call but a function call. + */ + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress, String diagnosticOperation, + Map caller, String parentOperationId) { + long started = System.nanoTime(); + String diagnosticOperationId = Diagnostics.requestOperationId(operationId, id); + Cancellation cancellation = new Cancellation(() -> diagnostics().degraded("notification", "cancellation_listener_failed")); + String key = requestKey(id); + synchronized (lock) { + incoming.put(key, new Call(cancellation, functionId)); + } + CallContext context = new CallContext(cancellation, this, functionId, diagnosticOperationId, progress, + new Host(channel, Collections.singletonList(cancellation), parentOperationId), workspaceContext, caller); + executor.execute(() -> { + Object result = null; + Map error = null; + try { + Object value = invoke.invoke(context); + cancellation.throwIfCancelled(); + result = shape.apply(value); + } catch (Throwable failure) { + if (!cancellation.isCancelled()) { + new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, failure, started); + } + error = toResponseError(failure, cancellation); + } + if (error == null && !cancellation.isCancelled()) { + boolean quiet; + synchronized (lock) { quiet = context.quietSuccess() || quietSuccess.contains(diagnosticOperation); } + if (!quiet) new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, null, started); + } + try { + if (onSettled != null) { + onSettled.run(); + } + } finally { + synchronized (lock) { + incoming.remove(key); + } + // Work belongs to its call: tools still running when the handler + // returned end now. Other calls have their own cancellation. + cancellation.cancel("The call ended."); + // Answered whatever the clean-up did, so Lithe never waits for + // its timeout. + respond(id, result, error); + } + }); + } + + private Backend declareBuild(String method, Handler handler) { + if (handler == null) { + throw new IllegalArgumentException("A build handler must not be null."); + } + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.build.lateDeclaration", "Declare build handlers before listen()."); + } + buildHandlers.put(method, handler); + } + return this; + } + + private static void checkDeclared(String method, Object handler) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + " is managed by the SDK and Lithe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + } + + private void checkNewFunction(String id, Handler handler) { + if (!Protocol.isFunctionId(id)) { + throw new PluginSdkError("sdk.function.invalidID", "Function ID \"" + id + + "\" must be dot-separated lowerCamelCase segments of at most 128 bytes."); + } + if (handler == null) { + throw new IllegalArgumentException("A function handler must not be null."); + } + if (functions.containsKey(id)) { + throw new PluginSdkError("sdk.function.duplicate", "Function " + id + " is already declared."); + } + if (functions.size() >= Protocol.MAX_FUNCTIONS) { + throw new PluginSdkError("sdk.function.limit", + "A backend serves at most " + Protocol.MAX_FUNCTIONS + " functions."); + } + } + + /** True until the {@code initialize} answer fixes the initial function list. */ + private boolean beforeAnswer() { + return phase == Phase.IDLE || phase == Phase.LISTENING || phase == Phase.INITIALIZING; + } + + private void requireFunctions() { + if (phase != Phase.READY || !negotiated.functions()) { + throw new PluginSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions."); + } + } + + private static PluginSdkError unknownFunction(String id) { + return new PluginSdkError("sdk.function.unknown", "Function " + id + " is not registered."); + } + + private CompletableFuture queueRegistration(Supplier> change) { + synchronized (lock) { + CompletableFuture next = registrations.thenComposeAsync(ignored -> { + try { + return change.get(); + } catch (RuntimeException error) { + return failed(error); + } + }, executor); + registrations = next.handle((result, error) -> null); + return next; + } + } + + private void checkOutgoing(String method) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + + " is reserved. A backend never asks the host to run a domain operation or a function."); + } + if (phase != Phase.READY) { + throw new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + } + + private CompletableFuture request(String method, Object params) { + return send(method, params).response; + } + + /** Writes a request; params JSON cannot encode throw before anything is registered. */ + private HostChannel.Sent send(String method, Object params) { + String id = "sdk-" + nextRequestId.getAndIncrement(); + CompletableFuture future = new CompletableFuture<>(); + Map message = message(id, method); + if (params != null) { + message.put("params", params); + } + byte[] frame = Framing.encode(message); + synchronized (lock) { + if (phase == Phase.EXITED) { + future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + return new HostChannel.Sent(id, future); + } + outgoing.put(id, new Pending(future, method)); + } + writeEncoded(frame); + return new HostChannel.Sent(id, future); + } + + private void settleOutgoing(Map message) { + Object id = message.get("id"); + Pending pending; + synchronized (lock) { + pending = id instanceof String ? outgoing.remove(id) : null; + } + if (pending == null) { + return; + } + Object error = message.get("error"); + // Completed on a handler thread: the reader thread never runs plugin code. + if (error instanceof Map) { + HostError rejection = HostError.fromResponse(pending.method, Json.object(error)); + executor.execute(() -> pending.future.completeExceptionally(rejection)); + } else { + Object result = message.get("result"); + executor.execute(() -> pending.future.complete(result)); + } + } + + private void cancelAll(String reason) { + List calls; + synchronized (lock) { + calls = new ArrayList<>(incoming.values()); + } + for (Call call : calls) { + call.cancellation.cancel(reason); + } + } + + private void finish(int code) { + List pending; + synchronized (lock) { + if (phase == Phase.EXITED) { + return; + } + phase = Phase.EXITED; + exitCode = code; + pending = new ArrayList<>(outgoing.values()); + outgoing.clear(); + } + channel.close(); + cancelAll("The session ended."); + Processes.killAll(); + for (Pending request : pending) { + request.future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + } + // Running handlers finish on their own threads; nothing new starts. + executor.shutdown(); + } + + private void respond(Object id, Object result, Map error) { + if (phase == Phase.EXITED) { + return; + } + Map message = message(id, null); + if (error != null) { + message.put("error", error); + } else { + message.put("result", result); + } + try { + writeEncoded(Framing.encode(message)); + } catch (Json.JsonException failure) { + // A result JSON cannot encode must not end the session. + diagnostics().terminal("result-encoding", failure, System.nanoTime()); + Map fallback = message(id, null); + fallback.put("error", toResponseError(failure, null)); + write(fallback); + } + } + + private void write(Map message) { + writeEncoded(Framing.encode(message)); + } + + private void writeEncoded(byte[] frame) { + synchronized (writeLock) { + OutputStream stream = output; + if (stream == null || phase == Phase.EXITED) { + return; + } + try { + stream.write(frame); + stream.flush(); + } catch (IOException error) { + // The host closed the pipe; the input side ends the session. + // The closed protocol pipe leaves the host owning the terminal process fact. + } + } + } + + /** + * The JSON-RPC error object for a handler failure. Only {@link PluginError} + * carries a plugin code; any other exception becomes a generic internal + * error so that stack traces and machine paths never reach the host's UI. + */ + static Map toResponseError(Throwable failure, Cancellation cancellation) { + Throwable error = unwrap(failure); + if (cancellation != null && cancellation.isCancelled() && error instanceof CancelledException) { + return error(Protocol.REQUEST_CANCELLED, "The request was cancelled."); + } + if (error instanceof PluginError) { + Map response = error(Protocol.REQUEST_FAILED, Protocol.boundedText(error.getMessage())); + response.put("data", singleton("code", ((PluginError) error).code())); + return response; + } + // Unexpected exceptions often embed absolute paths or internals; the + // caller logs only a fixed failure category to stderr. + return error(Protocol.INTERNAL_ERROR, "The plugin backend failed unexpectedly."); + } + + /** + * Stamps the canonical format on a build result, so a handler can return the + * plain document. A result in another format is a backend bug: Core would + * refuse it as {@code plugin.build.invalidOutput}, so it fails here with a log. + */ + static Object buildResult(String method, Object result) { + String expected = BUILD_FORMATS.get(method); + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " must return a reply object."); + } + Map document = new LinkedHashMap<>(Json.object(result)); + if (expected != null) { + Object format = document.get("format"); + if (format != null && !expected.equals(format)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " returned another format."); + } + Object version = document.get("version"); + if (version != null && !(version instanceof Number && ((Number) version).doubleValue() == BUILD_DOCUMENT_VERSION)) { + throw new PluginSdkError("sdk.build.invalidResult", + method + " returned a version other than " + BUILD_DOCUMENT_VERSION + "."); + } + document.put("format", expected); + document.put("version", BUILD_DOCUMENT_VERSION); + } + if (Protocol.BUILD_EXECUTE.equals(method) || Protocol.BUILD_TEST.equals(method)) { + Object exit = document.get("exitCode"); + Object output = document.get("output"); + if (!(exit instanceof Number) || ((Number) exit).doubleValue() < Integer.MIN_VALUE + || ((Number) exit).doubleValue() > Integer.MAX_VALUE + || ((Number) exit).doubleValue() != ((Number) exit).longValue() + || !(output instanceof String) || Protocol.utf8Length((String) output) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs an int32 exitCode and bounded output."); + } + document.put("exitCode", ((Number) exit).longValue()); + } + if (Protocol.BUILD_PREPARE_DEBUG.equals(method)) { + if (!(document.get("program") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment")) + || document.size() != 4) { + throw new PluginSdkError("sdk.build.invalidResult", "Native debug preparation needs program, arguments, workingDirectory and environment only."); + } + } + if (Protocol.BUILD_PREPARE_RUN.equals(method)) { + Map executable = Json.object(document.get("executable")); + if (!("toolchain".equals(executable.get("kind")) || "command".equals(executable.get("kind"))) + || !(executable.get("value") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment"))) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs a portable launch plan."); + } + } + // Workspace containment and domain facts remain Core/provider responsibilities. + if (Protocol.utf8Length(Json.stringify(document)) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " exceeds the build-result size limit."); + } + return document; + } + + private static boolean stringList(Object value) { + if (!(value instanceof List)) return false; + for (Object item : (List) value) if (!(item instanceof String)) return false; + return true; + } + + private static boolean stringMap(Object value) { + if (!(value instanceof Map)) return false; + for (Map.Entry item : ((Map) value).entrySet()) { + if (!(item.getKey() instanceof String) || !(item.getValue() instanceof String)) return false; + } + return true; + } + + /** + * A function result as the JSON value Core accepts. A value JSON cannot + * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a + * log line, instead of breaking the response frame or being refused by Core. + */ + static Object functionResult(Object result) { + String encoded; + try { + encoded = Json.stringify(result); + } catch (Json.JsonException error) { + throw new PluginSdkError("sdk.function.invalidResult", "The result is not JSON: " + error.getMessage()); + } + if (encoded.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_RESULT_BYTES) { + throw new PluginSdkError("sdk.function.invalidResult", + "The result exceeds " + Protocol.MAX_RESULT_BYTES + " bytes."); + } + return result; + } + + private static boolean offers(Object entry, int version) { + if (!(entry instanceof Map)) { + return false; + } + Object versions = ((Map) entry).get("versions"); + if (!(versions instanceof List)) { + return false; + } + for (Object offered : (List) versions) { + if (offered instanceof Number && ((Number) offered).doubleValue() == version) { + return true; + } + } + return false; + } + + /** {@code capabilities.experimental}, or an empty map. */ + private static Map experimental(Object capabilities) { + Object experimental = capabilities instanceof Map ? ((Map) capabilities).get("experimental") : null; + return experimental instanceof Map ? Json.object(experimental) : Collections.emptyMap(); + } + + /** The JSON-RPC ID as a map key; numbers and strings never collide. */ + private static String requestKey(Object id) { + if (id instanceof Number) { + Number number = (Number) id; + return "number:" + (number.doubleValue() == number.longValue() ? Long.toString(number.longValue()) : number); + } + return (id instanceof String ? "string:" : "other:") + id; + } + + private static Map message(Object id, String method) { + Map message = new LinkedHashMap<>(); + message.put("jsonrpc", "2.0"); + if (id != null || method == null) { + message.put("id", id); + } + if (method != null) { + message.put("method", method); + } + return message; + } + + private static Map error(int code, String text) { + Map error = new LinkedHashMap<>(); + error.put("code", code); + error.put("message", text); + return error; + } + + private static Map singleton(String key, Object value) { + Map map = new LinkedHashMap<>(); + map.put(key, value); + return map; + } + + /** The failure inside {@code CompletableFuture}'s wrappers, from {@code join()} or {@code get()}. */ + static Throwable unwrap(Throwable error) { + Throwable current = error; + while ((current instanceof CompletionException || current instanceof ExecutionException) && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } + + /** The {@code { contextID, generation }} the host sent, or null. */ + private static Map workspaceContext(Object value) { + return Protocol.isContextReference(value) ? Host.contextReference(Json.object(value)) : null; + } + + /** + * The {@code { pluginID }} of the plugin that called a function through the + * relay, or null. Core adds it only to a relayed call, and only as exactly + * {@code { pluginID }}; anything else is not a caller. + */ + private Map callerReference(Object value) { + if (!negotiated.functions() || !(value instanceof Map)) { + return null; + } + Map caller = (Map) value; + Object pluginId = caller.get("pluginID"); + if (caller.size() != 1 || !(pluginId instanceof String) || ((String) pluginId).isEmpty()) { + return null; + } + return Collections.singletonMap("pluginID", pluginId); + } + + /** The session's wire, for host services. */ + private final class Wire implements HostChannel.Transport { + @Override + public boolean negotiated() { + return negotiated.functions(); + } + + @Override + public boolean ready() { + return phase == Phase.READY; + } + + @Override + public HostChannel.Sent send(String method, Object params) { + return Backend.this.send(method, params); + } + + @Override + public void notify(String method, Object params) { + Map notification = message(null, method); + notification.put("params", params); + write(notification); + } + + @Override + public void log(String message) { + Backend.this.diagnostics().degraded("notification", "subscription_queue_full"); + } + + @Override + public void log(String message, Throwable error) { + Backend.this.diagnostics().terminal("notification", error, System.nanoTime()); + } + + @Override + public void execute(Runnable task) { + executor.execute(task); + } + } + + /** One host request being handled. */ + private static final class Call { + final Cancellation cancellation; + final String functionId; + + Call(Cancellation cancellation, String functionId) { + this.cancellation = cancellation; + this.functionId = functionId; + } + } + + /** One request this backend sent to the host. */ + private static final class Pending { + final CompletableFuture future; + final String method; + + Pending(CompletableFuture future, String method) { + this.future = future; + this.method = method; + } + } + + /** Daemon threads, so a handler still running never keeps the process alive after exit. */ + private static final class ThreadNamer implements java.util.concurrent.ThreadFactory { + private final AtomicInteger next = new AtomicInteger(1); + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "lithe-sdk-call-" + next.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java new file mode 100644 index 0000000..6eb8e01 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java @@ -0,0 +1,143 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * What a handler gets besides its params: the call's cancellation, tools and + * host requests that end with the call, the backend's log, and progress for + * plugin functions or bounded build operations. + */ +public final class CallContext { + /** Sends one progress report; absent for model, dependency and discovery requests. */ + interface ProgressSink { + void report(String message, Double percentage); + default void report(String message, Double percentage, String output) { report(message, percentage); } + } + + private final java.util.concurrent.atomic.AtomicBoolean quietSuccess = new java.util.concurrent.atomic.AtomicBoolean(); + private final Cancellation cancellation; + private final Backend backend; + private final String functionId; + private final String operationId; + private final ProgressSink progress; + private final Host host; + private final Map workspaceContext; + private final Map caller; + + CallContext(Cancellation cancellation, Backend backend, String functionId, String operationId, ProgressSink progress, + Host host, Map workspaceContext, Map caller) { + this.cancellation = cancellation; + this.backend = backend; + this.functionId = functionId; + this.operationId = operationId; + this.progress = progress; + this.host = host; + this.workspaceContext = workspaceContext; + this.caller = caller; + } + + /** + * Cancelled when the host cancels the call, the backend shuts down, or the + * call ends; work a handler leaves running after it returned is stopped. + */ + public Cancellation cancellation() { + return cancellation; + } + + public boolean isCancelled() { + return cancellation.isCancelled(); + } + + /** Throws {@link CancelledException} once the call was cancelled. */ + public void throwIfCancelled() { + cancellation.throwIfCancelled(); + } + + /** + * Runs a tool that belongs to this call: cancelling the call or ending it + * stops the tool, and the backend shutting down ends it. + */ + public Processes.Result run(List command, Processes.Options options) throws IOException { + Processes.Options settings = options == null ? new Processes.Options() : options.copy(); + settings.listenerFailure(() -> diagnostics().degraded("notification", "output_listener_failed")); + Cancellation own = settings.cancellation(); + settings.cancellation(own == null ? cancellation : cancellation.combinedWith(own)); + return Processes.run(command, settings); + } + + /** Runs a tool that belongs to this call with default options. */ + public Processes.Result run(List command) throws IOException { + return run(command, null); + } + + public void suppressSuccessDiagnostics() { quietSuccess.set(true); } + boolean quietSuccess() { return quietSuccess.get(); } + + public Diagnostics diagnostics() { return new Diagnostics(backend, operationId); } + + /** + * Reports progress of a function or bounded build call. Function messages + * are cut to 1024 bytes, build messages to 4096; percentages are rounded to + * 0-100. Reports after cancellation or completion are dropped. + */ + public void progress(String message, Double percentage) { progress(message, percentage, null); } + + /** Build calls may additionally stream up to 64 KiB of output per report. */ + public void progress(String message, Double percentage, String output) { + if (progress != null && !cancellation.isCancelled()) progress.report(message, percentage, output); + } + + /** The function this call runs, or null for a build or LSP request. */ + public String functionId() { + return functionId; + } + + /** + * The wire operation ID of a function or bounded build call, otherwise null. + * It identifies the call in diagnostics and, when the request has no usable + * operation ID, falls back to the JSON-RPC request ID: do not use it as a + * {@code parentOperationID}. {@link #host()} already sends the right one. + */ + public String operationId() { + return operationId; + } + + /** + * Host services that belong to this call: requests still unanswered when + * the call is cancelled or ends fail with {@link CancelledException} and + * are cancelled on the wire. A subscription created here outlives the call + * until it is disposed. + */ + public Host host() { + return host; + } + + /** + * The {@code { contextID, generation }} of the workspace a function was + * invoked for, or null: for other calls and for an invocation outside a + * workspace. Pass it to the + * {@link Host} methods that name a context. + */ + public Map workspaceContext() { + return workspaceContext; + } + + /** + * The plugin that called this function through the relay: an + * unmodifiable {@code { pluginID }}, written by Core from the calling + * session. Null when the host started the call, and for calls that are not + * function invocations. + * Decide by who asks from this, never from a plugin ID in the params, + * which any caller can write. + */ + public Map caller() { + return caller; + } + + /** The {@code pluginID} of {@link #caller()}, or null when there is no calling plugin. */ + public String callerPluginId() { + return caller == null ? null : (String) caller.get("pluginID"); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java new file mode 100644 index 0000000..d80cd7d --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java @@ -0,0 +1,112 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.List; + +/** + * Cancellation of one call, or of work a plugin manages itself. Listeners run + * once, on the thread that cancels; a listener added after cancellation runs + * immediately. A listener that throws is logged to stderr and does not keep + * the others, or the thread that cancelled, from running on. Cancelling never interrupts threads, because an interrupt + * closes NIO channels a handler may be writing state through; long work checks + * {@link #isCancelled()} or {@link #throwIfCancelled()} instead. + */ +public final class Cancellation { + private final Object lock = new Object(); + private final List listeners = new ArrayList<>(); + private String reason; + private final Runnable listenerFailure; + public Cancellation() { this(() -> {}); } + Cancellation(Runnable listenerFailure) { this.listenerFailure = listenerFailure; } + + /** Cancels with {@code reason}; later calls have no effect. */ + public void cancel(String reason) { + List pending; + synchronized (lock) { + if (this.reason != null) { + return; + } + this.reason = reason == null ? "The request was cancelled." : reason; + pending = new ArrayList<>(listeners); + listeners.clear(); + } + for (Runnable listener : pending) { + runIsolated(listener); + } + } + + public boolean isCancelled() { + synchronized (lock) { + return reason != null; + } + } + + /** Throws {@link CancelledException} once cancelled. */ + public void throwIfCancelled() { + String current; + synchronized (lock) { + current = reason; + } + if (current != null) { + throw new CancelledException(current); + } + } + + /** + * Runs {@code listener} on cancellation. The returned handle removes it, + * for work that finished first. + */ + public Registration onCancel(Runnable listener) { + synchronized (lock) { + if (reason == null) { + listeners.add(listener); + return () -> { + synchronized (lock) { + listeners.remove(listener); + } + }; + } + } + runIsolated(listener); + return () -> {}; + } + + /** + * A token cancelled when either this one or {@code other} is; for work that + * a plugin may also stop for its own reasons. + */ + public Cancellation combinedWith(Cancellation other) { + Cancellation combined = new Cancellation(listenerFailure); + Registration first = onCancel(() -> combined.cancel(reasonOrDefault())); + Registration second = other.onCancel(() -> combined.cancel(other.reasonOrDefault())); + combined.onCancel(() -> { + first.remove(); + second.remove(); + }); + return combined; + } + + private void runIsolated(Runnable listener) { + try { + listener.run(); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + + /** The reason it was cancelled with, or the default text before that. */ + String reason() { + return reasonOrDefault(); + } + + private String reasonOrDefault() { + synchronized (lock) { + return reason == null ? "The request was cancelled." : reason; + } + } + + /** Removes a cancellation listener. */ + public interface Registration { + void remove(); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java new file mode 100644 index 0000000..dd01676 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java @@ -0,0 +1,14 @@ +package io.github.litheidea.plugin.sdk; + +/** + * Thrown when the call a piece of work belongs to was cancelled or ended. + * A handler normally lets it propagate; the SDK then answers the host with + * {@code RequestCancelled}. + */ +public class CancelledException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public CancelledException(String message) { + super(message); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java new file mode 100644 index 0000000..c4d9bd4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -0,0 +1,72 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** Typed facts for the host's litheLogging 1 catalog; never accepts message or payload text. */ +public final class Diagnostics { + static final long MAX_INTEGER = 9007199254740991L; + static final Set OPERATIONS = new HashSet<>(Arrays.asList( + "initialize", "shutdown", "notification", "function-call", "result-encoding", + "lithe/build/model", "lithe/build/dependencies", "lithe/build/execute", "lithe/build/test", + "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", + "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", "lithe/vcs/fileHistory", + "lithe/vcs/annotate", "lithe/vcs/checkin", "lithe/vcs/rollback", "lithe/vcs/update", + "lithe/vcs/fileOperation", "lithe/vcs/resolve", "lithe/vcs/cleanup", + "lithe/keymap/import")); + private final Backend backend; + private final String operationId; + + Diagnostics(Backend backend, String operationId) { + this.backend = backend; + this.operationId = operationId; + } + + public void degraded(String operation, String code, Long count) { record("degraded", operation, code, count, null); } + public void recovered(String operation, String code, Long count) { record("recovered", operation, code, count, null); } + public void degraded(String operation, String code) { degraded(operation, code, null); } + public void recovered(String operation, String code) { recovered(operation, code, null); } + + static boolean token(String value, int maximum) { + return value != null && value.length() > 0 && value.length() <= maximum && value.matches("[A-Za-z0-9._:/\\-$]+"); + } + + static String requestOperationId(String operationId, Object requestId) { + if (token(operationId, 128)) return operationId; + String fallback = requestId instanceof String ? (String) requestId : null; + if (requestId instanceof Number) { + double number = ((Number) requestId).doubleValue(); + if (Double.isFinite(number) && Math.abs(number) <= MAX_INTEGER && number == Math.rint(number)) { + fallback = Long.toString(((Number) requestId).longValue()); + } + } + return token(fallback, 128) ? fallback : null; + } + + void terminal(String operation, Throwable failure, long started) { + String code = null; + if (failure != null) { + Throwable error = Backend.unwrap(failure); + code = error instanceof PluginError ? ((PluginError) error).code() : "internal_error"; + } + record(failure == null ? "operationFinished" : "operationFailed", operation, code, null, + Math.min(MAX_INTEGER, Math.max(0, (System.nanoTime() - started) / 1000000))); + } + + private void record(String kind, String operation, String code, Long count, Long duration) { + if (!backend.loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation."); + if (code != null && !token(code, 64)) throw new PluginSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code."); + if (count != null && (count < 0 || count > MAX_INTEGER)) throw new PluginSdkError("sdk.logging.invalidCount", "Diagnostics need a nonnegative safe count."); + Map params = new LinkedHashMap<>(); + params.put("kind", kind); + params.put("operation", operation.length() <= 64 ? operation : "function-call"); + if (code != null) params.put("code", code); + if (count != null) params.put("count", count); + if (duration != null) params.put("durationMs", duration); + if (token(operationId, 128)) params.put("operationId", operationId); + backend.logFact(params); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java new file mode 100644 index 0000000..36f76f6 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java @@ -0,0 +1,138 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * LSP base-protocol framing: {@code Content-Length} headers followed by a UTF-8 + * JSON body. Lithe talks to every plugin backend this way, so the SDK owns the + * framing and plugin code never writes to stdout itself. + */ +public final class Framing { + /** Largest header block accepted from the host. */ + static final int MAX_HEADER_BYTES = 8192; + + /** Largest body accepted from the host. Larger frames end the session. */ + public static final int MAX_FRAME_BYTES = 64 * 1024 * 1024; + + /** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ + public static final Object MALFORMED = new Object() { + @Override + public String toString() { + return "MALFORMED"; + } + }; + + private static final byte[] HEADER_END = {'\r', '\n', '\r', '\n'}; + + private Framing() {} + + /** A framing error the session cannot recover from. */ + public static final class FramingException extends RuntimeException { + private static final long serialVersionUID = 1L; + + FramingException(String message) { + super(message); + } + } + + /** Encodes one JSON-RPC message as a complete frame. */ + public static byte[] encode(Object message) { + byte[] body = Json.stringify(message).getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + byte[] frame = Arrays.copyOf(header, header.length + body.length); + System.arraycopy(body, 0, frame, header.length, body.length); + return frame; + } + + /** Incrementally splits a byte stream into decoded JSON-RPC messages. */ + public static final class Decoder { + private byte[] buffer = new byte[8192]; + private int length; + + /** + * Appends {@code count} bytes of {@code chunk} and returns every complete + * message they finished. A body that is not JSON is returned as + * {@link #MALFORMED} so the caller can report it without losing the + * framing position. + */ + public List push(byte[] chunk, int offset, int count) { + ensureCapacity(length + count); + System.arraycopy(chunk, offset, buffer, length, count); + length += count; + List messages = new ArrayList<>(); + int start = 0; + for (;;) { + int headerEnd = indexOfHeaderEnd(start); + int available = length - start; + // The same bound whether the header arrived whole or in pieces. + if ((headerEnd >= 0 && headerEnd - start > MAX_HEADER_BYTES) + || (headerEnd < 0 && available > MAX_HEADER_BYTES)) { + throw new FramingException("The message header is too long."); + } + if (headerEnd < 0) { + break; + } + int bodyLength = contentLength(new String(buffer, start, headerEnd - start, StandardCharsets.US_ASCII)); + int bodyStart = headerEnd + HEADER_END.length; + if ((long) length < (long) bodyStart + bodyLength) { + break; + } + String body = new String(buffer, bodyStart, bodyLength, StandardCharsets.UTF_8); + start = bodyStart + bodyLength; + try { + messages.add(Json.parse(body)); + } catch (Json.JsonException error) { + messages.add(MALFORMED); + } + } + if (start > 0) { + System.arraycopy(buffer, start, buffer, 0, length - start); + length -= start; + } + return messages; + } + + private int indexOfHeaderEnd(int from) { + for (int index = from; index + HEADER_END.length <= length; index++) { + if (buffer[index] == '\r' && buffer[index + 1] == '\n' + && buffer[index + 2] == '\r' && buffer[index + 3] == '\n') { + return index; + } + } + return -1; + } + + private void ensureCapacity(int required) { + if (required > buffer.length) { + buffer = Arrays.copyOf(buffer, Math.max(required, buffer.length * 2)); + } + } + } + + private static int contentLength(String header) { + for (String line : header.split("\r\n")) { + int separator = line.indexOf(':'); + if (separator < 0) { + continue; + } + if (!line.substring(0, separator).trim().equalsIgnoreCase("content-length")) { + continue; + } + String value = line.substring(separator + 1).trim(); + if (!value.matches("[0-9]+")) { + break; + } + // More than ten digits exceeds the limit whatever they are. + long length = value.length() > 10 ? Long.MAX_VALUE : Long.parseLong(value); + if (length > MAX_FRAME_BYTES) { + throw new FramingException("A message of " + value + " bytes exceeds the " + + MAX_FRAME_BYTES + "-byte limit."); + } + return (int) length; + } + throw new FramingException("A message has no valid Content-Length header."); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java new file mode 100644 index 0000000..fb0e988 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -0,0 +1,637 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.BooleanSupplier; + +/** + * Host services ({@code lithe/host/*}): credentials; workspace contexts, + * files, documents, the editor, previews, the browser, messages, and + * capability discovery; calls to other plugins' functions. Every method + * answers with a future and never blocks; failures the host reports arrive as + * {@link HostError}. + * + *

{@link Backend#host()} is usable once the session is ready. A handler's + * {@link CallContext#host()} belongs to its call: requests still unanswered + * when the call is cancelled or ends fail with {@link CancelledException} and + * are cancelled on the wire. At most 16 requests are on the wire at once; the + * rest wait their turn. + * + *

Contract: {@code contract/v1/README.md}, "Host services". + */ +public final class Host { + /** Receives a subscription's events, one at a time and in order. */ + @FunctionalInterface + public interface Listener { + void onEvent(Event event) throws Exception; + } + + /** One {@code lithe/host/subscriptions/notify}. */ + public static final class Event { + private final String subscriptionId; + private final long sequence; + private final boolean gap; + private final Object event; + + Event(String subscriptionId, long sequence, boolean gap, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.gap = gap; + this.event = event; + } + + public String subscriptionId() { + return subscriptionId; + } + + /** Starts at 1 and grows by one per event of the subscription. */ + public long sequence() { + return sequence; + } + + /** + * True when events before this one were lost, so state built from + * earlier events should be refreshed, for example by rescanning. + */ + public boolean gap() { + return gap; + } + + /** The event, usually an object. */ + public Object event() { + return event; + } + } + + /** A host subscription, such as a file watch or registered editor actions. */ + public static final class Subscription { + private final String id; + private final BooleanSupplier live; + private final HostChannel channel; + + Subscription(String id, BooleanSupplier live, HostChannel channel) { + this.id = id; + this.live = live; + this.channel = channel; + } + + public String id() { + return id; + } + + /** True once disposed here or the session ended. */ + public boolean isDisposed() { + return !live.getAsBoolean(); + } + + /** Stops routing events at once and asks the host to dispose the subscription. */ + public CompletableFuture dispose() { + return channel.dispose(id); + } + } + + private final HostChannel channel; + private final List scope; + /** The wire operation ID of the function call this Host belongs to, or null; the default parent of {@link Functions#invoke}. */ + private final String parentOperationId; + private final Credentials credentials = new Credentials(); + private final Subscriptions subscriptions = new Subscriptions(); + private final Workspace workspace = new Workspace(); + private final Documents documents = new Documents(); + private final Editor editor = new Editor(); + private final Preview preview = new Preview(); + private final Browser browser = new Browser(); + private final Window window = new Window(); + private final Functions functions = new Functions(); + + Host(HostChannel channel, List scope, String parentOperationId) { + this.channel = channel; + this.scope = Collections.unmodifiableList(new ArrayList<>(scope)); + this.parentOperationId = parentOperationId; + } + + /** Whether the host offered plugin functions ({@code litheFunctions}); false before {@code initialize}. */ + public boolean negotiated() { + return channel.negotiated(); + } + + /** + * The same services, with requests also cancelled by {@code cancellation}, + * for work a plugin may stop for its own reasons. Calls to other plugins + * keep the parent call of this Host. + */ + public Host withCancellation(Cancellation cancellation) { + if (cancellation == null) { + throw new IllegalArgumentException("A cancellation must not be null."); + } + List combined = new ArrayList<>(scope); + combined.add(cancellation); + return new Host(channel, combined, parentOperationId); + } + + /** + * Sends any {@code lithe/host/*} request, including methods a later host + * adds; {@link #supports} says whether the session may call it. + */ + public CompletableFuture request(String method, Object params) { + return channel.request(method, params, scope); + } + + /** + * Sends a request that answers {@code { subscriptionID }} and routes the + * subscription's events to {@code listener}. + */ + public CompletableFuture subscribe(String method, Object params, Listener listener) { + return channel.subscribe(method, params, listener, scope); + } + + /** + * {@code { protocolVersion, backendAuthority, services, limits }}, asked + * once per session. + */ + public CompletableFuture> capabilities() { + return channel.capabilities(); + } + + /** Whether this session may call {@code method}, as {@link #capabilities} lists it. */ + public CompletableFuture supports(String method) { + return channel.supports(method); + } + + public Credentials credentials() { + return credentials; + } + + public Subscriptions subscriptions() { + return subscriptions; + } + + public Workspace workspace() { + return workspace; + } + + public Documents documents() { + return documents; + } + + public Editor editor() { + return editor; + } + + public Preview preview() { + return preview; + } + + public Browser browser() { + return browser; + } + + public Terminal terminal() { + return new Terminal(); + } + + public Window window() { + return window; + } + + /** Calls to functions other plugins export. */ + public Functions functions() { + return functions; + } + + /** + * {@code { contextID, generation }} of a context reference or of a full + * context from {@code listContexts} or {@code getContext}, so either can be + * passed on. + * + * @throws PluginSdkError {@code sdk.host.invalidContext} for anything else + */ + public static Map contextReference(Map context) { + Object id = context == null ? null : context.get("contextID"); + Object generation = context == null ? null : context.get("generation"); + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id) || !Protocol.isGeneration(generation)) { + throw new PluginSdkError("sdk.host.invalidContext", + "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation."); + } + Map reference = new LinkedHashMap<>(); + reference.put("contextID", id); + reference.put("generation", ((Number) generation).longValue()); + return Collections.unmodifiableMap(reference); + } + + /** Secrets in the operating system's credential store, scoped to the plugin. */ + public final class Credentials { + private Credentials() {} + + /** The stored secret, or null when nothing is stored under {@code key}. */ + public CompletableFuture get(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_GET, params("key", key), scope).thenApply(result -> { + if (result == null) { + return null; + } + Object secret = result instanceof Map ? ((Map) result).get("secret") : null; + if (!(secret instanceof String)) { + throw new PluginSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret."); + } + return (String) secret; + }); + } + + public CompletableFuture set(String key, String secret) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_CREDENTIAL_SECRET_BYTES) { + return failed(new PluginSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.")); + } + Map params = params("key", key); + params.put("secret", secret); + return channel.request(Protocol.HOST_CREDENTIALS_SET, params, scope).thenApply(result -> null); + } + + /** Deletes the secret; also succeeds when nothing was stored. */ + public CompletableFuture delete(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_DELETE, params("key", key), scope).thenApply(result -> null); + } + } + + public final class Subscriptions { + private Subscriptions() {} + + /** Disposes a subscription by ID; also succeeds for an unknown or disposed one. */ + public CompletableFuture dispose(String subscriptionId) { + return channel.dispose(subscriptionId); + } + } + + /** + * Workspace contexts and files. Every method but + * {@link #listContexts} names a context: a reference from + * {@link CallContext#workspaceContext()}, or a context from + * {@link #listContexts}. + */ + public final class Workspace { + private Workspace() {} + + /** {@code { revision, contexts }}. */ + public CompletableFuture> listContexts() { + return object(Protocol.HOST_WORKSPACE_LIST_CONTEXTS, channel.request( + Protocol.HOST_WORKSPACE_LIST_CONTEXTS, new LinkedHashMap(), scope)); + } + + public CompletableFuture> getContext(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_CONTEXT, context, null); + } + + /** {@code { folders }}. */ + public CompletableFuture> getFolders(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_FOLDERS, context, null); + } + + /** {@code params}: {@code resource, cursor?, limit?}. */ + public CompletableFuture> readDirectory(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_DIRECTORY, context, params); + } + + /** {@code params}: {@code resource}. */ + public CompletableFuture> stat(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_STAT, context, params); + } + + /** {@code params}: {@code resource, maximumBytes?}. */ + public CompletableFuture> readFile(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_FILE, context, params); + } + + /** + * Watches {@code resource, recursive?}; events are + * {@code { rootID, changedPaths, requiresRescan }}. + */ + public CompletableFuture watch(Map context, Map params, Listener listener) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_WORKSPACE_WATCH, message, listener, scope); + } + + /** {@code params}: root {@code resource, query, fileMask?, cursor?, limit?}. */ + public CompletableFuture> findFiles(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_FILES, context, params); + } + + /** {@code params}: root {@code resource, pattern}, and optional search options. */ + public CompletableFuture> findText(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_TEXT, context, params); + } + } + + /** Open documents, read from their live buffers. */ + public final class Documents { + private Documents() {} + + /** {@code { documents }}. */ + public CompletableFuture> list(Map context) { + return scoped(Protocol.HOST_DOCUMENTS_LIST, context, null); + } + + /** {@code params}: {@code documentID}; answers {@code { document, text }}. */ + public CompletableFuture> getSnapshot(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_GET_SNAPSHOT, context, params); + } + } + + /** The text editor. */ + public final class Editor { + private Editor() {} + + /** The foreground text tab's document summary, or null. */ + public CompletableFuture> getActive(Map context) { + return scoped(Protocol.HOST_EDITOR_GET_ACTIVE, context, null); + } + + /** {@code params}: {@code documentID}. */ + public CompletableFuture> getSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_GET_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, edits}. */ + public CompletableFuture> applyEdits(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_APPLY_EDITS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, selections, replacements}. */ + public CompletableFuture> replaceSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REPLACE_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, at, text}. */ + public CompletableFuture> insertText(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_INSERT_TEXT, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> open(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_OPEN, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> reveal(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REVEAL, context, params); + } + + /** + * Registers editor actions ({@code id, function, selector}) that invoke + * one of the backend's functions; disposing the subscription removes them. + */ + public CompletableFuture registerActions(Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_EDITOR_REGISTER_ACTIONS, message, null, scope); + } + } + + /** HTML previews. */ + public final class Preview { + private Preview() {} + + /** {@code params}: HTML {@code resource, presentation?, range?}. */ + public CompletableFuture> openHtml(Map context, Map params) { + return scoped(Protocol.HOST_PREVIEW_OPEN_HTML, context, params); + } + } + + /** The system browser. */ + public final class Browser { + private Browser() {} + + /** {@code params}: exactly one of an HTTP(S) {@code url} or an HTML {@code resource}. */ + public CompletableFuture> openExternal(Map context, Map params) { + return scoped(Protocol.HOST_BROWSER_OPEN_EXTERNAL, context, params); + } + } + + /** Native terminals private to the backend session and workspace. */ + public final class Terminal { + private Terminal() {} + /** Params: executable, arguments?, title?, cwd?, environment?, show?. */ + public CompletableFuture> create(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CREATE, context, params); + } + public CompletableFuture> show(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_SHOW, context, params); + } + public CompletableFuture> close(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CLOSE, context, params); + } + /** Restarts the saved argv, restoring only the chosen plain display suffix. */ + public CompletableFuture> reopen(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_REOPEN, context, params); + } + /** Forgets the handle and its retained display history. */ + public CompletableFuture> dispose(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_DISPOSE, context, params); + } + /** Params: terminalID; disposing the subscription does not close the terminal. */ + public CompletableFuture onExit(Map context, Map params) { + Map message; + try { message = withContext(context, params); } + catch (PluginSdkError error) { return failed(error); } + return channel.subscribe(Protocol.HOST_TERMINAL_ON_EXIT, message, null, scope); + } + } + + /** + * Messages in the window. {@code params}: {@code text, + * actions?}; answers {@code { selectedIndex }}, null on dismissal. + */ + public final class Window { + private Window() {} + + public CompletableFuture> showInformation(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_INFORMATION, context, params); + } + + public CompletableFuture> showWarning(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_WARNING, context, params); + } + + public CompletableFuture> showError(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_ERROR, context, params); + } + } + + /** + * Calls to functions other plugins export, relayed by Core. The plugin's + * manifest must declare each function it calls. Both methods fail with a + * {@link HostError} {@code plugin.host.unavailable} when the host did not + * offer plugin functions, without sending anything, and a malformed + * argument fails with {@code sdk.functions.invalidCall} (a malformed + * context with {@code sdk.host.invalidContext}), also without sending + * anything. + * + *

A provider's own failure arrives as a {@link HostError} with code + * {@code plugin.function.failed}; {@link HostError#pluginErrorCode()} is + * its error code. Other relay failures have their own + * {@code plugin.function.*} codes, see {@link HostError#CODES}. + */ + public final class Functions { + private Functions() {} + + /** + * {@code { providers: [{ pluginID, version }] }}: the enabled plugins + * other than this one that export {@code functionId}, sorted by plugin + * ID. A listed provider's backend need not be running. + */ + public CompletableFuture> providers(String functionId) { + if (!Protocol.isFunctionId(functionId)) { + return failed(invalidCall("A functionID is dot-separated lowerCamelCase segments of at most 128 bytes.")); + } + return object(Protocol.HOST_FUNCTIONS_PROVIDERS, channel.request( + Protocol.HOST_FUNCTIONS_PROVIDERS, params("functionID", functionId), scope)); + } + + /** + * Calls one provider's exported function in the workspace {@code context} + * (a reference from {@link CallContext#workspaceContext()}, or a context + * from {@code workspace().listContexts()}) and answers {@code { value }}, + * the provider's result, where {@code value} may be null. Only the + * fields listed here are sent. {@code call}: + *

    + *
  • {@code pluginID}: the provider, a non-empty string; required;
  • + *
  • {@code functionID}: the exported function; required;
  • + *
  • {@code params}: an object, omitted when absent;
  • + *
  • {@code timeoutMilliseconds}: a positive integer; Core defaults to + * 60 000 and caps it at 600 000;
  • + *
  • {@code parentOperationID}: a string of 1-128 bytes. When absent + * and this Host belongs to a function call, that call's wire operation + * ID is sent, so Core knows the new call belongs to it; otherwise the + * field is omitted and Core counts the new call as a child of every + * relayed call this backend is serving.
  • + *
+ * When the call this Host belongs to is cancelled or ends, the relayed + * call is cancelled on the wire and the future fails with + * {@link CancelledException}. + */ + public CompletableFuture> invoke(Map context, Map call) { + Map message; + try { + message = relayParams(context, call); + } catch (PluginSdkError error) { + return failed(error); + } + return object(Protocol.HOST_FUNCTIONS_INVOKE, channel.request(Protocol.HOST_FUNCTIONS_INVOKE, message, scope)); + } + } + + /** The wire params of a relayed call: the listed fields of {@code call}, never another one. */ + private Map relayParams(Map context, Map call) { + if (call == null) { + throw invalidCall("A call is { pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }."); + } + Object pluginId = call.get("pluginID"); + if (!(pluginId instanceof String) || ((String) pluginId).isEmpty()) { + throw invalidCall("A call's pluginID is a non-empty string."); + } + Object functionId = call.get("functionID"); + if (!(functionId instanceof String) || !Protocol.isFunctionId((String) functionId)) { + throw invalidCall("A functionID is dot-separated lowerCamelCase segments of at most 128 bytes."); + } + Map message = new LinkedHashMap<>(); + message.put("pluginID", pluginId); + message.put("functionID", functionId); + message.put("context", contextReference(context)); + Object params = call.get("params"); + if (params != null) { + if (!(params instanceof Map)) { + throw invalidCall("A call's params is an object."); + } + message.put("params", params); + } + Object timeout = call.get("timeoutMilliseconds"); + if (timeout != null) { + if (!Protocol.isGeneration(timeout)) { + throw invalidCall("A call's timeoutMilliseconds is a positive integer."); + } + message.put("timeoutMilliseconds", ((Number) timeout).longValue()); + } + Object parent = call.get("parentOperationID"); + if (parent == null) { + parent = parentOperationId; + } else if (!Protocol.isParentOperationId(parent)) { + throw invalidCall("A call's parentOperationID is a string of 1-128 bytes."); + } + if (parent != null) { + message.put("parentOperationID", parent); + } + return message; + } + + private static PluginSdkError invalidCall(String message) { + return new PluginSdkError("sdk.functions.invalidCall", message); + } + + /** A method whose params name a workspace context. */ + private CompletableFuture> scoped(String method, Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return object(method, channel.request(method, message, scope)); + } + + private static Map withContext(Map context, Map params) { + Map message = params == null ? new LinkedHashMap() : new LinkedHashMap(params); + message.put("context", contextReference(context)); + return message; + } + + /** The result as an object, or null; anything else is a host bug. */ + private static CompletableFuture> object(String method, CompletableFuture response) { + return response.thenApply(result -> { + if (result == null) { + return null; + } + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered with something other than an object."); + } + return Json.object(result); + }); + } + + private static Map params(String key, Object value) { + Map params = new LinkedHashMap<>(); + params.put(key, value); + return params; + } + + private static PluginSdkError invalidKey() { + return new PluginSdkError("sdk.credentials.invalidKey", + "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\"."); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java new file mode 100644 index 0000000..995e7e4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java @@ -0,0 +1,495 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +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.RejectedExecutionException; + +/** + * The session's host-request state. The backend owns the wire; this class + * owns what Core expects of a well-behaved client -- at most 16 unanswered + * host requests, cancellation through {@code $/cancelRequest}, and + * subscription events routed by ID, in order, off the reader thread. + * + *

Contract: {@code contract/v1/README.md}, "Host services". + */ +final class HostChannel { + /** Events kept for a subscription whose creating request is still unanswered. */ + static final int MAX_EARLY_EVENTS = 128; + + /** The backend's wire. */ + interface Transport { + /** Whether the host offered plugin functions ({@code litheFunctions}); false before {@code initialize}. */ + boolean negotiated(); + + boolean ready(); + + /** Writes a request; its response settles when the host answers or the session ends. */ + Sent send(String method, Object params); + + void notify(String method, Object params); + + void log(String message); + + void log(String message, Throwable error); + + /** Runs plugin code off the reader thread. */ + void execute(Runnable task); + } + + /** A request on the wire. */ + static final class Sent { + final String id; + final CompletableFuture response; + + Sent(String id, CompletableFuture response) { + this.id = id; + this.response = response; + } + } + + private enum State { QUEUED, SENDING, SENT } + + /** One host request; settles for its caller once. */ + private static final class Entry { + final String method; + final Object params; + final CompletableFuture future = new CompletableFuture<>(); + final List registrations = new ArrayList<>(); + State state = State.QUEUED; + boolean settled; + /** Cancelled while being written: {@code $/cancelRequest} follows the write. */ + boolean cancelAfterWrite; + String id; + + Entry(String method, Object params) { + this.method = method; + this.params = params; + } + } + + /** A live subscription. */ + private static final class Route { + final String id; + final Host.Listener listener; + final ArrayDeque pending = new ArrayDeque<>(); + volatile boolean live = true; + long lastSequence; + boolean draining; + + Route(String id, Host.Listener listener) { + this.id = id; + this.listener = listener; + } + + boolean isLive() { + return live; + } + } + + private static final class Early { + final String subscriptionId; + final long sequence; + final Object event; + + Early(String subscriptionId, long sequence, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.event = event; + } + } + + private final Transport transport; + private final Object lock = new Object(); + private final ArrayDeque queue = new ArrayDeque<>(); + private final Map routes = new HashMap<>(); + private final List early = new ArrayList<>(); + private int inFlight; + /** Subscribing requests not yet answered; early events wait only while there are some. */ + private int subscribing; + private CompletableFuture> capabilities; + private boolean closed; + + HostChannel(Transport transport) { + this.transport = transport; + } + + boolean negotiated() { + return transport.negotiated(); + } + + /** + * Sends {@code method} once a slot is free. Cancelling any of + * {@code scope} rejects the caller at once with {@link CancelledException}; + * a request already sent is cancelled on the wire, and never sent again, + * because a cancelled mutation may already have taken effect. + */ + CompletableFuture request(String method, Object params, List scope) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + return failed(new PluginSdkError("sdk.host.method", + method + " is not a host method; host requests are lithe/host/*.")); + } + if (!open()) { + return failed(notReady()); + } + if (!transport.negotiated()) { + // The answer Core would give, without the round trip. + return failed(unavailable(method, + "The host did not negotiate plugin functions (litheFunctions), which offer host services.")); + } + for (Cancellation cancellation : scope) { + try { + cancellation.throwIfCancelled(); + } catch (CancelledException error) { + return failed(error); + } + } + Entry entry = new Entry(method, params); + synchronized (lock) { + if (closed || !transport.ready()) { + return failed(notReady()); + } + queue.add(entry); + } + for (Cancellation cancellation : scope) { + Cancellation.Registration registration = cancellation.onCancel(() -> cancel(entry, cancellation)); + boolean settled; + synchronized (lock) { + settled = entry.settled; + if (!settled) { + entry.registrations.add(registration); + } + } + if (settled) { + registration.remove(); + } + } + drain(); + return entry.future; + } + + /** + * Sends a request whose result is {@code { subscriptionID }} and routes + * that subscription's events to {@code listener}, one at a time and in the + * order the host sent them. + */ + CompletableFuture subscribe(String method, Object params, Host.Listener listener, + List scope) { + synchronized (lock) { + subscribing++; + } + return request(method, params, scope).handle((result, error) -> { + try { + if (error != null) { + throw new CompletionException(Backend.unwrap(error)); + } + Object id = result instanceof Map ? ((Map) result).get("subscriptionID") : null; + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered without a subscriptionID."); + } + String subscriptionId = (String) id; + Route route = new Route(subscriptionId, listener); + synchronized (lock) { + if (closed) { + throw new PluginSdkError("sdk.session.closed", "The session ended."); + } + routes.put(subscriptionId, route); + // Events the host sent before this answer was read. + for (Iterator events = early.iterator(); events.hasNext();) { + Early event = events.next(); + if (event.subscriptionId.equals(subscriptionId)) { + events.remove(); + emit(route, event.sequence, event.event); + } + } + } + return new Host.Subscription(subscriptionId, route::isLive, this); + } finally { + synchronized (lock) { + subscribing--; + if (subscribing == 0) { + early.clear(); + } + } + } + }); + } + + /** Stops routing a subscription's events at once and asks the host to dispose it. */ + CompletableFuture dispose(String subscriptionId) { + synchronized (lock) { + Route route = routes.remove(subscriptionId); + if (route != null) { + route.live = false; + route.pending.clear(); + } + if (closed || !transport.ready()) { + return CompletableFuture.completedFuture(null); + } + } + Map params = new LinkedHashMap<>(); + params.put("subscriptionID", subscriptionId); + return request(Protocol.HOST_SUBSCRIPTIONS_DISPOSE, params, Collections.emptyList()) + .thenApply(result -> null); + } + + /** Routes one {@code lithe/host/subscriptions/notify}. */ + void deliver(Map params) { + Object id = params.get("subscriptionID"); + if (!(id instanceof String)) { + return; + } + Object number = params.get("sequence"); + long sequence = number instanceof Number ? ((Number) number).longValue() : 0; + synchronized (lock) { + Route route = routes.get(id); + if (route != null) { + emit(route, sequence, params.get("event")); + } else if (subscribing > 0) { + if (early.size() < MAX_EARLY_EVENTS) { + early.add(new Early((String) id, sequence, params.get("event"))); + } else { + transport.log("Dropped an early subscription event: queue_full"); + } + } + // Otherwise the subscription was disposed; nothing follows a disposal. + } + } + + /** The cached {@code getCapabilities} answer; Core answers it itself. */ + CompletableFuture> capabilities() { + if (!transport.negotiated()) { + return failed(unavailable(Protocol.HOST_GET_CAPABILITIES, + "The host did not negotiate plugin functions (litheFunctions), which offer capability discovery.")); + } + CompletableFuture> answer; + synchronized (lock) { + if (capabilities != null) { + return capabilities.thenApply(result -> result); + } + answer = new CompletableFuture<>(); + capabilities = answer; + } + request(Protocol.HOST_GET_CAPABILITIES, null, Collections.emptyList()).whenComplete((result, error) -> { + if (error == null && result instanceof Map) { + answer.complete(Collections.unmodifiableMap(Json.object(result))); + return; + } + synchronized (lock) { + if (capabilities == answer) { + capabilities = null; + } + } + answer.completeExceptionally(error != null ? Backend.unwrap(error) + : new PluginSdkError("sdk.host.invalidResult", "getCapabilities answered without an object.")); + }); + return answer.thenApply(result -> result); + } + + /** + * Whether this session may call {@code method}, from + * {@code getCapabilities}; false when the host offered no plugin functions. + * A missing grant still fails the request. + */ + CompletableFuture supports(String method) { + if (!transport.negotiated()) { + return CompletableFuture.completedFuture(false); + } + return capabilities().thenApply(answer -> { + Object services = answer.get("services"); + if (!(services instanceof Map)) { + return false; + } + for (Object service : ((Map) services).values()) { + Object methods = service instanceof Map ? ((Map) service).get("methods") : null; + if (methods instanceof List && ((List) methods).contains(method)) { + return true; + } + } + return false; + }); + } + + /** Ends the channel with the session: queued requests fail, subscriptions end. */ + void close() { + List queued; + synchronized (lock) { + closed = true; + queued = new ArrayList<>(queue); + queue.clear(); + for (Route route : routes.values()) { + route.live = false; + route.pending.clear(); + } + routes.clear(); + early.clear(); + capabilities = null; + } + for (Entry entry : queued) { + settle(entry, null, new PluginSdkError("sdk.session.closed", "The session ended.")); + } + } + + private void drain() { + List starting = new ArrayList<>(); + synchronized (lock) { + while (!closed && inFlight < Protocol.MAX_PENDING_HOST_REQUESTS && !queue.isEmpty()) { + Entry entry = queue.poll(); + entry.state = State.SENDING; + inFlight++; + starting.add(entry); + } + } + for (Entry entry : starting) { + start(entry); + } + } + + /** Writes outside the lock, so a full pipe never blocks the reader thread's routing. */ + private void start(Entry entry) { + Sent sent; + try { + sent = transport.send(entry.method, entry.params); + } catch (RuntimeException error) { + // Params JSON cannot encode never reached the wire. + synchronized (lock) { + inFlight--; + } + settle(entry, null, error); + drain(); + return; + } + boolean cancelNow; + synchronized (lock) { + entry.id = sent.id; + entry.state = State.SENT; + cancelNow = entry.cancelAfterWrite; + } + if (cancelNow) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", sent.id)); + } + sent.response.whenComplete((result, error) -> { + synchronized (lock) { + // The slot frees when Core answers, also after a cancellation: + // Core answers a cancelled request at once. + inFlight--; + } + settle(entry, result, error == null ? null : Backend.unwrap(error)); + drain(); + }); + } + + private void cancel(Entry entry, Cancellation cancellation) { + String id = null; + synchronized (lock) { + if (entry.settled) { + return; + } + if (entry.state == State.QUEUED) { + queue.remove(entry); + } else if (entry.state == State.SENDING) { + entry.cancelAfterWrite = true; + } else { + id = entry.id; + } + } + if (id != null) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", id)); + } + settle(entry, null, new CancelledException(cancellation.reason())); + } + + /** Completes the caller's future once, on a handler thread. */ + private void settle(Entry entry, Object result, Throwable error) { + List registrations; + synchronized (lock) { + if (entry.settled) { + return; + } + entry.settled = true; + registrations = new ArrayList<>(entry.registrations); + entry.registrations.clear(); + } + for (Cancellation.Registration registration : registrations) { + registration.remove(); + } + Runnable complete = () -> { + if (error != null) { + entry.future.completeExceptionally(error); + } else { + entry.future.complete(result); + } + }; + try { + transport.execute(complete); + } catch (RejectedExecutionException ended) { + complete.run(); + } + } + + /** Queues one event; called with the lock held. */ + private void emit(Route route, long sequence, Object event) { + boolean gap = sequence != route.lastSequence + 1; + route.lastSequence = sequence; + route.pending.add(new Host.Event(route.id, sequence, gap, event)); + if (route.draining) { + return; + } + route.draining = true; + try { + transport.execute(() -> run(route)); + } catch (RejectedExecutionException ended) { + route.draining = false; + route.pending.clear(); + } + } + + /** Hands a subscription's events to its listener one at a time. */ + private void run(Route route) { + while (true) { + Host.Event event; + synchronized (lock) { + event = route.live ? route.pending.poll() : null; + if (event == null) { + route.draining = false; + route.pending.clear(); + return; + } + } + try { + if (route.listener != null) { + route.listener.onEvent(event); + } + } catch (Throwable error) { + transport.log("A subscription listener failed:", error); + } + } + } + + private boolean open() { + synchronized (lock) { + return !closed && transport.ready(); + } + } + + private static PluginSdkError notReady() { + return new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + + private static HostError unavailable(String method, String message) { + return new HostError("plugin.host.unavailable", message, Protocol.METHOD_NOT_FOUND, null, method); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java new file mode 100644 index 0000000..3730a02 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -0,0 +1,126 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The host refused or failed a request this backend sent. {@link #code()} is + * the stable {@code error.data.code}, such as {@code plugin.host.contextExpired}; + * {@link #rpcCode()} the JSON-RPC number; {@link #details()} the object a + * host may add, such as {@code { option }} or + * {@code { retryAfterMilliseconds }}. + */ +public final class HostError extends PluginSdkError { + private static final long serialVersionUID = 1L; + + /** + * Stable host failure codes and their JSON-RPC numbers, including the + * {@code plugin.function.*} codes of cross-plugin calls. A later host adds + * codes after the highest number here. + */ + public static final Map CODES; + private static final Map BY_RPC_CODE; + + static { + Map codes = new LinkedHashMap<>(); + codes.put("plugin.host.unavailable", -32601); + codes.put("plugin.host.invalidParams", -32602); + codes.put("plugin.host.failed", -32603); + codes.put("plugin.host.cancelled", -32800); + codes.put("plugin.host.permissionDenied", -32010); + codes.put("plugin.host.contextExpired", -32011); + codes.put("plugin.host.authorityUnsupported", -32012); + codes.put("plugin.host.versionConflict", -32013); + codes.put("plugin.host.limitExceeded", -32014); + codes.put("plugin.host.timeout", -32015); + codes.put("plugin.host.notFound", -32016); + codes.put("plugin.host.readOnly", -32017); + codes.put("plugin.host.unsupportedOption", -32018); + codes.put("plugin.host.preconditionFailed", -32019); + codes.put("plugin.host.busy", -32020); + codes.put("plugin.host.rateLimited", -32021); + codes.put("plugin.host.languageServerUnavailable", -32022); + codes.put("plugin.host.languageServerError", -32023); + codes.put("plugin.host.methodNotDeclared", -32024); + codes.put("plugin.host.toolUnresolved", -32025); + codes.put("plugin.host.foreignContribution", -32026); + codes.put("plugin.function.notDeclared", -32027); + codes.put("plugin.function.notExported", -32028); + codes.put("plugin.function.providerDisabled", -32029); + codes.put("plugin.function.versionMismatch", -32030); + codes.put("plugin.function.callCycle", -32065); + codes.put("plugin.function.depthExceeded", -32066); + codes.put("plugin.function.tooManyCalls", -32067); + codes.put("plugin.function.payloadTooLarge", -32068); + codes.put("plugin.function.providerUnavailable", -32069); + codes.put("plugin.function.failed", -32070); + codes.put("plugin.function.invalidResult", -32071); + CODES = Collections.unmodifiableMap(codes); + Map byNumber = new HashMap<>(); + for (Map.Entry entry : codes.entrySet()) { + byNumber.put(entry.getValue(), entry.getKey()); + } + BY_RPC_CODE = Collections.unmodifiableMap(byNumber); + } + + private final transient Map details; + private final String method; + + public HostError(String code, String message, Integer rpcCode, Map details, String method) { + super(code, message, rpcCode); + this.details = details == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(details)); + this.method = method; + } + + /** The failure's {@code error.data.details}, or null when the host sent none. */ + public Map details() { + return details; + } + + /** The request that failed. */ + public String method() { + return method; + } + + /** + * For {@code plugin.function.failed}, the provider's own + * {@code error.data.code} (from {@code details.pluginErrorCode}); null for + * any other failure or when the provider named none. + */ + public String pluginErrorCode() { + if (!"plugin.function.failed".equals(code()) || details == null) { + return null; + } + Object pluginErrorCode = details.get("pluginErrorCode"); + return pluginErrorCode instanceof String ? (String) pluginErrorCode : null; + } + + /** + * The failure for a JSON-RPC error answer. A host method without a known + * code is a host failure: a number names one code, and an unknown number + * is {@code plugin.host.failed}. + */ + static HostError fromResponse(String method, Map error) { + Object data = error.get("data"); + Map fields = data instanceof Map ? Json.object(data) : Collections.emptyMap(); + Object rpcCode = error.get("code"); + Integer number = rpcCode instanceof Number && ((Number) rpcCode).doubleValue() == ((Number) rpcCode).intValue() + ? ((Number) rpcCode).intValue() + : null; + String code = Json.string(fields, "code"); + if (code == null) { + if (method.startsWith(Protocol.HOST_PREFIX)) { + String known = number == null ? null : BY_RPC_CODE.get(number); + code = known == null ? "plugin.host.failed" : known; + } else { + code = "sdk.host.error"; + } + } + Object details = fields.get("details"); + String text = Json.string(error, "message"); + return new HostError(code, text == null ? method + " failed." : text, number, + details instanceof Map ? Json.object(details) : null, method); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java new file mode 100644 index 0000000..64ff3f5 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java @@ -0,0 +1,426 @@ +package io.github.litheidea.plugin.sdk; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Minimal JSON reader and writer for protocol messages and stored state. + * + *

The SDK carries its own codec so that a plugin can shade it next to any + * JSON library without version conflicts. Values map to plain Java types: + * objects to {@code Map} (insertion-ordered), arrays to + * {@code List}, strings to {@code String}, booleans to + * {@code Boolean}, {@code null} to {@code null}, integers to {@code Long} (or + * {@code BigInteger} beyond its range), and other numbers to {@code Double}. + */ +public final class Json { + /** Deeper input is refused instead of overflowing the reader's stack. */ + private static final int MAX_DEPTH = 512; + + private Json() {} + + /** A value that is not JSON, or one JSON cannot represent. */ + public static final class JsonException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public JsonException(String message) { + super(message); + } + } + + /** Parses one JSON document; trailing content other than whitespace is an error. */ + public static Object parse(String text) { + Reader reader = new Reader(text); + reader.skipWhitespace(); + Object value = reader.value(0); + reader.skipWhitespace(); + if (reader.position != text.length()) { + throw reader.error("Unexpected content after the value"); + } + return value; + } + + /** + * Encodes {@code value}. Maps need string keys; numbers must be finite. + * Arrays of objects and any {@link Collection} encode as JSON arrays. + */ + public static String stringify(Object value) { + StringBuilder output = new StringBuilder(); + write(output, value, 0); + return output.toString(); + } + + /** {@code value} as an object, or an empty map when it is {@code null}. */ + @SuppressWarnings("unchecked") + public static Map object(Object value) { + if (value == null) { + return new LinkedHashMap<>(); + } + if (value instanceof Map) { + return (Map) value; + } + throw new JsonException("Expected a JSON object."); + } + + /** The string at {@code key}, or {@code null} when it is missing or not a string. */ + public static String string(Map object, String key) { + Object value = object.get(key); + return value instanceof String ? (String) value : null; + } + + private static void write(StringBuilder output, Object value, int depth) { + if (depth > MAX_DEPTH) { + throw new JsonException("The value is nested too deeply, or contains itself."); + } + if (value == null) { + output.append("null"); + } else if (value instanceof String || value instanceof Character) { + quote(output, value.toString()); + } else if (value instanceof Boolean) { + output.append(value.toString()); + } else if (value instanceof Double || value instanceof Float) { + output.append(decimal(((Number) value).doubleValue())); + } else if (value instanceof Long || value instanceof Integer || value instanceof Short + || value instanceof Byte || value instanceof BigInteger) { + output.append(value.toString()); + } else if (value instanceof BigDecimal) { + output.append(((BigDecimal) value).toString()); + } else if (value instanceof Map) { + output.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!(entry.getKey() instanceof String)) { + throw new JsonException("Object keys must be strings."); + } + if (!first) { + output.append(','); + } + first = false; + quote(output, (String) entry.getKey()); + output.append(':'); + write(output, entry.getValue(), depth + 1); + } + output.append('}'); + } else if (value instanceof Collection) { + writeArray(output, ((Collection) value).toArray(), depth); + } else if (value instanceof Object[]) { + writeArray(output, (Object[]) value, depth); + } else { + throw new JsonException("A " + value.getClass().getName() + " is not a JSON value."); + } + } + + private static void writeArray(StringBuilder output, Object[] values, int depth) { + output.append('['); + for (int index = 0; index < values.length; index++) { + if (index > 0) { + output.append(','); + } + write(output, values[index], depth + 1); + } + output.append(']'); + } + + private static String decimal(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new JsonException("JSON has no representation for " + value + "."); + } + // Integral values print without a fraction, as JavaScript prints them. + if (value == Math.rint(value) && Math.abs(value) < 1e15) { + return Long.toString((long) value); + } + return Double.toString(value); + } + + private static void quote(StringBuilder output, String text) { + output.append('"'); + for (int index = 0; index < text.length(); index++) { + char character = text.charAt(index); + switch (character) { + case '"': + output.append("\\\""); + break; + case '\\': + output.append("\\\\"); + break; + case '\n': + output.append("\\n"); + break; + case '\r': + output.append("\\r"); + break; + case '\t': + output.append("\\t"); + break; + case '\b': + output.append("\\b"); + break; + case '\f': + output.append("\\f"); + break; + default: + if (character < 0x20 || isLoneSurrogate(text, index)) { + // A lone surrogate has no UTF-8 encoding; escaping it + // keeps the frame valid, as JSON.stringify does. + output.append(String.format("\\u%04x", (int) character)); + } else { + output.append(character); + } + } + } + output.append('"'); + } + + private static boolean isLoneSurrogate(String text, int index) { + char character = text.charAt(index); + if (Character.isHighSurrogate(character)) { + return index + 1 >= text.length() || !Character.isLowSurrogate(text.charAt(index + 1)); + } + if (Character.isLowSurrogate(character)) { + return index == 0 || !Character.isHighSurrogate(text.charAt(index - 1)); + } + return false; + } + + private static final class Reader { + private final String text; + private int position; + + Reader(String text) { + this.text = text; + } + + Object value(int depth) { + if (depth > MAX_DEPTH) { + throw error("The document is nested too deeply"); + } + if (position >= text.length()) { + throw error("Unexpected end of input"); + } + char character = text.charAt(position); + switch (character) { + case '{': + return object(depth); + case '[': + return array(depth); + case '"': + return string(); + case 't': + return literal("true", Boolean.TRUE); + case 'f': + return literal("false", Boolean.FALSE); + case 'n': + return literal("null", null); + default: + if (character == '-' || (character >= '0' && character <= '9')) { + return number(); + } + throw error("Unexpected character"); + } + } + + private Map object(int depth) { + Map result = new LinkedHashMap<>(); + position++; + skipWhitespace(); + if (peek() == '}') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + if (peek() != '"') { + throw error("Expected a property name"); + } + String key = string(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + result.put(key, value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == '}') { + return result; + } + if (next != ',') { + throw error("Expected ',' or '}'"); + } + } + } + + private List array(int depth) { + List result = new ArrayList<>(); + position++; + skipWhitespace(); + if (peek() == ']') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + result.add(value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == ']') { + return result; + } + if (next != ',') { + throw error("Expected ',' or ']'"); + } + } + } + + private String string() { + position++; + StringBuilder result = new StringBuilder(); + for (;;) { + if (position >= text.length()) { + throw error("Unterminated string"); + } + char character = text.charAt(position++); + if (character == '"') { + return result.toString(); + } + if (character < 0x20) { + throw error("Control character in string"); + } + if (character != '\\') { + result.append(character); + continue; + } + if (position >= text.length()) { + throw error("Unterminated escape"); + } + char escape = text.charAt(position++); + switch (escape) { + case '"': + case '\\': + case '/': + result.append(escape); + break; + case 'b': + result.append('\b'); + break; + case 'f': + result.append('\f'); + break; + case 'n': + result.append('\n'); + break; + case 'r': + result.append('\r'); + break; + case 't': + result.append('\t'); + break; + case 'u': + if (position + 4 > text.length()) { + throw error("Incomplete unicode escape"); + } + int code = 0; + for (int index = 0; index < 4; index++) { + int digit = Character.digit(text.charAt(position++), 16); + if (digit < 0) { + throw error("Invalid unicode escape"); + } + code = code * 16 + digit; + } + result.append((char) code); + break; + default: + throw error("Invalid escape"); + } + } + } + + private Object number() { + int start = position; + if (peek() == '-') { + position++; + } + if (peek() == '0') { + position++; + } else if (isDigit(peek())) { + digits(); + } else { + throw error("Invalid number"); + } + boolean integral = true; + if (peek() == '.') { + integral = false; + position++; + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + if (peek() == 'e' || peek() == 'E') { + integral = false; + position++; + if (peek() == '+' || peek() == '-') { + position++; + } + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + String literal = text.substring(start, position); + if (integral) { + BigInteger value = new BigInteger(literal); + return value.bitLength() < 64 ? (Object) value.longValue() : value; + } + return Double.parseDouble(literal); + } + + private void digits() { + while (isDigit(peek())) { + position++; + } + } + + private Object literal(String word, Object value) { + if (!text.startsWith(word, position)) { + throw error("Unexpected literal"); + } + position += word.length(); + return value; + } + + private void expect(char character) { + if (peek() != character) { + throw error("Expected '" + character + "'"); + } + position++; + } + + private char peek() { + return position < text.length() ? text.charAt(position) : '\0'; + } + + void skipWhitespace() { + while (position < text.length()) { + char character = text.charAt(position); + if (character != ' ' && character != '\t' && character != '\n' && character != '\r') { + return; + } + position++; + } + } + + JsonException error(String message) { + return new JsonException(message + " at offset " + position + "."); + } + + private static boolean isDigit(char character) { + return character >= '0' && character <= '9'; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java new file mode 100644 index 0000000..c7e83b3 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java @@ -0,0 +1,38 @@ +package io.github.litheidea.plugin.sdk; + +/** + * A failure a handler reports on purpose. Core ends the call with the stable + * {@code plugin.function.failed} code and forwards {@link #code()} as + * {@code pluginErrorCode}, so the plugin's own UI can tell its failures apart. + * Lithe never branches on it. + * + *

The message is shown to the user as written (Core keeps its first 1024 + * bytes), so it must not contain stack traces or machine paths. + */ +public class PluginError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + + /** + * @param code identifier of at most 64 bytes, such as {@code maven.snapshotLocked} + * @param message user-facing text + */ + public PluginError(String code, String message) { + this(code, message, null); + } + + /** As {@link #PluginError(String, String)}; {@code cause} stays in memory, outside automatic diagnostics. */ + public PluginError(String code, String message, Throwable cause) { + super(message, cause); + if (!Protocol.isPluginErrorCode(code)) { + throw new IllegalArgumentException("Plugin error code \"" + code + + "\" must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes."); + } + this.code = code; + } + + public String code() { + return code; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java new file mode 100644 index 0000000..043ba52 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java @@ -0,0 +1,32 @@ +package io.github.litheidea.plugin.sdk; + +/** + * An SDK usage error raised to the plugin author, or a failure the host + * reported for a request this backend sent. {@link #rpcCode()} carries the + * host's JSON-RPC error code in the latter case. + */ +public class PluginSdkError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + private final Integer rpcCode; + + public PluginSdkError(String code, String message) { + this(code, message, null); + } + + public PluginSdkError(String code, String message, Integer rpcCode) { + super(message); + this.code = code; + this.rpcCode = rpcCode; + } + + public String code() { + return code; + } + + /** The host's JSON-RPC error code, or {@code null} for a local usage error. */ + public Integer rpcCode() { + return rpcCode; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java new file mode 100644 index 0000000..39e9a7a --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java @@ -0,0 +1,629 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Child processes a backend starts for one call. + * + *

Lithe's host offers no process capability, so a + * backend runs its tools itself; this helper makes sure that the call ending, + * cancelling it, or the backend shutting down also ends the tools it started. + * + *

Process trees: on macOS and Linux every tool leads its own process group, + * as in the Node SDK, on every Java version. Java has no API for that, so the + * tool starts through the system {@code perl}, which calls {@code setpgrp} and + * then replaces itself with the tool, keeping its PID. A stop signals the whole + * group, and once the tool exits on its own the members it left behind, such + * as a background worker, are killed too; descendants that leave the group + * with {@code setsid} are out of reach. Windows, and a system without + * {@code perl}, fall back to {@code ProcessHandle} on Java 9 and newer, found + * by reflection so the SDK still loads on Java 8; it reaches only the + * descendants still attached to the tool. Lithe starts every backend inside + * its own process scope ({@code LITHE_PLUGIN_BACKEND_SCOPE}) and ends whatever + * is left of it when the session ends; that remains the final boundary. + */ +public final class Processes { + /** + * Variables Lithe sets on the backend so it can find and end every process + * the backend started, even one that left its parent. A tool always + * inherits them, also when the plugin replaces the environment. + */ + static final String[] HOST_MARKERS = {"LITHE_PROCESS_SCOPE", "LITHE_PLUGIN_BACKEND_SCOPE"}; + + /** Every tool started through {@link #run} that has not exited or been stopped. */ + private static final Set RUNNING = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + private static final ScheduledExecutorService TIMERS = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "lithe-sdk-process-timer"); + thread.setDaemon(true); + return thread; + }); + + private static final ProcessTree TREE = ProcessTree.load(); + + private static final ProcessGroups GROUPS = ProcessGroups.load(); + + private Processes() {} + + /** Options of one {@link #run}; every setter returns this object. */ + public static final class Options { + private Path directory; + private Map environment; + private Cancellation cancellation; + private int maxOutputBytes = 1 << 20; + private long killGraceMillis = 2000; + private Consumer onStdout; + private Consumer onStderr; + private Runnable listenerFailure = () -> {}; + + /** Working directory; defaults to the backend's. */ + public Options directory(Path value) { + directory = value; + return this; + } + + /** Replaces the environment; the host's process markers are carried over regardless. */ + public Options environment(Map value) { + environment = value; + return this; + } + + /** Cancelling it stops the tool and makes {@link #run} throw {@link CancelledException}. */ + public Options cancellation(Cancellation value) { + cancellation = value; + return this; + } + + /** Captured bytes per stream; default 1 MiB. Listeners still see everything. */ + public Options maxOutputBytes(int value) { + maxOutputBytes = value; + return this; + } + + /** Delay between the polite and the forced stop; default 2000. */ + public Options killGraceMillis(long value) { + killGraceMillis = value; + return this; + } + + /** Receives stdout as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStdout(Consumer value) { + onStdout = value; + return this; + } + + /** Receives stderr as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStderr(Consumer value) { + onStderr = value; + return this; + } + + Options listenerFailure(Runnable value) { listenerFailure = value; return this; } + + Cancellation cancellation() { + return cancellation; + } + + Options copy() { + Options copy = new Options(); + copy.directory = directory; + copy.environment = environment; + copy.cancellation = cancellation; + copy.maxOutputBytes = maxOutputBytes; + copy.killGraceMillis = killGraceMillis; + copy.onStdout = onStdout; + copy.onStderr = onStderr; + copy.listenerFailure = listenerFailure; + return copy; + } + } + + /** Exit status and captured output of a tool. */ + public static final class Result { + private final int exitCode; + private final String stdout; + private final String stderr; + private final boolean truncated; + + Result(int exitCode, String stdout, String stderr, boolean truncated) { + this.exitCode = exitCode; + this.stdout = stdout; + this.stderr = stderr; + this.truncated = truncated; + } + + /** The exit code; on POSIX a tool ended by signal N reports 128 + N. */ + public int exitCode() { + return exitCode; + } + + public String stdout() { + return stdout; + } + + public String stderr() { + return stderr; + } + + /** True when either stream exceeded {@code maxOutputBytes}. */ + public boolean truncated() { + return truncated; + } + } + + /** + * Runs {@code command} without a shell and returns its exit status and + * captured output. A non-zero exit returns normally; the caller decides + * what it means for its tool. Cancellation stops the tool and throws + * {@link CancelledException} once it ended. + */ + public static Result run(List command, Options options) throws IOException { + Options settings = options == null ? new Options() : options; + Cancellation cancellation = settings.cancellation; + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + if (command.isEmpty()) { + throw new IllegalArgumentException("A command needs an executable."); + } + ProcessBuilder builder = new ProcessBuilder(new ArrayList<>(command)); + if (settings.directory != null) { + builder.directory(settings.directory.toFile()); + } + if (settings.environment != null) { + Map environment = builder.environment(); + environment.clear(); + environment.putAll(settings.environment); + for (String name : HOST_MARKERS) { + String value = System.getenv(name); + if (value == null) { + environment.remove(name); + } else { + environment.put(name, value); + } + } + } + boolean grouped = GROUPS.available(); + if (grouped) { + builder.command(GROUPS.launcher(command, builder.environment())); + } + Process process = builder.start(); + // Tools get no input; an open pipe would let one wait on it forever. + process.getOutputStream().close(); + Running entry = new Running(process, grouped ? GROUPS.leader(process) : 0); + RUNNING.add(entry); + Capture stdout = new Capture(process.getInputStream(), settings.maxOutputBytes, settings.onStdout, "stdout", settings.listenerFailure); + Capture stderr = new Capture(process.getErrorStream(), settings.maxOutputBytes, settings.onStderr, "stderr", settings.listenerFailure); + Cancellation.Registration registration = cancellation == null + ? () -> {} + : cancellation.onCancel(() -> entry.stop(settings.killGraceMillis)); + int exitCode; + try { + exitCode = waitFor(process, entry); + registration.remove(); + // The tool ended on its own; what it left running, such as a + // background worker, ends with it. A stopped tool stays registered + // until its forced stop, which reaches the same members. + entry.endLeftovers(); + // A descendant out of reach can keep the inherited pipes open after + // the tool exited; the output then ends at the grace period. + stdout.join(settings.killGraceMillis); + stderr.join(settings.killGraceMillis); + } finally { + registration.remove(); + if (!entry.stopping()) { + RUNNING.remove(entry); + } + } + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + String errors = stderr.text(); + if (grouped && exitCode == ProcessGroups.EXEC_FAILED && errors.startsWith(ProcessGroups.EXEC_FAILURE)) { + // The launcher could not start the tool; report it as ProcessBuilder would. + throw new IOException("Cannot run program \"" + command.get(0) + "\": " + + errors.substring(ProcessGroups.EXEC_FAILURE.length()).trim()); + } + return new Result(exitCode, stdout.text(), errors, stdout.truncated() || stderr.truncated()); + } + + /** Runs {@code command} with default options. */ + public static Result run(List command) throws IOException { + return run(command, null); + } + + /** + * Forcibly ends every tool still running. The backend calls it on shutdown, + * on {@code exit}, and when the host closes stdin, so no tool outlives the + * session that started it. + */ + public static void killAll() { + for (Running entry : new ArrayList<>(RUNNING)) { + entry.forceStop(); + } + RUNNING.clear(); + } + + /** Number of tools still running or being stopped, for tests and diagnostics. */ + public static int runningCount() { + return RUNNING.size(); + } + + private static int waitFor(Process process, Running entry) { + boolean interrupted = false; + try { + for (;;) { + try { + return process.waitFor(); + } catch (InterruptedException error) { + // The tool still belongs to this call; end it before giving + // the interrupt back to the caller. + interrupted = true; + entry.forceStop(); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** One started tool and its stop state. */ + private static final class Running { + private final Process process; + /** The tool's process group, or 0 when it has none of its own. */ + private final long group; + private final Object lock = new Object(); + private boolean stopping; + private List tree = Collections.emptyList(); + private ScheduledFuture forceTimer; + + Running(Process process, long group) { + this.process = process; + this.group = group; + } + + /** Kills what the tool left after exiting on its own, unless a stop owns that. */ + void endLeftovers() { + synchronized (lock) { + if (stopping) { + return; + } + } + if (group > 0) { + // While any member lives the group ID cannot be reused, so this + // reaches only what this tool started; an empty group is ignored. + GROUPS.signal(group, true); + } else { + // Windows keeps the parent link of an exited tool, so its + // descendants are still found there. + TREE.destroy(TREE.descendants(process), true); + } + } + + boolean stopping() { + synchronized (lock) { + return stopping; + } + } + + /** Asks the tree to stop, then forces it after {@code graceMillis}. */ + void stop(long graceMillis) { + synchronized (lock) { + if (stopping) { + return; + } + stopping = true; + if (group > 0) { + GROUPS.signal(group, false); + } else { + // Descendants are listed before the tool is signalled: once + // it exits they are reparented and no longer reachable from it. + tree = TREE.descendants(process); + TREE.destroy(tree, false); + } + // Also covers a tool that has not formed its group yet. + process.destroy(); + forceTimer = TIMERS.schedule(this::forceStop, graceMillis, TimeUnit.MILLISECONDS); + } + } + + void forceStop() { + List known; + synchronized (lock) { + stopping = true; + if (forceTimer != null) { + forceTimer.cancel(false); + } + known = new ArrayList<>(tree); + if (group <= 0) { + known.addAll(TREE.descendants(process)); + } + } + if (group > 0) { + GROUPS.signal(group, true); + } + TREE.destroy(known, true); + process.destroyForcibly(); + RUNNING.remove(this); + } + } + + /** Reads one output stream on its own thread, keeping at most {@code limit} bytes. */ + private static final class Capture { + private final ByteArrayOutputStream kept = new ByteArrayOutputStream(); + private final InputStream input; + private final int limit; + private final Consumer listener; + private final Runnable listenerFailure; + private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); + private final Thread thread; + private volatile boolean truncated; + + Capture(InputStream input, int limit, Consumer listener, String name, Runnable listenerFailure) { + this.listenerFailure = listenerFailure; + this.input = input; + this.limit = limit; + this.listener = listener; + thread = new Thread(this::read, "lithe-sdk-" + name); + thread.setDaemon(true); + thread.start(); + } + + private void read() { + byte[] chunk = new byte[8192]; + // Holds a multi-byte character split across reads until it is whole. + ByteBuffer pending = ByteBuffer.allocate(chunk.length + 8); + try { + int count; + while ((count = input.read(chunk)) >= 0) { + synchronized (kept) { + int room = Math.max(0, limit - kept.size()); + kept.write(chunk, 0, Math.min(room, count)); + if (count > room) { + truncated = true; + } + } + if (listener != null) { + pending.put(chunk, 0, count); + pending.flip(); + deliver(pending, false); + pending.compact(); + } + } + if (listener != null) { + pending.flip(); + deliver(pending, true); + } + } catch (IOException error) { + // The stream was closed after the grace period; what was read is kept. + } + } + + private void deliver(ByteBuffer bytes, boolean end) { + CharBuffer characters = CharBuffer.allocate(bytes.remaining() + 1); + decoder.decode(bytes, characters, end); + if (end) { + decoder.flush(characters); + } + characters.flip(); + if (characters.hasRemaining()) { + try { + listener.accept(characters.toString()); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + } + + void join(long millis) { + try { + thread.join(Math.max(1, millis)); + if (thread.isAlive()) { + input.close(); + thread.join(millis); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } catch (IOException error) { + // Closing an output pipe that already failed changes nothing. + } + } + + String text() { + synchronized (kept) { + return new String(kept.toByteArray(), StandardCharsets.UTF_8); + } + } + + boolean truncated() { + return truncated; + } + } + + /** + * A process group per tool on macOS and Linux. The launcher is + * {@code perl -e SCRIPT -- command...}: it calls + * {@code setpgrp(0, 0)} and replaces itself with the tool, so the PID Java + * reports is the tool's and also its group ID. {@code PERL5OPT} would make + * perl load modules before the script runs, so it is withheld from perl and + * handed back to the tool. Signals go through {@code /bin/kill}, which + * Java 8 needs for a negative PID. + */ + private static final class ProcessGroups { + /** Exit code and stderr prefix of a launcher that could not start the tool. */ + static final int EXEC_FAILED = 127; + static final String EXEC_FAILURE = "lithe-sdk-exec-failed: "; + + private static final String SCRIPT = "my $has = shift; my $opt = shift;" + + " $ENV{PERL5OPT} = $opt if $has;" + + " setpgrp(0, 0);" + + " exec { $ARGV[0] } @ARGV;" + + " print STDERR '" + EXEC_FAILURE + "', \"$!\\n\"; exit " + EXEC_FAILED + ";"; + + /** A signal that has not run after this long is abandoned; the host scope remains. */ + private static final long SIGNAL_TIMEOUT_MILLIS = 2000; + + private final String perl; + private final String kill; + private final Method pid; + + private ProcessGroups(String perl, String kill, Method pid) { + this.perl = perl; + this.kill = kill; + this.pid = pid; + } + + static ProcessGroups load() { + if (System.getProperty("os.name", "").startsWith("Windows")) { + return new ProcessGroups(null, null, null); + } + Method pid; + try { + pid = Process.class.getMethod("pid"); + } catch (NoSuchMethodException error) { + // Java 8 keeps the PID in a private field of UNIXProcess. + pid = null; + } + return new ProcessGroups(executable("/usr/bin/perl", "/bin/perl"), + executable("/bin/kill", "/usr/bin/kill"), pid); + } + + private static String executable(String... candidates) { + for (String candidate : candidates) { + if (new File(candidate).canExecute()) { + return candidate; + } + } + return null; + } + + boolean available() { + return perl != null && kill != null; + } + + List launcher(List command, Map environment) { + String option = environment.remove("PERL5OPT"); + List launcher = new ArrayList<>(Arrays.asList(perl, "-e", SCRIPT, "--", + option == null ? "0" : "1", option == null ? "" : option)); + launcher.addAll(command); + return launcher; + } + + /** The tool's PID, which is its group ID; 0 when it cannot be read. */ + long leader(Process process) { + try { + if (pid != null) { + return ((Number) pid.invoke(process)).longValue(); + } + Field field = process.getClass().getDeclaredField("pid"); + field.setAccessible(true); + return field.getInt(process); + } catch (ReflectiveOperationException | RuntimeException error) { + return 0; + } + } + + /** Signals every member of {@code group}; an empty group is ignored. */ + void signal(long group, boolean forcibly) { + ProcessBuilder builder = new ProcessBuilder(kill, "-s", forcibly ? "KILL" : "TERM", "--", "-" + group); + File discard = new File("/dev/null"); + builder.redirectOutput(discard).redirectError(discard); + try { + Process signal = builder.start(); + signal.getOutputStream().close(); + if (!signal.waitFor(SIGNAL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { + signal.destroyForcibly(); + } + } catch (IOException error) { + // The host's process scope ends what this could not reach. + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + } + } + + /** + * {@code ProcessHandle} through reflection: present from Java 9, absent on + * Java 8, where only the direct child can be stopped. + */ + private static final class ProcessTree { + private final Method descendants; + private final Method destroy; + private final Method destroyForcibly; + + private ProcessTree(Method descendants, Method destroy, Method destroyForcibly) { + this.descendants = descendants; + this.destroy = destroy; + this.destroyForcibly = destroyForcibly; + } + + static ProcessTree load() { + try { + Class handle = Class.forName("java.lang.ProcessHandle"); + return new ProcessTree( + Process.class.getMethod("descendants"), + handle.getMethod("destroy"), + handle.getMethod("destroyForcibly")); + } catch (ReflectiveOperationException error) { + return new ProcessTree(null, null, null); + } + } + + List descendants(Process process) { + if (descendants == null) { + return Collections.emptyList(); + } + try { + @SuppressWarnings("unchecked") + Stream stream = (Stream) descendants.invoke(process); + return stream.collect(Collectors.toList()); + } catch (ReflectiveOperationException | RuntimeException error) { + return Collections.emptyList(); + } + } + + void destroy(List handles, boolean forcibly) { + Method method = forcibly ? destroyForcibly : destroy; + if (method == null) { + return; + } + for (Object handle : handles) { + try { + method.invoke(handle); + } catch (ReflectiveOperationException | RuntimeException error) { + // The process already exited, or the platform refused; the + // host's process scope ends what is left. + } + } + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java new file mode 100644 index 0000000..0d98743 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -0,0 +1,234 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Wire constants and validation shared with Lithe's Rust Core + * ({@code rust/crates/plugin-rpc/src/} in the Lithe + * repository) and the Node.js + * SDK. The SDK checks the same rules locally so a plugin author sees a mistake + * when registering a handler instead of as a refused session at runtime. + */ +public final class Protocol { + /** The version of each protocol this SDK speaks; the host offers it in {@code initialize}. */ + public static final int FUNCTIONS_VERSION = 0; + public static final int BUILD_VERSION = 0; + public static final int LOGGING_VERSION = 0; + public static final int KEYMAP_IMPORT_VERSION = 0; + + public static final String INITIALIZE = "initialize"; + public static final String INITIALIZED = "initialized"; + public static final String SHUTDOWN = "shutdown"; + public static final String EXIT = "exit"; + public static final String CANCEL_REQUEST = "$/cancelRequest"; + public static final String FUNCTION_INVOKE = "lithe/function/invoke"; + public static final String FUNCTION_REGISTER = "lithe/function/register"; + public static final String FUNCTION_UNREGISTER = "lithe/function/unregister"; + public static final String FUNCTION_PROGRESS = "lithe/function/progress"; + public static final String BUILD_MODEL = "lithe/build/model"; + public static final String BUILD_DEPENDENCIES = "lithe/build/dependencies"; + public static final String BUILD_EXECUTE = "lithe/build/execute"; + public static final String BUILD_TEST = "lithe/build/test"; + public static final String BUILD_DISCOVER_TESTS = "lithe/build/discoverTests"; + public static final String BUILD_PREPARE_DEBUG = "lithe/build/prepareDebug"; + public static final String BUILD_PREPARE_RUN = "lithe/build/prepareRun"; + public static final String BUILD_PROGRESS = "lithe/build/progress"; + + /** + * Backend-to-host requests. The host may add methods; + * {@link Host#request} sends any {@code lithe/host/*} method, and + * {@code getCapabilities} says which ones the session may call. + */ + public static final String HOST_TERMINAL_CREATE = "lithe/host/terminal/create"; + public static final String HOST_TERMINAL_SHOW = "lithe/host/terminal/show"; + public static final String HOST_TERMINAL_CLOSE = "lithe/host/terminal/close"; + public static final String HOST_TERMINAL_REOPEN = "lithe/host/terminal/reopen"; + public static final String HOST_TERMINAL_DISPOSE = "lithe/host/terminal/dispose"; + public static final String HOST_TERMINAL_ON_EXIT = "lithe/host/terminal/onExit"; + public static final String HOST_PREFIX = "lithe/host/"; + public static final String HOST_CREDENTIALS_GET = "lithe/host/credentials/get"; + public static final String HOST_CREDENTIALS_SET = "lithe/host/credentials/set"; + public static final String HOST_CREDENTIALS_DELETE = "lithe/host/credentials/delete"; + public static final String HOST_GET_CAPABILITIES = "lithe/host/getCapabilities"; + public static final String HOST_SUBSCRIPTIONS_DISPOSE = "lithe/host/subscriptions/dispose"; + public static final String HOST_WORKSPACE_LIST_CONTEXTS = "lithe/host/workspace/listContexts"; + public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; + public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; + public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; + public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; + public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; + public static final String HOST_WORKSPACE_WATCH = "lithe/host/workspace/watch"; + public static final String HOST_WORKSPACE_FIND_FILES = "lithe/host/workspace/findFiles"; + public static final String HOST_WORKSPACE_FIND_TEXT = "lithe/host/workspace/findText"; + public static final String HOST_DOCUMENTS_LIST = "lithe/host/documents/list"; + public static final String HOST_DOCUMENTS_GET_SNAPSHOT = "lithe/host/documents/getSnapshot"; + public static final String HOST_EDITOR_REGISTER_ACTIONS = "lithe/host/editor/registerActions"; + public static final String HOST_EDITOR_GET_ACTIVE = "lithe/host/editor/getActive"; + public static final String HOST_EDITOR_GET_SELECTIONS = "lithe/host/editor/getSelections"; + public static final String HOST_EDITOR_APPLY_EDITS = "lithe/host/editor/applyEdits"; + public static final String HOST_EDITOR_REPLACE_SELECTIONS = "lithe/host/editor/replaceSelections"; + public static final String HOST_EDITOR_INSERT_TEXT = "lithe/host/editor/insertText"; + public static final String HOST_EDITOR_OPEN = "lithe/host/editor/open"; + public static final String HOST_EDITOR_REVEAL = "lithe/host/editor/reveal"; + public static final String HOST_PREVIEW_OPEN_HTML = "lithe/host/preview/openHTML"; + public static final String HOST_BROWSER_OPEN_EXTERNAL = "lithe/host/browser/openExternal"; + public static final String HOST_WINDOW_SHOW_INFORMATION = "lithe/host/window/showInformation"; + public static final String HOST_WINDOW_SHOW_WARNING = "lithe/host/window/showWarning"; + public static final String HOST_WINDOW_SHOW_ERROR = "lithe/host/window/showError"; + + /** Cross-plugin calls Core relays. */ + public static final String HOST_FUNCTIONS_PROVIDERS = "lithe/host/functions/providers"; + public static final String HOST_FUNCTIONS_INVOKE = "lithe/host/functions/invoke"; + + /** Host-to-backend notifications. */ + public static final String HOST_DID_CHANGE_CONTEXTS = "lithe/host/workspace/didChangeContexts"; + public static final String HOST_SUBSCRIPTION_NOTIFY = "lithe/host/subscriptions/notify"; + public static final String HOST_COMMAND_DID_RUN = "lithe/host/commands/didRun"; + + /** JSON-RPC and LSP error codes the SDK answers with. */ + public static final int PARSE_ERROR = -32700; + public static final int INVALID_REQUEST = -32600; + public static final int METHOD_NOT_FOUND = -32601; + public static final int INVALID_PARAMS = -32602; + public static final int INTERNAL_ERROR = -32603; + public static final int SERVER_NOT_INITIALIZED = -32002; + public static final int REQUEST_FAILED = -32000; + public static final int REQUEST_CANCELLED = -32800; + + public static final int MAX_FUNCTIONS = 256; + public static final int MAX_FUNCTION_ID_BYTES = 128; + public static final int MAX_PLUGIN_ERROR_CODE_BYTES = 64; + public static final int MAX_MESSAGE_BYTES = 1024; + public static final int MAX_RESULT_BYTES = 1 << 20; + public static final int MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024; + public static final int MAX_BUILD_MESSAGE_BYTES = 4096; + public static final int MAX_BUILD_OUTPUT_BYTES = 65536; + /** Unanswered host requests Core allows a session; the SDK queues the rest. */ + public static final int MAX_PENDING_HOST_REQUESTS = 16; + public static final int MAX_CREDENTIAL_SECRET_BYTES = 16 * 1024; + /** Timeout Core gives a relayed call that names none. */ + public static final int RELAY_DEFAULT_TIMEOUT_MILLISECONDS = 60000; + /** Longest timeout of a relayed call; the SDK sends a longer one unchanged and leaves the cap to Core. */ + public static final int RELAY_MAX_TIMEOUT_MILLISECONDS = 600000; + public static final int MAX_PARENT_OPERATION_ID_BYTES = 128; + + static boolean buildProgress(String method) { + return BUILD_EXECUTE.equals(method) || BUILD_TEST.equals(method) || BUILD_PREPARE_RUN.equals(method) || BUILD_PREPARE_DEBUG.equals(method); + } + + private static final Pattern FUNCTION_SEGMENT = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern PLUGIN_ERROR_CODE = Pattern.compile("[A-Za-z][A-Za-z0-9._-]*"); + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}"); + private static final Pattern COMMAND_ID = Pattern.compile("[a-z0-9.-]{1,128}"); + private static final long MAX_SAFE_INTEGER = 9007199254740991L; + + private Protocol() {} + + /** Dot-separated lowerCamelCase segments, for example {@code snapshot.refresh}. */ + public static boolean isFunctionId(String value) { + if (value == null || value.isEmpty() || utf8Length(value) > MAX_FUNCTION_ID_BYTES) { + return false; + } + for (String segment : value.split("\\.", -1)) { + if (!FUNCTION_SEGMENT.matcher(segment).matches()) { + return false; + } + } + return true; + } + + /** The plugin error code alphabet Core forwards as {@code pluginErrorCode}. */ + public static boolean isPluginErrorCode(String value) { + return value != null + && utf8Length(value) <= MAX_PLUGIN_ERROR_CODE_BYTES + && PLUGIN_ERROR_CODE.matcher(value).matches(); + } + + /** + * The key alphabet of host services: 1-128 ASCII letters, digits, + * {@code .}, {@code _}, {@code :}, or {@code -}. Credential keys, context + * IDs, and subscription IDs use it. + */ + public static boolean isCredentialKey(String value) { + return value != null && KEY.matcher(value).matches(); + } + + /** {@code { contextID, generation }}, exactly, naming one generation of one workspace context. */ + public static boolean isContextReference(Object value) { + if (!(value instanceof Map) || ((Map) value).size() != 2) { + return false; + } + Map reference = (Map) value; + Object id = reference.get("contextID"); + return id instanceof String && isCredentialKey((String) id) && isGeneration(reference.get("generation")); + } + + /** A {@code parentOperationID}: a string of 1-128 UTF-8 bytes. */ + static boolean isParentOperationId(Object value) { + if (!(value instanceof String)) { + return false; + } + int bytes = utf8Length((String) value); + return bytes >= 1 && bytes <= MAX_PARENT_OPERATION_ID_BYTES; + } + + /** A command ID from the plugin's manifest: 1-128 of {@code [a-z0-9.-]}. */ + public static boolean isCommandId(String value) { + return value != null && COMMAND_ID.matcher(value).matches(); + } + + /** A positive integer JSON can carry exactly. */ + static boolean isGeneration(Object value) { + if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { + long number = ((Number) value).longValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER; + } + if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER && number == Math.rint(number); + } + return false; + } + + /** Cuts {@code value} to {@link #MAX_MESSAGE_BYTES} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value) { + return boundedText(value, MAX_MESSAGE_BYTES); + } + + /** Cuts {@code value} to {@code limit} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value, int limit) { + String text = value == null ? "" : value; + int used = 0; + int index = 0; + while (index < text.length()) { + int codePoint = text.codePointAt(index); + int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4; + if (used + size > limit) { + return text.substring(0, index); + } + used += size; + index += Character.charCount(codePoint); + } + return text; + } + + /** + * Methods reserved for the SDK. A plugin cannot install its own handler for + * these, or send them to the host: the lifecycle belongs to the host's + * session management, and {@code lithe/*} belongs to Lithe's typed contracts. + */ + public static boolean isReservedMethod(String method) { + return method.equals(INITIALIZE) + || method.equals(INITIALIZED) + || method.equals(SHUTDOWN) + || method.equals(EXIT) + || method.equals(CANCEL_REQUEST) + || method.startsWith("lithe/"); + } + + static int utf8Length(String value) { + return value.getBytes(StandardCharsets.UTF_8).length; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java new file mode 100644 index 0000000..24761e2 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java @@ -0,0 +1,198 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.CodeSource; +import java.security.SecureRandom; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Durable plugin state, in a directory the host gives the backend. + * + *

The host passes writable directories through the {@code ${stateDir}} and + * {@code ${workspaceStateDir}} launch variables; the installed package and the + * host's installation are read-only, because signatures and delta updates are + * computed over their exact bytes. Values are JSON; each key is one file + * replaced atomically, so a crash leaves either the old or the new value, + * never half of one. The envelope matches the Node.js SDK's, so either SDK + * reads what the other wrote. + */ +public final class StateStore { + /** Version of the envelope each value is stored in. */ + private static final int STORE_FORMAT = 1; + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,127}"); + private static final SecureRandom RANDOM = new SecureRandom(); + + private final Path root; + + private StateStore(Path root) { + this.root = root; + } + + /** + * Opens a store in {@code directory}, creating the directory. Refuses a + * directory inside the plugin package, found as the nearest directory with + * a {@code plugin.json} above the JAR this class was loaded from. + * + * @param directory absolute path, normally the value of {@code ${workspaceStateDir}} + */ + public static StateStore open(Path directory) throws IOException { + return open(directory, findPackageDirectory()); + } + + /** + * Opens a store in {@code directory}, refusing one inside + * {@code packageDirectory}; null skips that check. + */ + public static StateStore open(Path directory, Path packageDirectory) throws IOException { + if (directory == null || !directory.isAbsolute()) { + throw new PluginSdkError("sdk.state.invalidDirectory", + "The state directory must be an absolute path passed by the host."); + } + // Checked before creating anything, so a refused path leaves the package untouched. + Path resolved = canonical(directory); + if (packageDirectory != null && resolved.startsWith(canonical(packageDirectory))) { + throw new PluginSdkError("sdk.state.readOnlyPackage", + "The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}."); + } + Files.createDirectories(resolved); + return new StateStore(resolved); + } + + /** The resolved directory, for a backend that keeps its own files next to the store. */ + public Path directory() { + return root; + } + + /** The stored value, or {@code fallback} when the key is missing or unreadable. */ + public Object read(String key, Object fallback) { + Path path = path(key); + if (!Files.isRegularFile(path)) { + return fallback; + } + try { + Object envelope = Json.parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + if (!(envelope instanceof Map)) { + return fallback; + } + Map fields = (Map) envelope; + Object format = fields.get("litheStateStore"); + if (!(format instanceof Number) || ((Number) format).doubleValue() != STORE_FORMAT + || !fields.containsKey("value")) { + return fallback; + } + return fields.get("value"); + } catch (IOException | RuntimeException error) { + return fallback; + } + } + + /** Stores {@code value}, which must be JSON-encodable, replacing the previous one. */ + public void write(String key, Object value) throws IOException { + Path path = path(key); + Map envelope = new LinkedHashMap<>(); + envelope.put("litheStateStore", STORE_FORMAT); + envelope.put("value", value); + byte[] body; + try { + body = Json.stringify(envelope).getBytes(StandardCharsets.UTF_8); + } catch (Json.JsonException error) { + // Refused before touching the file, so the stored value stays. + throw new PluginSdkError("sdk.state.invalidValue", "The value for " + key + " is not JSON-encodable."); + } + Path temporary = root.resolve(key + ".json." + Long.toHexString(RANDOM.nextLong()) + ".tmp"); + try { + createPrivate(temporary); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = ByteBuffer.wrap(body); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + try { + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException error) { + Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException | RuntimeException error) { + Files.deleteIfExists(temporary); + throw error; + } + } + + /** Removes the key; a missing key is not an error. */ + public void delete(String key) throws IOException { + Files.deleteIfExists(path(key)); + } + + private Path path(String key) { + if (key == null || !KEY.matcher(key).matches() || key.endsWith(".tmp")) { + throw new PluginSdkError("sdk.state.invalidKey", "State key \"" + key + + "\" must be 1-128 letters, digits, \".\", \"_\" or \"-\", start with a letter or digit, and not end with \".tmp\"."); + } + return root.resolve(key + ".json"); + } + + /** Creates an empty file only the user can read, where the platform supports it. */ + private static void createPrivate(Path file) throws IOException { + try { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException error) { + Files.createFile(file); + } catch (FileAlreadyExistsException error) { + throw new IOException("A temporary state file already exists: " + file.getFileName(), error); + } + } + + /** Resolves symbolic links of the longest existing prefix of {@code path}. */ + static Path canonical(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + Path existing = absolute; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing == null) { + return absolute; + } + return existing.toRealPath().resolve(existing.relativize(absolute)); + } + + /** The nearest directory with a {@code plugin.json} above the JAR this class came from. */ + static Path findPackageDirectory() { + try { + CodeSource source = StateStore.class.getProtectionDomain().getCodeSource(); + URL location = source == null ? null : source.getLocation(); + if (location == null) { + return null; + } + Path current = Paths.get(location.toURI()).toAbsolutePath(); + if (Files.isRegularFile(current)) { + current = current.getParent(); + } + while (current != null) { + if (Files.isRegularFile(current.resolve("plugin.json"))) { + return current; + } + current = current.getParent(); + } + return null; + } catch (URISyntaxException | RuntimeException error) { + return null; + } + } +}