topkat-utils 1.3.23 → 1.3.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/backend.ts +3 -4
- package/dist/backend.js +3 -4
- package/dist/backend.js.map +1 -1
- package/dist/src/array-utils.d.ts +1 -1
- package/dist/src/array-utils.js +2 -2
- package/dist/src/array-utils.js.map +1 -1
- package/dist/src/clean-stack-trace.js.map +1 -1
- package/dist/src/date-utils.d.ts +25 -20
- package/dist/src/date-utils.js +1 -0
- package/dist/src/date-utils.js.map +1 -1
- package/dist/src/env-utils.d.ts +1 -1
- package/dist/src/env-utils.js.map +1 -1
- package/dist/src/error-utils.d.ts +9 -6
- package/dist/src/error-utils.js +3 -0
- package/dist/src/error-utils.js.map +1 -1
- package/dist/src/isset.js.map +1 -1
- package/dist/src/logger-utils.d.ts +33 -30
- package/dist/src/logger-utils.js +10 -29
- package/dist/src/logger-utils.js.map +1 -1
- package/dist/src/loop-utils.d.ts +4 -4
- package/dist/src/loop-utils.js.map +1 -1
- package/dist/src/mongo-utils.js.map +1 -1
- package/dist/src/object-utils.d.ts +4 -4
- package/dist/src/object-utils.js +1 -1
- package/dist/src/object-utils.js.map +1 -1
- package/dist/src/regexp-utils.d.ts +1 -1
- package/dist/src/regexp-utils.js.map +1 -1
- package/dist/src/remove-circular-json-stringify.d.ts +1 -1
- package/dist/src/remove-circular-json-stringify.js.map +1 -1
- package/dist/src/string-utils.d.ts +4 -4
- package/dist/src/string-utils.js +1 -1
- package/dist/src/string-utils.js.map +1 -1
- package/dist/src/tests-utils.js.map +1 -1
- package/dist/src/timer-utils.d.ts +4 -4
- package/dist/src/timer-utils.js +1 -1
- package/dist/src/timer-utils.js.map +1 -1
- package/dist/src/transaction-utils.d.ts +3 -3
- package/dist/src/transaction-utils.js.map +1 -1
- package/dist/src/transaction-utils.spec.js +1 -1
- package/dist/src/transaction-utils.spec.js.map +1 -1
- package/dist/src/validation-utils.d.ts +3 -3
- package/dist/src/validation-utils.js +17 -16
- package/dist/src/validation-utils.js.map +1 -1
- package/dist/src/wtf-utils.d.ts +3 -3
- package/dist/src/wtf-utils.js +1 -1
- package/dist/src/wtf-utils.js.map +1 -1
- package/package.json +1 -1
- package/src/array-utils.ts +3 -3
- package/src/clean-stack-trace.ts +1 -1
- package/src/date-utils.ts +45 -41
- package/src/env-utils.ts +1 -1
- package/src/error-utils.ts +13 -8
- package/src/isset.ts +1 -1
- package/src/logger-utils.ts +40 -52
- package/src/loop-utils.ts +5 -5
- package/src/mongo-utils.ts +1 -1
- package/src/object-utils.ts +22 -22
- package/src/regexp-utils.ts +3 -3
- package/src/remove-circular-json-stringify.ts +2 -2
- package/src/string-utils.ts +3 -3
- package/src/tests-utils.ts +1 -1
- package/src/timer-utils.ts +4 -4
- package/src/transaction-utils.spec.ts +1 -1
- package/src/transaction-utils.ts +5 -5
- package/src/validation-utils.ts +28 -26
- package/src/wtf-utils.ts +6 -6
- package/tsconfig.json +1 -1
package/src/logger-utils.ts
CHANGED
|
@@ -27,9 +27,9 @@ export const logger = {
|
|
|
27
27
|
/**
|
|
28
28
|
* @param {String[]|String} inputLogs
|
|
29
29
|
*/
|
|
30
|
-
toHtml(inputLogs = [...logger.raw]) {
|
|
30
|
+
toHtml(inputLogs = [...logger.raw] as string[]) {
|
|
31
31
|
if (!Array.isArray(inputLogs)) inputLogs = [inputLogs]
|
|
32
|
-
const code2css = {
|
|
32
|
+
const code2css: Record<string, any> = {
|
|
33
33
|
2: `opacity:.5`, // dim
|
|
34
34
|
32: `color:#679933`, // green
|
|
35
35
|
31: `color:#A8383B`, // red
|
|
@@ -54,12 +54,18 @@ export const logger = {
|
|
|
54
54
|
})
|
|
55
55
|
return `<div style='color:#ccc'>${htmlLogs}<br></div>`
|
|
56
56
|
},
|
|
57
|
-
toText(inputLogs = [...logger.raw]) {
|
|
57
|
+
toText(inputLogs = [...logger.raw] as string[]) {
|
|
58
58
|
const str = Array.isArray(inputLogs) ? inputLogs.join('\n') : inputLogs
|
|
59
59
|
return str.replace(/\x1b\[.*?m/g, '')
|
|
60
60
|
},
|
|
61
61
|
raw: [] as string[],
|
|
62
62
|
json: [] as string[],
|
|
63
|
+
} as {
|
|
64
|
+
log(str: string, level?: LogLevels): void
|
|
65
|
+
toHtml(inputLogs?: string[]): string
|
|
66
|
+
toText(inputLogs?: string[]): string
|
|
67
|
+
raw: string[]
|
|
68
|
+
json: string[]
|
|
63
69
|
}
|
|
64
70
|
|
|
65
71
|
/**
|
|
@@ -70,23 +76,23 @@ export const logger = {
|
|
|
70
76
|
// * or C.gradientize(myLongString)
|
|
71
77
|
*/
|
|
72
78
|
export const C = {
|
|
73
|
-
dim: str => C.output(2, str), // opacity 0.5
|
|
74
|
-
green: str => C.output(32, str),
|
|
75
|
-
red: str => C.output(31, str),
|
|
76
|
-
yellow: str => C.output(33, str),
|
|
77
|
-
grey: str => C.output(2, str),
|
|
78
|
-
magenta: str => C.output(35, str),
|
|
79
|
-
cyan: str => C.output(36, str),
|
|
80
|
-
blue: str => C.output(34, str),
|
|
81
|
-
primary: str => {
|
|
79
|
+
dim: (str: string) => C.output(2, str), // opacity 0.5
|
|
80
|
+
green: (str: string) => C.output(32, str),
|
|
81
|
+
red: (str: string) => C.output(31, str),
|
|
82
|
+
yellow: (str: string) => C.output(33, str),
|
|
83
|
+
grey: (str: string) => C.output(2, str),
|
|
84
|
+
magenta: (str: string) => C.output(35, str),
|
|
85
|
+
cyan: (str: string) => C.output(36, str),
|
|
86
|
+
blue: (str: string) => C.output(34, str),
|
|
87
|
+
primary: (str: string) => {
|
|
82
88
|
const primary: Color = configFn()?.terminal?.theme?.primary
|
|
83
89
|
return C.rgb(...primary) + str + C.reset
|
|
84
90
|
},
|
|
85
91
|
reset: '\x1b[0m',
|
|
86
|
-
output: (code, str = '') => configFn()?.terminal?.noColor ? str : `\x1b[${code}m${str}\x1b[0m`,
|
|
92
|
+
output: (code: number, str = '') => configFn()?.terminal?.noColor ? str : `\x1b[${code}m${str}\x1b[0m`,
|
|
87
93
|
// true RGB colors B-*
|
|
88
|
-
rgb: (r, g = 0, b = 0) => configFn()?.terminal?.noColor || !isset(r, g, b) ? '' : `\x1b[38;2;${r};${g};${b}m`,
|
|
89
|
-
bg: (r
|
|
94
|
+
rgb: (r: number, g = 0, b = 0) => configFn()?.terminal?.noColor || !isset(r, g, b) ? '' : `\x1b[38;2;${r};${g};${b}m`,
|
|
95
|
+
bg: (r?: number, g?: number, b?: number) => configFn()?.terminal?.noColor || !isset(r, g, b) ? '' : `${'\x1b['}48;2;${r};${g};${b}m`,
|
|
90
96
|
/** Output a line of title */
|
|
91
97
|
line(title = '', length = configFn()?.terminal?.theme?.pageWidth, clr = configFn()?.terminal?.theme?.primary, char = '=') {
|
|
92
98
|
this.log('\u00A0\n' + this.rgb(...clr) + (title + ' ').padEnd(length || 0, char) + this.reset + '\u00A0\n')
|
|
@@ -94,7 +100,7 @@ export const C = {
|
|
|
94
100
|
/** Eg: ['cell1', 'cell2', 'cell3'], [25, 15] will start cell2 at 25 and cell 3 at 25 + 15
|
|
95
101
|
* @param {Array} limits default divide the viewport
|
|
96
102
|
*/
|
|
97
|
-
cols(strings, limits: number[] = [], clr = configFn()?.terminal?.theme?.fontColor) {
|
|
103
|
+
cols(strings: string[], limits: number[] = [], clr = configFn()?.terminal?.theme?.fontColor) {
|
|
98
104
|
|
|
99
105
|
if (!limits.length) {
|
|
100
106
|
const colWidth = Math.round(configFn()?.terminal?.theme.pageWidth / strings.length)
|
|
@@ -109,58 +115,40 @@ export const C = {
|
|
|
109
115
|
this.logClr(str, clr)
|
|
110
116
|
},
|
|
111
117
|
/** Console log alias */
|
|
112
|
-
log(...stringsCtxMayBeFirstParam) {
|
|
113
|
-
stringsCtxMayBeFirstParam.forEach(str => this.logClr(str))
|
|
118
|
+
log(...stringsCtxMayBeFirstParam: any[]) {
|
|
119
|
+
stringsCtxMayBeFirstParam.forEach((str: string) => this.logClr(str))
|
|
114
120
|
},
|
|
115
|
-
logClr(str, clr = configFn()?.terminal?.theme?.fontColor) {
|
|
121
|
+
logClr(str: string, clr = configFn()?.terminal?.theme?.fontColor) {
|
|
116
122
|
if (!isset(str)) return
|
|
117
123
|
str = (typeof clr !== 'undefined' ? this.rgb(...clr) : '') + str.toString().replace(/\n/g, '\n' + (typeof clr !== 'undefined' ? this.rgb(...clr) : ''))
|
|
118
124
|
logger.log(str + this.reset, 'info')
|
|
119
125
|
},
|
|
120
|
-
info(...str) {
|
|
126
|
+
info(...str: string[]) {
|
|
121
127
|
str.forEach((s, i) => {
|
|
122
128
|
if (i === 0) this.logClr('ⓘ ' + s, configFn()?.terminal?.theme?.primary)
|
|
123
129
|
else this.log(this.dimStrSplit(s))
|
|
124
130
|
})
|
|
125
131
|
this.log(' ')
|
|
126
132
|
},
|
|
127
|
-
success(...str) {
|
|
133
|
+
success(...str: string[]) {
|
|
128
134
|
str.forEach((s, i) => {
|
|
129
135
|
if (i === 0) this.log(this.green('✓ ' + s))
|
|
130
136
|
else this.log(this.dimStrSplit(s))
|
|
131
137
|
})
|
|
132
138
|
},
|
|
133
139
|
/** First param **false** to avoid logging stack trace */
|
|
134
|
-
error: (...errors) => logErrPrivate('error', [255, 0, 0], ...errors),
|
|
140
|
+
error: (...errors: any[]) => logErrPrivate('error', [255, 0, 0], ...errors),
|
|
135
141
|
/** First param **false** to avoid logging stack trace */
|
|
136
|
-
warning: (...str) => logErrPrivate('warn', [255, 122, 0], ...str),
|
|
137
|
-
customError: (color, ...str) => logErrPrivate('error', color, ...str),
|
|
138
|
-
customWarning: (color, ...str) => logErrPrivate('warn', color, ...str),
|
|
139
|
-
applicationError: (color, ...str) => logErrPrivate('warn', color, ...str),
|
|
140
|
-
warningLight: (_, ...str) => logErrPrivate('warn', [196, 120, 52], ...str),
|
|
141
|
-
dimStrSplit(...logs) {
|
|
142
|
+
warning: (...str: string[]) => logErrPrivate('warn', [255, 122, 0], ...str),
|
|
143
|
+
customError: (color: Color, ...str: string[]) => logErrPrivate('error', color, ...str),
|
|
144
|
+
customWarning: (color: Color, ...str: string[]) => logErrPrivate('warn', color, ...str),
|
|
145
|
+
applicationError: (color: Color, ...str: string[]) => logErrPrivate('warn', color, ...str),
|
|
146
|
+
warningLight: (_: any, ...str: string[]) => logErrPrivate('warn', [196, 120, 52], ...str),
|
|
147
|
+
dimStrSplit(...logs: string[]) {
|
|
142
148
|
const logsStr: string[] = []
|
|
143
149
|
logs.filter(isset).forEach(log => log.toString().split('\n').forEach(line => line && logsStr.push(this.dim(` ${line}`))))
|
|
144
150
|
return logsStr.join('\n')
|
|
145
151
|
},
|
|
146
|
-
notifShow() {
|
|
147
|
-
console.log('\n\u00A0')
|
|
148
|
-
this.notifications.forEach(fn => fn())
|
|
149
|
-
this.notifications = []
|
|
150
|
-
console.log('\n\u00A0')
|
|
151
|
-
},
|
|
152
|
-
/** Keep in memory the logs to show when needed with C.notifShow()
|
|
153
|
-
* Ex: C.notification('info', str); */
|
|
154
|
-
notification(type, ...messages) {
|
|
155
|
-
this.notifications.push(() => {
|
|
156
|
-
if (isset(this[type])) {
|
|
157
|
-
this[type](...messages)
|
|
158
|
-
} else {
|
|
159
|
-
this.warning('Wrong param for C.notification')
|
|
160
|
-
}
|
|
161
|
-
})
|
|
162
|
-
},
|
|
163
|
-
notifications: [] as any[], // fn array
|
|
164
152
|
/** Gratientize lines of text (separated by \n) */
|
|
165
153
|
gradientize(str = '', rgb1 = configFn()?.terminal?.theme?.shade1, rgb2 = configFn()?.terminal?.theme?.shade2, bgRgb = configFn()?.terminal?.theme?.bgColor, paddingY = 2) {
|
|
166
154
|
|
|
@@ -177,7 +165,7 @@ export const C = {
|
|
|
177
165
|
}, '') +
|
|
178
166
|
padLine.repeat(paddingY))
|
|
179
167
|
},
|
|
180
|
-
debugModeLog(title, ...string) {
|
|
168
|
+
debugModeLog(title: string, ...string: string[]) {
|
|
181
169
|
this.logClr('🐞 ' + title, configFn()?.terminal?.theme?.debugModeColor)
|
|
182
170
|
this.log(this.dimStrSplit(...string))
|
|
183
171
|
},
|
|
@@ -191,7 +179,7 @@ export const C = {
|
|
|
191
179
|
}
|
|
192
180
|
}
|
|
193
181
|
|
|
194
|
-
function logErrPrivate(level: NotInfoLogLevel, color: Color, ...errors) {
|
|
182
|
+
function logErrPrivate(level: NotInfoLogLevel, color: Color, ...errors: any[]) {
|
|
195
183
|
const { isProd } = configFn()
|
|
196
184
|
|
|
197
185
|
if (errors.length === 1 && typeof errors[0]?.log === 'function') return errors[0].log()
|
|
@@ -201,7 +189,7 @@ function logErrPrivate(level: NotInfoLogLevel, color: Color, ...errors) {
|
|
|
201
189
|
const symbol = level === 'error' ? '✘ ' : '⚠ '
|
|
202
190
|
if (errors.length > 1 && !isset(errors[0])) errors.shift() // remove first empty object
|
|
203
191
|
|
|
204
|
-
const getStringFromErr = (err, i) => {
|
|
192
|
+
const getStringFromErr = (err: any, i: number) => {
|
|
205
193
|
if (!isset(err)) return ''
|
|
206
194
|
else if (typeof err === 'string') {
|
|
207
195
|
if (i === 0) return C.rgb(...color) + symbol + err + C.reset
|
|
@@ -243,7 +231,7 @@ function logErrPrivate(level: NotInfoLogLevel, color: Color, ...errors) {
|
|
|
243
231
|
}
|
|
244
232
|
}
|
|
245
233
|
|
|
246
|
-
function stringifyInstanceOfError(err, type = 'error', color: Color = [255, 0, 0], level = 0) { // level = keep track of recursions
|
|
234
|
+
function stringifyInstanceOfError(err: any, type: NotInfoLogLevel = 'error', color: Color = [255, 0, 0], level = 0): { str: string, stackTrace?: string } { // level = keep track of recursions
|
|
247
235
|
if (level > 5) return { str: '' }
|
|
248
236
|
let str = ''
|
|
249
237
|
let stackTrace
|
|
@@ -261,7 +249,7 @@ function stringifyInstanceOfError(err, type = 'error', color: Color = [255, 0, 0
|
|
|
261
249
|
return { str, stackTrace }
|
|
262
250
|
}
|
|
263
251
|
|
|
264
|
-
function stringifyExtraInfos(extraInfoOriginal, type, color, level = 0) {
|
|
252
|
+
function stringifyExtraInfos(extraInfoOriginal: Record<string, any>, type: NotInfoLogLevel, color: Color, level = 0) {
|
|
265
253
|
let stackTrace
|
|
266
254
|
const originalError = [C.dim(`ORIGINAL ERROR ${'-'.repeat(39)}\n`)]
|
|
267
255
|
if (extraInfoOriginal instanceof Error) { // case where error is passed directly to extraInfos
|
|
@@ -336,7 +324,7 @@ export class cliLoadingSpinner {
|
|
|
336
324
|
this.animFrames = anims[type].frames
|
|
337
325
|
this.activeProcess = activeProcess
|
|
338
326
|
}
|
|
339
|
-
start(msg) {
|
|
327
|
+
start(msg: string) {
|
|
340
328
|
this.frameNb = 0
|
|
341
329
|
this.progressMessage = msg
|
|
342
330
|
this.interval = setInterval(() => {
|
package/src/loop-utils.ts
CHANGED
|
@@ -31,7 +31,7 @@ export function forI<T extends any[] | any>(
|
|
|
31
31
|
/** Current iteration index (0-based) */
|
|
32
32
|
number: number,
|
|
33
33
|
/** Result from previous iteration */
|
|
34
|
-
previousValue,
|
|
34
|
+
previousValue: any,
|
|
35
35
|
/** Array of all previous results */
|
|
36
36
|
arrayOfPreviousValues: any[]
|
|
37
37
|
) => T
|
|
@@ -58,7 +58,7 @@ export function forI<T extends any[] | any>(
|
|
|
58
58
|
* ```
|
|
59
59
|
* // Returns: [1, 1, 2, 3, 5, 8, 13, 21]
|
|
60
60
|
*/
|
|
61
|
-
export async function forIasync<T extends any[] | any>(nbIterations: number, callback: (number) => T): Promise<T[]> {
|
|
61
|
+
export async function forIasync<T extends any[] | any>(nbIterations: number, callback: (number: number) => T): Promise<T[]> {
|
|
62
62
|
const results: any[] = []
|
|
63
63
|
for (let i = 0; i < nbIterations; i++) {
|
|
64
64
|
results.push(await callback(i))
|
|
@@ -67,7 +67,7 @@ export async function forIasync<T extends any[] | any>(nbIterations: number, cal
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
|
|
70
|
-
export type RecursiveCallback = (item: any, addr: string, lastElementKey: string | number, parent
|
|
70
|
+
export type RecursiveCallback = (item: any, addr: string, lastElementKey: string | number, parent?: ObjectGeneric | any[]) => false | any
|
|
71
71
|
export type RecursiveConfig = {
|
|
72
72
|
disableCircularDependencyRemoval?: boolean
|
|
73
73
|
isObjectTestFunction?: (item: any) => boolean
|
|
@@ -98,7 +98,7 @@ export async function recursiveGenericFunction(
|
|
|
98
98
|
addr$ = '',
|
|
99
99
|
/** Technical field */
|
|
100
100
|
lastElementKey: string | number = '',
|
|
101
|
-
parent
|
|
101
|
+
parent?: Record<string, any>,
|
|
102
102
|
techFieldToAvoidCircularDependency: any[] = []
|
|
103
103
|
) {
|
|
104
104
|
err500IfNotSet({ callback })
|
|
@@ -141,7 +141,7 @@ export async function recursiveGenericFunction(
|
|
|
141
141
|
* NOTE: will remove circular references
|
|
142
142
|
* /!\ check return values
|
|
143
143
|
*/
|
|
144
|
-
export function recursiveGenericFunctionSync(item: ObjectGeneric | any[], callback: RecursiveCallback, config: RecursiveConfig = {}, addr$ = '', lastElementKey: string | number = '', parent
|
|
144
|
+
export function recursiveGenericFunctionSync(item: ObjectGeneric | any[], callback: RecursiveCallback, config: RecursiveConfig = {}, addr$ = '', lastElementKey: string | number = '', parent?: Record<string, any>, techFieldToAvoidCircularDependency: any[] = []) {
|
|
145
145
|
err500IfNotSet({ callback })
|
|
146
146
|
|
|
147
147
|
if (!config.isObjectTestFunction) config.isObjectTestFunction = isObject
|
package/src/mongo-utils.ts
CHANGED
|
@@ -17,7 +17,7 @@ export function getId(obj: any): string | undefined {
|
|
|
17
17
|
* @param {Object} filterB
|
|
18
18
|
* @param {Boolean} assignToFilterA defualt false: if true, it will modify filterA, else it will return merged filters as a new object
|
|
19
19
|
*/
|
|
20
|
-
export function mongoFilterMerger(filterA, filterB, assignToFilterA = false) {
|
|
20
|
+
export function mongoFilterMerger(filterA: any, filterB: any, assignToFilterA = false) {
|
|
21
21
|
if (isset(filterA.$and) && isset(filterB.$and)) {
|
|
22
22
|
filterA.$and.push(...filterB.$and)
|
|
23
23
|
delete filterB.$and
|
package/src/object-utils.ts
CHANGED
|
@@ -29,7 +29,7 @@ export function simpleObjectMaskOrSelect<Obj extends ObjectGeneric>(
|
|
|
29
29
|
keysToMask.forEach(keyNameToDelete => delete object[keyNameToDelete])
|
|
30
30
|
return object
|
|
31
31
|
} else {
|
|
32
|
-
return allKeys.reduce((newObject, key) => {
|
|
32
|
+
return allKeys.reduce((newObject: Record<string, any>, key) => {
|
|
33
33
|
if (!keysToMask.includes(key)) newObject[key] = object[key]
|
|
34
34
|
return newObject
|
|
35
35
|
}, {}) as Obj
|
|
@@ -93,7 +93,7 @@ export function findByAddressAll<ReturnAddresses extends boolean = false>(
|
|
|
93
93
|
/** Enforce writing subItems. Eg: user.name.blah will ensure all are set until the writing of the last item
|
|
94
94
|
* NOTE: doesn't work when parent is array
|
|
95
95
|
*/
|
|
96
|
-
export function objForceWrite<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item, options: { doNotWriteFinalValue?: boolean } = {}): MainObj {
|
|
96
|
+
export function objForceWrite<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any, options: { doNotWriteFinalValue?: boolean } = {}): MainObj {
|
|
97
97
|
const { doNotWriteFinalValue = false } = options
|
|
98
98
|
const writeFinalValue = !doNotWriteFinalValue
|
|
99
99
|
|
|
@@ -129,13 +129,13 @@ export const objForceWritePath = forcePathInObject
|
|
|
129
129
|
* if user.name.blah has a value it will not change it.
|
|
130
130
|
* NOTE: doesn't work when parent is array
|
|
131
131
|
*/
|
|
132
|
-
export function objForceWriteIfNotSet<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item): MainObj {
|
|
132
|
+
export function objForceWriteIfNotSet<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any): MainObj {
|
|
133
133
|
if (!isset(findByAddress(obj, addr))) return objForceWrite(obj, addr, item)
|
|
134
134
|
else return obj
|
|
135
135
|
}
|
|
136
136
|
|
|
137
137
|
/** Merge mixins into class. Use it in the constructor like: mergeMixins(this, {myMixin: true}) */
|
|
138
|
-
export function mergeMixins(that, ...mixins) {
|
|
138
|
+
export function mergeMixins(that: any, ...mixins: any[]) {
|
|
139
139
|
mixins.forEach(mixin => {
|
|
140
140
|
for (const method in mixin) {
|
|
141
141
|
that[method] = mixin[method]
|
|
@@ -187,7 +187,7 @@ export function deepClone<MainObj extends Record<string, any>>(obj: MainObj, cac
|
|
|
187
187
|
* @param {Object} obj the object on which we want to filter the keys
|
|
188
188
|
* @param {function} filterFunc function that returns true if the key match the wanted criteria
|
|
189
189
|
*/
|
|
190
|
-
export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, filter): MainObj {
|
|
190
|
+
export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, filter: any): MainObj {
|
|
191
191
|
const clone = cloneObject(obj)
|
|
192
192
|
recursiveGenericFunctionSync(obj, (_, addr, lastElementKey) => {
|
|
193
193
|
if (!filter(lastElementKey)) deleteByAddress(clone, addr.split('.'))
|
|
@@ -199,7 +199,7 @@ export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, fi
|
|
|
199
199
|
* @param {Array} addrArr addressArray on which to delete the property
|
|
200
200
|
*/
|
|
201
201
|
export function deleteByAddress(obj: object, addr: string | string[]) {
|
|
202
|
-
let current = obj
|
|
202
|
+
let current = obj as Record<string, any>
|
|
203
203
|
const addrArr = Array.isArray(addr) ? addr : addr.split('.')
|
|
204
204
|
for (let i = 0; i < addrArr.length; i++) {
|
|
205
205
|
const currentAddr = addrArr[i].replace(/(\[|\])/g, '')
|
|
@@ -227,9 +227,9 @@ export function readOnly<MainObj extends Record<string, any>>(o: MainObj): { rea
|
|
|
227
227
|
}
|
|
228
228
|
|
|
229
229
|
/** Fields of the object can be created BUT NOT reassignated */
|
|
230
|
-
export function reassignForbidden(o) {
|
|
230
|
+
export function reassignForbidden(o: Record<string, any>) {
|
|
231
231
|
return new Proxy(o, {
|
|
232
|
-
defineProperty: function (that, key, value) {
|
|
232
|
+
defineProperty: function (that: Record<string, any>, key: string, value) {
|
|
233
233
|
if (key in that) throw new DescriptiveError(`Cannot reassign the property ${key.toString()} of this object`, { code: 500 })
|
|
234
234
|
else {
|
|
235
235
|
that[key] = value
|
|
@@ -243,9 +243,9 @@ export function reassignForbidden(o) {
|
|
|
243
243
|
}
|
|
244
244
|
|
|
245
245
|
/** All fileds and subFields of the object will become readOnly */
|
|
246
|
-
export function readOnlyRecursive(object) {
|
|
246
|
+
export function readOnlyRecursive(object: Record<string, any>) {
|
|
247
247
|
recursiveGenericFunctionSync(object, (item, _, lastElementKey, parent) => {
|
|
248
|
-
if (typeof item === 'object') parent[lastElementKey] = readOnly(item)
|
|
248
|
+
if (typeof item === 'object' && parent) (parent as any)[lastElementKey] = readOnly(item)
|
|
249
249
|
})
|
|
250
250
|
return object
|
|
251
251
|
}
|
|
@@ -253,7 +253,7 @@ export function readOnlyRecursive(object) {
|
|
|
253
253
|
/** @deprecated use readOnlyRecursive instead */
|
|
254
254
|
export const readOnlyForAll = readOnlyRecursive
|
|
255
255
|
|
|
256
|
-
export function objFilterUndefinedRecursive(obj) {
|
|
256
|
+
export function objFilterUndefinedRecursive(obj: Record<string, any>) {
|
|
257
257
|
if (obj) {
|
|
258
258
|
const flattenedObj = flattenObject(obj)
|
|
259
259
|
Object.keys(flattenedObj).forEach(key => {
|
|
@@ -265,8 +265,8 @@ export function objFilterUndefinedRecursive(obj) {
|
|
|
265
265
|
} else return obj
|
|
266
266
|
}
|
|
267
267
|
|
|
268
|
-
export function sortObjKeyAccordingToValue(unorderedObj, ascending = true) {
|
|
269
|
-
const orderedObj = {}
|
|
268
|
+
export function sortObjKeyAccordingToValue(unorderedObj: Record<string, any>, ascending = true) {
|
|
269
|
+
const orderedObj = {} as Record<string, any>
|
|
270
270
|
const sortingConst = ascending ? 1 : -1
|
|
271
271
|
Object.keys(unorderedObj)
|
|
272
272
|
.sort((keyA, keyB) => unorderedObj[keyA] < unorderedObj[keyB] ? sortingConst : -sortingConst)
|
|
@@ -285,7 +285,7 @@ export function sortObjKeyAccordingToValue(unorderedObj, ascending = true) {
|
|
|
285
285
|
export function ensureObjectProp<MainObj extends Record<string, any>, Addr extends string>(
|
|
286
286
|
obj: MainObj,
|
|
287
287
|
addr: Addr,
|
|
288
|
-
defaultValue,
|
|
288
|
+
defaultValue: any,
|
|
289
289
|
callback: (o: any) => any
|
|
290
290
|
): MainObj[Addr] {
|
|
291
291
|
err500IfNotSet({ obj, addr, defaultValue, callback })
|
|
@@ -309,7 +309,7 @@ export function mergeDeep<
|
|
|
309
309
|
>(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6 {
|
|
310
310
|
return mergeDeepConfigurable(
|
|
311
311
|
(previousVal, currentVal) => [...previousVal, ...currentVal].filter((elm, i, arr) => arr.indexOf(elm) === i),
|
|
312
|
-
(previousVal, currentVal) => mergeDeep(previousVal, currentVal),
|
|
312
|
+
(previousVal: any, currentVal: any) => mergeDeep(previousVal, currentVal),
|
|
313
313
|
undefined,
|
|
314
314
|
...objects
|
|
315
315
|
)
|
|
@@ -329,7 +329,7 @@ export function mergeDeepOverrideArrays<
|
|
|
329
329
|
>(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6 {
|
|
330
330
|
return mergeDeepConfigurable(
|
|
331
331
|
undefined,
|
|
332
|
-
(previousVal, currentVal) => mergeDeepOverrideArrays(previousVal, currentVal),
|
|
332
|
+
(previousVal: any, currentVal: any) => mergeDeepOverrideArrays(previousVal, currentVal),
|
|
333
333
|
undefined,
|
|
334
334
|
...objects
|
|
335
335
|
)
|
|
@@ -351,11 +351,11 @@ export function mergeDeepConfigurable<
|
|
|
351
351
|
O5 extends Record<string, any> = Record<string, any>,
|
|
352
352
|
O6 extends Record<string, any> = Record<string, any>,
|
|
353
353
|
>(
|
|
354
|
-
replacerForArrays = (_, curr) => curr, replacerForObjects,
|
|
355
|
-
replacerDefault = (_, curr) => curr,
|
|
354
|
+
replacerForArrays = (_: any, curr: any) => curr, replacerForObjects: any,
|
|
355
|
+
replacerDefault = (_: any, curr: any) => curr,
|
|
356
356
|
...objects: [O1, O2?, O3?, O4?, O5?, O6?]
|
|
357
357
|
): O1 & O2 & O3 & O4 & O5 & O6 {
|
|
358
|
-
return objects.reduce((actuallyMerged, obj) => {
|
|
358
|
+
return objects.reduce((actuallyMerged: Record<string, any>, obj) => {
|
|
359
359
|
if (obj && typeof obj === 'object') Object.keys(obj).forEach(key => {
|
|
360
360
|
const previousVal = actuallyMerged[key]
|
|
361
361
|
const currentVal = obj[key]
|
|
@@ -376,11 +376,11 @@ export function mergeDeepConfigurable<
|
|
|
376
376
|
/** { a: {b:2}} => {'a.b':2} useful for translations
|
|
377
377
|
* NOTE: will remove circular references
|
|
378
378
|
*/
|
|
379
|
-
export function flattenObject(data, config: { withoutArraySyntax?: boolean, withArraySyntaxMinified?: boolean } = {}): Record<string, any> {
|
|
379
|
+
export function flattenObject(data: any, config: { withoutArraySyntax?: boolean, withArraySyntaxMinified?: boolean } = {}): Record<string, any> {
|
|
380
380
|
const { withoutArraySyntax = false, withArraySyntaxMinified = false } = config
|
|
381
|
-
const result = {}
|
|
381
|
+
const result = {} as Record<string, any>
|
|
382
382
|
const seenObjects: any[] = [] // avoidCircular reference to infinite loop
|
|
383
|
-
const recurse = (cur, prop) => {
|
|
383
|
+
const recurse = (cur: any, prop: string) => {
|
|
384
384
|
if (Array.isArray(cur)) {
|
|
385
385
|
const l = cur.length
|
|
386
386
|
let i = 0
|
package/src/regexp-utils.ts
CHANGED
|
@@ -33,10 +33,10 @@ export function firstMatch(str: string, regExp: RegExp): string | undefined { re
|
|
|
33
33
|
* Eg: [ [full, match1, m2], [f, m1, m2]... ]
|
|
34
34
|
* NOTE: the G flag will be appended to regexp
|
|
35
35
|
*/
|
|
36
|
-
export function allMatches(str: string, reg: RegExp)
|
|
36
|
+
export function allMatches(str: string, reg: RegExp) {
|
|
37
37
|
let i = 0
|
|
38
|
-
let matches
|
|
39
|
-
const arr:
|
|
38
|
+
let matches: RegExpExecArray | null
|
|
39
|
+
const arr: (RegExpExecArray | null)[] = []
|
|
40
40
|
if (typeof str !== 'string') C.error('Not a string provided as first argument for allMatches()')
|
|
41
41
|
else {
|
|
42
42
|
reg = new RegExp(reg, 'g')
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
2
2
|
|
|
3
3
|
/** Best way to stringify a value! Default indent: 2 */
|
|
4
|
-
export function removeCircularJSONstringify(object, indent = 2) {
|
|
4
|
+
export function removeCircularJSONstringify(object: Record<string, any>, indent = 2) {
|
|
5
5
|
const getCircularReplacer = () => {
|
|
6
6
|
const seen = new WeakSet()
|
|
7
|
-
return (_, value) => {
|
|
7
|
+
return (_: any, value: any) => {
|
|
8
8
|
if (typeof value === 'object' && value !== null) {
|
|
9
9
|
if (seen.has(value)) {
|
|
10
10
|
return
|
package/src/string-utils.ts
CHANGED
|
@@ -76,7 +76,7 @@ export function getValuesBetweenSeparator(str: string, separator: string, remove
|
|
|
76
76
|
* @param ignoreBetweenOpen default ['\'', '`', '"', '/'], when reaching an opening char, it will ignore all until it find the corresponding closing char
|
|
77
77
|
* @param ignoreBetweenClose default ['\'', '`', '"', '/'] list of corresponding closing chars
|
|
78
78
|
*/
|
|
79
|
-
export function getValuesBetweenStrings(str: string, openingOrSeparator, closing, ignoreBetweenOpen = ['\'', '`', '"', '/'], ignoreBetweenClose = ['\'', '`', '"', '/'], removeTrailingSpaces = true) {
|
|
79
|
+
export function getValuesBetweenStrings(str: string, openingOrSeparator: string, closing?: string, ignoreBetweenOpen = ['\'', '`', '"', '/'], ignoreBetweenClose = ['\'', '`', '"', '/'], removeTrailingSpaces = true) {
|
|
80
80
|
err500IfEmptyOrNotSet({ openingOrSeparator, str })
|
|
81
81
|
|
|
82
82
|
str = str.replace(/<</g, '§§"').replace(/>>/g, '"§§')
|
|
@@ -129,7 +129,7 @@ export function getValuesBetweenStrings(str: string, openingOrSeparator, closing
|
|
|
129
129
|
|
|
130
130
|
pushActualValue()
|
|
131
131
|
|
|
132
|
-
const replaceValz = arr => arr.map(v => v.replace(/§§"/g, '<<').replace(/"§§/g, '>>')).filter(v => v)
|
|
132
|
+
const replaceValz = (arr: string[]) => arr.map(v => v.replace(/§§"/g, '<<').replace(/"§§/g, '>>')).filter(v => v)
|
|
133
133
|
|
|
134
134
|
return { inner: replaceValz(arrayValues), outer: replaceValz(betweenArray) }
|
|
135
135
|
}
|
|
@@ -240,7 +240,7 @@ export function miniTemplater(content: string, varz: ObjectGeneric, options: Par
|
|
|
240
240
|
|
|
241
241
|
|
|
242
242
|
/** Clean output for outside world. All undefined / null / NaN / Infinity values are changed to '-' */
|
|
243
|
-
export function cln(val, replacerInCaseItIsUndefinNaN = '-') { return ['undefined', undefined, 'indéfini', 'NaN', NaN, Infinity, null].includes(val) ? replacerInCaseItIsUndefinNaN : val }
|
|
243
|
+
export function cln(val: any, replacerInCaseItIsUndefinNaN = '-') { return ['undefined', undefined, 'indéfini', 'NaN', NaN, Infinity, null].includes(val) ? replacerInCaseItIsUndefinNaN : val }
|
|
244
244
|
|
|
245
245
|
export function nbOccurenceInString(baseString: string, searchedString: string, allowOverlapping: boolean = false) {
|
|
246
246
|
|
package/src/tests-utils.ts
CHANGED
|
@@ -16,7 +16,7 @@ export const restTestMini = {
|
|
|
16
16
|
restTestMini.lastErrors = []
|
|
17
17
|
restTestMini.throwOnErr = throwOnErr
|
|
18
18
|
},
|
|
19
|
-
newErr(err) {
|
|
19
|
+
newErr(err: any) {
|
|
20
20
|
restTestMini.nbError++
|
|
21
21
|
restTestMini.lastErrors.push(err)
|
|
22
22
|
if (restTestMini.throwOnErr) throw new Error(err)
|
package/src/timer-utils.ts
CHANGED
|
@@ -7,9 +7,9 @@ import { DescriptiveError } from './error-utils'
|
|
|
7
7
|
import { round2 } from './math-utils'
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
export async function timeout(ms, fn = () => { /* */ }) { return new Promise(res => setTimeout(res, ms)).then(fn) }
|
|
10
|
+
export async function timeout(ms: number, fn = () => { /* */ }) { return new Promise(res => setTimeout(res, ms)).then(fn) }
|
|
11
11
|
|
|
12
|
-
export async function runAsync(callback, milliseconds$ = 1) { return timeout(milliseconds$, callback) }
|
|
12
|
+
export async function runAsync(callback: () => any, milliseconds$ = 1) { return timeout(milliseconds$, callback) }
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
*
|
|
@@ -18,7 +18,7 @@ export async function runAsync(callback, milliseconds$ = 1) { return timeout(mil
|
|
|
18
18
|
* @param {Boolean|String} errorAfterNSeconds default:true output an error in case of timeout, can be the displayed error message
|
|
19
19
|
* @param {*} cliOutput write a cli progress to show that a process is running
|
|
20
20
|
*/
|
|
21
|
-
export async function waitUntilTrue(callback, timeoutSec = 10, errorAfterNSeconds = true, cliOutput = true) {
|
|
21
|
+
export async function waitUntilTrue(callback: () => any, timeoutSec = 10, errorAfterNSeconds = true, cliOutput = true) {
|
|
22
22
|
let generalTimeout = true
|
|
23
23
|
let step = 3
|
|
24
24
|
const errMess = typeof errorAfterNSeconds === 'string' ? 'Timeout: ' + errorAfterNSeconds : 'Timeout for waitUntilTrue() callback'
|
|
@@ -42,7 +42,7 @@ let isExecuting = false
|
|
|
42
42
|
* @param {Number} time default: 500ms;
|
|
43
43
|
* @param {Function} errorCallback default: e => C.error(e)
|
|
44
44
|
*/
|
|
45
|
-
export async function executeInDelayedLoop(callback, time = 500, errorCallback = e => C.error(e)) {
|
|
45
|
+
export async function executeInDelayedLoop(callback: () => any, time = 500, errorCallback = (e: any) => C.error(e)) {
|
|
46
46
|
delayedLoopParams.push([callback, time, errorCallback])
|
|
47
47
|
if (isExecuting) return
|
|
48
48
|
isExecuting = true
|
|
@@ -9,7 +9,7 @@ import { timeout } from './timer-utils'
|
|
|
9
9
|
describe('TRANSACTION TEST', () => {
|
|
10
10
|
const statusArr = [] as number[]
|
|
11
11
|
|
|
12
|
-
const asyncCallback = i => async () => {
|
|
12
|
+
const asyncCallback = (i: number) => async () => {
|
|
13
13
|
await timeout(1000)
|
|
14
14
|
statusArr.push(i)
|
|
15
15
|
}
|
package/src/transaction-utils.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { isset } from './isset'
|
|
|
5
5
|
import { C } from './logger-utils'
|
|
6
6
|
import { timeout } from './timer-utils'
|
|
7
7
|
|
|
8
|
-
const transactionRunning = { __default: false }
|
|
9
|
-
const queue = { __default: [] }
|
|
8
|
+
const transactionRunning = { __default: false } as Record<string, boolean>
|
|
9
|
+
const queue = { __default: [] } as Record<string, any[]>
|
|
10
10
|
|
|
11
11
|
/** Allow to perform async functions in a defined order
|
|
12
12
|
* This adds the callback to a queue and is resolved when ALL previous callbacks with same name are executed
|
|
@@ -16,7 +16,7 @@ const queue = { __default: [] }
|
|
|
16
16
|
* @param {Number} timeout default: 120000 (120s) will throw an error if transaction time is higher that this amount of ms
|
|
17
17
|
* @returns {Promise}
|
|
18
18
|
*/
|
|
19
|
-
export async function transaction(name, asyncCallback, timeout = 120000, doNotThrow = false) {
|
|
19
|
+
export async function transaction(name: string, asyncCallback: () => any, timeout = 120000, doNotThrow = false) {
|
|
20
20
|
if (typeof name === 'function') {
|
|
21
21
|
asyncCallback = name
|
|
22
22
|
name = '__default'
|
|
@@ -45,7 +45,7 @@ export async function transaction(name, asyncCallback, timeout = 120000, doNotTh
|
|
|
45
45
|
})
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
export async function removeItemFromQueue(name) {// meoww!
|
|
48
|
+
export async function removeItemFromQueue(name: string) {// meoww!
|
|
49
49
|
if (transactionRunning[name] === true) return // v
|
|
50
50
|
transactionRunning[name] = true // A A /\
|
|
51
51
|
while (queue[name].length) await queue[name].shift()() // ||
|
|
@@ -54,7 +54,7 @@ export async function removeItemFromQueue(name) {// meoww!
|
|
|
54
54
|
// 11 11
|
|
55
55
|
|
|
56
56
|
/** Wait for a transaction to complete without creating a new transaction */
|
|
57
|
-
export async function waitForTransaction(transactionName, forceReleaseInSeconds = 30) {
|
|
57
|
+
export async function waitForTransaction(transactionName: string, forceReleaseInSeconds = 30) {
|
|
58
58
|
let brk = false
|
|
59
59
|
setTimeout(() => brk = true, forceReleaseInSeconds * 1000)
|
|
60
60
|
while (isset(transactionRunning[transactionName]) && transactionRunning[transactionName] === true) {
|