-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
389 lines (325 loc) · 10.5 KB
/
index.ts
File metadata and controls
389 lines (325 loc) · 10.5 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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/* eslint-disable no-control-regex */
import type readline from 'node:readline';
import { stdin, stdout } from 'node:process';
import { detectTerminal } from 'detect-terminal';
import { emitKeypressEvents } from '~/emit-keypress';
import { mousepress } from '~/mousepress';
import { keycodes } from '~/keycodes';
import { kEscape } from '~/keypress';
import { enableKeyboardProtocol, resetKeyboardProtocol } from '~/keyboard-protocol';
import {
createShortcut,
isMousepress,
isPrintableCharacter,
parsePosition,
prioritizeKeymap,
sortShortcutModifier
} from '~/utils';
export * from '~/utils';
export const isWindows = globalThis.process.platform === 'win32';
export const MAX_PASTE_BUFFER = 1024 * 1024; // 1MB limit for paste buffer
export const ENABLE_PASTE_BRACKET_MODE = `${kEscape}[?2004h`;
export const DISABLE_PASTE_BRACKET_MODE = `${kEscape}[?2004l`;
export const ENABLE_MOUSE = `${kEscape}[?1003h`;
export const DISABLE_MOUSE = `${kEscape}[?1003l`;
export const enablePaste = (stdout: NodeJS.WriteStream) => {
stdout.write(ENABLE_PASTE_BRACKET_MODE);
};
export const disablePaste = (stdout: NodeJS.WriteStream) => {
stdout.write(DISABLE_PASTE_BRACKET_MODE);
};
export const enableMouse = (stdout: NodeJS.WriteStream) => {
stdout.write(ENABLE_MOUSE);
};
export const disableMouse = (stdout: NodeJS.WriteStream) => {
stdout.write(DISABLE_MOUSE);
};
export const cursor = {
hide: (stdout: NodeJS.WriteStream) => {
stdout.write(`${kEscape}[?25l`);
},
show: (stdout: NodeJS.WriteStream) => {
stdout.write(`${kEscape}[?25h`);
},
position: (stdout: NodeJS.WriteStream) => {
stdout.write(`${kEscape}[6n`);
}
};
export const hasMatchingModifiers = (a: readline.Key, b) => {
return (
(!hasModifier(a) && !hasModifier(b)) ||
(a.ctrl === b.ctrl && a.shift === b.shift && a.meta === b.meta && a.fn === b.fn)
);
};
export const hasModifier = (key: readline.Key) => {
return key.ctrl || key.shift || key.meta || key.fn;
};
export const createEmitKeypress = (config?: { setupProcessHandlers?: boolean }) => {
const sessionCounts = new WeakMap<NodeJS.ReadStream, number>();
function acquireInput(input) {
sessionCounts.set(input, (sessionCounts.get(input) || 0) + 1);
}
function releaseInput(input) {
const count = sessionCounts.get(input) || 0;
if (count > 1) {
sessionCounts.set(input, count - 1);
} else {
sessionCounts.delete(input);
input.pause(); // actually pause only when last session closes
}
}
// If this is the singleton, use the (possibly global) handlers array
const setupProcessHandlers = config?.setupProcessHandlers === true;
let onExitHandlers: Set<() => void>;
// If not explicitly told to skip, AND we are the singleton (first created),
// use the process global array
if (setupProcessHandlers || !config) {
// Use process-global handlers for the singleton instance only
onExitHandlers = globalThis.onExitHandlers ||= new Set();
if (!globalThis.exitHandlers) {
globalThis.exitHandlers = onExitHandlers;
}
const hasListener = (name, fn) => {
return process.listeners(name).includes(fn);
};
// Register process listeners ONLY ONCE (singleton)
if (!hasListener('uncaughtException', onExitHandler)) {
process.once('uncaughtException', onExitHandler);
}
if (!hasListener('SIGINT', onExitHandler)) {
process.once('SIGINT', onExitHandler);
}
if (!hasListener('exit', onExitHandler)) {
process.once('exit', onExitHandler);
}
} else {
// For non-singleton, just use a local handlers array
onExitHandlers = new Set();
}
function onExitHandler() {
for (const fn of onExitHandlers) {
try {
fn();
onExitHandlers.delete(fn);
} catch (err) {
console.error('Error in exit handler:', err);
}
}
}
const emitKeypress = ({
input = stdin,
output = stdout,
keymap = [],
onKeypress,
onMousepress,
onExit,
maxPasteBuffer = MAX_PASTE_BUFFER,
escapeCodeTimeout = 500,
handleClose = true,
hideCursor = false,
initialPosition = false,
enablePasteMode = false,
pasteModeTimeout = 100,
keyboardProtocol = false
}: {
// eslint-disable-next-line no-undef
input?: NodeJS.ReadStream;
output?: NodeJS.WriteStream;
keymap?: Array<{ sequence: string; shortcut: string }>;
// eslint-disable-next-line no-unused-vars
onKeypress: (input: string, key: readline.Key, close: () => void) => void;
// eslint-disable-next-line no-unused-vars
onMousepress?: (input: string, key: any, close: () => void) => void;
onExit?: () => void;
maxPasteBuffer?: number;
escapeCodeTimeout?: number;
handleClose?: boolean;
hideCursor?: boolean;
initialPosition?: boolean;
enablePasteMode?: boolean;
pasteModeTimeout?: number;
keyboardProtocol?: boolean;
}) => {
if (!input || (input !== process.stdin && !input.isTTY)) {
throw new Error('Invalid stream passed');
}
const isRaw = input.isRaw;
let closed = false;
let pasting = false;
let initial = true;
let sorted = false;
let buffer = '';
let pasteTimeout: NodeJS.Timeout | null = null;
let disableProtocol: (() => void) | null = null;
const clearPasteState = () => {
pasting = false;
buffer = '';
if (pasteTimeout) {
clearTimeout(pasteTimeout);
pasteTimeout = null;
}
};
if (typeof keymap === 'function') {
keymap = keymap();
}
// eslint-disable-next-line complexity
async function handleKeypress(input: string, key: readline.Key) {
if (input === undefined && key.sequence === '\x1B[27u' && keyboardProtocol === true) {
key.name = 'esc';
key.sequence = '\x1B';
key.ctrl = false;
key.meta = false;
key.shift = false;
key.printable = false;
onKeypress('', key, close);
return;
}
if (initialPosition && initial && key.name === 'position') {
const parsed = parsePosition(key.sequence);
if (parsed) {
initial = false;
onKeypress('', parsed, close);
return;
}
}
if (key.name === 'paste-start' || /\x1B\[200~/.test(key.sequence)) {
clearPasteState();
pasting = true;
pasteTimeout = setTimeout(clearPasteState, pasteModeTimeout);
return;
}
if (key.name === 'paste-end' || /\x1B\[201~/.test(key.sequence)) {
clearTimeout(pasteTimeout);
pasteTimeout = null;
if (pasting) {
key.name = 'paste';
key.sequence = buffer.replace(/\x1B\[201~/g, '');
key.ctrl = false;
key.shift = false;
key.meta = false;
key.fn = false;
key.printable = true;
onKeypress(buffer, key, close);
clearPasteState();
}
return;
}
if (pasting) {
if (buffer.length < maxPasteBuffer) {
buffer += key.sequence?.replace(/\r/g, '\n') || '';
}
// Ignore any more characters, but don't clear state yet!
return;
}
if (!buffer && isMousepress(key.sequence, key)) {
const k = mousepress(key.sequence, Buffer.from(key.sequence));
k.mouse = true;
onMousepress?.(k, close);
} else {
let addShortcut = false;
if (!sorted) {
keymap = prioritizeKeymap(keymap);
sorted = true;
}
const found = keymap.filter(k => k.sequence === key.sequence);
if (found.length === 1) {
key = { ...key, ...found[0] };
addShortcut = false;
}
// console.log({ found, key });
const shortcut = key.shortcut
? sortShortcutModifier(key.shortcut)
: createShortcut(key);
if (!key.shortcut && hasModifier(key)) {
key.shortcut = shortcut;
}
for (const mapping of keymap) {
if (mapping.sequence) {
if (key.sequence === mapping.sequence && hasMatchingModifiers(key, mapping)) {
key = { ...key, ...mapping };
addShortcut = false;
break;
}
continue;
}
// Only continue comparison if the custom key mapping does not have a sequence
if (
shortcut === mapping.shortcut ||
(key.name && key.name === mapping.shortcut && hasMatchingModifiers(key, mapping))
) {
key = { ...key, ...mapping };
addShortcut = false;
break;
}
}
if (/^f[0-9]+$/.test(key.name)) {
addShortcut = true;
}
if (addShortcut) {
key.shortcut ||= shortcut;
}
key.printable ||= isPrintableCharacter(key.sequence);
onKeypress(key.sequence, key, close);
}
}
acquireInput(input);
function close() {
if (closed) return;
closed = true;
onExitHandlers.delete(close);
if (!isWindows && input.isTTY) input.setRawMode(isRaw);
if (hideCursor) cursor.show(output);
if (onMousepress) disableMouse(output);
if (enablePasteMode) disablePaste(output);
if (disableProtocol) disableProtocol();
if (onKeypress) input.off('keypress', handleKeypress);
if (pasteTimeout) clearTimeout(pasteTimeout);
input.off('pause', close);
releaseInput(input);
onExit?.();
}
emitKeypressEvents(input, { escapeCodeTimeout });
if (onMousepress) {
enableMouse(output);
}
if (enablePasteMode === true) {
enablePaste(output);
}
resetKeyboardProtocol(output);
if (keyboardProtocol) {
disableProtocol = enableKeyboardProtocol(detectTerminal(), output);
}
// Disable automatic character echoing
if (!isWindows && input.isTTY) input.setRawMode(true);
if (hideCursor) cursor.hide(output);
if (onKeypress) input.on('keypress', handleKeypress);
input.setEncoding('utf8');
input.once('pause', close);
input.resume();
if (initialPosition) {
cursor.position(output);
}
if (handleClose !== false && !onExitHandlers.has(close)) {
onExitHandlers.add(close);
}
return close;
};
return {
emitKeypress,
onExitHandlers
};
};
export declare global {
var onExitHandlers: Set<() => void>; // eslint-disable-line no-var
var exitHandlers: Array<() => void>; // eslint-disable-line no-var
}
export const { emitKeypress } = createEmitKeypress();
export {
createShortcut,
emitKeypressEvents,
isMousepress,
isPrintableCharacter,
keycodes,
mousepress
};
export default emitKeypress;