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