-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtelemetrydeck.js
187 lines (155 loc) · 5.18 KB
/
telemetrydeck.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { randomString } from './utils/random-string.js';
import { sha256 } from './utils/sha256.js';
import { Store } from './utils/store.js';
import { version } from './utils/version.js';
/**
* @typedef {Object} TelemetryDeckOptions
*
* @property {string} appID the app ID to send telemetry data to
* @property {string} clientUser the clientUser ID to send telemetry data to
* @property {string} [target] the target URL to send telemetry data to
* @property {string} [sessionID] An optional session ID to include in each signal
* @property {string} [salt] A salt to use when hashing the clientUser ID
* @property {boolean} [testMode] If "true", signals will be marked as test signals and only show up in Test Mode in the Dashbaord
* @property {Store} [store] A store to use for queueing signals
* @property {Function} [subtleCrypto] Used for providing an alternative implementation of SubtleCrypto where no browser is available. Expects a class providing a `.digest(method, value)` method.
*/
/**
* @typedef {Object.<string, any>} TelemetryDeckPayload
*/
export default class TelemetryDeck {
appID = '';
clientUser = '';
salt = '';
target = 'https://nom.telemetrydeck.com/v2/';
testMode = false;
/**
*
* @param {TelemetryDeckOptions} options
*/
constructor(options = {}) {
const { target, appID, clientUser, sessionID, salt, testMode, store, subtleCrypto } = options;
if (!appID) {
throw new Error('appID is required');
}
this.store = store ?? new Store();
this.target = target ?? this.target;
this.appID = appID;
this.clientUser = clientUser;
this.sessionID = sessionID ?? randomString();
this.salt = salt ?? this.salt;
this.testMode = testMode ?? this.testMode;
this.subtleCrypto = subtleCrypto;
}
/**
* Send a TelemetryDeck signal
*
* @param {string} type the type of telemetry data to send
* @param {TelemetryDeckPayload} [payload] custom payload to be stored with each signal
* @param {TelemetryDeckOptions} [options]
* @returns <Promise<Response>> a promise with the response from the server, echoing the sent data
*/
async signal(type, payload, options) {
const body = await this._build(type, payload, options);
return this._post([body]);
}
/**
* Enqueue a signal to be sent to TelemetryDeck later.
*
* Use flush() to send all queued signals.
*
* @param {string} type
* @param {TelemetryDeckPayload} [payload]
* @param {TelemetryDeckOptions} [options]
* @returns <Promise>
*/
async queue(type, payload, options) {
const receivedAt = new Date().toISOString();
const bodyPromise = this._build(type, payload, options, receivedAt);
return this.store.push(bodyPromise);
}
/**
* Send all queued signals to TelemetryDeck.
*
* Enqueue signals with queue().
*
* @returns <Promise<Response>> a promise with the response from the server, echoing the sent data
*/
async flush() {
const flushPromise = this._post(this.store.values());
this.store.clear();
return flushPromise;
}
_clientUserAndSalt = '';
_clientUserHashed = '';
async _hashedClientUser(clientUser, salt) {
if (clientUser + salt !== this._clientUserAndSalt) {
this._clientUserHashed = await sha256([clientUser, salt].join(''), this.subtleCrypto);
this._clientUserAndSalt = clientUser + salt;
}
return this._clientUserHashed;
}
async _build(type, payload, options, receivedAt) {
const { appID, testMode } = this;
let { clientUser, salt, sessionID } = this;
options = options ?? {};
clientUser = options.clientUser ?? clientUser;
salt = options.salt ?? salt;
sessionID = options.sessionID ?? sessionID;
if (!type) {
throw new Error(`TelemetryDeck: "type" is not set`);
}
if (!appID) {
throw new Error(`TelemetryDeck: "appID" is not set`);
}
if (!clientUser) {
throw new Error(`TelemetryDeck: "clientUser" is not set`);
}
clientUser = await this._hashedClientUser(clientUser, salt);
const body = {
clientUser,
sessionID,
appID,
type,
telemetryClientVersion: `JavaScriptSDK ${version}`,
};
if (receivedAt) {
body.receivedAt = receivedAt;
}
if (testMode) {
body.isTestMode = true;
}
return this._appendPayload(body, payload);
}
_appendPayload(body, payload) {
if (!payload || typeof payload !== 'object' || Object.keys(payload).length === 0) {
return body;
}
body.payload = {};
for (const [key, value] of Object.entries(payload ?? {})) {
if (key === 'floatValue') {
body.payload[key] = Number.parseFloat(value);
} else if (value instanceof Date) {
body.payload[key] = value.toISOString();
} else if (typeof value === 'string') {
body.payload[key] = value;
} else if (typeof value === 'object') {
body.payload[key] = JSON.stringify(value);
} else {
body.payload[key] = `${value}`;
}
}
return body;
}
_post(body) {
const { target } = this;
return fetch(target, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
}