File size: 4,088 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { spawn, ChildProcess } from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import { detectPlatform, getBinaryName, getBinaryPath } from './platform';
import {
  SnapshotParams,
  SnapshotResponse,
  TabClickParams,
  TabLockParams,
  TabUnlockParams,
  CreateTabParams,
  CreateTabResponse,
  PinchtabOptions,
} from './types';

export * from './types';
export * from './platform';

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.getBinaryPathInternal();
    }

    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
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  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 AbortSignal,
      });

      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 getBinaryPathInternal(): Promise<string> {
    const platform = detectPlatform();
    const binaryName = getBinaryName(platform);

    // Try version-specific path first
    const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
    const binaryPath = getBinaryPath(binaryName, pkg.version);

    if (!fs.existsSync(binaryPath)) {
      throw new Error(
        `Pinchtab binary not found at ${binaryPath}.\n` +
          `Please run: npm rebuild pinchtab\n` +
          `Or set PINCHTAB_BINARY_PATH=/path/to/binary`
      );
    }

    return binaryPath;
  }
}

export default Pinchtab;