-
Notifications
You must be signed in to change notification settings - Fork 9
/
utils.ts
283 lines (234 loc) · 8.5 KB
/
utils.ts
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import type * as fsExtra from 'fs-extra';
import type * as path from 'path';
import type * as Mocha from 'mocha';
import * as Ajv from 'ajv';
const ajv = new Ajv();
import type { ConfigOptions, DeviceConfigOptions } from './types/ConfigOptions';
type PathType = typeof path;
class Utils {
private path?: PathType;
private fsExtra?: typeof fsExtra;
// We use a dynamic require to avoid an issue in the brightscript vscode extension
private require<T>(id: string): T {
return require(id) as T;
}
private getPath() {
if (!this.path) {
this.path = this.require<PathType>('path');
}
return this.path;
}
private getFsExtra() {
if (!this.fsExtra) {
this.fsExtra = this.require<typeof fsExtra>('fs-extra');
}
return this.fsExtra;
}
/** Provides a way to easily get a path to device files for external access */
public getDeviceFilesPath() {
return this.getPath().resolve(__dirname + '/../../device');
}
/** Provides a way to easily get a path to client files for external access */
public getClientFilesPath() {
return this.getPath().resolve(__dirname + '/../');
}
public parseJsonFile(filePath: string) {
return JSON.parse(this.getFsExtra().readFileSync(filePath, 'utf-8'));
}
public getMatchingDevices(config: ConfigOptions, deviceSelector: Record<string, any>): { [key: string]: DeviceConfigOptions} {
const matchingDevices = {};
config.RokuDevice.devices.forEach((device, index) => {
for (const key in deviceSelector) {
if (!device.properties) {
continue;
}
const requestedValue = deviceSelector[key];
if (device.properties[key] !== requestedValue) continue;
}
matchingDevices[index] = device;
});
return matchingDevices;
}
public getConfigFromConfigFile(configFilePath = 'rta-config.json') {
const config = this.getConfigFromConfigFileCore(configFilePath);
this.validateRTAConfigSchema(config);
return config;
}
private getConfigFromConfigFileCore(configFilePath = 'rta-config.json', parentConfigPaths: string[] = []) {
configFilePath = this.getPath().resolve(configFilePath);
let config: ConfigOptions;
try {
config = this.parseJsonFile(configFilePath);
} catch(e) {
throw utils.makeError('NoConfigFound', 'Config could not be found or parsed correctly.');
}
parentConfigPaths.push(configFilePath);
if (config.extends) {
const baseConfigFilePath = this.getPath().resolve(config.extends);
if (parentConfigPaths.includes(baseConfigFilePath)) {
throw new Error(`Circular dependency detected. '${baseConfigFilePath}' has already been included`);
}
const baseConfig = this.getConfigFromConfigFileCore(baseConfigFilePath, parentConfigPaths);
for (const section of ['RokuDevice', 'ECP', 'OnDeviceComponent', 'NetworkProxy', 'NetworkProxy']) {
// Override every field that was specified in the child
for (const key in config[section]) {
if (!baseConfig[section]) {
baseConfig[section] = {};
}
baseConfig[section][key] = config[section][key];
}
}
config = baseConfig;
}
return config;
}
/** Helper for setting up process.env from a config */
setupEnvironmentFromConfig(config: ConfigOptions, deviceSelector?: Record<string, any> | number) {
if (deviceSelector === undefined) {
deviceSelector = config.RokuDevice.deviceIndex ?? 0;
}
if (typeof deviceSelector === 'number') {
config.RokuDevice.deviceIndex = deviceSelector;
} else {
const matchingDevices = this.getMatchingDevices(config, deviceSelector);
const keys = Object.keys(matchingDevices);
if (keys.length === 0) {
throw utils.makeError('NoMatchingDevicesFound', 'No devices matched the device selection criteria');
}
config.RokuDevice.deviceIndex = parseInt(keys[0]);
}
process.env.rtaConfig = JSON.stringify(config);
}
/** Helper for setting up process.env from a config file */
public setupEnvironmentFromConfigFile(configFilePath = 'rta-config.json', deviceSelector: Record<string, any> | number | undefined = undefined) {
const config = this.getConfigFromConfigFile(configFilePath);
this.setupEnvironmentFromConfig(config, deviceSelector);
}
/** Validates the ConfigOptions schema the current class is using
* @param sectionsToValidate - if non empty array will only validate the sections provided instead of the whole schema
*/
public validateRTAConfigSchema(config: any) {
const schema = utils.parseJsonFile(__dirname + '/../rta-config.schema.json');
if (!ajv.validate(schema, config)) {
const error = ajv.errors?.[0];
throw utils.makeError('ConfigValidationError', `${error?.dataPath} ${error?.message}`);
}
}
public getConfigFromEnvironmentOrConfigFile(configFilePath = 'rta-config.json') {
let config = this.getOptionalConfigFromEnvironment();
if (!config) {
config = this.getConfigFromConfigFile(configFilePath);
}
return config;
}
public getConfigFromEnvironment() {
const config = this.getOptionalConfigFromEnvironment();
if (!config) {
throw this.makeError('MissingEnvironmentError', 'Did not contain config at "process.env.rtaConfig"');
}
return config;
}
public getOptionalConfigFromEnvironment() {
if (!process.env.rtaConfig) return undefined;
const config: ConfigOptions = JSON.parse(process.env.rtaConfig);
if (config) {
this.validateRTAConfigSchema(config);
}
return config;
}
public sleep(milliseconds: number) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
public async promiseTimeout<T>(promise: Promise<T>, milliseconds: number, message?: string) {
let timeout;
const timeoutPromise = new Promise<T>((resolve, reject) => {
timeout = setTimeout(() => {
if (!message) {
message = 'Timed out after ' + milliseconds + 'ms.';
}
reject(this.makeError('Timeout', message));
}, milliseconds);
});
// Returns a race between our timeout and the passed in promise
try {
return await Promise.race([
promise,
timeoutPromise
]);
} finally {
clearTimeout(timeout);
}
}
public makeError(name: string, message: string) {
const error = new Error(message);
error.name = name;
return error;
}
public getTestTitlePath(contextOrSuite: Mocha.Context | Mocha.Suite, sanitize = true) {
let ctx: Mocha.Context;
if (contextOrSuite.constructor.name === 'Context') {
ctx = contextOrSuite as Mocha.Context;
} else if (contextOrSuite.constructor.name === 'Suite') {
ctx = contextOrSuite.ctx as Mocha.Context;
} else {
throw new Error('Neither Mocha.Context or Mocha.Suite passed in');
}
let test: Mocha.Runnable;
if (ctx.currentTest?.constructor.name === 'Test') {
test = ctx.currentTest;
} else if (ctx.test?.constructor.name === 'Test') {
test = ctx.test;
} else {
throw new Error('Mocha.Context did not contain test. At least surrounding Mocha.Suite must use non arrow function');
}
const pathParts = test.titlePath();
if (sanitize) {
for (const [index, pathPart] of pathParts.entries()) {
if (sanitize) {
pathParts[index] = pathPart.replace(/[^a-zA-Z0-9_]/g, '_');
} else {
pathParts[index] = pathPart;
}
}
}
return pathParts;
}
public generateFileNameForTest(contextOrSuite: Mocha.Context | Mocha.Suite, extension: string, postFix = '', separator = '_') {
const titlePath = this.getTestTitlePath(contextOrSuite);
return titlePath.join(separator) + postFix + `.${extension}`;
}
public async ensureDirExistForFilePath(filePath: string) {
await this.getFsExtra().ensureDir(this.getPath().dirname(filePath));
}
public randomStringGenerator(length = 7) {
const p = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return [...Array(length)].reduce((a) => a + p[~~(Math.random() * p.length)], '');
}
public addRandomPostfix(message: string, length = 2) {
return `${message}-${this.randomStringGenerator(length)}`;
}
public isObjectWithProperty<Y extends PropertyKey>
(obj: any, prop: Y): obj is Record<Y, unknown> {
if (obj === null || typeof obj !== 'object') {
return false;
}
// eslint-disable-next-line no-prototype-builtins
return obj.hasOwnProperty(prop);
}
public convertValueToNumber(value: string | number | undefined, defaultValue = 0) {
if (typeof value === 'number') {
return value;
} else if (typeof value === 'string') {
return +value;
}
return defaultValue;
}
public lpad(value, padLength = 2, padCharacter = '0') {
return value.toString().padStart(padLength, padCharacter);
}
public randomInteger(max = 2147483647, min = 0) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
}
const utils = new Utils();
export { utils };