|
| 1 | +const transformPayload = (payload) => |
| 2 | + Object.entries(payload).map((entry) => entry.join(':')); |
| 3 | + |
| 4 | +const assertOption = (options, key) => { |
| 5 | + if (!options[key]) { |
| 6 | + throw Error(`TelemetryDeck: options.${key} is not set`); |
| 7 | + } |
| 8 | +}; |
| 9 | + |
| 10 | +export default async function sendTelemetry(options, payload) { |
| 11 | + options = { |
| 12 | + host: 'https://nom.telemetrydeck.com', |
| 13 | + appID: null, |
| 14 | + userIdentifier: null, |
| 15 | + ...options, |
| 16 | + }; |
| 17 | + |
| 18 | + payload = { |
| 19 | + url: location.href, |
| 20 | + useragent: navigator.userAgent, |
| 21 | + locale: navigator.language, |
| 22 | + platform: navigator.userAgentData, |
| 23 | + vendor: navigator.vendor, |
| 24 | + ...payload, |
| 25 | + }; |
| 26 | + |
| 27 | + assertOption(options, 'appID'); |
| 28 | + assertOption(options, 'userIdentifier'); |
| 29 | + |
| 30 | + let { appID, userIdentifier } = options; |
| 31 | + |
| 32 | + userIdentifier = await sha256(userIdentifier); |
| 33 | + |
| 34 | + return fetch(`${options.host}/api/v1/apps/app/signals/multiple/`, { |
| 35 | + method: 'POST', |
| 36 | + mode: 'cors', |
| 37 | + headers: { |
| 38 | + 'Content-Type': 'application/json', |
| 39 | + }, |
| 40 | + body: JSON.stringify([ |
| 41 | + { |
| 42 | + appID: appID, |
| 43 | + clientUser: userIdentifier, |
| 44 | + sessionID: userIdentifier, |
| 45 | + telemetryClientVersion: '0.1.0', |
| 46 | + type: 'pageview', |
| 47 | + payload: transformPayload(payload), |
| 48 | + }, |
| 49 | + ]), |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +// https://stackoverflow.com/a/48161723/54547 |
| 54 | +async function sha256(message) { |
| 55 | + // encode as UTF-8 |
| 56 | + const msgBuffer = new TextEncoder().encode(message); |
| 57 | + |
| 58 | + // hash the message |
| 59 | + const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); |
| 60 | + |
| 61 | + // convert ArrayBuffer to Array |
| 62 | + const hashArray = Array.from(new Uint8Array(hashBuffer)); |
| 63 | + |
| 64 | + // convert bytes to hex string |
| 65 | + const hashHex = hashArray |
| 66 | + .map((b) => b.toString(16).padStart(2, '0')) |
| 67 | + .join(''); |
| 68 | + return hashHex; |
| 69 | +} |
0 commit comments