encodePacket.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.encodePacketToBinary = exports.encodePacket = void 0;
  4. const commons_js_1 = require("./commons.js");
  5. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  6. if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
  7. return callback(supportsBinary ? data : "b" + toBuffer(data, true).toString("base64"));
  8. }
  9. // plain string
  10. return callback(commons_js_1.PACKET_TYPES[type] + (data || ""));
  11. };
  12. exports.encodePacket = encodePacket;
  13. const toBuffer = (data, forceBufferConversion) => {
  14. if (Buffer.isBuffer(data) ||
  15. (data instanceof Uint8Array && !forceBufferConversion)) {
  16. return data;
  17. }
  18. else if (data instanceof ArrayBuffer) {
  19. return Buffer.from(data);
  20. }
  21. else {
  22. return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  23. }
  24. };
  25. let TEXT_ENCODER;
  26. function encodePacketToBinary(packet, callback) {
  27. if (packet.data instanceof ArrayBuffer || ArrayBuffer.isView(packet.data)) {
  28. return callback(toBuffer(packet.data, false));
  29. }
  30. (0, exports.encodePacket)(packet, true, encoded => {
  31. if (!TEXT_ENCODER) {
  32. // lazily created for compatibility with Node.js 10
  33. TEXT_ENCODER = new TextEncoder();
  34. }
  35. callback(TEXT_ENCODER.encode(encoded));
  36. });
  37. }
  38. exports.encodePacketToBinary = encodePacketToBinary;