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