-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathclient.ts
270 lines (229 loc) · 7.66 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/**
* Handles attaching transport
*/
import { Logger } from '../utils/logger';
import { Response, Transport } from '../utils/transport';
import { VimValue } from '../types/VimValue';
import { Neovim } from './Neovim';
import { Buffer } from './Buffer';
const REGEX_BUF_EVENT = /nvim_buf_(.*)_event/;
export class NeovimClient extends Neovim {
protected requestQueue: any[];
/**
* Handlers for custom (non "nvim_") methods registered by the remote module.
* These handle requests from the Nvim peer.
*/
public handlers: {
[index: string]: (args: any[], event: { name: string }) => any;
} = {};
private transportAttached: boolean;
private _channelId?: number;
private attachedBuffers: Map<string, Map<string, Function[]>> = new Map();
/**
* Defines a handler for incoming RPC request method/notification.
*/
setHandler(
method: string,
fn: (args: any[], event: { name: string }) => any
) {
this.handlers[method] = fn;
}
constructor(options: { transport?: Transport; logger?: Logger } = {}) {
// Neovim has no `data` or `metadata`
super({
logger: options.logger,
transport: options.transport || new Transport(),
});
this.requestQueue = [];
this.transportAttached = false;
this.handleRequest = this.handleRequest.bind(this);
this.handleNotification = this.handleNotification.bind(this);
}
/** Attaches msgpack to read/write streams * */
attach({ reader, writer }: { reader: NodeJS.ReadableStream; writer: NodeJS.WritableStream }) {
this.transport.attach(writer, reader, this);
this.transportAttached = true;
this.setupTransport();
}
get isApiReady(): boolean {
return this.transportAttached && this._channelId !== undefined;
}
get channelId(): Promise<number> {
return (async () => {
await this._isReady;
if (!this._channelId) {
throw new Error('channelId requested before _isReady');
}
return this._channelId;
})();
}
isAttached(buffer: Buffer): boolean {
const key = `${buffer.data}`;
return this.attachedBuffers.has(key);
}
/** Handles incoming request (from the peer). */
handleRequest(method: string, args: VimValue[], resp: Response, ...restArgs: any[]) {
// If neovim API is not generated yet and we are not handle a 'specs' request
// then queue up requests
//
// Otherwise emit as normal
if (!this.isApiReady && method !== 'specs') {
this.logger.info('handleRequest (queued): %s', method);
this.requestQueue.push({
type: 'request',
args: [method, args, resp, ...restArgs],
});
} else {
this.logger.info('handleRequest: %s', method);
this.emit('request', method, args, resp);
}
}
/** Publishes to (local) subscribers of this `EventEmitter`. */
emitNotification(method: string, args: any[]) {
if (method.endsWith('_event')) {
if (!method.startsWith('nvim_buf_')) {
this.logger.error('Unhandled event: %s', method);
return;
}
const shortName = method.replace(REGEX_BUF_EVENT, '$1');
const [buffer] = args;
const bufferKey = `${buffer.data}`;
const bufferMap = this.attachedBuffers.get(bufferKey);
if (bufferMap === undefined) {
// this is a problem
return;
}
const cbs = bufferMap.get(shortName) || [];
cbs.forEach(cb => cb(...args));
// Handle `nvim_buf_detach_event`
// clean `attachedBuffers` since it will no longer be attached
if (shortName === 'detach') {
this.attachedBuffers.delete(bufferKey);
}
} else {
this.emit('notification', method, args);
}
}
/** Handles incoming notification (from the peer). */
handleNotification(method: string, args: VimValue[], ...restArgs: any[]) {
this.logger.info('handleNotification: %s', method);
// If neovim API is not generated yet then queue up requests
//
// Otherwise emit as normal
if (!this.isApiReady) {
this.requestQueue.push({
type: 'notification',
args: [method, args, ...restArgs],
});
} else {
this.emitNotification(method, args);
}
}
// Listen and setup handlers for transport
setupTransport() {
if (!this.transportAttached) {
throw new Error('Not attached to input/output');
}
this.transport.on('request', this.handleRequest);
this.transport.on('notification', this.handleNotification);
this.transport.on('detach', () => {
this.emit('disconnect');
this.transport.removeAllListeners('request');
this.transport.removeAllListeners('notification');
this.transport.removeAllListeners('detach');
});
this._isReady = this.generateApi();
}
requestApi(): Promise<any[]> {
return new Promise((resolve, reject) => {
this.transport.request('nvim_get_api_info', [], (err: Error, res: any[]) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
// Request API from neovim and augment this current class to add these APIs
async generateApi(): Promise<boolean> {
let results;
try {
results = await this.requestApi();
} catch (err) {
this.logger.error('Could not get vim api results');
this.logger.error(err);
}
if (results) {
try {
const [channelId /* , encodedMetadata */] = results;
// const metadata = encodedMetadata;
// this.logger.debug(`$$$: ${metadata}`);
// Perform sanity check for metadata types
// Object.keys(metadata.types).forEach((name: string) => {
// const metaDataForType = metadata.types[name]; // eslint-disable-line @typescript-eslint/no-unused-vars
// TODO: check `prefix` and `id`
// });
this._channelId = channelId;
// register the non-queueing handlers
// dequeue any pending RPCs
this.requestQueue.forEach(pending => {
if (pending.type === 'notification') {
this.emitNotification(pending.args[0], pending.args[1]);
} else {
this.emit(pending.type, ...pending.args);
}
});
this.requestQueue = [];
return true;
} catch (e) {
const err = e as Error;
this.logger.error(`Could not dynamically generate neovim API: %s: %O`, err.name, {
error: err,
});
this.logger.error(err.stack);
return false;
}
}
return false;
}
attachBuffer(buffer: Buffer, eventName: string, cb: Function) {
const bufferKey = `${buffer.data}`;
if (!this.attachedBuffers.has(bufferKey)) {
this.attachedBuffers.set(bufferKey, new Map());
}
const bufferMap = this.attachedBuffers.get(bufferKey);
if (!bufferMap) {
throw Error(`buffer not found: ${bufferKey}`);
}
if (!bufferMap.get(eventName)) {
bufferMap.set(eventName, []);
}
const cbs = bufferMap.get(eventName) ?? [];
if (cbs.includes(cb)) return cb;
cbs.push(cb);
bufferMap.set(eventName, cbs);
this.attachedBuffers.set(bufferKey, bufferMap);
return cb;
}
/**
* Returns `true` if buffer should be detached
*/
detachBuffer(buffer: Buffer, eventName: string, cb: Function) {
const bufferKey = `${buffer.data}`;
const bufferMap = this.attachedBuffers.get(bufferKey);
if (!bufferMap) return false;
const handlers = (bufferMap.get(eventName) || []).filter(handler => handler !== cb);
// Remove eventName listener from bufferMap if no more handlers
if (!handlers.length) {
bufferMap.delete(eventName);
} else {
bufferMap.set(eventName, handlers);
}
if (!bufferMap.size) {
this.attachedBuffers.delete(bufferKey);
return true;
}
return false;
}
}