11// Simple JSON-RPC 2.0 LSP-like fake server over stdio
22// Implements a minimal LSP handshake and publishes diagnostics
33
4- import { Buffer } from 'node:buffer'
5- import process from 'node:process'
4+ import { send , start } from './fake-lsp-transport.js'
65
76let nextId = 1
87// Tracks how many didOpen notifications were received per uri, so tests can
98// assert that concurrent opens do not emit a duplicate didOpen.
109const openCounts = { }
1110
12- function encode ( message ) {
13- const json = JSON . stringify ( message )
14- const header = `Content-Length: ${ Buffer . byteLength ( json , 'utf8' ) } \r\n\r\n`
15- return Buffer . concat ( [
16- Buffer . from ( header , 'utf8' ) ,
17- Buffer . from ( json , 'utf8' ) ,
18- ] )
19- }
20-
21- function decodeFrames ( buffer ) {
22- const results = [ ]
23- let idx = buffer . indexOf ( '\r\n\r\n' )
24- while ( idx !== - 1 ) {
25- const header = buffer . slice ( 0 , idx ) . toString ( 'utf8' )
26- const m = / C o n t e n t - L e n g t h : \s * ( \d + ) / i. exec ( header )
27- const len = m ? Number . parseInt ( m [ 1 ] , 10 ) : 0
28- const bodyStart = idx + 4
29- const bodyEnd = bodyStart + len
30- if ( buffer . length < bodyEnd )
31- break
32- const body = buffer . slice ( bodyStart , bodyEnd ) . toString ( 'utf8' )
33- results . push ( body )
34- buffer = buffer . slice ( bodyEnd )
35- idx = buffer . indexOf ( '\r\n\r\n' )
36- }
37- return { messages : results , rest : buffer }
38- }
39-
40- let readBuffer = Buffer . alloc ( 0 )
41-
42- process . stdin . on ( 'data' , ( chunk ) => {
43- readBuffer = Buffer . concat ( [ readBuffer , chunk ] )
44- const { messages, rest } = decodeFrames ( readBuffer )
45- readBuffer = rest
46- for ( const m of messages ) handle ( m )
47- } )
48-
49- function send ( msg ) {
50- process . stdout . write ( encode ( msg ) )
51- }
52-
5311function sendNotification ( method , params ) {
5412 send ( { jsonrpc : '2.0' , method, params } )
5513}
@@ -60,14 +18,7 @@ function sendRequest(method, params) {
6018 return id
6119}
6220
63- function handle ( raw ) {
64- let data
65- try {
66- data = JSON . parse ( raw )
67- }
68- catch {
69- return
70- }
21+ start ( ( data ) => {
7122
7223 // Initialize request
7324 if ( data . method === 'initialize' ) {
@@ -211,4 +162,4 @@ function handle(raw) {
211162 if ( typeof data . id !== 'undefined' ) {
212163 send ( { jsonrpc : '2.0' , id : data . id , result : null } )
213164 }
214- }
165+ } )
0 commit comments