-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathansi.ts
More file actions
60 lines (56 loc) · 2.03 KB
/
ansi.ts
File metadata and controls
60 lines (56 loc) · 2.03 KB
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
/**
* @fileoverview ANSI escape code utilities.
* Provides constants and helpers for terminal formatting.
*/
// ANSI escape codes - commonly used sequences.
export const ANSI_RESET = '\x1b[0m'
export const ANSI_BOLD = '\x1b[1m'
export const ANSI_DIM = '\x1b[2m'
export const ANSI_ITALIC = '\x1b[3m'
export const ANSI_UNDERLINE = '\x1b[4m'
export const ANSI_STRIKETHROUGH = '\x1b[9m'
// ANSI escape code regex to strip colors/formatting.
// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences use control characters.
const ANSI_REGEX = /\x1b\[[0-9;]*m/g
/**
* Create a regular expression for matching ANSI escape codes.
*
* Inlined ansi-regex:
* https://socket.dev/npm/package/ansi-regexp/overview/6.2.2
* MIT License
* Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
*
* @example
* ```typescript
* const regex = ansiRegex()
* '\u001b[31mHello\u001b[0m'.match(regex) // ['\u001b[31m', '\u001b[0m']
* ansiRegex({ onlyFirst: true }) // matches only the first code
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function ansiRegex(options?: { onlyFirst?: boolean }): RegExp {
const { onlyFirst } = options ?? {}
// Valid string terminator sequences are BEL, ESC\, and 0x9c.
const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'
// OSC sequences only: ESC ] ... ST (non-greedy until the first ST).
const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`
// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte.
const csi =
'[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]'
const pattern = `${osc}|${csi}`
return new RegExp(pattern, onlyFirst ? undefined : 'g')
}
/**
* Strip ANSI escape codes from text.
* Uses the inlined ansi-regex for matching.
*
* @example
* ```typescript
* stripAnsi('\u001b[31mError\u001b[0m') // 'Error'
* stripAnsi('\u001b[1mBold\u001b[0m') // 'Bold'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function stripAnsi(text: string): string {
return text.replace(ANSI_REGEX, '')
}