Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: add npm package wrapper for pinchtab binary

Mario4aac6c159c1f
diff --git a/npm/README.md b/npm/README.md
new file mode 100644
index 00000000..6ff362ca
--- /dev/null
+++ b/npm/README.md
@@ -0,0 +1,104 @@
+# Pinchtab
+
+Browser control API for AI agents.
+
+## Installation
+
+```bash
+npm install pinchtab
+```
+
+This downloads the Pinchtab binary for your platform (macOS, Linux, Windows) on install.
+
+## Quick Start
+
+### Start the server
+
+```bash
+pinchtab serve --port 9867
+```
+
+### Use the SDK
+
+```typescript
+import Pinchtab from 'pinchtab';
+
+const pinch = new Pinchtab({ port: 9867 });
+
+// Start the server
+await pinch.start();
+
+// Take a snapshot
+const snapshot = await pinch.snapshot({ refs: 'role' });
+console.log(snapshot.html);
+
+// Click on an element
+await pinch.click({ ref: 'e42' });
+
+// Lock a tab
+await pinch.lock({ tabId: 'tab1', timeoutMs: 5000 });
+
+// Stop the server
+await pinch.stop();
+```
+
+## API
+
+### `new Pinchtab(options)`
+
+Create a Pinchtab client.
+
+**Options:**
+- `baseUrl` (string): API base URL. Default: `http://localhost:9867`
+- `timeout` (number): Request timeout in ms. Default: `30000`
+- `port` (number): Port to run on. Default: `9867`
+
+### `start(binaryPath?)`
+
+Start the Pinchtab server process.
+
+### `stop()`
+
+Stop the Pinchtab server process.
+
+### `snapshot(params?)`
+
+Take a snapshot of the current tab.
+
+**Params:**
+- `refs` ('role' | 'aria'): Reference system
+- `selector` (string): CSS selector filter
+- `maxTokens` (number): Token limit
+- `format` ('full' | 'compact'): Response format
+
+### `click(params)`
+
+Click on an element.
+
+**Params:**
+- `ref` (string): Element reference
+- `targetId` (string): Optional target tab ID
+
+### `lock(params)` / `unlock(params)`
+
+Lock/unlock a tab.
+
+### `createTab(params)`
+
+Create a new tab.
+
+**Params:**
+- `url` (string): Tab URL
+- `stealth` ('light' | 'full'): Stealth level
+
+## CLI
+
+```bash
+pinchtab serve [--port PORT]
+pinchtab --version
+pinchtab --help
+```
+
+## License
+
+MIT
diff --git a/npm/bin/pinchtab b/npm/bin/pinchtab
new file mode 100755
index 00000000..3ad5efe8
--- /dev/null
+++ b/npm/bin/pinchtab
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+
+const path = require('path');
+const { spawn } = require('child_process');
+const os = require('os');
+
+function getBinaryName() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+
+ if (platform === 'darwin') {
+ return `pinchtab-darwin-${arch}`;
+ } else if (platform === 'linux') {
+ return `pinchtab-linux-${arch}`;
+ } else if (platform === 'win32') {
+ return `pinchtab-windows-${arch}.exe`;
+ }
+
+ throw new Error(`Unsupported platform: ${platform}`);
+}
+
+const binaryPath = path.join(os.homedir(), '.pinchtab', 'bin', getBinaryName());
+
+const proc = spawn(binaryPath, process.argv.slice(2), {
+ stdio: 'inherit',
+ shell: false,
+});
+
+proc.on('error', (err) => {
+ console.error(`Failed to run Pinchtab: ${err.message}`);
+ process.exit(1);
+});
+
+process.on('SIGINT', () => {
+ proc.kill();
+});
+
+process.on('SIGTERM', () => {
+ proc.kill();
+});
diff --git a/npm/dist/download.d.ts b/npm/dist/download.d.ts
new file mode 100644
index 00000000..2603b6c2
--- /dev/null
+++ b/npm/dist/download.d.ts
@@ -0,0 +1 @@
+export declare function ensureBinary(): Promise<string>;
diff --git a/npm/dist/download.js b/npm/dist/download.js
new file mode 100644
index 00000000..3b4b458c
--- /dev/null
+++ b/npm/dist/download.js
@@ -0,0 +1,119 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ensureBinary = ensureBinary;
+const fs = __importStar(require("fs"));
+const path = __importStar(require("path"));
+const https = __importStar(require("https"));
+const GITHUB_REPO = 'pinchtab/pinchtab';
+const VERSION = '0.7.0';
+function detectPlatform() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ const osMap = {
+ darwin: 'darwin',
+ linux: 'linux',
+ win32: 'windows',
+ };
+ const os = osMap[platform];
+ if (!os) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+ return { os, arch };
+}
+function getBinaryName(platform) {
+ const { os, arch } = platform;
+ const archName = arch === 'arm64' ? 'arm64' : 'x64';
+ if (os === 'windows') {
+ return `pinchtab-${os}-${archName}.exe`;
+ }
+ return `pinchtab-${os}-${archName}`;
+}
+function getBinDir() {
+ return path.join(process.env.HOME || process.env.USERPROFILE || '', '.pinchtab', 'bin');
+}
+async function downloadBinary(platform) {
+ const binaryName = getBinaryName(platform);
+ const binDir = getBinDir();
+ const binaryPath = path.join(binDir, binaryName);
+ // Skip if already exists
+ if (fs.existsSync(binaryPath)) {
+ console.log(`✓ Pinchtab binary already present: ${binaryPath}`);
+ return;
+ }
+ const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}/${binaryName}`;
+ console.log(`Downloading Pinchtab ${VERSION} for ${platform.os}-${platform.arch}...`);
+ console.log(`URL: ${downloadUrl}`);
+ // Ensure directory exists
+ if (!fs.existsSync(binDir)) {
+ fs.mkdirSync(binDir, { recursive: true });
+ }
+ return new Promise((resolve, reject) => {
+ https
+ .get(downloadUrl, (response) => {
+ if (response.statusCode === 404) {
+ reject(new Error(`Binary not found: ${downloadUrl}. Make sure v${VERSION} is released on GitHub.`));
+ return;
+ }
+ if (response.statusCode !== 200) {
+ reject(new Error(`Download failed with status ${response.statusCode}`));
+ return;
+ }
+ const file = fs.createWriteStream(binaryPath);
+ response.pipe(file);
+ file.on('finish', () => {
+ file.close();
+ // Make executable
+ fs.chmodSync(binaryPath, 0o755);
+ console.log(`✓ Downloaded to ${binaryPath}`);
+ resolve();
+ });
+ file.on('error', (err) => {
+ fs.unlink(binaryPath, () => { });
+ reject(err);
+ });
+ })
+ .on('error', (err) => {
+ reject(err);
+ });
+ });
+}
+async function ensureBinary() {
+ const platform = detectPlatform();
+ await downloadBinary(platform);
+ const binDir = getBinDir();
+ const binaryName = getBinaryName(platform);
+ return path.join(binDir, binaryName);
+}
diff --git a/npm/dist/index.d.ts b/npm/dist/index.d.ts
new file mode 100644
index 00000000..acb3cf3d
--- /dev/null
+++ b/npm/dist/index.d.ts
@@ -0,0 +1,48 @@
+import { SnapshotParams, SnapshotResponse, TabClickParams, TabLockParams, TabUnlockParams, CreateTabParams, CreateTabResponse, PinchtabOptions } from './types';
+export * from './types';
+export declare class Pinchtab {
+ private baseUrl;
+ private timeout;
+ private port;
+ private process;
+ private binaryPath;
+ constructor(options?: PinchtabOptions);
+ /**
+ * Start the Pinchtab server process
+ */
+ start(binaryPath?: string): Promise<void>;
+ /**
+ * Stop the Pinchtab server process
+ */
+ stop(): Promise<void>;
+ /**
+ * Take a snapshot of the current tab
+ */
+ snapshot(params?: SnapshotParams): Promise<SnapshotResponse>;
+ /**
+ * Click on a UI element
+ */
+ click(params: TabClickParams): Promise<void>;
+ /**
+ * Lock a tab
+ */
+ lock(params: TabLockParams): Promise<void>;
+ /**
+ * Unlock a tab
+ */
+ unlock(params: TabUnlockParams): Promise<void>;
+ /**
+ * Create a new tab
+ */
+ createTab(params: CreateTabParams): Promise<CreateTabResponse>;
+ /**
+ * Make a request to the Pinchtab API
+ */
+ private request;
+ /**
+ * Get the path to the Pinchtab binary
+ */
+ private getBinaryPath;
+ private getBinaryName;
+}
+export default Pinchtab;
diff --git a/npm/dist/index.js b/npm/dist/index.js
new file mode 100644
index 00000000..0f8431f6
--- /dev/null
+++ b/npm/dist/index.js
@@ -0,0 +1,174 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.Pinchtab = void 0;
+const child_process_1 = require("child_process");
+const path = __importStar(require("path"));
+const fs = __importStar(require("fs"));
+__exportStar(require("./types"), exports);
+class Pinchtab {
+ constructor(options = {}) {
+ this.process = null;
+ this.binaryPath = null;
+ this.port = options.port || 9867;
+ this.baseUrl = options.baseUrl || `http://localhost:${this.port}`;
+ this.timeout = options.timeout || 30000;
+ }
+ /**
+ * Start the Pinchtab server process
+ */
+ async start(binaryPath) {
+ if (this.process) {
+ throw new Error('Pinchtab process already running');
+ }
+ if (!binaryPath) {
+ binaryPath = await this.getBinaryPath();
+ }
+ this.binaryPath = binaryPath;
+ return new Promise((resolve, reject) => {
+ this.process = (0, child_process_1.spawn)(binaryPath, ['serve', `--port=${this.port}`], {
+ stdio: 'inherit',
+ });
+ this.process.on('error', (err) => {
+ reject(new Error(`Failed to start Pinchtab: ${err.message}`));
+ });
+ // Give the server a moment to start
+ setTimeout(resolve, 500);
+ });
+ }
+ /**
+ * Stop the Pinchtab server process
+ */
+ async stop() {
+ if (this.process) {
+ return new Promise((resolve) => {
+ this.process?.kill();
+ this.process = null;
+ resolve();
+ });
+ }
+ }
+ /**
+ * Take a snapshot of the current tab
+ */
+ async snapshot(params) {
+ return this.request('/snapshot', params);
+ }
+ /**
+ * Click on a UI element
+ */
+ async click(params) {
+ await this.request('/tab/click', params);
+ }
+ /**
+ * Lock a tab
+ */
+ async lock(params) {
+ await this.request('/tab/lock', params);
+ }
+ /**
+ * Unlock a tab
+ */
+ async unlock(params) {
+ await this.request('/tab/unlock', params);
+ }
+ /**
+ * Create a new tab
+ */
+ async createTab(params) {
+ return this.request('/tab/create', params);
+ }
+ /**
+ * Make a request to the Pinchtab API
+ */
+ async request(path, body) {
+ const url = `${this.baseUrl}${path}`;
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(`${response.status}: ${error}`);
+ }
+ return response.json();
+ }
+ finally {
+ clearTimeout(timeoutId);
+ }
+ }
+ /**
+ * Get the path to the Pinchtab binary
+ */
+ async getBinaryPath() {
+ const homedir = require('os').homedir();
+ const defaultPath = path.join(homedir, '.pinchtab', 'bin', this.getBinaryName());
+ if (fs.existsSync(defaultPath)) {
+ return defaultPath;
+ }
+ // Try relative to package
+ const relativePath = path.join(__dirname, '..', 'bin', this.getBinaryName());
+ if (fs.existsSync(relativePath)) {
+ return relativePath;
+ }
+ throw new Error(`Pinchtab binary not found. Please run: npm run postinstall or ensure the binary is in ~/.pinchtab/bin/`);
+ }
+ getBinaryName() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ if (platform === 'darwin') {
+ return `pinchtab-darwin-${arch}`;
+ }
+ else if (platform === 'linux') {
+ return `pinchtab-linux-${arch}`;
+ }
+ else if (platform === 'win32') {
+ return `pinchtab-windows-${arch}.exe`;
+ }
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+}
+exports.Pinchtab = Pinchtab;
+exports.default = Pinchtab;
diff --git a/npm/dist/src/download.d.ts b/npm/dist/src/download.d.ts
new file mode 100644
index 00000000..2603b6c2
--- /dev/null
+++ b/npm/dist/src/download.d.ts
@@ -0,0 +1 @@
+export declare function ensureBinary(): Promise<string>;
diff --git a/npm/dist/src/download.js b/npm/dist/src/download.js
new file mode 100644
index 00000000..3b4b458c
--- /dev/null
+++ b/npm/dist/src/download.js
@@ -0,0 +1,119 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ensureBinary = ensureBinary;
+const fs = __importStar(require("fs"));
+const path = __importStar(require("path"));
+const https = __importStar(require("https"));
+const GITHUB_REPO = 'pinchtab/pinchtab';
+const VERSION = '0.7.0';
+function detectPlatform() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ const osMap = {
+ darwin: 'darwin',
+ linux: 'linux',
+ win32: 'windows',
+ };
+ const os = osMap[platform];
+ if (!os) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+ return { os, arch };
+}
+function getBinaryName(platform) {
+ const { os, arch } = platform;
+ const archName = arch === 'arm64' ? 'arm64' : 'x64';
+ if (os === 'windows') {
+ return `pinchtab-${os}-${archName}.exe`;
+ }
+ return `pinchtab-${os}-${archName}`;
+}
+function getBinDir() {
+ return path.join(process.env.HOME || process.env.USERPROFILE || '', '.pinchtab', 'bin');
+}
+async function downloadBinary(platform) {
+ const binaryName = getBinaryName(platform);
+ const binDir = getBinDir();
+ const binaryPath = path.join(binDir, binaryName);
+ // Skip if already exists
+ if (fs.existsSync(binaryPath)) {
+ console.log(`✓ Pinchtab binary already present: ${binaryPath}`);
+ return;
+ }
+ const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}/${binaryName}`;
+ console.log(`Downloading Pinchtab ${VERSION} for ${platform.os}-${platform.arch}...`);
+ console.log(`URL: ${downloadUrl}`);
+ // Ensure directory exists
+ if (!fs.existsSync(binDir)) {
+ fs.mkdirSync(binDir, { recursive: true });
+ }
+ return new Promise((resolve, reject) => {
+ https
+ .get(downloadUrl, (response) => {
+ if (response.statusCode === 404) {
+ reject(new Error(`Binary not found: ${downloadUrl}. Make sure v${VERSION} is released on GitHub.`));
+ return;
+ }
+ if (response.statusCode !== 200) {
+ reject(new Error(`Download failed with status ${response.statusCode}`));
+ return;
+ }
+ const file = fs.createWriteStream(binaryPath);
+ response.pipe(file);
+ file.on('finish', () => {
+ file.close();
+ // Make executable
+ fs.chmodSync(binaryPath, 0o755);
+ console.log(`✓ Downloaded to ${binaryPath}`);
+ resolve();
+ });
+ file.on('error', (err) => {
+ fs.unlink(binaryPath, () => { });
+ reject(err);
+ });
+ })
+ .on('error', (err) => {
+ reject(err);
+ });
+ });
+}
+async function ensureBinary() {
+ const platform = detectPlatform();
+ await downloadBinary(platform);
+ const binDir = getBinDir();
+ const binaryName = getBinaryName(platform);
+ return path.join(binDir, binaryName);
+}
diff --git a/npm/dist/src/index.d.ts b/npm/dist/src/index.d.ts
new file mode 100644
index 00000000..acb3cf3d
--- /dev/null
+++ b/npm/dist/src/index.d.ts
@@ -0,0 +1,48 @@
+import { SnapshotParams, SnapshotResponse, TabClickParams, TabLockParams, TabUnlockParams, CreateTabParams, CreateTabResponse, PinchtabOptions } from './types';
+export * from './types';
+export declare class Pinchtab {
+ private baseUrl;
+ private timeout;
+ private port;
+ private process;
+ private binaryPath;
+ constructor(options?: PinchtabOptions);
+ /**
+ * Start the Pinchtab server process
+ */
+ start(binaryPath?: string): Promise<void>;
+ /**
+ * Stop the Pinchtab server process
+ */
+ stop(): Promise<void>;
+ /**
+ * Take a snapshot of the current tab
+ */
+ snapshot(params?: SnapshotParams): Promise<SnapshotResponse>;
+ /**
+ * Click on a UI element
+ */
+ click(params: TabClickParams): Promise<void>;
+ /**
+ * Lock a tab
+ */
+ lock(params: TabLockParams): Promise<void>;
+ /**
+ * Unlock a tab
+ */
+ unlock(params: TabUnlockParams): Promise<void>;
+ /**
+ * Create a new tab
+ */
+ createTab(params: CreateTabParams): Promise<CreateTabResponse>;
+ /**
+ * Make a request to the Pinchtab API
+ */
+ private request;
+ /**
+ * Get the path to the Pinchtab binary
+ */
+ private getBinaryPath;
+ private getBinaryName;
+}
+export default Pinchtab;
diff --git a/npm/dist/src/index.js b/npm/dist/src/index.js
new file mode 100644
index 00000000..0f8431f6
--- /dev/null
+++ b/npm/dist/src/index.js
@@ -0,0 +1,174 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.Pinchtab = void 0;
+const child_process_1 = require("child_process");
+const path = __importStar(require("path"));
+const fs = __importStar(require("fs"));
+__exportStar(require("./types"), exports);
+class Pinchtab {
+ constructor(options = {}) {
+ this.process = null;
+ this.binaryPath = null;
+ this.port = options.port || 9867;
+ this.baseUrl = options.baseUrl || `http://localhost:${this.port}`;
+ this.timeout = options.timeout || 30000;
+ }
+ /**
+ * Start the Pinchtab server process
+ */
+ async start(binaryPath) {
+ if (this.process) {
+ throw new Error('Pinchtab process already running');
+ }
+ if (!binaryPath) {
+ binaryPath = await this.getBinaryPath();
+ }
+ this.binaryPath = binaryPath;
+ return new Promise((resolve, reject) => {
+ this.process = (0, child_process_1.spawn)(binaryPath, ['serve', `--port=${this.port}`], {
+ stdio: 'inherit',
+ });
+ this.process.on('error', (err) => {
+ reject(new Error(`Failed to start Pinchtab: ${err.message}`));
+ });
+ // Give the server a moment to start
+ setTimeout(resolve, 500);
+ });
+ }
+ /**
+ * Stop the Pinchtab server process
+ */
+ async stop() {
+ if (this.process) {
+ return new Promise((resolve) => {
+ this.process?.kill();
+ this.process = null;
+ resolve();
+ });
+ }
+ }
+ /**
+ * Take a snapshot of the current tab
+ */
+ async snapshot(params) {
+ return this.request('/snapshot', params);
+ }
+ /**
+ * Click on a UI element
+ */
+ async click(params) {
+ await this.request('/tab/click', params);
+ }
+ /**
+ * Lock a tab
+ */
+ async lock(params) {
+ await this.request('/tab/lock', params);
+ }
+ /**
+ * Unlock a tab
+ */
+ async unlock(params) {
+ await this.request('/tab/unlock', params);
+ }
+ /**
+ * Create a new tab
+ */
+ async createTab(params) {
+ return this.request('/tab/create', params);
+ }
+ /**
+ * Make a request to the Pinchtab API
+ */
+ async request(path, body) {
+ const url = `${this.baseUrl}${path}`;
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(`${response.status}: ${error}`);
+ }
+ return response.json();
+ }
+ finally {
+ clearTimeout(timeoutId);
+ }
+ }
+ /**
+ * Get the path to the Pinchtab binary
+ */
+ async getBinaryPath() {
+ const homedir = require('os').homedir();
+ const defaultPath = path.join(homedir, '.pinchtab', 'bin', this.getBinaryName());
+ if (fs.existsSync(defaultPath)) {
+ return defaultPath;
+ }
+ // Try relative to package
+ const relativePath = path.join(__dirname, '..', 'bin', this.getBinaryName());
+ if (fs.existsSync(relativePath)) {
+ return relativePath;
+ }
+ throw new Error(`Pinchtab binary not found. Please run: npm run postinstall or ensure the binary is in ~/.pinchtab/bin/`);
+ }
+ getBinaryName() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ if (platform === 'darwin') {
+ return `pinchtab-darwin-${arch}`;
+ }
+ else if (platform === 'linux') {
+ return `pinchtab-linux-${arch}`;
+ }
+ else if (platform === 'win32') {
+ return `pinchtab-windows-${arch}.exe`;
+ }
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+}
+exports.Pinchtab = Pinchtab;
+exports.default = Pinchtab;
diff --git a/npm/dist/src/types.d.ts b/npm/dist/src/types.d.ts
new file mode 100644
index 00000000..95d085bb
--- /dev/null
+++ b/npm/dist/src/types.d.ts
@@ -0,0 +1,33 @@
+export interface SnapshotParams {
+ refs?: 'role' | 'aria';
+ selector?: string;
+ maxTokens?: number;
+ format?: 'full' | 'compact';
+}
+export interface SnapshotResponse {
+ html: string;
+ refs?: Record<string, any>;
+}
+export interface TabClickParams {
+ ref: string;
+ targetId?: string;
+}
+export interface TabLockParams {
+ tabId: string;
+ timeoutMs?: number;
+}
+export interface TabUnlockParams {
+ tabId: string;
+}
+export interface CreateTabParams {
+ url: string;
+ stealth?: 'light' | 'full';
+}
+export interface CreateTabResponse {
+ tabId: string;
+}
+export interface PinchtabOptions {
+ baseUrl?: string;
+ timeout?: number;
+ port?: number;
+}
diff --git a/npm/dist/src/types.js b/npm/dist/src/types.js
new file mode 100644
index 00000000..c8ad2e54
--- /dev/null
+++ b/npm/dist/src/types.js
@@ -0,0 +1,2 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
diff --git a/npm/dist/tests/integration.test.d.ts b/npm/dist/tests/integration.test.d.ts
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/npm/dist/tests/integration.test.d.ts
@@ -0,0 +1 @@
+export {};
diff --git a/npm/dist/tests/integration.test.js b/npm/dist/tests/integration.test.js
new file mode 100644
index 00000000..149e4023
--- /dev/null
+++ b/npm/dist/tests/integration.test.js
@@ -0,0 +1,137 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const node_test_1 = require("node:test");
+const assert = __importStar(require("node:assert"));
+const index_1 = __importDefault(require("../src/index"));
+const fs = __importStar(require("fs"));
+const path = __importStar(require("path"));
+const os = __importStar(require("os"));
+(0, node_test_1.describe)('Pinchtab npm Integration Tests', () => {
+ let pinch;
+ const testPort = 9867;
+ (0, node_test_1.before)(async () => {
+ // Check if binary exists before running tests
+ const binDir = path.join(os.homedir(), '.pinchtab', 'bin');
+ const platform = process.platform === 'darwin' ? 'darwin' : process.platform === 'linux' ? 'linux' : 'windows';
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ const ext = platform === 'windows' ? '.exe' : '';
+ const binaryPath = path.join(binDir, `pinchtab-${platform}-${arch}${ext}`);
+ if (!fs.existsSync(binaryPath)) {
+ console.warn(`⚠ Binary not found at ${binaryPath}`);
+ console.warn('Tests will skip binary execution. Build the Go binary and place it at:');
+ console.warn(` ${binaryPath}`);
+ }
+ pinch = new index_1.default({ port: testPort });
+ });
+ (0, node_test_1.after)(async () => {
+ // Clean up: stop server if running
+ try {
+ await pinch.stop();
+ }
+ catch (e) {
+ // Ignore
+ }
+ });
+ (0, node_test_1.test)('should import Pinchtab class', () => {
+ assert.ok(typeof index_1.default === 'function');
+ assert.ok(pinch instanceof index_1.default);
+ });
+ (0, node_test_1.test)('should initialize with default options', () => {
+ const client = new index_1.default();
+ assert.ok(client);
+ });
+ (0, node_test_1.test)('should initialize with custom port', () => {
+ const client = new index_1.default({ port: 9999 });
+ assert.ok(client);
+ });
+ (0, node_test_1.test)('should have API methods defined', () => {
+ assert.strictEqual(typeof pinch.start, 'function');
+ assert.strictEqual(typeof pinch.stop, 'function');
+ assert.strictEqual(typeof pinch.snapshot, 'function');
+ assert.strictEqual(typeof pinch.click, 'function');
+ assert.strictEqual(typeof pinch.lock, 'function');
+ assert.strictEqual(typeof pinch.unlock, 'function');
+ assert.strictEqual(typeof pinch.createTab, 'function');
+ });
+ (0, node_test_1.test)('should start server (requires binary)', async () => {
+ const client = new index_1.default({ port: testPort });
+ try {
+ await client.start();
+ // Give server a moment to be ready
+ await new Promise(r => setTimeout(r, 1000));
+ // Try a simple health check
+ const response = await fetch(`http://localhost:${testPort}/`);
+ assert.ok(response.status !== undefined);
+ await client.stop();
+ }
+ catch (err) {
+ const errorMsg = err.message;
+ if (errorMsg.includes('ENOENT') || errorMsg.includes('not found')) {
+ console.log('⊘ Binary not available — skipping start test');
+ }
+ else {
+ throw err;
+ }
+ }
+ });
+ (0, node_test_1.test)('should handle missing binary gracefully', async () => {
+ const client = new index_1.default({ port: 9998 });
+ try {
+ await client.start('/nonexistent/path/to/binary');
+ // If we get here, the binary exists (unusual test environment)
+ }
+ catch (err) {
+ assert.ok(err instanceof Error);
+ assert.ok(err.message.includes('Failed to start') ||
+ err.message.includes('ENOENT'));
+ }
+ });
+ (0, node_test_1.test)('should reject invalid request to non-running server', async () => {
+ const client = new index_1.default({ port: 9997 });
+ try {
+ await client.snapshot();
+ // Should not reach here
+ assert.fail('Expected connection error');
+ }
+ catch (err) {
+ // Expected — server not running
+ assert.ok(err instanceof Error);
+ }
+ });
+});
diff --git a/npm/dist/types.d.ts b/npm/dist/types.d.ts
new file mode 100644
index 00000000..95d085bb
--- /dev/null
+++ b/npm/dist/types.d.ts
@@ -0,0 +1,33 @@
+export interface SnapshotParams {
+ refs?: 'role' | 'aria';
+ selector?: string;
+ maxTokens?: number;
+ format?: 'full' | 'compact';
+}
+export interface SnapshotResponse {
+ html: string;
+ refs?: Record<string, any>;
+}
+export interface TabClickParams {
+ ref: string;
+ targetId?: string;
+}
+export interface TabLockParams {
+ tabId: string;
+ timeoutMs?: number;
+}
+export interface TabUnlockParams {
+ tabId: string;
+}
+export interface CreateTabParams {
+ url: string;
+ stealth?: 'light' | 'full';
+}
+export interface CreateTabResponse {
+ tabId: string;
+}
+export interface PinchtabOptions {
+ baseUrl?: string;
+ timeout?: number;
+ port?: number;
+}
diff --git a/npm/dist/types.js b/npm/dist/types.js
new file mode 100644
index 00000000..c8ad2e54
--- /dev/null
+++ b/npm/dist/types.js
@@ -0,0 +1,2 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
diff --git a/npm/package-lock.json b/npm/package-lock.json
new file mode 100644
index 00000000..1ac053ff
--- /dev/null
+++ b/npm/package-lock.json
@@ -0,0 +1,55 @@
+{
+ "name": "pinchtab",
+ "version": "0.7.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "pinchtab",
+ "version": "0.7.0",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "pinchtab": "bin/pinchtab"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.3.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.33",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz",
+ "integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/npm/package.json b/npm/package.json
new file mode 100644
index 00000000..49ef448b
--- /dev/null
+++ b/npm/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "pinchtab",
+ "version": "0.7.0",
+ "description": "Browser control API for AI agents",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "bin": {
+ "pinchtab": "bin/pinchtab"
+ },
+ "scripts": {
+ "build": "tsc",
+ "test": "node --test dist/tests/integration.test.js",
+ "postinstall": "node scripts/postinstall.js",
+ "prepare": "npm run build"
+ },
+ "files": [
+ "dist",
+ "bin",
+ "scripts"
+ ],
+ "keywords": [
+ "browser",
+ "automation",
+ "api",
+ "agent",
+ "ai"
+ ],
+ "author": "Mario <[email protected]>",
+ "license": "MIT",
+ "devDependencies": {
+ "typescript": "^5.3.0",
+ "@types/node": "^20.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+}
diff --git a/npm/scripts/postinstall.js b/npm/scripts/postinstall.js
new file mode 100644
index 00000000..4852e321
--- /dev/null
+++ b/npm/scripts/postinstall.js
@@ -0,0 +1,112 @@
+#!/usr/bin/env node
+
+const https = require('https');
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+
+const GITHUB_REPO = 'pinchtab/pinchtab';
+const VERSION = '0.7.0';
+
+function detectPlatform() {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+
+ const osMap = {
+ darwin: 'darwin',
+ linux: 'linux',
+ win32: 'windows',
+ };
+
+ const detectedOS = osMap[platform];
+ if (!detectedOS) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+
+ return { os: detectedOS, arch };
+}
+
+function getBinaryName(platform) {
+ const { os, arch } = platform;
+ const archName = arch === 'arm64' ? 'arm64' : 'x64';
+
+ if (os === 'windows') {
+ return `pinchtab-${os}-${archName}.exe`;
+ }
+ return `pinchtab-${os}-${archName}`;
+}
+
+function getBinDir() {
+ return path.join(os.homedir(), '.pinchtab', 'bin');
+}
+
+async function downloadBinary(platform) {
+ const binaryName = getBinaryName(platform);
+ const binDir = getBinDir();
+ const binaryPath = path.join(binDir, binaryName);
+
+ // Skip if already exists
+ if (fs.existsSync(binaryPath)) {
+ console.log(`✓ Pinchtab binary already present: ${binaryPath}`);
+ return;
+ }
+
+ const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}/${binaryName}`;
+
+ console.log(`Downloading Pinchtab ${VERSION} for ${platform.os}-${platform.arch}...`);
+
+ // Ensure directory exists
+ if (!fs.existsSync(binDir)) {
+ fs.mkdirSync(binDir, { recursive: true });
+ }
+
+ return new Promise((resolve, reject) => {
+ https
+ .get(downloadUrl, (response) => {
+ if (response.statusCode === 404) {
+ console.warn(
+ `⚠ Binary not found at ${downloadUrl}. Make sure v${VERSION} is released on GitHub.`
+ );
+ resolve();
+ return;
+ }
+
+ if (response.statusCode !== 200) {
+ console.warn(`⚠ Download failed with status ${response.statusCode}`);
+ resolve();
+ return;
+ }
+
+ const file = fs.createWriteStream(binaryPath);
+ response.pipe(file);
+
+ file.on('finish', () => {
+ file.close();
+ fs.chmodSync(binaryPath, 0o755);
+ console.log(`✓ Downloaded to ${binaryPath}`);
+ resolve();
+ });
+
+ file.on('error', (err) => {
+ fs.unlink(binaryPath, () => {});
+ reject(err);
+ });
+ })
+ .on('error', (err) => {
+ console.warn(`⚠ Failed to download: ${err.message}`);
+ resolve();
+ });
+ });
+}
+
+// Run download
+const platform = detectPlatform();
+downloadBinary(platform)
+ .then(() => {
+ console.log('✓ Pinchtab setup complete');
+ process.exit(0);
+ })
+ .catch((err) => {
+ console.error('✗ Setup error:', err.message);
+ process.exit(1);
+ });
diff --git a/npm/scripts/postinstall.ts b/npm/scripts/postinstall.ts
new file mode 100644
index 00000000..bb88e19d
--- /dev/null
+++ b/npm/scripts/postinstall.ts
@@ -0,0 +1,11 @@
+import { ensureBinary } from '../src/download';
+
+ensureBinary()
+ .then(() => {
+ console.log('✓ Pinchtab setup complete');
+ process.exit(0);
+ })
+ .catch((err) => {
+ console.error('✗ Failed to setup Pinchtab:', err.message);
+ process.exit(1);
+ });
diff --git a/npm/src/download.ts b/npm/src/download.ts
new file mode 100644
index 00000000..ab761bbb
--- /dev/null
+++ b/npm/src/download.ts
@@ -0,0 +1,111 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import * as https from 'https';
+
+const GITHUB_REPO = 'pinchtab/pinchtab';
+const VERSION = '0.7.0';
+
+interface Platform {
+ os: 'darwin' | 'linux' | 'windows';
+ arch: 'x64' | 'arm64';
+}
+
+function detectPlatform(): Platform {
+ const platform = process.platform as any;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+
+ const osMap: Record<string, 'darwin' | 'linux' | 'windows'> = {
+ darwin: 'darwin',
+ linux: 'linux',
+ win32: 'windows',
+ };
+
+ const os = osMap[platform];
+ if (!os) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+
+ return { os, arch };
+}
+
+function getBinaryName(platform: Platform): string {
+ const { os, arch } = platform;
+ const archName = arch === 'arm64' ? 'arm64' : 'x64';
+
+ if (os === 'windows') {
+ return `pinchtab-${os}-${archName}.exe`;
+ }
+ return `pinchtab-${os}-${archName}`;
+}
+
+function getBinDir(): string {
+ return path.join(process.env.HOME || process.env.USERPROFILE || '', '.pinchtab', 'bin');
+}
+
+async function downloadBinary(platform: Platform): Promise<void> {
+ const binaryName = getBinaryName(platform);
+ const binDir = getBinDir();
+ const binaryPath = path.join(binDir, binaryName);
+
+ // Skip if already exists
+ if (fs.existsSync(binaryPath)) {
+ console.log(`✓ Pinchtab binary already present: ${binaryPath}`);
+ return;
+ }
+
+ const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}/${binaryName}`;
+
+ console.log(`Downloading Pinchtab ${VERSION} for ${platform.os}-${platform.arch}...`);
+ console.log(`URL: ${downloadUrl}`);
+
+ // Ensure directory exists
+ if (!fs.existsSync(binDir)) {
+ fs.mkdirSync(binDir, { recursive: true });
+ }
+
+ return new Promise((resolve, reject) => {
+ https
+ .get(downloadUrl, (response) => {
+ if (response.statusCode === 404) {
+ reject(
+ new Error(
+ `Binary not found: ${downloadUrl}. Make sure v${VERSION} is released on GitHub.`
+ )
+ );
+ return;
+ }
+
+ if (response.statusCode !== 200) {
+ reject(new Error(`Download failed with status ${response.statusCode}`));
+ return;
+ }
+
+ const file = fs.createWriteStream(binaryPath);
+ response.pipe(file);
+
+ file.on('finish', () => {
+ file.close();
+ // Make executable
+ fs.chmodSync(binaryPath, 0o755);
+ console.log(`✓ Downloaded to ${binaryPath}`);
+ resolve();
+ });
+
+ file.on('error', (err) => {
+ fs.unlink(binaryPath, () => {});
+ reject(err);
+ });
+ })
+ .on('error', (err) => {
+ reject(err);
+ });
+ });
+}
+
+export async function ensureBinary(): Promise<string> {
+ const platform = detectPlatform();
+ await downloadBinary(platform);
+ const binDir = getBinDir();
+ const binaryName = getBinaryName(platform);
+ return path.join(binDir, binaryName);
+}
diff --git a/npm/src/index.ts b/npm/src/index.ts
new file mode 100644
index 00000000..763c1d14
--- /dev/null
+++ b/npm/src/index.ts
@@ -0,0 +1,174 @@
+import { spawn, ChildProcess } from 'child_process';
+import * as path from 'path';
+import * as fs from 'fs';
+import {
+ SnapshotParams,
+ SnapshotResponse,
+ TabClickParams,
+ TabLockParams,
+ TabUnlockParams,
+ CreateTabParams,
+ CreateTabResponse,
+ PinchtabOptions,
+} from './types';
+
+export * from './types';
+
+export class Pinchtab {
+ private baseUrl: string;
+ private timeout: number;
+ private port: number;
+ private process: ChildProcess | null = null;
+ private binaryPath: string | null = null;
+
+ constructor(options: PinchtabOptions = {}) {
+ this.port = options.port || 9867;
+ this.baseUrl = options.baseUrl || `http://localhost:${this.port}`;
+ this.timeout = options.timeout || 30000;
+ }
+
+ /**
+ * Start the Pinchtab server process
+ */
+ async start(binaryPath?: string): Promise<void> {
+ if (this.process) {
+ throw new Error('Pinchtab process already running');
+ }
+
+ if (!binaryPath) {
+ binaryPath = await this.getBinaryPath();
+ }
+
+ this.binaryPath = binaryPath;
+
+ return new Promise((resolve, reject) => {
+ this.process = spawn(binaryPath, ['serve', `--port=${this.port}`], {
+ stdio: 'inherit',
+ });
+
+ this.process.on('error', (err) => {
+ reject(new Error(`Failed to start Pinchtab: ${err.message}`));
+ });
+
+ // Give the server a moment to start
+ setTimeout(resolve, 500);
+ });
+ }
+
+ /**
+ * Stop the Pinchtab server process
+ */
+ async stop(): Promise<void> {
+ if (this.process) {
+ return new Promise((resolve) => {
+ this.process?.kill();
+ this.process = null;
+ resolve();
+ });
+ }
+ }
+
+ /**
+ * Take a snapshot of the current tab
+ */
+ async snapshot(params?: SnapshotParams): Promise<SnapshotResponse> {
+ return this.request<SnapshotResponse>('/snapshot', params);
+ }
+
+ /**
+ * Click on a UI element
+ */
+ async click(params: TabClickParams): Promise<void> {
+ await this.request('/tab/click', params);
+ }
+
+ /**
+ * Lock a tab
+ */
+ async lock(params: TabLockParams): Promise<void> {
+ await this.request('/tab/lock', params);
+ }
+
+ /**
+ * Unlock a tab
+ */
+ async unlock(params: TabUnlockParams): Promise<void> {
+ await this.request('/tab/unlock', params);
+ }
+
+ /**
+ * Create a new tab
+ */
+ async createTab(params: CreateTabParams): Promise<CreateTabResponse> {
+ return this.request<CreateTabResponse>('/tab/create', params);
+ }
+
+ /**
+ * Make a request to the Pinchtab API
+ */
+ private async request<T = any>(path: string, body?: any): Promise<T> {
+ const url = `${this.baseUrl}${path}`;
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ signal: controller.signal as any,
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ throw new Error(`${response.status}: ${error}`);
+ }
+
+ return response.json() as Promise<T>;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ /**
+ * Get the path to the Pinchtab binary
+ */
+ private async getBinaryPath(): Promise<string> {
+ const homedir = require('os').homedir();
+ const defaultPath = path.join(homedir, '.pinchtab', 'bin', this.getBinaryName());
+
+ if (fs.existsSync(defaultPath)) {
+ return defaultPath;
+ }
+
+ // Try relative to package
+ const relativePath = path.join(__dirname, '..', 'bin', this.getBinaryName());
+ if (fs.existsSync(relativePath)) {
+ return relativePath;
+ }
+
+ throw new Error(
+ `Pinchtab binary not found. Please run: npm run postinstall or ensure the binary is in ~/.pinchtab/bin/`
+ );
+ }
+
+ private getBinaryName(): string {
+ const platform = process.platform;
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+
+ if (platform === 'darwin') {
+ return `pinchtab-darwin-${arch}`;
+ } else if (platform === 'linux') {
+ return `pinchtab-linux-${arch}`;
+ } else if (platform === 'win32') {
+ return `pinchtab-windows-${arch}.exe`;
+ }
+
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+}
+
+export default Pinchtab;
diff --git a/npm/src/types.ts b/npm/src/types.ts
new file mode 100644
index 00000000..c1c574df
--- /dev/null
+++ b/npm/src/types.ts
@@ -0,0 +1,40 @@
+export interface SnapshotParams {
+ refs?: 'role' | 'aria';
+ selector?: string;
+ maxTokens?: number;
+ format?: 'full' | 'compact';
+}
+
+export interface SnapshotResponse {
+ html: string;
+ refs?: Record<string, any>;
+}
+
+export interface TabClickParams {
+ ref: string;
+ targetId?: string;
+}
+
+export interface TabLockParams {
+ tabId: string;
+ timeoutMs?: number;
+}
+
+export interface TabUnlockParams {
+ tabId: string;
+}
+
+export interface CreateTabParams {
+ url: string;
+ stealth?: 'light' | 'full';
+}
+
+export interface CreateTabResponse {
+ tabId: string;
+}
+
+export interface PinchtabOptions {
+ baseUrl?: string;
+ timeout?: number;
+ port?: number;
+}
diff --git a/npm/tests/TEST_PLAN.md b/npm/tests/TEST_PLAN.md
new file mode 100644
index 00000000..7b25201e
--- /dev/null
+++ b/npm/tests/TEST_PLAN.md
@@ -0,0 +1,48 @@
+# Pinchtab npm Package — Test Plan
+
+## Scope
+Test that the npm package correctly:
+1. Finds and executes the Pinchtab binary
+2. Manages process lifecycle (start/stop)
+3. Communicates with the API via HTTP
+4. Handles errors gracefully
+
+## Test Cases
+
+### 1. Binary Discovery
+- ✓ Binary exists at `~/.pinchtab/bin/pinchtab-<os>-<arch>`
+- ✓ CLI wrapper finds and executes binary
+- ✗ Graceful error if binary missing
+
+### 2. Process Lifecycle
+- ✓ `start()` spawns server on correct port
+- ✓ Server responds to health check (any endpoint)
+- ✓ `stop()` kills process cleanly
+- ✗ `start()` twice throws error
+- ✗ `stop()` when not running is no-op
+
+### 3. API Requests
+- ✓ `snapshot()` returns valid response
+- ✓ `click()` executes without error
+- ✓ `lock()` / `unlock()` work
+- ✓ `createTab()` returns tab ID
+- ✗ Request timeout after 30s
+
+### 4. Error Handling
+- ✗ Invalid endpoint returns 404
+- ✗ Malformed params rejected
+- ✗ Server crashes → clear error message
+
+## Environment
+- Binary must exist: `~/.pinchtab/bin/pinchtab-darwin-arm64` (or platform equivalent)
+- Port 9867 must be available
+- Test runner: Node.js native `test` module
+
+## Execution
+```bash
+npm test
+```
+
+---
+
+*Add new test cases as you discover edge cases.*
diff --git a/npm/tests/integration.test.d.ts b/npm/tests/integration.test.d.ts
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/npm/tests/integration.test.d.ts
@@ -0,0 +1 @@
+export {};
diff --git a/npm/tests/integration.test.js b/npm/tests/integration.test.js
new file mode 100644
index 00000000..149e4023
--- /dev/null
+++ b/npm/tests/integration.test.js
@@ -0,0 +1,137 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const node_test_1 = require("node:test");
+const assert = __importStar(require("node:assert"));
+const index_1 = __importDefault(require("../src/index"));
+const fs = __importStar(require("fs"));
+const path = __importStar(require("path"));
+const os = __importStar(require("os"));
+(0, node_test_1.describe)('Pinchtab npm Integration Tests', () => {
+ let pinch;
+ const testPort = 9867;
+ (0, node_test_1.before)(async () => {
+ // Check if binary exists before running tests
+ const binDir = path.join(os.homedir(), '.pinchtab', 'bin');
+ const platform = process.platform === 'darwin' ? 'darwin' : process.platform === 'linux' ? 'linux' : 'windows';
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ const ext = platform === 'windows' ? '.exe' : '';
+ const binaryPath = path.join(binDir, `pinchtab-${platform}-${arch}${ext}`);
+ if (!fs.existsSync(binaryPath)) {
+ console.warn(`⚠ Binary not found at ${binaryPath}`);
+ console.warn('Tests will skip binary execution. Build the Go binary and place it at:');
+ console.warn(` ${binaryPath}`);
+ }
+ pinch = new index_1.default({ port: testPort });
+ });
+ (0, node_test_1.after)(async () => {
+ // Clean up: stop server if running
+ try {
+ await pinch.stop();
+ }
+ catch (e) {
+ // Ignore
+ }
+ });
+ (0, node_test_1.test)('should import Pinchtab class', () => {
+ assert.ok(typeof index_1.default === 'function');
+ assert.ok(pinch instanceof index_1.default);
+ });
+ (0, node_test_1.test)('should initialize with default options', () => {
+ const client = new index_1.default();
+ assert.ok(client);
+ });
+ (0, node_test_1.test)('should initialize with custom port', () => {
+ const client = new index_1.default({ port: 9999 });
+ assert.ok(client);
+ });
+ (0, node_test_1.test)('should have API methods defined', () => {
+ assert.strictEqual(typeof pinch.start, 'function');
+ assert.strictEqual(typeof pinch.stop, 'function');
+ assert.strictEqual(typeof pinch.snapshot, 'function');
+ assert.strictEqual(typeof pinch.click, 'function');
+ assert.strictEqual(typeof pinch.lock, 'function');
+ assert.strictEqual(typeof pinch.unlock, 'function');
+ assert.strictEqual(typeof pinch.createTab, 'function');
+ });
+ (0, node_test_1.test)('should start server (requires binary)', async () => {
+ const client = new index_1.default({ port: testPort });
+ try {
+ await client.start();
+ // Give server a moment to be ready
+ await new Promise(r => setTimeout(r, 1000));
+ // Try a simple health check
+ const response = await fetch(`http://localhost:${testPort}/`);
+ assert.ok(response.status !== undefined);
+ await client.stop();
+ }
+ catch (err) {
+ const errorMsg = err.message;
+ if (errorMsg.includes('ENOENT') || errorMsg.includes('not found')) {
+ console.log('⊘ Binary not available — skipping start test');
+ }
+ else {
+ throw err;
+ }
+ }
+ });
+ (0, node_test_1.test)('should handle missing binary gracefully', async () => {
+ const client = new index_1.default({ port: 9998 });
+ try {
+ await client.start('/nonexistent/path/to/binary');
+ // If we get here, the binary exists (unusual test environment)
+ }
+ catch (err) {
+ assert.ok(err instanceof Error);
+ assert.ok(err.message.includes('Failed to start') ||
+ err.message.includes('ENOENT'));
+ }
+ });
+ (0, node_test_1.test)('should reject invalid request to non-running server', async () => {
+ const client = new index_1.default({ port: 9997 });
+ try {
+ await client.snapshot();
+ // Should not reach here
+ assert.fail('Expected connection error');
+ }
+ catch (err) {
+ // Expected — server not running
+ assert.ok(err instanceof Error);
+ }
+ });
+});
diff --git a/npm/tests/integration.test.ts b/npm/tests/integration.test.ts
new file mode 100644
index 00000000..a8604811
--- /dev/null
+++ b/npm/tests/integration.test.ts
@@ -0,0 +1,113 @@
+import { test, describe, before, after } from 'node:test';
+import * as assert from 'node:assert';
+import Pinchtab from '../src/index';
+import * as fs from 'fs';
+import * as path from 'path';
+import * as os from 'os';
+
+describe('Pinchtab npm Integration Tests', () => {
+ let pinch: Pinchtab;
+ const testPort = 9867;
+
+ before(async () => {
+ // Check if binary exists before running tests
+ const binDir = path.join(os.homedir(), '.pinchtab', 'bin');
+ const platform = process.platform === 'darwin' ? 'darwin' : process.platform === 'linux' ? 'linux' : 'windows';
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
+ const ext = platform === 'windows' ? '.exe' : '';
+ const binaryPath = path.join(binDir, `pinchtab-${platform}-${arch}${ext}`);
+
+ if (!fs.existsSync(binaryPath)) {
+ console.warn(`⚠ Binary not found at ${binaryPath}`);
+ console.warn('Tests will skip binary execution. Build the Go binary and place it at:');
+ console.warn(` ${binaryPath}`);
+ }
+
+ pinch = new Pinchtab({ port: testPort });
+ });
+
+ after(async () => {
+ // Clean up: stop server if running
+ try {
+ await pinch.stop();
+ } catch (e) {
+ // Ignore
+ }
+ });
+
+ test('should import Pinchtab class', () => {
+ assert.ok(typeof Pinchtab === 'function');
+ assert.ok(pinch instanceof Pinchtab);
+ });
+
+ test('should initialize with default options', () => {
+ const client = new Pinchtab();
+ assert.ok(client);
+ });
+
+ test('should initialize with custom port', () => {
+ const client = new Pinchtab({ port: 9999 });
+ assert.ok(client);
+ });
+
+ test('should have API methods defined', () => {
+ assert.strictEqual(typeof pinch.start, 'function');
+ assert.strictEqual(typeof pinch.stop, 'function');
+ assert.strictEqual(typeof pinch.snapshot, 'function');
+ assert.strictEqual(typeof pinch.click, 'function');
+ assert.strictEqual(typeof pinch.lock, 'function');
+ assert.strictEqual(typeof pinch.unlock, 'function');
+ assert.strictEqual(typeof pinch.createTab, 'function');
+ });
+
+ test('should start server (requires binary)', async () => {
+ const client = new Pinchtab({ port: testPort });
+
+ try {
+ await client.start();
+ // Give server a moment to be ready
+ await new Promise(r => setTimeout(r, 1000));
+
+ // Try a simple health check
+ const response = await fetch(`http://localhost:${testPort}/`);
+ assert.ok(response.status !== undefined);
+
+ await client.stop();
+ } catch (err) {
+ const errorMsg = (err as Error).message;
+ if (errorMsg.includes('ENOENT') || errorMsg.includes('not found')) {
+ console.log('⊘ Binary not available — skipping start test');
+ } else {
+ throw err;
+ }
+ }
+ });
+
+ test('should handle missing binary gracefully', async () => {
+ const client = new Pinchtab({ port: 9998 });
+
+ try {
+ await client.start('/nonexistent/path/to/binary');
+ // If we get here, the binary exists (unusual test environment)
+ } catch (err) {
+ assert.ok(err instanceof Error);
+ assert.ok(
+ (err as Error).message.includes('Failed to start') ||
+ (err as Error).message.includes('ENOENT')
+ );
+ }
+ });
+
+ test('should reject invalid request to non-running server', async () => {
+ const client = new Pinchtab({ port: 9997 });
+
+ try {
+ await client.snapshot();
+ // Should not reach here
+ assert.fail('Expected connection error');
+ } catch (err) {
+ // Expected — server not running
+ assert.ok(err instanceof Error);
+ }
+ });
+});
diff --git a/npm/tsconfig.json b/npm/tsconfig.json
new file mode 100644
index 00000000..99ffe173
--- /dev/null
+++ b/npm/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "commonjs",
+ "lib": ["ES2020"],
+ "declaration": true,
+ "outDir": "./dist",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src/**/*", "tests/**/*"],
+ "exclude": ["node_modules"]
+}