All files / player-terminal/src/node node-input-runtime.ts

80.16% Statements 198/247
68.07% Branches 113/166
91.66% Functions 22/24
80.08% Lines 197/246

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 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548                                                                  4x             3x       14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x   14x 14x 14x 14x 14x   14x 57x                         14x             14x 4x           14x         17x 17x 17x 17x   17x   17x                             17x       17x 3x     17x 6x 6x                 17x 9x 9x                 17x     14x 17x 1x   16x 1x 1x   15x 1x 1x   14x 1x 1x     13x 13x 2x       2x     11x 1x     1x     10x             14x 25x 2x                   23x 23x 9x 9x           23x 23x 7x     16x 13x 14x   13x     3x 3x   3x       3x 1x 1x   2x         2x 2x               2x 1x     1x       14x 3x       3x 3x 3x             3x 3x 3x               3x     14x 13x 2x   11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 10x 10x   11x         14x 14x 3x   11x 11x 11x 11x 11x 11x 14x 14x 14x         14x                   23x 23x               23x 23x 23x 23x       23x 7x       7x 7x 7x 7x 7x 2x 3x           5x       16x 2x 2x 2x 2x 2x               2x     14x             17x           17x     17x   17x     17x 17x 17x 17x       4x 4x     16x       7x             9x 9x 9x 9x 3x 3x     3x 3x 3x   9x 9x       9x             4x     1x       16x       2x     2x               15x 15x 17x 15x   2x 2x 2x     2x 2x       15x 17x 17x 17x         15x             15x 13x   2x                                                                    
import readline from 'node:readline';
import type { LogEntry } from '@be-music/shared-utils/log';
import { beginStatefulKeyboardProtocolOptIn, resolveInputTokenEvent } from '../manual-input.ts';
import {
  resolveHighSpeedControlActionFromLaneChannels,
  type HighSpeedControlAction,
  type PlayerInputSignalBus,
} from '@be-music/player-engine/signals';
import { beginSharedRawInputCapture, type RawInputCapture } from '../raw-input-capture.ts';
 
export interface NodeInputRuntimeOptions {
  mode: 'auto' | 'manual';
  inputSignals: PlayerInputSignalBus;
  inputTokenToChannels: ReadonlyMap<string, readonly string[]>;
  onLog?: (entry: LogEntry) => void;
}
 
export interface NodeInputRuntime {
  start: () => void;
  stop: () => void;
  /**
   * `true` when the terminal had already negotiated a stateful keyboard protocol when the runtime was created
   * ({@link hasNegotiatedStatefulKeyboardProtocol}), so the play's keys report their releases from the first one
   * (`PlayerInputRuntime.reportsKeyReleases`). Absent otherwise: the engine detects it from the first `kitty-state`.
   */
  reportsKeyReleases?: true;
}
 
/**
 * Whether the terminal has answered the stateful keyboard protocol opt-in (the kitty keyboard protocol, or Windows'
 * win32-input-mode) with a key event in that protocol since the process started. The runtime opts in again at every
 * play's start, so from then on each play's keys report their releases.
 */
let statefulKeyboardProtocolNegotiated = false;
 
/**
 * True once the terminal has sent a key event in a stateful keyboard protocol (kitty, or win32-input-mode) during an
 * earlier play of this process: a play started now can declare that its input reports key releases.
 */
export function hasNegotiatedStatefulKeyboardProtocol(): boolean {
  return statefulKeyboardProtocolNegotiated;
}
 
