UNPKG

leref.ts

Version:

Something upcoming for aoi.js and npm packages uses

1 lines 4.75 kB
"use strict";var __decorate=this&&this.__decorate||function(e,t,s,o){var i,r=arguments.length,n=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,s):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,s,o);else for(var a=e.length-1;0<=a;a--)(i=e[a])&&(n=(r<3?i(n):3<r?i(t,s,n):i(t,s))||n);return 3<r&&n&&Object.defineProperty(t,s,n),n},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.LerefNodes=void 0;const ws_1=__importDefault(require("ws")),undici_1=require("undici"),stream_1=require("stream"),tiny_typed_emitter_1=require("tiny-typed-emitter"),constructs_1=require("../utils/decorators/constructs"),utils_1=require("../utils"),lerefRoutes_1=require("./lerefRoutes");let LerefNodes=class extends tiny_typed_emitter_1.TypedEmitter{constructor(e,t){super(),this.lava=e,this.calls=0,this.connected=!1,this.resumed=!1,this.routePlanner=new lerefRoutes_1.LerefRoutes(this),this.reconnectAttempts=1,this.options={password:"lerefpassword",secure:!1,retryAmount:5,retryDelay:3e4,maxConnections:null,...t},this.stats={players:0,playingPlayers:0,uptime:0,memory:{free:0,used:0,allocated:0,reservable:0},cpu:{cores:0,systemLoad:0,lavalinkLoad:0},lastUpdated:Date.now()},this.http=new undici_1.Pool(`http${this.options.secure?"s":""}://`+this.options.url,{connections:this.options.maxConnections}),this.lava.emit("nodeCreate",this),this.lava.nodes.set(this.options.name,this)}async request(e){e=e.replace(/^\//gm,"");const t=[];return await this.http.stream({path:"/"+e,method:"GET",opaque:t,bodyTimeout:this.options.requestTimeout,headersTimeout:this.options.requestTimeout,headers:{Authorization:this.options.password}},({opaque:o})=>new stream_1.Writable({defaultEncoding:"utf-8",write(e,t,s){o.push(e),s()}})),this.calls++,JSON.parse(t.join(""))}async post(e,t,s=!1){e=e.replace(/^\//gm,""),void 0!==t&&(t=JSON.stringify(t));const o={Authorization:this.options.password},i={path:"/"+e,method:"POST",bodyTimeout:this.options.requestTimeout,headersTimeout:this.options.requestTimeout,headers:o};"string"==typeof t&&(o["Content-Type"]="application/json",i.body=t);const r=await this.http.request(i);return this.calls++,s?r:r.body.json()}connect(){if(!this.connected){const e={Authorization:this.options.password,"Num-Shards":String(this.lava.options.shards),"User-Id":this.lava.clientID,"Client-Name":this.lava.options.clientName};void 0!==this.lava.options.resumeConfig&&(e["Resume-Key"]=this.lava.options.resumeConfig.key),this.socket=new ws_1.default(`ws${this.options.secure?"s":""}://${this.options.url}/`,{headers:e}),this.socket.once("upgrade",e=>{e=e.headers["session-resumed"];this.resumed="true"===e}),this.socket.once("open",this.open.bind(this)),this.socket.once("close",this.close.bind(this)),this.socket.on("error",this.error.bind(this)),this.socket.on("message",this.message.bind(this))}}destroy(){this.connected&&(this.socket.close(1e3,"destroy"),this.socket.removeAllListeners(),delete this.socket,this.reconnectAttempts=1,this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.emit("destroy"))}send(o){return new Promise((t,s)=>{if(!this.connected)return t(!1);const e=JSON.stringify(o);if(!o||!e.startsWith("{"))return t(!1);this.socket?.send(e,e=>{e?s(e):t(!0)})})}configResume(){this.lava.options.resumeConfig&&this.send({op:utils_1.OpCodes.ConfigResume,key:this.lava.options.resumeConfig.key,timeout:this.lava.options.resumeConfig.timeout})}reconnect(){this.reconnectTimeout=setTimeout(()=>this.reconnectAttempts>=this.options.retryAmount?(this.error(new Error(`Unable to reconnect after ${this.options.retryAmount} attempts`)),this.destroy()):(this.socket?.removeAllListeners(),delete this.socket,this.emit("reconnect"),this.connect(),void this.reconnectAttempts++),this.options.retryDelay)}open(){this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.connected=!0,this.configResume(),this.emit("connect")}close(e,t){this.connected=!1,this.emit("disconnect",{code:e,reason:t}),1e3===e&&"destroy"===t||this.reconnect()}error(e){this.emit("error",e)}message(e){Array.isArray(e)?e=Buffer.concat(e):e instanceof ArrayBuffer&&(e=Buffer.from(e));var t=JSON.parse(e.toString());if(t.op)switch(this.emit("raw",t),t.op){case"stats":this.stats={players:t.players,playingPlayers:t.playingPlayers,uptime:t.uptime,memory:t.memory,cpu:t.cpu,lastUpdated:Date.now(),frameStats:t.frameStats};break;case"playerUpdate":this.emit("playerUpdate",t.guildId,t.state);break;case"event":this.emit("event",t);break;default:this.error(new Error(`Unexpected op '${t.op}' with data: `+e.toString()))}}};LerefNodes=__decorate([constructs_1.constructNode()],LerefNodes),exports.LerefNodes=LerefNodes;