All files / player-terminal/src keyboard-diagnostic.ts

0% Statements 0/44
0% Branches 0/20
0% Functions 0/12
0% Lines 0/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                           
import readline from 'node:readline';
import {
  beginStatefulKeyboardProtocolOptIn,
  inspectInputTokenEvent,
  type InputProtocolInspection,
} from './manual-input.ts';
 
interface DiagnosticChunk {
  text: string;
  escaped: string;
  hex: string;
}
 
interface DiagnosticKey {
  name?: string;
  sequence?: string;
  ctrl?: boolean;
  meta?: boolean;
  shift?: boolean;
}
 
let sequence = 0;
 
main();
 
function main(): void {
  const stdin = process.stdin as NodeJS.ReadStream & { isRaw?: boolean };
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    process.stderr.write('Keyboard diagnostic requires a TTY on stdin/stdout.\n');
    process.exitCode = 1;
    return;
  }
 
  const wasRawMode = Boolean(stdin.isRaw);
  const shouldResetRawModeOnStart = process.platform === 'win32';
  readline.emitKeypressEvents(process.stdin);
  if (shouldResetRawModeOnStart && stdin.isRaw) {
    process.stdin.setRawMode(false);
  }
  process.stdin.setRawMode(true);
  process.stdin.resume();
 
  const stopStatefulKeyboardProtocol = beginStatefulKeyboardProtocolOptIn(
    process.stdout,
    process.platform,
    process.env,
  );
 
  process.stdout.write('Keyboard diagnostics started. Press keys to inspect stdin events. Press Ctrl+C to exit.\n');
  emitRecord({
    kind: 'config',
    platform: process.platform,
    termProgram: process.env.TERM_PROGRAM,
    wezTermPane: Boolean(process.env.WEZTERM_PANE),
    stdinIsTTY: process.stdin.isTTY,
    stdoutIsTTY: process.stdout.isTTY,
    statefulProtocols: process.env.BE_MUSIC_KEYBOARD_PROTOCOLS ?? (process.platform === 'win32' ? 'none' : 'kitty'),
  });
 
  const cleanup = (): void => {
    process.stdin.off('keypress', onKeyPress);
    process.stdin.off('data', onData);
    stopStatefulKeyboardProtocol();
    process.stdin.setRawMode(wasRawMode);
  };
 
  const onKeyPress = (chunk: string | undefined, key: readline.Key): void => {
    const actualChunk = chunk ?? '';
    const inspection = inspectInputTokenEvent(actualChunk, key);
    emitRecord({
      kind: 'keypress',
      chunk: describeChunk(actualChunk),
      key: describeKey(key),
      selected: inspection.selected,
      protocols: normalizeProtocols(inspection.protocols),
    });
    if (key.sequence === '\u0003' || inspection.selected.tokens.includes('ctrl+c')) {
      cleanup();
      process.exit(0);
    }
  };
 
  const onData = (data: Buffer): void => {
    const chunk = data.toString('utf8');
    const inspection = inspectInputTokenEvent(chunk, {
      name: undefined,
      sequence: chunk,
      ctrl: false,
      meta: false,
      shift: false,
    } satisfies readline.Key);
    emitRecord({
      kind: 'data',
      chunk: describeChunk(chunk),
      selected: inspection.selected,
      protocols: normalizeProtocols(inspection.protocols),
    });
  };
 
  process.stdin.on('keypress', onKeyPress);
  process.stdin.on('data', onData);
}
 
function emitRecord(payload: Record<string, unknown>): void {
  process.stdout.write(
    `${JSON.stringify({
      sequence: sequence++,
      at: new Date().toISOString(),
      ...payload,
    })}\n`,
  );
}
 
function describeChunk(value: string): DiagnosticChunk {
  return {
    text: value,
    escaped: escapeControlCharacters(value),
    hex: [...Buffer.from(value)].map((byte) => byte.toString(16).padStart(2, '0')).join(' '),
  };
}
 
function describeKey(key: readline.Key): DiagnosticKey {
  return {
    name: key.name,
    sequence: key.sequence,
    ctrl: key.ctrl,
    meta: key.meta,
    shift: key.shift,
  };
}
 
function normalizeProtocols(protocols: {
  legacy: InputProtocolInspection;
  kitty: InputProtocolInspection;
  win32: InputProtocolInspection;
}): Record<string, InputProtocolInspection & { rawEventCount: number }> {
  return {
    legacy: withRawEventCount(protocols.legacy),
    kitty: withRawEventCount(protocols.kitty),
    win32: withRawEventCount(protocols.win32),
  };
}
 
function withRawEventCount(protocol: InputProtocolInspection): InputProtocolInspection & { rawEventCount: number } {
  return {
    ...protocol,
    rawEventCount: protocol.tokens.length + protocol.repeatTokens.length + protocol.releaseTokens.length,
  };
}
 
function escapeControlCharacters(value: string): string {
  // eslint-disable-next-line no-control-regex
  return value.replaceAll(/[\u0000-\u001f\u007f-\u009f]/g, (character) => {
    const code = character.codePointAt(0) ?? 0;
    return `\\u${code.toString(16).padStart(4, '0')}`;
  });
}