{"version":3,"sources":["../src/index.ts","../src/core/Mouse.ts","../src/types/error.ts","../src/core/EventStreamFactory.ts","../src/core/MouseConvenienceMethods.ts","../src/utils/freeze.ts","../src/parser/constants.ts","../src/parser/ansiParser.ts","../src/core/ClickDetector.ts","../src/core/PositionTracker.ts","../src/core/MouseEventManager.ts","../src/utils/validation.ts","../src/core/TTYController.ts"],"sourcesContent":["export { Mouse } from './core/Mouse';\nexport type { MouseEvent, MouseEventAction, MouseOptions, ReadableStreamWithEncoding } from './types';\nexport { MouseError } from './types';\n","import { EventEmitter } from 'node:events';\nimport type { ListenerFor, MouseEvent, MouseEventAction, MouseOptions, ReadableStreamWithEncoding } from '../types';\nimport { EventStreamFactory } from './EventStreamFactory';\nimport { MouseConvenienceMethods } from './MouseConvenienceMethods';\nimport { MouseEventManager } from './MouseEventManager';\nimport { TTYController } from './TTYController';\n\n/**\n * Represents and manages mouse events in a TTY environment.\n *\n * This class is a **facade** that composes smaller, focused components:\n * - **TTYController**: Manages terminal state and stream I/O\n * - **MouseEventManager**: Handles event emission and detection\n * - **EventStreamFactory**: Creates async generator streams\n * - **MouseConvenienceMethods**: Provides promise-based convenience methods\n *\n * **Automatic Cleanup:**\n * Mouse instances automatically register for cleanup when `enable()` is called.\n * If a Mouse instance is garbage collected without explicit cleanup via `disable()` or `destroy()`,\n * the TTYController ensures that stdin event listeners are removed to prevent memory leaks.\n *\n * **Recommended Cleanup:**\n * Despite automatic cleanup, it's still recommended to explicitly call `destroy()` when done\n * with a Mouse instance for immediate and predictable resource release.\n */\nclass Mouse {\n  private readonly tty: TTYController;\n  private readonly eventManager: MouseEventManager;\n  private readonly streamFactory: EventStreamFactory;\n  private readonly convenience: MouseConvenienceMethods;\n\n  /**\n   * Result type for terminal capability checks.\n   */\n  static readonly SupportCheckResult = {\n    /** Mouse events are supported */\n    Supported: 'supported',\n    /** Input stream is not a TTY */\n    NotTTY: 'not_tty',\n    /** Output stream is not a TTY */\n    OutputNotTTY: 'output_not_tty',\n  } as const;\n\n  /**\n   * Constructs a new Mouse instance.\n   * @param options Optional configuration options for mouse behavior and dependencies.\n   * @param options.emitter The event emitter to use for emitting mouse events (defaults to a new EventEmitter).\n   * @param options.inputStream The readable stream to listen for mouse events on (defaults to process.stdin).\n   * @param options.outputStream The writable stream to send control sequences to (defaults to process.stdout).\n   * @param options.setRawMode Custom function to set raw mode (defaults to inputStream.setRawMode).\n   * @param options.clickDistanceThreshold Maximum allowed distance for click detection.\n   *\n   * @example\n   * ```ts\n   * // Default configuration\n   * const mouse = new Mouse();\n   *\n   * // Custom streams\n   * const mouse2 = new Mouse({\n   *   inputStream: customStdin,\n   *   outputStream: customStdout,\n   * });\n   *\n   * // Custom emitter\n   * const mouse3 = new Mouse({\n   *   emitter: myEventEmitter,\n   * });\n   *\n   * // Testing with mock setRawMode\n   * const mockSetRawMode = vi.fn();\n   * const mouse4 = new Mouse({ setRawMode: mockSetRawMode });\n   *\n   * // Custom click threshold\n   * const mouse5 = new Mouse({ clickDistanceThreshold: 0 });\n   *\n   * // All options combined\n   * const mouse6 = new Mouse({\n   *   emitter: myEventEmitter,\n   *   inputStream: customStdin,\n   *   outputStream: customStdout,\n   *   setRawMode: mockSetRawMode,\n   *   clickDistanceThreshold: 5,\n   * });\n   * ```\n   */\n  constructor(options?: MouseOptions) {\n    const inputStream = options?.inputStream ?? process.stdin;\n    const outputStream = options?.outputStream ?? process.stdout;\n    const eventEmitter = options?.emitter ?? new EventEmitter();\n\n    // Create event manager first (needed by TTYController for handleEvent)\n    this.eventManager = new MouseEventManager(eventEmitter, options);\n\n    // Create TTY controller with event handler and custom setRawMode\n    this.tty = new TTYController(\n      inputStream,\n      outputStream,\n      (data: Buffer) => this.eventManager.handleEvent(data, this.tty.isPaused()),\n      options?.setRawMode,\n    );\n\n    // Create stream factory and convenience methods\n    this.streamFactory = new EventStreamFactory(this.eventManager.getEmitter());\n    this.convenience = new MouseConvenienceMethods(this.eventManager.getEmitter(), () =>\n      this.eventManager.getLastPosition(),\n    );\n  }\n\n  /**\n   * Checks if the current terminal environment supports mouse events.\n   *\n   * This is a convenience method that wraps {@link checkSupport} and returns\n   * a simple boolean. It checks if the provided streams (or `process.stdin`/\n   * `process.stdout` by default) are TTYs.\n   *\n   * **Use Cases:**\n   * - Before creating a Mouse instance in environments that may not support TTY\n   * - To provide better error messages in CLI tools\n   * - To conditionally enable mouse features in applications\n   * - Checking custom streams before passing to Mouse constructor\n   *\n   * **Note:** For detailed error information (e.g., to distinguish between\n   * input and output stream issues), use {@link checkSupport} instead.\n   *\n   * @param inputStream Optional input stream to check (defaults to process.stdin)\n   * @param outputStream Optional output stream to check (defaults to process.stdout)\n   * @returns true if the terminal likely supports mouse events\n   *\n   * @example\n   * ```ts\n   * import { Mouse } from 'xterm-mouse';\n   *\n   * // Check default streams\n   * if (Mouse.isSupported()) {\n   *   const mouse = new Mouse();\n   *   mouse.enable();\n   * } else {\n   *   console.log('Mouse events not supported in this environment');\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Check custom streams\n   * const customStdin = getCustomStdin();\n   * const customStdout = getCustomStdout();\n   *\n   * if (Mouse.isSupported(customStdin, customStdout)) {\n   *   const mouse = new Mouse({\n   *     inputStream: customStdin,\n   *     outputStream: customStdout,\n   *   });\n   *   mouse.enable();\n   * }\n   * ```\n   */\n  static isSupported(inputStream?: ReadableStreamWithEncoding, outputStream?: NodeJS.WriteStream): boolean {\n    const result = Mouse.checkSupport({ inputStream, outputStream });\n    return result === Mouse.SupportCheckResult.Supported;\n  }\n\n  /**\n   * Performs a detailed check of terminal mouse event support.\n   *\n   * This method provides more information than `isSupported()` by checking\n   * specific streams and returning the reason if support is not available.\n   *\n   * **Use Cases:**\n   * - Need detailed information about why mouse events aren't supported\n   * - Checking custom streams\n   * - Providing user-friendly error messages\n   *\n   * @param options Optional configuration with custom streams to check\n   * @param options.inputStream The input stream to check (defaults to process.stdin)\n   * @param options.outputStream The output stream to check (defaults to process.stdout)\n   * @returns A result from SupportCheckResult indicating support status\n   *\n   * @example\n   * ```ts\n   * import { Mouse } from 'xterm-mouse';\n   *\n   * const result = Mouse.checkSupport();\n   * if (result === Mouse.SupportCheckResult.Supported) {\n   *   console.log('Mouse events are supported!');\n   * } else if (result === Mouse.SupportCheckResult.NotTTY) {\n   *   console.error('Not running in a terminal');\n   * } else if (result === Mouse.SupportCheckResult.OutputNotTTY) {\n   *   console.error('Output is not a terminal');\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Check custom streams\n   * const result = Mouse.checkSupport({\n   *   inputStream: myCustomStdin,\n   *   outputStream: myCustomStdout,\n   * });\n   * ```\n   */\n  static checkSupport(options?: Pick<MouseOptions, 'inputStream' | 'outputStream'>): string {\n    const inputStream = options?.inputStream ?? process.stdin;\n    const outputStream = options?.outputStream ?? process.stdout;\n\n    if (!inputStream.isTTY) {\n      return Mouse.SupportCheckResult.NotTTY;\n    }\n    if (!outputStream.isTTY) {\n      return Mouse.SupportCheckResult.OutputNotTTY;\n    }\n    return Mouse.SupportCheckResult.Supported;\n  }\n\n  /**\n   * Enables mouse event tracking.\n   *\n   * This method activates mouse event capture by putting the input stream into raw mode\n   * and sending the appropriate ANSI escape sequences to enable mouse tracking in the terminal.\n   *\n   * **TTY Requirement:** This method requires the input stream to be a TTY (terminal).\n   * Mouse events cannot be captured when the input is piped, redirected, or running in a\n   * non-interactive environment. Check `process.stdin.isTTY` before calling this method.\n   *\n   * **Error Handling:** This method throws a `MouseError` if:\n   * - The input stream is not a TTY (interactive terminal)\n   * - The stream cannot be put into raw mode\n   * - The terminal does not support the mouse tracking ANSI codes\n   *\n   * **Automatic Cleanup:**\n   * When `enable()` is called, the Mouse instance registers with a FinalizationRegistry.\n   * If the instance is garbage collected without explicit cleanup via `disable()` or `destroy()`,\n   * the registry will automatically remove the stdin listener and restore stream state to prevent\n   * memory leaks. This is a safety net - explicit cleanup via `destroy()` is still recommended\n   * for immediate and predictable resource release.\n   *\n   * **Side Effects:**\n   * - The input stream is switched to raw mode (character-by-character input)\n   * - The input encoding is set to UTF-8\n   * - The input stream is resumed if paused\n   * - ANSI escape codes are written to the output stream to enable mouse tracking\n   * - The original stream settings are preserved for restoration on `disable()`\n   * - The Mouse instance is registered with the FinalizationRegistry for automatic cleanup\n   *\n   * @throws {Error} If the input stream is not a TTY\n   * @throws {MouseError} If enabling mouse tracking fails\n   * @see {@link disable} to disable tracking and restore the stream\n   * @see {@link destroy} for recommended cleanup method\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   *\n   * if (process.stdin.isTTY) {\n   *   mouse.enable();\n   *   mouse.on('press', (event) => {\n   *     console.log(`Pressed at ${event.x}, ${event.y}`);\n   *   });\n   * } else {\n   *   console.error('Mouse tracking requires a TTY');\n   * }\n   * ```\n   */\n  public enable = (): void => {\n    this.tty.enable();\n  };\n\n  /**\n   * Disables mouse event tracking.\n   * This method restores the input stream to its previous state and stops listening for data.\n   * @see {@link enable} to enable tracking and capture mouse events\n   */\n  public disable = (): void => {\n    this.tty.disable();\n  };\n\n  /**\n   * Pauses mouse event emission without disabling terminal mouse mode.\n   *\n   * This method temporarily stops the emission of mouse events while keeping\n   * the terminal mouse mode active. This is useful when you want to temporarily\n   * ignore mouse events without the overhead of disabling and re-enabling mouse tracking.\n   *\n   * **Idempotent:** Calling this method when already paused has no effect.\n   *\n   * **No Terminal State Changes:** Unlike {@link disable}, this method does not:\n   * - Send ANSI escape codes to the terminal\n   * - Modify the input stream's raw mode\n   * - Change the input stream encoding\n   * - Remove event listeners from the input stream\n   *\n   * **Difference from disable():**\n   * - pause(): Stops event emission only, terminal mouse mode remains active\n   * - disable(): Stops event emission AND deactivates terminal mouse mode\n   *\n   * @see {@link resume} to resume event emission\n   * @see {@link disable} to completely disable mouse tracking\n   * @see {@link isPaused} to check if currently paused\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Temporarily ignore mouse events during an operation\n   * mouse.pause();\n   * // ... perform operations that should not trigger mouse events\n   * mouse.resume();\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Comparing pause() vs disable()\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Using pause(): Fast, no terminal overhead\n   * mouse.pause();\n   * performQuickOperation();\n   * mouse.resume(); // Terminal mouse mode was never disabled\n   *\n   * // VS using disable(): Slower, terminal overhead\n   * mouse.disable();\n   * performQuickOperation();\n   * mouse.enable(); // Had to re-enable terminal mouse mode\n   * ```\n   */\n  public pause = (): void => {\n    this.tty.pause();\n  };\n\n  /**\n   * Resumes mouse event emission without modifying terminal mouse mode.\n   *\n   * This method resumes the emission of mouse events after they were paused\n   * using {@link pause}. The terminal mouse mode remains active throughout.\n   *\n   * **Idempotent:** Calling this method when not paused has no effect.\n   *\n   * **No Terminal State Changes:** Unlike {@link enable}, this method does not:\n   * - Send ANSI escape codes to the terminal\n   * - Modify the input stream's raw mode\n   * - Change the input stream encoding\n   * - Add event listeners to the input stream\n   *\n   * **Difference from enable():**\n   * - resume(): Resumes event emission only, assumes terminal mouse mode is already active\n   * - enable(): Activates terminal mouse mode AND resumes event emission\n   *\n   * @see {@link pause} to pause event emission\n   * @see {@link enable} to completely enable mouse tracking\n   * @see {@link isPaused} to check if currently paused\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Temporarily ignore mouse events during an operation\n   * mouse.pause();\n   * // ... perform operations that should not trigger mouse events\n   * mouse.resume(); // Events will now be emitted again\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Comparing resume() vs enable()\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Pause and resume: Fast state change\n   * mouse.pause();\n   * performOperation();\n   * mouse.resume(); // No terminal overhead\n   *\n   * // VS disable and enable: Slower, re-enables terminal\n   * mouse.disable();\n   * performOperation();\n   * mouse.enable(); // Re-enables terminal mouse mode (ANSI codes, raw mode)\n   * ```\n   */\n  public resume = (): void => {\n    this.tty.resume();\n  };\n\n  /**\n   * Registers a listener for a specific mouse event.\n   *\n   * **Type Inference:**\n   * This method uses TypeScript's type inference to provide accurate types for the event parameter\n   * based on the event name. For example:\n   * - For 'wheel' events, `event.button` is typed as `'wheel-up' | 'wheel-down' | 'wheel-left' | 'wheel-right'`\n   * - For 'move' events, `event.button` is typed as `'none'`\n   * - For 'drag' events, `event.button` excludes wheel buttons\n   *\n   * @param event The name of the event to listen for.\n   * @param listener The callback function to execute when the event is triggered.\n   * @returns The event emitter instance.\n   * @see {@link off} to remove the listener\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // TypeScript knows event.button is a wheel button type here\n   * mouse.on('wheel', (event) => {\n   *   console.log(event.button); // 'wheel-up' | 'wheel-down' | 'wheel-left' | 'wheel-right'\n   * });\n   *\n   * // TypeScript knows event.button is 'none' here\n   * mouse.on('move', (event) => {\n   *   console.log(event.button); // 'none'\n   * });\n   * ```\n   */\n  public on = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    return this.eventManager.on(event, listener);\n  };\n\n  /**\n   * Removes a listener for a specific mouse event.\n   *\n   * **Type Inference:**\n   * This method uses the same type inference as `on()` to ensure type safety when removing listeners.\n   *\n   * @param event The name of the event to stop listening for.\n   * @param listener The callback function to remove.\n   * @returns The event emitter instance.\n   * @see {@link on} to add a listener\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * const handler = (event: EventByAction<'press'>) => {\n   *   console.log(`Pressed at ${event.x}, ${event.y}`);\n   * };\n   *\n   * mouse.on('press', handler);\n   * mouse.off('press', handler);\n   * ```\n   */\n  public off = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    return this.eventManager.off(event, listener);\n  };\n\n  /**\n   * Registers a one-time listener that automatically removes itself after the first event.\n   *\n   * **Type Inference:**\n   * This method uses the same type inference as `on()` to provide accurate types for the event parameter.\n   *\n   * **Automatic Cleanup:**\n   * The listener is automatically removed after the first invocation, preventing memory leaks\n   * and eliminating the need for manual cleanup code.\n   *\n   * @param event The name of the event to listen for.\n   * @param listener The callback function to execute once when the event is triggered.\n   * @returns The event emitter instance.\n   * @see {@link on} for persistent listeners\n   * @see {@link off} to manually remove listeners\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Listen for a single click\n   * mouse.once('click', (event) => {\n   *   console.log('Got one click!', event);\n   *   // Listener is automatically removed after this execution\n   * });\n   *\n   * // Wait for first wheel event\n   * mouse.once('wheel', (event) => {\n   *   // TypeScript knows event.button is a wheel button type\n   *   console.log(`Scrolled: ${event.button}`);\n   * });\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Simplified one-time event handling\n   * // Before (manual cleanup required):\n   * const handler = (event) => {\n   *   console.log('Got click', event);\n   *   mouse.off('click', handler);\n   *   // continue logic...\n   * };\n   * mouse.on('click', handler);\n   *\n   * // After (automatic cleanup):\n   * mouse.once('click', (event) => {\n   *   console.log('Got click', event);\n   *   // continue logic... listener already removed\n   * });\n   * ```\n   */\n  public once = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    return this.eventManager.once(event, listener);\n  };\n\n  /**\n   * Returns an async generator that yields mouse events of a specific type.\n   *\n   * This method provides a convenient way to iterate over mouse events using async/await syntax.\n   * The async generator will yield events as they occur, allowing for clean and readable event handling code.\n   *\n   * **Cancellation with AbortSignal:** The async generator supports cancellation through the `signal` option.\n   * When the provided AbortSignal is aborted, the generator will throw a `MouseError` and clean up all listeners.\n   * This is particularly useful for implementing timeout functionality or user-initiated cancellation.\n   *\n   * **Queue Management:**\n   * - By default, events are queued up to `maxQueue` (default: 100, max: 1000)\n   * - When `latestOnly` is true, only the most recent event is buffered, dropping intermediate events\n   * - This is useful for high-frequency events like 'move' where you only care about the latest position\n   *\n   * **Error Handling:** Errors from the mouse event stream will be thrown from the generator,\n   * allowing for try/catch error handling in the iteration loop.\n   *\n   * **Cleanup:** The generator automatically cleans up event listeners when:\n   * - The iteration loop completes (breaks or returns)\n   * - An error is thrown\n   * - The abort signal is triggered\n   *\n   * @param type The type of mouse event to listen for (e.g., 'press', 'drag', 'wheel').\n   * @param options Configuration for the event stream.\n   * @param options.latestOnly If true, only the latest event is buffered. Defaults to false.\n   * @param options.maxQueue The maximum number of events to queue. Defaults to 100, with a maximum of 1000.\n   * @param options.signal An AbortSignal to cancel the async generator and clean up resources.\n   * @yields {MouseEvent} A mouse event object containing x, y, button, and action properties.\n   * @throws {MouseError} When the abort signal is triggered or a mouse event stream error occurs.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Collect 5 mouse clicks\n   * const clicks: MouseEvent[] = [];\n   * for await (const event of mouse.eventsOf('click')) {\n   *   clicks.push(event);\n   *   console.log(`Click at ${event.x}, ${event.y}`);\n   *   if (clicks.length >= 5) break;\n   * }\n   * mouse.disable();\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Track mouse movement with cancellation after 5 seconds\n   * const controller = new AbortController();\n   * setTimeout(() => controller.abort(), 5000);\n   *\n   * try {\n   *   for await (const event of mouse.eventsOf('move', { signal: controller.signal })) {\n   *     console.log(`Mouse moved to ${event.x}, ${event.y}`);\n   *   }\n   * } catch (err) {\n   *   if (err instanceof MouseError && err.message.includes('aborted')) {\n   *     console.log('Tracking stopped after timeout');\n   *   } else {\n   *     throw err;\n   *   }\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Track only the latest mouse position (for high-frequency events)\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Display cursor position updates\n   * for await (const event of mouse.eventsOf('move', { latestOnly: true })) {\n   *   // Clear line and show position\n   *   process.stdout.write(`\\r\\x1b[KPosition: ${event.x}, ${event.y}`);\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Implement drag detection with user cancellation\n   * const controller = new AbortController();\n   *\n   * // Listen for Ctrl+C to cancel\n   * process.stdin.setRawMode(true);\n   * process.stdin.on('data', (key) => {\n   *   if (key[0] === 3) { // Ctrl+C\n   *     controller.abort();\n   *   }\n   * });\n   *\n   * try {\n   *   for await (const event of mouse.eventsOf('drag', { signal: controller.signal })) {\n   *     console.log(`Dragging at ${event.x}, ${event.y} with button ${event.button}`);\n   *   }\n   * } catch (err) {\n   *   if (err instanceof MouseError && err.message.includes('aborted')) {\n   *     console.log('\\nDrag tracking cancelled by user');\n   *   }\n   * } finally {\n   *   mouse.disable();\n   * }\n   * ```\n   */\n  public async *eventsOf(\n    type: MouseEventAction,\n    options?: { latestOnly?: boolean; maxQueue?: number; signal?: AbortSignal },\n  ): AsyncGenerator<MouseEvent> {\n    yield* this.streamFactory.eventsOf(type, options);\n  }\n\n  /**\n   * Returns an async generator that yields move events at most once per specified interval.\n   *\n   * This method provides debounced move events, reducing event frequency for smooth animations\n   * and performance optimization. Unlike `eventsOf('move')` which yields every move event,\n   * this method waits for a quiet period before emitting, ensuring you only get events at\n   * a controlled rate.\n   *\n   * **Debouncing Behavior:**\n   * - Move events are collected during the debounce interval\n   * - Only the most recent event is yielded after the interval elapses\n   * - If the mouse continues moving, the timer restarts with each new event\n   * - This is ideal for UI updates, animations, and position tracking where you want\n   *   to avoid excessive redraws\n   *\n   * **Cancellation with AbortSignal:** The async generator supports cancellation through\n   * the `signal` option. When the provided AbortSignal is aborted, the generator will stop\n   * immediately and clean up all listeners.\n   *\n   * **Cleanup:** The generator automatically cleans up event listeners and timers when:\n   * - The iteration loop completes (breaks or returns)\n   * - An error is thrown\n   * - The abort signal is triggered\n   *\n   * @param options Configuration for the debounced event stream.\n   * @param options.interval Minimum time in milliseconds between yielded events. Defaults to 16 (~60fps).\n   * @param options.signal An AbortSignal to cancel the async generator and clean up resources.\n   * @yields {MouseEvent} A mouse move event object containing x, y, button, and action properties.\n   * @throws {MouseError} When the abort signal is triggered or a mouse event stream error occurs.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Track mouse position at ~60fps for smooth cursor following\n   * for await (const event of mouse.debouncedMoveEvents()) {\n   *   console.log(`Mouse at ${event.x}, ${event.y}`);\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Slower update rate (30fps) for less frequent UI updates\n   * for await (const event of mouse.debouncedMoveEvents({ interval: 33 })) {\n   *   updateCursorPosition(event.x, event.y);\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Debounced move events with cancellation\n   * const controller = new AbortController();\n   * setTimeout(() => controller.abort(), 10000); // Stop after 10 seconds\n   *\n   * try {\n   *   for await (const event of mouse.debouncedMoveEvents({ signal: controller.signal })) {\n   *     // Smooth animation update at 60fps\n   *     renderFrame(event.x, event.y);\n   *   }\n   * } catch (err) {\n   *   if (err instanceof MouseError && err.message.includes('aborted')) {\n   *     console.log('Animation stopped');\n   *   }\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Comparing debounced vs raw move events\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Raw: Can fire hundreds of times per second\n   * for await (const event of mouse.eventsOf('move')) {\n   *   console.log('Raw move'); // May print too fast to read\n   *   if (event.x > 50) break;\n   * }\n   *\n   * // Debounced: Controlled rate, easier to process\n   * for await (const event of mouse.debouncedMoveEvents({ interval: 100 })) {\n   *   console.log('Debounced move'); // Prints at most 10 times per second\n   *   if (event.x > 50) break;\n   * }\n   * ```\n   */\n  public async *debouncedMoveEvents(options?: { interval?: number; signal?: AbortSignal }): AsyncGenerator<MouseEvent> {\n    yield* this.streamFactory.debouncedMoveEvents(options);\n  }\n\n  /**\n   * Returns an async generator that yields all mouse events.\n   * Each yielded value is an object containing the event type and the event data.\n   * @param options Configuration for the event stream.\n   * @param options.latestOnly If true, only the latest event is buffered. Defaults to false.\n   * @param options.maxQueue The maximum number of events to queue. Defaults to 1000.\n   * @param options.signal An AbortSignal to cancel the async generator.\n   * @yields {{ type: MouseEventAction; event: MouseEvent }} An object with the event type and data.\n   */\n  public async *stream(options?: {\n    latestOnly?: boolean;\n    maxQueue?: number;\n    signal?: AbortSignal;\n  }): AsyncGenerator<{ type: MouseEventAction; event: MouseEvent }> {\n    yield* this.streamFactory.stream(options);\n  }\n\n  /**\n   * Checks if mouse event tracking is currently enabled.\n   * @returns {boolean} True if enabled, false otherwise.\n   */\n  public isEnabled(): boolean {\n    return this.tty.isEnabled();\n  }\n\n  /**\n   * Checks if mouse event emission is currently paused.\n   *\n   * This method returns the current pause state of mouse event emission.\n   * When paused, no mouse events will be emitted, but terminal mouse mode\n   * remains active.\n   *\n   * **Independent from enabled state:** The paused state is independent from\n   * the enabled state. You can have:\n   * - enabled=true, paused=false: Normal operation, events are emitted\n   * - enabled=true, paused=true: Terminal mouse mode active, but no events emitted\n   * - enabled=false, paused=false: Terminal mouse mode inactive, no events emitted\n   * - enabled=false, paused=true: Terminal mouse mode inactive, pause state preserved\n   *\n   * **Difference from isEnabled():**\n   * - isPaused(): Checks if event emission is paused (state flag only)\n   * - isEnabled(): Checks if terminal mouse mode is active (includes terminal state)\n   *\n   * @returns {boolean} True if event emission is paused, false otherwise.\n   * @see {@link pause} to pause event emission\n   * @see {@link resume} to resume event emission\n   * @see {@link isEnabled} to check if terminal mouse mode is enabled\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * console.log(mouse.isPaused()); // false\n   *\n   * mouse.pause();\n   * console.log(mouse.isPaused()); // true\n   *\n   * mouse.resume();\n   * console.log(mouse.isPaused()); // false\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Comparing isPaused() vs isEnabled()\n   * const mouse = new Mouse();\n   *\n   * mouse.enable();\n   * console.log(mouse.isEnabled()); // true (terminal mouse mode active)\n   * console.log(mouse.isPaused());  // false (events are being emitted)\n   *\n   * mouse.pause();\n   * console.log(mouse.isEnabled()); // true (terminal mouse mode still active!)\n   * console.log(mouse.isPaused());  // true (events are paused)\n   *\n   * mouse.disable();\n   * console.log(mouse.isEnabled()); // false (terminal mouse mode inactive)\n   * console.log(mouse.isPaused());  // true (pause state is preserved)\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Practical use: Check state before performing operations\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * function performSensitiveOperation() {\n   *   // Save current state\n   *   const wasPaused = mouse.isPaused();\n   *\n   *   // Ensure we're paused during the operation\n   *   mouse.pause();\n   *\n   *   // ... perform operation ...\n   *\n   *   // Restore previous state\n   *   if (!wasPaused) {\n   *     mouse.resume();\n   *   }\n   * }\n   * ```\n   */\n  public isPaused(): boolean {\n    return this.tty.isPaused();\n  }\n\n  /**\n   * Disables mouse tracking and removes all event listeners.\n   *\n   * **Recommended for Immediate Cleanup:**\n   * This method is the recommended way to clean up a Mouse instance when you're done with it.\n   * While automatic cleanup via FinalizationRegistry prevents memory leaks on garbage collection,\n   * calling `destroy()` explicitly ensures immediate and predictable resource release with\n   * no dependency on GC timing.\n   *\n   * **Idempotent:** Calling this method multiple times is safe and has no additional effect.\n   *\n   * **Side Effects:**\n   * - Calls `disable()` to stop mouse tracking and restore stream state\n   * - Unregisters from the FinalizationRegistry to prevent duplicate cleanup\n   * - Removes all event listeners from the internal event emitter\n   * - Sets the Mouse instance to a non-functional state\n   *\n   * @see {@link disable} to disable mouse tracking without removing event listeners\n   * @see {@link enable} to enable mouse tracking\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // ... use mouse instance ...\n   *\n   * // Always destroy when done for immediate cleanup\n   * mouse.destroy();\n   * ```\n   */\n  public destroy(): void {\n    this.tty.destroy();\n    this.eventManager.removeAllListeners();\n  }\n\n  /**\n   * Waits for a single click event and returns it.\n   *\n   * This is a convenience method that wraps the streaming API into a simple promise-based helper.\n   * It's useful for common interaction patterns like \"wait for user to click anywhere\".\n   *\n   * **Timeout:** The method will reject with a `MouseError` if the timeout is exceeded.\n   *\n   * **Cancellation:** The method can be cancelled early using an AbortSignal.\n   *\n   * @param options Configuration options for the wait operation.\n   * @param options.timeout Maximum time to wait in milliseconds. Defaults to 30000 (30 seconds).\n   * @param options.signal An AbortSignal to cancel the operation early.\n   * @returns A promise that resolves with the click event.\n   * @throws {MouseError} If timeout is exceeded or operation is aborted.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * try {\n   *   const click = await mouse.waitForClick();\n   *   console.log(`Clicked at ${click.x}, ${click.y} with ${click.button}`);\n   * } catch (err) {\n   *   if (err instanceof MouseError) {\n   *     console.error('Timeout or error:', err.message);\n   *   }\n   * } finally {\n   *   mouse.disable();\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Wait with custom timeout\n   * const click = await mouse.waitForClick({ timeout: 5000 });\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Cancel with AbortController\n   * const controller = new AbortController();\n   * setTimeout(() => controller.abort(), 1000);\n   *\n   * try {\n   *   const click = await mouse.waitForClick({ signal: controller.signal });\n   * } catch (err) {\n   *   if (err instanceof MouseError && err.message.includes('aborted')) {\n   *     console.log('Wait cancelled');\n   *   }\n   * }\n   * ```\n   */\n  public async waitForClick(options?: { timeout?: number; signal?: AbortSignal }): Promise<MouseEvent> {\n    return this.convenience.waitForClick(options);\n  }\n\n  /**\n   * Waits for any mouse input event and returns it.\n   *\n   * This is a convenience method that waits for any mouse event (press, release, click,\n   * drag, wheel, or move). Useful for \"wait for any user interaction\" patterns.\n   *\n   * **Timeout:** The method will reject with a `MouseError` if the timeout is exceeded.\n   *\n   * **Cancellation:** The method can be cancelled early using an AbortSignal.\n   *\n   * @param options Configuration options for the wait operation.\n   * @param options.timeout Maximum time to wait in milliseconds. Defaults to 30000 (30 seconds).\n   * @param options.signal An AbortSignal to cancel the operation early.\n   * @returns A promise that resolves with the first mouse event received.\n   * @throws {MouseError} If timeout is exceeded or operation is aborted.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * try {\n   *   const event = await mouse.waitForInput();\n   *   console.log(`Got ${event.action} at ${event.x}, ${event.y}`);\n   * } catch (err) {\n   *   if (err instanceof MouseError) {\n   *     console.error('Timeout or error:', err.message);\n   *   }\n   * } finally {\n   *   mouse.disable();\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Wait with custom timeout\n   * const event = await mouse.waitForInput({ timeout: 5000 });\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Use for \"press any key to continue\" style interaction\n   * console.log('Move mouse or click to continue...');\n   * await mouse.waitForInput();\n   * console.log('Continuing...');\n   * ```\n   */\n  public async waitForInput(options?: { timeout?: number; signal?: AbortSignal }): Promise<MouseEvent> {\n    return this.convenience.waitForInput(options);\n  }\n\n  /**\n   * Gets the last known mouse position synchronously.\n   *\n   * This method immediately returns the last cached mouse position from move or drag events,\n   * without waiting for new events. Returns null if no mouse movement has occurred yet.\n   *\n   * **No Waiting:** Unlike `getMousePosition()`, this method never waits - it returns\n   * the cached position immediately or null if unavailable.\n   *\n   * **Use Cases:**\n   * - When you need immediate position access without awaiting\n   * - To check if mouse has moved yet (null check)\n   * - For non-async contexts where you can't use await\n   *\n   * @returns The last known position as { x, y }, or null if no movement yet.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * // Returns null if mouse hasn't moved yet\n   * const pos = mouse.getLastPosition();\n   * if (pos) {\n   *   console.log(`Mouse at ${pos.x}, ${pos.y}`);\n   * } else {\n   *   console.log('No movement yet');\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Use in synchronous context\n   * mouse.on('move', () => {\n   *   const pos = mouse.getLastPosition();\n   *   console.log(`Current: ${pos?.x}, ${pos?.y}`);\n   * });\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Combine with async version for fallback\n   * let pos = mouse.getLastPosition();\n   * if (!pos) {\n   *   pos = await mouse.getMousePosition();\n   * }\n   * ```\n   */\n  public getLastPosition(): { x: number; y: number } | null {\n    return this.eventManager.getLastPosition();\n  }\n\n  /**\n   * Gets the current mouse position, returning immediately if available.\n   *\n   * This method returns the last known mouse position from move or drag events.\n   * If the mouse has moved since tracking was enabled, the position is returned\n   * immediately without waiting. Otherwise, it waits for the next move event.\n   *\n   * **Cached Position:** The method maintains an internal cache of the last position\n   * from move or drag events. This allows for instant position retrieval without\n   * waiting for new events.\n   *\n   * **Timeout:** The method will reject with a `MouseError` if the timeout is exceeded\n   * while waiting for the first move event.\n   *\n   * **Cancellation:** The method can be cancelled early using an AbortSignal.\n   *\n   * @param options Configuration options for the wait operation.\n   * @param options.timeout Maximum time to wait in milliseconds. Defaults to 30000 (30 seconds).\n   * @param options.signal An AbortSignal to cancel the operation early.\n   * @returns A promise that resolves with the x, y coordinates.\n   * @throws {MouseError} If timeout is exceeded or operation is aborted.\n   *\n   * @example\n   * ```ts\n   * const mouse = new Mouse();\n   * mouse.enable();\n   *\n   * try {\n   *   // If mouse has moved, returns immediately\n   *   // Otherwise waits for first move event\n   *   const { x, y } = await mouse.getMousePosition();\n   *   console.log(`Mouse is at ${x}, ${y}`);\n   * } finally {\n   *   mouse.disable();\n   * }\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Get position without waiting (after mouse has moved)\n   * mouse.on('move', () => {\n   *   // This will resolve immediately since we have a cached position\n   *   mouse.getMousePosition().then(({ x, y }) => {\n   *     console.log(`Current position: ${x}, ${y}`);\n   *   });\n   * });\n   * ```\n   *\n   * @example\n   * ```ts\n   * // Use with custom timeout\n   * const { x, y } = await mouse.getMousePosition({ timeout: 5000 });\n   * ```\n   */\n  public async getMousePosition(options?: {\n    timeout?: number;\n    signal?: AbortSignal;\n  }): Promise<{ x: number; y: number }> {\n    return this.convenience.getMousePosition(options);\n  }\n}\n\nexport { Mouse };\n","/**\n * Custom error class for errors that occur within the Mouse class.\n * This allows for more specific error handling and preserves the original error.\n */\nexport class MouseError extends Error {\n  /**\n   * @param message The error message.\n   * @param originalError The original error, if any.\n   */\n  constructor(\n    message: string,\n    public originalError?: Error,\n  ) {\n    super(message);\n    this.name = 'MouseError';\n  }\n}\n","import type { EventEmitter } from 'node:events';\nimport type { MouseEvent, MouseEventAction } from '../types';\nimport { MouseError } from '../types';\n\n/**\n * EventStreamFactory creates async generators for mouse event streams.\n *\n * Responsibilities:\n * - Create type-specific event streams (eventsOf)\n * - Create debounced move event streams\n * - Create all-event streams\n * - Handle queue management, abort signals, and cleanup\n */\nexport class EventStreamFactory {\n  constructor(private emitter: EventEmitter) {}\n\n  /**\n   * Returns an async generator that yields mouse events of a specific type.\n   *\n   * @param type The type of mouse event to listen for\n   * @param options Configuration for the event stream\n   * @yields Mouse events of the specified type\n   */\n  public async *eventsOf(\n    type: MouseEventAction,\n    {\n      latestOnly = false,\n      maxQueue = 100,\n      signal,\n    }: { latestOnly?: boolean; maxQueue?: number; signal?: AbortSignal } = {},\n  ): AsyncGenerator<MouseEvent> {\n    if (signal?.aborted) {\n      throw new Error('The operation was aborted.');\n    }\n\n    const queue: MouseEvent[] = [];\n    const errorQueue: Error[] = [];\n    const finalMaxQueue = Math.min(maxQueue, 1000);\n    let latest: MouseEvent | null = null;\n    let resolveNext: ((value: MouseEvent) => void) | null = null;\n    let rejectNext: ((err: Error) => void) | null = null;\n\n    const handler = (ev: MouseEvent): void => {\n      if (resolveNext) {\n        resolveNext(ev);\n        resolveNext = null;\n        rejectNext = null;\n        latest = null;\n      } else if (latestOnly) {\n        latest = ev;\n      } else {\n        if (queue.length >= finalMaxQueue) queue.shift();\n        queue.push(ev);\n      }\n    };\n\n    const errorHandler = (err: Error): void => {\n      const mouseError = new MouseError(`Error in mouse event stream: ${err.message}`, err);\n      if (rejectNext) {\n        rejectNext(mouseError);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(mouseError);\n      }\n    };\n\n    const abortHandler = (): void => {\n      const err = new MouseError('The operation was aborted.');\n      if (rejectNext) {\n        rejectNext(err);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(err);\n      }\n    };\n\n    this.emitter.on(type, handler);\n    this.emitter.on('error', errorHandler);\n    signal?.addEventListener('abort', abortHandler);\n\n    try {\n      while (true) {\n        if (signal?.aborted) {\n          throw new MouseError('The operation was aborted.');\n        }\n\n        if (errorQueue.length > 0) {\n          throw errorQueue.shift();\n        }\n\n        if (queue.length > 0) {\n          const event = queue.shift();\n          if (event) {\n            yield event;\n          }\n        } else if (latest !== null) {\n          const ev = latest;\n          latest = null;\n          yield ev;\n        } else {\n          // biome-ignore lint/performance/noAwaitInLoops: This is an async generator, await in loop is necessary\n          yield await new Promise<MouseEvent>((resolve, reject) => {\n            resolveNext = resolve;\n            rejectNext = reject;\n          });\n        }\n      }\n    } finally {\n      this.emitter.off(type, handler);\n      this.emitter.off('error', errorHandler);\n      signal?.removeEventListener('abort', abortHandler);\n    }\n  }\n\n  /**\n   * Returns an async generator that yields move events at most once per specified interval.\n   *\n   * @param options Configuration for the debounced event stream\n   * @yields Debounced mouse move events\n   */\n  public async *debouncedMoveEvents({\n    interval = 16,\n    signal,\n  }: {\n    interval?: number;\n    signal?: AbortSignal;\n  } = {}): AsyncGenerator<MouseEvent> {\n    if (signal?.aborted) {\n      throw new MouseError('The operation was aborted.');\n    }\n\n    let latestEvent: MouseEvent | null = null;\n    let timeoutId: ReturnType<typeof setTimeout> | null = null;\n    let resolveNext: ((value: MouseEvent) => void) | null = null;\n    let rejectNext: ((err: Error) => void) | null = null;\n    const errorQueue: Error[] = [];\n\n    const scheduleEvent = (ev: MouseEvent): void => {\n      latestEvent = ev;\n\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId);\n      }\n\n      timeoutId = setTimeout(() => {\n        if (latestEvent !== null && resolveNext !== null) {\n          const eventToYield = latestEvent;\n          latestEvent = null;\n          resolveNext(eventToYield);\n          resolveNext = null;\n          rejectNext = null;\n        }\n      }, interval);\n    };\n\n    const errorHandler = (err: Error): void => {\n      const mouseError = new MouseError(`Error in mouse event stream: ${err.message}`, err);\n      if (rejectNext) {\n        rejectNext(mouseError);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(mouseError);\n      }\n    };\n\n    const abortHandler = (): void => {\n      const err = new MouseError('The operation was aborted.');\n      if (rejectNext) {\n        rejectNext(err);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(err);\n      }\n    };\n\n    this.emitter.on('move', scheduleEvent);\n    this.emitter.on('error', errorHandler);\n    signal?.addEventListener('abort', abortHandler);\n\n    try {\n      while (true) {\n        if (signal?.aborted) {\n          throw new MouseError('The operation was aborted.');\n        }\n\n        if (errorQueue.length > 0) {\n          throw errorQueue.shift();\n        }\n\n        if (latestEvent !== null && timeoutId === null) {\n          const ev = latestEvent;\n          latestEvent = null;\n          yield ev;\n        } else {\n          // biome-ignore lint/performance/noAwaitInLoops: This is an async generator, await in loop is necessary\n          yield await new Promise<MouseEvent>((resolve, reject) => {\n            resolveNext = resolve;\n            rejectNext = reject;\n          });\n        }\n      }\n    } finally {\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId);\n      }\n      this.emitter.off('move', scheduleEvent);\n      this.emitter.off('error', errorHandler);\n      signal?.removeEventListener('abort', abortHandler);\n    }\n  }\n\n  /**\n   * Returns an async generator that yields all mouse events.\n   *\n   * @param options Configuration for the event stream\n   * @yields Objects containing the event type and event data\n   */\n  public async *stream({\n    latestOnly = false,\n    maxQueue = 1000,\n    signal,\n  }: {\n    latestOnly?: boolean;\n    maxQueue?: number;\n    signal?: AbortSignal;\n  } = {}): AsyncGenerator<{ type: MouseEventAction; event: MouseEvent }> {\n    if (signal?.aborted) {\n      throw new Error('The operation was aborted.');\n    }\n\n    const queue: { type: MouseEventAction; event: MouseEvent }[] = [];\n    const errorQueue: Error[] = [];\n    let latest: { type: MouseEventAction; event: MouseEvent } | null = null;\n    let resolveNext: ((value: { type: MouseEventAction; event: MouseEvent }) => void) | null = null;\n    let rejectNext: ((err: Error) => void) | null = null;\n\n    const handlers = new Map<MouseEventAction, (ev: MouseEvent) => void>();\n    const allEvents: MouseEventAction[] = ['press', 'release', 'drag', 'wheel', 'move', 'click'];\n\n    allEvents.forEach((type) => {\n      const handler = (ev: MouseEvent): void => {\n        const wrapped = { type, event: ev };\n\n        if (resolveNext) {\n          resolveNext(wrapped);\n          resolveNext = null;\n          rejectNext = null;\n          latest = null;\n        } else if (latestOnly) {\n          latest = wrapped;\n        } else {\n          if (queue.length >= maxQueue) queue.shift();\n          queue.push(wrapped);\n        }\n      };\n\n      handlers.set(type, handler);\n      this.emitter.on(type, handler);\n    });\n\n    const errorHandler = (err: Error): void => {\n      const mouseError = new MouseError(`Error in mouse event stream: ${err.message}`, err);\n      if (rejectNext) {\n        rejectNext(mouseError);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(mouseError);\n      }\n    };\n    this.emitter.on('error', errorHandler);\n\n    const abortHandler = (): void => {\n      const err = new MouseError('The operation was aborted.');\n      if (rejectNext) {\n        rejectNext(err);\n        resolveNext = null;\n        rejectNext = null;\n      } else {\n        errorQueue.push(err);\n      }\n    };\n    signal?.addEventListener('abort', abortHandler);\n\n    try {\n      while (true) {\n        if (signal?.aborted) {\n          throw new MouseError('The operation was aborted.');\n        }\n\n        if (errorQueue.length > 0) {\n          throw errorQueue.shift();\n        }\n\n        if (queue.length > 0) {\n          const event = queue.shift();\n          if (event) {\n            yield event;\n          }\n        } else if (latest !== null) {\n          const ev = latest;\n          latest = null;\n          yield ev;\n        } else {\n          // biome-ignore lint/performance/noAwaitInLoops: This is an async generator, await in loop is necessary\n          yield await new Promise<{ type: MouseEventAction; event: MouseEvent }>((resolve, reject) => {\n            resolveNext = resolve;\n            rejectNext = reject;\n          });\n        }\n      }\n    } finally {\n      allEvents.forEach((type) => {\n        const handler = handlers.get(type);\n        if (handler) {\n          this.emitter.off(type, handler);\n        }\n      });\n      this.emitter.off('error', errorHandler);\n      signal?.removeEventListener('abort', abortHandler);\n    }\n  }\n}\n","import type { EventEmitter } from 'node:events';\nimport type { MouseEvent, MouseEventAction } from '../types';\nimport { MouseError } from '../types';\n\n/**\n * MouseConvenienceMethods provides promise-based wrappers for common mouse event patterns.\n *\n * Responsibilities:\n * - waitForClick: Wait for a single click event\n * - waitForInput: Wait for any mouse event\n * - getMousePosition: Get current mouse position (with caching)\n */\nexport class MouseConvenienceMethods {\n  constructor(\n    private emitter: EventEmitter,\n    private getLastPosition: () => { x: number; y: number } | null,\n  ) {}\n\n  /**\n   * Waits for a single click event and returns it.\n   *\n   * @param options Configuration options for the wait operation\n   * @returns A promise that resolves with the click event\n   * @throws {MouseError} If timeout is exceeded or operation is aborted\n   */\n  public async waitForClick({\n    timeout = 30000,\n    signal,\n  }: {\n    timeout?: number;\n    signal?: AbortSignal;\n  } = {}): Promise<MouseEvent> {\n    if (signal?.aborted) {\n      throw new MouseError('The operation was aborted.');\n    }\n\n    return new Promise<MouseEvent>((resolve, reject) => {\n      const timeoutId = setTimeout(() => {\n        cleanup();\n        reject(new MouseError(`Timeout waiting for click after ${timeout}ms`));\n      }, timeout);\n\n      const abortHandler = (): void => {\n        cleanup();\n        reject(new MouseError('The operation was aborted.'));\n      };\n\n      const clickHandler = (event: MouseEvent): void => {\n        cleanup();\n        resolve(event);\n      };\n\n      const cleanup = (): void => {\n        clearTimeout(timeoutId);\n        signal?.removeEventListener('abort', abortHandler);\n        this.emitter.off('click', clickHandler);\n      };\n\n      signal?.addEventListener('abort', abortHandler);\n      this.emitter.on('click', clickHandler);\n    });\n  }\n\n  /**\n   * Waits for any mouse input event and returns it.\n   *\n   * @param options Configuration options for the wait operation\n   * @returns A promise that resolves with the first mouse event received\n   * @throws {MouseError} If timeout is exceeded or operation is aborted\n   */\n  public async waitForInput({\n    timeout = 30000,\n    signal,\n  }: {\n    timeout?: number;\n    signal?: AbortSignal;\n  } = {}): Promise<MouseEvent> {\n    if (signal?.aborted) {\n      throw new MouseError('The operation was aborted.');\n    }\n\n    return new Promise<MouseEvent>((resolve, reject) => {\n      const timeoutId = setTimeout(() => {\n        cleanup();\n        reject(new MouseError(`Timeout waiting for input after ${timeout}ms`));\n      }, timeout);\n\n      const abortHandler = (): void => {\n        cleanup();\n        reject(new MouseError('The operation was aborted.'));\n      };\n\n      const allEvents: MouseEventAction[] = ['press', 'release', 'drag', 'wheel', 'move', 'click'];\n\n      // Store handler references to ensure we remove the same functions we added\n      const handlers = new Map<MouseEventAction, (event: MouseEvent) => void>();\n\n      const inputHandler =\n        (_action: MouseEventAction) =>\n        (event: MouseEvent): void => {\n          cleanup();\n          resolve(event);\n        };\n\n      const cleanup = (): void => {\n        clearTimeout(timeoutId);\n        signal?.removeEventListener('abort', abortHandler);\n        handlers.forEach((handler, action) => {\n          this.emitter.off(action, handler);\n        });\n      };\n\n      signal?.addEventListener('abort', abortHandler);\n      allEvents.forEach((action) => {\n        const handler = inputHandler(action);\n        handlers.set(action, handler);\n        this.emitter.on(action, handler);\n      });\n    });\n  }\n\n  /**\n   * Gets the current mouse position, returning immediately if available.\n   *\n   * If the mouse has moved since tracking was enabled, the position is returned\n   * immediately without waiting. Otherwise, it waits for the next move event.\n   *\n   * @param options Configuration options for the wait operation\n   * @returns A promise that resolves with the x, y coordinates\n   * @throws {MouseError} If timeout is exceeded or operation is aborted\n   */\n  public async getMousePosition({\n    timeout = 30000,\n    signal,\n  }: {\n    timeout?: number;\n    signal?: AbortSignal;\n  } = {}): Promise<{ x: number; y: number }> {\n    if (signal?.aborted) {\n      throw new MouseError('The operation was aborted.');\n    }\n\n    // If we already have a cached position, return it immediately\n    const cachedPosition = this.getLastPosition();\n    if (cachedPosition !== null) {\n      return cachedPosition;\n    }\n\n    return new Promise<{ x: number; y: number }>((resolve, reject) => {\n      const timeoutId = setTimeout(() => {\n        cleanup();\n        reject(new MouseError(`Timeout waiting for mouse position after ${timeout}ms`));\n      }, timeout);\n\n      const abortHandler = (): void => {\n        cleanup();\n        reject(new MouseError('The operation was aborted.'));\n      };\n\n      const moveHandler = (event: MouseEvent): void => {\n        cleanup();\n        resolve({ x: event.x, y: event.y });\n      };\n\n      const cleanup = (): void => {\n        clearTimeout(timeoutId);\n        signal?.removeEventListener('abort', abortHandler);\n        this.emitter.off('move', moveHandler);\n      };\n\n      signal?.addEventListener('abort', abortHandler);\n      this.emitter.on('move', moveHandler);\n    });\n  }\n}\n","/**\n * Deep freeze utilities for runtime immutability with TypeScript type safety\n *\n * Provides recursive freezing with type-level readonly guarantees that match\n * runtime behavior. Prevents object tampering and prototype pollution attacks.\n *\n * @module utils/freeze\n */\n\n/**\n * Primitive types that don't need freezing\n */\ntype Primitive = string | number | boolean | bigint | symbol | null | undefined;\n\n/**\n * Built-in objects that have their own freezing semantics\n */\n// biome-ignore lint/complexity/noBannedTypes: Function type is appropriate for generic built-in check\ntype Builtin = Primitive | Function | Date | RegExp | Error | File | Blob | URL;\n\n/**\n * Recursively makes all properties readonly, matching runtime deepFreeze behavior\n *\n * This type transforms:\n * - Objects: `{ readonly [P in keyof T]: DeepReadonly<T[P]> }`\n * - Arrays: `ReadonlyArray<DeepReadonly<U>>`\n * - Maps: `ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>`\n * - Sets: `ReadonlySet<DeepReadonly<U>>`\n * - WeakMaps/WeakSets: Unchanged (cannot be frozen deeply)\n * - Primitives/Builtins: Unchanged\n *\n * @example\n * ```ts\n * type Config = {\n *   user: { name: string; meta: { age: number } };\n *   tags: string[];\n *   flags: Set<string>;\n * };\n *\n * const frozen: DeepReadonly<Config> = deepFreeze(config);\n * frozen.user.name = \"Bob\"; // ❌ TypeScript error\n * frozen.tags.push(\"go\");  // ❌ TypeScript error\n * ```\n */\nexport type DeepReadonly<T> = T extends Builtin\n  ? T\n  : T extends Map<infer K, infer V>\n    ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n    : T extends Set<infer M>\n      ? ReadonlySet<DeepReadonly<M>>\n      : T extends WeakMap<infer WK, infer WV>\n        ? WeakMap<DeepReadonly<WK>, DeepReadonly<WV>>\n        : T extends WeakSet<infer WM>\n          ? WeakSet<DeepReadonly<WM>>\n          : T extends ReadonlyArray<infer U>\n            ? readonly DeepReadonly<U>[]\n            : T extends Array<infer U>\n              ? readonly DeepReadonly<U>[]\n              : T extends object\n                ? { readonly [P in keyof T]: DeepReadonly<T[P]> }\n                : T;\n\n/**\n * Recursively freezes an object and all its nested properties\n *\n * Freezes objects recursively to prevent any modifications at runtime.\n * Handles built-in objects (Date, RegExp, Error, etc.) specially.\n * Prevents infinite loops with circular references using WeakSet.\n *\n * @param obj - The object to freeze\n * @param seen - Internal WeakSet to track already-seen objects (prevent infinite loops)\n * @returns The same object with all nested properties frozen\n *\n * @example\n * ```ts\n * const config = {\n *   user: { name: \"Max\", meta: { age: 30 } },\n *   tags: [\"ts\", \"rust\"],\n *   flags: new Set([\"a\", \"b\"]),\n *   map: new Map([[\"feature\", { enabled: true }]]),\n * };\n *\n * const frozen = deepFreeze(config);\n *\n * frozen.user.name = \"Bob\";                 // ❌ Runtime error: Cannot assign to read only property\n * frozen.tags.push(\"go\");                   // ❌ Runtime error: Cannot assign to read only property\n * frozen.flags.add(\"c\");                    // ❌ Runtime error: Cannot add property to frozen Set\n * frozen.map.get(\"feature\")!.enabled = false; // ❌ Runtime error: Cannot assign to read only property\n * ```\n */\nexport function deepFreeze<T>(obj: T, seen: WeakSet<object> = new WeakSet<object>()): DeepReadonly<T> {\n  if (obj === null || typeof obj !== 'object') {\n    return obj as DeepReadonly<T>;\n  }\n\n  if (seen.has(obj as object)) {\n    return obj as DeepReadonly<T>;\n  }\n  seen.add(obj as object);\n\n  // Built-in objects have their own semantics - just freeze at top level\n  const builtins = [Date, RegExp, Error, URL, File, Blob] as const;\n  if (builtins.some((ctor) => obj instanceof ctor)) {\n    return Object.freeze(obj) as DeepReadonly<T>;\n  }\n\n  if (obj instanceof Map) {\n    for (const [k, v] of obj.entries()) {\n      // biome-ignore lint/suspicious/noExplicitAny: Recursive freeze needs to handle arbitrary keys/values\n      deepFreeze(k as any, seen);\n      // biome-ignore lint/suspicious/noExplicitAny: Recursive freeze needs to handle arbitrary keys/values\n      deepFreeze(v as any, seen);\n    }\n    return Object.freeze(obj) as DeepReadonly<T>;\n  }\n\n  if (obj instanceof Set) {\n    for (const v of obj.values()) {\n      // biome-ignore lint/suspicious/noExplicitAny: Recursive freeze needs to handle arbitrary values\n      deepFreeze(v as any, seen);\n    }\n    return Object.freeze(obj) as DeepReadonly<T>;\n  }\n\n  // WeakMap/WeakSet can only freeze top-level (cannot iterate entries)\n  if (obj instanceof WeakMap || obj instanceof WeakSet) {\n    return Object.freeze(obj) as DeepReadonly<T>;\n  }\n\n  const propNames = Object.getOwnPropertyNames(obj);\n  for (const name of propNames) {\n    // biome-ignore lint/suspicious/noExplicitAny: Need to access arbitrary properties for recursion\n    const value = (obj as any)[name];\n    deepFreeze(value, seen);\n  }\n\n  return Object.freeze(obj) as DeepReadonly<T>;\n}\n\n/**\n * Freezes an object only in development mode\n *\n * In production, returns the object unchanged for performance.\n * Useful for adding safety during development without production overhead.\n *\n * @param obj - The object to conditionally freeze\n * @returns The frozen object (dev) or original object (prod)\n *\n * @example\n * ```ts\n * const config = { user: { name: \"Max\" } };\n * const frozen = freezeIfDev(config);\n *\n * if (process.env.NODE_ENV === 'development') {\n *   frozen.user.name = \"Bob\"; // ❌ Runtime error in dev\n * }\n * // In production, this would work (no freezing)\n * ```\n */\nexport function freezeIfDev<T>(obj: T): T {\n  if (process.env.NODE_ENV === 'development') {\n    return deepFreeze(obj) as T;\n  }\n  return obj;\n}\n\n/**\n * Freezes an object in strict TypeScript mode only\n *\n * When 'strict' is enabled in tsconfig, freezes the object.\n * Otherwise returns it unchanged.\n *\n * @param obj - The object to conditionally freeze\n * @returns The frozen object (strict mode) or original object\n *\n * @example\n * ```ts\n * // tsconfig.json: { \"strict\": true }\n * const config = { user: { name: \"Max\" } };\n * const frozen = freezeInStrictMode(config);\n * frozen.user.name = \"Bob\"; // ❌ TypeScript + runtime error\n * ```\n */\nexport function freezeInStrictMode<T>(obj: T): T {\n  // Note: This is a compile-time check. At runtime, we always freeze\n  // because we can't detect the tsconfig setting at runtime.\n  // The type system will enforce readonly if strict mode is on.\n  return deepFreeze(obj) as T;\n}\n\n/**\n * Checks if an object is frozen (either by Object.freeze or deepFreeze)\n *\n * @param obj - The object to check\n * @returns true if the object is frozen, false otherwise\n *\n * @example\n * ```ts\n * const obj = { data: [1, 2, 3] };\n * const frozen = deepFreeze(obj);\n *\n * isFrozen(obj);    // false (outer object is frozen, but this checks if we passed it)\n * isFrozen(frozen); // true\n * ```\n */\nexport function isFrozen(obj: unknown): boolean {\n  if (obj === null || typeof obj !== 'object') {\n    return true; // Primitives are immutable\n  }\n\n  return Object.isFrozen(obj as object);\n}\n","/**\n * Maximum allowed length for mouse event escape sequences to prevent ReDoS attacks.\n * These limits match the maximum sizes defined by the regex patterns.\n *\n * SGR format: ESC[<Cb;Cx;Cy(M|m) where:\n * - Cb is 1-3 digits (button code: 0-255)\n * - Cx, Cy are 1-4 digits (coordinates: 0-9999)\n * - Maximum: ESC[<255;9999;9999M = 21 chars\n *\n * ESC format: ESC[MCbCxCy where:\n * - Cb, Cx, Cy are single characters (6 chars total)\n *\n * **Security:** Deeply frozen to prevent prototype pollution attacks.\n */\nimport { type DeepReadonly, deepFreeze } from '../utils/freeze';\n\ntype MaxEventLengths = {\n  sgr: 21;\n  esc: 6;\n};\n\nconst MAX_EVENT_LENGTHS: DeepReadonly<MaxEventLengths> = deepFreeze({\n  /**\n   * SGR format with bounded quantifiers\n   * ESC[< + 3 digits + ; + 4 digits + ; + 4 digits + M/m = 21 chars\n   */\n  sgr: 21,\n\n  /**\n   * ESC format: ESC[M + 3 chars = 6 chars\n   */\n  esc: 6,\n});\n\n/**\n * ANSI escape codes for enabling and disabling different mouse tracking modes in terminals.\n * These codes are used to control how the terminal reports mouse events.\n *\n * **Security:** All objects are deeply frozen to prevent prototype pollution attacks\n * and tampering at runtime.\n */\ntype AnsiCodes = {\n  mouseButton: {\n    on: '\\x1b[?1000h';\n    off: '\\x1b[?1000l';\n  };\n  mouseDrag: {\n    on: '\\x1b[?1002h';\n    off: '\\x1b[?1002l';\n  };\n  mouseMotion: {\n    on: '\\x1b[?1003h';\n    off: '\\x1b[?1003l';\n  };\n  mouseSGR: {\n    on: '\\x1b[?1006h';\n    off: '\\x1b[?1006l';\n  };\n};\n\nconst ANSI_CODES: DeepReadonly<AnsiCodes> = deepFreeze({\n  // Terminal will send event on button pressed with mouse position\n  // SET_VT200_MOUSE\n  mouseButton: { on: '\\x1b[?1000h', off: '\\x1b[?1000l' },\n\n  // Terminal will send event on button pressed and mouse motion as long as a button is down, with mouse position\n  // SET_BTN_EVENT_MOUSE\n  mouseDrag: { on: '\\x1b[?1002h', off: '\\x1b[?1002l' },\n\n  // Terminal will send event on button pressed and motion\n  // SET_ANY_EVENT_MOUSE\n  mouseMotion: { on: '\\x1b[?1003h', off: '\\x1b[?1003l' },\n\n  // Another mouse protocol that extend coordinate mapping (without it, it supports only 223 rows and columns)\n  // SET_SGR_EXT_MODE_MOUSE\n  mouseSGR: { on: '\\x1b[?1006h', off: '\\x1b[?1006l' },\n});\n\n/**\n * Regular expression patterns for parsing ANSI escape sequences that contain mouse event data.\n * These patterns match the different formats terminals use to report mouse positions and button states.\n *\n * ReDoS Protection:\n * - Anchored with ^ to match only at string start (prevents full-string scanning)\n * - Bounded quantifiers {min,max} instead of greedy + (prevents unbounded matching)\n * - Fixed structure with literal separators between variable parts\n * - No nested quantifiers or overlapping alternations (prevents exponential backtracking)\n */\nconst ANSI_RESPONSE_PATTERNS = {\n  /**\n   * SGR pattern: ESC[<Cb;Cx;Cy(M|m)\n   * - Cb: button code, 1-3 digits (0-255, practical terminal limit)\n   * - Cx, Cy: coordinates, 1-4 digits each (0-9999, exceeds typical terminal sizes)\n   * - Bounded quantifiers {1,3} and {1,4} prevent unbounded backtracking\n   * - ^ anchor ensures match only at start\n   */\n  // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require control characters\n  sgrPattern: /^\\x1b\\[<(\\d{1,3});(\\d{1,4});(\\d{1,4})([Mm])/,\n\n  /**\n   * ESC pattern: ESC[MCbCxCy\n   * - Fixed-length pattern (exactly 3 characters after ESC[M)\n   * - Character classes match single characters (no quantifiers)\n   * - No possibility of backtracking or ambiguous matches\n   */\n  // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require control characters\n  escPattern: /^\\x1b\\[M([\\x20-\\x7f])([\\x20-\\x7f])([\\x20-\\x7f])/,\n};\n\nexport { ANSI_CODES, ANSI_RESPONSE_PATTERNS, MAX_EVENT_LENGTHS };\n","import type { ButtonType, ESCMouseEvent, MouseEventAction, SGRMouseEvent } from '../types';\n\nimport { ANSI_RESPONSE_PATTERNS, MAX_EVENT_LENGTHS } from './constants.ts';\n\n/**\n * Decodes the SGR (SGR-Style) mouse button code into button type and action.\n * @param code The raw button code from the SGR mouse event.\n * @returns An object containing the button type and the action performed.\n */\nfunction decodeSGRButton(code: number): { button: ButtonType; action: MouseEventAction } {\n  const motion = !!(code & 32);\n  // Modifier bits for shift, alt, ctrl, and motion\n  const modifierBits = 4 | 8 | 16 | 32;\n  const buttonCode = code & ~modifierBits; // Isolate the actual button code\n\n  let button: ButtonType;\n  switch (buttonCode) {\n    case 0:\n      button = 'left';\n      break;\n    case 1:\n      button = 'middle';\n      break;\n    case 2:\n      button = 'right';\n      break;\n    case 3:\n      button = 'none';\n      break;\n    case 64:\n      button = 'wheel-up';\n      break;\n    case 65:\n      button = 'wheel-down';\n      break;\n    case 66:\n      button = 'wheel-left';\n      break;\n    case 67:\n      button = 'wheel-right';\n      break;\n    case 128:\n      button = 'back';\n      break;\n    case 129:\n      button = 'forward';\n      break;\n    default:\n      button = 'unknown';\n      break;\n  }\n\n  let action: MouseEventAction;\n  if (motion) {\n    action = button === 'none' ? 'move' : 'drag';\n  } else if (button.startsWith('wheel-')) {\n    action = 'wheel';\n  } else {\n    // For SGR, release is indicated by the 'm' terminator, not the button code\n    action = 'press';\n  }\n\n  return { button, action };\n}\n\n/**\n * Decodes the ESC (legacy escape sequence) mouse button code into button type and action.\n * @param code The raw button code from the ESC mouse event.\n * @returns An object containing the button type and the action performed.\n */\nfunction decodeESCButton(code: number): { button: ButtonType; action: MouseEventAction } {\n  const motion = !!(code & 32);\n\n  let button: ButtonType = 'unknown'; // Initialize with fallback value\n  if (code & 64) {\n    // Wheel event\n    switch (code) {\n      case 64:\n        button = 'wheel-up';\n        break;\n      case 65:\n        button = 'wheel-down';\n        break;\n      case 66:\n        button = 'wheel-left';\n        break;\n      case 67:\n        button = 'wheel-right';\n        break;\n      default:\n        button = 'unknown'; // Fallback for unknown wheel codes\n        break;\n    }\n  } else {\n    // Button event\n    switch (code & 3) {\n      case 0:\n        button = 'left';\n        break;\n      case 1:\n        button = 'middle';\n        break;\n      case 2:\n        button = 'right';\n        break;\n      case 3:\n        button = 'none';\n        break;\n    }\n  }\n\n  let action: MouseEventAction;\n  if (motion) {\n    action = button === 'none' ? 'move' : 'drag';\n  } else if (button.startsWith('wheel-')) {\n    action = 'wheel';\n  } else if ((code & 3) === 3) {\n    action = 'release';\n  } else {\n    action = 'press';\n  }\n\n  return { button, action };\n}\n\n/**\n * Parses a single SGR (SGR-Style) mouse event from a string starting at the given position.\n * @param data The string containing the raw mouse event data.\n * @param start The position in the string to start parsing from.\n * @returns A tuple containing the parsed mouse event (or null if parsing fails) and the position to continue parsing from.\n */\nfunction parseSGRMouseEvent(data: string, start: number): [SGRMouseEvent | null, number] {\n  const slice = data.slice(start, start + MAX_EVENT_LENGTHS.sgr);\n\n  const match = slice.match(ANSI_RESPONSE_PATTERNS.sgrPattern);\n\n  if (!match) {\n    return [null, start + 1];\n  }\n\n  const [fullMatch, bStr, xStr, yStr, terminator] = match as [string, string, string, string, string];\n  const isRelease = terminator === 'm';\n\n  const b = parseInt(bStr, 10);\n  const x = parseInt(xStr, 10);\n  const y = parseInt(yStr, 10);\n\n  if (Number.isNaN(b) || Number.isNaN(x) || Number.isNaN(y)) {\n    return [null, start + 1];\n  }\n\n  const { button, action } = decodeSGRButton(b);\n\n  const event: SGRMouseEvent = {\n    protocol: 'SGR',\n    x,\n    y,\n    button,\n    action: isRelease ? 'release' : action,\n    shift: !!(b & 4),\n    alt: !!(b & 8),\n    ctrl: !!(b & 16),\n    raw: b,\n    data: fullMatch,\n  };\n\n  return [event, start + fullMatch.length];\n}\n\n/**\n * Parses a single ESC (legacy escape sequence) mouse event from a string starting at the given position.\n * @param data The string containing the raw mouse event data.\n * @param start The position in the string to start parsing from.\n * @returns A tuple containing the parsed mouse event (or null if parsing fails) and the position to continue parsing from.\n */\nfunction parseESCMouseEvent(data: string, start: number): [ESCMouseEvent | null, number] {\n  const slice = data.slice(start, start + MAX_EVENT_LENGTHS.esc);\n\n  const match = slice.match(ANSI_RESPONSE_PATTERNS.escPattern);\n\n  if (!match) {\n    return [null, start + 1];\n  }\n\n  const [fullMatch, bChar, xChar, yChar] = match as [string, string, string, string];\n\n  const cb = bChar.charCodeAt(0) - 32;\n  const cx = xChar.charCodeAt(0) - 32;\n  const cy = yChar.charCodeAt(0) - 32;\n\n  const { button, action } = decodeESCButton(cb);\n\n  const event: ESCMouseEvent = {\n    protocol: 'ESC',\n    x: cx,\n    y: cy,\n    button,\n    action,\n    shift: !!(cb & 4),\n    alt: !!(cb & 8),\n    ctrl: !!(cb & 16),\n    raw: cb,\n    data: fullMatch,\n  };\n\n  return [event, start + fullMatch.length];\n}\n\n/**\n * Parses mouse events from raw ANSI escape sequence data.\n * @param data The raw string data containing ANSI mouse event escape sequences.\n * @yields {SGRMouseEvent | ESCMouseEvent} A parsed mouse event object.\n */\nfunction* parseMouseEvents(data: string): Generator<SGRMouseEvent | ESCMouseEvent> {\n  let i = 0;\n  let lastEventData: string | null = null;\n\n  while (i < data.length) {\n    const escIndex = data.indexOf('\\x1b[', i);\n    if (escIndex === -1) {\n      break;\n    }\n\n    i = escIndex;\n    let event: SGRMouseEvent | ESCMouseEvent | null = null;\n    let nextIndex: number;\n\n    if (data[i + 2] === '<') {\n      // Potential SGR event\n      [event, nextIndex] = parseSGRMouseEvent(data, i);\n    } else if (data[i + 2] === 'M') {\n      // Potential ESC event\n      [event, nextIndex] = parseESCMouseEvent(data, i);\n    } else {\n      // Unrecognized escape sequence, skip it\n      nextIndex = i + 2;\n    }\n\n    if (event) {\n      // Implement run-length deduplication\n      if (event.data !== lastEventData) {\n        yield event;\n        lastEventData = event.data;\n      }\n    }\n    i = nextIndex;\n  }\n}\n\nexport { parseMouseEvents };\n","import type { MouseEvent, MouseOptions } from '../types';\n\n/**\n * ClickDetector manages click detection from mouse press and release events.\n *\n * A click is detected when:\n * - A press event occurs\n * - Followed by a release event within clickDistanceThreshold\n * - The threshold is the maximum allowed distance (in cells) between press and release\n *\n * Responsibilities:\n * - Track last press event\n * - Detect clicks based on press+release proximity\n * - Emit click events through provided callback\n */\nexport class ClickDetector {\n  private lastPress: MouseEvent | null = null;\n  private readonly clickDistanceThreshold: number;\n\n  constructor(options?: MouseOptions) {\n    this.clickDistanceThreshold = options?.clickDistanceThreshold ?? 1;\n  }\n\n  /**\n   * Processes a mouse event and detects clicks.\n   *\n   * When a press event is received, it's stored.\n   * When a release event is received, checks if it matches the last press\n   * within the click distance threshold.\n   *\n   * @param event The mouse event to process\n   * @param emitClick Callback to emit a click event when detected\n   */\n  public processEvent(event: MouseEvent, emitClick: (clickEvent: MouseEvent) => void): void {\n    if (event.action === 'press') {\n      this.lastPress = event;\n    } else if (event.action === 'release') {\n      if (this.lastPress) {\n        const xDiff = Math.abs(event.x - this.lastPress.x);\n        const yDiff = Math.abs(event.y - this.lastPress.y);\n\n        if (xDiff <= this.clickDistanceThreshold && yDiff <= this.clickDistanceThreshold) {\n          const clickEvent: MouseEvent = { ...event, action: 'click' };\n          // Use nextTick to avoid emitting during event processing\n          process.nextTick(() => {\n            emitClick(clickEvent);\n          });\n        }\n      }\n      this.lastPress = null;\n    }\n  }\n\n  /**\n   * Resets the click detector state.\n   * Clears any pending press event.\n   */\n  public reset(): void {\n    this.lastPress = null;\n  }\n}\n","import type { MouseEvent } from '../types';\n\n/**\n * PositionTracker tracks the last known mouse position.\n *\n * Responsibilities:\n * - Track mouse position from move and drag events\n * - Provide synchronous access to last position\n * - Support waiting for position updates\n */\nexport class PositionTracker {\n  private lastPosition: { x: number; y: number } | null = null;\n\n  /**\n   * Processes a mouse event and updates position tracking.\n   *\n   * @param event The mouse event to process\n   */\n  public processEvent(event: MouseEvent): void {\n    if (event.action === 'move' || event.action === 'drag') {\n      this.lastPosition = { x: event.x, y: event.y };\n    }\n  }\n\n  /**\n   * Gets the last known mouse position synchronously.\n   *\n   * @returns The last known position as { x, y }, or null if no movement yet\n   */\n  public getLastPosition(): { x: number; y: number } | null {\n    return this.lastPosition;\n  }\n\n  /**\n   * Resets the position tracker state.\n   */\n  public reset(): void {\n    this.lastPosition = null;\n  }\n}\n","import type { EventEmitter } from 'node:events';\nimport { parseMouseEvents } from '../parser/ansiParser';\nimport type { ListenerFor, MouseEventAction, MouseOptions } from '../types';\nimport { ClickDetector } from './ClickDetector';\nimport { PositionTracker } from './PositionTracker';\n\n/**\n * MouseEventManager handles event emission and detection.\n *\n * Responsibilities:\n * - Parse raw ANSI data into mouse events\n * - Emit events through EventEmitter\n * - Detect clicks from press+release events\n * - Track mouse position\n * - Provide type-safe event listener management (on/off/once)\n */\nexport class MouseEventManager {\n  private readonly clickDetector: ClickDetector;\n  private readonly positionTracker: PositionTracker;\n\n  constructor(\n    private emitter: EventEmitter,\n    options?: MouseOptions,\n  ) {\n    this.clickDetector = new ClickDetector(options);\n    this.positionTracker = new PositionTracker();\n  }\n\n  /**\n   * Processes raw ANSI data and emits mouse events.\n   *\n   * This method:\n   * - Parses ANSI escape sequences into mouse events\n   * - Emits events through the EventEmitter\n   * - Detects clicks and emits click events\n   * - Tracks mouse position\n   *\n   * @param data Raw ANSI data from stdin\n   * @param paused Whether event emission is currently paused\n   */\n  public handleEvent = (data: Buffer, paused: boolean): void => {\n    if (paused) {\n      return;\n    }\n\n    try {\n      const events = parseMouseEvents(data.toString());\n      for (const event of events) {\n        // Track position for move/drag events\n        this.positionTracker.processEvent(event);\n\n        // Emit the event\n        this.emitter.emit(event.action, event);\n\n        // Detect clicks\n        this.clickDetector.processEvent(event, (clickEvent) => {\n          this.emitter.emit('click', clickEvent);\n        });\n      }\n    } catch (err) {\n      this.emitter.emit('error', err);\n    }\n  };\n\n  /**\n   * Registers a listener for a specific mouse event.\n   *\n   * @param event The name of the event to listen for\n   * @param listener The callback function to execute when the event is triggered\n   * @returns The event emitter instance\n   */\n  public on = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    return this.emitter.on(event, listener as Parameters<typeof this.emitter.on>[1]);\n  };\n\n  /**\n   * Removes a listener for a specific mouse event.\n   *\n   * @param event The name of the event to stop listening for\n   * @param listener The callback function to remove\n   * @returns The event emitter instance\n   */\n  public off = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    return this.emitter.off(event, listener as Parameters<typeof this.emitter.off>[1]);\n  };\n\n  /**\n   * Registers a one-time listener that automatically removes itself after the first event.\n   *\n   * @param event The name of the event to listen for\n   * @param listener The callback function to execute once when the event is triggered\n   * @returns The event emitter instance\n   */\n  public once = <T extends MouseEventAction | 'error'>(\n    event: T,\n    listener: T extends 'error' ? (error: Error) => void : ListenerFor<T>,\n  ): EventEmitter => {\n    const wrappedListener = (...args: unknown[]): void => {\n      this.emitter.off(event, wrappedListener);\n      (listener as (...args: unknown[]) => void)(...args);\n    };\n    return this.emitter.on(event, wrappedListener as Parameters<typeof this.emitter.on>[1]);\n  };\n\n  /**\n   * Gets the underlying EventEmitter instance.\n   */\n  public getEmitter(): EventEmitter {\n    return this.emitter;\n  }\n\n  /**\n   * Gets the last known mouse position.\n   */\n  public getLastPosition(): { x: number; y: number } | null {\n    return this.positionTracker.getLastPosition();\n  }\n\n  /**\n   * Removes all event listeners from the emitter.\n   */\n  public removeAllListeners(): void {\n    this.emitter.removeAllListeners();\n  }\n\n  /**\n   * Resets the internal state (click detector and position tracker).\n   */\n  public reset(): void {\n    this.clickDetector.reset();\n    this.positionTracker.reset();\n  }\n}\n","/**\n * Runtime validation utilities for stream objects and dependencies.\n *\n * Provides defense-in-depth against type confusion attacks, malformed objects,\n * and compromised dependencies by validating object shapes at runtime.\n */\n\n/**\n * Validates that an object has all required methods.\n *\n * Performs runtime validation to ensure type safety and prevent crashes from\n * malformed or malicious objects. This is defense-in-depth against type confusion\n * attacks and runtime errors.\n *\n * @param obj - The unknown object to validate\n * @param requiredMethods - Array of method names that must exist and be functions\n * @param objName - Name of the object for error messages\n * @throws {TypeError} If obj is not an object, is null, or missing required methods\n *\n * @example\n * ```ts\n * validateStream(inputStream, ['on', 'off', 'pause', 'resume'], 'inputStream');\n * // Throws if inputStream is missing any of these methods\n * ```\n */\nexport function validateStream(\n  obj: unknown,\n  requiredMethods: string[],\n  objName: string,\n): asserts obj is Record<string, unknown> {\n  if (typeof obj !== 'object' || obj === null) {\n    throw new TypeError(\n      `[xterm-mouse] ${objName} must be an object, got ${typeof obj === 'object' ? 'null' : typeof obj}`,\n    );\n  }\n\n  for (const method of requiredMethods) {\n    const value = (obj as Record<string, unknown>)[method];\n\n    if (typeof value !== 'function') {\n      throw new TypeError(\n        `[xterm-mouse] ${objName} must have method ${method}(), but ${typeof value === 'undefined' ? 'it is missing' : `it has type ${typeof value}`}`,\n      );\n    }\n  }\n}\n\n/**\n * Validates that a value is a function.\n *\n * @param fn - The unknown value to validate\n * @param fnName - Name of the function parameter for error messages\n * @throws {TypeError} If fn is not a function\n *\n * @example\n * ```ts\n * validateFunction(handleEvent, 'handleEvent');\n * // Throws if handleEvent is not a function\n * ```\n */\nexport function validateFunction(fn: unknown, fnName: string): asserts fn is (...args: unknown[]) => unknown {\n  if (typeof fn !== 'function') {\n    throw new TypeError(`[xterm-mouse] ${fnName} must be a function, got ${typeof fn}`);\n  }\n}\n\n/**\n * Validates that a value is a writable stream with a write method.\n *\n * @param stream - The unknown stream to validate\n * @param streamName - Name of the stream for error messages\n * @throws {TypeError} If stream doesn't have a write method\n *\n * @example\n * ```ts\n * validateWritableStream(outputStream, 'outputStream');\n * // Throws if outputStream.write is not a function\n * ```\n */\nexport function validateWritableStream(stream: unknown, streamName: string): void {\n  validateStream(stream, ['write'], streamName);\n}\n\n/**\n * Validates that a value is a readable stream with required event emitter methods.\n *\n * @param stream - The unknown stream to validate\n * @param streamName - Name of the stream for error messages\n * @throws {TypeError} If stream doesn't have required methods\n *\n * @example\n * ```ts\n * validateReadableStream(inputStream, 'inputStream');\n * // Throws if inputStream is missing on/off/pause/resume methods\n * ```\n */\nexport function validateReadableStream(stream: unknown, streamName: string): void {\n  validateStream(stream, ['on', 'off', 'pause', 'resume'], streamName);\n}\n","import { ANSI_CODES } from '../parser/constants';\nimport type { ReadableStreamWithEncoding } from '../types';\nimport { MouseError } from '../types';\nimport { validateFunction, validateReadableStream, validateWritableStream } from '../utils/validation';\n\n/**\n * FinalizationRegistry for automatic cleanup of TTY controllers.\n *\n * When a TTYController is garbage collected without explicit cleanup,\n * this registry ensures that:\n * - The stdin 'data' event listener is removed\n * - The input stream state is restored (raw mode disabled, stream paused)\n * - ANSI disable codes are sent to the terminal\n *\n * This prevents memory leaks from accumulated event listeners when controllers\n * are not properly destroyed.\n */\nconst ttyCleanupRegistry: FinalizationRegistry<{\n  inputStream: ReadableStreamWithEncoding;\n  handleEvent: (data: Buffer) => void;\n  outputStream: NodeJS.WriteStream;\n  previousRawMode: boolean | null;\n  isRaw: boolean | null;\n  setRawModeFn?: (mode: boolean) => void;\n}> = new FinalizationRegistry(\n  (heldValue: {\n    inputStream: ReadableStreamWithEncoding;\n    handleEvent: (data: Buffer) => void;\n    outputStream: NodeJS.WriteStream;\n    previousRawMode: boolean | null;\n    isRaw: boolean | null;\n    setRawModeFn?: (mode: boolean) => void;\n  }) => {\n    try {\n      heldValue.inputStream.off('data', heldValue.handleEvent);\n    } catch {\n      // Ignore errors during GC cleanup\n    }\n\n    try {\n      if (heldValue.isRaw) {\n        if (heldValue.setRawModeFn) {\n          heldValue.setRawModeFn(false);\n        } else {\n          heldValue.inputStream.setRawMode(false);\n        }\n      }\n      heldValue.inputStream.pause();\n    } catch {\n      // Ignore errors during GC cleanup\n    }\n\n    try {\n      heldValue.outputStream.write(\n        ANSI_CODES.mouseSGR.off + ANSI_CODES.mouseMotion.off + ANSI_CODES.mouseDrag.off + ANSI_CODES.mouseButton.off,\n      );\n    } catch {\n      // Ignore errors during GC cleanup\n    }\n  },\n);\n\n/**\n * TTYController manages terminal state for mouse event tracking.\n *\n * Responsibilities:\n * - Enable/disable terminal mouse mode via ANSI escape codes\n * - Manage input stream state (raw mode, encoding, pause/resume)\n * - Provide pause/resume for event throttling without terminal overhead\n * - Automatic cleanup via FinalizationRegistry\n */\nexport class TTYController {\n  private enabled = false;\n  private paused = false;\n  private previousEncoding: BufferEncoding | null = null;\n  private previousRawMode: boolean | null = null;\n  private currentRawMode: boolean | null = null;\n  private cleanupToken: { instance: TTYController } | null = null;\n\n  constructor(\n    private inputStream: ReadableStreamWithEncoding,\n    private outputStream: NodeJS.WriteStream,\n    private handleEvent: (data: Buffer) => void,\n    private setRawModeFn?: (mode: boolean) => void,\n  ) {\n    validateReadableStream(inputStream, 'inputStream');\n    // biome-ignore lint/security/noSecrets: stream name\n    validateWritableStream(outputStream, 'outputStream');\n    validateFunction(handleEvent, 'handleEvent');\n\n    if (setRawModeFn !== undefined) {\n      // biome-ignore lint/security/noSecrets: function name\n      validateFunction(setRawModeFn, 'setRawModeFn');\n    }\n  }\n\n  /**\n   * Sets raw mode on the input stream using either the custom function\n   * or the default stream.setRawMode method.\n   */\n  private setRawMode(mode: boolean): void {\n    if (this.setRawModeFn) {\n      this.setRawModeFn(mode);\n    } else {\n      this.inputStream.setRawMode(mode);\n    }\n  }\n\n  /**\n   * Enables mouse event tracking.\n   *\n   * This method activates mouse event capture by putting the input stream into raw mode\n   * and sending the appropriate ANSI escape sequences to enable mouse tracking in the terminal.\n   *\n   * @throws {Error} If the input stream is not a TTY\n   * @throws {MouseError} If enabling mouse tracking fails\n   */\n  public enable = (): void => {\n    if (this.enabled) {\n      return;\n    }\n\n    if (!this.inputStream.isTTY) {\n      throw new Error('Mouse events require a TTY input stream');\n    }\n\n    try {\n      this.previousRawMode = this.setRawModeFn ? (this.currentRawMode ?? false) : (this.inputStream.isRaw ?? false);\n      this.previousEncoding = this.inputStream.readableEncoding || null;\n\n      this.enabled = true;\n\n      this.outputStream.write(\n        ANSI_CODES.mouseButton.on + ANSI_CODES.mouseDrag.on + ANSI_CODES.mouseMotion.on + ANSI_CODES.mouseSGR.on,\n      );\n\n      this.setRawMode(true);\n      this.currentRawMode = true;\n      this.inputStream.setEncoding('utf8');\n      this.inputStream.resume();\n      this.inputStream.on('data', this.handleEvent);\n\n      this.cleanupToken = { instance: this };\n      ttyCleanupRegistry.register(\n        this,\n        {\n          inputStream: this.inputStream,\n          handleEvent: this.handleEvent,\n          outputStream: this.outputStream,\n          previousRawMode: this.previousRawMode,\n          isRaw: this.inputStream.isRaw ?? false,\n          setRawModeFn: this.setRawModeFn,\n        },\n        this.cleanupToken,\n      );\n    } catch (err) {\n      this.enabled = false;\n      throw new MouseError(\n        `Failed to enable mouse: ${err instanceof Error ? err.message : String(err)}`,\n        err instanceof Error ? err : undefined,\n      );\n    }\n  };\n\n  /**\n   * Disables mouse event tracking.\n   *\n   * This method restores the input stream to its previous state and stops listening for data.\n   */\n  public disable = (): void => {\n    if (!this.enabled) {\n      return;\n    }\n\n    try {\n      // Unregister from FinalizationRegistry before cleanup\n      if (this.cleanupToken) {\n        ttyCleanupRegistry.unregister(this.cleanupToken);\n        this.cleanupToken = null;\n      }\n\n      this.inputStream.off('data', this.handleEvent);\n      this.inputStream.pause();\n\n      if (this.previousRawMode !== null) {\n        this.setRawMode(this.previousRawMode);\n        this.currentRawMode = this.previousRawMode;\n      }\n\n      if (this.previousEncoding !== null) {\n        this.inputStream.setEncoding(this.previousEncoding);\n      }\n\n      this.outputStream.write(\n        ANSI_CODES.mouseSGR.off + ANSI_CODES.mouseMotion.off + ANSI_CODES.mouseDrag.off + ANSI_CODES.mouseButton.off,\n      );\n    } catch (err) {\n      throw new MouseError(\n        `Failed to disable mouse: ${err instanceof Error ? err.message : String(err)}`,\n        err instanceof Error ? err : undefined,\n      );\n    } finally {\n      this.enabled = false;\n      this.previousRawMode = null;\n      this.previousEncoding = null;\n      this.currentRawMode = null;\n    }\n  };\n\n  /**\n   * Pauses mouse event emission without disabling terminal mouse mode.\n   *\n   * This method temporarily stops the emission of mouse events while keeping\n   * the terminal mouse mode active.\n   *\n   * **Idempotent:** Calling this method when already paused has no effect.\n   *\n   * **No Terminal State Changes:** Unlike disable(), this method does not:\n   * - Send ANSI escape codes to the terminal\n   * - Modify the input stream's raw mode\n   * - Change the input stream encoding\n   * - Remove event listeners from the input stream\n   */\n  public pause = (): void => {\n    if (this.paused) {\n      return;\n    }\n\n    this.paused = true;\n  };\n\n  /**\n   * Resumes mouse event emission without modifying terminal mouse mode.\n   *\n   * This method resumes the emission of mouse events after they were paused.\n   *\n   * **Idempotent:** Calling this method when not paused has no effect.\n   */\n  public resume = (): void => {\n    if (!this.paused) {\n      return;\n    }\n\n    this.paused = false;\n  };\n\n  /**\n   * Checks if mouse event tracking is currently enabled.\n   */\n  public isEnabled(): boolean {\n    return this.enabled;\n  }\n\n  /**\n   * Checks if mouse event emission is currently paused.\n   */\n  public isPaused(): boolean {\n    return this.paused;\n  }\n\n  /**\n   * Destroys the controller and cleans up all resources.\n   *\n   * **Idempotent:** Calling this method multiple times is safe and has no additional effect.\n   */\n  public destroy(): void {\n    this.disable();\n\n    if (this.cleanupToken) {\n      ttyCleanupRegistry.unregister(this.cleanupToken);\n      this.cleanupToken = null;\n    }\n  }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAA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AO,CAC9C,CAkDO,iBAAmD,CACxD,OAAO,KAAK,aAAa,gBAAgB,CAC3C,CAwDA,MAAa,iBAAiBA,EAGQ,CACpC,OAAO,KAAK,YAAY,iBAAiBA,CAAO,CAClD,CACF","names":["index_exports","__export","Mouse","MouseError","__toCommonJS","import_node_events","MouseError","message","originalError","EventStreamFactory","emitter","type","latestOnly","maxQueue","signal","queue","errorQueue","finalMaxQueue","latest","resolveNext","rejectNext","handler","ev","errorHandler","err","mouseError","MouseError","abortHandler","event","resolve","reject","interval","latestEvent","timeoutId","scheduleEvent","eventToYield","handlers","allEvents","wrapped","MouseConvenienceMethods","emitter","getLastPosition","timeout","signal","MouseError","resolve","reject","timeoutId","cleanup","abortHandler","clickHandler","event","allEvents","handlers","inputHandler","_action","handler","action","cachedPosition","moveHandler","deepFreeze","obj","seen","ctor","k","v","propNames","name","value","MAX_EVENT_LENGTHS","deepFreeze","ANSI_CODES","ANSI_RESPONSE_PATTERNS","decodeSGRButton","code","motion","buttonCode","button","action","decodeESCButton","parseSGRMouseEvent","data","start","match","MAX_EVENT_LENGTHS","ANSI_RESPONSE_PATTERNS","fullMatch","bStr","xStr","yStr","terminator","isRelease","b","x","y","parseESCMouseEvent","bChar","xChar","yChar","cb","cx","cy","parseMouseEvents","i","lastEventData","escIndex","event","nextIndex","ClickDetector","options","event","emitClick","xDiff","yDiff","clickEvent","PositionTracker","event","MouseEventManager","emitter","options","ClickDetector","PositionTracker","data","paused","events","parseMouseEvents","event","clickEvent","err","listener","wrappedListener","args","validateStream","obj","requiredMethods","objName","method","value","validateFunction","fn","fnName","validateWritableStream","stream","streamName","validateReadableStream","ttyCleanupRegistry","heldValue","ANSI_CODES","TTYController","inputStream","outputStream","handleEvent","setRawModeFn","validateReadableStream","validateWritableStream","validateFunction","mode","err","MouseError","Mouse","_Mouse","options","inputStream","outputStream","eventEmitter","MouseEventManager","TTYController","data","EventStreamFactory","MouseConvenienceMethods","event","listener","type"]}