| 1 | import { getRandomValues, randomBytes, randomInt, randomUUID } from 'node:crypto' |
| 2 | import { env, nextTick } from 'node:process' |
| 3 | |
| 4 | import { |
| 5 | formatDuration, |
| 6 | hoursToMinutes, |
| 7 | hoursToSeconds, |
| 8 | isDate, |
| 9 | millisecondsToHours, |
| 10 | millisecondsToMinutes, |
| 11 | millisecondsToSeconds, |
| 12 | minutesToSeconds, |
| 13 | secondsToMilliseconds |
| 14 | } from 'date-fns' |
| 15 | |
| 16 | import { Constants } from './Constants.js' |
| 17 | import { |
| 18 | type EmptyObject, |
| 19 | type ProtocolResponse, |
| 20 | type TimestampedData, |
| 21 | WebSocketCloseEventStatusString |
| 22 | } from '../types/index.js' |
| 23 | |
| 24 | export const logPrefix = (prefixString = ''): string => { |
| 25 | return `${new Date().toLocaleString()}${prefixString}` |
| 26 | } |
| 27 | |
| 28 | export const generateUUID = (): string => { |
| 29 | return randomUUID() |
| 30 | } |
| 31 | |
| 32 | export const validateUUID = (uuid: string): boolean => { |
| 33 | 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(uuid) |
| 34 | } |
| 35 | |
| 36 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
| 37 | return await new Promise<NodeJS.Timeout>(resolve => |
| 38 | setTimeout(resolve as () => void, milliSeconds) |
| 39 | ) |
| 40 | } |
| 41 | |
| 42 | export const formatDurationMilliSeconds = (duration: number): string => { |
| 43 | duration = convertToInt(duration) |
| 44 | if (duration < 0) { |
| 45 | throw new RangeError('Duration cannot be negative') |
| 46 | } |
| 47 | const days = Math.floor(duration / (24 * 3600 * 1000)) |
| 48 | const hours = Math.floor(millisecondsToHours(duration) - days * 24) |
| 49 | const minutes = Math.floor( |
| 50 | millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours) |
| 51 | ) |
| 52 | const seconds = Math.floor( |
| 53 | millisecondsToSeconds(duration) - |
| 54 | days * 24 * 3600 - |
| 55 | hoursToSeconds(hours) - |
| 56 | minutesToSeconds(minutes) |
| 57 | ) |
| 58 | if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) { |
| 59 | return formatDuration({ seconds }, { zero: true }) |
| 60 | } |
| 61 | return formatDuration({ |
| 62 | days, |
| 63 | hours, |
| 64 | minutes, |
| 65 | seconds |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | export const formatDurationSeconds = (duration: number): string => { |
| 70 | return formatDurationMilliSeconds(secondsToMilliseconds(duration)) |
| 71 | } |
| 72 | |
| 73 | // More efficient time validation function than the one provided by date-fns |
| 74 | export const isValidDate = (date: Date | number | undefined): date is Date | number => { |
| 75 | if (typeof date === 'number') { |
| 76 | return !isNaN(date) |
| 77 | } else if (isDate(date)) { |
| 78 | return !isNaN(date.getTime()) |
| 79 | } |
| 80 | return false |
| 81 | } |
| 82 | |
| 83 | export const convertToDate = ( |
| 84 | value: Date | string | number | undefined | null |
| 85 | ): Date | undefined => { |
| 86 | if (value == null) { |
| 87 | return undefined |
| 88 | } |
| 89 | if (isDate(value)) { |
| 90 | return value |
| 91 | } |
| 92 | if (isString(value) || typeof value === 'number') { |
| 93 | const valueToDate = new Date(value) |
| 94 | if (isNaN(valueToDate.getTime())) { |
| 95 | throw new Error(`Cannot convert to date: '${value}'`) |
| 96 | } |
| 97 | return valueToDate |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | export const convertToInt = (value: unknown): number => { |
| 102 | if (value == null) { |
| 103 | return 0 |
| 104 | } |
| 105 | if (Number.isSafeInteger(value)) { |
| 106 | return value as number |
| 107 | } |
| 108 | if (typeof value === 'number') { |
| 109 | return Math.trunc(value) |
| 110 | } |
| 111 | let changedValue: number = value as number |
| 112 | if (isString(value)) { |
| 113 | changedValue = parseInt(value) |
| 114 | } |
| 115 | if (isNaN(changedValue)) { |
| 116 | throw new Error(`Cannot convert to integer: '${String(value)}'`) |
| 117 | } |
| 118 | return changedValue |
| 119 | } |
| 120 | |
| 121 | export const convertToFloat = (value: unknown): number => { |
| 122 | if (value == null) { |
| 123 | return 0 |
| 124 | } |
| 125 | let changedValue: number = value as number |
| 126 | if (isString(value)) { |
| 127 | changedValue = parseFloat(value) |
| 128 | } |
| 129 | if (isNaN(changedValue)) { |
| 130 | throw new Error(`Cannot convert to float: '${String(value)}'`) |
| 131 | } |
| 132 | return changedValue |
| 133 | } |
| 134 | |
| 135 | export const convertToBoolean = (value: unknown): boolean => { |
| 136 | let result = false |
| 137 | if (value != null) { |
| 138 | // Check the type |
| 139 | if (typeof value === 'boolean') { |
| 140 | return value |
| 141 | } else if (isString(value) && (value.toLowerCase() === 'true' || value === '1')) { |
| 142 | result = true |
| 143 | } else if (typeof value === 'number' && value === 1) { |
| 144 | result = true |
| 145 | } |
| 146 | } |
| 147 | return result |
| 148 | } |
| 149 | |
| 150 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { |
| 151 | if (max < min) { |
| 152 | throw new RangeError('Invalid interval') |
| 153 | } |
| 154 | if (max - min === Infinity) { |
| 155 | throw new RangeError('Invalid interval') |
| 156 | } |
| 157 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min |
| 158 | } |
| 159 | |
| 160 | export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { |
| 161 | max = Math.floor(max) |
| 162 | if (min !== 0) { |
| 163 | min = Math.ceil(min) |
| 164 | return Math.floor(randomInt(min, max + 1)) |
| 165 | } |
| 166 | return Math.floor(randomInt(max + 1)) |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Rounds the given number to the given scale. |
| 171 | * The rounding is done using the "round half away from zero" method. |
| 172 | * |
| 173 | * @param numberValue - The number to round. |
| 174 | * @param scale - The scale to round to. |
| 175 | * @returns The rounded number. |
| 176 | */ |
| 177 | export const roundTo = (numberValue: number, scale: number): number => { |
| 178 | const roundPower = Math.pow(10, scale) |
| 179 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower |
| 180 | } |
| 181 | |
| 182 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { |
| 183 | if (min !== 0) { |
| 184 | return roundTo(getRandomFloat(max, min), scale) |
| 185 | } |
| 186 | return roundTo(getRandomFloat(max), scale) |
| 187 | } |
| 188 | |
| 189 | export const getRandomFloatFluctuatedRounded = ( |
| 190 | staticValue: number, |
| 191 | fluctuationPercent: number, |
| 192 | scale = 2 |
| 193 | ): number => { |
| 194 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { |
| 195 | throw new RangeError( |
| 196 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` |
| 197 | ) |
| 198 | } |
| 199 | if (fluctuationPercent === 0) { |
| 200 | return roundTo(staticValue, scale) |
| 201 | } |
| 202 | const fluctuationRatio = fluctuationPercent / 100 |
| 203 | return getRandomFloatRounded( |
| 204 | staticValue * (1 + fluctuationRatio), |
| 205 | staticValue * (1 - fluctuationRatio), |
| 206 | scale |
| 207 | ) |
| 208 | } |
| 209 | |
| 210 | export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { |
| 211 | return timeSeries.map(timeSeriesItem => timeSeriesItem.value) |
| 212 | } |
| 213 | |
| 214 | export const clone = <T>(object: T): T => { |
| 215 | return structuredClone<T>(object) |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Detects whether the given value is an asynchronous function or not. |
| 220 | * |
| 221 | * @param fn - Unknown value. |
| 222 | * @returns `true` if `fn` was an asynchronous function, otherwise `false`. |
| 223 | * @internal |
| 224 | */ |
| 225 | export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => { |
| 226 | return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' |
| 227 | } |
| 228 | |
| 229 | export const isObject = (value: unknown): value is object => { |
| 230 | return value != null && typeof value === 'object' && !Array.isArray(value) |
| 231 | } |
| 232 | |
| 233 | export const isEmptyObject = (object: object): object is EmptyObject => { |
| 234 | if (object.constructor !== Object) { |
| 235 | return false |
| 236 | } |
| 237 | // Iterates over the keys of an object, if |
| 238 | // any exist, return false. |
| 239 | // eslint-disable-next-line no-unreachable-loop |
| 240 | for (const _ in object) { |
| 241 | return false |
| 242 | } |
| 243 | return true |
| 244 | } |
| 245 | |
| 246 | export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { |
| 247 | return isObject(value) && Object.hasOwn(value, property) |
| 248 | } |
| 249 | |
| 250 | export const isCFEnvironment = (): boolean => { |
| 251 | return env.VCAP_APPLICATION != null |
| 252 | } |
| 253 | |
| 254 | const isString = (value: unknown): value is string => { |
| 255 | return typeof value === 'string' |
| 256 | } |
| 257 | |
| 258 | export const isEmptyString = (value: unknown): value is '' | undefined | null => { |
| 259 | return value == null || (isString(value) && value.trim().length === 0) |
| 260 | } |
| 261 | |
| 262 | export const isNotEmptyString = (value: unknown): value is string => { |
| 263 | return isString(value) && value.trim().length > 0 |
| 264 | } |
| 265 | |
| 266 | export const isEmptyArray = (value: unknown): value is never[] => { |
| 267 | return Array.isArray(value) && value.length === 0 |
| 268 | } |
| 269 | |
| 270 | export const isNotEmptyArray = (value: unknown): value is unknown[] => { |
| 271 | return Array.isArray(value) && value.length > 0 |
| 272 | } |
| 273 | |
| 274 | export const insertAt = (str: string, subStr: string, pos: number): string => |
| 275 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}` |
| 276 | |
| 277 | /** |
| 278 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. |
| 279 | * |
| 280 | * @param retryNumber - the number of retries that have already been attempted |
| 281 | * @param delayFactor - the base delay factor in milliseconds |
| 282 | * @returns delay in milliseconds |
| 283 | */ |
| 284 | export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => { |
| 285 | const delay = Math.pow(2, retryNumber) * delayFactor |
| 286 | const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay |
| 287 | return delay + randomSum |
| 288 | } |
| 289 | |
| 290 | /** |
| 291 | * Generates a cryptographically secure random number in the [0,1[ range |
| 292 | * |
| 293 | * @returns A number in the [0,1[ range |
| 294 | */ |
| 295 | export const secureRandom = (): number => { |
| 296 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000 |
| 297 | } |
| 298 | |
| 299 | export const JSONStringifyWithMapSupport = ( |
| 300 | object: |
| 301 | | Record<string, unknown> |
| 302 | | Array<Record<string, unknown>> |
| 303 | | Map<unknown, unknown> |
| 304 | | ProtocolResponse, |
| 305 | space?: string | number |
| 306 | ): string => { |
| 307 | return JSON.stringify( |
| 308 | object, |
| 309 | (_, value: Record<string, unknown>) => { |
| 310 | if (value instanceof Map) { |
| 311 | return { |
| 312 | dataType: 'Map', |
| 313 | value: [...value] |
| 314 | } |
| 315 | } |
| 316 | return value |
| 317 | }, |
| 318 | space |
| 319 | ) |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Converts websocket error code to human readable string message |
| 324 | * |
| 325 | * @param code - websocket error code |
| 326 | * @returns human readable string message |
| 327 | */ |
| 328 | export const getWebSocketCloseEventStatusString = (code: number): string => { |
| 329 | if (code >= 0 && code <= 999) { |
| 330 | return '(Unused)' |
| 331 | } else if (code >= 1016) { |
| 332 | if (code <= 1999) { |
| 333 | return '(For WebSocket standard)' |
| 334 | } else if (code <= 2999) { |
| 335 | return '(For WebSocket extensions)' |
| 336 | } else if (code <= 3999) { |
| 337 | return '(For libraries and frameworks)' |
| 338 | } else if (code <= 4999) { |
| 339 | return '(For applications)' |
| 340 | } |
| 341 | } |
| 342 | if ( |
| 343 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 344 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null |
| 345 | ) { |
| 346 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] |
| 347 | } |
| 348 | return '(Unknown)' |
| 349 | } |
| 350 | |
| 351 | export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => { |
| 352 | for (let index = 0; index < array.length - 1; ++index) { |
| 353 | if (compareFn(array[index], array[index + 1]) > 0) { |
| 354 | return false |
| 355 | } |
| 356 | } |
| 357 | return true |
| 358 | } |
| 359 | |
| 360 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 361 | export const once = <T, A extends any[], R>( |
| 362 | fn: (...args: A) => R, |
| 363 | context: T |
| 364 | ): ((...args: A) => R) => { |
| 365 | let result: R |
| 366 | return (...args: A) => { |
| 367 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 368 | if (fn != null) { |
| 369 | result = fn.apply<T, A, R>(context, args) |
| 370 | ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined |
| 371 | } |
| 372 | return result |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | export const min = (...args: number[]): number => |
| 377 | args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity) |
| 378 | |
| 379 | export const max = (...args: number[]): number => |
| 380 | args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) |
| 381 | |
| 382 | export const throwErrorInNextTick = (error: Error): void => { |
| 383 | nextTick(() => { |
| 384 | throw error |
| 385 | }) |
| 386 | } |