@xoong/lsp 0.0.0-stage → 0.0.35

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Duong Tran Xuan
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/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # @xoong/lsp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A language server for xoong screens: the diagnostics of `xoong check`, completion of operation names and `xo-*` attributes, and hover documentation in any editor that speaks LSP.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @xoong/lsp
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```bash
14
+ npx xoong-lsp
15
+ ```
16
+
17
+ ## More
18
+
19
+ * Documentation and demos: https://github.com/fpt-duongtx/xoong#readme
20
+ * Source: https://github.com/fpt-duongtx/xoong/tree/main/packages/lsp
21
+ * All packages share one version number and are released together: https://github.com/fpt-duongtx/xoong/releases
22
+ * xoong is a working prototype (0.0.x): the HTML syntax is still Draft.
23
+
24
+ MIT licence.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@xoong/lsp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.35",
4
+ "description": "Language server for xoong screens: the same diagnostics as `xoong check`, completion of operation names and xo-* attributes, hover docs. Any editor that speaks LSP.",
5
+ "type": "module",
6
+ "bin": {
7
+ "xoong-lsp": "src/cli.js"
8
+ },
9
+ "exports": {
10
+ ".": "./src/server.js"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "keywords": [
16
+ "xoong",
17
+ "language-server",
18
+ "lsp"
19
+ ],
20
+ "engines": {
21
+ "node": ">=22.12"
22
+ },
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "@xoong/cli": "0.0.35",
26
+ "@xoong/core": "0.0.35"
27
+ },
28
+ "author": "Duong Tran Xuan <duongtx1505@icloud.com>",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/fpt-duongtx/xoong.git",
32
+ "directory": "packages/lsp"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/fpt-duongtx/xoong/issues"
36
+ },
37
+ "homepage": "https://github.com/fpt-duongtx/xoong#readme",
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }
package/src/cli.js ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // xoong-lsp: language server over stdio (Content-Length framing). Finds .xoong/operations.json from the workspace folder upward.
4
+ import { readFile, stat } from 'node:fs/promises';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { createLanguageServer } from './server.js';
8
+
9
+ let root = process.cwd();
10
+ let cached = { file: '', mtime: 0, table: /** @type {any} */ (null) };
11
+
12
+ async function operations() {
13
+ for (let dir = root; ; dir = dirname(dir)) {
14
+ const file = join(dir, '.xoong', 'operations.json');
15
+ try {
16
+ const { mtimeMs } = await stat(file);
17
+ if (cached.file !== file || cached.mtime !== mtimeMs) cached = { file, mtime: mtimeMs, table: JSON.parse(await readFile(file, 'utf8')) };
18
+ return cached.table;
19
+ } catch { /* look one folder up */ }
20
+ if (dirname(dir) === dir) return null;
21
+ }
22
+ }
23
+
24
+ const server = createLanguageServer({ operations });
25
+ const send = (m) => { const body = Buffer.from(JSON.stringify(m)); process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`); process.stdout.write(body); };
26
+
27
+ let buffer = Buffer.alloc(0);
28
+ let chain = Promise.resolve(); // messages are handled one after another, so responses cannot overtake each other
29
+
30
+ async function process_(msg) {
31
+ try {
32
+ if (msg.method === 'initialize' && typeof msg.params?.rootUri === 'string' && msg.params.rootUri.startsWith('file:')) root = fileURLToPath(msg.params.rootUri);
33
+ if (msg.method === 'exit') process.exit(0);
34
+ for (const out of await server.handle(msg)) send(out);
35
+ } catch (e) {
36
+ console.error('xoong-lsp:', e); // stderr only: stdout carries the protocol
37
+ }
38
+ }
39
+
40
+ process.stdin.on('data', (chunk) => {
41
+ buffer = Buffer.concat([buffer, chunk]);
42
+ for (;;) {
43
+ const sep = buffer.indexOf('\r\n\r\n');
44
+ if (sep < 0) return;
45
+ const length = Number(/Content-Length: (\d+)/i.exec(buffer.subarray(0, sep).toString())?.[1]);
46
+ if (!length) { buffer = buffer.subarray(sep + 4); continue; } // a header we cannot use: drop it and keep going
47
+ if (buffer.length < sep + 4 + length) return;
48
+ const body = buffer.subarray(sep + 4, sep + 4 + length).toString();
49
+ buffer = buffer.subarray(sep + 4 + length);
50
+ let msg;
51
+ try { msg = JSON.parse(body); } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
52
+ chain = chain.then(() => process_(msg));
53
+ }
54
+ });
package/src/server.js ADDED
@@ -0,0 +1,152 @@
1
+ // @ts-check
2
+ /**
3
+ * xoong language server core: pure message handling, no I/O. `handle(message)` returns the messages to send back
4
+ * (a response and/or notifications), so it can be tested without a process. `cli.js` adds stdio framing.
5
+ *
6
+ * Features (one engine, see docs/editor-integration.md):
7
+ * diagnostics the findings of `xoong check`, with the same message and fix, as you type
8
+ * completion operation names inside xo-click, xo-submit, get and op; xo-* attribute names
9
+ * hover what an xo-* attribute or element does
10
+ * code action "Use <closest operation>" for unknown operations
11
+ */
12
+ import { checkHtml, checkScript } from '@xoong/cli/check';
13
+ import { ATTRIBUTE_DOCS, ELEMENT_DOCS } from '@xoong/cli/html-data';
14
+ import { XO_ATTRIBUTES, XO_ELEMENTS, XO_UI_ATTRIBUTES, XO_UI_ELEMENTS, XO_CONTROL_ATTRIBUTES, XO_CONTROL_ELEMENTS } from '@xoong/core/syntax';
15
+
16
+ const ATTRS = [...XO_ATTRIBUTES, ...XO_UI_ATTRIBUTES, ...XO_CONTROL_ATTRIBUTES];
17
+ const TAGS = [...XO_ELEMENTS, ...XO_UI_ELEMENTS, ...XO_CONTROL_ELEMENTS];
18
+ const isScript = (uri) => /\.(c|m)?[jt]sx?$/.test(uri);
19
+ const isMutationAttr = (name) => name === 'xo-click' || name === 'xo-submit' || name === 'op';
20
+
21
+ /**
22
+ * @param {{ operations: () => Promise<{ operations: Record<string, any> } | null> }} ctx
23
+ * `operations()` returns the synced table (re-read on every call so `xoong sync` is picked up) or null if there is none yet.
24
+ */
25
+ export function createLanguageServer(ctx) {
26
+ /** @type {Map<string, string>} open documents */
27
+ const docs = new Map();
28
+
29
+ const notify = (method, params) => ({ jsonrpc: '2.0', method, params });
30
+ const reply = (id, result) => ({ jsonrpc: '2.0', id, result });
31
+
32
+ /** End of the word that starts at (line, col) (0-based), so the squiggle covers the attribute or value, not one letter. */
33
+ function rangeAt(text, line, col) {
34
+ const row = text.split('\n')[line] ?? '';
35
+ let end = col;
36
+ while (end < row.length && !/[\s"'<>=]/.test(row[end])) end++;
37
+ if (end === col) end = Math.min(col + 1, row.length);
38
+ return { start: { line, character: col }, end: { line, character: end } };
39
+ }
40
+
41
+ async function diagnose(uri) {
42
+ const text = docs.get(uri) ?? '';
43
+ const table = await ctx.operations();
44
+ if (!table) return notify('textDocument/publishDiagnostics', { uri, diagnostics: [{ range: rangeAt(text, 0, 0), severity: 3, source: 'xoong', code: 'no-operations', message: 'No .xoong/operations.json found. Run `xoong sync <openapi>` so operations can be checked.' }] });
45
+ const findings = isScript(uri) ? checkScript(text, table, uri) : checkHtml(text, table, uri);
46
+ return notify('textDocument/publishDiagnostics', {
47
+ uri,
48
+ diagnostics: findings.map((f) => ({
49
+ range: rangeAt(text, f.line - 1, f.column - 1),
50
+ severity: f.level === 'error' ? 1 : 2,
51
+ source: 'xoong', code: f.code,
52
+ message: `${f.message}\nfix: ${f.fix}`,
53
+ data: { fix: f.fix },
54
+ })),
55
+ });
56
+ }
57
+
58
+ /** The text of the line before the cursor. */
59
+ const before = (uri, pos) => (docs.get(uri)?.split('\n')[pos.line] ?? '').slice(0, pos.character);
60
+
61
+ async function complete(uri, pos) {
62
+ const line = before(uri, pos);
63
+ const value = /(?<![\w:.-])(xo-click|xo-submit|get|op)\s*=\s*(["'])([^"']*)$/.exec(line);
64
+ if (value) {
65
+ const table = await ctx.operations();
66
+ if (!table) return [];
67
+ const [, attr, , typed] = value;
68
+ const reads = attr === 'get';
69
+ const items = [];
70
+ for (const o of Object.values(table.operations)) {
71
+ if (reads ? o.method !== 'GET' : o.method === 'GET') continue;
72
+ for (const label of reads ? [o.id, o.path] : [o.id, `${o.method} ${o.path}`]) if (label.toLowerCase().includes(typed.toLowerCase())) {
73
+ items.push({ label, kind: 12, detail: `${o.method} ${o.path}`, documentation: o.bodyFields ? `Body: ${o.bodyFields.map((b) => b.name + (b.required ? '*' : '')).join(', ')}` : undefined,
74
+ textEdit: { range: { start: { line: pos.line, character: pos.character - typed.length }, end: pos }, newText: label } });
75
+ }
76
+ }
77
+ return items;
78
+ }
79
+ const attr = /<[\w-]+[^<>]*\s(xo-[\w-]*|[\w-]*)$/.exec(line);
80
+ if (attr && attr[1].startsWith('xo-')) return ATTRS.map((name) => ({ label: name, kind: 10, documentation: ATTRIBUTE_DOCS[name] }));
81
+ const tag = /<(xo-[\w-]*)$/.exec(line);
82
+ if (tag) return TAGS.map((name) => ({ label: name, kind: 7, documentation: ELEMENT_DOCS[name]?.[0] }));
83
+ return [];
84
+ }
85
+
86
+ function hover(uri, pos) {
87
+ const row = docs.get(uri)?.split('\n')[pos.line] ?? '';
88
+ for (const m of row.matchAll(/xo-[\w-]+/g)) {
89
+ if (m.index <= pos.character && pos.character <= m.index + m[0].length) {
90
+ const name = m[0];
91
+ const text = ATTRIBUTE_DOCS[name] ?? ELEMENT_DOCS[name]?.[0];
92
+ if (text) return { contents: { kind: 'markdown', value: `**${name}**\n\n${text}` } };
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ function codeActions(uri, diagnostics) {
99
+ const actions = [];
100
+ for (const d of diagnostics ?? []) {
101
+ const closest = d.code === 'XO201' && /Use "([^"]+)"/.exec(d.data?.fix ?? '')?.[1];
102
+ if (!closest) continue;
103
+ const text = docs.get(uri) ?? '';
104
+ const row = text.split('\n')[d.range.start.line] ?? '';
105
+ let start, length;
106
+ if (isScript(uri)) { // the diagnostic starts at the operation name itself
107
+ const typo = /unknown operation "([^"]+)"/.exec(d.message)?.[1];
108
+ if (!typo || !row.startsWith(typo, d.range.start.character)) continue;
109
+ start = d.range.start.character; length = typo.length;
110
+ } else { // the diagnostic starts at the attribute: replace the quoted value after it
111
+ const quoted = /(["'])([^"']*)\1/.exec(row.slice(d.range.start.character));
112
+ if (!quoted) continue;
113
+ start = d.range.start.character + quoted.index + 1; length = quoted[2].length;
114
+ }
115
+ actions.push({ title: `Use "${closest}"`, kind: 'quickfix', diagnostics: [d], isPreferred: true,
116
+ edit: { changes: { [uri]: [{ range: { start: { line: d.range.start.line, character: start }, end: { line: d.range.start.line, character: start + length } }, newText: closest }] } } });
117
+ }
118
+ return actions;
119
+ }
120
+
121
+ /** @param {any} msg @returns {Promise<any[]>} */
122
+ async function handle(msg) {
123
+ try {
124
+ return await dispatch(msg ?? {});
125
+ } catch (e) { // one bad message must never take the server down
126
+ return msg?.id !== undefined ? [{ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: String(e instanceof Error ? e.message : e) } }] : [];
127
+ }
128
+ }
129
+
130
+ async function dispatch(msg) {
131
+ const { method, id, params } = msg;
132
+ switch (method) {
133
+ case 'initialize': return [reply(id, { capabilities: { textDocumentSync: 1, completionProvider: { triggerCharacters: ['"', "'", '-', '<'] }, hoverProvider: true, codeActionProvider: true }, serverInfo: { name: 'xoong-lsp', version: '0.0.1' } })];
134
+ case 'shutdown': return [reply(id, null)];
135
+ case 'textDocument/didOpen': docs.set(params.textDocument.uri, params.textDocument.text); return [await diagnose(params.textDocument.uri)];
136
+ case 'textDocument/didChange': {
137
+ const text = params?.contentChanges?.at(-1)?.text;
138
+ if (typeof text !== 'string') return []; // nothing usable: keep the last known text
139
+ docs.set(params.textDocument.uri, text);
140
+ return [await diagnose(params.textDocument.uri)];
141
+ }
142
+ case 'textDocument/didSave': return docs.has(params.textDocument.uri) ? [await diagnose(params.textDocument.uri)] : []; // also picks up a fresh `xoong sync`
143
+ case 'textDocument/didClose': docs.delete(params.textDocument.uri); return [notify('textDocument/publishDiagnostics', { uri: params.textDocument.uri, diagnostics: [] })];
144
+ case 'textDocument/completion': return [reply(id, await complete(params.textDocument.uri, params.position))];
145
+ case 'textDocument/hover': return [reply(id, hover(params.textDocument.uri, params.position))];
146
+ case 'textDocument/codeAction': return [reply(id, codeActions(params.textDocument.uri, params.context?.diagnostics))];
147
+ default: return id !== undefined ? [{ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } }] : [];
148
+ }
149
+ }
150
+
151
+ return { handle };
152
+ }