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