encodePacket.js 954 B

123456789101112131415161718192021222324252627
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const commons_js_1 = require("./commons.js");
  4. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  5. if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
  6. const buffer = toBuffer(data);
  7. return callback(encodeBuffer(buffer, supportsBinary));
  8. }
  9. // plain string
  10. return callback(commons_js_1.PACKET_TYPES[type] + (data || ""));
  11. };
  12. const toBuffer = data => {
  13. if (Buffer.isBuffer(data)) {
  14. return data;
  15. }
  16. else if (data instanceof ArrayBuffer) {
  17. return Buffer.from(data);
  18. }
  19. else {
  20. return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  21. }
  22. };
  23. // only 'message' packets can contain binary, so the type prefix is not needed
  24. const encodeBuffer = (data, supportsBinary) => {
  25. return supportsBinary ? data : "b" + data.toString("base64");
  26. };
  27. exports.default = encodePacket;