(data: Uint8Array)
| 33 | }; |
| 34 | |
| 35 | export const decodeMessage = (data: Uint8Array): WSMessage => { |
| 36 | const type = data[0]; |
| 37 | const payload = data.slice(1); |
| 38 | switch (type) { |
| 39 | case 0x00: { |
| 40 | return { |
| 41 | type: "handshake", |
| 42 | version: 0, |
| 43 | model: 0, |
| 44 | }; |
| 45 | } |
| 46 | case 0x01: |
| 47 | return { |
| 48 | type: "audio", |
| 49 | data: payload, |
| 50 | }; |
| 51 | case 0x02: |
| 52 | return { |
| 53 | type: "text", |
| 54 | data: new TextDecoder().decode(payload), |
| 55 | }; |
| 56 | case 0x03: { |
| 57 | const action = Object.keys(CONTROL_MESSAGES_MAP).find( |
| 58 | key => CONTROL_MESSAGES_MAP[key as CONTROL_MESSAGE] === payload[0], |
| 59 | ) as CONTROL_MESSAGE | undefined; |
| 60 | |
| 61 | //TODO: log this and don't throw |
| 62 | if (!action) { |
| 63 | throw new Error("Unknown control message"); |
| 64 | } |
| 65 | return { |
| 66 | type: "control", |
| 67 | action, |
| 68 | }; |
| 69 | } |
| 70 | case 0x04: |
| 71 | return { |
| 72 | type: "metadata", |
| 73 | data: JSON.parse(new TextDecoder().decode(payload)), |
| 74 | } |
| 75 | case 0x05: |
| 76 | return { |
| 77 | type: "error", |
| 78 | data: new TextDecoder().decode(payload), |
| 79 | } |
| 80 | case 0x06: |
| 81 | return { |
| 82 | type: "ping", |
| 83 | } |
| 84 | default: { |
| 85 | console.log(type); |
| 86 | throw new Error("Unknown message type"); |
| 87 | } |
| 88 | } |
| 89 | }; |
no test coverage detected