jspteroapi
Version:
A pterodactyl v1 api using undici
62 lines (61 loc) • 1.76 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Socket = void 0;
const ws_1 = require("ws");
class Socket {
url;
options;
constructor(url, options) {
this.url = url;
this.options = options;
this.open();
}
reconnectNum = 0;
open = () => {
const options = this.options;
const reconnect = this.reconnect;
this.ws = new ws_1.WebSocket(this.url);
this.ws.onmessage = options.onmessage;
const onOpen = options.onopen.bind(this);
this.ws.onopen = (e) => {
onOpen(e);
this.reconnectNum = 0;
};
const onClose = options.onclose.bind(this);
this.ws.onclose = function (e) {
e.code === 1e3 || e.code === 1001 || e.code === 1005 || reconnect(e);
onClose(e);
};
const onError = options.onerror.bind(this);
this.ws.onerror = function (e) {
e && e.code === 'ECONNREFUSED'
? reconnect(e)
: onError(e);
};
};
reconnect = (e) => {
const onReconnect = this.options.onreconnect.bind(this);
const onMaximum = this.options.onmaximum.bind(this);
const open = this.open;
if (this.timer && this.reconnectNum++ < Infinity) {
this.timer = setTimeout(function () {
onReconnect(e);
open();
}, 1e3);
}
else {
onMaximum(e);
}
};
json = (x) => {
this.ws.send(JSON.stringify(x));
};
send = (x) => {
this.ws.send(x);
};
close = (x, y) => {
clearTimeout(this.timer);
this.ws.close(x || 1e3, y);
};
}
exports.Socket = Socket;