|
|
|
|
| const { formatWithOptions: baseFormatWithOptions } = require('node:util')
|
| const { redactLog } = require('@npmcli/redact')
|
|
|
|
|
|
|
|
|
|
|
| const HAS_C01 = /[\x00-\x08\x0c\x0e-\x1f\x7f-\x9f]/
|
|
|
|
|
| const ALLOWED_SGR = /^\[[0-9;]{0,8}m/
|
|
|
|
|
| const SGR_MAX_LEN = 10
|
|
|
|
|
| function STRIP_C01 (str) {
|
| if (!HAS_C01.test(str)) {
|
| return str
|
| }
|
| let result = ''
|
| for (let i = 0; i < str.length; i++) {
|
| const char = str[i]
|
| const code = char.charCodeAt(0)
|
| if (!HAS_C01.test(char)) {
|
|
|
| result = `${result}${char}`
|
| } else if (code === 27 && ALLOWED_SGR.test(str.slice(i + 1, i + SGR_MAX_LEN + 1))) {
|
|
|
| result = `${result}\x1b`
|
| } else if (code <= 31) {
|
|
|
| result = `${result}^${String.fromCharCode(code + 64)}`
|
| } else {
|
|
|
| result = `${result}^${String.fromCharCode(code - 64)}`
|
| }
|
| }
|
| return result
|
| }
|
|
|
| const formatWithOptions = ({ prefix: prefixes = [], eol = '\n', redact = true, ...options }, ...args) => {
|
| const prefix = prefixes.filter(p => p != null).join(' ')
|
| let formatted = STRIP_C01(baseFormatWithOptions(options, ...args))
|
| if (redact) {
|
| formatted = redactLog(formatted)
|
| }
|
|
|
|
|
| const lines = formatted.split(/\r?\n/)
|
| return lines.reduce((acc, l) => `${acc}${prefix}${prefix && l ? ' ' : ''}${l}${eol}`, '')
|
| }
|
|
|
| module.exports = { formatWithOptions }
|
|
|