export function createNodeInputRuntime(options: NodeInputRuntimeOptions): NodeInputRuntime {
  const reportsKeyReleases = statefulKeyboardProtocolNegotiated;
  const stdin = process.stdin as NodeJS.ReadStream & { isRaw?: boolean };
  const canCaptureInput = process.stdin.isTTY;
  let started = false;
  let stopped = false;
  let wasRawMode = false;
  const shouldResetRawModeOnStart = process.platform === 'win32';
  let rawInputCapture: RawInputCapture | undefined;
  let suppressKeypressUntilMs = 0;
  let stopStatefulKeyboardProtocol: () => void = () => undefined;
  let pendingProtocolKeypress = '';
  let pendingProtocolKeypressUpdatedAtMs = 0;
  let lastAcceptedInputSignature = '';
  let lastAcceptedInputSource: 'keypress' | 'data' | undefined;
  let lastAcceptedInputAtMs = 0;
  let loggedFirstKeyPress = false;
  let loggedFirstRawData = false;
  let loggedFirstAcceptedInput = false;
  let loggedFirstIgnoredInput = false;
 
  const emitRuntimeLog = (event: string, fields?: Record<string, unknown>): void => {
    options.onLog?.({
      source: 'input-runtime',
      level: 'info',
      event,
      fields: {
        emittedAtUnixMs: Date.now(),
        emittedAtMonotonicMs: performance.now(),
        mode: options.mode,
        ...fields,
      },
    });
  };
 
  emitRuntimeLog('input-runtime.created', {
    canCaptureInput,
    platform: process.platform,
    stdinIsRaw: Boolean(stdin.isRaw),
    mappedTokenCount: options.inputTokenToChannels.size,
  });
 
  const emitInterrupt = (reason: 'escape' | 'ctrl-c' | 'restart'): void => {
    options.inputSignals.pushCommand({
      kind: 'interrupt',
      reason,
    });
  };
 
  const emitManualInput = (
    inputEvent: ReturnType<typeof resolveInputTokenEvent>,
    source: 'keypress' | 'data',
    pressedAt: number,
  ): void => {
    const pressTokens = inputEvent.tokens;
    const repeatTokens = inputEvent.repeatTokens;
    const releaseTokens = inputEvent.releaseTokens;
    const isStatefulProtocol = inputEvent.protocol !== 'legacy';
    const acceptedRawLegacyFallback =
      source === 'data' && inputEvent.protocol === 'legacy' && process.platform === 'win32' && pressTokens.length > 0;
 
    Iif (source === 'data' && !isStatefulProtocol && !acceptedRawLegacyFallback) {
      if (!loggedFirstIgnoredInput) {
        loggedFirstIgnoredInput = true;
        emitRuntimeLog('input-runtime.input.ignored', {
          source,
          protocol: inputEvent.protocol,
          tokens: pressTokens.join(','),
          repeatTokens: repeatTokens.join(','),
          releaseTokens: releaseTokens.join(','),
          reason: 'raw-data-not-stateful',
        });
      }
      return;
    }
 
    Iif (isDuplicateAcceptedInput(inputEvent, source)) {
      return;
    }
 
    if (source === 'data' && (isStatefulProtocol || acceptedRawLegacyFallback)) {
      suppressKeypressUntilMs = Date.now() + 36;
    }
 
    if (isStatefulProtocol && (pressTokens.length > 0 || repeatTokens.length > 0 || releaseTokens.length > 0)) {
      statefulKeyboardProtocolNegotiated = true;
      options.inputSignals.pushCommand({
        kind: 'kitty-state',
        pressTokens: [...pressTokens],
        repeatTokens: [...repeatTokens],
        releaseTokens: [...releaseTokens],
        pressedAt,
      });
    }
 
    if (!loggedFirstAcceptedInput) {
      loggedFirstAcceptedInput = true;
      emitRuntimeLog('input-runtime.input.accepted', {
        source,
        protocol: inputEvent.protocol,
        tokens: pressTokens.join(','),
        repeatTokens: repeatTokens.join(','),
        releaseTokens: releaseTokens.join(','),
      });
    }
 
    handlePressedTokens(pressTokens, pressedAt);
  };
 
  const handlePressedTokens = (tokens: readonly string[], pressedAt: number): void => {
    if (tokens.length === 0) {
      return;
    }
    if (tokens.includes('ctrl+c')) {
      emitInterrupt('ctrl-c');
      return;
    }
    if (tokens.includes('escape')) {
      emitInterrupt('escape');
      return;
    }
    if (isRestartInputTokens(tokens)) {
      emitInterrupt('restart');
      return;
    }
 
    const highSpeedAction = resolveHighSpeedControlActionFromAltLaneTokens(tokens, options.inputTokenToChannels);
    if (highSpeedAction) {
      options.inputSignals.pushCommand({
        kind: 'high-speed',
        action: highSpeedAction,
      });
      return;
    }
 
    if (tokens.includes('space')) {
      options.inputSignals.pushCommand({
        kind: 'toggle-pause',
      });
      return;
    }
 
    options.inputSignals.pushCommand({
      kind: 'lane-input',
      tokens: [...tokens],
      pressedAt,
    });
  };
 
  const onKeyPress = (chunk: string | undefined, key: readline.Key): void => {
    if (options.mode === 'manual' && Date.now() < suppressKeypressUntilMs) {
      return;
    }
    // Wall-clock-ms snapshot at handler entry — `performance.timeOrigin + performance.now()` is
    // `Date.now()`-equivalent but with sub-ms precision. We use the wall-clock domain (not raw
    // `performance.now()`) because the engine runs in a `worker_threads` Worker on the TUI side and each
    // thread has its own `performance.timeOrigin`, so a raw `performance.now()` from this main thread
    // would always read as "in the future" from the worker's clock and the engine's defensive fallback
    // would silently swallow the press. The engine subtracts the wall-clock delta against this when
    // resolving the judge timestamp so a press that lands a few ms before the next 60 Hz tick still
    // resolves at its true timing.
    const pressedAt = performance.timeOrigin + performance.now();
    if (!loggedFirstKeyPress) {
      loggedFirstKeyPress = true;
      emitRuntimeLog('input-runtime.keypress.first', {
        chunk: chunk ?? '',
        sequence: key.sequence ?? '',
        keyName: key.name,
      });
    }
    const inputEvents = resolveKeyPressInputEvents(chunk, key);
    if (inputEvents.length === 0) {
      return;
    }
 
    if (options.mode === 'manual') {
      for (const inputEvent of inputEvents) {
        emitManualInput(inputEvent, 'keypress', pressedAt);
      }
      return;
    }
 
    const inputEvent = inputEvents[0]!;
    const tokens = inputEvent.tokens;
 
    Iif (key.sequence === '\u0003' || tokens.includes('ctrl+c')) {
      emitInterrupt('ctrl-c');
      return;
    }
    if (key.name?.toLowerCase() === 'escape' || key.sequence === '\u001b' || tokens.includes('escape')) {
      emitInterrupt('escape');
      return;
    }
    Iif (isRestartInputTokens(tokens) || isRestartKeyPress(chunk, key)) {
      emitInterrupt('restart');
      return;
    }
 
    const highSpeedAction = resolveHighSpeedControlActionFromAltLaneTokens(tokens, options.inputTokenToChannels, key);
    Iif (highSpeedAction) {
      options.inputSignals.pushCommand({
        kind: 'high-speed',
        action: highSpeedAction,
      });
      return;
    }
 
    if (tokens.includes('space') || isSpaceKey(key)) {
      options.inputSignals.pushCommand({
        kind: 'toggle-pause',
      });
      return;
    }
  };
 
  const onRawInputData = (data: Buffer): void => {
    Iif (options.mode !== 'manual') {
      return;
    }
    // Same wall-clock-ms snapshot rationale as `onKeyPress` — see that handler's comment.
    const pressedAt = performance.timeOrigin + performance.now();
    const chunk = data.toString('utf8');
    const inputEvent = resolveInputTokenEvent(chunk, {
      name: undefined,
      sequence: chunk,
      ctrl: false,
      meta: false,
      shift: false,
    } satisfies readline.Key);
    Eif (!loggedFirstRawData) {
      loggedFirstRawData = true;
      emitRuntimeLog('input-runtime.raw-data.first', {
        chunk,
        protocol: inputEvent.protocol,
        tokens: inputEvent.tokens.join(','),
        repeatTokens: inputEvent.repeatTokens.join(','),
        releaseTokens: inputEvent.releaseTokens.join(','),
      });
    }
    emitManualInput(inputEvent, 'data', pressedAt);
  };
 
  const start = (): void => {
    if (!canCaptureInput || started) {
      return;
    }
    started = true;
    stopped = false;
    pendingProtocolKeypress = '';
    pendingProtocolKeypressUpdatedAtMs = 0;
    lastAcceptedInputSignature = '';
    lastAcceptedInputSource = undefined;
    lastAcceptedInputAtMs = 0;
    wasRawMode = Boolean(stdin.isRaw);
    rawInputCapture = beginSharedRawInputCapture({
      forceResetRawMode: shouldResetRawModeOnStart,
    });
    readline.emitKeypressEvents(process.stdin);
    process.stdin.on('keypress', onKeyPress);
    if (options.mode === 'manual') {
      stopStatefulKeyboardProtocol = beginStatefulKeyboardProtocolOptIn(process.stdout, process.platform, process.env);
      process.stdin.prependListener('data', onRawInputData);
    }
    emitRuntimeLog('input-runtime.started', {
      stdinIsRaw: Boolean(stdin.isRaw),
    });
  };
 
  const stop = (): void => {
    if (!canCaptureInput || stopped) {
      return;
    }
    stopped = true;
    pendingProtocolKeypress = '';
    pendingProtocolKeypressUpdatedAtMs = 0;
    process.stdin.removeListener('keypress', onKeyPress);
    process.stdin.removeListener('data', onRawInputData);
    rawInputCapture?.restore();
    rawInputCapture = undefined;
    stopStatefulKeyboardProtocol();
    emitRuntimeLog('input-runtime.stopped', {
      restoreRawMode: wasRawMode,
    });
  };
 
  return {
    start,
    stop,
    ...(reportsKeyReleases ? { reportsKeyReleases: true as const } : {}),
  };
 
  function resolveKeyPressInputEvents(
    chunk: string | undefined,
    key: readline.Key,
  ): Array<ReturnType<typeof resolveInputTokenEvent>> {
    const nowMs = Date.now();
    Iif (
      pendingProtocolKeypress.length > 0 &&
      nowMs - pendingProtocolKeypressUpdatedAtMs > PROTOCOL_KEYPRESS_FRAGMENT_TIMEOUT_MS
    ) {
      pendingProtocolKeypress = '';
      pendingProtocolKeypressUpdatedAtMs = 0;
    }
 
    const keyChunk = chunk ?? '';
    const keySequence = key.sequence ?? '';
    const piece = keyChunk.length > 0 ? keyChunk : keySequence;
    Iif (piece.length === 0) {
      return [];
    }
 
    if (pendingProtocolKeypress.length > 0) {
      Iif (!isProtocolKeypressContinuationPiece(piece)) {
        pendingProtocolKeypress = '';
        pendingProtocolKeypressUpdatedAtMs = 0;
      } else {
        pendingProtocolKeypress += piece;
        pendingProtocolKeypressUpdatedAtMs = nowMs;
        const consumed = consumeProtocolKeypressSequences(pendingProtocolKeypress);
        pendingProtocolKeypress = consumed.pending;
        if (consumed.sequences.length > 0) {
          return consumed.sequences.map((sequence) =>
            resolveInputTokenEvent(sequence, {
              ...key,
              sequence,
            }),
          );
        }
        return [];
      }
    }
 
    if (isProtocolKeypressStart(piece)) {
      pendingProtocolKeypress = piece;
      pendingProtocolKeypressUpdatedAtMs = nowMs;
      const consumed = consumeProtocolKeypressSequences(pendingProtocolKeypress);
      pendingProtocolKeypress = consumed.pending;
      Iif (consumed.sequences.length > 0) {
        return consumed.sequences.map((sequence) =>
          resolveInputTokenEvent(sequence, {
            ...key,
            sequence,
          }),
        );
      }
      return [];
    }
 
    return [resolveInputTokenEvent(keyChunk, key)];
  }
 
  function isDuplicateAcceptedInput(
    inputEvent: ReturnType<typeof resolveInputTokenEvent>,
    source: 'keypress' | 'data',
  ): boolean {
    const signature = [
      inputEvent.protocol,
      inputEvent.tokens.join(','),
      inputEvent.repeatTokens.join(','),
      inputEvent.releaseTokens.join(','),
    ].join('|');
    Iif (signature === 'legacy|||') {
      return false;
    }
    const nowMs = Date.now();
    const duplicate =
      source !== lastAcceptedInputSource &&
      signature === lastAcceptedInputSignature &&
      nowMs - lastAcceptedInputAtMs <= CROSS_SOURCE_DUPLICATE_WINDOW_MS;
    lastAcceptedInputSignature = signature;
    lastAcceptedInputSource = source;
    lastAcceptedInputAtMs = nowMs;
    return duplicate;
  }
}
 
