File size: 9,438 Bytes
97ec0e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { spawn } from 'child_process';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

class antigravityRequester {
    constructor(options = {}) {
        this.binPath = options.binPath;
        this.executablePath = options.executablePath || this._getExecutablePath();
        this.proc = null;
        this.requestId = 0;
        this.pendingRequests = new Map();
        this.buffer = '';
        this.writeQueue = Promise.resolve();
    }

    _getExecutablePath() {
        const platform = os.platform();
        const arch = os.arch();
        
        let filename;
        if (platform === 'win32') {
            filename = 'antigravity_requester_windows_amd64.exe';
        } else if (platform === 'android') {
            filename = 'antigravity_requester_android_arm64';
        } else if (platform === 'linux') {
            filename = 'antigravity_requester_linux_amd64';
        } else {
            throw new Error(`Unsupported platform: ${platform}`);
        }
        
        const binPath = this.binPath || path.join(__dirname, 'bin');
        const requester_execPath = path.join(binPath, filename);
        // 设置执行权限(非Windows平台)
        if (platform !== 'win32') {
            try {
                fs.chmodSync(requester_execPath, 0o755);
            } catch (error) {
                console.warn(`Could not set executable permissions: ${error.message}`);
            }
        }
        return requester_execPath;
    }

    _ensureProcess() {
        if (this.proc) return;

        this.proc = spawn(this.executablePath, [], {
            stdio: ['pipe', 'pipe', 'pipe']
        });

        // 设置 stdin 为非阻塞模式
        if (this.proc.stdin.setDefaultEncoding) {
            this.proc.stdin.setDefaultEncoding('utf8');
        }

        // 增大 stdout 缓冲区以减少背压
        if (this.proc.stdout.setEncoding) {
            this.proc.stdout.setEncoding('utf8');
        }
        
        // 使用 setImmediate 异步处理数据,避免阻塞
        this.proc.stdout.on('data', (data) => {
            this.buffer += data.toString();
            
            // 使用 setImmediate 异步处理,避免阻塞 stdout 读取
            setImmediate(() => {
                const lines = this.buffer.split('\n');
                this.buffer = lines.pop();

                for (const line of lines) {
                    if (!line.trim()) continue;
                    try {
                        const response = JSON.parse(line);
                        const pending = this.pendingRequests.get(response.id);
                        if (!pending) continue;

                        if (pending.streamResponse) {
                            pending.streamResponse._handleChunk(response);
                            if (response.type === 'end' || response.type === 'error') {
                                this.pendingRequests.delete(response.id);
                            }
                        } else {
                            this.pendingRequests.delete(response.id);
                            if (response.ok) {
                                pending.resolve(new antigravityResponse(response));
                            } else {
                                pending.reject(new Error(response.error || 'Request failed'));
                            }
                        }
                    } catch (e) {
                        console.error('Failed to parse response:', e, 'Line:', line);
                    }
                }
            });
        });

        this.proc.stderr.on('data', (data) => {
            console.error('antigravityRequester stderr:', data.toString());
        });

        this.proc.on('close', () => {
            this.proc = null;
            for (const [id, pending] of this.pendingRequests) {
                if (pending.reject) {
                    pending.reject(new Error('Process closed'));
                } else if (pending.streamResponse && pending.streamResponse._onError) {
                    pending.streamResponse._onError(new Error('Process closed'));
                }
            }
            this.pendingRequests.clear();
        });
    }

    async antigravity_fetch(url, options = {}) {
        this._ensureProcess();

        const id = `req-${++this.requestId}`;
        const request = {
            id,
            url,
            method: options.method || 'GET',
            headers: options.headers,
            body: options.body,
            timeout_ms: options.timeout || 30000,
            proxy: options.proxy,
            response_format: 'text',
            ...options
        };

        return new Promise((resolve, reject) => {
            this.pendingRequests.set(id, { resolve, reject });
            this._writeRequest(request);
        });
    }

    antigravity_fetchStream(url, options = {}) {
        this._ensureProcess();

        const id = `req-${++this.requestId}`;
        const request = {
            id,
            url,
            method: options.method || 'GET',
            headers: options.headers,
            body: options.body,
            timeout_ms: options.timeout || 30000,
            proxy: options.proxy,
            stream: true,
            ...options
        };

        const streamResponse = new StreamResponse(id);
        this.pendingRequests.set(id, { streamResponse });
        this._writeRequest(request);
        
        return streamResponse;
    }

    _writeRequest(request) {
        this.writeQueue = this.writeQueue.then(() => {
            return new Promise((resolve, reject) => {
                const data = JSON.stringify(request) + '\n';
                const canWrite = this.proc.stdin.write(data);
                if (canWrite) {
                    resolve();
                } else {
                    // 等待 drain 事件
                    this.proc.stdin.once('drain', resolve);
                    this.proc.stdin.once('error', reject);
                }
            });
        }).catch(err => {
            console.error('Write request failed:', err);
        });
    }

    close() {
        if (this.proc) {
            this.proc.stdin.end();
            this.proc = null;
        }
    }
}

class StreamResponse {
    constructor(id) {
        this.id = id;
        this.status = null;
        this.statusText = null;
        this.headers = null;
        this.chunks = [];
        this._onStart = null;
        this._onData = null;
        this._onEnd = null;
        this._onError = null;
        this._ended = false;
        this._error = null;
        this._textPromiseResolve = null;
        this._textPromiseReject = null;
    }

    _handleChunk(chunk) {
        if (chunk.type === 'start') {
            this.status = chunk.status;
            this.headers = new Map(Object.entries(chunk.headers || {}));
            if (this._onStart) this._onStart({ status: chunk.status, headers: this.headers });
        } else if (chunk.type === 'data') {
            const data = chunk.encoding === 'base64' 
                ? Buffer.from(chunk.data, 'base64').toString('utf8')
                : chunk.data;
            this.chunks.push(data);
            if (this._onData) this._onData(data);
        } else if (chunk.type === 'end') {
            this._ended = true;
            if (this._textPromiseResolve) this._textPromiseResolve(this.chunks.join(''));
            if (this._onEnd) this._onEnd();
        } else if (chunk.type === 'error') {
            this._ended = true;
            this._error = new Error(chunk.error);
            if (this._textPromiseReject) this._textPromiseReject(this._error);
            if (this._onError) this._onError(this._error);
        }
    }

    onStart(callback) {
        this._onStart = callback;
        return this;
    }

    onData(callback) {
        this._onData = callback;
        return this;
    }

    onEnd(callback) {
        this._onEnd = callback;
        return this;
    }

    onError(callback) {
        this._onError = callback;
        return this;
    }

    async text() {
        if (this._ended) {
            if (this._error) throw this._error;
            return this.chunks.join('');
        }
        return new Promise((resolve, reject) => {
            this._textPromiseResolve = resolve;
            this._textPromiseReject = reject;
        });
    }
}

class antigravityResponse {
    constructor(response) {
        this._response = response;
        this.ok = response.ok;
        this.status = response.status;
        this.statusText = response.status_text;
        this.url = response.url;
        this.headers = new Map(Object.entries(response.headers || {}));
        this.redirected = response.redirected;
    }

    async text() {
        if (this._response.body_encoding === 'base64') {
            return Buffer.from(this._response.body, 'base64').toString('utf8');
        }
        return this._response.body;
    }

    async json() {
        const text = await this.text();
        return JSON.parse(text);
    }

    async buffer() {
        if (this._response.body_encoding === 'base64') {
            return Buffer.from(this._response.body, 'base64');
        }
        return Buffer.from(this._response.body, 'utf8');
    }
}

export default antigravityRequester;