@opentide/lsp-client 0.0.0-stage → 1.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.d.ts +211 -0
- package/dist/index.js +441 -0
- package/package.json +35 -4
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) opentide contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* opentide language client.
|
|
3
|
+
*
|
|
4
|
+
* The factory is `createOpentideClient`. There is no `createOtideClient`.
|
|
5
|
+
*
|
|
6
|
+
* Three transports reach the same engine:
|
|
7
|
+
*
|
|
8
|
+
* - `stdio` runs `opentide-lsp --stdio` once and speaks JSON-RPC to it
|
|
9
|
+
* (`opentide/analyze`, `opentide/highlight`).
|
|
10
|
+
* - `worker` speaks the same JSON-RPC to the same server running in a Web
|
|
11
|
+
* Worker (`worker`: `serveLanguageServer` from `@opentide/lsp-worker`, over
|
|
12
|
+
* `opentide-wasm`), one message per `postMessage`. Given a loaded `module`
|
|
13
|
+
* instead, it calls `highlight()` and `legend()` in this thread and does not
|
|
14
|
+
* analyze.
|
|
15
|
+
* - `wasi` runs the `wasm32-wasip1` `opentide-lsp` CLI under `node:wasi`, one
|
|
16
|
+
* `analyze` or `highlight` per call. Under Node 22, run the process with
|
|
17
|
+
* `--no-turbo-fast-api-calls`: `node:wasi`'s fast calls (`path_open`,
|
|
18
|
+
* `fd_write`) can start a garbage collection inside the call, which
|
|
19
|
+
* segfaults the process once the WASI instances hold enough memory.
|
|
20
|
+
*
|
|
21
|
+
* A transport that cannot answer rejects. It never returns an empty result in
|
|
22
|
+
* place of one.
|
|
23
|
+
*/
|
|
24
|
+
export type Transport = "stdio" | "worker" | "wasi";
|
|
25
|
+
/** A language the server handles: its LSP language id and file globs. */
|
|
26
|
+
export interface OpentideLanguage {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
patterns: string[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Every language the server handles. `kql` is Microsoft KQL; `kuery` is
|
|
33
|
+
* Kibana KQL (Elastic `language: kuery`). Tide YAML is scoped to `objects/`,
|
|
34
|
+
* where the server owns diagnostics (turn yamlls off there).
|
|
35
|
+
*
|
|
36
|
+
* `cql` is the CrowdStrike Query Language (Falcon LogScale, Next-Gen SIEM).
|
|
37
|
+
* Cassandra's CQL uses the `.cql` extension too: where a workspace holds
|
|
38
|
+
* Cassandra scripts, leave out the `.cql` file pattern and match `cql` by
|
|
39
|
+
* language id alone.
|
|
40
|
+
*
|
|
41
|
+
* `exabeam` is the Exabeam Query Language (New-Scale SIEM), which Exabeam's
|
|
42
|
+
* guides call "EQL"; `eql` stays Elastic's. A `.exabeam` file is a search.
|
|
43
|
+
*
|
|
44
|
+
* `opentide-config` is configuration TOML (`.opentide/configurations/`). The
|
|
45
|
+
* host that runs the server checks it (`opentide lsp start`); `opentide-lsp`
|
|
46
|
+
* on its own reports nothing for it, so `analyze` and `highlight` refuse it.
|
|
47
|
+
* Keep the editor's TOML grammar for it.
|
|
48
|
+
*/
|
|
49
|
+
export declare const LANGUAGES: readonly OpentideLanguage[];
|
|
50
|
+
/** A document filter by language id. */
|
|
51
|
+
export interface LanguageFilter {
|
|
52
|
+
language: string;
|
|
53
|
+
}
|
|
54
|
+
/** A document filter by file pattern, for `file:` URIs only. */
|
|
55
|
+
export interface FileFilter {
|
|
56
|
+
scheme: "file";
|
|
57
|
+
pattern: string;
|
|
58
|
+
}
|
|
59
|
+
/** A document filter by file pattern, for a URI of any scheme. */
|
|
60
|
+
export interface PatternFilter {
|
|
61
|
+
pattern: string;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* LSP document selector for every language, by language id and by file
|
|
65
|
+
* pattern, so a file is served even when no extension registered its id
|
|
66
|
+
* (for example `.esql` when Elastic's own extension owns the id). Its
|
|
67
|
+
* patterns match `file:` URIs only: use it on the desktop.
|
|
68
|
+
*
|
|
69
|
+
* A plain array, so it is vscode-languageclient's `documentSelector` as it
|
|
70
|
+
* is; do not change it in place.
|
|
71
|
+
*/
|
|
72
|
+
export declare const DOCUMENT_SELECTOR: Array<LanguageFilter | FileFilter>;
|
|
73
|
+
/**
|
|
74
|
+
* The same selector with no scheme, for web hosts (vscode.dev, github.dev),
|
|
75
|
+
* where documents are `vscode-vfs:`, `vscode-remote:` or other virtual URIs,
|
|
76
|
+
* not `file:` ones. A pattern without a scheme matches the URI's path
|
|
77
|
+
* whatever its scheme. A plain array, like `DOCUMENT_SELECTOR`.
|
|
78
|
+
*/
|
|
79
|
+
export declare const WEB_DOCUMENT_SELECTOR: Array<LanguageFilter | PatternFilter>;
|
|
80
|
+
/** The `opentide-wasm` exports the `worker` transport calls when given a `module`. */
|
|
81
|
+
export interface HighlightModule {
|
|
82
|
+
highlight(language_id: string, bytes: Uint8Array): unknown;
|
|
83
|
+
legend(): unknown;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The client's end of a channel to a worker serving the language server: a
|
|
87
|
+
* `Worker`, or one port of a `MessageChannel`. Each message is one JSON-RPC
|
|
88
|
+
* message as JSON text.
|
|
89
|
+
*/
|
|
90
|
+
export interface WorkerPort {
|
|
91
|
+
postMessage(message: string): void;
|
|
92
|
+
addEventListener(type: "message", listener: (event: {
|
|
93
|
+
data: unknown;
|
|
94
|
+
}) => void): void;
|
|
95
|
+
start?(): void;
|
|
96
|
+
/** A `MessagePort`'s. */
|
|
97
|
+
close?(): void;
|
|
98
|
+
/** A `Worker`'s. */
|
|
99
|
+
terminate?(): void;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* What a host with no filesystem tells the server about its workspace on
|
|
103
|
+
* `initialize` (`initializationOptions.workspace`), so references resolve and
|
|
104
|
+
* declared datasets apply: whole object documents, objects known by their
|
|
105
|
+
* metadata alone, and the text of `visibility.toml`.
|
|
106
|
+
*/
|
|
107
|
+
export interface SuppliedWorkspace {
|
|
108
|
+
documents?: {
|
|
109
|
+
uri: string;
|
|
110
|
+
text: string;
|
|
111
|
+
}[];
|
|
112
|
+
objects?: {
|
|
113
|
+
uuid: string;
|
|
114
|
+
schema: string;
|
|
115
|
+
name?: string;
|
|
116
|
+
uri?: string;
|
|
117
|
+
}[];
|
|
118
|
+
visibility?: string;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* What changed in a supplied workspace (`opentide/didChangeWorkspace`): documents and objects added or
|
|
122
|
+
* changed, the URIs of files that are gone (`opentide-object:<uuid>` for an object supplied without a
|
|
123
|
+
* `uri`), and `visibility.toml`'s new text, or `null` when it is gone.
|
|
124
|
+
*/
|
|
125
|
+
export interface WorkspaceChange {
|
|
126
|
+
documents?: {
|
|
127
|
+
uri: string;
|
|
128
|
+
text: string;
|
|
129
|
+
}[];
|
|
130
|
+
objects?: {
|
|
131
|
+
uuid: string;
|
|
132
|
+
schema: string;
|
|
133
|
+
name?: string;
|
|
134
|
+
uri?: string;
|
|
135
|
+
}[];
|
|
136
|
+
removed?: string[];
|
|
137
|
+
visibility?: string | null;
|
|
138
|
+
}
|
|
139
|
+
export interface OpentideClientOptions {
|
|
140
|
+
transport: Transport;
|
|
141
|
+
/** stdio: the server binary. Default `opentide-lsp`, found on `PATH`. */
|
|
142
|
+
command?: string;
|
|
143
|
+
/** stdio: arguments. Default `["--stdio"]`. */
|
|
144
|
+
args?: string[];
|
|
145
|
+
/** stdio: workspace root sent on `initialize` (a `file:` URI). */
|
|
146
|
+
rootUri?: string;
|
|
147
|
+
/** stdio and worker: the workspace sent on `initialize`, for a server that cannot read one from disk. */
|
|
148
|
+
workspace?: SuppliedWorkspace;
|
|
149
|
+
/** worker: a worker serving the language server (`serveLanguageServer` in `@opentide/lsp-worker`). */
|
|
150
|
+
worker?: WorkerPort;
|
|
151
|
+
/** worker, without `worker`: the loaded module (`loadHighlightModule` in `@opentide/lsp-worker`). */
|
|
152
|
+
module?: HighlightModule;
|
|
153
|
+
/** wasi: the `wasm32-wasip1` `opentide-lsp` build, as a path, its bytes, or a compiled module. */
|
|
154
|
+
wasi?: string | URL | Uint8Array | WebAssembly.Module;
|
|
155
|
+
}
|
|
156
|
+
export interface HighlightToken {
|
|
157
|
+
capture: string;
|
|
158
|
+
start: number;
|
|
159
|
+
end: number;
|
|
160
|
+
}
|
|
161
|
+
export interface HighlightResult {
|
|
162
|
+
language_id: string;
|
|
163
|
+
tokens: HighlightToken[];
|
|
164
|
+
legend: string[];
|
|
165
|
+
}
|
|
166
|
+
export interface Position {
|
|
167
|
+
line: number;
|
|
168
|
+
character: number;
|
|
169
|
+
}
|
|
170
|
+
export interface Diagnostic {
|
|
171
|
+
code: string;
|
|
172
|
+
severity: "error" | "warning" | "information" | "hint";
|
|
173
|
+
message: string;
|
|
174
|
+
range: {
|
|
175
|
+
start: Position;
|
|
176
|
+
end: Position;
|
|
177
|
+
};
|
|
178
|
+
field_path?: string[];
|
|
179
|
+
suggestion?: string;
|
|
180
|
+
object_uuid?: string;
|
|
181
|
+
object_type?: string;
|
|
182
|
+
}
|
|
183
|
+
export interface AnalyzeResult {
|
|
184
|
+
diagnostics: Diagnostic[];
|
|
185
|
+
}
|
|
186
|
+
export interface OpentideClient {
|
|
187
|
+
transport: Transport;
|
|
188
|
+
highlight(languageId: string, text: string): Promise<HighlightResult>;
|
|
189
|
+
legend(): Promise<string[]>;
|
|
190
|
+
analyze(languageId: string, text: string): Promise<AnalyzeResult>;
|
|
191
|
+
/**
|
|
192
|
+
* Tell the server the supplied workspace changed (`opentide/didChangeWorkspace`): what `workspace` gave
|
|
193
|
+
* on `initialize` is all a server with no filesystem reads. stdio and worker (with `worker`); the
|
|
194
|
+
* other transports have no session to update, and reject.
|
|
195
|
+
*/
|
|
196
|
+
updateWorkspace(change: WorkspaceChange): Promise<void>;
|
|
197
|
+
dispose(): Promise<void>;
|
|
198
|
+
}
|
|
199
|
+
declare function encodeMessage(body: unknown): Uint8Array;
|
|
200
|
+
/**
|
|
201
|
+
* Splits a byte stream into JSON-RPC messages framed by `Content-Length`.
|
|
202
|
+
* Bytes may arrive in any chunking; `push` returns every message completed.
|
|
203
|
+
*/
|
|
204
|
+
export declare class MessageDecoder {
|
|
205
|
+
private buffer;
|
|
206
|
+
push(chunk: Uint8Array): unknown[];
|
|
207
|
+
}
|
|
208
|
+
export declare function createOpentideClient(options: OpentideClientOptions): OpentideClient;
|
|
209
|
+
/** @deprecated Never use this name. */
|
|
210
|
+
export declare function createOtideClient(_options: OpentideClientOptions): never;
|
|
211
|
+
export { encodeMessage };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* opentide language client.
|
|
3
|
+
*
|
|
4
|
+
* The factory is `createOpentideClient`. There is no `createOtideClient`.
|
|
5
|
+
*
|
|
6
|
+
* Three transports reach the same engine:
|
|
7
|
+
*
|
|
8
|
+
* - `stdio` runs `opentide-lsp --stdio` once and speaks JSON-RPC to it
|
|
9
|
+
* (`opentide/analyze`, `opentide/highlight`).
|
|
10
|
+
* - `worker` speaks the same JSON-RPC to the same server running in a Web
|
|
11
|
+
* Worker (`worker`: `serveLanguageServer` from `@opentide/lsp-worker`, over
|
|
12
|
+
* `opentide-wasm`), one message per `postMessage`. Given a loaded `module`
|
|
13
|
+
* instead, it calls `highlight()` and `legend()` in this thread and does not
|
|
14
|
+
* analyze.
|
|
15
|
+
* - `wasi` runs the `wasm32-wasip1` `opentide-lsp` CLI under `node:wasi`, one
|
|
16
|
+
* `analyze` or `highlight` per call. Under Node 22, run the process with
|
|
17
|
+
* `--no-turbo-fast-api-calls`: `node:wasi`'s fast calls (`path_open`,
|
|
18
|
+
* `fd_write`) can start a garbage collection inside the call, which
|
|
19
|
+
* segfaults the process once the WASI instances hold enough memory.
|
|
20
|
+
*
|
|
21
|
+
* A transport that cannot answer rejects. It never returns an empty result in
|
|
22
|
+
* place of one.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Every language the server handles. `kql` is Microsoft KQL; `kuery` is
|
|
26
|
+
* Kibana KQL (Elastic `language: kuery`). Tide YAML is scoped to `objects/`,
|
|
27
|
+
* where the server owns diagnostics (turn yamlls off there).
|
|
28
|
+
*
|
|
29
|
+
* `cql` is the CrowdStrike Query Language (Falcon LogScale, Next-Gen SIEM).
|
|
30
|
+
* Cassandra's CQL uses the `.cql` extension too: where a workspace holds
|
|
31
|
+
* Cassandra scripts, leave out the `.cql` file pattern and match `cql` by
|
|
32
|
+
* language id alone.
|
|
33
|
+
*
|
|
34
|
+
* `exabeam` is the Exabeam Query Language (New-Scale SIEM), which Exabeam's
|
|
35
|
+
* guides call "EQL"; `eql` stays Elastic's. A `.exabeam` file is a search.
|
|
36
|
+
*
|
|
37
|
+
* `opentide-config` is configuration TOML (`.opentide/configurations/`). The
|
|
38
|
+
* host that runs the server checks it (`opentide lsp start`); `opentide-lsp`
|
|
39
|
+
* on its own reports nothing for it, so `analyze` and `highlight` refuse it.
|
|
40
|
+
* Keep the editor's TOML grammar for it.
|
|
41
|
+
*/
|
|
42
|
+
export const LANGUAGES = [
|
|
43
|
+
{ id: "opentide-yaml", name: "Tide YAML", patterns: ["**/objects/**/*.yaml", "**/objects/**/*.yml"] },
|
|
44
|
+
{ id: "kql", name: "KQL (Microsoft)", patterns: ["**/*.kql"] },
|
|
45
|
+
{ id: "spl", name: "SPL", patterns: ["**/*.spl"] },
|
|
46
|
+
{ id: "esql", name: "ES|QL", patterns: ["**/*.esql"] },
|
|
47
|
+
{ id: "eql", name: "EQL", patterns: ["**/*.eql"] },
|
|
48
|
+
{ id: "kuery", name: "Kibana KQL", patterns: ["**/*.kuery"] },
|
|
49
|
+
{ id: "lucene", name: "Lucene", patterns: ["**/*.lucene"] },
|
|
50
|
+
{ id: "falco", name: "Falco", patterns: ["**/*.falco"] },
|
|
51
|
+
{ id: "cql", name: "CrowdStrike Query Language", patterns: ["**/*.cql"] },
|
|
52
|
+
{ id: "yara", name: "YARA", patterns: ["**/*.yar", "**/*.yara"] },
|
|
53
|
+
{ id: "exabeam", name: "Exabeam Query Language", patterns: ["**/*.exabeam"] },
|
|
54
|
+
{ id: "yaral", name: "YARA-L", patterns: ["**/*.yaral", "**/*.yl2"] },
|
|
55
|
+
{ id: "opentide-config", name: "opentide configuration", patterns: ["**/.opentide/configurations/**/*.toml"] },
|
|
56
|
+
];
|
|
57
|
+
/**
|
|
58
|
+
* LSP document selector for every language, by language id and by file
|
|
59
|
+
* pattern, so a file is served even when no extension registered its id
|
|
60
|
+
* (for example `.esql` when Elastic's own extension owns the id). Its
|
|
61
|
+
* patterns match `file:` URIs only: use it on the desktop.
|
|
62
|
+
*
|
|
63
|
+
* A plain array, so it is vscode-languageclient's `documentSelector` as it
|
|
64
|
+
* is; do not change it in place.
|
|
65
|
+
*/
|
|
66
|
+
export const DOCUMENT_SELECTOR = LANGUAGES.flatMap((l) => [
|
|
67
|
+
{ language: l.id },
|
|
68
|
+
...l.patterns.map((pattern) => ({ scheme: "file", pattern })),
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* The same selector with no scheme, for web hosts (vscode.dev, github.dev),
|
|
72
|
+
* where documents are `vscode-vfs:`, `vscode-remote:` or other virtual URIs,
|
|
73
|
+
* not `file:` ones. A pattern without a scheme matches the URI's path
|
|
74
|
+
* whatever its scheme. A plain array, like `DOCUMENT_SELECTOR`.
|
|
75
|
+
*/
|
|
76
|
+
export const WEB_DOCUMENT_SELECTOR = LANGUAGES.flatMap((l) => [
|
|
77
|
+
{ language: l.id },
|
|
78
|
+
...l.patterns.map((pattern) => ({ pattern })),
|
|
79
|
+
]);
|
|
80
|
+
/** The languages `analyze` and `highlight` take: not `opentide-config`, which only a host checks. */
|
|
81
|
+
const LANGUAGE_IDS = new Set(LANGUAGES.map((l) => l.id).filter((id) => id !== "opentide-config"));
|
|
82
|
+
/** The server refuses an unknown id (and `opentide-config`) with InvalidParams; refusing it here saves the round trip. */
|
|
83
|
+
function checkLanguage(languageId) {
|
|
84
|
+
if (languageId === "opentide-config") {
|
|
85
|
+
throw new Error("opentide-config is checked by the host that runs the server (opentide lsp start), not by analyze or highlight");
|
|
86
|
+
}
|
|
87
|
+
if (!LANGUAGE_IDS.has(languageId)) {
|
|
88
|
+
throw new Error(`unknown language ${JSON.stringify(languageId)}; expected one of ${[...LANGUAGE_IDS].join(", ")}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** File suffix the CLI detects `languageId` from. */
|
|
92
|
+
function extensionFor(languageId) {
|
|
93
|
+
return languageId === "opentide-yaml" ? "yaml" : languageId;
|
|
94
|
+
}
|
|
95
|
+
function encodeMessage(body) {
|
|
96
|
+
const json = new TextEncoder().encode(JSON.stringify(body));
|
|
97
|
+
const header = new TextEncoder().encode(`Content-Length: ${json.length}\r\n\r\n`);
|
|
98
|
+
const out = new Uint8Array(header.length + json.length);
|
|
99
|
+
out.set(header, 0);
|
|
100
|
+
out.set(json, header.length);
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Splits a byte stream into JSON-RPC messages framed by `Content-Length`.
|
|
105
|
+
* Bytes may arrive in any chunking; `push` returns every message completed.
|
|
106
|
+
*/
|
|
107
|
+
export class MessageDecoder {
|
|
108
|
+
buffer = new Uint8Array(0);
|
|
109
|
+
push(chunk) {
|
|
110
|
+
const joined = new Uint8Array(this.buffer.length + chunk.length);
|
|
111
|
+
joined.set(this.buffer, 0);
|
|
112
|
+
joined.set(chunk, this.buffer.length);
|
|
113
|
+
this.buffer = joined;
|
|
114
|
+
const messages = [];
|
|
115
|
+
for (;;) {
|
|
116
|
+
const end = indexOfHeaderEnd(this.buffer);
|
|
117
|
+
if (end < 0)
|
|
118
|
+
break;
|
|
119
|
+
const header = new TextDecoder().decode(this.buffer.subarray(0, end));
|
|
120
|
+
const match = /^content-length:\s*(\d+)\s*$/im.exec(header);
|
|
121
|
+
if (!match)
|
|
122
|
+
throw new Error(`JSON-RPC header without Content-Length: ${JSON.stringify(header)}`);
|
|
123
|
+
const start = end + 4;
|
|
124
|
+
const length = Number(match[1]);
|
|
125
|
+
if (this.buffer.length < start + length)
|
|
126
|
+
break;
|
|
127
|
+
messages.push(JSON.parse(new TextDecoder().decode(this.buffer.subarray(start, start + length))));
|
|
128
|
+
this.buffer = this.buffer.slice(start + length);
|
|
129
|
+
}
|
|
130
|
+
return messages;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function indexOfHeaderEnd(bytes) {
|
|
134
|
+
for (let i = 0; i + 3 < bytes.length; i++) {
|
|
135
|
+
if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10)
|
|
136
|
+
return i;
|
|
137
|
+
}
|
|
138
|
+
return -1;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* One JSON-RPC session with the server, started on first use: the
|
|
142
|
+
* `initialize` handshake, requests matched to their responses, and
|
|
143
|
+
* `shutdown`/`exit` on dispose. A subclass opens the channel and writes to it.
|
|
144
|
+
*/
|
|
145
|
+
class Connection {
|
|
146
|
+
ready;
|
|
147
|
+
nextId = 1;
|
|
148
|
+
pending = new Map();
|
|
149
|
+
closed;
|
|
150
|
+
options;
|
|
151
|
+
constructor(options) {
|
|
152
|
+
this.options = options;
|
|
153
|
+
}
|
|
154
|
+
request(method, params) {
|
|
155
|
+
return this.start().then(() => this.send(method, params));
|
|
156
|
+
}
|
|
157
|
+
/** A notification, once the session is up. */
|
|
158
|
+
notification(method, params) {
|
|
159
|
+
return this.start().then(() => {
|
|
160
|
+
if (this.closed)
|
|
161
|
+
throw this.closed;
|
|
162
|
+
this.notify(method, params);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
start() {
|
|
166
|
+
this.ready ??= (async () => {
|
|
167
|
+
await this.open();
|
|
168
|
+
await this.send("initialize", {
|
|
169
|
+
processId: this.processId(),
|
|
170
|
+
rootUri: this.options.rootUri ?? null,
|
|
171
|
+
capabilities: {},
|
|
172
|
+
...(this.options.workspace ? { initializationOptions: { workspace: this.options.workspace } } : {}),
|
|
173
|
+
});
|
|
174
|
+
this.notify("initialized", {});
|
|
175
|
+
})();
|
|
176
|
+
return this.ready;
|
|
177
|
+
}
|
|
178
|
+
send(method, params) {
|
|
179
|
+
if (this.closed)
|
|
180
|
+
return Promise.reject(this.closed);
|
|
181
|
+
const id = this.nextId++;
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
this.pending.set(id, { resolve, reject });
|
|
184
|
+
this.write({ jsonrpc: "2.0", id, method, params });
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
notify(method, params) {
|
|
188
|
+
if (!this.closed)
|
|
189
|
+
this.write({ jsonrpc: "2.0", method, params });
|
|
190
|
+
}
|
|
191
|
+
receive(message) {
|
|
192
|
+
// Notifications from the server (publishDiagnostics) carry no id.
|
|
193
|
+
if (message.id === undefined || message.method !== undefined)
|
|
194
|
+
return;
|
|
195
|
+
const waiter = this.pending.get(message.id);
|
|
196
|
+
if (!waiter)
|
|
197
|
+
return;
|
|
198
|
+
this.pending.delete(message.id);
|
|
199
|
+
if (message.error)
|
|
200
|
+
waiter.reject(new Error(`${message.error.message} (${message.error.code})`));
|
|
201
|
+
else
|
|
202
|
+
waiter.resolve(message.result);
|
|
203
|
+
}
|
|
204
|
+
fail(error) {
|
|
205
|
+
this.closed ??= error;
|
|
206
|
+
for (const waiter of this.pending.values())
|
|
207
|
+
waiter.reject(error);
|
|
208
|
+
this.pending.clear();
|
|
209
|
+
}
|
|
210
|
+
async dispose() {
|
|
211
|
+
if (!this.ready)
|
|
212
|
+
return;
|
|
213
|
+
try {
|
|
214
|
+
await this.ready;
|
|
215
|
+
await this.send("shutdown", null);
|
|
216
|
+
this.notify("exit", null);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// Already gone: nothing to shut down.
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
await this.close();
|
|
223
|
+
this.fail(new Error("client disposed"));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** One `opentide-lsp --stdio` process. */
|
|
228
|
+
class StdioConnection extends Connection {
|
|
229
|
+
child;
|
|
230
|
+
stderr = "";
|
|
231
|
+
async open() {
|
|
232
|
+
const { spawn } = await import("node:child_process");
|
|
233
|
+
const command = this.options.command ?? "opentide-lsp";
|
|
234
|
+
const child = spawn(command, this.options.args ?? ["--stdio"], { stdio: ["pipe", "pipe", "pipe"] });
|
|
235
|
+
this.child = child;
|
|
236
|
+
const decoder = new MessageDecoder();
|
|
237
|
+
child.stdout.on("data", (chunk) => {
|
|
238
|
+
for (const message of decoder.push(chunk))
|
|
239
|
+
this.receive(message);
|
|
240
|
+
});
|
|
241
|
+
child.stderr.on("data", (chunk) => {
|
|
242
|
+
this.stderr = (this.stderr + new TextDecoder().decode(chunk)).slice(-4096);
|
|
243
|
+
});
|
|
244
|
+
child.on("error", (e) => this.fail(new Error(`cannot start ${command}: ${e.message}`)));
|
|
245
|
+
// A write to a server that died (EPIPE) is reported through `close`.
|
|
246
|
+
child.stdin.on("error", () => { });
|
|
247
|
+
child.on("close", (code, signal) => {
|
|
248
|
+
const detail = this.stderr.trim() ? `: ${this.stderr.trim()}` : "";
|
|
249
|
+
this.fail(new Error(`${command} exited (${signal ?? code})${detail}`));
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
write(message) {
|
|
253
|
+
this.child.stdin.write(encodeMessage(message));
|
|
254
|
+
}
|
|
255
|
+
processId() {
|
|
256
|
+
return process.pid;
|
|
257
|
+
}
|
|
258
|
+
async close() {
|
|
259
|
+
const child = this.child;
|
|
260
|
+
if (!child)
|
|
261
|
+
return;
|
|
262
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
263
|
+
const exited = new Promise((resolve) => child.once("close", () => resolve()));
|
|
264
|
+
const timeout = new Promise((resolve) => {
|
|
265
|
+
// Node's timer has `unref`, so a server that never exits does not keep the process alive.
|
|
266
|
+
const timer = setTimeout(resolve, 2000);
|
|
267
|
+
timer.unref?.();
|
|
268
|
+
});
|
|
269
|
+
await Promise.race([exited, timeout]);
|
|
270
|
+
}
|
|
271
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
272
|
+
child.kill();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** The language server in a worker (`serveLanguageServer` in `@opentide/lsp-worker`), one message per `postMessage`. */
|
|
276
|
+
class WorkerConnection extends Connection {
|
|
277
|
+
async open() {
|
|
278
|
+
const port = this.options.worker;
|
|
279
|
+
port.addEventListener("message", (event) => {
|
|
280
|
+
const text = typeof event.data === "string" ? event.data : JSON.stringify(event.data);
|
|
281
|
+
try {
|
|
282
|
+
this.receive(JSON.parse(text));
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
this.fail(new Error(`the worker posted something that is not JSON-RPC: ${text.slice(0, 200)}`));
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
port.start?.();
|
|
289
|
+
}
|
|
290
|
+
write(message) {
|
|
291
|
+
this.options.worker.postMessage(JSON.stringify(message));
|
|
292
|
+
}
|
|
293
|
+
processId() {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
async close() {
|
|
297
|
+
const port = this.options.worker;
|
|
298
|
+
port.close?.();
|
|
299
|
+
port.terminate?.();
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/** A client of a JSON-RPC connection to the server: the stdio process, or the worker. */
|
|
303
|
+
function connectionClient(transport, connection) {
|
|
304
|
+
const highlight = async (languageId, text) => {
|
|
305
|
+
checkLanguage(languageId);
|
|
306
|
+
return (await connection.request("opentide/highlight", { language: languageId, text }));
|
|
307
|
+
};
|
|
308
|
+
return {
|
|
309
|
+
transport,
|
|
310
|
+
highlight,
|
|
311
|
+
async legend() {
|
|
312
|
+
return (await highlight("kql", "")).legend;
|
|
313
|
+
},
|
|
314
|
+
async analyze(languageId, text) {
|
|
315
|
+
checkLanguage(languageId);
|
|
316
|
+
const uri = `untitled:query.${extensionFor(languageId)}`;
|
|
317
|
+
return (await connection.request("opentide/analyze", { language: languageId, text, uri }));
|
|
318
|
+
},
|
|
319
|
+
updateWorkspace: (change) => connection.notification("opentide/didChangeWorkspace", change),
|
|
320
|
+
dispose: () => connection.dispose(),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function stdioClient(options) {
|
|
324
|
+
return connectionClient("stdio", new StdioConnection(options));
|
|
325
|
+
}
|
|
326
|
+
function workerClient(options) {
|
|
327
|
+
if (options.worker)
|
|
328
|
+
return connectionClient("worker", new WorkerConnection(options));
|
|
329
|
+
const module = options.module;
|
|
330
|
+
if (!module) {
|
|
331
|
+
throw new Error("the worker transport needs `worker` (a worker running serveLanguageServer from @opentide/lsp-worker) or `module` (loadHighlightModule)");
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
transport: "worker",
|
|
335
|
+
async highlight(languageId, text) {
|
|
336
|
+
checkLanguage(languageId);
|
|
337
|
+
return module.highlight(languageId, new TextEncoder().encode(text));
|
|
338
|
+
},
|
|
339
|
+
async legend() {
|
|
340
|
+
return [...module.legend()];
|
|
341
|
+
},
|
|
342
|
+
async analyze() {
|
|
343
|
+
throw new Error("analyze needs the language server: pass `worker` (serveLanguageServer from @opentide/lsp-worker), not a highlight `module`");
|
|
344
|
+
},
|
|
345
|
+
async updateWorkspace() {
|
|
346
|
+
throw new Error("updateWorkspace needs the language server: pass `worker` (serveLanguageServer from @opentide/lsp-worker), not a highlight `module`");
|
|
347
|
+
},
|
|
348
|
+
async dispose() { },
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
function wasiClient(options) {
|
|
352
|
+
const source = options.wasi;
|
|
353
|
+
if (!source) {
|
|
354
|
+
throw new Error("the wasi transport needs `wasi`: the wasm32-wasip1 opentide-lsp build");
|
|
355
|
+
}
|
|
356
|
+
let compiled;
|
|
357
|
+
const load = () => (compiled ??= (async () => {
|
|
358
|
+
if (source instanceof WebAssembly.Module)
|
|
359
|
+
return source;
|
|
360
|
+
if (source instanceof Uint8Array)
|
|
361
|
+
return WebAssembly.compile(source);
|
|
362
|
+
const { readFile } = await import("node:fs/promises");
|
|
363
|
+
return WebAssembly.compile(await readFile(source));
|
|
364
|
+
})());
|
|
365
|
+
/** Run one CLI subcommand on `text`, as `opentide-lsp <command> /work/query.<ext>`. */
|
|
366
|
+
const run = async (command, languageId, text) => {
|
|
367
|
+
checkLanguage(languageId);
|
|
368
|
+
const [{ WASI }, fs, { tmpdir }, { join }] = await Promise.all([
|
|
369
|
+
import("node:wasi"),
|
|
370
|
+
import("node:fs"),
|
|
371
|
+
import("node:os"),
|
|
372
|
+
import("node:path"),
|
|
373
|
+
]);
|
|
374
|
+
const module = await load();
|
|
375
|
+
const dir = fs.mkdtempSync(join(tmpdir(), "opentide-wasi-"));
|
|
376
|
+
try {
|
|
377
|
+
const file = `query.${extensionFor(languageId)}`;
|
|
378
|
+
fs.writeFileSync(join(dir, file), text);
|
|
379
|
+
const out = fs.openSync(join(dir, "stdout"), "w");
|
|
380
|
+
const err = fs.openSync(join(dir, "stderr"), "w");
|
|
381
|
+
let code;
|
|
382
|
+
try {
|
|
383
|
+
const wasi = new WASI({
|
|
384
|
+
version: "preview1",
|
|
385
|
+
args: ["opentide-lsp", command, `/work/${file}`, "--language", languageId],
|
|
386
|
+
preopens: { "/work": dir },
|
|
387
|
+
stdout: out,
|
|
388
|
+
stderr: err,
|
|
389
|
+
returnOnExit: true,
|
|
390
|
+
});
|
|
391
|
+
const instance = await WebAssembly.instantiate(module, wasi.getImportObject());
|
|
392
|
+
code = wasi.start(instance);
|
|
393
|
+
}
|
|
394
|
+
finally {
|
|
395
|
+
fs.closeSync(out);
|
|
396
|
+
fs.closeSync(err);
|
|
397
|
+
}
|
|
398
|
+
if (code !== 0) {
|
|
399
|
+
const stderr = fs.readFileSync(join(dir, "stderr"), "utf8").trim();
|
|
400
|
+
throw new Error(`opentide-lsp ${command} exited ${code}${stderr ? `: ${stderr}` : ""}`);
|
|
401
|
+
}
|
|
402
|
+
return JSON.parse(fs.readFileSync(join(dir, "stdout"), "utf8"));
|
|
403
|
+
}
|
|
404
|
+
finally {
|
|
405
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
const highlight = async (languageId, text) => (await run("highlight", languageId, text));
|
|
409
|
+
return {
|
|
410
|
+
transport: "wasi",
|
|
411
|
+
highlight,
|
|
412
|
+
async legend() {
|
|
413
|
+
return (await highlight("kql", "")).legend;
|
|
414
|
+
},
|
|
415
|
+
async analyze(languageId, text) {
|
|
416
|
+
// The CLI prints the diagnostics array; the RPC wraps it.
|
|
417
|
+
return { diagnostics: (await run("analyze", languageId, text)) };
|
|
418
|
+
},
|
|
419
|
+
async updateWorkspace() {
|
|
420
|
+
throw new Error("the wasi transport runs the CLI once per call: there is no session whose workspace to update");
|
|
421
|
+
},
|
|
422
|
+
async dispose() { },
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
export function createOpentideClient(options) {
|
|
426
|
+
switch (options.transport) {
|
|
427
|
+
case "stdio":
|
|
428
|
+
return stdioClient(options);
|
|
429
|
+
case "worker":
|
|
430
|
+
return workerClient(options);
|
|
431
|
+
case "wasi":
|
|
432
|
+
return wasiClient(options);
|
|
433
|
+
default:
|
|
434
|
+
throw new Error(`unsupported transport ${String(options.transport)}`);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/** @deprecated Never use this name. */
|
|
438
|
+
export function createOtideClient(_options) {
|
|
439
|
+
throw new Error("createOtideClient is not a valid export; use createOpentideClient");
|
|
440
|
+
}
|
|
441
|
+
export { encodeMessage };
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentide/lsp-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0-rc.3",
|
|
4
|
+
"description": "opentide language client. createOpentideClient — never createOtideClient.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --experimental-strip-types --test src/index.test.ts",
|
|
20
|
+
"build": "tsc -p tsconfig.json",
|
|
21
|
+
"prepack": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/opentidehq/opentide.git",
|
|
27
|
+
"directory": "packages/lsp-client"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"provenance": true
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "26.6.6",
|
|
35
|
+
"typescript": "5.9.3"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/README.md
DELETED