Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
format.js57 linesDownload Raw Back to utils
1// All logging goes through here, both to console and log files
2
3const { formatWithOptions: baseFormatWithOptions } = require('node:util')
4const { redactLog } = require('@npmcli/redact')
5
6// These are most assuredly not a mistake
7// https://eslint.org/docs/latest/rules/no-control-regex
8// \x00 through \x1f, \x7f through \x9f, not including \x09 \x0a \x0b \x0d
9/* eslint-disable-next-line no-control-regex */
10const HAS_C01 = /[\x00-\x08\x0c\x0e-\x1f\x7f-\x9f]/
11
12// Allows everything up to '[38;5;255m' in 8 bit notation
13const ALLOWED_SGR = /^\[[0-9;]{0,8}m/
14
15// '[38;5;255m'.length
16const SGR_MAX_LEN = 10
17
18// Strips all ANSI C0 and C1 control characters (except for SGR up to 8 bit)
19function STRIP_C01 (str) {
20  if (!HAS_C01.test(str)) {
21    return str
22  }
23  let result = ''
24  for (let i = 0; i < str.length; i++) {
25    const char = str[i]
26    const code = char.charCodeAt(0)
27    if (!HAS_C01.test(char)) {
28      // Most characters are in this set so continue early if we can
29      result = `${result}${char}`
30    } else if (code === 27 && ALLOWED_SGR.test(str.slice(i + 1, i + SGR_MAX_LEN + 1))) {
31      // \x1b with allowed SGR
32      result = `${result}\x1b`
33    } else if (code <= 31) {
34      // escape all other C0 control characters besides \x7f
35      result = `${result}^${String.fromCharCode(code + 64)}`
36    } else {
37      // hasC01 ensures this is now a C1 control character or \x7f
38      result = `${result}^${String.fromCharCode(code - 64)}`
39    }
40  }
41  return result
42}
43
44const formatWithOptions = ({ prefix: prefixes = [], eol = '\n', redact = true, ...options }, ...args) => {
45  const prefix = prefixes.filter(p => p != null).join(' ')
46  let formatted = STRIP_C01(baseFormatWithOptions(options, ...args))
47  if (redact) {
48    formatted = redactLog(formatted)
49  }
50  // Splitting could be changed to only `\n` once we are sure we only emit unix newlines.
51  // The eol param to this function will put the correct newlines in place for the returned string.
52  const lines = formatted.split(/\r?\n/)
53  return lines.reduce((acc, l) => `${acc}${prefix}${prefix && l ? ' ' : ''}${l}${eol}`, '')
54}
55
56module.exports = { formatWithOptions }
57 
codekingpro/portable-devtools · Team Ai