57 lines
2.1 KiB
JavaScript
57 lines
2.1 KiB
JavaScript
export class DummyServer {
|
|
constructor(config = {}) {
|
|
this.config = config;
|
|
this.initialized = false;
|
|
this.subscribers = [];
|
|
this.files = [];
|
|
}
|
|
subscribe(listener) {
|
|
this.subscribers.push(listener);
|
|
}
|
|
unsubscribe(listener) {
|
|
this.subscribers = this.subscribers.filter(l => l != listener);
|
|
}
|
|
send(message) {
|
|
var _a, _b;
|
|
if ((_b = (_a = this.config).brokenPipe) === null || _b === void 0 ? void 0 : _b.call(_a))
|
|
throw new Error("Broken Pipe");
|
|
const msg = JSON.parse(message);
|
|
if ("id" in msg) {
|
|
this.handleRequest(msg.method, msg.params).then(result => {
|
|
this.broadcast({ jsonrpc: "2.0", id: msg.id, result });
|
|
}, e => {
|
|
let error = e instanceof ServerError ? { code: e.code, message: e.message }
|
|
: { code: -32603 /* InternalError */, message: String(e) };
|
|
this.broadcast({ jsonrpc: "2.0", id: msg.id, error });
|
|
});
|
|
}
|
|
else {
|
|
this.handleNotification(msg.method, msg.params);
|
|
}
|
|
}
|
|
broadcast(message) {
|
|
for (let sub of this.subscribers)
|
|
sub(JSON.stringify(message));
|
|
}
|
|
handleRequest(method, params) {
|
|
return new Promise(resolve => {
|
|
var _a;
|
|
if (!this.initialized && method != "initialize")
|
|
throw new ServerError(-32002 /* ServerNotInitialized */, "Not initialized");
|
|
let handler = requestHandlers[method];
|
|
if (!handler)
|
|
throw new ServerError(-32601 /* MethodNotFound */, "Method not found");
|
|
let result = handler(params, this), delay = (_a = this.config.delay) === null || _a === void 0 ? void 0 : _a[method];
|
|
if (delay)
|
|
setTimeout(() => resolve(result), delay);
|
|
else
|
|
queueMicrotask(() => resolve(result));
|
|
});
|
|
}
|
|
handleNotification(method, params) {
|
|
let handler = notificationHandlers[method];
|
|
if (handler)
|
|
handler(params, this);
|
|
}
|
|
getFile(uri) { return this.files.find(f => f.uri == uri); }
|
|
}
|