/
level.js
88 lines (69 loc) · 2.08 KB
/
level.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { emitWarning } from 'process'
import { multipleValidOptions } from 'jest-validate'
import filterObj from 'filter-obj'
import { result, mapValues } from './utils.js'
// Retrieve error's log level
export const getLevel = function({ opts, name, error }) {
const level = result(opts.level[name], error)
if (level === 'default' || level === undefined) {
return DEFAULT_LEVEL[name]
}
if (LEVELS.includes(level)) {
return level
}
emitWarning(
`Invalid option 'level.${name}' returning '${level}': function must return one of ${LEVELS.join(
', ',
)}`,
)
return DEFAULT_LEVEL[name]
}
// Apply `opts.level.default` and default values to `opts.level`
export const applyDefaultLevels = function({
opts: { level: { default: defaultLevel, ...level } = {} },
}) {
const levelA = filterObj(level, isDefined)
if (defaultLevel === undefined) {
return { ...DEFAULT_LEVEL, ...levelA }
}
const defaultLevels = mapValues(DEFAULT_LEVEL, () => defaultLevel)
return { ...defaultLevels, ...levelA }
}
const isDefined = function(key, value) {
return value !== undefined
}
// Use during options validation
export const getExampleLevels = function() {
return mapValues(DEFAULT_LEVEL, getExampleLevel)
}
const getExampleLevel = function(level) {
// eslint-disable-next-line no-empty-function
return multipleValidOptions(level, () => {})
}
export const validateLevels = function({ level }) {
Object.entries(level).forEach(validateLevel)
}
const validateLevel = function([name, level]) {
if (isValidLevel({ level })) {
return
}
throw new Error(
`Invalid option 'level.${name}' '${level}': must be a function or one of ${LEVELS.join(
', ',
)}`,
)
}
const isValidLevel = function({ level }) {
return (
LEVELS.includes(level) || level === undefined || typeof level === 'function'
)
}
const LEVELS = ['debug', 'info', 'warn', 'error', 'silent', 'default']
export const DEFAULT_LEVEL = {
default: 'error',
uncaughtException: 'error',
warning: 'warn',
unhandledRejection: 'error',
rejectionHandled: 'error',
multipleResolves: 'info',
}