encodePacket.browser.js 2.4 KB

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