Commit | Line | Data |
---|---|---|
c37528f1 | 1 | import crypto from 'crypto'; |
8114d10e | 2 | |
5e3cb728 JB |
3 | import { WebSocketCloseEventStatusString } from '../types/WebSocket'; |
4 | ||
3f40bc9c | 5 | export default class Utils { |
d5bd1c00 JB |
6 | private constructor() { |
7 | // This is intentional | |
8 | } | |
9 | ||
0f16a662 | 10 | public static logPrefix(prefixString = ''): string { |
147d0e0f JB |
11 | return new Date().toLocaleString() + prefixString; |
12 | } | |
13 | ||
0f16a662 | 14 | public static generateUUID(): string { |
03eacbe5 JB |
15 | return crypto.randomUUID(); |
16 | } | |
17 | ||
18 | public static validateUUID(uuid: string): boolean { | |
8bd02502 JB |
19 | return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test( |
20 | uuid | |
21 | ); | |
7dde0b73 JB |
22 | } |
23 | ||
0f16a662 | 24 | public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> { |
5f8a4fd6 | 25 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
7dde0b73 JB |
26 | } |
27 | ||
d7d1db72 JB |
28 | public static formatDurationMilliSeconds(duration: number): string { |
29 | duration = Utils.convertToInt(duration); | |
30 | const hours = Math.floor(duration / (3600 * 1000)); | |
e7aeea18 JB |
31 | const minutes = Math.floor((duration / 1000 - hours * 3600) / 60); |
32 | const seconds = duration / 1000 - hours * 3600 - minutes * 60; | |
a3868ec4 JB |
33 | let hoursStr = hours.toString(); |
34 | let minutesStr = minutes.toString(); | |
35 | let secondsStr = seconds.toString(); | |
d7d1db72 JB |
36 | |
37 | if (hours < 10) { | |
38 | hoursStr = '0' + hours.toString(); | |
39 | } | |
40 | if (minutes < 10) { | |
41 | minutesStr = '0' + minutes.toString(); | |
42 | } | |
43 | if (seconds < 10) { | |
b322b8b4 | 44 | secondsStr = '0' + seconds.toString(); |
d7d1db72 | 45 | } |
b322b8b4 | 46 | return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6); |
9ac86a7e JB |
47 | } |
48 | ||
d7d1db72 JB |
49 | public static formatDurationSeconds(duration: number): string { |
50 | return Utils.formatDurationMilliSeconds(duration * 1000); | |
7dde0b73 JB |
51 | } |
52 | ||
d439da5c JB |
53 | public static convertToDate(value: unknown): Date | null | undefined { |
54 | if (Utils.isNullOrUndefined(value)) { | |
55 | return value as null | undefined; | |
56 | } | |
57 | if (value instanceof Date) { | |
58 | return value; | |
560bcf5b | 59 | } |
d439da5c JB |
60 | if (Utils.isString(value) || typeof value === 'number') { |
61 | return new Date(value as string | number); | |
7dde0b73 | 62 | } |
d439da5c | 63 | return null; |
7dde0b73 JB |
64 | } |
65 | ||
0f16a662 | 66 | public static convertToInt(value: unknown): number { |
72766a82 | 67 | if (!value) { |
7dde0b73 JB |
68 | return 0; |
69 | } | |
69bafbed | 70 | let changedValue: number = value as number; |
72766a82 | 71 | if (Number.isSafeInteger(value)) { |
95926c9b | 72 | return value as number; |
72766a82 | 73 | } |
df645d8f JB |
74 | if (typeof value === 'number') { |
75 | changedValue = Math.trunc(value); | |
76 | } | |
3df786f9 JB |
77 | if (Utils.isString(value)) { |
78 | changedValue = parseInt(value as string); | |
79 | } | |
72766a82 | 80 | return changedValue; |
7dde0b73 JB |
81 | } |
82 | ||
0f16a662 | 83 | public static convertToFloat(value: unknown): number { |
72766a82 | 84 | if (!value) { |
7dde0b73 JB |
85 | return 0; |
86 | } | |
69bafbed | 87 | let changedValue: number = value as number; |
087a502d | 88 | if (Utils.isString(value)) { |
73d09045 | 89 | changedValue = parseFloat(value as string); |
7dde0b73 | 90 | } |
72766a82 | 91 | return changedValue; |
7dde0b73 JB |
92 | } |
93 | ||
0f16a662 | 94 | public static convertToBoolean(value: unknown): boolean { |
a6e68f34 | 95 | let result = false; |
a6e68f34 JB |
96 | if (value) { |
97 | // Check the type | |
98 | if (typeof value === 'boolean') { | |
a6e68f34 | 99 | result = value; |
df645d8f JB |
100 | } else if ( |
101 | Utils.isString(value) && | |
102 | ((value as string).toLowerCase() === 'true' || value === '1') | |
103 | ) { | |
104 | result = true; | |
105 | } else if (typeof value === 'number' && value === 1) { | |
106 | result = true; | |
a6e68f34 JB |
107 | } |
108 | } | |
109 | return result; | |
110 | } | |
111 | ||
b5e5892d | 112 | public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number { |
b3aa9f53 | 113 | if (max < min || max < 0 || min < 0) { |
b322b8b4 JB |
114 | throw new RangeError('Invalid interval'); |
115 | } | |
fd00fa2e | 116 | const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; |
e7aeea18 | 117 | const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1; |
fd00fa2e | 118 | return sign * (randomPositiveFloat * (max - min) + min); |
560bcf5b JB |
119 | } |
120 | ||
b5e5892d | 121 | public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number { |
b3aa9f53 | 122 | if (max < min || max < 0 || min < 0) { |
a3868ec4 JB |
123 | throw new RangeError('Invalid interval'); |
124 | } | |
fd00fa2e | 125 | max = Math.floor(max); |
1f86b121 | 126 | if (!Utils.isNullOrUndefined(min) && min !== 0) { |
fd00fa2e | 127 | min = Math.ceil(min); |
c37528f1 | 128 | return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; |
7dde0b73 | 129 | } |
c37528f1 | 130 | return Math.floor(Utils.secureRandom() * (max + 1)); |
560bcf5b JB |
131 | } |
132 | ||
0f16a662 | 133 | public static roundTo(numberValue: number, scale: number): number { |
ad3de6c4 | 134 | const roundPower = Math.pow(10, scale); |
035742f7 | 135 | return Math.round(numberValue * roundPower) / roundPower; |
560bcf5b JB |
136 | } |
137 | ||
0f16a662 | 138 | public static truncTo(numberValue: number, scale: number): number { |
6d3a11a0 | 139 | const truncPower = Math.pow(10, scale); |
035742f7 | 140 | return Math.trunc(numberValue * truncPower) / truncPower; |
6d3a11a0 JB |
141 | } |
142 | ||
b5e5892d | 143 | public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number { |
560bcf5b JB |
144 | if (min) { |
145 | return Utils.roundTo(Utils.getRandomFloat(max, min), scale); | |
146 | } | |
147 | return Utils.roundTo(Utils.getRandomFloat(max), scale); | |
7dde0b73 JB |
148 | } |
149 | ||
e7aeea18 JB |
150 | public static getRandomFloatFluctuatedRounded( |
151 | staticValue: number, | |
152 | fluctuationPercent: number, | |
153 | scale = 2 | |
154 | ): number { | |
9ccca265 JB |
155 | if (fluctuationPercent === 0) { |
156 | return Utils.roundTo(staticValue, scale); | |
157 | } | |
97ef739c | 158 | const fluctuationRatio = fluctuationPercent / 100; |
e7aeea18 JB |
159 | return Utils.getRandomFloatRounded( |
160 | staticValue * (1 + fluctuationRatio), | |
161 | staticValue * (1 - fluctuationRatio), | |
162 | scale | |
163 | ); | |
9ccca265 JB |
164 | } |
165 | ||
0f16a662 | 166 | public static cloneObject<T>(object: T): T { |
e56aa9a4 | 167 | return JSON.parse(JSON.stringify(object)) as T; |
2e6f5966 | 168 | } |
facd8ebd | 169 | |
0f16a662 | 170 | public static isIterable<T>(obj: T): boolean { |
7558b3a6 | 171 | return obj ? typeof obj[Symbol.iterator] === 'function' : false; |
67e9cccf JB |
172 | } |
173 | ||
0f16a662 | 174 | public static isString(value: unknown): boolean { |
560bcf5b JB |
175 | return typeof value === 'string'; |
176 | } | |
177 | ||
e8191622 | 178 | public static isEmptyString(value: unknown): boolean { |
87f82a94 | 179 | return Utils.isString(value) && (value as string).trim().length === 0; |
e8191622 JB |
180 | } |
181 | ||
0f16a662 | 182 | public static isUndefined(value: unknown): boolean { |
ead548f2 JB |
183 | return typeof value === 'undefined'; |
184 | } | |
185 | ||
0f16a662 | 186 | public static isNullOrUndefined(value: unknown): boolean { |
7558b3a6 JB |
187 | // eslint-disable-next-line eqeqeq, no-eq-null |
188 | return value == null ? true : false; | |
facd8ebd | 189 | } |
4a56deef | 190 | |
45999aab | 191 | public static isEmptyArray(object: unknown | unknown[]): boolean { |
a2111e8d | 192 | if (!Array.isArray(object)) { |
30e27491 | 193 | return true; |
fd1ee77c | 194 | } |
45999aab | 195 | if (object.length > 0) { |
4a56deef JB |
196 | return false; |
197 | } | |
198 | return true; | |
199 | } | |
7abfea5f | 200 | |
94ec7e96 | 201 | public static isEmptyObject(obj: object): boolean { |
5e5ba121 | 202 | if (obj?.constructor !== Object) { |
d20581ee JB |
203 | return false; |
204 | } | |
87f82a94 JB |
205 | // Iterates over the keys of an object, if |
206 | // any exist, return false. | |
207 | for (const _ in obj) { | |
208 | return false; | |
209 | } | |
210 | return true; | |
7abfea5f | 211 | } |
7ec46a9a | 212 | |
e7aeea18 JB |
213 | public static insertAt = (str: string, subStr: string, pos: number): string => |
214 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; | |
032d6efc JB |
215 | |
216 | /** | |
81797102 JB |
217 | * @param [retryNumber=0] |
218 | * @returns delay in milliseconds | |
032d6efc | 219 | */ |
0f16a662 | 220 | public static exponentialDelay(retryNumber = 0): number { |
032d6efc | 221 | const delay = Math.pow(2, retryNumber) * 100; |
c37528f1 | 222 | const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay |
032d6efc JB |
223 | return delay + randomSum; |
224 | } | |
32a1eb7a | 225 | |
6d9abcc2 | 226 | public static async promiseWithTimeout<T>( |
e7aeea18 JB |
227 | promise: Promise<T>, |
228 | timeoutMs: number, | |
229 | timeoutError: Error, | |
230 | timeoutCallback: () => void = () => { | |
231 | /* This is intentional */ | |
232 | } | |
6d9abcc2 JB |
233 | ): Promise<T> { |
234 | // Create a timeout promise that rejects in timeout milliseconds | |
235 | const timeoutPromise = new Promise<never>((_, reject) => { | |
236 | setTimeout(() => { | |
ed0f8380 | 237 | timeoutCallback(); |
6d9abcc2 JB |
238 | reject(timeoutError); |
239 | }, timeoutMs); | |
240 | }); | |
241 | ||
242 | // Returns a race between timeout promise and the passed promise | |
243 | return Promise.race<T>([promise, timeoutPromise]); | |
244 | } | |
245 | ||
c37528f1 | 246 | /** |
0f16a662 | 247 | * Generate a cryptographically secure random number in the [0,1[ range |
c37528f1 JB |
248 | * |
249 | * @returns | |
250 | */ | |
0f16a662 | 251 | public static secureRandom(): number { |
c37528f1 JB |
252 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
253 | } | |
fe791818 JB |
254 | |
255 | public static JSONStringifyWithMapSupport( | |
256 | obj: Record<string, unknown> | Record<string, unknown>[], | |
257 | space?: number | |
258 | ): string { | |
259 | return JSON.stringify( | |
260 | obj, | |
261 | (key, value: Record<string, unknown>) => { | |
262 | if (value instanceof Map) { | |
263 | return { | |
264 | dataType: 'Map', | |
265 | value: [...value], | |
266 | }; | |
267 | } | |
268 | return value; | |
269 | }, | |
270 | space | |
271 | ); | |
272 | } | |
5e3cb728 JB |
273 | |
274 | /** | |
275 | * Convert websocket error code to human readable string message | |
276 | * | |
277 | * @param code websocket error code | |
278 | * @returns human readable string message | |
279 | */ | |
280 | public static getWebSocketCloseEventStatusString(code: number): string { | |
281 | if (code >= 0 && code <= 999) { | |
282 | return '(Unused)'; | |
283 | } else if (code >= 1016) { | |
284 | if (code <= 1999) { | |
285 | return '(For WebSocket standard)'; | |
286 | } else if (code <= 2999) { | |
287 | return '(For WebSocket extensions)'; | |
288 | } else if (code <= 3999) { | |
289 | return '(For libraries and frameworks)'; | |
290 | } else if (code <= 4999) { | |
291 | return '(For applications)'; | |
292 | } | |
293 | } | |
294 | if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) { | |
295 | return WebSocketCloseEventStatusString[code] as string; | |
296 | } | |
297 | return '(Unknown)'; | |
298 | } | |
7dde0b73 | 299 | } |