const PROTOCOL_KEYPRESS_FRAGMENT_TIMEOUT_MS = 24;
const CROSS_SOURCE_DUPLICATE_WINDOW_MS = 8;
 
function isProtocolKeypressStart(piece: string): boolean {
  return piece.startsWith('\u001b[');
}
 
function isProtocolKeypressContinuationPiece(piece: string): boolean {
  return piece.includes('\u001b[') || /^[0-9;:_u]+$/.test(piece);
}
 
function consumeProtocolKeypressSequences(buffer: string): {
  sequences: string[];
  pending: string;
} {
  const sequences: string[] = [];
  let consumedLength = 0;
  const matcher = new RegExp(PROTOCOL_KEYPRESS_SEQUENCE.source, 'g');
  for (const match of buffer.matchAll(matcher)) {
    const start = match.index ?? -1;
    Iif (start !== consumedLength) {
      break;
    }
    const sequence = match[0];
    sequences.push(sequence);
    consumedLength += sequence.length;
  }
  let pending = buffer.slice(consumedLength);
  Iif (pending.length > 0 && !pending.startsWith('\u001b[')) {
    const nextProtocolStart = pending.indexOf('\u001b[');
    pending = nextProtocolStart >= 0 ? pending.slice(nextProtocolStart) : '';
  }
  return {
    sequences,
    pending,
  };
}
 
