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