1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | const commons_js_1 = require("./commons.js");
|
---|
4 | const base64_arraybuffer_1 = require("base64-arraybuffer");
|
---|
5 | const withNativeArrayBuffer = typeof ArrayBuffer === "function";
|
---|
6 | const decodePacket = (encodedPacket, binaryType) => {
|
---|
7 | if (typeof encodedPacket !== "string") {
|
---|
8 | return {
|
---|
9 | type: "message",
|
---|
10 | data: mapBinary(encodedPacket, binaryType)
|
---|
11 | };
|
---|
12 | }
|
---|
13 | const type = encodedPacket.charAt(0);
|
---|
14 | if (type === "b") {
|
---|
15 | return {
|
---|
16 | type: "message",
|
---|
17 | data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
|
---|
18 | };
|
---|
19 | }
|
---|
20 | const packetType = commons_js_1.PACKET_TYPES_REVERSE[type];
|
---|
21 | if (!packetType) {
|
---|
22 | return commons_js_1.ERROR_PACKET;
|
---|
23 | }
|
---|
24 | return encodedPacket.length > 1
|
---|
25 | ? {
|
---|
26 | type: commons_js_1.PACKET_TYPES_REVERSE[type],
|
---|
27 | data: encodedPacket.substring(1)
|
---|
28 | }
|
---|
29 | : {
|
---|
30 | type: commons_js_1.PACKET_TYPES_REVERSE[type]
|
---|
31 | };
|
---|
32 | };
|
---|
33 | const decodeBase64Packet = (data, binaryType) => {
|
---|
34 | if (withNativeArrayBuffer) {
|
---|
35 | const decoded = (0, base64_arraybuffer_1.decode)(data);
|
---|
36 | return mapBinary(decoded, binaryType);
|
---|
37 | }
|
---|
38 | else {
|
---|
39 | return { base64: true, data }; // fallback for old browsers
|
---|
40 | }
|
---|
41 | };
|
---|
42 | const mapBinary = (data, binaryType) => {
|
---|
43 | switch (binaryType) {
|
---|
44 | case "blob":
|
---|
45 | return data instanceof ArrayBuffer ? new Blob([data]) : data;
|
---|
46 | case "arraybuffer":
|
---|
47 | default:
|
---|
48 | return data; // assuming the data is already an ArrayBuffer
|
---|
49 | }
|
---|
50 | };
|
---|
51 | exports.default = decodePacket;
|
---|