UNPKG

@4players/odin

Version:

A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects

46 lines (45 loc) 1.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseJwt = parseJwt; exports.valueToUint8Array = valueToUint8Array; exports.uint8ArrayToValue = uint8ArrayToValue; function parseJwt(token) { const base64Url = token.split('.')[1]; const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); const payload = decodeURIComponent(atob(base64) .split('') .map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join('')); return JSON.parse(payload); } /** * Encodes a value or an object with the help of JSON.stringify to an Uint8Array. * * @param value Value or object to encode * @returns The Uint8Array encoded value */ function valueToUint8Array(value) { if (typeof value === 'undefined' || value === null) { throw new Error('Error when converting to uint8array because the value is null or undefined'); } return new TextEncoder().encode(JSON.stringify(value)); } /** * Decodes a Uint8Array. * * @param bytes Byte array to decode * @returns The decoded value or undefined on error */ function uint8ArrayToValue(bytes) { if (bytes.length === 0) { return {}; } try { return JSON.parse(new TextDecoder().decode(bytes)); } catch (e) { throw new Error('Error when decoding uInt8Array.'); } }