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