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