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