// eslint-disable-next-line no-control-regex
const PROTOCOL_KEYPRESS_SEQUENCE = /\u001b\[[0-9]+(?:;[0-9]+){5}_|\u001b\[[0-9:]+(?:;[0-9:]+)*u/;
 
function isSpaceKey(key: readline.Key): boolean {
  return key.name?.toLowerCase() === 'space' || key.sequence === ' ';
}
 
function isRestartInputTokens(tokens: readonly string[]): boolean {
  return tokens.includes('shift+r');
}
 
function isRestartKeyPress(chunk: string | undefined, key: readline.Key): boolean {
  Iif (typeof chunk === 'string' && chunk === 'R') {
    return true;
  }
  return key.name?.toLowerCase() === 'r' && Boolean(key.shift);
}
 
function resolveHighSpeedControlActionFromAltLaneTokens(
  tokens: readonly string[],
  inputTokenToChannels: ReadonlyMap<string, readonly string[]>,
  key?: readline.Key,
): HighSpeedControlAction | undefined {
  const channels = new Set<string>();
  const addChannelsForAltToken = (token: string): void => {
    if (!token.startsWith('alt+')) {
      return;
    }
    const baseToken = token.slice('alt+'.length).toLowerCase();
    const mapped = inputTokenToChannels.get(baseToken);
    Iif (!mapped) {
      return;
    }
    for (const channel of mapped) {
      channels.add(channel);
    }
  };
 
  for (const token of tokens) {
    const normalizedToken = token.toLowerCase();
    addChannelsForAltToken(normalizedToken);
    Iif (normalizedToken.startsWith('option+')) {
      addChannelsForAltToken(`alt+${normalizedToken.slice('option+'.length)}`);
    }
  }
 
  Iif (key?.meta) {
    const keyName = normalizeLegacyKeyNameToken(key.name);
    if (keyName) {
      addChannelsForAltToken(`alt+${keyName}`);
    }
  }
 
  if (channels.size === 0) {
    return undefined;
  }
  return resolveHighSpeedControlActionFromLaneChannels([...channels]);
}
 
function normalizeLegacyKeyNameToken(name: string | undefined): string | undefined {
  if (typeof name !== 'string' || name.length === 0) {
    return undefined;
  }
  const lowered = name.toLowerCase();
  if (lowered.length === 1) {
    return lowered;
  }
  if (lowered === 'comma') {
    return ',';
  }
  if (lowered === 'period') {
    return '.';
  }
  if (lowered === 'slash') {
    return '/';
  }
  if (lowered === 'semicolon') {
    return ';';
  }
  if (lowered === 'quote') {
    return "'";
  }
  if (lowered === 'leftbracket') {
    return '[';
  }
  if (lowered === 'rightbracket') {
    return ']';
  }
  return undefined;
}