encodePacket.browser.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.encodePacket = exports.encodePacketToBinary = void 0;
  4. const commons_js_1 = require("./commons.js");
  5. const withNativeBlob = typeof Blob === "function" ||
  6. (typeof Blob !== "undefined" &&
  7. Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
  8. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  9. // ArrayBuffer.isView method is not defined in IE10
  10. const isView = obj => {
  11. return typeof ArrayBuffer.isView === "function"
  12. ? ArrayBuffer.isView(obj)
  13. : obj && obj.buffer instanceof ArrayBuffer;
  14. };
  15. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  16. if (withNativeBlob && data instanceof Blob) {
  17. if (supportsBinary) {
  18. return callback(data);
  19. }
  20. else {
  21. return encodeBlobAsBase64(data, callback);
  22. }
  23. }
  24. else if (withNativeArrayBuffer &&
  25. (data instanceof ArrayBuffer || isView(data))) {
  26. if (supportsBinary) {
  27. return callback(data);
  28. }
  29. else {
  30. return encodeBlobAsBase64(new Blob([data]), callback);
  31. }
  32. }
  33. // plain string
  34. return callback(commons_js_1.PACKET_TYPES[type] + (data || ""));
  35. };
  36. exports.encodePacket = encodePacket;
  37. const encodeBlobAsBase64 = (data, callback) => {
  38. const fileReader = new FileReader();
  39. fileReader.onload = function () {
  40. const content = fileReader.result.split(",")[1];
  41. callback("b" + (content || ""));
  42. };
  43. return fileReader.readAsDataURL(data);
  44. };
  45. function toArray(data) {
  46. if (data instanceof Uint8Array) {
  47. return data;
  48. }
  49. else if (data instanceof ArrayBuffer) {
  50. return new Uint8Array(data);
  51. }
  52. else {
  53. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  54. }
  55. }
  56. let TEXT_ENCODER;
  57. function encodePacketToBinary(packet, callback) {
  58. if (withNativeBlob && packet.data instanceof Blob) {
  59. return packet.data
  60. .arrayBuffer()
  61. .then(toArray)
  62. .then(callback);
  63. }
  64. else if (withNativeArrayBuffer &&
  65. (packet.data instanceof ArrayBuffer || isView(packet.data))) {
  66. return callback(toArray(packet.data));
  67. }
  68. encodePacket(packet, false, encoded => {
  69. if (!TEXT_ENCODER) {
  70. TEXT_ENCODER = new TextEncoder();
  71. }
  72. callback(TEXT_ENCODER.encode(encoded));
  73. });
  74. }
  75. exports.encodePacketToBinary = encodePacketToBinary;