@@ -9,9 +9,68 @@ const log = (msg: string) => {
9
9
} )
10
10
}
11
11
12
+ // Encode message
13
+ export const encode = ( payload : Object ) => {
14
+ const content = JSON . stringify ( payload )
15
+ return `Content-Length: ${ content . length } \r\n\r\n${ content } `
16
+ }
17
+
18
+ interface Message {
19
+ jsonrpc : string ;
20
+ }
21
+
22
+ interface RequestMessage extends Message {
23
+ id : number ;
24
+ method : string ;
25
+ }
26
+
27
+ // Decode message
28
+ export const decode = ( content : string ) : RequestMessage | null => {
29
+ const [ header , body ] = content . split ( "\r\n\r\n" )
30
+ if ( header . startsWith ( "Content-Length" ) ) {
31
+ const length = parseInt ( header . split ( ": " ) [ 1 ] )
32
+ return JSON . parse ( body . substring ( 0 , length ) )
33
+ } else {
34
+ log ( `Could not parse: ${ content } \n` )
35
+ return null
36
+ }
37
+ }
38
+
39
+ const respond = ( id : number , result : Object | null ) => {
40
+ const response = encode ( { jsonrpc : "2.0" , id, result } )
41
+ process . stdout . write ( response )
42
+ log ( response + "\n" )
43
+ }
44
+
45
+ const initializeResult = ( ) => {
46
+ return {
47
+ capabilities : {
48
+ textDocumentSync : 1
49
+ } ,
50
+ serverInfo : {
51
+ name : "leaflet-html" ,
52
+ version : "0.0.0"
53
+ }
54
+ }
55
+ }
56
+
57
+ const shutdownResult = ( ) => null
58
+
12
59
// Listen on stdin/stdout
13
60
process . stdin . on ( "data" , ( buf ) => {
14
61
const message = buf . toString ( )
15
- log ( message )
16
- process . stdout . write ( message )
62
+ log ( message + "\n" )
63
+ const payload = decode ( message )
64
+ if ( payload !== null ) {
65
+ switch ( payload . method ) {
66
+ case ( "initialize" ) :
67
+ respond ( payload . id , initializeResult ( ) ) ;
68
+ break ;
69
+ case ( "shutdown" ) :
70
+ respond ( payload . id , shutdownResult ( ) ) ;
71
+ break ;
72
+ case ( "exit" ) :
73
+ process . exit ( 0 )
74
+ }
75
+ }
17
76
} )
0 commit comments