/** * Utility Class to construct a packet conforming to Minecraft's * protocol. All data types are BE except VarInt and VarLong. * * @see https://wiki.vg/Protocol */ export class ServerBoundPacket { private buffer: number[] protected constructor() { this.buffer = [] } public static build(): ServerBoundPacket { return new ServerBoundPacket() } /** * Packet is prefixed with its data length as a VarInt. * * @see https://wiki.vg/Protocol#Packet_format */ public toBuffer(): Buffer { const finalizedPacket = new ServerBoundPacket() finalizedPacket.writeVarInt(this.buffer.length) finalizedPacket.writeBytes(...this.buffer) return Buffer.from(finalizedPacket.buffer) } public writeBytes(...bytes: number[]): ServerBoundPacket { this.buffer.push(...bytes) return this } /** * @see https://wiki.vg/Protocol#VarInt_and_VarLong */ public writeVarInt(value: number): ServerBoundPacket { do { let temp = value & 0b01111111 value >>>= 7 if (value != 0) { temp |= 0b10000000 } this.writeBytes(temp) } while (value != 0) return this } /** * Strings are prefixed with their length as a VarInt. * * @see https://wiki.vg/Protocol#Data_types */ public writeString(string: string): ServerBoundPacket { this.writeVarInt(string.length) for (let i=0; i 5) { throw new Error('VarInt is too big') } } while ((read & 0b10000000) != 0) return result } public readString(): string { const length = this.readVarInt() const data = this.readBytes(length) let value = '' for (let i=0; i>>= 7 size++ } while (value != 0) return size } }