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