# monio-napi

[![npm](https://img.shields.io/npm/v/monio-napi.svg)](https://www.npmjs.com/package/monio-napi)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/HuakunShen/monio-napi)

Cross-platform input monitoring for Node.js, powered by [monio](https://github.com/HuakunShen/monio) and [napi-rs](https://napi.rs).

## Features

- **Cross-platform**: macOS, Windows, and Linux (X11) support
- **Proper drag detection**: Distinguishes `MouseDragged` from `MouseMoved` events
- **Event listening**: Non-blocking background listener with callback
- **Event simulation**: Programmatically generate keyboard and mouse events
- **Display queries**: Get monitor info, scale factor, refresh rate, system settings
- **Native performance**: Rust native addon via N-API, no electron/node-gyp required

## Install

```bash
npm install monio-napi
# or
pnpm add monio-napi
```

### AI agent skill

Install the monio-napi skill for agent guidance with:

```bash
npx skills add https://github.com/HuakunShen/monio-napi/skills --skill monio-napi
```

## Usage

### Listening for Events

```js
import { startListen, EventTypeJs } from 'monio-napi'

const hook = startListen((event) => {
  switch (event.eventType) {
    case EventTypeJs.KeyPressed:
      console.log('Key pressed:', event.keyboard?.key, 'raw:', event.keyboard?.rawCode)
      break
    case EventTypeJs.MouseMoved:
      console.log(`Mouse at (${event.mouse?.x}, ${event.mouse?.y})`)
      break
    case EventTypeJs.MouseDragged:
      console.log(`Dragging at (${event.mouse?.x}, ${event.mouse?.y})`)
      break
    case EventTypeJs.MouseWheel:
      console.log('Scroll:', event.wheel?.direction, event.wheel?.delta)
      break
  }
})

// Check if running
console.log('Listening:', hook.isRunning)

// Stop when done
hook.stop()
```

### Simulating Input

```js
import {
  simulateMouseMove,
  simulateMouseClick,
  simulateKeyTap,
  simulateKeyPress,
  simulateKeyRelease,
  simulateMousePress,
  simulateMouseRelease,
  ButtonJs,
  KeyJs,
} from 'monio-napi'

// Move mouse to position
simulateMouseMove(100, 200)

// Click
simulateMouseClick(ButtonJs.Left)

// Type a key
simulateKeyTap(KeyJs.KeyA)

// Hold and release
simulateKeyPress(KeyJs.ShiftLeft)
simulateKeyTap(KeyJs.KeyA) // types 'A'
simulateKeyRelease(KeyJs.ShiftLeft)
```

### Display Information

```js
import { getDisplays, getPrimaryDisplay, getDisplayAtPoint, getSystemSettings } from 'monio-napi'

// All displays
const displays = getDisplays()
for (const display of displays) {
  console.log(`Display ${display.id}: ${display.bounds.width}x${display.bounds.height}`)
  console.log(`  Scale: ${display.scaleFactor}, Refresh: ${display.refreshRate}Hz`)
}

// Primary display
const primary = getPrimaryDisplay()

// Display at a point
const display = getDisplayAtPoint(500, 300)

// System settings
const settings = getSystemSettings()
console.log('Double-click time:', settings.doubleClickTime, 'ms')
console.log('Keyboard layout:', settings.keyboardLayout)
```

## Event Types

| Event Type      | Description                             |
| --------------- | --------------------------------------- |
| `HookEnabled`   | Hook started successfully               |
| `HookDisabled`  | Hook stopped                            |
| `KeyPressed`    | Key pressed down                        |
| `KeyReleased`   | Key released                            |
| `KeyTyped`      | Character typed                         |
| `MousePressed`  | Mouse button pressed                    |
| `MouseReleased` | Mouse button released                   |
| `MouseClicked`  | Button press + release without movement |
| `MouseMoved`    | Mouse moved (no buttons held)           |
| `MouseDragged`  | Mouse moved while button held           |
| `MouseWheel`    | Scroll wheel rotated                    |

## Platform Notes

### macOS

Requires **Accessibility permissions**. Grant in System Settings > Privacy & Security > Accessibility.

### Windows

No special permissions required for hooking. Simulation may require Administrator in some contexts.

### Linux

The default entry point uses X11 (XRecord for capture, XTest for simulation).
It requires `libx11` and `libxtst` at runtime.

For input listening and simulation on Wayland, opt in to the experimental evdev backend on Linux x64 (glibc):

```js
const { startListen, EventTypeJs } = require('monio-napi/evdev')

const hook = startListen((event) => {
  if (event.eventType === EventTypeJs.KeyPressed) console.log(event.keyboard?.key)
})

process.once('SIGINT', () => hook.stop())
```

The process needs read access to `/dev/input/event*` and write access to `/dev/uinput`.
These are system input permissions. Grant them only to trusted users and processes.
The evdev entry point provides `startListen()`, including its event mask and stop controls.
Pointer coordinates for relative devices represent accumulated motion.

```js
const { simulateKeyTap, simulateMouseClick, simulateMouseMoveRelative, KeyJs, ButtonJs } = require('monio-napi/evdev')

simulateKeyTap(KeyJs.KeyA)
simulateMouseClick(ButtonJs.Left)
simulateMouseMoveRelative(40, -10)
```

`simulateMouseMoveRelative()` takes signed 32-bit input counts. The desktop applies
pointer acceleration and scaling. Absolute pointer movement and display queries
are available through the default X11 entry point. Wayland simulation was verified
on GNOME with a native GTK window. Validate other compositors separately.

When building from source, run `pnpm build:evdev` to build the evdev addon.

## Development

```bash
pnpm install
pnpm build       # release build
pnpm build:debug # debug build
pnpm test
```

## Release

Ensure `NPM_TOKEN` is set in your GitHub repository secrets.

```bash
npm version patch  # or minor / major
git push
```

GitHub Actions will build native binaries for all platforms and publish to npm.

## Publish

```bash
npm version patch
git push --follow-tags
```

## License

MIT
