glidercli 0.4.6 → 0.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -15
- package/bin/glider.js +1576 -415
- package/docs/setup.json +13 -10
- package/lib/bcdp.js +8 -3
- package/lib/beval.js +2 -1
- package/lib/bexplore.js +9 -3
- package/lib/bextract.js +4 -2
- package/lib/bfavicon.js +2 -1
- package/lib/bfetch.js +9 -4
- package/lib/browser-config.js +94 -0
- package/lib/bserve.js +242 -127
- package/lib/bspawn.js +4 -2
- package/lib/bwindow.js +8 -3
- package/lib/glider-daemon.sh +334 -46
- package/lib/guard.js +7 -4
- package/lib/relay-config.js +24 -0
- package/package.json +10 -5
package/bin/glider.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* - Checkpointing and state persistence
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
const { spawn, execSync, exec } = require('child_process');
|
|
24
|
+
const { spawn, execFileSync, execSync, exec } = require('child_process');
|
|
25
25
|
const path = require('path');
|
|
26
26
|
const fs = require('fs');
|
|
27
27
|
const os = require('os');
|
|
@@ -30,22 +30,40 @@ const WebSocket = require('ws');
|
|
|
30
30
|
const YAML = require('yaml');
|
|
31
31
|
|
|
32
32
|
// Config
|
|
33
|
-
const
|
|
33
|
+
const { relayPort } = require('../lib/relay-config.js');
|
|
34
34
|
const DEBUG_PORT = process.env.GLIDER_DEBUG_PORT || 9222;
|
|
35
|
-
const SERVER_URL = `http://127.0.0.1:${PORT}`;
|
|
36
35
|
const DEBUG_URL = `http://127.0.0.1:${DEBUG_PORT}`;
|
|
37
36
|
const LIB_DIR = path.join(__dirname, '..', 'lib');
|
|
38
37
|
const STATE_FILE = '/tmp/glider-state.json';
|
|
39
|
-
const LOG_FILE = '/tmp/glider.log';
|
|
40
38
|
const REGISTRY_FILE = path.join(LIB_DIR, 'registry.json');
|
|
41
39
|
|
|
42
40
|
// Active CDP session (multi-tab). Env or --session / --session-id on CLI.
|
|
43
41
|
let activeSessionId = process.env.GLIDER_SESSION_ID || null;
|
|
44
42
|
let jsonOutput = false;
|
|
45
43
|
let allowedDomainList = null;
|
|
46
|
-
const
|
|
44
|
+
const { configPath, gliderHome } = require(path.join(LIB_DIR, 'paths.js'));
|
|
45
|
+
const { isBrowserInternalUrl, loadBrowserConfig } = require(path.join(LIB_DIR, 'browser-config.js'));
|
|
46
|
+
const GLIDER_HOME = gliderHome();
|
|
47
|
+
const LOG_FILE = path.join(GLIDER_HOME, 'relay.log');
|
|
48
|
+
const SESSION_STORE = path.join(GLIDER_HOME, 'config', 'active-session.json');
|
|
47
49
|
const { resolveAllowedDomains, assertUrlAllowed, urlAllowed } = require(path.join(LIB_DIR, 'guard.js'));
|
|
48
50
|
const { buildSnapshotExpression, formatSnapshotText } = require(path.join(LIB_DIR, 'bsnapshot.js'));
|
|
51
|
+
let PORT = null;
|
|
52
|
+
let SERVER_URL = null;
|
|
53
|
+
let relayConfigError = null;
|
|
54
|
+
try {
|
|
55
|
+
PORT = relayPort();
|
|
56
|
+
SERVER_URL = `http://127.0.0.1:${PORT}`;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
relayConfigError = error;
|
|
59
|
+
}
|
|
60
|
+
const RELAY_ENTRY = path.join(LIB_DIR, 'bserve.js');
|
|
61
|
+
const RELAY_PID_FILE = PORT === null ? null : path.join(GLIDER_HOME, `relay-${PORT}.pid`);
|
|
62
|
+
const RELAY_START_LOCK = PORT === null ? null : path.join(GLIDER_HOME, `relay-${PORT}.lifecycle.lock`);
|
|
63
|
+
const DAEMON_ENTRY = path.join(LIB_DIR, 'glider-daemon.sh');
|
|
64
|
+
const DAEMON_PID_FILE = PORT === null ? null : path.join(GLIDER_HOME, `daemon-${PORT}.pid`);
|
|
65
|
+
const DAEMON_CLAIM_DIR = PORT === null ? null : path.join(GLIDER_HOME, `daemon-${PORT}.claim`);
|
|
66
|
+
const DAEMON_MANAGEMENT_LOCK = PORT === null ? null : path.join(GLIDER_HOME, `daemon-${PORT}.management.lock`);
|
|
49
67
|
|
|
50
68
|
// Load pattern registry
|
|
51
69
|
let REGISTRY = {};
|
|
@@ -60,10 +78,7 @@ const { DirectCDP, checkChrome } = require(path.join(LIB_DIR, 'cdp-direct.js'));
|
|
|
60
78
|
const { resolveDomain } = require(path.join(LIB_DIR, 'domain-resolve.js'));
|
|
61
79
|
|
|
62
80
|
// Domain extensions - load from ~/.glider/config/domains.json
|
|
63
|
-
const DOMAIN_CONFIG_PATHS =
|
|
64
|
-
path.join(os.homedir(), '.glider', 'config', 'domains.json'),
|
|
65
|
-
path.join(os.homedir(), '.glider', 'domains.json'),
|
|
66
|
-
];
|
|
81
|
+
const DOMAIN_CONFIG_PATHS = configPath('domains.json');
|
|
67
82
|
let DOMAINS = {};
|
|
68
83
|
for (const cfgPath of DOMAIN_CONFIG_PATHS) {
|
|
69
84
|
if (fs.existsSync(cfgPath)) {
|
|
@@ -74,52 +89,8 @@ for (const cfgPath of DOMAIN_CONFIG_PATHS) {
|
|
|
74
89
|
}
|
|
75
90
|
}
|
|
76
91
|
|
|
77
|
-
// Browser config- which browser to launch/use (must be Chromium-based, see README.md#Browsers)
|
|
78
|
-
const BROWSER_CONFIG_PATHS = [
|
|
79
|
-
path.join(os.homedir(), '.glider', 'config', 'browser.json'),
|
|
80
|
-
path.join(os.homedir(), '.glider', 'browser.json'),
|
|
81
|
-
];
|
|
82
|
-
let BROWSER_CONFIG = {};
|
|
83
|
-
for (const cfgPath of BROWSER_CONFIG_PATHS) {
|
|
84
|
-
if (fs.existsSync(cfgPath)) {
|
|
85
|
-
try {
|
|
86
|
-
BROWSER_CONFIG = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
|
|
87
|
-
break;
|
|
88
|
-
} catch (e) { /* ignore parse errors */ }
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Browsers registry - key → { name, path, processName }. Used when browser.json has "use": "<key>"
|
|
93
|
-
const BROWSERS_REGISTRY_PATHS = [
|
|
94
|
-
path.join(os.homedir(), '.glider', 'config', 'browsers-registry.json'),
|
|
95
|
-
].filter(Boolean);
|
|
96
|
-
let BROWSERS_REGISTRY = {};
|
|
97
|
-
for (const regPath of BROWSERS_REGISTRY_PATHS) {
|
|
98
|
-
if (regPath && fs.existsSync(regPath)) {
|
|
99
|
-
try {
|
|
100
|
-
const data = JSON.parse(fs.readFileSync(regPath, 'utf8'));
|
|
101
|
-
BROWSERS_REGISTRY = data.registry || data;
|
|
102
|
-
break;
|
|
103
|
-
} catch (e) { /* ignore */ }
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
92
|
function getBrowserConfig() {
|
|
108
|
-
|
|
109
|
-
let pathOrNull = BROWSER_CONFIG.path || null;
|
|
110
|
-
let processName = BROWSER_CONFIG.processName || null;
|
|
111
|
-
|
|
112
|
-
// Key-based lookup: browser.json has { "use": "arc" } → resolve from registry
|
|
113
|
-
if (!name && BROWSER_CONFIG.use && BROWSERS_REGISTRY[BROWSER_CONFIG.use]) {
|
|
114
|
-
const entry = BROWSERS_REGISTRY[BROWSER_CONFIG.use];
|
|
115
|
-
name = entry.name;
|
|
116
|
-
pathOrNull = entry.path != null ? entry.path : null;
|
|
117
|
-
processName = entry.processName || entry.name;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
name = name || 'Google Chrome';
|
|
121
|
-
processName = processName || name;
|
|
122
|
-
return { name, path: pathOrNull, processName };
|
|
93
|
+
return loadBrowserConfig({ home: GLIDER_HOME });
|
|
123
94
|
}
|
|
124
95
|
|
|
125
96
|
// Colors - matching the deep blue gradient logo
|
|
@@ -179,6 +150,292 @@ const log = {
|
|
|
179
150
|
},
|
|
180
151
|
};
|
|
181
152
|
|
|
153
|
+
function getProcessIdentity(pid) {
|
|
154
|
+
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
155
|
+
try {
|
|
156
|
+
process.kill(pid, 0);
|
|
157
|
+
const identityEnv = {
|
|
158
|
+
...process.env,
|
|
159
|
+
LC_ALL: 'C',
|
|
160
|
+
LANG: 'C',
|
|
161
|
+
TZ: 'UTC',
|
|
162
|
+
};
|
|
163
|
+
const command = execFileSync('ps', ['-p', String(pid), '-o', 'command='], {
|
|
164
|
+
encoding: 'utf8',
|
|
165
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
166
|
+
env: identityEnv,
|
|
167
|
+
}).trim();
|
|
168
|
+
const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
|
|
169
|
+
encoding: 'utf8',
|
|
170
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
171
|
+
env: identityEnv,
|
|
172
|
+
}).trim();
|
|
173
|
+
if (!command || !started) return null;
|
|
174
|
+
return { command, started };
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function commandIncludesPath(command, expectedPath) {
|
|
181
|
+
if (!command || !expectedPath) return false;
|
|
182
|
+
const resolved = fs.realpathSync(expectedPath);
|
|
183
|
+
return command.includes(expectedPath) || command.includes(resolved);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function readRelayPidRecord(filePath) {
|
|
187
|
+
try {
|
|
188
|
+
const record = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
189
|
+
if (record?.schema !== 1 || !Number.isInteger(record.pid) || record.pid <= 0) return null;
|
|
190
|
+
return record;
|
|
191
|
+
} catch {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function relayPidRecordMatches(record, identity) {
|
|
197
|
+
return Boolean(
|
|
198
|
+
record
|
|
199
|
+
&& identity
|
|
200
|
+
&& record.port === PORT
|
|
201
|
+
&& record.entry === fs.realpathSync(RELAY_ENTRY)
|
|
202
|
+
&& record.started === identity.started
|
|
203
|
+
&& commandIncludesPath(identity.command, RELAY_ENTRY)
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function writeRelayPidRecord(record) {
|
|
208
|
+
const temp = `${RELAY_PID_FILE}.${process.pid}.${record.pid}.tmp`;
|
|
209
|
+
fs.writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
|
|
210
|
+
fs.renameSync(temp, RELAY_PID_FILE);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function removeRelayPidRecordIfOwned(pid, started) {
|
|
214
|
+
const current = readRelayPidRecord(RELAY_PID_FILE);
|
|
215
|
+
if (current?.pid === pid && current.started === started) {
|
|
216
|
+
fs.unlinkSync(RELAY_PID_FILE);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function readProcessLock(filePath) {
|
|
221
|
+
try {
|
|
222
|
+
const record = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
223
|
+
if (record?.schema !== 1 || !Number.isInteger(record.pid) || record.pid <= 0) return null;
|
|
224
|
+
return record;
|
|
225
|
+
} catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function processLockIsLive(record) {
|
|
231
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
232
|
+
return Boolean(
|
|
233
|
+
identity
|
|
234
|
+
&& record.started === identity.started
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function acquireProcessLock(filePath, label, timeoutMs = 7000) {
|
|
239
|
+
const identity = getProcessIdentity(process.pid);
|
|
240
|
+
if (!identity) throw new Error(`Could not verify ${label} lock owner`);
|
|
241
|
+
const record = {
|
|
242
|
+
schema: 1,
|
|
243
|
+
pid: process.pid,
|
|
244
|
+
entry: fs.realpathSync(__filename),
|
|
245
|
+
started: identity.started,
|
|
246
|
+
};
|
|
247
|
+
const deadline = Date.now() + timeoutMs;
|
|
248
|
+
while (Date.now() < deadline) {
|
|
249
|
+
try {
|
|
250
|
+
const fd = fs.openSync(filePath, 'wx', 0o600);
|
|
251
|
+
try {
|
|
252
|
+
fs.writeFileSync(fd, `${JSON.stringify(record, null, 2)}\n`);
|
|
253
|
+
} finally {
|
|
254
|
+
fs.closeSync(fd);
|
|
255
|
+
}
|
|
256
|
+
return record;
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (error.code !== 'EEXIST') throw error;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const existing = readProcessLock(filePath);
|
|
262
|
+
if (!processLockIsLive(existing)) {
|
|
263
|
+
try {
|
|
264
|
+
const ageMs = Date.now() - fs.statSync(filePath).mtimeMs;
|
|
265
|
+
if (ageMs < 2000) {
|
|
266
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.code === 'ENOENT') continue;
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
throw new Error(`Stale ${label} lock requires manual removal: ${filePath}`);
|
|
274
|
+
}
|
|
275
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
276
|
+
}
|
|
277
|
+
throw new Error(`Timed out waiting for ${label} lock: ${filePath}`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function releaseProcessLock(filePath, record) {
|
|
281
|
+
const current = readProcessLock(filePath);
|
|
282
|
+
if (current?.pid === record?.pid && current.started === record.started) {
|
|
283
|
+
fs.unlinkSync(filePath);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function acquireRelayStartLock() {
|
|
288
|
+
return acquireProcessLock(RELAY_START_LOCK, 'relay lifecycle');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function releaseRelayStartLock(record) {
|
|
292
|
+
releaseProcessLock(RELAY_START_LOCK, record);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function acquireDaemonManagementLock() {
|
|
296
|
+
return acquireProcessLock(DAEMON_MANAGEMENT_LOCK, 'daemon management');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function releaseDaemonManagementLock(record) {
|
|
300
|
+
releaseProcessLock(DAEMON_MANAGEMENT_LOCK, record);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function acquireStandaloneRelayLocks() {
|
|
304
|
+
const daemonManagement = await acquireDaemonManagementLock();
|
|
305
|
+
try {
|
|
306
|
+
return {
|
|
307
|
+
daemonManagement,
|
|
308
|
+
relayLifecycle: await acquireRelayStartLock(),
|
|
309
|
+
};
|
|
310
|
+
} catch (error) {
|
|
311
|
+
releaseDaemonManagementLock(daemonManagement);
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function releaseStandaloneRelayLocks(locks) {
|
|
317
|
+
try {
|
|
318
|
+
releaseRelayStartLock(locks.relayLifecycle);
|
|
319
|
+
} finally {
|
|
320
|
+
releaseDaemonManagementLock(locks.daemonManagement);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function readDaemonPidRecord(filePath) {
|
|
325
|
+
try {
|
|
326
|
+
const record = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
327
|
+
if (
|
|
328
|
+
record?.schema !== 1
|
|
329
|
+
|| !Number.isInteger(record.pid)
|
|
330
|
+
|| record.pid <= 0
|
|
331
|
+
|| !Number.isInteger(record.port)
|
|
332
|
+
) return null;
|
|
333
|
+
return record;
|
|
334
|
+
} catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function daemonSupervisorMatches(record, identity, daemonScript) {
|
|
340
|
+
return Boolean(
|
|
341
|
+
record
|
|
342
|
+
&& identity
|
|
343
|
+
&& record.port === PORT
|
|
344
|
+
&& record.entry === fs.realpathSync(daemonScript)
|
|
345
|
+
&& record.started === identity.started
|
|
346
|
+
&& commandIncludesPath(identity.command, daemonScript)
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function daemonChildMatches(record) {
|
|
351
|
+
if (!Number.isInteger(record?.childPid) || record.childPid <= 0 || !record.childStarted) {
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
const identity = getProcessIdentity(record.childPid);
|
|
355
|
+
return Boolean(
|
|
356
|
+
identity
|
|
357
|
+
&& record.childEntry === fs.realpathSync(RELAY_ENTRY)
|
|
358
|
+
&& record.childStarted === identity.started
|
|
359
|
+
&& commandIncludesPath(identity.command, RELAY_ENTRY)
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function inspectDaemonOwnership() {
|
|
364
|
+
const recordExists = fs.existsSync(DAEMON_PID_FILE);
|
|
365
|
+
const claimExists = fs.existsSync(DAEMON_CLAIM_DIR);
|
|
366
|
+
if (!recordExists && !claimExists) return { state: 'absent', record: null };
|
|
367
|
+
|
|
368
|
+
const record = recordExists ? readDaemonPidRecord(DAEMON_PID_FILE) : null;
|
|
369
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
370
|
+
if (claimExists && daemonSupervisorMatches(record, identity, DAEMON_ENTRY)) {
|
|
371
|
+
return { state: 'owned', record };
|
|
372
|
+
}
|
|
373
|
+
return { state: 'unverified', record };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function assertStandaloneRelayAllowed(ownership = inspectDaemonOwnership()) {
|
|
377
|
+
if (ownership.state === 'owned') {
|
|
378
|
+
throw new Error(
|
|
379
|
+
`Relay port ${PORT} is managed by daemon PID ${ownership.record.pid}; use glider uninstall to stop the supervisor`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
if (ownership.state === 'unverified') {
|
|
383
|
+
throw new Error(
|
|
384
|
+
`Refusing standalone relay lifecycle while daemon ownership is unverified: ${DAEMON_PID_FILE}`,
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function removeDaemonPidRecordIfOwned(filePath, record) {
|
|
390
|
+
const current = readDaemonPidRecord(filePath);
|
|
391
|
+
if (
|
|
392
|
+
current
|
|
393
|
+
&& record
|
|
394
|
+
&& current.pid === record.pid
|
|
395
|
+
&& current.port === record.port
|
|
396
|
+
&& current.entry === record.entry
|
|
397
|
+
&& current.started === record.started
|
|
398
|
+
) {
|
|
399
|
+
fs.unlinkSync(filePath);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function inspectLegacyDaemonRecord(filePath, daemonScript) {
|
|
404
|
+
if (!fs.existsSync(filePath)) return { state: 'absent', pid: null };
|
|
405
|
+
let pid = null;
|
|
406
|
+
try {
|
|
407
|
+
pid = Number.parseInt(fs.readFileSync(filePath, 'utf8').trim(), 10);
|
|
408
|
+
} catch {}
|
|
409
|
+
if (!Number.isInteger(pid) || pid <= 0) return { state: 'stale', pid: null };
|
|
410
|
+
const identity = getProcessIdentity(pid);
|
|
411
|
+
if (!identity || !commandIncludesPath(identity.command, daemonScript)) {
|
|
412
|
+
return { state: 'stale', pid };
|
|
413
|
+
}
|
|
414
|
+
return { state: 'live-unverified', pid };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async function waitForProcessExit(pid, timeoutMs = 3000) {
|
|
418
|
+
const deadline = Date.now() + timeoutMs;
|
|
419
|
+
while (Date.now() < deadline) {
|
|
420
|
+
try {
|
|
421
|
+
process.kill(pid, 0);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error.code === 'ESRCH') return true;
|
|
424
|
+
throw error;
|
|
425
|
+
}
|
|
426
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
427
|
+
}
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function emitCommandFailure(message, exitCode = 1) {
|
|
432
|
+
if (jsonOutput) {
|
|
433
|
+
console.log(JSON.stringify({ ok: false, observation: null, error: message, warnings: [] }, null, 2));
|
|
434
|
+
}
|
|
435
|
+
log.fail(message);
|
|
436
|
+
process.exitCode = exitCode;
|
|
437
|
+
}
|
|
438
|
+
|
|
182
439
|
// macOS notification helper
|
|
183
440
|
function notify(title, message, sound = false) {
|
|
184
441
|
try {
|
|
@@ -189,19 +446,28 @@ function notify(title, message, sound = false) {
|
|
|
189
446
|
|
|
190
447
|
// HTTP helpers
|
|
191
448
|
function httpGet(urlPath) {
|
|
449
|
+
const started = Date.now();
|
|
192
450
|
return new Promise((resolve, reject) => {
|
|
193
451
|
const url = new URL(urlPath, SERVER_URL);
|
|
194
|
-
http.get(url, { timeout: 2000 }, (res) => {
|
|
452
|
+
const req = http.get(url, { timeout: 2000 }, (res) => {
|
|
195
453
|
let data = '';
|
|
196
454
|
res.on('data', chunk => data += chunk);
|
|
197
455
|
res.on('end', () => {
|
|
456
|
+
let parsed;
|
|
198
457
|
try {
|
|
199
|
-
|
|
458
|
+
parsed = data ? JSON.parse(data) : null;
|
|
200
459
|
} catch {
|
|
201
|
-
|
|
460
|
+
parsed = data;
|
|
202
461
|
}
|
|
462
|
+
const error = responseError(res, parsed, url);
|
|
463
|
+
if (error) reject(error);
|
|
464
|
+
else resolve(parsed);
|
|
203
465
|
});
|
|
204
|
-
})
|
|
466
|
+
});
|
|
467
|
+
req.on('timeout', () => req.destroy(new Error(`Request timed out: ${url.pathname}`)));
|
|
468
|
+
req.on('error', reject);
|
|
469
|
+
}).finally(() => {
|
|
470
|
+
lastHttpTiming.relay_ms = (lastHttpTiming.relay_ms || 0) + (Date.now() - started);
|
|
205
471
|
});
|
|
206
472
|
}
|
|
207
473
|
|
|
@@ -214,17 +480,55 @@ function loadPersistedSession() {
|
|
|
214
480
|
} catch { /* ignore */ }
|
|
215
481
|
}
|
|
216
482
|
|
|
483
|
+
function clearPersistedSession() {
|
|
484
|
+
activeSessionId = null;
|
|
485
|
+
try { if (fs.existsSync(SESSION_STORE)) fs.unlinkSync(SESSION_STORE); } catch { /* ignore */ }
|
|
486
|
+
}
|
|
487
|
+
|
|
217
488
|
function persistSession(sessionId) {
|
|
218
489
|
activeSessionId = sessionId;
|
|
219
490
|
fs.mkdirSync(path.dirname(SESSION_STORE), { recursive: true });
|
|
220
491
|
fs.writeFileSync(SESSION_STORE, JSON.stringify({ sessionId, updated: new Date().toISOString() }, null, 2));
|
|
221
492
|
}
|
|
222
493
|
|
|
494
|
+
const lastHttpTiming = { relay_ms: 0, cdp_ms: 0 };
|
|
495
|
+
let commandStartedAt = 0;
|
|
496
|
+
|
|
497
|
+
function resetCommandTiming() {
|
|
498
|
+
lastHttpTiming.relay_ms = 0;
|
|
499
|
+
lastHttpTiming.cdp_ms = 0;
|
|
500
|
+
commandStartedAt = Date.now();
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function timingFields() {
|
|
504
|
+
if (process.env.GLIDER_TIMING !== '1') return null;
|
|
505
|
+
return {
|
|
506
|
+
relay_ms: lastHttpTiming.relay_ms,
|
|
507
|
+
cdp_ms: lastHttpTiming.cdp_ms,
|
|
508
|
+
total_ms: Date.now() - (commandStartedAt || Date.now()),
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
223
512
|
function emitJson(ok, observation, error = null, warnings = []) {
|
|
224
|
-
|
|
513
|
+
const timing = timingFields();
|
|
514
|
+
const payload = { ok, observation, error, warnings };
|
|
515
|
+
if (timing) payload.timing = timing;
|
|
516
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
225
517
|
if (!ok) process.exit(1);
|
|
226
518
|
}
|
|
227
519
|
|
|
520
|
+
function failUnsupported(capability, detail) {
|
|
521
|
+
const message = `${capability} is not fully implemented: ${detail}`;
|
|
522
|
+
if (jsonOutput) {
|
|
523
|
+
const timing = timingFields();
|
|
524
|
+
const payload = { ok: false, observation: null, error: message, warnings: [] };
|
|
525
|
+
if (timing) payload.timing = timing;
|
|
526
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
527
|
+
}
|
|
528
|
+
log.fail(message);
|
|
529
|
+
process.exit(2);
|
|
530
|
+
}
|
|
531
|
+
|
|
228
532
|
async function assertCurrentUrlAllowed(action) {
|
|
229
533
|
if (!allowedDomainList) return;
|
|
230
534
|
const result = await httpPost('/cdp', {
|
|
@@ -240,11 +544,23 @@ function parseGlobalFlags(argv) {
|
|
|
240
544
|
const cliDomains = [];
|
|
241
545
|
for (let i = 0; i < argv.length; i++) {
|
|
242
546
|
const a = argv[i];
|
|
243
|
-
|
|
547
|
+
const equals = a.match(/^(--(?:session|session-id|allowed-domains))=(.*)$/);
|
|
548
|
+
if (equals) {
|
|
549
|
+
if (equals[2] === '') throw new Error(`${equals[1]} requires a value`);
|
|
550
|
+
if (equals[1] === '--allowed-domains') {
|
|
551
|
+
cliDomains.push(...equals[2].split(',').map((s) => s.trim()).filter(Boolean));
|
|
552
|
+
} else {
|
|
553
|
+
activeSessionId = equals[2];
|
|
554
|
+
}
|
|
555
|
+
} else if (a === '--session' || a === '--session-id') {
|
|
556
|
+
const value = argv[i + 1];
|
|
557
|
+
if (!value || value.startsWith('-')) throw new Error(`${a} requires a value`);
|
|
244
558
|
activeSessionId = argv[++i];
|
|
245
559
|
} else if (a === '--json') {
|
|
246
560
|
jsonOutput = true;
|
|
247
|
-
} else if (a === '--allowed-domains'
|
|
561
|
+
} else if (a === '--allowed-domains') {
|
|
562
|
+
const value = argv[i + 1];
|
|
563
|
+
if (!value || value.startsWith('-')) throw new Error('--allowed-domains requires a value');
|
|
248
564
|
cliDomains.push(...String(argv[++i]).split(',').map((s) => s.trim()).filter(Boolean));
|
|
249
565
|
} else {
|
|
250
566
|
rest.push(a);
|
|
@@ -254,11 +570,20 @@ function parseGlobalFlags(argv) {
|
|
|
254
570
|
return rest;
|
|
255
571
|
}
|
|
256
572
|
|
|
257
|
-
function
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
573
|
+
function responseError(res, body, url) {
|
|
574
|
+
if (res.statusCode >= 200 && res.statusCode < 300) return null;
|
|
575
|
+
const detail = body && typeof body === 'object'
|
|
576
|
+
? body.error?.message || body.error || body.message
|
|
577
|
+
: body;
|
|
578
|
+
return new Error(`HTTP ${res.statusCode} from ${url.pathname}${detail ? `: ${detail}` : ''}`);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function isSessionNotFoundError(error) {
|
|
582
|
+
return /Session not found/i.test(String(error?.message || error || ''));
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function httpPostRaw(urlPath, payload) {
|
|
586
|
+
const started = Date.now();
|
|
262
587
|
return new Promise((resolve, reject) => {
|
|
263
588
|
const url = new URL(urlPath, SERVER_URL);
|
|
264
589
|
const data = JSON.stringify(payload);
|
|
@@ -270,23 +595,91 @@ function httpPost(urlPath, body) {
|
|
|
270
595
|
let result = '';
|
|
271
596
|
res.on('data', chunk => result += chunk);
|
|
272
597
|
res.on('end', () => {
|
|
598
|
+
let parsed;
|
|
273
599
|
try {
|
|
274
|
-
|
|
600
|
+
parsed = result ? JSON.parse(result) : null;
|
|
275
601
|
} catch {
|
|
276
|
-
|
|
602
|
+
parsed = result;
|
|
277
603
|
}
|
|
604
|
+
const error = responseError(res, parsed, url);
|
|
605
|
+
if (error) reject(error);
|
|
606
|
+
else resolve(parsed);
|
|
278
607
|
});
|
|
279
608
|
});
|
|
609
|
+
req.on('timeout', () => req.destroy(new Error(`Request timed out: ${url.pathname}`)));
|
|
280
610
|
req.on('error', reject);
|
|
281
611
|
req.write(data);
|
|
282
612
|
req.end();
|
|
613
|
+
}).finally(() => {
|
|
614
|
+
const elapsed = Date.now() - started;
|
|
615
|
+
if (urlPath === '/cdp') lastHttpTiming.cdp_ms += elapsed;
|
|
616
|
+
else lastHttpTiming.relay_ms += elapsed;
|
|
283
617
|
});
|
|
284
618
|
}
|
|
285
619
|
|
|
620
|
+
async function pickLiveSessionId() {
|
|
621
|
+
const targets = await getTargets();
|
|
622
|
+
return targets[0]?.sessionId || null;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async function httpPost(urlPath, body) {
|
|
626
|
+
const payload = { ...body };
|
|
627
|
+
const pinned = activeSessionId;
|
|
628
|
+
if (urlPath === '/cdp' && pinned && payload.sessionId == null) {
|
|
629
|
+
payload.sessionId = pinned;
|
|
630
|
+
}
|
|
631
|
+
try {
|
|
632
|
+
return await httpPostRaw(urlPath, payload);
|
|
633
|
+
} catch (error) {
|
|
634
|
+
if (
|
|
635
|
+
urlPath === '/cdp'
|
|
636
|
+
&& pinned
|
|
637
|
+
&& payload.sessionId === pinned
|
|
638
|
+
&& isSessionNotFoundError(error)
|
|
639
|
+
) {
|
|
640
|
+
const live = await pickLiveSessionId();
|
|
641
|
+
clearPersistedSession();
|
|
642
|
+
if (live) {
|
|
643
|
+
persistSession(live);
|
|
644
|
+
const retry = { ...body, sessionId: live };
|
|
645
|
+
return httpPostRaw(urlPath, retry);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
throw error;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async function waitUntil(predicate, { timeoutMs = 5000, intervalMs = 50, label = 'condition' } = {}) {
|
|
653
|
+
const deadline = Date.now() + timeoutMs;
|
|
654
|
+
let lastError = null;
|
|
655
|
+
while (Date.now() < deadline) {
|
|
656
|
+
try {
|
|
657
|
+
if (await predicate()) return true;
|
|
658
|
+
} catch (error) {
|
|
659
|
+
lastError = error;
|
|
660
|
+
}
|
|
661
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
662
|
+
}
|
|
663
|
+
if (lastError) throw new Error(`${label} not met within ${timeoutMs}ms: ${lastError.message}`);
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
|
|
286
667
|
// Server checks
|
|
668
|
+
async function getRelayStatus() {
|
|
669
|
+
return httpGet('/status');
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function extensionReady(status) {
|
|
673
|
+
if (!status || status.extension !== true) return false;
|
|
674
|
+
if (Object.prototype.hasOwnProperty.call(status, 'extensionWorkerAlive')) {
|
|
675
|
+
return status.extensionWorkerAlive === true;
|
|
676
|
+
}
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
287
680
|
async function checkServer() {
|
|
288
681
|
try {
|
|
289
|
-
await
|
|
682
|
+
await getRelayStatus();
|
|
290
683
|
return true;
|
|
291
684
|
} catch {
|
|
292
685
|
return false;
|
|
@@ -296,7 +689,7 @@ async function checkServer() {
|
|
|
296
689
|
async function checkExtension() {
|
|
297
690
|
try {
|
|
298
691
|
const status = await httpGet('/status');
|
|
299
|
-
return status
|
|
692
|
+
return extensionReady(status);
|
|
300
693
|
} catch {
|
|
301
694
|
return false;
|
|
302
695
|
}
|
|
@@ -319,7 +712,77 @@ async function getTargets() {
|
|
|
319
712
|
}
|
|
320
713
|
}
|
|
321
714
|
|
|
322
|
-
|
|
715
|
+
function appleScriptString(value) {
|
|
716
|
+
return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// AppleScript launch/tab/activate steals focus and mutates the operator's session.
|
|
720
|
+
// Default OFF. Opt in: GLIDER_BROWSER_UI=1 (legacy: GLIDER_HEAL_NO_WAKE=0 alone is not enough).
|
|
721
|
+
function browserUiEnabled() {
|
|
722
|
+
const raw = process.env.GLIDER_BROWSER_UI;
|
|
723
|
+
if (raw == null || raw === '') return false;
|
|
724
|
+
return raw === '1' || /^true$/i.test(raw) || /^yes$/i.test(raw);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function browserUiBlockedReason(action) {
|
|
728
|
+
return `browser UI blocked (default): refused ${action}; set GLIDER_BROWSER_UI=1 to allow AppleScript launch/tabs/activate`;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function browserIsRunning(browser) {
|
|
732
|
+
try {
|
|
733
|
+
execFileSync('pgrep', ['-x', browser.processName], { stdio: 'ignore' });
|
|
734
|
+
return true;
|
|
735
|
+
} catch {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function launchBrowser(browser) {
|
|
741
|
+
if (!browserUiEnabled()) {
|
|
742
|
+
throw new Error(browserUiBlockedReason('launch browser'));
|
|
743
|
+
}
|
|
744
|
+
const args = browser.path ? [browser.path] : ['-a', browser.name];
|
|
745
|
+
execFileSync('open', args, { stdio: 'ignore' });
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function activeBrowserTabUrl(browser) {
|
|
749
|
+
if (!browserUiEnabled()) {
|
|
750
|
+
throw new Error(browserUiBlockedReason('read active tab URL'));
|
|
751
|
+
}
|
|
752
|
+
const app = appleScriptString(browser.name);
|
|
753
|
+
return execFileSync('osascript', [
|
|
754
|
+
'-e',
|
|
755
|
+
`tell application "${app}" to return URL of active tab of front window`,
|
|
756
|
+
]).toString().trim();
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function createBrowserPage(browser, url, newWindow = false) {
|
|
760
|
+
if (!browserUiEnabled()) {
|
|
761
|
+
throw new Error(browserUiBlockedReason(newWindow ? 'create window' : 'create tab'));
|
|
762
|
+
}
|
|
763
|
+
const app = appleScriptString(browser.name);
|
|
764
|
+
const target = appleScriptString(url);
|
|
765
|
+
const command = newWindow
|
|
766
|
+
? `tell application "${app}" to make new window with properties {URL:"${target}"}`
|
|
767
|
+
: `tell application "${app}" to make new tab at front window with properties {URL:"${target}"}`;
|
|
768
|
+
execFileSync('osascript', ['-e', command], { stdio: 'ignore' });
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function activateBrowser(browser) {
|
|
772
|
+
if (!browserUiEnabled()) {
|
|
773
|
+
throw new Error(browserUiBlockedReason('activate browser'));
|
|
774
|
+
}
|
|
775
|
+
execFileSync('osascript', ['-e', `tell application "${appleScriptString(browser.name)}" to activate`]);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function requestActiveTabAttach() {
|
|
779
|
+
const response = await fetch(`${SERVER_URL}/attach`, { method: 'POST' });
|
|
780
|
+
const data = await response.json();
|
|
781
|
+
if (!response.ok) throw new Error(data?.error || `HTTP ${response.status}`);
|
|
782
|
+
return data;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// Auto-connect helper - honors the browser selected by $GLIDER_HOME/config/browser.json.
|
|
323
786
|
async function ensureConnected() {
|
|
324
787
|
// Check if already connected
|
|
325
788
|
if (await checkTab()) {
|
|
@@ -329,29 +792,27 @@ async function ensureConnected() {
|
|
|
329
792
|
// Check if server is running
|
|
330
793
|
if (!await checkServer()) {
|
|
331
794
|
log.info('Server not running, starting...');
|
|
332
|
-
await cmdStart();
|
|
333
|
-
await
|
|
795
|
+
await cmdStart({ render: false });
|
|
796
|
+
await waitUntil(() => checkServer(), { timeoutMs: 5000, intervalMs: 50, label: 'relay ready' });
|
|
334
797
|
}
|
|
335
798
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
799
|
+
const browser = getBrowserConfig();
|
|
800
|
+
if (!browserIsRunning(browser)) {
|
|
801
|
+
if (!browserUiEnabled()) {
|
|
802
|
+
log.fail(`${browser.name} not running; browser UI blocked (set GLIDER_BROWSER_UI=1 to launch)`);
|
|
803
|
+
return false;
|
|
804
|
+
}
|
|
805
|
+
log.info(`${browser.name} not running, launching...`);
|
|
806
|
+
launchBrowser(browser);
|
|
807
|
+
await waitUntil(() => browserIsRunning(browser), { timeoutMs: 8000, intervalMs: 100, label: 'browser launch' });
|
|
344
808
|
}
|
|
345
809
|
|
|
346
810
|
// Wait for extension to connect
|
|
347
|
-
|
|
348
|
-
if (await checkExtension()) break;
|
|
349
|
-
await new Promise(r => setTimeout(r, 500));
|
|
350
|
-
}
|
|
811
|
+
await waitUntil(() => checkExtension(), { timeoutMs: 5000, intervalMs: 100, label: 'extension' });
|
|
351
812
|
|
|
352
813
|
if (!await checkExtension()) {
|
|
353
|
-
log.fail(
|
|
354
|
-
log.info('Install
|
|
814
|
+
log.fail(`Extension not connected in ${browser.name}`);
|
|
815
|
+
log.info('Install or enable Glider from Chrome Web Store: https://chromewebstore.google.com/detail/glider/njbidokkffhgpofcejgcfcgcinmeoalj');
|
|
355
816
|
return false;
|
|
356
817
|
}
|
|
357
818
|
|
|
@@ -360,45 +821,61 @@ async function ensureConnected() {
|
|
|
360
821
|
log.ok('Auto-connected to existing tab');
|
|
361
822
|
return true;
|
|
362
823
|
}
|
|
824
|
+
|
|
825
|
+
// HTTP attach only unless operator opts into AppleScript UI mutation
|
|
826
|
+
try {
|
|
827
|
+
const data = await requestActiveTabAttach();
|
|
828
|
+
if (data.attached > 0 || await checkTab()) {
|
|
829
|
+
log.ok('Auto-connected!');
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
} catch {}
|
|
833
|
+
|
|
834
|
+
if (!browserUiEnabled()) {
|
|
835
|
+
log.fail('No attached targets; browser UI blocked (default). Click Glider on an existing tab, or set GLIDER_BROWSER_UI=1 to allow tab creation.');
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
363
838
|
|
|
364
839
|
// Need to create/attach to a tab
|
|
365
840
|
try {
|
|
366
|
-
const tabUrl =
|
|
367
|
-
if (
|
|
368
|
-
log.info(
|
|
369
|
-
|
|
370
|
-
await
|
|
841
|
+
const tabUrl = activeBrowserTabUrl(browser);
|
|
842
|
+
if (isBrowserInternalUrl(tabUrl)) {
|
|
843
|
+
log.info(`Creating new tab (current URL is not attachable: ${tabUrl})...`);
|
|
844
|
+
createBrowserPage(browser, browser.bootstrapUrl);
|
|
845
|
+
await waitUntil(() => checkTab(), { timeoutMs: 4000, intervalMs: 100, label: 'tab attach' });
|
|
371
846
|
}
|
|
372
847
|
} catch {
|
|
373
848
|
// No window exists, create one
|
|
374
|
-
log.info(
|
|
375
|
-
|
|
376
|
-
await
|
|
849
|
+
log.info(`Creating new ${browser.name} window...`);
|
|
850
|
+
createBrowserPage(browser, browser.bootstrapUrl, true);
|
|
851
|
+
await waitUntil(() => checkTab(), { timeoutMs: 4000, intervalMs: 100, label: 'tab attach' });
|
|
377
852
|
}
|
|
378
853
|
|
|
379
854
|
// Trigger attach via HTTP
|
|
380
855
|
try {
|
|
381
|
-
const
|
|
382
|
-
const data = await result.json();
|
|
856
|
+
const data = await requestActiveTabAttach();
|
|
383
857
|
if (data.attached > 0) {
|
|
384
858
|
log.ok('Auto-connected!');
|
|
385
859
|
return true;
|
|
386
860
|
}
|
|
387
861
|
} catch {}
|
|
388
|
-
|
|
862
|
+
|
|
389
863
|
// Final fallback - create fresh tab
|
|
390
864
|
log.info('Creating fresh tab...');
|
|
391
|
-
|
|
392
|
-
await
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
log.ok('Auto-connected!');
|
|
399
|
-
return true;
|
|
865
|
+
createBrowserPage(browser, browser.bootstrapUrl);
|
|
866
|
+
await waitUntil(async () => {
|
|
867
|
+
try {
|
|
868
|
+
const data = await requestActiveTabAttach();
|
|
869
|
+
return data.attached > 0 || await checkTab();
|
|
870
|
+
} catch {
|
|
871
|
+
return checkTab();
|
|
400
872
|
}
|
|
401
|
-
}
|
|
873
|
+
}, { timeoutMs: 4000, intervalMs: 100, label: 'fresh tab attach' });
|
|
874
|
+
|
|
875
|
+
if (await checkTab()) {
|
|
876
|
+
log.ok('Auto-connected!');
|
|
877
|
+
return true;
|
|
878
|
+
}
|
|
402
879
|
|
|
403
880
|
log.fail('Could not auto-connect');
|
|
404
881
|
return false;
|
|
@@ -406,18 +883,54 @@ async function ensureConnected() {
|
|
|
406
883
|
|
|
407
884
|
// Commands
|
|
408
885
|
async function cmdStatus() {
|
|
886
|
+
let relay = null;
|
|
887
|
+
try {
|
|
888
|
+
relay = await httpGet('/status');
|
|
889
|
+
} catch {}
|
|
890
|
+
const serverOk = relay !== null;
|
|
891
|
+
const extOk = serverOk && extensionReady(relay);
|
|
892
|
+
const targets = serverOk && relay.extension === true ? await getTargets() : [];
|
|
893
|
+
const healthy = serverOk && extOk && targets.length > 0;
|
|
894
|
+
const healthError = healthy
|
|
895
|
+
? null
|
|
896
|
+
: !serverOk
|
|
897
|
+
? 'relay unavailable'
|
|
898
|
+
: !relay.extension
|
|
899
|
+
? 'extension disconnected'
|
|
900
|
+
: !extOk
|
|
901
|
+
? 'extension worker not alive (socket up, no pong; click Glider icon or reload extension)'
|
|
902
|
+
: 'no attached targets';
|
|
903
|
+
|
|
904
|
+
if (jsonOutput) {
|
|
905
|
+
emitJson(healthy, {
|
|
906
|
+
healthy,
|
|
907
|
+
port: PORT,
|
|
908
|
+
server: serverOk,
|
|
909
|
+
extension: !!relay?.extension,
|
|
910
|
+
extensionWorkerAlive: relay?.extensionWorkerAlive ?? null,
|
|
911
|
+
reconnecting: relay?.reconnecting === true,
|
|
912
|
+
targetCount: targets.length,
|
|
913
|
+
targets: targets.map((target) => ({
|
|
914
|
+
sessionId: target.sessionId,
|
|
915
|
+
targetId: target.targetId,
|
|
916
|
+
title: target.title || target.targetInfo?.title || '',
|
|
917
|
+
url: target.url || target.targetInfo?.url || '',
|
|
918
|
+
})),
|
|
919
|
+
}, healthError);
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
|
|
409
923
|
showBanner();
|
|
410
924
|
log.box('STATUS');
|
|
411
|
-
|
|
412
|
-
const serverOk = await checkServer();
|
|
413
925
|
console.log(serverOk ? ` ${GREEN}✓${NC} Server running on port ${PORT}` : ` ${RED}✗${NC} Server not running`);
|
|
414
926
|
|
|
415
927
|
if (serverOk) {
|
|
416
|
-
const extOk = await checkExtension();
|
|
417
928
|
console.log(extOk ? ` ${GREEN}✓${NC} Extension connected` : ` ${RED}✗${NC} Extension not connected`);
|
|
929
|
+
if (relay?.extension && !extOk) {
|
|
930
|
+
console.log(` ${DIM}socket up but worker silent - click Glider icon or reload extension${NC}`);
|
|
931
|
+
}
|
|
418
932
|
|
|
419
933
|
if (extOk) {
|
|
420
|
-
const targets = await getTargets();
|
|
421
934
|
if (targets.length > 0) {
|
|
422
935
|
console.log(` ${GREEN}✓${NC} ${targets.length} tab(s) connected:`);
|
|
423
936
|
targets.forEach(t => {
|
|
@@ -433,46 +946,146 @@ async function cmdStatus() {
|
|
|
433
946
|
console.log(` ${DIM}Run: glider install${NC}`);
|
|
434
947
|
}
|
|
435
948
|
console.log();
|
|
949
|
+
if (!healthy) process.exitCode = 1;
|
|
436
950
|
}
|
|
437
951
|
|
|
438
|
-
async function cmdStart() {
|
|
439
|
-
if (
|
|
440
|
-
|
|
441
|
-
return;
|
|
952
|
+
async function cmdStart({ render = true } = {}) {
|
|
953
|
+
if (!fs.existsSync(RELAY_ENTRY)) {
|
|
954
|
+
throw new Error(`bserve not found at ${RELAY_ENTRY}`);
|
|
442
955
|
}
|
|
443
956
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
957
|
+
fs.mkdirSync(GLIDER_HOME, { recursive: true });
|
|
958
|
+
if (render) log.info('Starting glider server...');
|
|
959
|
+
const locks = await acquireStandaloneRelayLocks();
|
|
960
|
+
|
|
961
|
+
let child = null;
|
|
962
|
+
let identity = null;
|
|
963
|
+
try {
|
|
964
|
+
let status = null;
|
|
965
|
+
try {
|
|
966
|
+
status = await getRelayStatus();
|
|
967
|
+
} catch {}
|
|
968
|
+
|
|
969
|
+
const ownership = inspectDaemonOwnership();
|
|
970
|
+
if (status?.pid) {
|
|
971
|
+
if (
|
|
972
|
+
ownership.state === 'owned'
|
|
973
|
+
&& (!daemonChildMatches(ownership.record) || status.pid !== ownership.record.childPid)
|
|
974
|
+
) {
|
|
975
|
+
throw new Error(`Daemon PID ${ownership.record.pid} does not own the active relay on port ${PORT}`);
|
|
976
|
+
}
|
|
977
|
+
if (ownership.state === 'unverified') assertStandaloneRelayAllowed(ownership);
|
|
978
|
+
const result = {
|
|
979
|
+
running: true,
|
|
980
|
+
port: PORT,
|
|
981
|
+
pid: status.pid,
|
|
982
|
+
alreadyRunning: true,
|
|
983
|
+
managedBy: ownership.state === 'owned' ? 'daemon' : 'standalone',
|
|
984
|
+
};
|
|
985
|
+
if (render) {
|
|
986
|
+
if (jsonOutput) emitJson(true, result);
|
|
987
|
+
else log.ok('Server already running');
|
|
988
|
+
}
|
|
989
|
+
return result;
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
assertStandaloneRelayAllowed(ownership);
|
|
993
|
+
|
|
994
|
+
child = spawn(process.execPath, [RELAY_ENTRY], {
|
|
995
|
+
detached: true,
|
|
996
|
+
stdio: ['ignore', fs.openSync(LOG_FILE, 'a'), fs.openSync(LOG_FILE, 'a')],
|
|
997
|
+
});
|
|
998
|
+
identity = getProcessIdentity(child.pid);
|
|
999
|
+
if (!identity) {
|
|
1000
|
+
child.kill('SIGTERM');
|
|
1001
|
+
throw new Error('Server process identity could not be verified');
|
|
1002
|
+
}
|
|
1003
|
+
writeRelayPidRecord({
|
|
1004
|
+
schema: 1,
|
|
1005
|
+
pid: child.pid,
|
|
1006
|
+
port: PORT,
|
|
1007
|
+
entry: fs.realpathSync(RELAY_ENTRY),
|
|
1008
|
+
started: identity.started,
|
|
1009
|
+
});
|
|
1010
|
+
child.unref();
|
|
1011
|
+
|
|
1012
|
+
for (let i = 0; i < 10; i++) {
|
|
1013
|
+
await new Promise(r => setTimeout(r, 500));
|
|
1014
|
+
let status = null;
|
|
1015
|
+
try { status = await getRelayStatus(); } catch {}
|
|
1016
|
+
if (status?.pid === child.pid && status.port === PORT) {
|
|
1017
|
+
assertStandaloneRelayAllowed();
|
|
1018
|
+
const result = { running: true, port: PORT, pid: child.pid };
|
|
1019
|
+
if (render) {
|
|
1020
|
+
if (jsonOutput) emitJson(true, result);
|
|
1021
|
+
else log.ok('Server started');
|
|
1022
|
+
}
|
|
1023
|
+
return result;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
throw new Error('Server failed to start');
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
if (child) {
|
|
1029
|
+
try { child.kill('SIGTERM'); } catch {}
|
|
1030
|
+
try { await waitForProcessExit(child.pid); } catch {}
|
|
1031
|
+
}
|
|
1032
|
+
if (identity) {
|
|
1033
|
+
try { removeRelayPidRecordIfOwned(child.pid, identity.started); } catch {}
|
|
1034
|
+
}
|
|
1035
|
+
throw error;
|
|
1036
|
+
} finally {
|
|
1037
|
+
releaseStandaloneRelayLocks(locks);
|
|
450
1038
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
for (let i = 0; i < 10; i++) {
|
|
460
|
-
await new Promise(r => setTimeout(r, 500));
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
async function cmdStop({ render = true } = {}) {
|
|
1042
|
+
fs.mkdirSync(GLIDER_HOME, { recursive: true });
|
|
1043
|
+
const locks = await acquireStandaloneRelayLocks();
|
|
1044
|
+
try {
|
|
1045
|
+
assertStandaloneRelayAllowed();
|
|
1046
|
+
if (!fs.existsSync(RELAY_PID_FILE)) {
|
|
461
1047
|
if (await checkServer()) {
|
|
462
|
-
|
|
463
|
-
|
|
1048
|
+
throw new Error(`Relay is running but is not owned by this CLI (${RELAY_PID_FILE} is absent); stop its service manager instead`);
|
|
1049
|
+
}
|
|
1050
|
+
const result = { running: false, port: PORT, alreadyStopped: true };
|
|
1051
|
+
if (render) {
|
|
1052
|
+
if (jsonOutput) emitJson(true, result);
|
|
1053
|
+
else log.warn('Server was not running');
|
|
464
1054
|
}
|
|
1055
|
+
return result;
|
|
465
1056
|
}
|
|
466
|
-
log.fail('Server failed to start');
|
|
467
|
-
process.exit(1);
|
|
468
|
-
}
|
|
469
1057
|
|
|
470
|
-
|
|
1058
|
+
const record = readRelayPidRecord(RELAY_PID_FILE);
|
|
1059
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
1060
|
+
if (!relayPidRecordMatches(record, identity)) {
|
|
1061
|
+
throw new Error(`Refusing to signal unverified relay PID record: ${RELAY_PID_FILE}`);
|
|
1062
|
+
}
|
|
471
1063
|
try {
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1064
|
+
process.kill(record.pid, 'SIGTERM');
|
|
1065
|
+
} catch (error) {
|
|
1066
|
+
if (error.code === 'ESRCH') {
|
|
1067
|
+
try { removeRelayPidRecordIfOwned(record.pid, record.started); } catch {}
|
|
1068
|
+
const result = { running: false, port: PORT, alreadyStopped: true };
|
|
1069
|
+
if (render) {
|
|
1070
|
+
if (jsonOutput) emitJson(true, result);
|
|
1071
|
+
else log.warn('Server was not running');
|
|
1072
|
+
}
|
|
1073
|
+
return result;
|
|
1074
|
+
}
|
|
1075
|
+
throw error;
|
|
1076
|
+
}
|
|
1077
|
+
if (!await waitForProcessExit(record.pid)) {
|
|
1078
|
+
throw new Error(`relay PID ${record.pid} did not exit after SIGTERM`);
|
|
1079
|
+
}
|
|
1080
|
+
removeRelayPidRecordIfOwned(record.pid, record.started);
|
|
1081
|
+
const result = { running: false, port: PORT, pid: record.pid };
|
|
1082
|
+
if (render) {
|
|
1083
|
+
if (jsonOutput) emitJson(true, result);
|
|
1084
|
+
else log.ok('Server stopped');
|
|
1085
|
+
}
|
|
1086
|
+
return result;
|
|
1087
|
+
} finally {
|
|
1088
|
+
releaseStandaloneRelayLocks(locks);
|
|
476
1089
|
}
|
|
477
1090
|
}
|
|
478
1091
|
|
|
@@ -704,8 +1317,11 @@ async function cmdText() {
|
|
|
704
1317
|
returnByValue: true,
|
|
705
1318
|
}
|
|
706
1319
|
});
|
|
707
|
-
|
|
1320
|
+
const value = result.result?.value || '';
|
|
1321
|
+
if (jsonOutput) emitJson(true, value);
|
|
1322
|
+
else console.log(value);
|
|
708
1323
|
} catch (e) {
|
|
1324
|
+
if (jsonOutput) emitJson(false, null, e.message);
|
|
709
1325
|
log.fail(`Text extraction failed: ${e.message}`);
|
|
710
1326
|
process.exit(1);
|
|
711
1327
|
}
|
|
@@ -716,26 +1332,70 @@ async function cmdText() {
|
|
|
716
1332
|
// ═══════════════════════════════════════════════════════════════════
|
|
717
1333
|
|
|
718
1334
|
async function cmdRestart() {
|
|
719
|
-
await cmdStop();
|
|
1335
|
+
const stopped = await cmdStop({ render: false });
|
|
720
1336
|
await new Promise(r => setTimeout(r, 500));
|
|
721
|
-
await cmdStart();
|
|
1337
|
+
const started = await cmdStart({ render: false });
|
|
1338
|
+
const result = { stopped, started };
|
|
1339
|
+
if (jsonOutput) emitJson(true, result);
|
|
1340
|
+
else log.ok('Server restarted');
|
|
1341
|
+
return result;
|
|
722
1342
|
}
|
|
723
1343
|
|
|
724
1344
|
// reload-ext: automate extension reload + tab re-attachment
|
|
725
1345
|
async function cmdReloadExt() {
|
|
726
1346
|
try {
|
|
1347
|
+
const before = await httpGetJson('/status');
|
|
1348
|
+
if (!Number.isInteger(before?.extensionGeneration)) {
|
|
1349
|
+
throw new Error('relay does not expose extension connection generation');
|
|
1350
|
+
}
|
|
727
1351
|
const r = await postExtension({ method: 'reloadSelf', params: {} });
|
|
728
|
-
// v0.3.15: same response unwrap fix as attach-all - r.result was always undefined
|
|
729
1352
|
const persisted = (r.result?.persisted ?? r.persisted ?? '?');
|
|
730
1353
|
log.ok(`Extension reload triggered (persisted ${persisted} tab URLs).`);
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
const
|
|
736
|
-
|
|
1354
|
+
const timeoutMs = Number.parseInt(process.env.GLIDER_RELOAD_TIMEOUT_MS || '15000', 10);
|
|
1355
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 100) {
|
|
1356
|
+
throw new Error('GLIDER_RELOAD_TIMEOUT_MS must be an integer >= 100');
|
|
1357
|
+
}
|
|
1358
|
+
const deadline = Date.now() + timeoutMs;
|
|
1359
|
+
const needsTarget = Number.isInteger(persisted) && persisted > 0;
|
|
1360
|
+
let status = null;
|
|
1361
|
+
let sawDisconnect = before.extension !== true;
|
|
1362
|
+
while (Date.now() < deadline) {
|
|
1363
|
+
try {
|
|
1364
|
+
status = await httpGetJson('/status');
|
|
1365
|
+
if (status?.extension !== true) sawDisconnect = true;
|
|
1366
|
+
if (
|
|
1367
|
+
status?.extension === true
|
|
1368
|
+
&& status.extensionGeneration !== before.extensionGeneration
|
|
1369
|
+
&& (!needsTarget || status.targets > 0)
|
|
1370
|
+
) break;
|
|
1371
|
+
} catch {
|
|
1372
|
+
sawDisconnect = true;
|
|
1373
|
+
}
|
|
1374
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1375
|
+
}
|
|
1376
|
+
if (
|
|
1377
|
+
status?.extension !== true
|
|
1378
|
+
|| status.extensionGeneration === before.extensionGeneration
|
|
1379
|
+
|| (needsTarget && status.targets < 1)
|
|
1380
|
+
) {
|
|
1381
|
+
if (!sawDisconnect && status?.extension === true
|
|
1382
|
+
&& status.extensionGeneration === before.extensionGeneration) {
|
|
1383
|
+
throw new Error(
|
|
1384
|
+
`extension did not reload (connection never dropped within ${timeoutMs}ms); `
|
|
1385
|
+
+ 'chrome.runtime.reload may be blocked in this browser/profile'
|
|
1386
|
+
);
|
|
1387
|
+
}
|
|
1388
|
+
throw new Error(`extension did not reconnect within ${timeoutMs}ms`);
|
|
1389
|
+
}
|
|
1390
|
+
if (jsonOutput) emitJson(true, {
|
|
1391
|
+
persisted,
|
|
1392
|
+
extension: true,
|
|
1393
|
+
targets: status.targets,
|
|
1394
|
+
extensionGeneration: status.extensionGeneration,
|
|
1395
|
+
});
|
|
1396
|
+
log.ok(`Relay reconnected: extension=true targets=${status.targets}`);
|
|
737
1397
|
} catch (e) {
|
|
738
|
-
|
|
1398
|
+
emitCommandFailure(`reload-ext failed: ${e.message}`);
|
|
739
1399
|
log.info('First-time bootstrap: open your browser extensions page and reload Glider (one time only).');
|
|
740
1400
|
}
|
|
741
1401
|
}
|
|
@@ -757,97 +1417,171 @@ async function cmdAttachAll(filter) {
|
|
|
757
1417
|
}
|
|
758
1418
|
} catch (e) {
|
|
759
1419
|
log.fail(`attach-all failed: ${e.message}`);
|
|
1420
|
+
process.exit(1);
|
|
760
1421
|
}
|
|
761
1422
|
}
|
|
762
1423
|
|
|
763
1424
|
// Helper: POST to relay's /extension endpoint (already exists in bserve.js)
|
|
764
1425
|
async function postExtension(body) {
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
hostname: '127.0.0.1', port: 19988, path: '/extension', method: 'POST',
|
|
769
|
-
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }
|
|
770
|
-
}, (res) => {
|
|
771
|
-
let s = '';
|
|
772
|
-
res.on('data', c => s += c);
|
|
773
|
-
res.on('end', () => {
|
|
774
|
-
try {
|
|
775
|
-
const j = JSON.parse(s);
|
|
776
|
-
if (j.error) reject(new Error(j.error.message || j.error));
|
|
777
|
-
else resolve(j);
|
|
778
|
-
} catch(e) { reject(new Error('bad JSON from /extension: ' + s.slice(0,200))); }
|
|
779
|
-
});
|
|
780
|
-
});
|
|
781
|
-
req.on('error', reject);
|
|
782
|
-
req.write(data); req.end();
|
|
783
|
-
});
|
|
1426
|
+
const result = await httpPost('/extension', body);
|
|
1427
|
+
if (result?.error) throw new Error(result.error.message || result.error);
|
|
1428
|
+
return result;
|
|
784
1429
|
}
|
|
785
1430
|
|
|
786
1431
|
async function httpGetJson(pathStr) {
|
|
787
|
-
return
|
|
788
|
-
http.get({ hostname: '127.0.0.1', port: 19988, path: pathStr }, (res) => {
|
|
789
|
-
let s = ''; res.on('data', c => s += c);
|
|
790
|
-
res.on('end', () => { try { resolve(JSON.parse(s)); } catch(e) { reject(e); } });
|
|
791
|
-
}).on('error', reject);
|
|
792
|
-
});
|
|
1432
|
+
return httpGet(pathStr);
|
|
793
1433
|
}
|
|
794
1434
|
|
|
795
1435
|
// Daemon management - runs forever, respawns on crash
|
|
796
1436
|
async function cmdInstallDaemon() {
|
|
797
1437
|
const home = os.homedir();
|
|
798
|
-
const daemonScript =
|
|
799
|
-
const logDir =
|
|
800
|
-
const pidFile =
|
|
1438
|
+
const daemonScript = DAEMON_ENTRY;
|
|
1439
|
+
const logDir = GLIDER_HOME;
|
|
1440
|
+
const pidFile = DAEMON_PID_FILE;
|
|
1441
|
+
const legacyPidFile = path.join(logDir, 'daemon.pid');
|
|
801
1442
|
|
|
802
1443
|
// Create log directory
|
|
803
1444
|
if (!fs.existsSync(logDir)) {
|
|
804
1445
|
fs.mkdirSync(logDir, { recursive: true });
|
|
805
1446
|
}
|
|
1447
|
+
const managementLock = await acquireDaemonManagementLock();
|
|
1448
|
+
try {
|
|
1449
|
+
|
|
1450
|
+
const legacy = inspectLegacyDaemonRecord(legacyPidFile, daemonScript);
|
|
1451
|
+
if (legacy.state === 'live-unverified') {
|
|
1452
|
+
emitCommandFailure(`Legacy daemon PID ${legacy.pid} is still running, but ${legacyPidFile} lacks safe ownership metadata; stop its service manager, then rerun glider install`);
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (legacy.state === 'stale') {
|
|
1456
|
+
try { fs.unlinkSync(legacyPidFile); } catch {}
|
|
1457
|
+
}
|
|
806
1458
|
|
|
807
|
-
// Kill existing daemon
|
|
808
1459
|
if (fs.existsSync(pidFile)) {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
1460
|
+
const record = readDaemonPidRecord(pidFile);
|
|
1461
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
1462
|
+
if (daemonSupervisorMatches(record, identity, daemonScript)) {
|
|
1463
|
+
let status = null;
|
|
1464
|
+
try { status = await getRelayStatus(); } catch {}
|
|
1465
|
+
if (
|
|
1466
|
+
record.ready === true
|
|
1467
|
+
&& daemonChildMatches(record)
|
|
1468
|
+
&& status?.pid === record.childPid
|
|
1469
|
+
&& status.port === PORT
|
|
1470
|
+
) {
|
|
1471
|
+
if (jsonOutput) emitJson(true, { running: true, port: PORT, pid: record.pid, childPid: record.childPid, alreadyRunning: true });
|
|
1472
|
+
log.ok('Daemon already running');
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
1475
|
+
emitCommandFailure(`Daemon PID ${record.pid} is running but does not own the relay on port ${PORT}`);
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
const claimDir = DAEMON_CLAIM_DIR;
|
|
1479
|
+
if (fs.existsSync(claimDir)) {
|
|
1480
|
+
emitCommandFailure(`Daemon claim exists without a verified ownership record: ${claimDir}`);
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
if (record) removeDaemonPidRecordIfOwned(pidFile, record);
|
|
1484
|
+
else fs.unlinkSync(pidFile);
|
|
813
1485
|
}
|
|
814
1486
|
|
|
815
|
-
|
|
816
|
-
const child = spawn('nohup', [daemonScript], {
|
|
1487
|
+
const child = spawn(daemonScript, [], {
|
|
817
1488
|
detached: true,
|
|
818
1489
|
stdio: ['ignore', 'ignore', 'ignore'],
|
|
819
|
-
cwd: home
|
|
1490
|
+
cwd: home,
|
|
1491
|
+
env: {
|
|
1492
|
+
...process.env,
|
|
1493
|
+
GLIDER_PORT: String(PORT),
|
|
1494
|
+
GLIDER_DAEMON_MANAGEMENT_OWNER_PID: String(managementLock.pid),
|
|
1495
|
+
GLIDER_DAEMON_MANAGEMENT_OWNER_STARTED: managementLock.started,
|
|
1496
|
+
},
|
|
820
1497
|
});
|
|
821
1498
|
child.unref();
|
|
822
1499
|
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
1500
|
+
for (let i = 0; i < 20; i++) {
|
|
1501
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
1502
|
+
const record = readDaemonPidRecord(pidFile);
|
|
1503
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
1504
|
+
let status = null;
|
|
1505
|
+
try { status = await getRelayStatus(); } catch {}
|
|
1506
|
+
if (
|
|
1507
|
+
daemonSupervisorMatches(record, identity, daemonScript)
|
|
1508
|
+
&& record.ready === true
|
|
1509
|
+
&& daemonChildMatches(record)
|
|
1510
|
+
&& status?.pid === record.childPid
|
|
1511
|
+
&& status.port === PORT
|
|
1512
|
+
) {
|
|
1513
|
+
const alreadyRunning = record.pid !== child.pid;
|
|
1514
|
+
if (jsonOutput) emitJson(true, { running: true, port: PORT, pid: record.pid, childPid: record.childPid, alreadyRunning });
|
|
1515
|
+
log.ok(alreadyRunning ? 'Daemon already running' : 'Daemon started');
|
|
1516
|
+
log.info('Relay will auto-restart on crash');
|
|
1517
|
+
log.info(`Logs: ${logDir}/daemon.log`);
|
|
1518
|
+
log.info(`PID: ${record.pid}`);
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
if (child.exitCode !== null && child.exitCode !== 0) break;
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
const identity = getProcessIdentity(child.pid);
|
|
1525
|
+
if (identity && commandIncludesPath(identity.command, daemonScript)) {
|
|
1526
|
+
try {
|
|
1527
|
+
process.kill(child.pid, 'SIGTERM');
|
|
1528
|
+
await waitForProcessExit(child.pid);
|
|
1529
|
+
} catch {}
|
|
1530
|
+
}
|
|
1531
|
+
const failedRecord = readDaemonPidRecord(pidFile);
|
|
1532
|
+
if (failedRecord?.pid === child.pid) removeDaemonPidRecordIfOwned(pidFile, failedRecord);
|
|
1533
|
+
emitCommandFailure(`Daemon failed to start a relay on port ${PORT}`);
|
|
1534
|
+
} finally {
|
|
1535
|
+
releaseDaemonManagementLock(managementLock);
|
|
832
1536
|
}
|
|
833
1537
|
}
|
|
834
1538
|
|
|
835
1539
|
async function cmdUninstallDaemon() {
|
|
836
|
-
|
|
837
|
-
const pidFile =
|
|
1540
|
+
fs.mkdirSync(GLIDER_HOME, { recursive: true });
|
|
1541
|
+
const pidFile = DAEMON_PID_FILE;
|
|
1542
|
+
const legacyPidFile = path.join(GLIDER_HOME, 'daemon.pid');
|
|
1543
|
+
const daemonScript = DAEMON_ENTRY;
|
|
1544
|
+
const claimDir = DAEMON_CLAIM_DIR;
|
|
1545
|
+
const managementLock = await acquireDaemonManagementLock();
|
|
1546
|
+
try {
|
|
1547
|
+
const legacy = inspectLegacyDaemonRecord(legacyPidFile, daemonScript);
|
|
1548
|
+
if (legacy.state === 'live-unverified') {
|
|
1549
|
+
emitCommandFailure(`Legacy daemon PID ${legacy.pid} is still running, but ${legacyPidFile} lacks safe ownership metadata; stop its service manager, then rerun glider uninstall`);
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
const legacyRecordRemoved = legacy.state === 'stale';
|
|
1553
|
+
if (legacyRecordRemoved) {
|
|
1554
|
+
try { fs.unlinkSync(legacyPidFile); } catch {}
|
|
1555
|
+
}
|
|
838
1556
|
|
|
839
1557
|
if (!fs.existsSync(pidFile)) {
|
|
1558
|
+
if (fs.existsSync(claimDir)) {
|
|
1559
|
+
emitCommandFailure(`Daemon claim exists without a verified ownership record: ${claimDir}`);
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
if (jsonOutput) emitJson(true, { running: false, port: PORT, legacyRecordRemoved });
|
|
840
1563
|
log.info('Daemon not running');
|
|
841
1564
|
return;
|
|
842
1565
|
}
|
|
843
1566
|
|
|
844
|
-
|
|
845
|
-
const
|
|
846
|
-
|
|
847
|
-
|
|
1567
|
+
const record = readDaemonPidRecord(pidFile);
|
|
1568
|
+
const identity = record ? getProcessIdentity(record.pid) : null;
|
|
1569
|
+
const childIsValid = record?.childPid == null || daemonChildMatches(record);
|
|
1570
|
+
if (!daemonSupervisorMatches(record, identity, daemonScript) || !childIsValid) {
|
|
1571
|
+
emitCommandFailure(`Refusing to signal unverified daemon PID record: ${pidFile}`);
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
process.kill(record.pid, 'SIGTERM');
|
|
1575
|
+
if (!await waitForProcessExit(record.pid)) {
|
|
1576
|
+
throw new Error(`daemon PID ${record.pid} did not exit after SIGTERM`);
|
|
1577
|
+
}
|
|
1578
|
+
if (fs.existsSync(pidFile)) removeDaemonPidRecordIfOwned(pidFile, record);
|
|
1579
|
+
if (jsonOutput) emitJson(true, { running: false, port: PORT, pid: record.pid });
|
|
848
1580
|
log.ok('Daemon stopped');
|
|
849
1581
|
} catch (e) {
|
|
850
|
-
|
|
1582
|
+
emitCommandFailure(`Failed to stop daemon: ${e.message}`);
|
|
1583
|
+
} finally {
|
|
1584
|
+
releaseDaemonManagementLock(managementLock);
|
|
851
1585
|
}
|
|
852
1586
|
}
|
|
853
1587
|
|
|
@@ -857,29 +1591,24 @@ async function cmdConnect() {
|
|
|
857
1591
|
|
|
858
1592
|
// 1. Ensure relay is running
|
|
859
1593
|
if (!await checkServer()) {
|
|
860
|
-
await cmdStart();
|
|
861
|
-
await
|
|
1594
|
+
await cmdStart({ render: false });
|
|
1595
|
+
await waitUntil(() => checkServer(), { timeoutMs: 5000, intervalMs: 50, label: 'relay ready' });
|
|
862
1596
|
}
|
|
863
1597
|
|
|
864
1598
|
// 2. Ensure browser is running (see getBrowserConfig + README.md#Browsers)
|
|
865
1599
|
const browser = getBrowserConfig();
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
if (browser.path) {
|
|
871
|
-
execSync(`open "${browser.path}"`, { stdio: 'ignore' });
|
|
872
|
-
} else {
|
|
873
|
-
execSync(`open -a "${browser.name}"`);
|
|
1600
|
+
if (!browserIsRunning(browser)) {
|
|
1601
|
+
if (!browserUiEnabled()) {
|
|
1602
|
+
log.fail(`${browser.name} not running; set GLIDER_BROWSER_UI=1 to allow launch, or start the browser yourself`);
|
|
1603
|
+
process.exit(1);
|
|
874
1604
|
}
|
|
875
|
-
|
|
1605
|
+
log.info(`Starting ${browser.name}...`);
|
|
1606
|
+
launchBrowser(browser);
|
|
1607
|
+
await waitUntil(() => browserIsRunning(browser), { timeoutMs: 8000, intervalMs: 100, label: 'browser launch' });
|
|
876
1608
|
}
|
|
877
1609
|
|
|
878
1610
|
// 3. Wait for extension to connect to relay
|
|
879
|
-
|
|
880
|
-
if (await checkExtension()) break;
|
|
881
|
-
await new Promise(r => setTimeout(r, 500));
|
|
882
|
-
}
|
|
1611
|
+
await waitUntil(() => checkExtension(), { timeoutMs: 5000, intervalMs: 100, label: 'extension' });
|
|
883
1612
|
|
|
884
1613
|
if (!await checkExtension()) {
|
|
885
1614
|
log.fail('Extension not connected to relay');
|
|
@@ -888,9 +1617,6 @@ async function cmdConnect() {
|
|
|
888
1617
|
}
|
|
889
1618
|
log.ok('Extension connected');
|
|
890
1619
|
|
|
891
|
-
// Wait for extension to fully initialize
|
|
892
|
-
await new Promise(r => setTimeout(r, 500));
|
|
893
|
-
|
|
894
1620
|
// 4. Check if already have targets
|
|
895
1621
|
if (await checkTab()) {
|
|
896
1622
|
log.ok('Already connected to tab(s)');
|
|
@@ -901,26 +1627,65 @@ async function cmdConnect() {
|
|
|
901
1627
|
return;
|
|
902
1628
|
}
|
|
903
1629
|
|
|
904
|
-
// 5.
|
|
1630
|
+
// 5. Prefer HTTP attach to existing tabs (no focus steal)
|
|
1631
|
+
log.info('Attaching to tab...');
|
|
1632
|
+
try {
|
|
1633
|
+
const data = await requestActiveTabAttach();
|
|
1634
|
+
if (data.attached > 0 || await checkTab()) {
|
|
1635
|
+
log.ok('Connected!');
|
|
1636
|
+
const targets = await getTargets();
|
|
1637
|
+
targets.slice(0, 3).forEach(t => {
|
|
1638
|
+
console.log(` ${CYAN}${t.targetInfo?.url || 'unknown'}${NC}`);
|
|
1639
|
+
});
|
|
1640
|
+
return;
|
|
1641
|
+
}
|
|
1642
|
+
} catch (e) {
|
|
1643
|
+
log.warn(`Attach failed: ${e.message}`);
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
if (!browserUiEnabled()) {
|
|
1647
|
+
log.warn(`Click the Glider extension icon in ${browser.name} (browser UI blocked by default; no tab/focus mutation)`);
|
|
1648
|
+
console.log(` ${B5}(on any real webpage, not a browser-internal page)${NC}`);
|
|
1649
|
+
console.log(` ${DIM}opt-in AppleScript tabs/activate: GLIDER_BROWSER_UI=1${NC}`);
|
|
1650
|
+
notify('Glider', `Click the extension icon in ${browser.name} to connect`, true);
|
|
1651
|
+
log.info('Waiting for connection...');
|
|
1652
|
+
for (let i = 0; i < 30; i++) {
|
|
1653
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
1654
|
+
if (await checkTab()) {
|
|
1655
|
+
log.ok('Connected!');
|
|
1656
|
+
notify('Glider', 'Connected to browser');
|
|
1657
|
+
const targets = await getTargets();
|
|
1658
|
+
targets.slice(0, 3).forEach(t => {
|
|
1659
|
+
console.log(` ${B5}${t.targetInfo?.url || 'unknown'}${NC}`);
|
|
1660
|
+
});
|
|
1661
|
+
return;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
log.fail('Timed out waiting for connection');
|
|
1665
|
+
notify('Glider', 'Connection timed out - click extension icon', true);
|
|
1666
|
+
log.info('Make sure you clicked the extension icon on a real webpage');
|
|
1667
|
+
process.exit(1);
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// 6. Opt-in UI path: ensure we have a real tab (not chrome:// or arc://)
|
|
905
1671
|
try {
|
|
906
|
-
const tabUrl =
|
|
907
|
-
if (
|
|
1672
|
+
const tabUrl = activeBrowserTabUrl(browser);
|
|
1673
|
+
if (isBrowserInternalUrl(tabUrl)) {
|
|
908
1674
|
log.info('Creating new tab...');
|
|
909
|
-
|
|
910
|
-
await
|
|
1675
|
+
createBrowserPage(browser, browser.bootstrapUrl);
|
|
1676
|
+
await waitUntil(() => checkTab(), { timeoutMs: 4000, intervalMs: 100, label: 'tab attach' });
|
|
911
1677
|
}
|
|
912
1678
|
} catch {
|
|
913
1679
|
// No window, create one
|
|
914
1680
|
log.info('Creating new window...');
|
|
915
|
-
|
|
916
|
-
await
|
|
1681
|
+
createBrowserPage(browser, browser.bootstrapUrl, true);
|
|
1682
|
+
await waitUntil(() => checkTab(), { timeoutMs: 4000, intervalMs: 100, label: 'tab attach' });
|
|
917
1683
|
}
|
|
918
1684
|
|
|
919
|
-
//
|
|
1685
|
+
// 7. Trigger attach via HTTP endpoint
|
|
920
1686
|
log.info('Attaching to tab...');
|
|
921
1687
|
try {
|
|
922
|
-
const
|
|
923
|
-
const data = await result.json();
|
|
1688
|
+
const data = await requestActiveTabAttach();
|
|
924
1689
|
|
|
925
1690
|
if (data.attached > 0) {
|
|
926
1691
|
log.ok('Connected!');
|
|
@@ -934,29 +1699,34 @@ async function cmdConnect() {
|
|
|
934
1699
|
log.warn(`Attach failed: ${e.message}`);
|
|
935
1700
|
}
|
|
936
1701
|
|
|
937
|
-
//
|
|
1702
|
+
// 8. Fallback: create fresh tab and retry
|
|
938
1703
|
log.info('Creating fresh tab...');
|
|
939
|
-
|
|
940
|
-
await
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
if (data.attached > 0) {
|
|
947
|
-
log.ok('Connected!');
|
|
948
|
-
const targets = await getTargets();
|
|
949
|
-
targets.slice(0, 3).forEach(t => {
|
|
950
|
-
console.log(` ${CYAN}${t.targetInfo?.url || 'unknown'}${NC}`);
|
|
951
|
-
});
|
|
952
|
-
return;
|
|
1704
|
+
createBrowserPage(browser, browser.bootstrapUrl);
|
|
1705
|
+
const attached = await waitUntil(async () => {
|
|
1706
|
+
try {
|
|
1707
|
+
const data = await requestActiveTabAttach();
|
|
1708
|
+
return data.attached > 0 || await checkTab();
|
|
1709
|
+
} catch {
|
|
1710
|
+
return checkTab();
|
|
953
1711
|
}
|
|
954
|
-
}
|
|
1712
|
+
}, { timeoutMs: 4000, intervalMs: 100, label: 'fresh tab attach' });
|
|
955
1713
|
|
|
956
|
-
|
|
1714
|
+
if (attached || await checkTab()) {
|
|
1715
|
+
log.ok('Connected!');
|
|
1716
|
+
const targets = await getTargets();
|
|
1717
|
+
targets.slice(0, 3).forEach(t => {
|
|
1718
|
+
console.log(` ${CYAN}${t.targetInfo?.url || 'unknown'}${NC}`);
|
|
1719
|
+
});
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
// 9. Need manual click - activate browser and show instructions (opt-in UI only)
|
|
957
1723
|
log.warn(`Click the Glider extension icon in ${browser.name}`);
|
|
958
|
-
console.log(` ${B5}(on any real webpage, not
|
|
959
|
-
|
|
1724
|
+
console.log(` ${B5}(on any real webpage, not a browser-internal page)${NC}`);
|
|
1725
|
+
try {
|
|
1726
|
+
activateBrowser(browser);
|
|
1727
|
+
} catch (e) {
|
|
1728
|
+
log.warn(e.message);
|
|
1729
|
+
}
|
|
960
1730
|
|
|
961
1731
|
// Send macOS notification so user sees it even if not looking at terminal
|
|
962
1732
|
notify('Glider', `Click the extension icon in ${browser.name} to connect`, true);
|
|
@@ -979,79 +1749,321 @@ async function cmdConnect() {
|
|
|
979
1749
|
log.fail('Timed out waiting for connection');
|
|
980
1750
|
notify('Glider', 'Connection timed out - click extension icon', true);
|
|
981
1751
|
log.info('Make sure you clicked the extension icon on a real webpage');
|
|
1752
|
+
process.exit(1);
|
|
982
1753
|
}
|
|
983
1754
|
|
|
984
1755
|
function cmdBrowser() {
|
|
985
1756
|
const b = getBrowserConfig();
|
|
1757
|
+
if (jsonOutput) {
|
|
1758
|
+
emitJson(true, {
|
|
1759
|
+
name: b.name,
|
|
1760
|
+
path: b.path,
|
|
1761
|
+
processName: b.processName,
|
|
1762
|
+
bootstrapUrl: b.bootstrapUrl,
|
|
1763
|
+
use: b.use,
|
|
1764
|
+
source: b.source,
|
|
1765
|
+
registrySource: b.registrySource,
|
|
1766
|
+
});
|
|
1767
|
+
return;
|
|
1768
|
+
}
|
|
986
1769
|
console.log('Browser config (used by glider connect):');
|
|
987
1770
|
console.log(` name: ${b.name}`);
|
|
988
1771
|
console.log(` path: ${b.path || '(default launch via name)'}`);
|
|
989
1772
|
console.log(` processName: ${b.processName}`);
|
|
990
|
-
|
|
991
|
-
|
|
1773
|
+
console.log(` bootstrapUrl: ${b.bootstrapUrl}`);
|
|
1774
|
+
if (b.use) {
|
|
1775
|
+
console.log(` use: ${b.use} ${DIM}(from registry)${NC}`);
|
|
992
1776
|
}
|
|
993
1777
|
console.log('');
|
|
994
|
-
console.log(
|
|
995
|
-
console.log(
|
|
1778
|
+
console.log(`Source: ${b.source || path.join(GLIDER_HOME, 'config', 'browser.json')} { "use": "<key>" } or { name, path } -> default "Google Chrome"`);
|
|
1779
|
+
console.log(`Registry: ${b.registrySource || path.join(GLIDER_HOME, 'config', 'browsers-registry.json')}. Keys: ` + (Object.keys(b.registry).join(', ') || '(none loaded)'));
|
|
996
1780
|
console.log('See README.md#browsers for compatibility and examples.');
|
|
997
1781
|
}
|
|
998
1782
|
|
|
999
1783
|
function cmdUse(key) {
|
|
1784
|
+
const browser = getBrowserConfig();
|
|
1000
1785
|
if (!key) {
|
|
1001
1786
|
console.log('Usage: glider use <key>');
|
|
1002
|
-
console.log('Keys in registry: ' + (Object.keys(
|
|
1003
|
-
if (
|
|
1787
|
+
console.log('Keys in registry: ' + (Object.keys(browser.registry).length ? Object.keys(browser.registry).join(', ') : '(no registry loaded)'));
|
|
1788
|
+
if (browser.use) console.log('Current: ' + browser.use);
|
|
1004
1789
|
return;
|
|
1005
1790
|
}
|
|
1006
|
-
if (!
|
|
1007
|
-
console.error('Unknown key: ' + key + '. Available: ' + Object.keys(
|
|
1791
|
+
if (!browser.registry[key]) {
|
|
1792
|
+
console.error('Unknown key: ' + key + '. Available: ' + Object.keys(browser.registry).join(', '));
|
|
1008
1793
|
process.exit(1);
|
|
1009
1794
|
}
|
|
1010
|
-
const configDir = path.join(
|
|
1795
|
+
const configDir = path.join(GLIDER_HOME, 'config');
|
|
1011
1796
|
const browserPath = path.join(configDir, 'browser.json');
|
|
1012
1797
|
if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
|
|
1013
1798
|
fs.writeFileSync(browserPath, JSON.stringify({ use: key }, null, 2) + '\n');
|
|
1014
|
-
console.log('Set browser to: ' + key + '
|
|
1799
|
+
console.log('Set browser to: ' + key + ' -> ' + browser.registry[key].name);
|
|
1015
1800
|
console.log('Run: glider connect');
|
|
1016
1801
|
}
|
|
1017
1802
|
|
|
1018
1803
|
async function cmdTest() {
|
|
1804
|
+
let relay = null;
|
|
1805
|
+
try {
|
|
1806
|
+
relay = await httpGet('/status');
|
|
1807
|
+
} catch {}
|
|
1808
|
+
const serverOk = relay !== null;
|
|
1809
|
+
const extOk = serverOk && extensionReady(relay);
|
|
1810
|
+
const tabOk = serverOk && Number(relay.targets || 0) > 0;
|
|
1811
|
+
let cdpOk = false;
|
|
1812
|
+
let cdpError = null;
|
|
1813
|
+
if (tabOk && extOk) {
|
|
1814
|
+
try {
|
|
1815
|
+
const result = await httpPost('/cdp', {
|
|
1816
|
+
method: 'Runtime.evaluate',
|
|
1817
|
+
params: { expression: '1+1', returnByValue: true }
|
|
1818
|
+
});
|
|
1819
|
+
cdpOk = result.result?.value === 2;
|
|
1820
|
+
if (!cdpOk) cdpError = 'unexpected Runtime.evaluate result';
|
|
1821
|
+
} catch (error) {
|
|
1822
|
+
cdpError = error.message;
|
|
1823
|
+
}
|
|
1824
|
+
} else if (tabOk && !extOk) {
|
|
1825
|
+
cdpError = 'extension worker not alive';
|
|
1826
|
+
}
|
|
1827
|
+
const healthy = serverOk && extOk && tabOk && cdpOk;
|
|
1828
|
+
const diagnosticError = healthy
|
|
1829
|
+
? null
|
|
1830
|
+
: cdpError || (!serverOk ? 'relay unavailable' : !extOk ? 'extension worker not alive' : !tabOk ? 'no attached target' : 'CDP probe failed');
|
|
1831
|
+
|
|
1832
|
+
if (jsonOutput) {
|
|
1833
|
+
emitJson(healthy, {
|
|
1834
|
+
healthy,
|
|
1835
|
+
server: serverOk,
|
|
1836
|
+
extension: !!relay?.extension,
|
|
1837
|
+
extensionWorkerAlive: relay?.extensionWorkerAlive ?? null,
|
|
1838
|
+
tab: tabOk,
|
|
1839
|
+
cdp: cdpOk,
|
|
1840
|
+
}, diagnosticError);
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1019
1844
|
showBanner();
|
|
1020
1845
|
log.box('DIAGNOSTICS');
|
|
1021
1846
|
|
|
1022
1847
|
// Test 1: Server
|
|
1023
|
-
const serverOk = await checkServer();
|
|
1024
1848
|
console.log(serverOk ? ` ${GREEN}✓${NC} ${B5}[1/4]${NC} Server` : ` ${RED}✗${NC} ${B5}[1/4]${NC} Server`);
|
|
1025
|
-
if (!serverOk) {
|
|
1026
|
-
log.info('Starting server...');
|
|
1027
|
-
await cmdStart();
|
|
1028
|
-
}
|
|
1029
1849
|
|
|
1030
1850
|
// Test 2: Extension
|
|
1031
|
-
const extOk = await checkExtension();
|
|
1032
1851
|
console.log(extOk ? ` ${GREEN}✓${NC} ${B5}[2/4]${NC} Extension` : ` ${RED}✗${NC} ${B5}[2/4]${NC} Extension`);
|
|
1033
1852
|
|
|
1034
1853
|
// Test 3: Tab
|
|
1035
|
-
const tabOk = await checkTab();
|
|
1036
1854
|
console.log(tabOk ? ` ${GREEN}✓${NC} ${B5}[3/4]${NC} Tab attached` : ` ${RED}✗${NC} ${B5}[3/4]${NC} No tabs`);
|
|
1037
1855
|
|
|
1038
1856
|
// Test 4: CDP command
|
|
1039
1857
|
if (tabOk) {
|
|
1040
|
-
|
|
1041
|
-
const result = await httpPost('/cdp', {
|
|
1042
|
-
method: 'Runtime.evaluate',
|
|
1043
|
-
params: { expression: '1+1', returnByValue: true }
|
|
1044
|
-
});
|
|
1045
|
-
const cdpOk = result.result?.value === 2;
|
|
1046
|
-
console.log(cdpOk ? `${GREEN}[4/4]${NC} CDP: OK` : `${RED}[4/4]${NC} CDP: FAIL`);
|
|
1047
|
-
} catch {
|
|
1048
|
-
console.log(`${RED}[4/4]${NC} CDP: FAIL`);
|
|
1049
|
-
}
|
|
1858
|
+
console.log(cdpOk ? `${GREEN}[4/4]${NC} CDP: OK` : `${RED}[4/4]${NC} CDP: FAIL${cdpError ? ` (${cdpError})` : ''}`);
|
|
1050
1859
|
} else {
|
|
1051
1860
|
console.log(`${YELLOW}[4/4]${NC} CDP: SKIPPED (no tab)`);
|
|
1052
1861
|
}
|
|
1053
1862
|
|
|
1054
1863
|
console.log('═══════════════════════════════════════');
|
|
1864
|
+
if (!healthy) process.exitCode = 1;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
// CWS extension id (override for unpacked/corp builds via GLIDER_EXTENSION_ID)
|
|
1868
|
+
const GLIDER_EXTENSION_ID = process.env.GLIDER_EXTENSION_ID || 'njbidokkffhgpofcejgcfcgcinmeoalj';
|
|
1869
|
+
const GLIDER_CWS_URL = `https://chromewebstore.google.com/detail/glider/${GLIDER_EXTENSION_ID}`;
|
|
1870
|
+
|
|
1871
|
+
function extensionWakeUrl() {
|
|
1872
|
+
return `chrome-extension://${GLIDER_EXTENSION_ID}/`;
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
function tryWakeExtensionWorker() {
|
|
1876
|
+
if (process.env.GLIDER_HEAL_NO_WAKE === '1') {
|
|
1877
|
+
return { attempted: false, reason: 'GLIDER_HEAL_NO_WAKE=1' };
|
|
1878
|
+
}
|
|
1879
|
+
if (!browserUiEnabled()) {
|
|
1880
|
+
return { attempted: false, reason: 'GLIDER_BROWSER_UI default off (no tab wake)' };
|
|
1881
|
+
}
|
|
1882
|
+
let browser;
|
|
1883
|
+
try {
|
|
1884
|
+
browser = getBrowserConfig();
|
|
1885
|
+
} catch (e) {
|
|
1886
|
+
return { attempted: false, reason: e.message };
|
|
1887
|
+
}
|
|
1888
|
+
if (!browserIsRunning(browser)) {
|
|
1889
|
+
return { attempted: false, reason: 'browser not running' };
|
|
1890
|
+
}
|
|
1891
|
+
try {
|
|
1892
|
+
createBrowserPage(browser, extensionWakeUrl());
|
|
1893
|
+
return { attempted: true, url: extensionWakeUrl(), browser: browser.name };
|
|
1894
|
+
} catch (e) {
|
|
1895
|
+
return { attempted: false, reason: e.message };
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
function doctorNextAction({ serverOk, socketOk, workerOk, targetCount, portOk }) {
|
|
1900
|
+
if (!serverOk) return 'glider start';
|
|
1901
|
+
if (!portOk) return `use port 19988 (CWS build) or set matching GLIDER_EXTENSION_ID; current=${PORT}`;
|
|
1902
|
+
if (!socketOk) return `install/enable Glider (${GLIDER_CWS_URL}); click icon; glider connect`;
|
|
1903
|
+
if (!workerOk) return 'glider heal # or click Glider icon / glider reload-ext';
|
|
1904
|
+
if (targetCount < 1) return 'glider connect';
|
|
1905
|
+
return null;
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
async function cmdDoctor() {
|
|
1909
|
+
let relay = null;
|
|
1910
|
+
try {
|
|
1911
|
+
relay = await httpGet('/status');
|
|
1912
|
+
} catch {}
|
|
1913
|
+
const serverOk = relay !== null;
|
|
1914
|
+
const socketOk = serverOk && relay.extension === true;
|
|
1915
|
+
const workerOk = extensionReady(relay);
|
|
1916
|
+
const targets = serverOk && socketOk ? await getTargets() : [];
|
|
1917
|
+
const portOk = PORT === 19988 || Boolean(process.env.GLIDER_EXTENSION_ID);
|
|
1918
|
+
let browserRunning = false;
|
|
1919
|
+
let browserName = null;
|
|
1920
|
+
try {
|
|
1921
|
+
const browser = getBrowserConfig();
|
|
1922
|
+
browserName = browser.name;
|
|
1923
|
+
browserRunning = browserIsRunning(browser);
|
|
1924
|
+
} catch {}
|
|
1925
|
+
const nextAction = doctorNextAction({
|
|
1926
|
+
serverOk,
|
|
1927
|
+
socketOk,
|
|
1928
|
+
workerOk,
|
|
1929
|
+
targetCount: targets.length,
|
|
1930
|
+
portOk,
|
|
1931
|
+
});
|
|
1932
|
+
const healthy = serverOk && workerOk && targets.length > 0 && portOk;
|
|
1933
|
+
const observation = {
|
|
1934
|
+
healthy,
|
|
1935
|
+
port: PORT,
|
|
1936
|
+
portMatchesCws: PORT === 19988,
|
|
1937
|
+
extensionId: GLIDER_EXTENSION_ID,
|
|
1938
|
+
cws: GLIDER_CWS_URL,
|
|
1939
|
+
server: serverOk,
|
|
1940
|
+
extension: socketOk,
|
|
1941
|
+
extensionWorkerAlive: relay?.extensionWorkerAlive ?? null,
|
|
1942
|
+
reconnecting: relay?.reconnecting === true,
|
|
1943
|
+
targetCount: targets.length,
|
|
1944
|
+
browser: browserName,
|
|
1945
|
+
browserRunning,
|
|
1946
|
+
nextAction,
|
|
1947
|
+
};
|
|
1948
|
+
|
|
1949
|
+
if (jsonOutput) {
|
|
1950
|
+
emitJson(healthy, observation, healthy ? null : (nextAction || 'unhealthy'));
|
|
1951
|
+
return;
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
showBanner();
|
|
1955
|
+
log.box('DOCTOR');
|
|
1956
|
+
console.log(serverOk ? ` ${GREEN}✓${NC} Relay :${PORT}` : ` ${RED}✗${NC} Relay down`);
|
|
1957
|
+
console.log(portOk ? ` ${GREEN}✓${NC} Port/extension id contract` : ` ${YELLOW}⚠${NC} Port ${PORT} ≠ CWS 19988 (set GLIDER_EXTENSION_ID if custom build)`);
|
|
1958
|
+
console.log(socketOk ? ` ${GREEN}✓${NC} Extension socket` : ` ${RED}✗${NC} Extension socket`);
|
|
1959
|
+
console.log(workerOk ? ` ${GREEN}✓${NC} Worker alive` : ` ${RED}✗${NC} Worker not alive`);
|
|
1960
|
+
console.log(targets.length > 0 ? ` ${GREEN}✓${NC} ${targets.length} target(s)` : ` ${YELLOW}⚠${NC} No targets`);
|
|
1961
|
+
if (browserName) {
|
|
1962
|
+
console.log(browserRunning ? ` ${GREEN}✓${NC} ${browserName} running` : ` ${YELLOW}⚠${NC} ${browserName} not running`);
|
|
1963
|
+
}
|
|
1964
|
+
if (nextAction) console.log(`\n next: ${CYAN}${nextAction}${NC}`);
|
|
1965
|
+
console.log();
|
|
1966
|
+
if (!healthy) process.exitCode = 1;
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
async function cmdHeal(args = []) {
|
|
1970
|
+
const clearPin = args.includes('--clear-pin') || process.env.GLIDER_HEAL_CLEAR_PIN === '1';
|
|
1971
|
+
const actions = [];
|
|
1972
|
+
let relay = null;
|
|
1973
|
+
|
|
1974
|
+
if (!await checkServer()) {
|
|
1975
|
+
await cmdStart({ render: false });
|
|
1976
|
+
actions.push({ step: 'start_relay', ok: true });
|
|
1977
|
+
try {
|
|
1978
|
+
await waitUntil(() => checkServer(), { timeoutMs: 5000, intervalMs: 50, label: 'relay ready' });
|
|
1979
|
+
} catch (e) {
|
|
1980
|
+
actions.push({ step: 'wait_relay', ok: false, error: e.message });
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
try {
|
|
1985
|
+
relay = await getRelayStatus();
|
|
1986
|
+
} catch {
|
|
1987
|
+
relay = null;
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
if (clearPin) {
|
|
1991
|
+
clearPersistedSession();
|
|
1992
|
+
actions.push({ step: 'clear_pin', ok: true });
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
if (!extensionReady(relay)) {
|
|
1996
|
+
const wake = tryWakeExtensionWorker();
|
|
1997
|
+
actions.push({ step: 'wake_extension', ...wake });
|
|
1998
|
+
if (wake.attempted) {
|
|
1999
|
+
try {
|
|
2000
|
+
await waitUntil(() => checkExtension(), { timeoutMs: 4000, intervalMs: 100, label: 'worker wake' });
|
|
2001
|
+
} catch {
|
|
2002
|
+
/* still dead - fall through */
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
try {
|
|
2006
|
+
relay = await getRelayStatus();
|
|
2007
|
+
} catch {
|
|
2008
|
+
relay = null;
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
// reload-ext only when worker can receive messages
|
|
2013
|
+
if (relay?.extension === true && extensionReady(relay) && Number(relay.targets || 0) === 0) {
|
|
2014
|
+
try {
|
|
2015
|
+
await requestActiveTabAttach();
|
|
2016
|
+
actions.push({ step: 'attach', ok: true });
|
|
2017
|
+
} catch (e) {
|
|
2018
|
+
actions.push({ step: 'attach', ok: false, error: e.message });
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
try {
|
|
2023
|
+
relay = await getRelayStatus();
|
|
2024
|
+
} catch {
|
|
2025
|
+
relay = null;
|
|
2026
|
+
}
|
|
2027
|
+
const serverOk = relay !== null;
|
|
2028
|
+
const workerOk = extensionReady(relay);
|
|
2029
|
+
const targets = serverOk && relay.extension === true ? await getTargets() : [];
|
|
2030
|
+
const nextAction = doctorNextAction({
|
|
2031
|
+
serverOk,
|
|
2032
|
+
socketOk: serverOk && relay.extension === true,
|
|
2033
|
+
workerOk,
|
|
2034
|
+
targetCount: targets.length,
|
|
2035
|
+
portOk: PORT === 19988 || Boolean(process.env.GLIDER_EXTENSION_ID),
|
|
2036
|
+
});
|
|
2037
|
+
const healthy = serverOk && workerOk && targets.length > 0;
|
|
2038
|
+
|
|
2039
|
+
const observation = {
|
|
2040
|
+
healthy,
|
|
2041
|
+
actions,
|
|
2042
|
+
server: serverOk,
|
|
2043
|
+
extension: !!relay?.extension,
|
|
2044
|
+
extensionWorkerAlive: relay?.extensionWorkerAlive ?? null,
|
|
2045
|
+
reconnecting: relay?.reconnecting === true,
|
|
2046
|
+
targetCount: targets.length,
|
|
2047
|
+
nextAction: healthy ? null : nextAction,
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
if (jsonOutput) {
|
|
2051
|
+
emitJson(healthy, observation, healthy ? null : (nextAction || 'heal incomplete'));
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
showBanner();
|
|
2056
|
+
log.box('HEAL');
|
|
2057
|
+
for (const a of actions) {
|
|
2058
|
+
const mark = a.ok === false || a.attempted === false ? YELLOW : GREEN;
|
|
2059
|
+
const detail = a.reason || a.error || a.url || '';
|
|
2060
|
+
console.log(` ${mark}•${NC} ${a.step}${detail ? ` ${DIM}${detail}${NC}` : ''}`);
|
|
2061
|
+
}
|
|
2062
|
+
console.log(workerOk ? ` ${GREEN}✓${NC} Worker alive` : ` ${RED}✗${NC} Worker not alive`);
|
|
2063
|
+
console.log(targets.length > 0 ? ` ${GREEN}✓${NC} ${targets.length} target(s)` : ` ${YELLOW}⚠${NC} No targets`);
|
|
2064
|
+
if (!healthy && nextAction) console.log(`\n next: ${CYAN}${nextAction}${NC}`);
|
|
2065
|
+
console.log();
|
|
2066
|
+
if (!healthy) process.exitCode = 1;
|
|
1055
2067
|
}
|
|
1056
2068
|
|
|
1057
2069
|
async function cmdTabs() {
|
|
@@ -1228,8 +2240,11 @@ async function cmdHtml(selector) {
|
|
|
1228
2240
|
method: 'Runtime.evaluate',
|
|
1229
2241
|
params: { expression, returnByValue: true }
|
|
1230
2242
|
});
|
|
1231
|
-
|
|
2243
|
+
const value = result.result?.value || '';
|
|
2244
|
+
if (jsonOutput) emitJson(true, value);
|
|
2245
|
+
else console.log(value);
|
|
1232
2246
|
} catch (e) {
|
|
2247
|
+
if (jsonOutput) emitJson(false, null, e.message);
|
|
1233
2248
|
log.fail(`HTML extraction failed: ${e.message}`);
|
|
1234
2249
|
process.exit(1);
|
|
1235
2250
|
}
|
|
@@ -1246,8 +2261,11 @@ async function cmdTitle() {
|
|
|
1246
2261
|
method: 'Runtime.evaluate',
|
|
1247
2262
|
params: { expression: 'document.title', returnByValue: true }
|
|
1248
2263
|
});
|
|
1249
|
-
|
|
2264
|
+
const value = result.result?.value || '';
|
|
2265
|
+
if (jsonOutput) emitJson(true, value);
|
|
2266
|
+
else console.log(value);
|
|
1250
2267
|
} catch (e) {
|
|
2268
|
+
if (jsonOutput) emitJson(false, null, e.message);
|
|
1251
2269
|
log.fail(`Title extraction failed: ${e.message}`);
|
|
1252
2270
|
process.exit(1);
|
|
1253
2271
|
}
|
|
@@ -1332,31 +2350,35 @@ async function cmdTargets() {
|
|
|
1332
2350
|
}
|
|
1333
2351
|
|
|
1334
2352
|
async function cmdUseSession(arg, opts = []) {
|
|
1335
|
-
|
|
1336
|
-
const
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
const raw = await httpGet('/targets');
|
|
1340
|
-
const targets = Array.isArray(raw) ? raw : [];
|
|
1341
|
-
const hit = targets.find((t) => {
|
|
1342
|
-
const u = t.url || t.targetInfo?.url || '';
|
|
1343
|
-
return u.includes(needle);
|
|
1344
|
-
});
|
|
1345
|
-
if (!hit) {
|
|
1346
|
-
const msg = `no target matching --url ${needle}`;
|
|
1347
|
-
if (jsonOutput) emitJson(false, null, msg);
|
|
1348
|
-
log.fail(msg);
|
|
1349
|
-
process.exit(1);
|
|
1350
|
-
}
|
|
1351
|
-
sessionId = hit.sessionId;
|
|
1352
|
-
}
|
|
1353
|
-
if (!sessionId) {
|
|
2353
|
+
const argv = [arg, ...opts].filter((value) => value !== undefined);
|
|
2354
|
+
const parsed = parseFlags(argv, { url: { type: 'string' } });
|
|
2355
|
+
const requestedSession = parsed._[0] || null;
|
|
2356
|
+
if (!requestedSession && !parsed.url) {
|
|
1354
2357
|
log.fail('Usage: glider use-session <sessionId> | glider use-session --url <host-fragment>');
|
|
1355
2358
|
process.exit(1);
|
|
1356
2359
|
}
|
|
2360
|
+
const raw = await httpGet('/targets');
|
|
2361
|
+
const targets = Array.isArray(raw) ? raw : [];
|
|
2362
|
+
const hit = parsed.url
|
|
2363
|
+
? targets.find((target) => (target.url || target.targetInfo?.url || '').includes(parsed.url))
|
|
2364
|
+
: targets.find((target) => target.sessionId === requestedSession || target.targetId === requestedSession);
|
|
2365
|
+
if (!hit) {
|
|
2366
|
+
const message = parsed.url
|
|
2367
|
+
? `no live target matching --url ${parsed.url}`
|
|
2368
|
+
: `session is not live: ${requestedSession}`;
|
|
2369
|
+
if (jsonOutput) emitJson(false, null, message);
|
|
2370
|
+
log.fail(message);
|
|
2371
|
+
process.exit(1);
|
|
2372
|
+
}
|
|
2373
|
+
const sessionId = hit.sessionId;
|
|
1357
2374
|
persistSession(sessionId);
|
|
1358
2375
|
if (jsonOutput) {
|
|
1359
|
-
emitJson(true, {
|
|
2376
|
+
emitJson(true, {
|
|
2377
|
+
sessionId,
|
|
2378
|
+
targetId: hit.targetId,
|
|
2379
|
+
url: hit.url || hit.targetInfo?.url || '',
|
|
2380
|
+
persisted: SESSION_STORE,
|
|
2381
|
+
});
|
|
1360
2382
|
} else {
|
|
1361
2383
|
log.ok(`Active session: ${sessionId}`);
|
|
1362
2384
|
console.log(SESSION_STORE);
|
|
@@ -1378,14 +2400,10 @@ async function cmdFetch(url, opts = []) {
|
|
|
1378
2400
|
process.exit(1);
|
|
1379
2401
|
}
|
|
1380
2402
|
|
|
2403
|
+
if (!await ensureConnected()) process.exit(1);
|
|
1381
2404
|
if (!jsonOutput) log.info(`Fetching: ${url}`);
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
for (let i = 0; i < opts.length; i++) {
|
|
1385
|
-
if (opts[i] === '--output' || opts[i] === '-o') {
|
|
1386
|
-
outputFile = opts[++i];
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
2405
|
+
const parsed = parseFlags(opts, { output: { short: 'o', type: 'string' } });
|
|
2406
|
+
const outputFile = parsed.output || null;
|
|
1389
2407
|
|
|
1390
2408
|
try {
|
|
1391
2409
|
const result = await httpPost('/cdp', {
|
|
@@ -1427,23 +2445,25 @@ async function cmdCorsFetch(url, opts = []) {
|
|
|
1427
2445
|
log.fail('Usage: glider cfetch <url> [--output file] [--method POST] [--body JSON]');
|
|
1428
2446
|
process.exit(1);
|
|
1429
2447
|
}
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
for (let i = 0; i < opts.length; i++) {
|
|
1438
|
-
if (opts[i] === '--output' || opts[i] === '-o') {
|
|
1439
|
-
outputFile = opts[++i];
|
|
1440
|
-
} else if (opts[i] === '--method' || opts[i] === '-X') {
|
|
1441
|
-
method = opts[++i];
|
|
1442
|
-
} else if (opts[i] === '--body' || opts[i] === '-d') {
|
|
1443
|
-
body = opts[++i];
|
|
1444
|
-
}
|
|
2448
|
+
|
|
2449
|
+
try {
|
|
2450
|
+
assertUrlAllowed(url, allowedDomainList, 'cfetch');
|
|
2451
|
+
} catch (error) {
|
|
2452
|
+
if (jsonOutput) emitJson(false, null, error.message);
|
|
2453
|
+
log.fail(error.message);
|
|
2454
|
+
process.exit(1);
|
|
1445
2455
|
}
|
|
1446
|
-
|
|
2456
|
+
|
|
2457
|
+
const parsed = parseFlags(opts, {
|
|
2458
|
+
output: { short: 'o', type: 'string' },
|
|
2459
|
+
method: { short: 'X', type: 'string', default: 'GET' },
|
|
2460
|
+
body: { short: 'd', type: 'string' },
|
|
2461
|
+
});
|
|
2462
|
+
const outputFile = parsed.output || null;
|
|
2463
|
+
const method = parsed.method.toUpperCase();
|
|
2464
|
+
const body = parsed.body ?? null;
|
|
2465
|
+
if (!jsonOutput) log.info(`CORS Fetch: ${url}`);
|
|
2466
|
+
|
|
1447
2467
|
try {
|
|
1448
2468
|
// Browser-typical Accept by default (unlocks Yammer-family 406-strict endpoints).
|
|
1449
2469
|
const defaultAccept = 'application/json, text/plain, */*';
|
|
@@ -1466,9 +2486,13 @@ async function cmdCorsFetch(url, opts = []) {
|
|
|
1466
2486
|
payload = result?.result ?? result;
|
|
1467
2487
|
}
|
|
1468
2488
|
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
2489
|
+
const fetchError = result?.error || payload?.error;
|
|
2490
|
+
if (fetchError) {
|
|
2491
|
+
const message = typeof fetchError === 'object'
|
|
2492
|
+
? fetchError.message || JSON.stringify(fetchError)
|
|
2493
|
+
: String(fetchError);
|
|
2494
|
+
emitCommandFailure(`CORS Fetch failed: ${message}`);
|
|
2495
|
+
return;
|
|
1472
2496
|
}
|
|
1473
2497
|
|
|
1474
2498
|
// cli_gap: cfetch_empty_response_crash - data may be undefined/null on empty bodies
|
|
@@ -1478,13 +2502,15 @@ async function cmdCorsFetch(url, opts = []) {
|
|
|
1478
2502
|
|
|
1479
2503
|
if (outputFile) {
|
|
1480
2504
|
fs.writeFileSync(outputFile, output);
|
|
1481
|
-
|
|
2505
|
+
if (jsonOutput) emitJson(true, { url, status: payload?.status, ok: payload?.ok, output: outputFile });
|
|
2506
|
+
else log.ok(`Saved to ${outputFile} (status: ${payload?.status})`);
|
|
2507
|
+
} else if (jsonOutput) {
|
|
2508
|
+
emitJson(true, { url, status: payload?.status, ok: payload?.ok, data });
|
|
1482
2509
|
} else {
|
|
1483
2510
|
console.log(output);
|
|
1484
2511
|
}
|
|
1485
2512
|
} catch (e) {
|
|
1486
|
-
|
|
1487
|
-
process.exit(1);
|
|
2513
|
+
emitCommandFailure(`CORS Fetch failed: ${e.message}`);
|
|
1488
2514
|
}
|
|
1489
2515
|
}
|
|
1490
2516
|
|
|
@@ -1611,8 +2637,9 @@ async function cmdThaw(opts = []) {
|
|
|
1611
2637
|
}
|
|
1612
2638
|
}
|
|
1613
2639
|
|
|
2640
|
+
const failed = results.filter((result) => !result.thawed);
|
|
1614
2641
|
if (jsonOutput) {
|
|
1615
|
-
emitJson(
|
|
2642
|
+
emitJson(failed.length === 0, all ? { thawed: results } : results[0], failed.length ? `${failed.length} target(s) failed to thaw` : null);
|
|
1616
2643
|
} else {
|
|
1617
2644
|
for (const r of results) {
|
|
1618
2645
|
if (!r.thawed) { log.fail(`thaw failed (${r.sessionId}): ${r.error}`); continue; }
|
|
@@ -1620,6 +2647,7 @@ async function cmdThaw(opts = []) {
|
|
|
1620
2647
|
if (verify) extra = ` - visibilityState=${r.visibilityState} asyncAlive=${r.asyncAlive}`;
|
|
1621
2648
|
log.ok(`thawed ${r.sessionId}${extra}`);
|
|
1622
2649
|
}
|
|
2650
|
+
if (failed.length) process.exitCode = 1;
|
|
1623
2651
|
}
|
|
1624
2652
|
}
|
|
1625
2653
|
|
|
@@ -1735,8 +2763,9 @@ async function cmdFreeze(opts = []) {
|
|
|
1735
2763
|
}
|
|
1736
2764
|
}
|
|
1737
2765
|
|
|
2766
|
+
const failed = results.filter((result) => !result.frozen && !result.skipped);
|
|
1738
2767
|
if (jsonOutput) {
|
|
1739
|
-
emitJson(
|
|
2768
|
+
emitJson(failed.length === 0, all ? { frozen: results, totalReclaimedMb: totalReclaimed } : results[0], failed.length ? `${failed.length} target(s) failed to freeze` : null);
|
|
1740
2769
|
} else {
|
|
1741
2770
|
for (const r of results) {
|
|
1742
2771
|
if (r.skipped) { log.info(`skipped ${r.sessionId} (${r.skipped})`); continue; }
|
|
@@ -1746,6 +2775,7 @@ async function cmdFreeze(opts = []) {
|
|
|
1746
2775
|
log.ok(`froze ${r.sessionId}${r.pid ? ` pid=${r.pid}` : ''}${extra}`);
|
|
1747
2776
|
}
|
|
1748
2777
|
if (all && verify) log.ok(`total heapΔ (V8 GC of quiesced tabs): ${totalReclaimed}MB across ${results.filter(r => r.frozen).length} tab(s)`);
|
|
2778
|
+
if (failed.length) process.exitCode = 1;
|
|
1749
2779
|
}
|
|
1750
2780
|
}
|
|
1751
2781
|
|
|
@@ -2506,13 +3536,15 @@ ${B5}USAGE${NC}
|
|
|
2506
3536
|
${DIM}GLIDER_SESSION_ID=session-N${NC} ${DIM}pin tab for all /cdp commands${NC}
|
|
2507
3537
|
|
|
2508
3538
|
${B5}SETUP${NC}
|
|
2509
|
-
${BW}install${NC} Install
|
|
3539
|
+
${BW}install${NC} Install detached relay supervisor ${DIM}(current session, auto-restarts)${NC}
|
|
2510
3540
|
${BW}uninstall${NC} Remove daemon
|
|
2511
3541
|
${BW}update${NC} Update to latest version
|
|
2512
|
-
${BW}connect${NC} Connect to browser ${DIM}(
|
|
3542
|
+
${BW}connect${NC} Connect to browser ${DIM}(uses $GLIDER_HOME/config/browser.json)${NC}
|
|
2513
3543
|
|
|
2514
3544
|
${B5}STATUS${NC}
|
|
2515
3545
|
${BW}status${NC} Check server, extension, tabs
|
|
3546
|
+
${BW}doctor${NC} Relay + SW + targets + next action ${DIM}(--json)${NC}
|
|
3547
|
+
${BW}heal${NC} [--clear-pin] Ensure relay, wake SW best-effort, reattach
|
|
2516
3548
|
${BW}browser${NC} Show browser config ${DIM}(name, path, processName, or use key)${NC}
|
|
2517
3549
|
${BW}use${NC} <key> Set browser by registry key ${DIM}(e.g. arc, brave, chrome)${NC}
|
|
2518
3550
|
${BW}test${NC} Run diagnostics
|
|
@@ -2574,7 +3606,7 @@ ${B5}LOOP OPTIONS${NC}
|
|
|
2574
3606
|
|
|
2575
3607
|
${B5}EXAMPLES${NC}
|
|
2576
3608
|
${DIM}$${NC} glider install ${DIM}# one-time setup${NC}
|
|
2577
|
-
${DIM}$${NC} glider connect ${DIM}# connect to
|
|
3609
|
+
${DIM}$${NC} glider connect ${DIM}# connect to the configured Chromium browser${NC}
|
|
2578
3610
|
${DIM}$${NC} glider goto "https://x.com" ${DIM}# navigate${NC}
|
|
2579
3611
|
${DIM}$${NC} glider eval "document.title"${DIM}# run JS${NC}
|
|
2580
3612
|
${DIM}$${NC} glider run scrape.yaml ${DIM}# run task${NC}
|
|
@@ -2610,10 +3642,10 @@ ${YELLOW}RALPH WIGGUM PATTERN:${NC}
|
|
|
2610
3642
|
|
|
2611
3643
|
${YELLOW}REQUIREMENTS:${NC}
|
|
2612
3644
|
- Node.js 18+
|
|
2613
|
-
- Glider Chrome
|
|
3645
|
+
- Glider extension from Chrome Web Store connected in a Chromium browser
|
|
2614
3646
|
|
|
2615
3647
|
${YELLOW}DOMAIN EXTENSIONS:${NC}
|
|
2616
|
-
Add custom domain commands via
|
|
3648
|
+
Add custom domain commands via $GLIDER_HOME/config/domains.json:
|
|
2617
3649
|
{
|
|
2618
3650
|
"mysite": { "url": "https://mysite.com/dashboard" },
|
|
2619
3651
|
"mytool": { "script": "~/scripts/mytool.sh" }
|
|
@@ -2649,7 +3681,7 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
|
|
|
2649
3681
|
pluginVerbs.push({ verb, def });
|
|
2650
3682
|
}
|
|
2651
3683
|
if (pluginVerbs.length > 0) {
|
|
2652
|
-
console.log(`${YELLOW}PLUGINS:${NC} (from
|
|
3684
|
+
console.log(`${YELLOW}PLUGINS:${NC} (from $GLIDER_HOME/plugins/)`);
|
|
2653
3685
|
for (const { verb, def } of pluginVerbs) {
|
|
2654
3686
|
const desc = (Array.isArray(def.help) ? def.help.find(l => !/^Usage:/i.test(l)) : def.help) || '(no description)';
|
|
2655
3687
|
const shortDesc = String(desc).replace(/^\s+/, '').slice(0, 60);
|
|
@@ -2661,7 +3693,7 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
|
|
|
2661
3693
|
console.log(` ${GREEN}${'read'.padEnd(16)}${NC} ${DIM}read attr/prop/text/html/value; --all --count --exists --visible --enabled${NC}`);
|
|
2662
3694
|
console.log(` ${GREEN}${'click'.padEnd(16)}${NC} ${DIM}--text --contains --regex --nth --role --inside --wait --double --right --hold${NC}`);
|
|
2663
3695
|
console.log(` ${GREEN}${'type'.padEnd(16)}${NC} ${DIM}--editor auto|ckeditor|tinymce|prosemirror|monaco|slate|contentEditable ; --file --clear-first --commit${NC}`);
|
|
2664
|
-
console.log(` ${GREEN}${'wait'.padEnd(16)}${NC} ${DIM}--selector --text --gone --matches --stable --url-matches --timeout${NC}`);
|
|
3696
|
+
console.log(` ${GREEN}${'wait'.padEnd(16)}${NC} ${DIM}--selector --text --gone --matches --stable --url-matches --timeout; --network-idle is partial${NC}`);
|
|
2665
3697
|
console.log(` ${GREEN}${'hover'.padEnd(16)}${NC} ${DIM}hover a target${NC}`);
|
|
2666
3698
|
console.log(` ${GREEN}${'focus/blur'.padEnd(16)}${NC} ${DIM}focus/blur an element${NC}`);
|
|
2667
3699
|
console.log(` ${GREEN}${'scroll'.padEnd(16)}${NC} ${DIM}scroll to <sel> | by <dx> <dy> | until <sel>${NC}`);
|
|
@@ -2682,9 +3714,9 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
|
|
|
2682
3714
|
console.log(` ${GREEN}${'cookies'.padEnd(16)}${NC} ${DIM}(read: no flags) | --set NAME=VAL --host H | --delete NAME --host H${NC}`);
|
|
2683
3715
|
console.log(` ${GREEN}${'history'.padEnd(16)}${NC} ${DIM}back | forward | reload${NC}`);
|
|
2684
3716
|
console.log(` ${GREEN}${'dialog'.padEnd(16)}${NC} ${DIM}dialog auto accept|dismiss${NC}`);
|
|
2685
|
-
console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}
|
|
3717
|
+
console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}tail | dump (partial: exits 2 until event streaming lands)${NC}`);
|
|
2686
3718
|
console.log(` ${GREEN}${'pdf'.padEnd(16)}${NC} ${DIM}[PATH] [--landscape] [--margin N] [--scale F]${NC}`);
|
|
2687
|
-
console.log(` ${GREEN}${'mock'.padEnd(16)}${NC} ${DIM}<url-glob> --status N --body FILE | mock clear${NC}`);
|
|
3719
|
+
console.log(` ${GREEN}${'mock'.padEnd(16)}${NC} ${DIM}<url-glob> --status N --body FILE (partial; exits 2) | mock clear${NC}`);
|
|
2688
3720
|
console.log(` ${GREEN}${'a11y'.padEnd(16)}${NC} ${DIM}Accessibility.getFullAXTree (snapshot --a11y flag equivalent)${NC}`);
|
|
2689
3721
|
console.log(` ${GREEN}${'frozen'.padEnd(16)}${NC} ${DIM}detect if tab is macrotask-frozen (hidden); exit 1 = frozen${NC}`);
|
|
2690
3722
|
console.log(` ${GREEN}${'thaw'.padEnd(16)}${NC} ${DIM}un-throttle a frozen/hidden tab in place (--all --verify); aka unfreeze/wake${NC}`);
|
|
@@ -2789,7 +3821,7 @@ const GLIDER_PLUGIN_REGISTRY = new Map(); // verb → plugin def
|
|
|
2789
3821
|
function pluginDirs() {
|
|
2790
3822
|
const dirs = [];
|
|
2791
3823
|
if (process.env.GLIDER_PLUGIN_DIR) dirs.push(process.env.GLIDER_PLUGIN_DIR);
|
|
2792
|
-
dirs.push(path.join(
|
|
3824
|
+
dirs.push(path.join(GLIDER_HOME, 'plugins'));
|
|
2793
3825
|
return dirs.filter(d => { try { return fs.statSync(d).isDirectory(); } catch { return false; } });
|
|
2794
3826
|
}
|
|
2795
3827
|
|
|
@@ -2955,22 +3987,49 @@ function parseJsonPluginArgs(argv, schema) {
|
|
|
2955
3987
|
function parseFlags(argv, specs) {
|
|
2956
3988
|
// specs: { longName: {short?, type: 'boolean'|'string'|'int'|'float', default?} }
|
|
2957
3989
|
const out = { _: [] };
|
|
3990
|
+
Object.defineProperty(out, '_provided', { value: new Set(), enumerable: false });
|
|
2958
3991
|
for (const k of Object.keys(specs)) if ('default' in specs[k]) out[k] = specs[k].default;
|
|
2959
3992
|
const shortMap = {};
|
|
2960
3993
|
for (const [k, s] of Object.entries(specs)) if (s.short) shortMap['-' + s.short] = k;
|
|
2961
3994
|
for (let i = 0; i < argv.length; i++) {
|
|
2962
3995
|
const a = argv[i];
|
|
3996
|
+
let inlineValue;
|
|
3997
|
+
let flagToken = a;
|
|
3998
|
+
if (a.startsWith('--') && a.includes('=')) {
|
|
3999
|
+
const eq = a.indexOf('=');
|
|
4000
|
+
flagToken = a.slice(0, eq);
|
|
4001
|
+
inlineValue = a.slice(eq + 1);
|
|
4002
|
+
}
|
|
2963
4003
|
let key = null;
|
|
2964
|
-
if (
|
|
2965
|
-
else if (shortMap[
|
|
4004
|
+
if (flagToken.startsWith('--')) key = flagToken.slice(2);
|
|
4005
|
+
else if (shortMap[flagToken]) key = shortMap[flagToken];
|
|
2966
4006
|
if (key && specs[key]) {
|
|
2967
4007
|
const s = specs[key];
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
4008
|
+
out._provided.add(key);
|
|
4009
|
+
if (s.type === 'boolean') {
|
|
4010
|
+
if (inlineValue === undefined) out[key] = true;
|
|
4011
|
+
else if (inlineValue === 'true') out[key] = true;
|
|
4012
|
+
else if (inlineValue === 'false') out[key] = false;
|
|
4013
|
+
else throw new Error(`${flagToken} expects true or false`);
|
|
4014
|
+
} else {
|
|
4015
|
+
let value = inlineValue;
|
|
4016
|
+
if (value === undefined) {
|
|
4017
|
+
const next = argv[i + 1];
|
|
4018
|
+
if (next === undefined || next.startsWith('--') || shortMap[next]) {
|
|
4019
|
+
throw new Error(`${flagToken} requires a value`);
|
|
4020
|
+
}
|
|
4021
|
+
value = argv[++i];
|
|
4022
|
+
}
|
|
4023
|
+
if (value === '') throw new Error(`${flagToken} requires a value`);
|
|
4024
|
+
if (s.type === 'int') {
|
|
4025
|
+
if (!/^-?\d+$/.test(value)) throw new Error(`${flagToken} expects an integer`);
|
|
4026
|
+
out[key] = parseInt(value, 10);
|
|
4027
|
+
} else if (s.type === 'float') {
|
|
4028
|
+
if (value.trim() === '' || !Number.isFinite(Number(value))) throw new Error(`${flagToken} expects a number`);
|
|
4029
|
+
out[key] = parseFloat(value);
|
|
4030
|
+
} else {
|
|
4031
|
+
out[key] = value;
|
|
4032
|
+
}
|
|
2974
4033
|
}
|
|
2975
4034
|
} else {
|
|
2976
4035
|
out._.push(a);
|
|
@@ -2979,6 +4038,13 @@ function parseFlags(argv, specs) {
|
|
|
2979
4038
|
return out;
|
|
2980
4039
|
}
|
|
2981
4040
|
|
|
4041
|
+
function assertExclusiveFlags(opts, names) {
|
|
4042
|
+
const present = names.filter((name) => opts._provided.has(name));
|
|
4043
|
+
if (present.length > 1) {
|
|
4044
|
+
throw new Error(`Mutually exclusive flags: ${present.map((name) => `--${name}`).join(', ')}`);
|
|
4045
|
+
}
|
|
4046
|
+
}
|
|
4047
|
+
|
|
2982
4048
|
// --- guard: allow-list check + auto-connect --------------------------
|
|
2983
4049
|
async function _guardAndConnect(action) {
|
|
2984
4050
|
if (!await ensureConnected()) process.exit(1);
|
|
@@ -3019,6 +4085,7 @@ async function cmdRead(argv) {
|
|
|
3019
4085
|
visible: { type: 'boolean' },
|
|
3020
4086
|
enabled: { type: 'boolean' },
|
|
3021
4087
|
});
|
|
4088
|
+
assertExclusiveFlags(opts, ['attr', 'prop', 'text', 'html', 'value', 'count', 'exists', 'visible', 'enabled']);
|
|
3022
4089
|
const sel = opts._[0];
|
|
3023
4090
|
if (!sel) { log.fail('Usage: glider read <selector> [--attr X | --prop Y | --text | --html | --value | --all | --count | --exists | --visible | --enabled]'); process.exit(1); }
|
|
3024
4091
|
await _guardAndConnect('read');
|
|
@@ -3386,9 +4453,20 @@ async function cmdWait(argv) {
|
|
|
3386
4453
|
'url-changes-from': { type: 'string' },
|
|
3387
4454
|
timeout: { type: 'int', default: 10000 }, poll: { type: 'int', default: 200 },
|
|
3388
4455
|
});
|
|
4456
|
+
assertExclusiveFlags(opts, ['selector', 'gone', 'matches', 'network-idle', 'url-matches', 'url-changes-from']);
|
|
4457
|
+
if (opts._provided.has('text') && !opts.selector) throw new Error('--text requires --selector');
|
|
4458
|
+
if (opts._provided.has('stable') && !opts.selector) throw new Error('--stable requires --selector');
|
|
4459
|
+
if (opts._provided.has('network-idle')) {
|
|
4460
|
+
failUnsupported('wait --network-idle', 'the relay does not yet persist Network event state');
|
|
4461
|
+
}
|
|
3389
4462
|
const positional = opts._[0];
|
|
4463
|
+
const conditionFlags = [
|
|
4464
|
+
'selector', 'text', 'gone', 'matches', 'stable',
|
|
4465
|
+
'network-idle', 'url-matches', 'url-changes-from',
|
|
4466
|
+
];
|
|
4467
|
+
const conditionProvided = conditionFlags.some((flag) => opts._provided.has(flag));
|
|
3390
4468
|
// Back-compat: bare number = sleep in seconds
|
|
3391
|
-
if (positional && /^\d+(\.\d+)?$/.test(positional) && !
|
|
4469
|
+
if (positional && /^\d+(\.\d+)?$/.test(positional) && !conditionProvided) {
|
|
3392
4470
|
await new Promise(r => setTimeout(r, parseFloat(positional) * 1000));
|
|
3393
4471
|
if (jsonOutput) emitJson(true, { slept_ms: parseFloat(positional) * 1000 });
|
|
3394
4472
|
return;
|
|
@@ -3509,20 +4587,77 @@ async function cmdDrag(argv) {
|
|
|
3509
4587
|
})()`);
|
|
3510
4588
|
const v = r.result?.value;
|
|
3511
4589
|
if (v?.error) { log.fail(v.error); process.exit(1); }
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
const
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
4590
|
+
const dropMarker = `__gliderDrop_${process.pid}_${Date.now()}_${Math.random().toString(16).slice(2)}`;
|
|
4591
|
+
await _rtEval(`(() => {
|
|
4592
|
+
const state = { dropped: false };
|
|
4593
|
+
state.handler = () => { state.dropped = true; };
|
|
4594
|
+
document.addEventListener('drop', state.handler, true);
|
|
4595
|
+
window[${JSON.stringify(dropMarker)}] = state;
|
|
4596
|
+
})()`);
|
|
4597
|
+
let mechanism = 'cdp';
|
|
4598
|
+
let mouseDown = false;
|
|
4599
|
+
try {
|
|
4600
|
+
await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.sx, y: v.sy, button: 'left', buttons: 1, clickCount: 1 } });
|
|
4601
|
+
mouseDown = true;
|
|
4602
|
+
for (let i = 1; i <= opts.steps; i++) {
|
|
4603
|
+
const x = v.sx + Math.round((v.dx - v.sx) * i / opts.steps);
|
|
4604
|
+
const y = v.sy + Math.round((v.dy - v.sy) * i / opts.steps);
|
|
4605
|
+
await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseMoved', x, y, button: 'left', buttons: 1 } });
|
|
4606
|
+
await new Promise((resolve) => setTimeout(resolve, 16));
|
|
4607
|
+
}
|
|
4608
|
+
const dragData = {
|
|
4609
|
+
items: [{ mimeType: 'text/plain', data: 'glider' }],
|
|
4610
|
+
dragOperationsMask: 1,
|
|
4611
|
+
};
|
|
4612
|
+
await httpPost('/cdp', { method: 'Input.dispatchDragEvent', params: { type: 'dragEnter', x: v.dx, y: v.dy, data: dragData } });
|
|
4613
|
+
await httpPost('/cdp', { method: 'Input.dispatchDragEvent', params: { type: 'dragOver', x: v.dx, y: v.dy, data: dragData } });
|
|
4614
|
+
await httpPost('/cdp', { method: 'Input.dispatchDragEvent', params: { type: 'drop', x: v.dx, y: v.dy, data: dragData } });
|
|
4615
|
+
await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.dx, y: v.dy, button: 'left', buttons: 0, clickCount: 1 } });
|
|
4616
|
+
mouseDown = false;
|
|
4617
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
4618
|
+
const delivered = await _rtEval(`!!window[${JSON.stringify(dropMarker)}]?.dropped`);
|
|
4619
|
+
if (delivered.result?.value !== true) {
|
|
4620
|
+
mechanism = 'html5-fallback';
|
|
4621
|
+
const fallback = await _rtEval(`(() => {
|
|
4622
|
+
const src = document.querySelector(${JSON.stringify(src)});
|
|
4623
|
+
const dst = document.querySelector(${JSON.stringify(dst)});
|
|
4624
|
+
if (!src || !dst) return { error: 'src or dst disappeared during drag' };
|
|
4625
|
+
const dataTransfer = new DataTransfer();
|
|
4626
|
+
dataTransfer.setData('text/plain', 'glider');
|
|
4627
|
+
const event = (type, target, x, y) => target.dispatchEvent(new DragEvent(type, {
|
|
4628
|
+
bubbles: true,
|
|
4629
|
+
cancelable: true,
|
|
4630
|
+
clientX: x,
|
|
4631
|
+
clientY: y,
|
|
4632
|
+
dataTransfer,
|
|
4633
|
+
}));
|
|
4634
|
+
event('dragstart', src, ${v.sx}, ${v.sy});
|
|
4635
|
+
event('dragenter', dst, ${v.dx}, ${v.dy});
|
|
4636
|
+
event('dragover', dst, ${v.dx}, ${v.dy});
|
|
4637
|
+
event('drop', dst, ${v.dx}, ${v.dy});
|
|
4638
|
+
event('dragend', src, ${v.dx}, ${v.dy});
|
|
4639
|
+
return { dispatched: true };
|
|
4640
|
+
})()`);
|
|
4641
|
+
if (fallback.result?.value?.error) throw new Error(fallback.result.value.error);
|
|
4642
|
+
}
|
|
4643
|
+
} finally {
|
|
4644
|
+
if (mouseDown) {
|
|
4645
|
+
await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.dx, y: v.dy, button: 'left', buttons: 0, clickCount: 1 } });
|
|
4646
|
+
}
|
|
4647
|
+
await _rtEval(`(() => {
|
|
4648
|
+
const state = window[${JSON.stringify(dropMarker)}];
|
|
4649
|
+
if (state?.handler) document.removeEventListener('drop', state.handler, true);
|
|
4650
|
+
delete window[${JSON.stringify(dropMarker)}];
|
|
4651
|
+
})()`);
|
|
4652
|
+
}
|
|
4653
|
+
if (jsonOutput) emitJson(true, { dragged: {from: [v.sx,v.sy], to: [v.dx,v.dy]}, mechanism });
|
|
3520
4654
|
else log.ok(`Dragged ${v.sx},${v.sy} -> ${v.dx},${v.dy}`);
|
|
3521
4655
|
}
|
|
3522
4656
|
|
|
3523
4657
|
// --- WAVE 2: cmdSelect ----------------------------------------------
|
|
3524
4658
|
async function cmdSelect(argv) {
|
|
3525
4659
|
const opts = parseFlags(argv, { 'by-text': { type: 'string' }, 'by-value': { type: 'string' }, nth: { type: 'int', default: 0 } });
|
|
4660
|
+
assertExclusiveFlags(opts, ['by-text', 'by-value', 'nth']);
|
|
3526
4661
|
const sel = opts._[0];
|
|
3527
4662
|
if (!sel || (!opts['by-text'] && !opts['by-value'] && opts.nth === undefined)) {
|
|
3528
4663
|
log.fail('Usage: glider select <selector> --by-text S | --by-value V | --nth N'); process.exit(1);
|
|
@@ -3582,9 +4717,19 @@ async function cmdEvalV2(argv) {
|
|
|
3582
4717
|
// So we re-walk argv for all --arg / --arg-file occurrences.
|
|
3583
4718
|
const args = {};
|
|
3584
4719
|
for (let i = 0; i < argv.length; i++) {
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
4720
|
+
let argSpec = null;
|
|
4721
|
+
let fileSpec = null;
|
|
4722
|
+
if (argv[i] === '--arg' && argv[i + 1]) argSpec = argv[++i];
|
|
4723
|
+
else if (argv[i].startsWith('--arg=')) argSpec = argv[i].slice('--arg='.length);
|
|
4724
|
+
else if (argv[i] === '--arg-file' && argv[i + 1]) fileSpec = argv[++i];
|
|
4725
|
+
else if (argv[i].startsWith('--arg-file=')) fileSpec = argv[i].slice('--arg-file='.length);
|
|
4726
|
+
if (argSpec !== null) {
|
|
4727
|
+
const [k, ...rest] = argSpec.split('=');
|
|
4728
|
+
if (!k || rest.length === 0) throw new Error('--arg expects K=V');
|
|
4729
|
+
args[k] = rest.join('=');
|
|
4730
|
+
} else if (fileSpec !== null) {
|
|
4731
|
+
const spec = fileSpec; const [k, ...rest] = spec.split('='); const path = rest.join('=');
|
|
4732
|
+
if (!k || !path) throw new Error('--arg-file expects K=@path');
|
|
3588
4733
|
const p = path.replace(/^@/, '');
|
|
3589
4734
|
args[k] = fs.readFileSync(p, 'utf8');
|
|
3590
4735
|
}
|
|
@@ -3610,6 +4755,7 @@ async function cmdScreenshotV2(argv) {
|
|
|
3610
4755
|
'full-page': { type: 'boolean' }, format: { type: 'string', default: 'png' },
|
|
3611
4756
|
pad: { type: 'int', default: 0 },
|
|
3612
4757
|
});
|
|
4758
|
+
assertExclusiveFlags(opts, ['selector', 'clip', 'full-page']);
|
|
3613
4759
|
const outPath = opts._[0] || `/tmp/glider-screenshot-${Date.now()}.${opts.format}`;
|
|
3614
4760
|
if (!await ensureConnected()) process.exit(1);
|
|
3615
4761
|
const params = { format: opts.format };
|
|
@@ -3635,24 +4781,7 @@ async function cmdScreenshotV2(argv) {
|
|
|
3635
4781
|
|
|
3636
4782
|
// --- WAVE 2: session_liveness_probe (upgrade cmdUseSession) ---
|
|
3637
4783
|
async function cmdUseSessionV2(arg, opts = []) {
|
|
3638
|
-
|
|
3639
|
-
try {
|
|
3640
|
-
await cmdUseSession(arg, opts);
|
|
3641
|
-
return;
|
|
3642
|
-
} catch (_) { /* fall through to re-probe */ }
|
|
3643
|
-
// Re-probe: connect + fetch targets, re-match on --url if provided
|
|
3644
|
-
const urlIdx = opts.indexOf('--url');
|
|
3645
|
-
if (urlIdx >= 0 && opts[urlIdx+1]) {
|
|
3646
|
-
log.warn('use-session failed - re-probing');
|
|
3647
|
-
try {
|
|
3648
|
-
const result = await httpPost('/list-targets', {});
|
|
3649
|
-
const targets = result.targets || [];
|
|
3650
|
-
const want = opts[urlIdx+1].toLowerCase();
|
|
3651
|
-
const hit = targets.find(t => (t.url||'').toLowerCase().includes(want));
|
|
3652
|
-
if (hit) { await cmdUseSession(hit.sessionId, opts); return; }
|
|
3653
|
-
} catch (e) { log.fail(`re-probe failed: ${e.message}`); }
|
|
3654
|
-
}
|
|
3655
|
-
log.fail(`use-session: session not live and no --url to re-probe`); process.exit(1);
|
|
4784
|
+
await cmdUseSession(arg, opts);
|
|
3656
4785
|
}
|
|
3657
4786
|
|
|
3658
4787
|
// --- WAVE 3: frames + iframe-scope-eval + upload-file ---
|
|
@@ -3695,14 +4824,14 @@ async function cmdUpload(argv) {
|
|
|
3695
4824
|
}
|
|
3696
4825
|
|
|
3697
4826
|
// --- WAVE 3: cmdHar (start/stop/dump/status) ---
|
|
3698
|
-
// v0.4.1: rewired to bexplore subprocess (was
|
|
4827
|
+
// v0.4.1: rewired to bexplore subprocess (was a stub - help advertised
|
|
3699
4828
|
// the verb but dump always returned 0 entries; "server-side subscription
|
|
3700
4829
|
// not implemented"). Now delegates to the same code path `explore --har` uses.
|
|
3701
4830
|
async function cmdHar(argv) {
|
|
3702
4831
|
const sub = argv[0];
|
|
3703
|
-
const STATE_PATH = path.join(
|
|
3704
|
-
const BUF_HAR = path.join(
|
|
3705
|
-
const BUF_OUT = path.join(
|
|
4832
|
+
const STATE_PATH = path.join(GLIDER_HOME, 'har-state.json');
|
|
4833
|
+
const BUF_HAR = path.join(GLIDER_HOME, 'har-buffer.har');
|
|
4834
|
+
const BUF_OUT = path.join(GLIDER_HOME, 'har-buffer-out');
|
|
3706
4835
|
const readState = () => { try { return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); } catch { return null; } };
|
|
3707
4836
|
const writeState = (st) => { try { fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true }); } catch {} fs.writeFileSync(STATE_PATH, JSON.stringify(st, null, 2)); };
|
|
3708
4837
|
const pidAlive = (pid) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };
|
|
@@ -3858,11 +4987,7 @@ async function cmdDialog(argv) {
|
|
|
3858
4987
|
}
|
|
3859
4988
|
async function cmdConsole(argv) {
|
|
3860
4989
|
const sub = argv[0]; if (sub !== 'tail' && sub !== 'dump') { log.fail('Usage: glider console tail | dump [PATH]'); process.exit(1); }
|
|
3861
|
-
|
|
3862
|
-
await httpPost('/cdp', { method: 'Runtime.enable', params: {} });
|
|
3863
|
-
// Persistent tail requires bg WS; here we do a one-shot poll: enable console + report installed
|
|
3864
|
-
log.warn('console tail is stub - needs bg WS subscription to Runtime.consoleAPICalled');
|
|
3865
|
-
if (jsonOutput) emitJson(true, { installed: true, note: 'stub - bg subscription required' });
|
|
4990
|
+
failUnsupported(`console ${sub}`, 'the CLI does not yet subscribe to Runtime.consoleAPICalled events');
|
|
3866
4991
|
}
|
|
3867
4992
|
async function cmdPdf(argv) {
|
|
3868
4993
|
const opts = parseFlags(argv, { landscape: { type: 'boolean' }, margin: { type: 'float' }, scale: { type: 'float', default: 1.0 } });
|
|
@@ -3877,17 +5002,29 @@ async function cmdPdf(argv) {
|
|
|
3877
5002
|
} catch (e) { log.fail(`pdf failed: ${e.message}`); process.exit(1); }
|
|
3878
5003
|
}
|
|
3879
5004
|
async function cmdCookieWrite(argv) {
|
|
3880
|
-
const opts = parseFlags(argv, {
|
|
3881
|
-
|
|
5005
|
+
const opts = parseFlags(argv, {
|
|
5006
|
+
set: { type: 'string' },
|
|
5007
|
+
delete: { type: 'string' },
|
|
5008
|
+
host: { type: 'string' },
|
|
5009
|
+
url: { type: 'string' },
|
|
5010
|
+
});
|
|
5011
|
+
assertExclusiveFlags(opts, ['set', 'delete']);
|
|
5012
|
+
assertExclusiveFlags(opts, ['host', 'url']);
|
|
5013
|
+
if ((!opts.host && !opts.url) || (!opts.set && !opts.delete)) {
|
|
5014
|
+
log.fail('Usage: glider cookies --set NAME=VAL (--host H | --url U) | --delete NAME (--host H | --url U)');
|
|
5015
|
+
process.exit(1);
|
|
5016
|
+
}
|
|
3882
5017
|
await _guardAndConnect('cookies-write');
|
|
5018
|
+
const cookieUrl = opts.url || (/^https?:\/\//i.test(opts.host) ? opts.host : `https://${opts.host}`);
|
|
3883
5019
|
try {
|
|
3884
5020
|
if (opts.set) {
|
|
3885
5021
|
const [name, ...rest] = opts.set.split('='); const value = rest.join('=');
|
|
3886
|
-
|
|
3887
|
-
|
|
5022
|
+
if (!name || rest.length === 0) throw new Error('--set expects NAME=VALUE');
|
|
5023
|
+
const r = await httpPost('/extension', { method: 'setCookie', params: { url: cookieUrl, name, value } });
|
|
5024
|
+
if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${new URL(cookieUrl).host}`);
|
|
3888
5025
|
} else if (opts.delete) {
|
|
3889
|
-
const r = await httpPost('/extension', { method: 'removeCookie', params: { url:
|
|
3890
|
-
if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${
|
|
5026
|
+
const r = await httpPost('/extension', { method: 'removeCookie', params: { url: cookieUrl, name: opts.delete } });
|
|
5027
|
+
if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${new URL(cookieUrl).host}`);
|
|
3891
5028
|
}
|
|
3892
5029
|
} catch (e) { log.fail(`cookie write failed: ${e.message}`); process.exit(1); }
|
|
3893
5030
|
}
|
|
@@ -3895,8 +5032,8 @@ async function cmdCookieWrite(argv) {
|
|
|
3895
5032
|
// --- WAVE 5: cmdMock + cmdA11ySnapshot + cmdRecord/Replay ---
|
|
3896
5033
|
async function cmdMock(argv) {
|
|
3897
5034
|
const sub = argv[0];
|
|
3898
|
-
await _guardAndConnect('mock');
|
|
3899
5035
|
if (sub === 'clear') {
|
|
5036
|
+
await _guardAndConnect('mock');
|
|
3900
5037
|
await httpPost('/cdp', { method: 'Fetch.disable', params: {} });
|
|
3901
5038
|
if (jsonOutput) emitJson(true, { cleared: true }); else log.ok('mocks cleared');
|
|
3902
5039
|
return;
|
|
@@ -3904,11 +5041,7 @@ async function cmdMock(argv) {
|
|
|
3904
5041
|
const opts = parseFlags(argv.slice(1), { status: { type: 'int', default: 200 }, body: { type: 'string' } });
|
|
3905
5042
|
const glob = argv[0];
|
|
3906
5043
|
if (!glob || !opts.body) { log.fail('Usage: glider mock <url-glob> --status N --body FILE | glider mock clear'); process.exit(1); }
|
|
3907
|
-
|
|
3908
|
-
await httpPost('/cdp', { method: 'Fetch.enable', params: { patterns: [{ urlPattern: glob }] } });
|
|
3909
|
-
log.warn('mock is stub - needs bg WS subscription to Fetch.requestPaused + Fetch.fulfillRequest');
|
|
3910
|
-
if (jsonOutput) emitJson(true, { registered: glob, note: 'stub' });
|
|
3911
|
-
} catch (e) { log.fail(`mock failed: ${e.message}`); process.exit(1); }
|
|
5044
|
+
failUnsupported('mock response', 'the relay does not yet route Fetch.requestPaused events back to this command');
|
|
3912
5045
|
}
|
|
3913
5046
|
async function cmdA11y(argv) {
|
|
3914
5047
|
await _guardAndConnect('a11y');
|
|
@@ -3925,6 +5058,7 @@ async function cmdA11y(argv) {
|
|
|
3925
5058
|
|
|
3926
5059
|
// Main
|
|
3927
5060
|
async function main() {
|
|
5061
|
+
resetCommandTiming();
|
|
3928
5062
|
const args = parseGlobalFlags(process.argv.slice(2));
|
|
3929
5063
|
loadPersistedSession();
|
|
3930
5064
|
loadPlugins(); // hydrate ~/.glider/plugins/*.plugin.{json,js} - verb-agnostic core
|
|
@@ -3933,11 +5067,6 @@ async function main() {
|
|
|
3933
5067
|
// v0.3.15: reload-ext command aliases -
|
|
3934
5068
|
// Accept common natural-language variants + typos for high-frequency commands.
|
|
3935
5069
|
// Rewrites args in place so downstream switch stays clean.
|
|
3936
|
-
const RELOAD_EXT_TWO_WORD = new Set([
|
|
3937
|
-
'ext-reload', 'ext reload',
|
|
3938
|
-
'reload-extension', 'reload extension',
|
|
3939
|
-
'reload-ext'
|
|
3940
|
-
]);
|
|
3941
5070
|
const RELOAD_EXT_ALIASES = new Set(['rex', 'reloadext', 'reloadExt']);
|
|
3942
5071
|
if (cmd === 'ext' && args[1] === 'reload') {
|
|
3943
5072
|
cmd = 'reload-ext';
|
|
@@ -3956,6 +5085,14 @@ async function main() {
|
|
|
3956
5085
|
showHelp();
|
|
3957
5086
|
process.exit(0);
|
|
3958
5087
|
}
|
|
5088
|
+
|
|
5089
|
+
const relayIndependent = new Set([
|
|
5090
|
+
'help', '--help', '-h', 'update', 'version', '-v', '--version',
|
|
5091
|
+
'browser', 'use', 'domains', 'resolve',
|
|
5092
|
+
]);
|
|
5093
|
+
if (relayConfigError && !relayIndependent.has(cmd)) {
|
|
5094
|
+
throw relayConfigError;
|
|
5095
|
+
}
|
|
3959
5096
|
|
|
3960
5097
|
// Background version check (non-blocking) - skip for update/version commands.
|
|
3961
5098
|
// Opt out via GLIDER_NO_UPDATE=1 or CI (operator sockets - set outside this repo).
|
|
@@ -3964,11 +5101,17 @@ async function main() {
|
|
|
3964
5101
|
checkForUpdates();
|
|
3965
5102
|
}
|
|
3966
5103
|
|
|
3967
|
-
//
|
|
3968
|
-
|
|
5104
|
+
// Config, diagnostics, and relay-management commands handle availability themselves.
|
|
5105
|
+
const noRelayPreflight = new Set([
|
|
5106
|
+
'start', 'stop', 'restart', 'status', 'test', 'doctor', 'heal', 'connect',
|
|
5107
|
+
'install', 'uninstall', 'browser', 'use',
|
|
5108
|
+
'help', '--help', '-h', 'update', 'version', '-v', '--version',
|
|
5109
|
+
'domains', 'resolve',
|
|
5110
|
+
]);
|
|
5111
|
+
if (!noRelayPreflight.has(cmd)) {
|
|
3969
5112
|
if (!await checkServer()) {
|
|
3970
5113
|
log.info('Server not running, starting...');
|
|
3971
|
-
await cmdStart();
|
|
5114
|
+
await cmdStart({ render: false });
|
|
3972
5115
|
}
|
|
3973
5116
|
}
|
|
3974
5117
|
|
|
@@ -4023,6 +5166,12 @@ async function main() {
|
|
|
4023
5166
|
case 'test':
|
|
4024
5167
|
await cmdTest();
|
|
4025
5168
|
break;
|
|
5169
|
+
case 'doctor':
|
|
5170
|
+
await cmdDoctor();
|
|
5171
|
+
break;
|
|
5172
|
+
case 'heal':
|
|
5173
|
+
await cmdHeal(args.slice(1));
|
|
5174
|
+
break;
|
|
4026
5175
|
case 'tabs':
|
|
4027
5176
|
await cmdTabs();
|
|
4028
5177
|
break;
|
|
@@ -4179,7 +5328,7 @@ async function main() {
|
|
|
4179
5328
|
await cmdFreeze(args.slice(1));
|
|
4180
5329
|
break;
|
|
4181
5330
|
case 'cookies':
|
|
4182
|
-
if (args.slice(1).some(a => a === '--set' || a === '--delete')) {
|
|
5331
|
+
if (args.slice(1).some(a => a === '--set' || a === '--delete' || a.startsWith('--set=') || a.startsWith('--delete='))) {
|
|
4183
5332
|
await cmdCookieWrite(args.slice(1));
|
|
4184
5333
|
} else {
|
|
4185
5334
|
await cmdCookies(args.slice(1));
|
|
@@ -4256,7 +5405,7 @@ async function main() {
|
|
|
4256
5405
|
log.fail(`Unknown command: ${cmd}`);
|
|
4257
5406
|
// v0.3.15: typo suggest (Levenshtein <=2) before dumping full help.
|
|
4258
5407
|
const KNOWN_CMDS = ['status','start','stop','restart','reload-ext','attach-all','install','uninstall',
|
|
4259
|
-
'update','version','connect','browser','use','test','domains','resolve','goto','eval','click','type',
|
|
5408
|
+
'update','version','connect','browser','use','test','doctor','heal','domains','resolve','goto','eval','click','type',
|
|
4260
5409
|
'screenshot','snapshot','text','html','title','url','tabs','targets','use-session','fetch','spawn',
|
|
4261
5410
|
'extract','explore','favicon','window','reg','run','loop','ralph',
|
|
4262
5411
|
'read','hover','focus','blur','scroll','wait','key','right-click','double-click','click-at','drag','select',
|
|
@@ -4280,7 +5429,19 @@ async function main() {
|
|
|
4280
5429
|
}
|
|
4281
5430
|
}
|
|
4282
5431
|
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
5432
|
+
module.exports = {
|
|
5433
|
+
getBrowserConfig,
|
|
5434
|
+
isBrowserInternalUrl,
|
|
5435
|
+
parseFlags,
|
|
5436
|
+
parseGlobalFlags,
|
|
5437
|
+
};
|
|
5438
|
+
|
|
5439
|
+
if (require.main === module) {
|
|
5440
|
+
main().catch(e => {
|
|
5441
|
+
if (jsonOutput) {
|
|
5442
|
+
console.log(JSON.stringify({ ok: false, observation: null, error: e.message, warnings: [] }, null, 2));
|
|
5443
|
+
}
|
|
5444
|
+
log.fail(e.message);
|
|
5445
|
+
process.exit(1);
|
|
5446
|
+
});
|
|
5447
|
+
}
|