UNPKG

@sangaman/xud

Version:
62 lines 2.57 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_js_1 = __importDefault(require("crypto-js")); const md5_1 = __importDefault(require("crypto-js/md5")); const v1_1 = __importDefault(require("uuid/v1")); function isPacketInterface(obj) { if (obj) { const header = obj.header; return header !== undefined && typeof header.id === 'string'; } return false; } var PacketDirection; (function (PacketDirection) { /** A packet that is pushed to a peer without expecting any response. */ PacketDirection[PacketDirection["UNILATERAL"] = 0] = "UNILATERAL"; /** A packet requesting a response. */ PacketDirection[PacketDirection["REQUEST"] = 1] = "REQUEST"; /** A packet that is sent in response to an incoming packet. */ PacketDirection[PacketDirection["RESPONSE"] = 2] = "RESPONSE"; })(PacketDirection || (PacketDirection = {})); exports.PacketDirection = PacketDirection; class Packet { constructor(bodyOrPacket, reqId) { if (isPacketInterface(bodyOrPacket)) { // we are deserializing a received packet from a raw JSON string delete bodyOrPacket.header.type; // deleting type from header because it's being used only for the wire protocol this.header = bodyOrPacket.header; if (bodyOrPacket.body) { this.body = bodyOrPacket.body; } } else { // we are creating a new outgoing packet from a body this.header = { id: v1_1.default() }; if (reqId) { this.header.reqId = reqId; } if (bodyOrPacket) { this.body = bodyOrPacket; this.header.hash = md5_1.default(JSON.stringify(bodyOrPacket)).toString(crypto_js_1.default.enc.Base64); } } } /** * Serialize this packet to JSON. * @returns JSON string representing the packet */ toRaw() { const { body } = this; // explicitly set the type on the header before serializing const header = Object.assign({}, this.header, { type: this.type }); return body ? JSON.stringify({ header, body }) : JSON.stringify({ header }); } } /** Wire protocol delimiter. */ Packet.PROTOCOL_DELIMITER = 'ↂ₿ↂ'; exports.default = Packet; //# sourceMappingURL=Packet.js.map