File size: 9,284 Bytes
064bfd6 | 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | /**
* Input Tokenizer - Escape sequence boundary detection
*
* Splits terminal input into tokens: text chunks and raw escape sequences.
* Unlike the Parser which interprets sequences semantically, this just
* identifies boundaries for use by keyboard input parsing.
*/
import { C0, ESC_TYPE, isEscFinal } from './ansi.js'
import { isCSIFinal, isCSIIntermediate, isCSIParam } from './csi.js'
export type Token =
| { type: 'text'; value: string }
| { type: 'sequence'; value: string }
type State =
| 'ground'
| 'escape'
| 'escapeIntermediate'
| 'csi'
| 'ss3'
| 'osc'
| 'dcs'
| 'apc'
export type Tokenizer = {
/** Feed input and get resulting tokens */
feed(input: string): Token[]
/** Flush any buffered incomplete sequences */
flush(): Token[]
/** Reset tokenizer state */
reset(): void
/** Get any buffered incomplete sequence */
buffer(): string
}
type TokenizerOptions = {
/**
* Treat `CSI M` as an X10 mouse event prefix and consume 3 payload bytes.
* Only enable for stdin input — `\x1b[M` is also CSI DL (Delete Lines) in
* output streams, and enabling this there swallows display text. Default false.
*/
x10Mouse?: boolean
}
/**
* Create a streaming tokenizer for terminal input.
*
* Usage:
* ```typescript
* const tokenizer = createTokenizer()
* const tokens1 = tokenizer.feed('hello\x1b[')
* const tokens2 = tokenizer.feed('A') // completes the escape sequence
* const remaining = tokenizer.flush() // force output incomplete sequences
* ```
*/
export function createTokenizer(options?: TokenizerOptions): Tokenizer {
let currentState: State = 'ground'
let currentBuffer = ''
const x10Mouse = options?.x10Mouse ?? false
return {
feed(input: string): Token[] {
const result = tokenize(
input,
currentState,
currentBuffer,
false,
x10Mouse,
)
currentState = result.state.state
currentBuffer = result.state.buffer
return result.tokens
},
flush(): Token[] {
const result = tokenize('', currentState, currentBuffer, true, x10Mouse)
currentState = result.state.state
currentBuffer = result.state.buffer
return result.tokens
},
reset(): void {
currentState = 'ground'
currentBuffer = ''
},
buffer(): string {
return currentBuffer
},
}
}
type InternalState = {
state: State
buffer: string
}
function tokenize(
input: string,
initialState: State,
initialBuffer: string,
flush: boolean,
x10Mouse: boolean,
): { tokens: Token[]; state: InternalState } {
const tokens: Token[] = []
const result: InternalState = {
state: initialState,
buffer: '',
}
const data = initialBuffer + input
let i = 0
let textStart = 0
let seqStart = 0
const flushText = (): void => {
if (i > textStart) {
const text = data.slice(textStart, i)
if (text) {
tokens.push({ type: 'text', value: text })
}
}
textStart = i
}
const emitSequence = (seq: string): void => {
if (seq) {
tokens.push({ type: 'sequence', value: seq })
}
result.state = 'ground'
textStart = i
}
while (i < data.length) {
const code = data.charCodeAt(i)
switch (result.state) {
case 'ground':
if (code === C0.ESC) {
flushText()
seqStart = i
result.state = 'escape'
i++
} else {
i++
}
break
case 'escape':
if (code === ESC_TYPE.CSI) {
result.state = 'csi'
i++
} else if (code === ESC_TYPE.OSC) {
result.state = 'osc'
i++
} else if (code === ESC_TYPE.DCS) {
result.state = 'dcs'
i++
} else if (code === ESC_TYPE.APC) {
result.state = 'apc'
i++
} else if (code === 0x4f) {
// 'O' - SS3
result.state = 'ss3'
i++
} else if (isCSIIntermediate(code)) {
// Intermediate byte (e.g., ESC ( for charset) - continue buffering
result.state = 'escapeIntermediate'
i++
} else if (isEscFinal(code)) {
// Two-character escape sequence
i++
emitSequence(data.slice(seqStart, i))
} else if (code === C0.ESC) {
// Double escape - emit first, start new
emitSequence(data.slice(seqStart, i))
seqStart = i
result.state = 'escape'
i++
} else {
// Invalid - treat ESC as text
result.state = 'ground'
textStart = seqStart
}
break
case 'escapeIntermediate':
// After intermediate byte(s), wait for final byte
if (isCSIIntermediate(code)) {
// More intermediate bytes
i++
} else if (isEscFinal(code)) {
// Final byte - complete the sequence
i++
emitSequence(data.slice(seqStart, i))
} else {
// Invalid - treat as text
result.state = 'ground'
textStart = seqStart
}
break
case 'csi':
// X10 mouse: CSI M + 3 raw payload bytes (Cb+32, Cx+32, Cy+32).
// M immediately after [ (offset 2) means no params — SGR mouse
// (CSI < … M) has a `<` param byte first and reaches M at offset > 2.
// Terminals that ignore DECSET 1006 but honor 1000/1002 emit this
// legacy encoding; without this branch the 3 payload bytes leak
// through as text (`` `rK `` / `arK` garbage in the prompt).
//
// Gated on x10Mouse — `\x1b[M` is also CSI DL (Delete Lines) and
// blindly consuming 3 chars corrupts output rendering (Parser/Ansi)
// and fragments bracketed-paste PASTE_END. Only stdin enables this.
// The ≥0x20 check on each payload slot is belt-and-suspenders: X10
// guarantees Cb≥32, Cx≥33, Cy≥33, so a control byte (ESC=0x1B) in
// any slot means this is CSI DL adjacent to another sequence, not a
// mouse event. Checking all three slots prevents PASTE_END's ESC
// from being consumed when paste content ends in `\x1b[M`+0-2 chars.
//
// Known limitation: this counts JS string chars, but X10 is byte-
// oriented and stdin uses utf8 encoding (App.tsx). At col 162-191 ×
// row 96-159 the two coord bytes (0xC2-0xDF, 0x80-0xBF) form a valid
// UTF-8 2-byte sequence and collapse to one char — the length check
// fails and the event buffers until the next keypress absorbs it.
// Fixing this requires latin1 stdin; X10's 223-coord cap is exactly
// why SGR was invented, and no-SGR terminals at 162+ cols are rare.
if (
x10Mouse &&
code === 0x4d /* M */ &&
i - seqStart === 2 &&
(i + 1 >= data.length || data.charCodeAt(i + 1) >= 0x20) &&
(i + 2 >= data.length || data.charCodeAt(i + 2) >= 0x20) &&
(i + 3 >= data.length || data.charCodeAt(i + 3) >= 0x20)
) {
if (i + 4 <= data.length) {
i += 4
emitSequence(data.slice(seqStart, i))
} else {
// Incomplete — exit loop; end-of-input buffers from seqStart.
// Re-entry re-tokenizes from ground via the invalid-CSI fallthrough.
i = data.length
}
break
}
if (isCSIFinal(code)) {
i++
emitSequence(data.slice(seqStart, i))
} else if (isCSIParam(code) || isCSIIntermediate(code)) {
i++
} else {
// Invalid CSI - abort, treat as text
result.state = 'ground'
textStart = seqStart
}
break
case 'ss3':
// SS3 sequences: ESC O followed by a single final byte
if (code >= 0x40 && code <= 0x7e) {
i++
emitSequence(data.slice(seqStart, i))
} else {
// Invalid - treat as text
result.state = 'ground'
textStart = seqStart
}
break
case 'osc':
if (code === C0.BEL) {
i++
emitSequence(data.slice(seqStart, i))
} else if (
code === C0.ESC &&
i + 1 < data.length &&
data.charCodeAt(i + 1) === ESC_TYPE.ST
) {
i += 2
emitSequence(data.slice(seqStart, i))
} else {
i++
}
break
case 'dcs':
case 'apc':
if (code === C0.BEL) {
i++
emitSequence(data.slice(seqStart, i))
} else if (
code === C0.ESC &&
i + 1 < data.length &&
data.charCodeAt(i + 1) === ESC_TYPE.ST
) {
i += 2
emitSequence(data.slice(seqStart, i))
} else {
i++
}
break
}
}
// Handle end of input
if (result.state === 'ground') {
flushText()
} else if (flush) {
// Force output incomplete sequence
const remaining = data.slice(seqStart)
if (remaining) tokens.push({ type: 'sequence', value: remaining })
result.state = 'ground'
} else {
// Buffer incomplete sequence for next call
result.buffer = data.slice(seqStart)
}
return { tokens, state: result }
}
|