@vibelet/cli 0.0.1
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 +39 -0
- package/bin/vibelet.mjs +667 -0
- package/dist/index.cjs +61 -0
- package/package.json +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Vibelet
|
|
2
|
+
|
|
3
|
+
`@vibelet/cli` is a macOS CLI that installs and manages the Vibelet daemon for remote coding sessions.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- macOS
|
|
8
|
+
- Node.js 18 or newer
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npx @vibelet/cli
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Or install it globally:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install -g @vibelet/cli
|
|
20
|
+
vibelet
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Commands
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
vibelet
|
|
27
|
+
vibelet status
|
|
28
|
+
vibelet logs
|
|
29
|
+
vibelet reset
|
|
30
|
+
vibelet --help
|
|
31
|
+
vibelet --version
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Notes
|
|
35
|
+
|
|
36
|
+
- The npm package publishes the CLI plus a minified daemon runtime bundle.
|
|
37
|
+
- The package is intended for end users of the macOS host daemon, not for importing as a library.
|
|
38
|
+
- The daemon keeps `~/.vibelet/data/audit.jsonl` and `~/.vibelet/logs/daemon.*.log` size-bounded by trimming the oldest content in place.
|
|
39
|
+
- Optional env vars: `VIBE_AUDIT_MAX_BYTES`, `VIBE_DAEMON_LOG_MAX_BYTES`, `VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS`.
|
package/bin/vibelet.mjs
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, openSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import QRCode from 'qrcode';
|
|
9
|
+
|
|
10
|
+
// ─── Paths & constants ─────────────────────────────────────────────────────────
|
|
11
|
+
|
|
12
|
+
const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
13
|
+
const packageJson = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8'));
|
|
14
|
+
const daemonDistDir = resolve(rootDir, 'dist');
|
|
15
|
+
const daemonEntryPath = resolve(daemonDistDir, 'index.cjs');
|
|
16
|
+
const port = Number(process.env.VIBE_PORT) || 9876;
|
|
17
|
+
const vibeletDir = join(homedir(), '.vibelet');
|
|
18
|
+
const logDir = join(vibeletDir, 'logs');
|
|
19
|
+
const runtimeDir = join(vibeletDir, 'runtime');
|
|
20
|
+
const runtimeCurrentDir = join(runtimeDir, 'current');
|
|
21
|
+
const runtimeMetadataPath = join(runtimeCurrentDir, 'runtime.json');
|
|
22
|
+
const runtimeDaemonEntryPath = join(runtimeCurrentDir, 'dist', 'index.cjs');
|
|
23
|
+
const stdoutLogPath = join(logDir, 'daemon.stdout.log');
|
|
24
|
+
const stderrLogPath = join(logDir, 'daemon.stderr.log');
|
|
25
|
+
const pidFilePath = join(vibeletDir, 'daemon.pid');
|
|
26
|
+
const relayConfigPath = join(vibeletDir, 'relay.json');
|
|
27
|
+
|
|
28
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────────
|
|
29
|
+
|
|
30
|
+
function fail(message, details) {
|
|
31
|
+
process.stderr.write(`${message}\n`);
|
|
32
|
+
if (details) {
|
|
33
|
+
process.stderr.write(`${details}\n`);
|
|
34
|
+
}
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readRuntimeMetadata() {
|
|
39
|
+
if (!existsSync(runtimeMetadataPath)) return null;
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse(readFileSync(runtimeMetadataPath, 'utf8'));
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function ensureRuntimeInstalled() {
|
|
48
|
+
if (!existsSync(daemonEntryPath)) {
|
|
49
|
+
fail('The compiled daemon runtime is missing.', 'Run `pnpm build` before invoking `npx @vibelet/cli` from a source checkout.');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const sourceDaemonStat = statSync(daemonEntryPath);
|
|
53
|
+
const runtimeMetadata = readRuntimeMetadata();
|
|
54
|
+
const runtimeLooksFresh =
|
|
55
|
+
existsSync(runtimeDaemonEntryPath) &&
|
|
56
|
+
runtimeMetadata?.version === packageJson.version &&
|
|
57
|
+
runtimeMetadata?.daemonEntryMtimeMs === sourceDaemonStat.mtimeMs;
|
|
58
|
+
|
|
59
|
+
if (runtimeLooksFresh) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
mkdirSync(runtimeDir, { recursive: true });
|
|
64
|
+
const nextRuntimeDir = join(runtimeDir, `current.${Date.now()}.${process.pid}`);
|
|
65
|
+
rmSync(nextRuntimeDir, { recursive: true, force: true });
|
|
66
|
+
mkdirSync(nextRuntimeDir, { recursive: true });
|
|
67
|
+
mkdirSync(logDir, { recursive: true });
|
|
68
|
+
|
|
69
|
+
writeFileSync(join(nextRuntimeDir, 'package.json'), JSON.stringify({
|
|
70
|
+
name: 'vibelet-runtime',
|
|
71
|
+
private: true,
|
|
72
|
+
type: 'module',
|
|
73
|
+
}, null, 2) + '\n', 'utf8');
|
|
74
|
+
|
|
75
|
+
cpSync(daemonDistDir, join(nextRuntimeDir, 'dist'), {
|
|
76
|
+
recursive: true,
|
|
77
|
+
dereference: true,
|
|
78
|
+
force: true,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
writeFileSync(runtimeMetadataPath.replace(runtimeCurrentDir, nextRuntimeDir), JSON.stringify({
|
|
82
|
+
version: packageJson.version,
|
|
83
|
+
daemonEntryMtimeMs: sourceDaemonStat.mtimeMs,
|
|
84
|
+
installedAt: new Date().toISOString(),
|
|
85
|
+
}, null, 2) + '\n', 'utf8');
|
|
86
|
+
|
|
87
|
+
rmSync(runtimeCurrentDir, { recursive: true, force: true });
|
|
88
|
+
renameSync(nextRuntimeDir, runtimeCurrentDir);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ─── PID file helpers ───────────────────────────────────────────────────────────
|
|
92
|
+
|
|
93
|
+
function writePidFile(pid) {
|
|
94
|
+
mkdirSync(dirname(pidFilePath), { recursive: true });
|
|
95
|
+
writeFileSync(pidFilePath, String(pid), 'utf8');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function readPidFile() {
|
|
99
|
+
try {
|
|
100
|
+
const pid = Number(readFileSync(pidFilePath, 'utf8').trim());
|
|
101
|
+
return Number.isFinite(pid) && pid > 0 ? pid : null;
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function removePidFile() {
|
|
108
|
+
rmSync(pidFilePath, { force: true });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isProcessAlive(pid) {
|
|
112
|
+
try {
|
|
113
|
+
process.kill(pid, 0);
|
|
114
|
+
return true;
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ─── Platform service backends ──────────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
function createDarwinBackend() {
|
|
123
|
+
const label = 'dev.vibelet.daemon';
|
|
124
|
+
const uid = process.getuid?.();
|
|
125
|
+
const launchDomain = `gui/${uid ?? 0}`;
|
|
126
|
+
const launchAgentsDir = join(homedir(), 'Library', 'LaunchAgents');
|
|
127
|
+
const plistPath = join(launchAgentsDir, `${label}.plist`);
|
|
128
|
+
|
|
129
|
+
function launchctl(args) {
|
|
130
|
+
return spawnSync('launchctl', args, { encoding: 'utf8' });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function plistContents() {
|
|
134
|
+
const programArgs = [
|
|
135
|
+
process.execPath,
|
|
136
|
+
runtimeDaemonEntryPath,
|
|
137
|
+
].map((value) => ` <string>${value}</string>`).join('\n');
|
|
138
|
+
|
|
139
|
+
const envVars = { VIBE_PORT: String(port) };
|
|
140
|
+
if (process.env.VIBELET_RELAY_URL) envVars.VIBELET_RELAY_URL = process.env.VIBELET_RELAY_URL;
|
|
141
|
+
const envSection = Object.keys(envVars).length > 0
|
|
142
|
+
? ` <key>EnvironmentVariables</key>
|
|
143
|
+
<dict>
|
|
144
|
+
${Object.entries(envVars).map(([k, v]) => ` <key>${k}</key>\n <string>${v}</string>`).join('\n')}
|
|
145
|
+
</dict>`
|
|
146
|
+
: '';
|
|
147
|
+
|
|
148
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
149
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
150
|
+
<plist version="1.0">
|
|
151
|
+
<dict>
|
|
152
|
+
<key>Label</key>
|
|
153
|
+
<string>${label}</string>
|
|
154
|
+
<key>ProgramArguments</key>
|
|
155
|
+
<array>
|
|
156
|
+
${programArgs}
|
|
157
|
+
</array>
|
|
158
|
+
<key>WorkingDirectory</key>
|
|
159
|
+
<string>${runtimeCurrentDir}</string>
|
|
160
|
+
<key>StandardOutPath</key>
|
|
161
|
+
<string>${stdoutLogPath}</string>
|
|
162
|
+
<key>StandardErrorPath</key>
|
|
163
|
+
<string>${stderrLogPath}</string>
|
|
164
|
+
${envSection}
|
|
165
|
+
<key>RunAtLoad</key>
|
|
166
|
+
<true/>
|
|
167
|
+
<key>KeepAlive</key>
|
|
168
|
+
<true/>
|
|
169
|
+
</dict>
|
|
170
|
+
</plist>
|
|
171
|
+
`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
name: 'launchd',
|
|
176
|
+
handlesProcessLifecycle: true,
|
|
177
|
+
|
|
178
|
+
isServiceInstalled() {
|
|
179
|
+
return launchctl(['print', `${launchDomain}/${label}`]).status === 0;
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
install() {
|
|
183
|
+
mkdirSync(launchAgentsDir, { recursive: true });
|
|
184
|
+
mkdirSync(logDir, { recursive: true });
|
|
185
|
+
const nextContents = plistContents();
|
|
186
|
+
const currentContents = existsSync(plistPath) ? readFileSync(plistPath, 'utf8') : null;
|
|
187
|
+
const serviceLoaded = this.isServiceInstalled();
|
|
188
|
+
const changed = currentContents !== nextContents;
|
|
189
|
+
if (changed) {
|
|
190
|
+
writeFileSync(plistPath, nextContents, 'utf8');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (changed && serviceLoaded) {
|
|
194
|
+
launchctl(['bootout', `${launchDomain}/${label}`]);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (changed || !serviceLoaded) {
|
|
198
|
+
const result = launchctl(['bootstrap', launchDomain, plistPath]);
|
|
199
|
+
if (result.status !== 0) {
|
|
200
|
+
fail('Failed to bootstrap vibelet launch agent.', result.stderr || result.stdout);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
|
|
205
|
+
start() {
|
|
206
|
+
const result = launchctl(['kickstart', `${launchDomain}/${label}`]);
|
|
207
|
+
if (result.status !== 0 && !this.isServiceInstalled()) {
|
|
208
|
+
fail('Failed to start vibelet daemon.', result.stderr || result.stdout);
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
stop() {
|
|
213
|
+
if (this.isServiceInstalled()) {
|
|
214
|
+
launchctl(['bootout', `${launchDomain}/${label}`]);
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
statusLabel() {
|
|
219
|
+
return this.isServiceInstalled() ? 'loaded' : 'not loaded';
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function createLinuxBackend() {
|
|
225
|
+
const unitName = 'vibelet-daemon.service';
|
|
226
|
+
const unitDir = join(homedir(), '.config', 'systemd', 'user');
|
|
227
|
+
const unitPath = join(unitDir, unitName);
|
|
228
|
+
|
|
229
|
+
function systemctl(args) {
|
|
230
|
+
return spawnSync('systemctl', ['--user', ...args], { encoding: 'utf8' });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function hasSystemd() {
|
|
234
|
+
return spawnSync('systemctl', ['--user', '--version'], { encoding: 'utf8' }).status === 0;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function unitContents() {
|
|
238
|
+
return `[Unit]
|
|
239
|
+
Description=Vibelet Daemon
|
|
240
|
+
After=network.target
|
|
241
|
+
|
|
242
|
+
[Service]
|
|
243
|
+
ExecStart=${process.execPath} ${runtimeDaemonEntryPath}
|
|
244
|
+
WorkingDirectory=${runtimeCurrentDir}
|
|
245
|
+
Restart=always
|
|
246
|
+
RestartSec=3
|
|
247
|
+
StandardOutput=append:${stdoutLogPath}
|
|
248
|
+
StandardError=append:${stderrLogPath}
|
|
249
|
+
Environment=VIBE_PORT=${port}${process.env.VIBELET_RELAY_URL ? `\nEnvironment=VIBELET_RELAY_URL=${process.env.VIBELET_RELAY_URL}` : ''}
|
|
250
|
+
|
|
251
|
+
[Install]
|
|
252
|
+
WantedBy=default.target
|
|
253
|
+
`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Fallback: detached process with PID file (no systemd)
|
|
257
|
+
const fallback = createDetachedBackend();
|
|
258
|
+
|
|
259
|
+
const useSystemd = hasSystemd();
|
|
260
|
+
return {
|
|
261
|
+
name: useSystemd ? 'systemd' : 'detached',
|
|
262
|
+
handlesProcessLifecycle: useSystemd,
|
|
263
|
+
|
|
264
|
+
isServiceInstalled() {
|
|
265
|
+
if (!hasSystemd()) return fallback.isServiceInstalled();
|
|
266
|
+
return systemctl(['is-enabled', unitName]).status === 0;
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
install() {
|
|
270
|
+
if (!hasSystemd()) {
|
|
271
|
+
fallback.install();
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
mkdirSync(unitDir, { recursive: true });
|
|
275
|
+
mkdirSync(logDir, { recursive: true });
|
|
276
|
+
const nextContents = unitContents();
|
|
277
|
+
const currentContents = existsSync(unitPath) ? readFileSync(unitPath, 'utf8') : null;
|
|
278
|
+
if (currentContents !== nextContents) {
|
|
279
|
+
writeFileSync(unitPath, nextContents, 'utf8');
|
|
280
|
+
systemctl(['daemon-reload']);
|
|
281
|
+
}
|
|
282
|
+
systemctl(['enable', unitName]);
|
|
283
|
+
},
|
|
284
|
+
|
|
285
|
+
start() {
|
|
286
|
+
if (!hasSystemd()) {
|
|
287
|
+
fallback.start();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const result = systemctl(['start', unitName]);
|
|
291
|
+
if (result.status !== 0) {
|
|
292
|
+
fail('Failed to start vibelet daemon.', result.stderr || result.stdout);
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
|
|
296
|
+
stop() {
|
|
297
|
+
if (!hasSystemd()) {
|
|
298
|
+
fallback.stop();
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
systemctl(['stop', unitName]);
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
statusLabel() {
|
|
305
|
+
if (!hasSystemd()) return fallback.statusLabel();
|
|
306
|
+
const result = systemctl(['is-active', unitName]);
|
|
307
|
+
return result.stdout?.trim() || 'unknown';
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function createDetachedBackend() {
|
|
313
|
+
return {
|
|
314
|
+
name: 'detached',
|
|
315
|
+
handlesProcessLifecycle: false,
|
|
316
|
+
|
|
317
|
+
isServiceInstalled() {
|
|
318
|
+
const pid = readPidFile();
|
|
319
|
+
return pid !== null && isProcessAlive(pid);
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
install() {
|
|
323
|
+
mkdirSync(logDir, { recursive: true });
|
|
324
|
+
},
|
|
325
|
+
|
|
326
|
+
start() {
|
|
327
|
+
if (this.isServiceInstalled()) return;
|
|
328
|
+
const stdoutFd = openSync(stdoutLogPath, 'a');
|
|
329
|
+
const stderrFd = openSync(stderrLogPath, 'a');
|
|
330
|
+
const child = spawn(process.execPath, [runtimeDaemonEntryPath], {
|
|
331
|
+
detached: true,
|
|
332
|
+
stdio: ['ignore', stdoutFd, stderrFd],
|
|
333
|
+
cwd: runtimeCurrentDir,
|
|
334
|
+
env: { ...process.env, VIBE_PORT: String(port) },
|
|
335
|
+
});
|
|
336
|
+
child.unref();
|
|
337
|
+
writePidFile(child.pid);
|
|
338
|
+
},
|
|
339
|
+
|
|
340
|
+
stop() {
|
|
341
|
+
const pid = readPidFile();
|
|
342
|
+
if (pid && isProcessAlive(pid)) {
|
|
343
|
+
try {
|
|
344
|
+
process.kill(pid, 'SIGTERM');
|
|
345
|
+
} catch { /* already dead */ }
|
|
346
|
+
}
|
|
347
|
+
removePidFile();
|
|
348
|
+
},
|
|
349
|
+
|
|
350
|
+
statusLabel() {
|
|
351
|
+
const pid = readPidFile();
|
|
352
|
+
if (!pid) return 'not running';
|
|
353
|
+
return isProcessAlive(pid) ? `running (pid ${pid})` : 'not running (stale pid)';
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function createWindowsBackend() {
|
|
359
|
+
// Windows: detached process with PID file
|
|
360
|
+
// Node.js detached on Windows creates a new console window — use windowsHide
|
|
361
|
+
return {
|
|
362
|
+
name: 'detached',
|
|
363
|
+
handlesProcessLifecycle: false,
|
|
364
|
+
|
|
365
|
+
isServiceInstalled() {
|
|
366
|
+
const pid = readPidFile();
|
|
367
|
+
return pid !== null && isProcessAlive(pid);
|
|
368
|
+
},
|
|
369
|
+
|
|
370
|
+
install() {
|
|
371
|
+
mkdirSync(logDir, { recursive: true });
|
|
372
|
+
},
|
|
373
|
+
|
|
374
|
+
start() {
|
|
375
|
+
if (this.isServiceInstalled()) return;
|
|
376
|
+
const stdoutFd = openSync(stdoutLogPath, 'a');
|
|
377
|
+
const stderrFd = openSync(stderrLogPath, 'a');
|
|
378
|
+
const child = spawn(process.execPath, [runtimeDaemonEntryPath], {
|
|
379
|
+
detached: true,
|
|
380
|
+
stdio: ['ignore', stdoutFd, stderrFd],
|
|
381
|
+
cwd: runtimeCurrentDir,
|
|
382
|
+
env: { ...process.env, VIBE_PORT: String(port) },
|
|
383
|
+
windowsHide: true,
|
|
384
|
+
});
|
|
385
|
+
child.unref();
|
|
386
|
+
writePidFile(child.pid);
|
|
387
|
+
},
|
|
388
|
+
|
|
389
|
+
stop() {
|
|
390
|
+
const pid = readPidFile();
|
|
391
|
+
if (pid && isProcessAlive(pid)) {
|
|
392
|
+
try {
|
|
393
|
+
process.kill(pid, 'SIGTERM');
|
|
394
|
+
} catch { /* already dead */ }
|
|
395
|
+
}
|
|
396
|
+
removePidFile();
|
|
397
|
+
},
|
|
398
|
+
|
|
399
|
+
statusLabel() {
|
|
400
|
+
const pid = readPidFile();
|
|
401
|
+
if (!pid) return 'not running';
|
|
402
|
+
return isProcessAlive(pid) ? `running (pid ${pid})` : 'not running (stale pid)';
|
|
403
|
+
},
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function resolveBackend() {
|
|
408
|
+
switch (process.platform) {
|
|
409
|
+
case 'darwin': return createDarwinBackend();
|
|
410
|
+
case 'linux': return createLinuxBackend();
|
|
411
|
+
case 'win32': return createWindowsBackend();
|
|
412
|
+
default: return createDetachedBackend();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ─── HTTP helpers ───────────────────────────────────────────────────────────────
|
|
417
|
+
|
|
418
|
+
async function probeHealth(timeoutMs = 0) {
|
|
419
|
+
const deadline = Date.now() + timeoutMs;
|
|
420
|
+
do {
|
|
421
|
+
try {
|
|
422
|
+
const response = await fetch(`http://127.0.0.1:${port}/health`);
|
|
423
|
+
if (response.ok) {
|
|
424
|
+
return await response.json();
|
|
425
|
+
}
|
|
426
|
+
} catch {
|
|
427
|
+
// Retry until timeout.
|
|
428
|
+
}
|
|
429
|
+
if (timeoutMs <= 0) break;
|
|
430
|
+
await new Promise((resolvePromise) => setTimeout(resolvePromise, 250));
|
|
431
|
+
} while (Date.now() < deadline);
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function waitForHealth(timeoutMs = 10_000) {
|
|
436
|
+
const health = await probeHealth(timeoutMs);
|
|
437
|
+
if (health) {
|
|
438
|
+
return health;
|
|
439
|
+
}
|
|
440
|
+
fail(`Timed out waiting for vibelet daemon on port ${port}.`);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function postJson(pathname, body = undefined) {
|
|
444
|
+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
|
|
445
|
+
method: 'POST',
|
|
446
|
+
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
|
447
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
448
|
+
});
|
|
449
|
+
const payload = await response.json().catch(() => ({}));
|
|
450
|
+
if (!response.ok) {
|
|
451
|
+
fail(`Request to ${pathname} failed.`, JSON.stringify(payload, null, 2));
|
|
452
|
+
}
|
|
453
|
+
return payload;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
async function requestShutdown() {
|
|
457
|
+
try {
|
|
458
|
+
await fetch(`http://127.0.0.1:${port}/shutdown`, { method: 'POST' });
|
|
459
|
+
// Wait for daemon to actually stop
|
|
460
|
+
const deadline = Date.now() + 5_000;
|
|
461
|
+
while (Date.now() < deadline) {
|
|
462
|
+
const health = await probeHealth(0);
|
|
463
|
+
if (!health) return true;
|
|
464
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
465
|
+
}
|
|
466
|
+
return false;
|
|
467
|
+
} catch {
|
|
468
|
+
return true; // Already dead
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ─── Commands ───────────────────────────────────────────────────────────────────
|
|
473
|
+
|
|
474
|
+
async function printPairingSummary() {
|
|
475
|
+
const health = await waitForHealth();
|
|
476
|
+
const pairingPayload = await postJson('/pair/open');
|
|
477
|
+
|
|
478
|
+
process.stdout.write(`Vibelet daemon is ready.\n\n`);
|
|
479
|
+
process.stdout.write(`Device: ${health.displayName}\n`);
|
|
480
|
+
process.stdout.write(`Daemon ID: ${health.daemonId}\n`);
|
|
481
|
+
process.stdout.write(`Host: ${pairingPayload.canonicalHost}\n`);
|
|
482
|
+
process.stdout.write(`Port: ${pairingPayload.port}\n`);
|
|
483
|
+
process.stdout.write(`Paired devices: ${health.pairedDevices}\n`);
|
|
484
|
+
|
|
485
|
+
const qr = await QRCode.toString(JSON.stringify(pairingPayload), {
|
|
486
|
+
type: 'terminal',
|
|
487
|
+
small: true,
|
|
488
|
+
});
|
|
489
|
+
process.stdout.write(`\nScan this QR code with the Vibelet app:\n\n${qr}\n`);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function printHelp() {
|
|
493
|
+
process.stdout.write(`Vibelet ${packageJson.version}\n\n`);
|
|
494
|
+
process.stdout.write(`Usage:\n`);
|
|
495
|
+
process.stdout.write(` npx @vibelet/cli Install/start the daemon and print a pairing QR code\n`);
|
|
496
|
+
process.stdout.write(` npx @vibelet/cli start Same as above\n`);
|
|
497
|
+
process.stdout.write(` npx @vibelet/cli --relay <url> Use a tunnel URL for remote access\n`);
|
|
498
|
+
process.stdout.write(` npx @vibelet/cli stop Stop the daemon\n`);
|
|
499
|
+
process.stdout.write(` npx @vibelet/cli restart Restart the daemon\n`);
|
|
500
|
+
process.stdout.write(` npx @vibelet/cli status Show service and daemon status\n`);
|
|
501
|
+
process.stdout.write(` npx @vibelet/cli logs Print recent daemon logs\n`);
|
|
502
|
+
process.stdout.write(` npx @vibelet/cli reset Reset pairings and print a fresh QR code\n`);
|
|
503
|
+
process.stdout.write(` npx @vibelet/cli --help Show this help text\n`);
|
|
504
|
+
process.stdout.write(` npx @vibelet/cli --version Show the installed CLI version\n`);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function parseRelayArg() {
|
|
508
|
+
const idx = process.argv.indexOf('--relay');
|
|
509
|
+
if (idx === -1) return null;
|
|
510
|
+
const url = process.argv[idx + 1];
|
|
511
|
+
if (!url || url.startsWith('-')) {
|
|
512
|
+
fail('--relay requires a URL argument (e.g. --relay https://abc.trycloudflare.com)');
|
|
513
|
+
}
|
|
514
|
+
// Remove --relay and URL from argv so they don't interfere with command parsing
|
|
515
|
+
process.argv.splice(idx, 2);
|
|
516
|
+
return url;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function loadRelayConfig() {
|
|
520
|
+
try {
|
|
521
|
+
const data = JSON.parse(readFileSync(relayConfigPath, 'utf8'));
|
|
522
|
+
return data.relayUrl || '';
|
|
523
|
+
} catch {
|
|
524
|
+
return '';
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function saveRelayConfig(relayUrl) {
|
|
529
|
+
mkdirSync(vibeletDir, { recursive: true });
|
|
530
|
+
writeFileSync(relayConfigPath, JSON.stringify({ relayUrl }, null, 2) + '\n', 'utf8');
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function clearRelayConfig() {
|
|
534
|
+
rmSync(relayConfigPath, { force: true });
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function main() {
|
|
538
|
+
const relayArg = parseRelayArg();
|
|
539
|
+
// --relay "" clears saved relay; --relay <url> saves it; omitted uses saved value
|
|
540
|
+
if (relayArg !== null) {
|
|
541
|
+
if (relayArg) {
|
|
542
|
+
saveRelayConfig(relayArg);
|
|
543
|
+
} else {
|
|
544
|
+
clearRelayConfig();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const relayUrl = relayArg || loadRelayConfig();
|
|
548
|
+
if (relayUrl) {
|
|
549
|
+
process.env.VIBELET_RELAY_URL = relayUrl;
|
|
550
|
+
}
|
|
551
|
+
const backend = resolveBackend();
|
|
552
|
+
const command = process.argv[2] ?? 'default';
|
|
553
|
+
|
|
554
|
+
if (command === '--help' || command === '-h' || command === 'help') {
|
|
555
|
+
printHelp();
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
if (command === '--version' || command === '-v' || command === 'version') {
|
|
560
|
+
process.stdout.write(`${packageJson.version}\n`);
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (command === 'stop') {
|
|
565
|
+
process.stdout.write('Stopping vibelet daemon...\n');
|
|
566
|
+
if (backend.handlesProcessLifecycle) {
|
|
567
|
+
// macOS launchd / Linux systemd: the service manager owns the process.
|
|
568
|
+
// bootout/stop kills the process and unregisters the service in one step.
|
|
569
|
+
backend.stop();
|
|
570
|
+
} else {
|
|
571
|
+
// Detached process: gracefully shut down via HTTP, then clean up PID file.
|
|
572
|
+
await requestShutdown();
|
|
573
|
+
backend.stop();
|
|
574
|
+
}
|
|
575
|
+
// Verify daemon is actually gone
|
|
576
|
+
const stillAlive = await probeHealth(1_500);
|
|
577
|
+
if (stillAlive) {
|
|
578
|
+
fail('Daemon did not stop in time.');
|
|
579
|
+
}
|
|
580
|
+
process.stdout.write('Daemon stopped.\n');
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (command === 'status') {
|
|
585
|
+
process.stdout.write(`Service (${backend.name}): ${backend.statusLabel()}\n`);
|
|
586
|
+
process.stdout.write(`Runtime: ${existsSync(runtimeDaemonEntryPath) ? runtimeDaemonEntryPath : 'not installed'}\n`);
|
|
587
|
+
const savedRelay = loadRelayConfig();
|
|
588
|
+
if (savedRelay) {
|
|
589
|
+
process.stdout.write(`Relay: ${savedRelay}\n`);
|
|
590
|
+
}
|
|
591
|
+
const health = await probeHealth(1_500);
|
|
592
|
+
if (health) {
|
|
593
|
+
process.stdout.write(JSON.stringify(health, null, 2) + '\n');
|
|
594
|
+
} else {
|
|
595
|
+
process.stdout.write('Daemon is not responding.\n');
|
|
596
|
+
}
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
if (command === 'logs') {
|
|
601
|
+
process.stdout.write(`Stdout: ${stdoutLogPath}\n`);
|
|
602
|
+
process.stdout.write(`Stderr: ${stderrLogPath}\n\n`);
|
|
603
|
+
const logFiles = [stdoutLogPath, stderrLogPath].filter((filePath) => existsSync(filePath));
|
|
604
|
+
if (logFiles.length === 0) {
|
|
605
|
+
process.stdout.write('No daemon logs have been written yet.\n');
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
if (process.platform === 'win32') {
|
|
609
|
+
for (const logFile of logFiles) {
|
|
610
|
+
const content = readFileSync(logFile, 'utf8');
|
|
611
|
+
const lines = content.split('\n').slice(-80).join('\n');
|
|
612
|
+
process.stdout.write(`==> ${logFile} <==\n${lines}\n`);
|
|
613
|
+
}
|
|
614
|
+
} else {
|
|
615
|
+
const result = spawnSync('tail', ['-n', '80', ...logFiles], { encoding: 'utf8' });
|
|
616
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
617
|
+
if (result.stderr) process.stderr.write(result.stderr);
|
|
618
|
+
}
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
if (command === 'restart') {
|
|
623
|
+
process.stdout.write('Restarting vibelet daemon...\n');
|
|
624
|
+
if (backend.handlesProcessLifecycle) {
|
|
625
|
+
backend.stop();
|
|
626
|
+
} else {
|
|
627
|
+
await requestShutdown();
|
|
628
|
+
backend.stop();
|
|
629
|
+
}
|
|
630
|
+
// Wait for daemon to actually stop
|
|
631
|
+
const stillAlive = await probeHealth(5_000);
|
|
632
|
+
if (stillAlive) {
|
|
633
|
+
fail('Daemon did not stop in time.');
|
|
634
|
+
}
|
|
635
|
+
process.stdout.write('Daemon stopped. Starting...\n');
|
|
636
|
+
ensureRuntimeInstalled();
|
|
637
|
+
backend.install();
|
|
638
|
+
backend.start();
|
|
639
|
+
await printPairingSummary();
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (command === 'reset') {
|
|
644
|
+
ensureRuntimeInstalled();
|
|
645
|
+
backend.install();
|
|
646
|
+
backend.start();
|
|
647
|
+
await waitForHealth();
|
|
648
|
+
await postJson('/pair/reset');
|
|
649
|
+
await printPairingSummary();
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
if (command !== 'default' && command !== 'start') {
|
|
654
|
+
printHelp();
|
|
655
|
+
fail(`Unknown command: ${command}`);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
ensureRuntimeInstalled();
|
|
659
|
+
backend.install();
|
|
660
|
+
backend.start();
|
|
661
|
+
await printPairingSummary();
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
process.on('SIGINT', () => process.exit(0));
|
|
665
|
+
process.on('SIGTERM', () => process.exit(0));
|
|
666
|
+
await main();
|
|
667
|
+
process.exit(0);
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";var cc=Object.create;var Ii=Object.defineProperty;var uc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var fc=Object.getPrototypeOf,hc=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var pc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dc(e))!hc.call(t,i)&&i!==n&&Ii(t,i,{get:()=>e[i],enumerable:!(r=uc(e,i))||r.enumerable});return t};var qe=(t,e,n)=>(n=t!=null?cc(fc(t)):{},pc(e||!t||!t.__esModule?Ii(n,"default",{value:t,enumerable:!0}):n,t));var oe=y((Ap,ki)=>{"use strict";var Ai=["nodebuffer","arraybuffer","fragments"],Ci=typeof Blob<"u";Ci&&Ai.push("blob");ki.exports={BINARY_TYPES:Ai,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ci,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _t=y((Cp,Zt)=>{"use strict";var{EMPTY_BUFFER:gc}=oe(),qn=Buffer[Symbol.species];function mc(t,e){if(t.length===0)return gc;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let s=t[i];n.set(s,r),r+=s.length}return r<e?new qn(n.buffer,n.byteOffset,r):n}function Pi(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function Ri(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function yc(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Wn(t){if(Wn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new qn(t):ArrayBuffer.isView(t)?e=new qn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Wn.readOnly=!1),e}Zt.exports={concat:mc,mask:Pi,toArrayBuffer:yc,toBuffer:Wn,unmask:Ri};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Zt.exports.mask=function(e,n,r,i,s){s<48?Pi(e,n,r,i,s):t.mask(e,n,r,i,s)},Zt.exports.unmask=function(e,n){e.length<32?Ri(e,n):t.unmask(e,n)}}catch{}});var Mi=y((kp,Oi)=>{"use strict";var Li=Symbol("kDone"),Gn=Symbol("kRun"),jn=class{constructor(e){this[Li]=()=>{this.pending--,this[Gn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Gn]()}[Gn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Li])}}};Oi.exports=jn});var vt=y((Pp,Fi)=>{"use strict";var St=require("zlib"),Ni=_t(),_c=Mi(),{kStatusCode:Bi}=oe(),Sc=Buffer[Symbol.species],vc=Buffer.from([0,0,255,255]),Xt=Symbol("permessage-deflate"),ae=Symbol("total-length"),We=Symbol("callback"),he=Symbol("buffers"),Ge=Symbol("error"),Qt,zn=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Qt){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Qt=new _c(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[We];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){Qt.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){Qt.add(i=>{this._compress(e,n,(s,o)=>{i(),r(s,o)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?St.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=St.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Xt]=this,this._inflate[ae]=0,this._inflate[he]=[],this._inflate.on("error",bc),this._inflate.on("data",Di)}this._inflate[We]=r,this._inflate.write(e),n&&this._inflate.write(vc),this._inflate.flush(()=>{let s=this._inflate[Ge];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=Ni.concat(this._inflate[he],this._inflate[ae]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ae]=0,this._inflate[he]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?St.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=St.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[he]=[],this._deflate.on("data",wc)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(St.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=Ni.concat(this._deflate[he],this._deflate[ae]);n&&(s=new Sc(s.buffer,s.byteOffset,s.length-4)),this._deflate[We]=null,this._deflate[ae]=0,this._deflate[he]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};Fi.exports=zn;function wc(t){this[he].push(t),this[ae]+=t.length}function Di(t){if(this[ae]+=t.length,this[Xt]._maxPayload<1||this[ae]<=this[Xt]._maxPayload){this[he].push(t);return}this[Ge]=new RangeError("Max payload size exceeded"),this[Ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ge][Bi]=1009,this.removeListener("data",Di),this.reset()}function bc(t){if(this[Xt]._inflate=null,this[Ge]){this[We](this[Ge]);return}t[Bi]=1007,this[We](t)}});var je=y((Rp,en)=>{"use strict";var{isUtf8:Ui}=require("buffer"),{hasBlob:Ec}=oe(),xc=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Tc(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function $n(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Ic(t){return Ec&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}en.exports={isBlob:Ic,isValidStatusCode:Tc,isValidUTF8:$n,tokenChars:xc};if(Ui)en.exports.isValidUTF8=function(t){return t.length<24?$n(t):Ui(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");en.exports.isValidUTF8=function(e){return e.length<32?$n(e):t(e)}}catch{}});var Zn=y((Lp,$i)=>{"use strict";var{Writable:Ac}=require("stream"),Hi=vt(),{BINARY_TYPES:Cc,EMPTY_BUFFER:qi,kStatusCode:kc,kWebSocket:Pc}=oe(),{concat:Vn,toArrayBuffer:Rc,unmask:Lc}=_t(),{isValidStatusCode:Oc,isValidUTF8:Wi}=je(),tn=Buffer[Symbol.species],G=0,Gi=1,ji=2,zi=3,Yn=4,Jn=5,nn=6,Kn=class extends Ac{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Cc[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Pc]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=G}_write(e,n,r){if(this._opcode===8&&this._state==G)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new tn(r.buffer,r.byteOffset+e,r.length-e),new tn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new tn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case G:this.getInfo(e);break;case Gi:this.getPayloadLength16(e);break;case ji:this.getPayloadLength64(e);break;case zi:this.getMask();break;case Yn:this.getData(e);break;case Jn:case nn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Hi.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Gi:this._payloadLength===127?this._state=ji:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=zi:this._state=Yn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yn}getData(e){let n=qi;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Lc(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Jn,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hi.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return n(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(s)}this.dataMessage(n),this._state===G&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=G;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Vn(r,n):this._binaryType==="arraybuffer"?i=Rc(Vn(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=G):(this._state=nn,setImmediate(()=>{this.emit("message",i,!0),this._state=G,this.startLoop(e)}))}else{let i=Vn(r,n);if(!this._skipUTF8Validation&&!Wi(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Jn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=G):(this._state=nn,setImmediate(()=>{this.emit("message",i,!1),this._state=G,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,qi),this.end();else{let r=e.readUInt16BE(0);if(!Oc(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wi(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=G):(this._state=nn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=G,this.startLoop(n)}))}createError(e,n,r,i,s){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=s,o[kc]=i,o}};$i.exports=Kn});var er=y((Mp,Ji)=>{"use strict";var{Duplex:Op}=require("stream"),{randomFillSync:Mc}=require("crypto"),Vi=vt(),{EMPTY_BUFFER:Nc,kWebSocket:Bc,NOOP:Dc}=oe(),{isBlob:ze,isValidStatusCode:Fc}=je(),{mask:Yi,toBuffer:Ie}=_t(),j=Symbol("kByteLength"),Uc=Buffer.alloc(4),rn=8*1024,Ae,$e=rn,K=0,Hc=1,qc=2,Qn=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=K,this.onerror=Dc,this[Bc]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||Uc,n.generateMask?n.generateMask(r):($e===rn&&(Ae===void 0&&(Ae=Buffer.alloc(rn)),Mc(Ae,0,rn),$e=0),r[0]=Ae[$e++],r[1]=Ae[$e++],r[2]=Ae[$e++],r[3]=Ae[$e++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[j]!==void 0?a=n[j]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let c=Buffer.allocUnsafe(i?a+s:s);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[s-4]=r[0],c[s-3]=r[1],c[s-2]=r[2],c[s-1]=r[3],o?[c,e]:i?(Yi(e,r,c,s,a),[c]):(Yi(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=Nc;else{if(typeof e!="number"||!Fc(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof n=="string"?s.write(n,2):s.set(n,2)}}let o={[j]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==K?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ze(e)?(i=e.size,s=!1):(e=Ie(e),i=e.length,s=Ie.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ze(e)?(i=e.size,s=!1):(e=Ie(e),i=e.length,s=Ie.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[Vi.extensionName],s=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ze(e)?(a=e.size,l=!1):(e=Ie(e),a=e.length,l=Ie.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),n.fin&&(this._firstFragment=!0);let c={[j]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==K?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[j],this._state=qc,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Xn,this,a,i);return}this._bufferedBytes-=r[j];let o=Ie(s);n?this.dispatch(o,n,r,i):(this._state=K,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Wc,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[Vi.extensionName];this._bufferedBytes+=r[j],this._state=Hc,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Xn(this,l,i);return}this._bufferedBytes-=r[j],this._state=K,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===K&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][j],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][j],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Ji.exports=Qn;function Xn(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],s=i[i.length-1];typeof s=="function"&&s(e)}}function Wc(t,e,n){Xn(t,e,n),t.onerror(e)}});var is=y((Np,rs)=>{"use strict";var{kForOnEventAttribute:wt,kListener:tr}=oe(),Ki=Symbol("kCode"),Zi=Symbol("kData"),Qi=Symbol("kError"),Xi=Symbol("kMessage"),es=Symbol("kReason"),Ve=Symbol("kTarget"),ts=Symbol("kType"),ns=Symbol("kWasClean"),le=class{constructor(e){this[Ve]=null,this[ts]=e}get target(){return this[Ve]}get type(){return this[ts]}};Object.defineProperty(le.prototype,"target",{enumerable:!0});Object.defineProperty(le.prototype,"type",{enumerable:!0});var Ce=class extends le{constructor(e,n={}){super(e),this[Ki]=n.code===void 0?0:n.code,this[es]=n.reason===void 0?"":n.reason,this[ns]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ki]}get reason(){return this[es]}get wasClean(){return this[ns]}};Object.defineProperty(Ce.prototype,"code",{enumerable:!0});Object.defineProperty(Ce.prototype,"reason",{enumerable:!0});Object.defineProperty(Ce.prototype,"wasClean",{enumerable:!0});var Ye=class extends le{constructor(e,n={}){super(e),this[Qi]=n.error===void 0?null:n.error,this[Xi]=n.message===void 0?"":n.message}get error(){return this[Qi]}get message(){return this[Xi]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var bt=class extends le{constructor(e,n={}){super(e),this[Zi]=n.data===void 0?null:n.data}get data(){return this[Zi]}};Object.defineProperty(bt.prototype,"data",{enumerable:!0});var Gc={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[wt]&&i[tr]===e&&!i[wt])return;let r;if(t==="message")r=function(s,o){let a=new bt("message",{data:o?s:s.toString()});a[Ve]=this,sn(e,this,a)};else if(t==="close")r=function(s,o){let a=new Ce("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ve]=this,sn(e,this,a)};else if(t==="error")r=function(s){let o=new Ye("error",{error:s,message:s.message});o[Ve]=this,sn(e,this,o)};else if(t==="open")r=function(){let s=new le("open");s[Ve]=this,sn(e,this,s)};else return;r[wt]=!!n[wt],r[tr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[tr]===e&&!n[wt]){this.removeListener(t,n);break}}};rs.exports={CloseEvent:Ce,ErrorEvent:Ye,Event:le,EventTarget:Gc,MessageEvent:bt};function sn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var nr=y((Bp,ss)=>{"use strict";var{tokenChars:Et}=je();function ne(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function jc(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,s=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Et[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(ne(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Et[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),ne(n,t.slice(l,u),!0),c===44&&(ne(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(Et[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),i=!1}else if(s)if(Et[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)s=!1,u=d;else if(c===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)s=!0;else if(u===-1&&Et[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),ne(n,a,h),c===44&&(ne(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?ne(e,f,n):(a===void 0?ne(n,f,!0):r?ne(n,a,f.replace(/\\/g,"")):ne(n,a,f),ne(e,o,n)),e}function zc(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let s=r[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ss.exports={format:zc,parse:jc}});var cn=y((Up,ys)=>{"use strict";var $c=require("events"),Vc=require("https"),Yc=require("http"),ls=require("net"),Jc=require("tls"),{randomBytes:Kc,createHash:Zc}=require("crypto"),{Duplex:Dp,Readable:Fp}=require("stream"),{URL:rr}=require("url"),pe=vt(),Qc=Zn(),Xc=er(),{isBlob:eu}=je(),{BINARY_TYPES:os,CLOSE_TIMEOUT:tu,EMPTY_BUFFER:on,GUID:nu,kForOnEventAttribute:ir,kListener:ru,kStatusCode:iu,kWebSocket:O,NOOP:cs}=oe(),{EventTarget:{addEventListener:su,removeEventListener:ou}}=is(),{format:au,parse:lu}=nr(),{toBuffer:cu}=_t(),us=Symbol("kAborted"),sr=[8,13],ce=["CONNECTING","OPEN","CLOSING","CLOSED"],uu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class t extends $c{constructor(e,n,r){super(),this._binaryType=os[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=on,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),ds(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){os.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new Qc({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Xc(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[O]=this,s[O]=this,e[O]=this,i.on("conclude",hu),i.on("drain",pu),i.on("error",gu),i.on("message",mu),i.on("ping",yu),i.on("pong",_u),s.onerror=Su,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ps),e.on("data",ln),e.on("end",gs),e.on("error",ms),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pe.extensionName]&&this._extensions[pe.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),hs(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){or(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||on,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){or(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||on,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){or(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[pe.extensionName]||(i.compress=!1),this._sender.send(e||on,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(x.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(x.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ir])return e[ru];return null},set(e){for(let n of this.listeners(t))if(n[ir]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ir]:!0})}})});x.prototype.addEventListener=su;x.prototype.removeEventListener=ou;ys.exports=x;function ds(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:tu,protocolVersion:sr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!sr.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${sr.join(", ")})`);let s;if(e instanceof rr)s=e;else try{s=new rr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;an(t,p);return}let c=o?443:80,u=Kc(16).toString("base64"),d=o?Vc.request:Yc.request,f=new Set,h;if(i.createConnection=i.createConnection||(o?fu:du),i.defaultPort=i.defaultPort||c,i.port=s.port||c,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new pe(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=au({[pe.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!uu.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let p=i.path.split(":");i.socketPath=p[0],i.path=p[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,S]of Object.entries(p))r.headers[m.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,p||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=t._req=d(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(i);i.timeout&&g.on("timeout",()=>{q(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[us]||(g=t._req=null,an(t,p))}),g.on("response",p=>{let m=p.headers.location,S=p.statusCode;if(m&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){q(t,g,"Maximum redirects exceeded");return}g.abort();let J;try{J=new rr(m,e)}catch{let T=new SyntaxError(`Invalid URL: ${m}`);an(t,T);return}ds(t,J,n,r)}else t.emit("unexpected-response",g,p)||q(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,m,S)=>{if(t.emit("upgrade",p),t.readyState!==x.CONNECTING)return;g=t._req=null;let J=p.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){q(t,m,"Invalid Upgrade header");return}let fe=Zc("sha1").update(u+nu).digest("base64");if(p.headers["sec-websocket-accept"]!==fe){q(t,m,"Invalid Sec-WebSocket-Accept header");return}let T=p.headers["sec-websocket-protocol"],L;if(T!==void 0?f.size?f.has(T)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":f.size&&(L="Server sent no subprotocol"),L){q(t,m,L);return}T&&(t._protocol=T);let W=p.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){q(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let te;try{te=lu(W)}catch{q(t,m,"Invalid Sec-WebSocket-Extensions header");return}let He=Object.keys(te);if(He.length!==1||He[0]!==pe.extensionName){q(t,m,"Server indicated an extension that was not requested");return}try{h.accept(te[pe.extensionName])}catch{q(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pe.extensionName]=h}t.setSocket(m,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function an(t,e){t._readyState=x.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function du(t){return t.path=t.socketPath,ls.connect(t)}function fu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ls.isIP(t.host)?"":t.host),Jc.connect(t)}function q(t,e,n){t._readyState=x.CLOSING;let r=new Error(n);Error.captureStackTrace(r,q),e.setHeader?(e[us]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(an,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function or(t,e,n){if(e){let r=eu(e)?e.size:cu(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ce[t.readyState]})`);process.nextTick(n,r)}}function hu(t,e){let n=this[O];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[O]!==void 0&&(n._socket.removeListener("data",ln),process.nextTick(fs,n._socket),t===1005?n.close():n.close(t,e))}function pu(){let t=this[O];t.isPaused||t._socket.resume()}function gu(t){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",ln),process.nextTick(fs,e._socket),e.close(t[iu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function as(){this[O].emitClose()}function mu(t,e){this[O].emit("message",t,e)}function yu(t){let e=this[O];e._autoPong&&e.pong(t,!this._isServer,cs),e.emit("ping",t)}function _u(t){this[O].emit("pong",t)}function fs(t){t.resume()}function Su(t){let e=this[O];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,hs(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function hs(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ps(){let t=this[O];if(this.removeListener("close",ps),this.removeListener("data",ln),this.removeListener("end",gs),t._readyState=x.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[O]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",as),t._receiver.on("finish",as))}function ln(t){this[O]._receiver.write(t)||this.pause()}function gs(){let t=this[O];t._readyState=x.CLOSING,t._receiver.end(),this.end()}function ms(){let t=this[O];this.removeListener("error",ms),this.on("error",cs),t&&(t._readyState=x.CLOSING,this.destroy())}});var ws=y((qp,vs)=>{"use strict";var Hp=cn(),{Duplex:vu}=require("stream");function _s(t){t.emit("close")}function wu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ss(t){this.removeListener("error",Ss),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function bu(t,e){let n=!0,r=new vu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&r._readableState.objectMode?s.toString():s;r.push(a)||t.pause()}),t.once("error",function(s){r.destroyed||(n=!1,r.destroy(s))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(_s,r);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(_s,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,s,o)});return}t.send(i,o)},r.on("end",wu),r.on("error",Ss),r}vs.exports=bu});var Es=y((Wp,bs)=>{"use strict";var{tokenChars:Eu}=je();function xu(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&Eu[o]===1)n===-1&&(n=i);else if(i!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=i);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(n,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}bs.exports={parse:xu}});var Ps=y((jp,ks)=>{"use strict";var Tu=require("events"),un=require("http"),{Duplex:Gp}=require("stream"),{createHash:Iu}=require("crypto"),xs=nr(),ke=vt(),Au=Es(),Cu=cn(),{CLOSE_TIMEOUT:ku,GUID:Pu,kWebSocket:Ru}=oe(),Lu=/^[+/0-9A-Za-z]{22}==$/,Ts=0,Is=1,Cs=2,ar=class extends Tu{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ku,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Cu,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=un.createServer((r,i)=>{let s=un.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Ou(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ts}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Cs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==Is)if(this._state=Is,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xt,this):process.nextTick(xt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{xt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",As);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Pe(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Pe(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!Lu.test(s)){Pe(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Pe(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Tt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Au.parse(l)}catch{Pe(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new ke(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=xs.parse(u);h[ke.extensionName]&&(f.accept(h[ke.extensionName]),d[ke.extensionName]=f)}catch{Pe(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,g,p,m)=>{if(!h)return Tt(n,g||401,p,m);this.completeUpgrade(d,s,c,e,n,r,i)});return}if(!this.options.verifyClient(f))return Tt(n,401)}this.completeUpgrade(d,s,c,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[Ru])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ts)return Tt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Iu("sha1").update(n+Pu).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[ke.extensionName]){let d=e[ke.extensionName].params,f=xs.format({[ke.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,i),s.write(c.concat(`\r
|
|
2
|
+
`).join(`\r
|
|
3
|
+
`)),s.removeListener("error",As),u.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(xt,this)})),a(u,i)}};ks.exports=ar;function Ou(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function xt(t){t._state=Cs,t.emit("close")}function As(){this.destroy()}function Tt(t,e,n,r){n=n||un.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${un.STATUS_CODES[e]}\r
|
|
4
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
5
|
+
`)+`\r
|
|
6
|
+
\r
|
|
7
|
+
`+n)}function Pe(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,Pe),t.emit("wsClientError",o,n,e)}else Tt(n,r,i,s)}});var cr=y(($p,Rs)=>{Rs.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ge=y(Re=>{var ur,Fu=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Re.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Re.getSymbolTotalCodewords=function(e){return Fu[e]};Re.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Re.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ur=e};Re.isKanjiModeEnabled=function(){return typeof ur<"u"};Re.toSJIS=function(e){return ur(e)}});var dn=y(z=>{z.L={bit:1};z.M={bit:0};z.Q={bit:3};z.H={bit:2};function Uu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return z.L;case"m":case"medium":return z.M;case"q":case"quartile":return z.Q;case"h":case"high":return z.H;default:throw new Error("Unknown EC Level: "+t)}}z.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};z.from=function(e,n){if(z.isValid(e))return e;try{return Uu(e)}catch{return n}}});var Ms=y((Jp,Os)=>{function Ls(){this.buffer=[],this.length=0}Ls.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Os.exports=Ls});var Bs=y((Kp,Ns)=>{function It(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}It.prototype.set=function(t,e,n,r){let i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)};It.prototype.get=function(t,e){return this.data[t*this.size+e]};It.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};It.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ns.exports=It});var Ds=y(fn=>{var Hu=ge().getSymbolSize;fn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Hu(e),i=r===145?26:Math.ceil((r-13)/(2*n-2))*2,s=[r-7];for(let o=1;o<n-1;o++)s[o]=s[o-1]-i;return s.push(6),s.reverse()};fn.getPositions=function(e){let n=[],r=fn.getRowColCoords(e),i=r.length;for(let s=0;s<i;s++)for(let o=0;o<i;o++)s===0&&o===0||s===0&&o===i-1||s===i-1&&o===0||n.push([r[s],r[o]]);return n}});var Hs=y(Us=>{var qu=ge().getSymbolSize,Fs=7;Us.getPositions=function(e){let n=qu(e);return[[0,0],[n-Fs,0],[0,n-Fs]]}});var qs=y(E=>{E.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Le={N1:3,N2:3,N3:40,N4:10};E.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};E.from=function(e){return E.isValid(e)?parseInt(e,10):void 0};E.getPenaltyN1=function(e){let n=e.size,r=0,i=0,s=0,o=null,a=null;for(let l=0;l<n;l++){i=s=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?i++:(i>=5&&(r+=Le.N1+(i-5)),o=u,i=1),u=e.get(c,l),u===a?s++:(s>=5&&(r+=Le.N1+(s-5)),a=u,s=1)}i>=5&&(r+=Le.N1+(i-5)),s>=5&&(r+=Le.N1+(s-5))}return r};E.getPenaltyN2=function(e){let n=e.size,r=0;for(let i=0;i<n-1;i++)for(let s=0;s<n-1;s++){let o=e.get(i,s)+e.get(i,s+1)+e.get(i+1,s)+e.get(i+1,s+1);(o===4||o===0)&&r++}return r*Le.N2};E.getPenaltyN3=function(e){let n=e.size,r=0,i=0,s=0;for(let o=0;o<n;o++){i=s=0;for(let a=0;a<n;a++)i=i<<1&2047|e.get(o,a),a>=10&&(i===1488||i===93)&&r++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&r++}return r*Le.N3};E.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let s=0;s<r;s++)n+=e.data[s];return Math.abs(Math.ceil(n*100/r/5)-10)*Le.N4};function Wu(t,e,n){switch(t){case E.Patterns.PATTERN000:return(e+n)%2===0;case E.Patterns.PATTERN001:return e%2===0;case E.Patterns.PATTERN010:return n%3===0;case E.Patterns.PATTERN011:return(e+n)%3===0;case E.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case E.Patterns.PATTERN101:return e*n%2+e*n%3===0;case E.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case E.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}E.applyMask=function(e,n){let r=n.size;for(let i=0;i<r;i++)for(let s=0;s<r;s++)n.isReserved(s,i)||n.xor(s,i,Wu(e,s,i))};E.getBestMask=function(e,n){let r=Object.keys(E.Patterns).length,i=0,s=1/0;for(let o=0;o<r;o++){n(o),E.applyMask(o,e);let a=E.getPenaltyN1(e)+E.getPenaltyN2(e)+E.getPenaltyN3(e)+E.getPenaltyN4(e);E.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var fr=y(dr=>{var me=dn(),hn=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],pn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];dr.getBlocksCount=function(e,n){switch(n){case me.L:return hn[(e-1)*4+0];case me.M:return hn[(e-1)*4+1];case me.Q:return hn[(e-1)*4+2];case me.H:return hn[(e-1)*4+3];default:return}};dr.getTotalCodewordsCount=function(e,n){switch(n){case me.L:return pn[(e-1)*4+0];case me.M:return pn[(e-1)*4+1];case me.Q:return pn[(e-1)*4+2];case me.H:return pn[(e-1)*4+3];default:return}}});var Ws=y(mn=>{var At=new Uint8Array(512),gn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)At[n]=e,gn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)At[n]=At[n-255]})();mn.log=function(e){if(e<1)throw new Error("log("+e+")");return gn[e]};mn.exp=function(e){return At[e]};mn.mul=function(e,n){return e===0||n===0?0:At[gn[e]+gn[n]]}});var Gs=y(Ct=>{var hr=Ws();Ct.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let i=0;i<e.length;i++)for(let s=0;s<n.length;s++)r[i+s]^=hr.mul(e[i],n[s]);return r};Ct.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let i=r[0];for(let o=0;o<n.length;o++)r[o]^=hr.mul(n[o],i);let s=0;for(;s<r.length&&r[s]===0;)s++;r=r.slice(s)}return r};Ct.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Ct.mul(n,new Uint8Array([1,hr.exp(r)]));return n}});var $s=y((rg,zs)=>{var js=Gs();function pr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}pr.prototype.initialize=function(e){this.degree=e,this.genPoly=js.generateECPolynomial(this.degree)};pr.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=js.mod(n,this.genPoly),i=this.degree-r.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(r,i),s}return r};zs.exports=pr});var gr=y(Vs=>{Vs.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var mr=y(ue=>{var Ys="[0-9]+",Gu="[A-Z $%*+\\-./:]+",kt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";kt=kt.replace(/u/g,"\\u");var ju="(?:(?![A-Z0-9 $%*+\\-./:]|"+kt+`)(?:.|[\r
|
|
8
|
+
]))+`;ue.KANJI=new RegExp(kt,"g");ue.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ue.BYTE=new RegExp(ju,"g");ue.NUMERIC=new RegExp(Ys,"g");ue.ALPHANUMERIC=new RegExp(Gu,"g");var zu=new RegExp("^"+kt+"$"),$u=new RegExp("^"+Ys+"$"),Vu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ue.testKanji=function(e){return zu.test(e)};ue.testNumeric=function(e){return $u.test(e)};ue.testAlphanumeric=function(e){return Vu.test(e)}});var ye=y(C=>{var Yu=gr(),yr=mr();C.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};C.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};C.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};C.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};C.MIXED={bit:-1};C.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Yu.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};C.getBestModeForData=function(e){return yr.testNumeric(e)?C.NUMERIC:yr.testAlphanumeric(e)?C.ALPHANUMERIC:yr.testKanji(e)?C.KANJI:C.BYTE};C.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};C.isValid=function(e){return e&&e.bit&&e.ccBits};function Ju(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return C.NUMERIC;case"alphanumeric":return C.ALPHANUMERIC;case"kanji":return C.KANJI;case"byte":return C.BYTE;default:throw new Error("Unknown mode: "+t)}}C.from=function(e,n){if(C.isValid(e))return e;try{return Ju(e)}catch{return n}}});var Xs=y(Oe=>{var yn=ge(),Ku=fr(),Js=dn(),_e=ye(),_r=gr(),Zs=7973,Ks=yn.getBCHDigit(Zs);function Zu(t,e,n){for(let r=1;r<=40;r++)if(e<=Oe.getCapacity(r,n,t))return r}function Qs(t,e){return _e.getCharCountIndicator(t,e)+4}function Qu(t,e){let n=0;return t.forEach(function(r){let i=Qs(r.mode,e);n+=i+r.getBitsLength()}),n}function Xu(t,e){for(let n=1;n<=40;n++)if(Qu(t,n)<=Oe.getCapacity(n,e,_e.MIXED))return n}Oe.from=function(e,n){return _r.isValid(e)?parseInt(e,10):n};Oe.getCapacity=function(e,n,r){if(!_r.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=_e.BYTE);let i=yn.getSymbolTotalCodewords(e),s=Ku.getTotalCodewordsCount(e,n),o=(i-s)*8;if(r===_e.MIXED)return o;let a=o-Qs(r,e);switch(r){case _e.NUMERIC:return Math.floor(a/10*3);case _e.ALPHANUMERIC:return Math.floor(a/11*2);case _e.KANJI:return Math.floor(a/13);case _e.BYTE:default:return Math.floor(a/8)}};Oe.getBestVersionForData=function(e,n){let r,i=Js.from(n,Js.M);if(Array.isArray(e)){if(e.length>1)return Xu(e,i);if(e.length===0)return 1;r=e[0]}else r=e;return Zu(r.mode,r.getLength(),i)};Oe.getEncodedBits=function(e){if(!_r.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;yn.getBCHDigit(n)-Ks>=0;)n^=Zs<<yn.getBCHDigit(n)-Ks;return e<<12|n}});var ro=y(no=>{var Sr=ge(),to=1335,ed=21522,eo=Sr.getBCHDigit(to);no.getEncodedBits=function(e,n){let r=e.bit<<3|n,i=r<<10;for(;Sr.getBCHDigit(i)-eo>=0;)i^=to<<Sr.getBCHDigit(i)-eo;return(r<<10|i)^ed}});var so=y((cg,io)=>{var td=ye();function Je(t){this.mode=td.NUMERIC,this.data=t.toString()}Je.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Je.prototype.getLength=function(){return this.data.length};Je.prototype.getBitsLength=function(){return Je.getBitsLength(this.data.length)};Je.prototype.write=function(e){let n,r,i;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),i=parseInt(r,10),e.put(i,10);let s=this.data.length-n;s>0&&(r=this.data.substr(n),i=parseInt(r,10),e.put(i,s*3+1))};io.exports=Je});var ao=y((ug,oo)=>{var nd=ye(),vr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Ke(t){this.mode=nd.ALPHANUMERIC,this.data=t}Ke.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Ke.prototype.getLength=function(){return this.data.length};Ke.prototype.getBitsLength=function(){return Ke.getBitsLength(this.data.length)};Ke.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=vr.indexOf(this.data[n])*45;r+=vr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(vr.indexOf(this.data[n]),6)};oo.exports=Ke});var co=y((dg,lo)=>{var rd=ye();function Ze(t){this.mode=rd.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ze.getBitsLength=function(e){return e*8};Ze.prototype.getLength=function(){return this.data.length};Ze.prototype.getBitsLength=function(){return Ze.getBitsLength(this.data.length)};Ze.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};lo.exports=Ze});var fo=y((fg,uo)=>{var id=ye(),sd=ge();function Qe(t){this.mode=id.KANJI,this.data=t}Qe.getBitsLength=function(e){return e*13};Qe.prototype.getLength=function(){return this.data.length};Qe.prototype.getBitsLength=function(){return Qe.getBitsLength(this.data.length)};Qe.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=sd.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
9
|
+
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};uo.exports=Qe});var ho=y((hg,wr)=>{"use strict";var Pt={single_source_shortest_paths:function(t,e,n){var r={},i={};i[e]=0;var s=Pt.PriorityQueue.make();s.push(e,0);for(var o,a,l,c,u,d,f,h,g;!s.empty();){o=s.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=i[l],g=typeof i[l]>"u",(g||h>f)&&(i[l]=f,s.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof i[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,i;r;)n.push(r),i=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Pt.single_source_shortest_paths(t,e,n);return Pt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Pt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof wr<"u"&&(wr.exports=Pt)});var wo=y(Xe=>{var w=ye(),mo=so(),yo=ao(),_o=co(),So=fo(),Rt=mr(),_n=ge(),od=ho();function po(t){return unescape(encodeURIComponent(t)).length}function Lt(t,e,n){let r=[],i;for(;(i=t.exec(n))!==null;)r.push({data:i[0],index:i.index,mode:e,length:i[0].length});return r}function vo(t){let e=Lt(Rt.NUMERIC,w.NUMERIC,t),n=Lt(Rt.ALPHANUMERIC,w.ALPHANUMERIC,t),r,i;return _n.isKanjiModeEnabled()?(r=Lt(Rt.BYTE,w.BYTE,t),i=Lt(Rt.KANJI,w.KANJI,t)):(r=Lt(Rt.BYTE_KANJI,w.BYTE,t),i=[]),e.concat(n,r,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function br(t,e){switch(e){case w.NUMERIC:return mo.getBitsLength(t);case w.ALPHANUMERIC:return yo.getBitsLength(t);case w.KANJI:return So.getBitsLength(t);case w.BYTE:return _o.getBitsLength(t)}}function ad(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function ld(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case w.NUMERIC:e.push([r,{data:r.data,mode:w.ALPHANUMERIC,length:r.length},{data:r.data,mode:w.BYTE,length:r.length}]);break;case w.ALPHANUMERIC:e.push([r,{data:r.data,mode:w.BYTE,length:r.length}]);break;case w.KANJI:e.push([r,{data:r.data,mode:w.BYTE,length:po(r.data)}]);break;case w.BYTE:e.push([{data:r.data,mode:w.BYTE,length:po(r.data)}])}}return e}function cd(t,e){let n={},r={start:{}},i=["start"];for(let s=0;s<t.length;s++){let o=t[s],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+s+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<i.length;d++){let f=i[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=br(n[f].lastCount+c.length,c.mode)-br(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=br(c.length,c.mode)+4+w.getCharCountIndicator(c.mode,e))}}i=a}for(let s=0;s<i.length;s++)r[i[s]].end=0;return{map:r,table:n}}function go(t,e){let n,r=w.getBestModeForData(t);if(n=w.from(e,r),n!==w.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+w.toString(n)+`.
|
|
10
|
+
Suggested mode is: `+w.toString(r));switch(n===w.KANJI&&!_n.isKanjiModeEnabled()&&(n=w.BYTE),n){case w.NUMERIC:return new mo(t);case w.ALPHANUMERIC:return new yo(t);case w.KANJI:return new So(t);case w.BYTE:return new _o(t)}}Xe.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(go(r,null)):r.data&&n.push(go(r.data,r.mode)),n},[])};Xe.fromString=function(e,n){let r=vo(e,_n.isKanjiModeEnabled()),i=ld(r),s=cd(i,n),o=od.find_path(s.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(s.table[o[l]].node);return Xe.fromArray(ad(a))};Xe.rawSplit=function(e){return Xe.fromArray(vo(e,_n.isKanjiModeEnabled()))}});var Cr=y(bo=>{var vn=ge(),Er=dn(),ud=Ms(),dd=Bs(),fd=Ds(),hd=Hs(),Ir=qs(),Ar=fr(),pd=$s(),Sn=Xs(),gd=ro(),md=ye(),xr=wo();function yd(t,e){let n=t.size,r=hd.getPositions(e);for(let i=0;i<r.length;i++){let s=r[i][0],o=r[i][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||n<=s+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(s+a,o+l,!0,!0):t.set(s+a,o+l,!1,!0))}}function _d(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function Sd(t,e){let n=fd.getPositions(e);for(let r=0;r<n.length;r++){let i=n[r][0],s=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(i+o,s+a,!0,!0):t.set(i+o,s+a,!1,!0)}}function vd(t,e){let n=t.size,r=Sn.getEncodedBits(e),i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+n-8-3,o=(r>>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function Tr(t,e,n){let r=t.size,i=gd.getEncodedBits(e,n),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(r-15+s,8,o,!0),s<8?t.set(8,r-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(r-8,8,1,!0)}function wd(t,e){let n=t.size,r=-1,i=n-1,s=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(i,a-l,c),s--,s===-1&&(o++,s=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}function bd(t,e,n){let r=new ud;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),md.getCharCountIndicator(l.mode,t)),l.write(r)});let i=vn.getSymbolTotalCodewords(t),s=Ar.getTotalCodewordsCount(t,e),o=(i-s)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Ed(r,t,e)}function Ed(t,e,n){let r=vn.getSymbolTotalCodewords(e),i=Ar.getTotalCodewordsCount(e,n),s=r-i,o=Ar.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(s/o),d=u+1,f=c-u,h=new pd(f),g=0,p=new Array(o),m=new Array(o),S=0,J=new Uint8Array(t.buffer);for(let te=0;te<o;te++){let He=te<l?u:d;p[te]=J.slice(g,g+He),m[te]=h.encode(p[te]),g+=He,S=Math.max(S,He)}let fe=new Uint8Array(r),T=0,L,W;for(L=0;L<S;L++)for(W=0;W<o;W++)L<p[W].length&&(fe[T++]=p[W][L]);for(L=0;L<f;L++)for(W=0;W<o;W++)fe[T++]=m[W][L];return fe}function xd(t,e,n,r){let i;if(Array.isArray(t))i=xr.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=xr.rawSplit(t);c=Sn.getBestVersionForData(u,n)}i=xr.fromString(t,c||40)}else throw new Error("Invalid data");let s=Sn.getBestVersionForData(i,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
|
|
11
|
+
The chosen QR Code version cannot contain this amount of data.
|
|
12
|
+
Minimum version required to store current data is: `+s+`.
|
|
13
|
+
`);let o=bd(e,n,i),a=vn.getSymbolSize(e),l=new dd(a);return yd(l,e),_d(l),Sd(l,e),Tr(l,n,0),e>=7&&vd(l,e),wd(l,o),isNaN(r)&&(r=Ir.getBestMask(l,Tr.bind(null,l,n))),Ir.applyMask(r,l),Tr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:i}}bo.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Er.M,i,s;return typeof n<"u"&&(r=Er.from(n.errorCorrectionLevel,Er.M),i=Sn.from(n.version),s=Ir.from(n.maskPattern),n.toSJISFunc&&vn.setToSJISFunction(n.toSJISFunc)),xd(e,i,r,s)}});var kr=y((mg,xo)=>{"use strict";var Td=require("util"),Eo=require("stream"),Z=xo.exports=function(){Eo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Td.inherits(Z,Eo);Z.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Z.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Z.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Z.prototype.destroySoon=Z.prototype.end;Z.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Z.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Z.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Z.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[n++],s=Math.min(i.length,t.length-e);i.copy(r,e,0,s),e+=s,s!==i.length&&(this._buffers[--n]=i.slice(s))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};Z.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Rr=y(Pr=>{"use strict";var Se=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Pr.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,s=(t-r)/8,o=(e-i)/8;for(let a=0;a<Se.length;a++){let l=Se[a],c=s*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<i;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Pr.getInterlaceIterator=function(t){return function(e,n,r){let i=e%Se[r].x.length,s=(e-i)/Se[r].x.length*8+Se[r].x[i],o=n%Se[r].y.length,a=(n-o)/Se[r].y.length*8+Se[r].y[o];return s*4+a*t*4}}});var Lr=y((_g,To)=>{"use strict";To.exports=function(e,n,r){let i=e+n-r,s=Math.abs(i-e),o=Math.abs(i-n),a=Math.abs(i-r);return s<=o&&s<=a?e:o<=a?n:r}});var Or=y((Sg,Ao)=>{"use strict";var Id=Rr(),Ad=Lr();function Io(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var et=Ao.exports=function(t,e){let n=t.width,r=t.height,i=t.interlace,s=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=Id.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Io(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Io(n,s,o),height:r,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};et.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};et.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=t[1+s],a=s>i?e[s-r]:0;e[s]=o+a}};et.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=t[1+i],o=r?r[i]:0;e[i]=s+o}};et.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};et.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-r]:0,u=o>i&&s?s[o-r]:0,d=Ad(c,l,u);e[o]=a+d}};et.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Po=y((vg,ko)=>{"use strict";var Cd=require("util"),Co=kr(),kd=Or(),Pd=ko.exports=function(t){Co.call(this);let e=[],n=this;this._filter=new kd(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Cd.inherits(Pd,Co)});var tt=y((wg,Ro)=>{"use strict";Ro.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Br=y((bg,Lo)=>{"use strict";var Mr=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Mr[t]=e}})();var Nr=Lo.exports=function(){this._crc=-1};Nr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Mr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Nr.prototype.crc32=function(){return this._crc^-1};Nr.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Mr[(e^t[n])&255]^e>>>8;return e^-1}});var Dr=y((Eg,Oo)=>{"use strict";var R=tt(),Rd=Br(),M=Oo.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[R.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[R.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[R.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[R.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[R.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[R.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};M.prototype.start=function(){this.read(R.PNG_SIGNATURE.length,this._parseSignature.bind(this))};M.prototype._parseSignature=function(t){let e=R.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};M.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(t[s]);let i=!!(t[4]&32);if(!this._hasIHDR&&n!==R.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Rd,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};M.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};M.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};M.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],s=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(i in R.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(s!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=R.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(i&R.COLORTYPE_PALETTE),color:!!(i&R.COLORTYPE_COLOR),alpha:!!(i&R.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};M.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};M.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};M.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};M.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===R.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===R.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===R.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};M.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};M.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/R.GAMMA_DIVISION),this._handleChunkEnd()};M.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};M.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===R.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};M.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};M.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Fr=y(No=>{"use strict";var Mo=Rr(),Ld=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Od=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Md(t,e){let n=[],r=0;function i(){if(r===t.length)throw new Error("Ran out of data");let s=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,h=s>>4,n.push(h,f);break;case 2:u=s&3,d=s>>2&3,f=s>>4&3,h=s>>6&3,n.push(h,f,d,u);break;case 1:o=s&1,a=s>>1&1,l=s>>2&1,c=s>>3&1,u=s>>4&1,d=s>>5&1,f=s>>6&1,h=s>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(s){for(;n.length<s;)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function Nd(t,e,n,r,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);Ld[r](e,i,d,s),s+=r}return s}function Bd(t,e,n,r,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=i.get(r),f=n(u,c,l);Od[r](e,d,f,s)}i.resetAfterLine()}}No.dataToBitMap=function(t,e){let n=e.width,r=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=Md(t,i));let l;i<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,u=0,d,f;if(o)d=Mo.getImagePasses(n,r),f=Mo.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)i===8?u=Nd(d[h],l,f,s,t,u):Bd(d[h],l,f,s,a,c);if(i===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Ur=y((Tg,Bo)=>{"use strict";function Dd(t,e,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=i[t[s]];if(!l)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=l[c];s+=4}}function Fd(t,e,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(i.length===1?i[0]===t[s]&&(l=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(l=!0),l)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function Ud(t,e,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*s/o+.5);a+=4}}Bo.exports=function(t,e){let n=e.depth,r=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,l=t;return s===3?Dd(t,l,r,i,a):(o&&Fd(t,l,r,i,o),n!==8&&(n===16&&(l=Buffer.alloc(r*i*4)),Ud(t,l,r,i,n))),l}});var Uo=y((Ig,Fo)=>{"use strict";var Hd=require("util"),Hr=require("zlib"),Do=kr(),qd=Po(),Wd=Dr(),Gd=Fr(),jd=Ur(),re=Fo.exports=function(t){Do.call(this),this._parser=new Wd(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Hd.inherits(re,Do);re.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};re.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Hr.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Hr.Z_MIN_CHUNK);this._inflate=Hr.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};re.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new qd(this._bitmapInfo)};re.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};re.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};re.prototype._simpleTransparency=function(){this._metaData.alpha=!0};re.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};re.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};re.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Gd.dataToBitMap(t,this._bitmapInfo);e=jd(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var qo=y((Ag,Ho)=>{"use strict";var $=tt();Ho.exports=function(t,e,n,r){let i=[$.COLORTYPE_COLOR_ALPHA,$.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let s=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=$.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=$.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,m,S=o;switch(r.inputColorType){case $.COLORTYPE_COLOR_ALPHA:S=s[u+3],g=s[u],p=s[u+1],m=s[u+2];break;case $.COLORTYPE_COLOR:g=s[u],p=s[u+1],m=s[u+2];break;case $.COLORTYPE_ALPHA:S=s[u+1],g=s[u],p=g,m=g;break;case $.COLORTYPE_GRAYSCALE:g=s[u],p=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(i||(S/=o,g=Math.min(Math.max(Math.round((1-S)*f.red+S*g),0),o),p=Math.min(Math.max(Math.round((1-S)*f.green+S*p),0),o),m=Math.min(Math.max(Math.round((1-S)*f.blue+S*m),0),o))),{red:g,green:p,blue:m,alpha:S}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let m=h(s,u);switch(r.colorType){case $.COLORTYPE_COLOR_ALPHA:case $.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,i&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),i&&c.writeUInt16BE(m.alpha,d+6));break;case $.COLORTYPE_ALPHA:case $.COLORTYPE_GRAYSCALE:{let S=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=S,i&&(c[d+1]=m.alpha)):(c.writeUInt16BE(S,d),i&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var jo=y((Cg,Go)=>{"use strict";var Wo=Lr();function zd(t,e,n,r,i){for(let s=0;s<n;s++)r[i+s]=t[e+s]}function $d(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++)r+=Math.abs(t[s]);return r}function Vd(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=t[e+o]-a;r[i+o]=l}}function Yd(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=t[e+s]-o;i+=Math.abs(a)}return i}function Jd(t,e,n,r,i){for(let s=0;s<n;s++){let o=e>0?t[e+s-n]:0,a=t[e+s]-o;r[i+s]=a}}function Kd(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++){let o=e>0?t[s-n]:0,a=t[s]-o;r+=Math.abs(a)}return r}function Zd(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[i+o]=c}}function Qd(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=e>0?t[e+s-n]:0,l=t[e+s]-(o+a>>1);i+=Math.abs(l)}return i}function Xd(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=s?t[e+o-(n+s)]:0,u=t[e+o]-Wo(a,l,c);r[i+o]=u}}function ef(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=e>0?t[e+s-n]:0,l=e>0&&s>=r?t[e+s-(n+r)]:0,c=t[e+s]-Wo(o,a,l);i+=Math.abs(c)}return i}var tf={0:zd,1:Vd,2:Jd,3:Zd,4:Xd},nf={0:$d,1:Yd,2:Kd,3:Qd,4:ef};Go.exports=function(t,e,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType=="number")s=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(i*=2);let o=e*i,a=0,l=0,c=Buffer.alloc((o+1)*n),u=s[0];for(let d=0;d<n;d++){if(s.length>1){let f=1/0;for(let h=0;h<s.length;h++){let g=nf[s[h]](t,l,o,i);g<f&&(u=s[h],f=g)}}c[a]=u,a++,tf[u](t,l,o,c,a,i),a+=o,l+=o}return c}});var qr=y((kg,zo)=>{"use strict";var B=tt(),rf=Br(),sf=qo(),of=jo(),af=require("zlib"),ve=zo.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||af.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:B.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:B.COLORTYPE_COLOR_ALPHA,[B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};ve.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ve.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ve.prototype.filterData=function(t,e,n){let r=sf(t,e,n,this._options),i=B.COLORTYPE_TO_BPP_MAP[this._options.colorType];return of(r,e,n,this._options,i)};ve.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(rf.crc32(r.slice(4,r.length-4)),r.length-4),r};ve.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*B.GAMMA_DIVISION),0),this._packChunk(B.TYPE_gAMA,e)};ve.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(B.TYPE_IHDR,n)};ve.prototype.packIDAT=function(t){return this._packChunk(B.TYPE_IDAT,t)};ve.prototype.packIEND=function(){return this._packChunk(B.TYPE_IEND,null)}});var Jo=y((Pg,Yo)=>{"use strict";var lf=require("util"),$o=require("stream"),cf=tt(),uf=qr(),Vo=Yo.exports=function(t){$o.call(this);let e=t||{};this._packer=new uf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};lf.inherits(Vo,$o);Vo.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(cf.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ta=y((Ot,ea)=>{"use strict";var Ko=require("assert").ok,nt=require("zlib"),df=require("util"),Zo=require("buffer").kMaxLength;function Me(t){if(!(this instanceof Me))return new Me(t);t&&t.chunkSize<nt.Z_MIN_CHUNK&&(t.chunkSize=nt.Z_MIN_CHUNK),nt.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function ff(t){return new Me(t)}function Qo(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Me.prototype._processChunk=function(t,e,n){if(typeof n=="function")return nt.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let m=s-p;if(Ko(m>=0,"have should not go down"),m>0){let S=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=i-g,i=g,!0):!1}Ko(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Zo)throw Qo(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Zo.toString(16)+" bytes");let h=Buffer.concat(l,c);return Qo(this),h};df.inherits(Me,nt.Inflate);function hf(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=nt.Z_FINISH),t._processChunk(e,n)}function Xo(t,e){return hf(new Me(e),t)}ea.exports=Ot=Xo;Ot.Inflate=Me;Ot.createInflate=ff;Ot.inflateSync=Xo});var Wr=y((Rg,ra)=>{"use strict";var na=ra.exports=function(t){this._buffer=t,this._reads=[]};na.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};na.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var sa=y(ia=>{"use strict";var pf=Wr(),gf=Or();ia.process=function(t,e){let n=[],r=new pf(t);return new gf(e,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var ca=y((Og,la)=>{"use strict";var oa=!0,aa=require("zlib"),mf=ta();aa.deflateSync||(oa=!1);var yf=Wr(),_f=sa(),Sf=Dr(),vf=Fr(),wf=Ur();la.exports=function(t,e){if(!oa)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(T){n=T}let i;function s(T){i=T}function o(T){i.transColor=T}function a(T){i.palette=T}function l(){i.alpha=!0}let c;function u(T){c=T}let d=[];function f(T){d.push(T)}let h=new yf(t);if(new Sf(e,{read:h.read.bind(h),error:r,metadata:s,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let m;if(i.interlace)m=aa.inflateSync(p);else{let L=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;m=mf(p,{chunkSize:L,maxLength:L})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=_f.process(m,i);p=null;let J=vf.dataToBitMap(S,i);S=null;let fe=wf(J,i);return i.data=fe,i.gamma=c||0,i}});var ha=y((Mg,fa)=>{"use strict";var ua=!0,da=require("zlib");da.deflateSync||(ua=!1);var bf=tt(),Ef=qr();fa.exports=function(t,e){if(!ua)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new Ef(n),i=[];i.push(Buffer.from(bf.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma&&i.push(r.packGAMA(t.gamma));let s=r.filterData(t.data,t.width,t.height),o=da.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var pa=y(Gr=>{"use strict";var xf=ca(),Tf=ha();Gr.read=function(t,e){return xf(t,e||{})};Gr.write=function(t,e){return Tf(t,e)}});var ya=y(ma=>{"use strict";var If=require("util"),ga=require("stream"),Af=Uo(),Cf=Jo(),kf=pa(),F=ma.PNG=function(t){ga.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Af(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Cf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};If.inherits(F,ga);F.sync=kf;F.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};F.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};F.prototype.write=function(t){return this._parser.write(t),!0};F.prototype.end=function(t){this._parser.end(t)};F.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};F.prototype._gamma=function(t){this.gamma=t};F.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};F.bitblt=function(t,e,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>t.width||r>t.height||n+i>t.width||r+s>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+i>e.width||a+s>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<s;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+i<<2)};F.prototype.bitblt=function(t,e,n,r,i,s,o){return F.bitblt(this,t,e,n,r,i,s,o),this};F.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let s=t.data[r+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[r+i]=Math.round(s*255)}}t.gamma=0}};F.prototype.adjustGamma=function(){F.adjustGamma(this)}});var Mt=y(Ne=>{function _a(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Ne.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:r,scale:r?4:i,margin:n,color:{dark:_a(e.color.dark||"#000000ff"),light:_a(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ne.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ne.getImageWidth=function(e,n){let r=Ne.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Ne.qrToImageData=function(e,n,r){let i=n.modules.size,s=n.modules.data,o=Ne.getScale(i,r),a=Math.floor((i+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[s[g*i+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Sa=y(ie=>{var Pf=require("fs"),Rf=ya().PNG,jr=Mt();ie.render=function(e,n){let r=jr.getOptions(n),i=r.rendererOpts,s=jr.getImageWidth(e.modules.size,r);i.width=s,i.height=s;let o=new Rf(i);return jr.qrToImageData(o.data,e,r),o};ie.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ie.renderToBuffer(e,n,function(i,s){i&&r(i);let o="data:image/png;base64,";o+=s.toString("base64"),r(null,o)})};ie.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let i=ie.render(e,n),s=[];i.on("error",r),i.on("data",function(o){s.push(o)}),i.on("end",function(){r(null,Buffer.concat(s))}),i.pack()};ie.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=!1,o=(...l)=>{s||(s=!0,i.apply(null,l))},a=Pf.createWriteStream(e);a.on("error",o),a.on("close",o),ie.renderToFileStream(a,n,r)};ie.renderToFileStream=function(e,n,r){ie.render(n,r).pack().pipe(e)}});var va=y(wn=>{var Lf=Mt(),Of={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Mf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Nf(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}wn.render=function(t,e,n){let r=Lf.getOptions(e),i=Of;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=Mf);let s=t.modules.size,o=t.modules.data,a="",l=Array(s+r.margin*2+1).join(i.WW);l=Array(r.margin/2+1).join(l+`
|
|
14
|
+
`);let c=Array(r.margin+1).join(i.WW);a+=l;for(let u=0;u<s;u+=2){a+=c;for(let d=0;d<s;d++){let f=o[u*s+d],h=o[(u+1)*s+d];a+=Nf(f,h,i)}a+=c+`
|
|
15
|
+
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};wn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),o=wn.render(n,r);s.writeFile(e,o,i)}});var ba=y(wa=>{wa.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
|
|
16
|
+
`;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=i[u*r+d]?s:o;a+=c+`
|
|
17
|
+
`}return a+=l+`
|
|
18
|
+
`,typeof n=="function"&&n(null,a),a}});var Ia=y(Ta=>{var Bf="\x1B[47m",Df="\x1B[40m",zr="\x1B[37m",$r="\x1B[30m",Be="\x1B[0m",Ff=Bf+$r,Uf=Df+zr,Hf=function(t,e,n){return{"00":Be+" "+t,"01":Be+e+"\u2584"+t,"02":Be+n+"\u2584"+t,10:Be+e+"\u2580"+t,11:" ",12:"\u2584",20:Be+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Ea=function(t,e,n,r){let i=e+1;if(n>=i||r>=i||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let s=r*e+n;return t[s]?"2":"1"},xa=function(t,e,n,r){return Ea(t,e,n,r)+Ea(t,e,n,r+1)};Ta.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?Uf:Ff,c=Hf(o,s?$r:zr,s?zr:$r),u=Be+`
|
|
19
|
+
`+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[xa(i,r,h,f)];d+=c[xa(i,r,r,f)]+u}return d+=Be,typeof n=="function"&&n(null,d),d}});var Ca=y(Aa=>{var qf=ba(),Wf=Ia();Aa.render=function(t,e,n){return e&&e.small?Wf.render(t,e,n):qf.render(t,e,n)}});var Yr=y(Pa=>{var Gf=Mt();function ka(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Vr(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function jf(t,e,n){let r="",i=0,s=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!s&&(s=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=s?Vr("M",l+n,.5+c+n):Vr("m",i,0),i=0,s=!1),l+1<e&&t[a+1]||(r+=Vr("h",o),o=0)):i++}return r}Pa.render=function(e,n,r){let i=Gf.getOptions(n),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,l=i.color.light.a?"<path "+ka(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+ka(i.color.dark,"stroke")+' d="'+jf(o,s,i.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
|
|
20
|
+
`;return typeof r=="function"&&r(null,f),f}});var Ra=y(bn=>{var zf=Yr();bn.render=zf.render;bn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+bn.render(n,r);s.writeFile(e,a,i)}});var La=y(En=>{var Jr=Mt();function $f(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function Vf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}En.render=function(e,n,r){let i=r,s=n;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),n||(s=Vf()),i=Jr.getOptions(i);let o=Jr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),l=a.createImageData(o,o);return Jr.qrToImageData(l.data,e,i),$f(a,s,o),a.putImageData(l,0,0),s};En.renderToDataURL=function(e,n,r){let i=r;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),i||(i={});let s=En.render(e,n,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Ma=y(Nt=>{var Yf=cr(),Kr=Cr(),Oa=La(),Jf=Yr();function Zr(t,e,n,r,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Yf())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=r,r=void 0):(i=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=Kr.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Kr.create(n,r);i(null,t(l,e,r))}catch(l){i(l)}}Nt.create=Kr.create;Nt.toCanvas=Zr.bind(null,Oa.render);Nt.toDataURL=Zr.bind(null,Oa.renderToDataURL);Nt.toString=Zr.bind(null,function(t,e,n){return Jf.render(t,n)})});var Fa=y(we=>{var Na=cr(),Qr=Cr(),Kf=Sa(),Ba=va(),Zf=Ca(),Da=Ra();function Bt(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(Na())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Qf(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function xn(t){switch(t){case"svg":return Da;case"txt":case"utf8":return Ba;case"png":case"image/png":default:return Kf}}function Xf(t){switch(t){case"svg":return Da;case"terminal":return Zf;case"utf8":default:return Ba}}function Dt(t,e,n){if(!n.cb)return new Promise(function(r,i){try{let s=Qr.create(e,n.opts);return t(s,n.opts,function(o,a){return o?i(o):r(a)})}catch(s){i(s)}});try{let r=Qr.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}we.create=Qr.create;we.toCanvas=Ma().toCanvas;we.toString=function(e,n,r){let i=Bt(e,n,r),s=i.opts?i.opts.type:void 0,o=Xf(s);return Dt(o.render,e,i)};we.toDataURL=function(e,n,r){let i=Bt(e,n,r),s=xn(i.opts.type);return Dt(s.renderToDataURL,e,i)};we.toBuffer=function(e,n,r){let i=Bt(e,n,r),s=xn(i.opts.type);return Dt(s.renderToBuffer,e,i)};we.toFile=function(e,n,r,i){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Na())throw new Error("Too few arguments provided");let s=Bt(n,r,i),o=s.opts.type||Qf(e),l=xn(o).renderToFile.bind(null,e);return Dt(l,n,s)};we.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Bt(n,r,e.emit.bind(e,"error")),o=xn("png").renderToFileStream.bind(null,e);Dt(o,n,i)}});var Ha=y((Yg,Ua)=>{Ua.exports=Fa()});var nc=require("http");var Mu=qe(ws(),1),Nu=qe(Zn(),1),Bu=qe(er(),1),Du=qe(cn(),1),lr=qe(Ps(),1);var Fe=require("fs/promises"),Un=require("path"),rc=require("os"),ic=qe(Ha(),1);var it=require("child_process"),qa=require("fs"),U=require("path"),Ut=require("os"),eh=["fnm_multishells"],th=6e4;function be(t){return eh.some(e=>t.includes(e))}function ei(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var rt=null;function Wa(){if(rt&&!be(rt.PATH??""))return rt;for(let t of ei())try{let e=(0,it.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
|
|
21
|
+
`)){let i=r.indexOf("=");i>0&&(n[r.slice(0,i)]=r.slice(i+1))}return be(n.PATH??"")?rt=null:rt=n,n}catch{}return rt={},{}}function nh(t=Wa()){let e=(0,Ut.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,U.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",i=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,U.join)(e,".npm-global","bin"),(0,U.join)(e,".local","bin"),(0,U.join)(e,".claude","bin"),n],s=r.split(U.delimiter).filter(Boolean),o=new Set(s);for(let a of i)o.has(a)||(s.push(a),o.add(a));return s.join(U.delimiter)}function Xr(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function Tn(){let t=Wa(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=nh(t),e.HOME||(e.HOME=(0,Ut.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Ft(t,e=3e3){try{return(0,it.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Tn()}).trim()||null}catch{return null}}function rh(t){for(let e of ei())try{let n=(0,it.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function ih(){let t=(0,Ut.homedir)();return[(0,U.join)(t,".local","bin","claude"),(0,U.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,U.join)(t,".npm-global","bin","claude")]}function sh(){for(let t of ih())if(Ft(t))return t;try{let t=(0,it.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Tn()}).trim();if(t&&!t.includes("cmux")&&Ft(t))return t}catch{}}function oh(){let t=(0,Ut.homedir)(),e=[process.env.PNPM_HOME,(0,U.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,U.join)(t,".npm-global","bin","codex"),(0,U.join)(t,".local","bin","codex"),...e.map(n=>(0,U.join)(n,"codex"))]}function ah(){let t;for(let n of oh())if(Ft(n)){if(!be(n))return n;t=n}try{let n=(0,it.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Tn()}).trim();if(n&&Ft(n)){if(!be(n))return n;t=t??n}}catch{}let e=rh("codex");if(e&&Ft(e)){if(!be(e))return e;t=t??e}return t}function Ga(t,e){let n=null,r=0;return()=>{let i=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[i])return process.env[i];let s=Date.now();return(!n||s-r>th||!(0,qa.existsSync)(n)||be(n))&&(n=t()??e,r=s,process.stdout.write(JSON.stringify({level:"info",ts:new Date().toISOString(),module:"config",msg:"binary resolved",name:e,path:n,transient:be(n)})+`
|
|
22
|
+
`)),n}}var lh=Ga(sh,"claude"),ch=Ga(ah,"codex");function uh(t,e){return{command:ei()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var _={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Number(process.env.VIBE_IDLE_TIMEOUT_MS)||1800*1e3,auditMaxBytes:Xr("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Xr("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Xr("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return lh()},get codexPath(){return ch()},isTransientPath:be,execViaLoginShell:uh,buildSanitizedEnv:Tn};var Fl=require("fs/promises");var rl=require("child_process"),il=require("fs");var ja={debug:10,info:20,warn:30,error:40},dh=process.env.VIBE_LOG_LEVEL||"info";function za(t,e,n){if(ja[t]<ja[dh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},i=JSON.stringify(r);t==="error"||t==="warn"?process.stderr.write(i+`
|
|
23
|
+
`):process.stdout.write(i+`
|
|
24
|
+
`)}function $a(t={}){function e(n,r,i){typeof r=="string"?za(n,t,r):za(n,{...t,...r},i)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>$a({...t,...n})}}var N=$a({module:"daemon"});var An=require("fs"),nl=require("path");var Va=require("os"),V=require("path"),Ht=(0,V.join)((0,Va.homedir)(),".vibelet"),Ya=(0,V.join)(Ht,"logs"),Ja=(0,V.join)(Ht,"data"),fh=(0,V.join)(Ht,"runtime"),Zg=(0,V.join)(fh,"current"),Ka=(0,V.join)(Ht,"identity.json"),Za=(0,V.join)(Ht,"pairings.json"),In=(0,V.join)(Ja,"sessions.json"),st=(0,V.join)(Ja,"audit.jsonl"),Qa=(0,V.join)(Ya,"daemon.stdout.log"),Xa=(0,V.join)(Ya,"daemon.stderr.log");var H=require("fs");function hh(t,e,n,r){let i=Math.max(0,e-n),s=Math.floor(e*.75);return Math.max(0,Math.min(t,i,r??s))}function qt(t,e){if(!(0,H.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,H.statSync)(t).size,i=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+i<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let s=hh(r,e.maxBytes,i,e.retainBytes),o=(0,H.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(s>0){let l=Buffer.alloc(s);(0,H.readSync)(o,l,0,s,r-s);let c=0;if(r>s){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,H.ftruncateSync)(o,0),a.length>0&&(0,H.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,H.closeSync)(o)}}function el(t){let e=[qt(t.auditPath,{maxBytes:t.auditMaxBytes}),qt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),qt(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var tl=!1,ph=new Set(["ts","event","source","appEvent","level"]);function gh(t={}){let e={};for(let[n,r]of Object.entries(t))ph.has(n)||(e[n]=r);return e}function mh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...gh(n)}}function yh(){tl||((0,An.mkdirSync)((0,nl.dirname)(st),{recursive:!0}),tl=!0)}var ti=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},i){this.write(mh(e,n,r,i))}write(e){yh();try{let n=JSON.stringify(e)+`
|
|
25
|
+
`;qt(st,{maxBytes:_.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,An.appendFileSync)(st,n)}catch{}}},v=new ti;var Y=N.child({module:"claude"}),sl="claude-permission-denial:";function ni(t){process.stderr.write(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
|
|
26
|
+
`)}function _h(t){return typeof t=="string"?t:JSON.stringify(t)}function Sh(t){return/requested permissions|haven't granted/i.test(t)}function ri(t){return t.startsWith(sl)}var Cn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),Y.info({sessionId:this.sessionId,cwd:e},"session initialized"),v.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;Y.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),ni(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.proc=(0,rl.spawn)(_.claudePath,n,{cwd:this.cwd||void 0,stdio:["pipe","pipe","pipe"],env:_.buildSanitizedEnv()}),this.proc.on("error",i=>{let s=i.message;i.code==="ENOENT"&&this.cwd&&!(0,il.existsSync)(this.cwd)&&(s=`Working directory does not exist: ${this.cwd}`),Y.error({sessionId:this.sessionId,error:s,cwd:this.cwd},"spawn error"),v.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:s}),this.handler?.({type:"error",sessionId:this.sessionId,message:s})}),this.buffer="",this.proc.stdout.on("data",i=>{this.buffer+=i.toString();let s=this.buffer.split(`
|
|
27
|
+
`);this.buffer=s.pop();for(let o of s)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Y.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",i=>{let s=i.toString().trim();s&&(Y.debug({sessionId:this.sessionId,stderr:s},"stderr"),this.lastStderr.push(s),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(i,s)=>{Y.info({sessionId:this.sessionId,exitCode:i,signal:s},"process exited");let o=this.interrupted;this.proc=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):i&&i!==0&&!this.sawFinalResult&&(Y.error({sessionId:this.sessionId,exitCode:i,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:`Claude exited with code ${i}`})),this.exitHandler?.(i)})}respondApproval(e,n){if(Y.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return Y.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
|
|
28
|
+
`),!0}setApprovalMode(e){this.approvalMode=e,Y.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Y.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(Y.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),v.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{let r=e.message?.content;if(!Array.isArray(r))break;for(let i of r)i.type==="tool_use"&&this.handler({type:"tool.call",sessionId:this.sessionId,toolName:i.name,input:i.input??{},toolCallId:i.id});break}case"user":{let r=e.message?.content;if(!Array.isArray(r))break;for(let i of r)if(i.type==="tool_result"){let s=_h(i.content);i.is_error===!0&&typeof i.tool_use_id=="string"&&Sh(s)&&this.pendingPermissionDescriptions.set(i.tool_use_id,s),this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i.tool_use_id,output:s})}break}case"control_request":{let r=e.request;r?.subtype==="can_use_tool"&&(v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){ni("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:r||"Claude returned an error result."});break}let i=Array.isArray(e.permission_denials)?e.permission_denials:[];if(i.length>0){let a=i[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${sl}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let s=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;ni("Claude finished. Run `claude --continue` to continue on desktop."),v.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:s,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:s,usage:o});break}}}};var ol=require("child_process"),al=require("fs");var ii=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),i=JSON.stringify(n),s=r.find(o=>JSON.stringify(o.labels)===i);s?s.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),i=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return i.count++,i.totalMs+=r,i.minMs=Math.min(i.minMs,r),i.maxMs=Math.max(i.maxMs,r),i.lastMs=r,this.timers.set(e,i),r}}snapshot(){let e={};for(let[i,s]of this.counters)e[i]=s.map(o=>({...o}));let n={};for(let[i,s]of this.timers)n[i]={...s,minMs:s.minMs===1/0?0:s.minMs};let r={};for(let[i,s]of this.gauges)r[i]=s;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();N.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},I=new ii;var k=N.child({module:"codex"}),kn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e;let i=_.codexPath,s,o=this.buildSpawnArgs();if(_.isTransientPath(i)){let l=_.execViaLoginShell("codex",o);s=l.command,o=l.args,k.info({spawnCmd:s,argsPreview:o.slice(0,2)},"spawning via login shell")}else s=i,k.info({spawnCmd:s,args:o},"spawning");v.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,ol.spawn)(s,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:_.buildSanitizedEnv()}),this.proc.on("error",l=>{let c=l.message;l.code==="ENOENT"&&e&&!(0,al.existsSync)(e)&&(c=`Working directory does not exist: ${e}`),k.error({error:c,cwd:e},"spawn error"),v.emit("driver.error",{agent:"codex",error:c})}),this.proc.stdout.on("data",l=>{this.buffer+=l.toString();let c=this.buffer.split(`
|
|
29
|
+
`);this.buffer=c.pop();for(let u of c)if(u.trim())try{this.handleRaw(JSON.parse(u))}catch{k.warn({linePreview:u.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",l=>{let c=l.toString().trim();c&&(k.debug({stderr:c},"stderr"),this.lastStderr.push(c),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",l=>{k.info({threadId:this.threadId,exitCode:l},"process exited"),l&&l!==0&&k.error({threadId:this.threadId,exitCode:l,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null;for(let[,{reject:c}]of this.pending)c(new Error(`Codex process exited with code ${l}`));this.pending.clear(),this.exitHandler?.(l),l&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${l}`})});let a=I.startTimer("rpc.duration");if(await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:"0.0.1"}}),a(),this.rpcNotify("initialized",{}),n){let l=await this.rpc("thread/resume",{threadId:n});this.threadId=l?.thread?.id??n,k.info({threadId:this.threadId},"thread resumed"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let l=await this.rpc("thread/start",{cwd:e});this.threadId=l?.thread?.id??l?.threadId??"",k.info({threadId:this.threadId},"thread created"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){let e=["app-server"];return this.approvalMode==="autoApprove"&&(e.push("-c",'approval_policy="never"'),e.push("-c",'sandbox_mode="danger-full-access"')),e.push("--listen","stdio://"),e}sendPrompt(e){k.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]}).then(n=>k.debug({resultPreview:JSON.stringify(n).slice(0,200)},"turn/start result")).catch(n=>{k.error({threadId:this.threadId,error:n.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:n.message})})}respondApproval(e,n){let r=Number(e);if(!this.proc?.stdin?.writable)return!1;let i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};return k.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
|
|
30
|
+
`),!0}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,k.info({approvalMode:e},"approval mode updated (takes effect on restart)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,i=I.startTimer("rpc.duration");return new Promise((s,o)=>{if(this.pending.set(r,{resolve:a=>{i(),s(a)},reject:a=>{i(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),i(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
|
|
31
|
+
`),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),k.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),i(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
|
|
32
|
+
`)}handleRaw(e){if(k.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let i=this.pending.get(e.id);this.pending.delete(e.id),e.error?i.reject(new Error(e.error.message??"RPC error")):i.resolve(e.result);return}if(!this.handler)return;let n=e.method,r=e.params;if(n==="item/commandExecution/requestApproval"&&e.id!=null){v.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:"command"}),this.handler({type:"approval.request",sessionId:this.threadId,requestId:String(e.id),toolName:"command",input:{command:r?.command??"",cwd:r?.cwd??""},description:r?.reason??""});return}switch(n&&k.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let i=r?.text??r?.delta??r?.content??"";i?this.handler({type:"text.delta",sessionId:this.threadId,content:i}):k.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:r.output});break;case"item/started":{let i=r?.item;i?.type==="command_execution"&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:"command",input:{command:i.command??""},toolCallId:i.id??""});break}case"turn/completed":{let i=r?.usage?{inputTokens:r.usage.input_tokens??0,outputTokens:r.usage.output_tokens??0}:void 0;k.info({threadId:this.threadId},"turn completed"),v.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:n&&k.debug({method:n},"unhandled notification");break}}};var P=require("fs/promises"),bl=require("fs"),El=require("readline"),A=require("path"),de=require("os");var vh=new Set(["New session","Resumed session","Untitled session"]),wh=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function bh(t){return t.replace(/\s+/g," ").trim()}function Pn(t){return typeof t!="string"?void 0:bh(t)||void 0}function ll(t){let e=Pn(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function ot(t){let e=Pn(t);return!e||vh.has(e)||ll(e)}function Eh(t){for(let e of t.replace(/\r/g,"").split(`
|
|
33
|
+
`)){let n=Pn(e);if(n&&!xh(n)&&!Th(n))return n}}function xh(t){return wh.some(e=>t.startsWith(e))}function Th(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Ih(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function si(t,e=80){if(typeof t!="string")return;let n=Eh(t);if(!n)return;let r=Ih(n),s=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!s||ll(s)))return s.length<=e?s:`${s.slice(0,Math.max(1,e-3)).trimEnd()}...`}function De(t,e){for(let n of t){let r=Pn(n);if(!(!r||ot(r)))return r}return si(e)}var ul=require("child_process"),at=require("fs/promises"),Ee=require("path"),oi=require("os"),dl=require("util");var Ah=(0,dl.promisify)(ul.execFile),Ch=3e3,Wt=null;function ai(){Wt=null}function kh(t){return t.replace(/^['"]|['"]$/g,"")}function Ph(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(kh)}function fl(t){let e=Ph(t);for(let n=0;n<e.length;n+=1){let r=e[n],i=(0,Ee.basename)(r);if(i==="claude"||i==="codex")return{agent:i,args:e.slice(n+1)}}return null}function Rh(t,e){let n=fl(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let i=0;i<r.length;i+=1){let s=r[i];if((s==="--resume"||s==="--session-id")&&r[i+1]&&!r[i+1].startsWith("-"))return r[i+1];if(s.startsWith("--resume="))return s.slice(9);if(s.startsWith("--session-id="))return s.slice(13)}return null}if(r[0]!=="resume")return null;for(let i=1;i<r.length;i+=1){let s=r[i];if(!s.startsWith("-"))return s}return null}function Rn(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Lh(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Oh(t){let e=Rh(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(i=>Lh(t.agent,i));if(n.length!==1)return null;let r=lt(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function Mh(t,e){let n=t,r=e;return(Rn(e.confidence)>Rn(t.confidence)||Rn(e.confidence)===Rn(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function Nh(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,i=e.get(r);e.set(r,i?Mh(i,n):n)}return[...e.values()]}async function li(t,e){try{let{stdout:n}=await Ah(t,e,{maxBuffer:8388608});return n}catch{return""}}async function cl(t){if(!t.sessionFilePath)return t;let e=await Gt(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function Bh(t){return(await li("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
|
|
34
|
+
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Dh(t){let n=(await li("lsof",["-p",String(t),"-Fn"])).split(`
|
|
35
|
+
`).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function Fh(){return(await li("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
|
|
36
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),i=n[2],s=fl(i);return!Number.isFinite(r)||!s?null:{pid:r,command:i,agent:s.agent}}).filter(e=>!!e)}async function Uh(){let t=await Fh();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await Bh(e.pid),sessionFiles:await Dh(e.pid)})))}function Hh(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function qh(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ee.join)((0,oi.homedir)(),".claude","projects",Hh(e)),l=(await(0,at.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let h=await(0,at.stat)((0,Ee.join)(o,f)).catch(()=>null);h&&(!c||h.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:h.mtimeMs})})),!c)return null;let u=(0,Ee.join)(o,c.name),d=lt(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ee.join)((0,oi.homedir)(),".codex","sessions"),r=null;async function i(o){let a=await(0,at.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ee.join)(o,l.name);if(l.isDirectory())await i(c);else if(l.name.endsWith(".jsonl")){let u=await(0,at.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await Gt(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await i(n);let s=r;return s?{sessionId:s.sessionId,filePath:s.path}:null}catch{return null}}async function hl(){if(Wt&&Date.now()<Wt.expiresAt)return Wt.value;let t=await Uh(),e=await Promise.all(t.map(async r=>{let i=Oh(r);if(i)return cl(i);let s=await qh(r.agent,r.cwd);return s?cl({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:s.sessionId,confidence:"low",sessionFilePath:s.filePath}):null})),n=Nh(e.filter(r=>r!==null));return Wt={value:n,expiresAt:Date.now()+Ch},n}var gl=N.child({module:"inventory"}),ct={daemonActive:3,externalRunning:2,idle:1},pl={high:3,medium:2,low:1};function ml(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Wh(t,e){let n=t.runtime.needsAttention?1:0;return(e.runtime.needsAttention?1:0)-n||ct[e.runtime.state]-ct[t.runtime.state]||ml(t,e)}function Gh(t,e){return ct[e.state]>ct[t.state]?e:ct[e.state]<ct[t.state]?t:pl[e.confidence]>pl[t.confidence]?e:t}function jh(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function zh(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function $h(t,e){return e?t?!(ot(e)&&!ot(t)):!0:!1}function ci(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Vh(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:ci()}}function Yh(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",pid:t.pid,command:t.command}}}function Jh(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0}}}function Kh(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,i=t.get(r);if(!i){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let s=$h(i.title,n.title)?n.title:i.title,o=n.cwd||i.cwd,a=Gh(i.runtime,n.runtime),l=i.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=i.sources.includes("process")&&!i.sources.includes("daemon"),d=c?i.lastActivityAt:u?n.lastActivityAt:zh(i.lastActivityAt,n.lastActivityAt);t.set(r,{...i,cwd:o,title:s,createdAt:jh(i.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a})}}function Zh(...t){let e=new Map;for(let n of t)Kh(e,n);return[...e.values()]}function Qh(t,e,n,r,i){let s=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(s){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(s)||c.includes(s),d=i?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&gl.debug({total:t.length,filtered:o.length,search:r,contentMatchIds:i?.size??0},"filter applied"),o}function Xh(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let i=n+r>>1,s=t[i];(e.lastActivityAt.localeCompare(s.lastActivityAt)||s.sessionId.localeCompare(e.sessionId))>0?r=i:n=i+1}if(n>0){let i=t[n-1];if(i.lastActivityAt===e.lastActivityAt&&i.sessionId===e.sessionId)return n}return 0}function ep(t,e,n,r,i,s,o){let a=s?1/0:Math.max(1,e||50),l=Zh(t.sessionRecords.map(Vh),t.scannedSessions,t.runningSessions.map(m=>Yh(m,t.scannedAt)),t.activeSessions.map(Jh)),c=Qh(l,r,i,s,o),u=c.filter(m=>m.runtime.state!=="idle").sort(Wh),d=c.filter(m=>m.runtime.state==="idle").sort(ml),f=Xh(d,n),h=d.slice(f,f+a),p=f+h.length<d.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...u,...h],nextCursor:p}}async function yl(t){let e=new Date().toISOString(),[n,r,i]=await Promise.all([jt(t.agent,t.cwd),hl(),t.search?_l(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&gl.info({search:t.search,contentMatches:i?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),ep({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:n,runningSessions:r,scannedAt:e},t.limit,t.cursor,t.agent,t.cwd,t.search,i)}var se=N.child({module:"scanner"});function xl(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Tl=5e3,di=xl(Tl),fi=xl(Tl);function hi(){di.clear(),fi.clear()}function Il(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}function*Al(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let i=t.indexOf(`
|
|
37
|
+
`,n);i===-1&&(i=t.length);let s=t.substring(n,i);n=i+1,!(s.length===0||s.trim().length===0)&&(yield s,r+=1)}}var ui=512*1024;async function Cl(t,e){if(e<=ui)return(0,P.readFile)(t,"utf-8");let n=await(0,P.open)(t,"r");try{let r=Buffer.alloc(ui),{bytesRead:i}=await n.read(r,0,ui,0);return r.toString("utf-8",0,i)}finally{await n.close()}}function pi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function kl(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?pi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function zt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}function tp(t){return t?.type!=="user"||t.message?.role!=="user"?"":zt(t.message.content)}function Pl(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Rl(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:ci()}}function lt(t,e){let n=(0,A.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function np(t,e){let n=await Cl(t,e),r=Al(n,64),i="",s="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!i&&typeof u.cwd=="string"&&(i=u.cwd),!s&&typeof u.sessionId=="string"&&(s=u.sessionId),o||(o=De([u.customTitle,u.summary])),!l){let d=tp(u),f=De([],d);f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||lt("claude",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function rp(t,e){let n=await Cl(t,e),r=Al(n,96),i="",s="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(i||(i=u.payload?.cwd??u.cwd??""),s||(s=u.payload?.id??u.id??""),o||(o=De([u.payload?.title,u.title])),!l){let d=kl(u),f=d&&!Pl(d)?De([],d):void 0;f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||lt("codex",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function Gt(t,e){let n=await(0,P.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let s=await np(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let i=await rp(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Sl(t){let e=(0,A.join)((0,de.homedir)(),".claude","projects");try{let n;t?n=[Il(t)]:n=(await(0,P.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let r=[];for(let o of n){let a=(0,A.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&r.push((0,A.join)(a,c))}return(await Promise.all(r.map(o=>Gt(o,"claude")))).filter(o=>o!==null).map(o=>Rl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list claude sessions"),[]}}async function vl(t){let e=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let n=await(0,P.readdir)(e).catch(()=>[]),r=[];for(let o of n){let a=(0,A.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,A.join)(a,c),d=await(0,P.readdir)(u).catch(()=>[]);for(let f of d){let h=(0,A.join)(u,f),g=await(0,P.readdir)(h).catch(()=>[]);for(let p of g)p.endsWith(".jsonl")&&r.push((0,A.join)(h,p))}}}return(await Promise.all(r.map(o=>Gt(o,"codex")))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>Rl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list codex sessions"),[]}}async function jt(t,e){let r=`list:${(0,de.homedir)()}:${t??"all"}:${e??""}`,i=di.get(r);if(i)return i;let s;if(t==="claude")s=await Sl(e);else if(t==="codex")s=await vl(e);else{let[o,a]=await Promise.all([Sl(e),vl(e)]);s=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return di.set(r,s),s}async function _l(t,e){let r=`search:${(0,de.homedir)()}:${t}:${e??"all"}`,i=fi.get(r);if(i)return i;let s=new Set,o=t.toLowerCase();async function a(){let c=(0,A.join)((0,de.homedir)(),".claude","projects");try{let u=await(0,P.readdir)(c,{withFileTypes:!0}),d=[];for(let h of u){if(!h.isDirectory())continue;let g=(0,A.join)(c,h.name),p=await(0,P.readdir)(g).catch(()=>[]);for(let m of p)m.endsWith(".jsonl")&&d.push((0,A.join)(g,m))}let f=await Promise.all(d.map(h=>wl(h,o,"claude")));for(let h of f)h&&s.add(h)}catch(u){se.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let u=[];async function d(h){let g=await(0,P.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let p of g){let m=(0,A.join)(h,p.name);p.isDirectory()?await d(m):p.name.endsWith(".jsonl")&&u.push(m)}}await d(c);let f=await Promise.all(u.map(h=>wl(h,o,"codex")));for(let h of f)h&&s.add(h)}catch(u){se.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),fi.set(r,s),s}async function wl(t,e,n){let r=(0,bl.createReadStream)(t,{encoding:"utf-8"}),i=(0,El.createInterface)({input:r,crlfDelay:1/0}),s=n==="claude"?ip:sp,o="",a=!1;try{for await(let l of i){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=s(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{i.close(),r.destroy()}return a?o||lt(n,t):null}function ip(t){return t?.type==="user"&&t.message?.role==="user"||t?.type==="assistant"&&t.message?.role==="assistant"?zt(t.message.content):""}function sp(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return pi(t.payload.content)}let e=kl(t);return e||""}async function Ln(t,e,n){let r=[];if(e==="claude"){let i=(0,A.join)((0,de.homedir)(),".claude","projects");try{let s=n?[Il(n)]:await(0,P.readdir)(i);for(let o of s){let a=(0,A.join)(i,o,`${t}.jsonl`);try{let l=await(0,P.readFile)(a,"utf-8");for(let c of l.split(`
|
|
38
|
+
`))if(c.trim())try{let u=JSON.parse(c);if(u.type==="user"&&u.message?.role==="user"){let d=zt(u.message.content);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=zt(u.message.content);d&&r.push({role:"assistant",content:d})}}catch(u){se.warn({error:String(u)},"failed to parse claude history line")}if(r.length>0)break}catch(l){l.code!=="ENOENT"&&se.warn({error:String(l)},"failed to read claude session file")}}}catch(s){se.warn({error:String(s)},"failed to read claude session history")}}else if(e==="codex"){let i=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let s=await Ll(i,t);if(s){let o=await(0,P.readFile)(s,"utf-8");for(let a of o.split(`
|
|
39
|
+
`))if(a.trim())try{let l=JSON.parse(a);if(l.type==="response_item"&&l.payload?.type==="message"){let c=l.payload.role;if(c!=="user"&&c!=="assistant")continue;let u=pi(l.payload.content);if(!u||c==="user"&&Pl(u))continue;r.push({role:c,content:u})}}catch(l){se.warn({error:String(l)},"failed to parse codex history line")}}}catch(s){se.warn({error:String(s)},"failed to read codex session history")}}return r}async function Ll(t,e){try{let n=await(0,P.readdir)(t,{withFileTypes:!0});for(let r of n){let i=(0,A.join)(t,r.name);if(r.isDirectory()){let s=await Ll(i,e);if(s)return s}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return i}}catch(n){se.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var ut=require("fs"),Ol=require("path");var op=500,On=class{records;debounceTimer=null;constructor(){this.records=this.loadFromDisk()}getAll(){return this.records}find(e){return this.records.find(n=>n.sessionId===e)}upsert(e){let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},op)}loadFromDisk(){try{let e=(0,ut.readFileSync)(In,"utf-8");return JSON.parse(e).map(n=>({...n,lastActivityAt:n.lastActivityAt??n.createdAt}))}catch{return[]}}saveToDisk(){(0,ut.mkdirSync)((0,Ol.dirname)(In),{recursive:!0}),(0,ut.writeFileSync)(In,JSON.stringify(this.records,null,2))}};var Ml=require("path"),Nl=require("os");function Mn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Ml.join)((0,Nl.homedir)(),t.slice(2)):t}var $t=N.child({module:"push"}),ap="https://exp.host/--/api/v2/push/send",dt=new Set;function gi(t){dt.add(t),$t.info({token:t,total:dt.size},"push token registered")}function mi(t){dt.delete(t),$t.info({token:t,total:dt.size},"push token unregistered")}async function Bl(t,e,n){if(dt.size===0)return;let r=[...dt].map(i=>({to:i,sound:"default",title:t,body:e,data:n}));try{let i=await fetch(ap,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});i.ok?$t.debug({count:r.length},"push sent"):$t.error({status:i.status,statusText:i.statusText},"push send failed")}catch(i){$t.error({error:String(i)},"push send error")}}var b=N.child({module:"manager"}),lp="Done.",Dl=180;function xe(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt}}var Nn=class{constructor(e=Bl){this.pushSender=e;this.startIdleSweep()}sessions=new Map;store=new On;idleSweepInterval=null;startIdleSweep(){_.idleTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=_.idleTimeoutMs;if(n<=0)return;let r=3600*1e3;for(let[i,s]of this.sessions){if(!s.active&&!s.driver){if(s.clients.size===0){let a=e-s.lastActivityTs;a>=r&&(b.info({sessionId:s.sessionId,inactiveMs:a},"removing inactive session from memory"),I.increment("session.cleanup",{reason:"inactive"}),this.sessions.delete(i))}continue}if(!s.active||!s.driver||s.isResponding)continue;let o=e-s.lastActivityTs;o<n||(b.info({sessionId:s.sessionId,agent:s.agent,idleMs:o,timeoutMs:n},"stopping idle driver"),I.increment("driver.idle_timeout",{agent:s.agent}),v.emit("driver.idle_timeout",{sessionId:s.sessionId,agent:s.agent,idleMs:o}),s.driver.stop(),s.active=!1,s.driver=null,this.updateGauges(),this.touchSession(s.sessionId))}}bindDriverLifecycle(e,n,r,i){e.driver?.onMessage(s=>{if(b.debug({agent:n,context:r,msgType:s.type,sessionId:e.sessionId},"driver message received"),s.type!=="response"&&s.sessionId&&s.sessionId!==e.sessionId&&!this.sessions.has(s.sessionId)){let o=e.sessionId;b.info({oldSessionId:o,newSessionId:s.sessionId},"session ID updated"),this.store.remove(o),this.sessions.delete(o),e.sessionId=s.sessionId,this.sessions.set(s.sessionId,e),this.store.upsert(xe(e)),i&&this.reply(i,`id_update_${Date.now()}`,!0,{sessionId:s.sessionId,oldSessionId:o})}(s.type==="session.done"||s.type==="session.interrupted")&&(e.isResponding=!1,e.pendingApproval=void 0),s.type==="approval.request"&&(e.pendingApproval={requestId:s.requestId,toolName:s.toolName,input:s.input,description:s.description}),n==="claude"&&s.type==="approval.request"&&ri(s.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[s.requestId]={message:e.lastUserMessage,toolName:s.toolName}:b.warn({sessionId:e.sessionId,requestId:s.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,s.type!=="text.delta"),this.broadcast(e.sessionId,s)}),e.driver?.onExit?.(s=>{b.info({agent:n,context:r,exitCode:s,sessionId:e.sessionId},"driver exited"),v.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:s}),I.increment("driver.exit",{agent:n,abnormal:s&&s!==0?"true":"false"}),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",e.pendingApproval=void 0,this.updateGauges(),this.touchSession(e.sessionId)})}resendPendingApproval(e,n){if(!e.pendingApproval||n.readyState!==1)return;let{requestId:r,toolName:i,input:s,description:o}=e.pendingApproval;b.info({sessionId:e.sessionId,requestId:r,toolName:i},"resending pending approval to reconnected client");let a={type:"approval.request",sessionId:e.sessionId,requestId:r,toolName:i,input:s,description:o};n.send(JSON.stringify(a))}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Dl?n:`${n.slice(0,Math.max(1,Dl-3)).trimEnd()}...`:lp}touchSession(e,n=!0){let r=new Date().toISOString(),i=this.sessions.get(e);if(i){i.lastActivityAt=r,i.lastActivityTs=Date.now(),n&&this.store.upsert(xe(i));return}let s=this.store.find(e);s&&this.store.upsert({...s,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;I.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{}});return e}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}removeClient(e){for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep();for(let e of this.sessions.values()){try{e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear()}this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,i,s,o){i=Mn(i),b.info({agent:r,cwd:i,approvalMode:s,continueSession:o},"creating session");try{if(!(await(0,Fl.stat)(i)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${i}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${i}`);return}if(o)try{let a=await jt(r,i);if(a.length>0){let l=a[0];return b.info({sessionId:l.sessionId,cwd:i},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,i,s)}b.info("continue mode: no previous sessions found, creating new")}catch(a){b.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=I.startTimer("driver.spawn"),l=this.createDriver(r),c=await l.start(i,void 0,s),u=a();b.info({sessionId:c,agent:r,spawnMs:u},"session created"),I.increment("session.create",{agent:r}),v.emit("session.create",{sessionId:c,agent:r,cwd:i,approvalMode:s});let d={sessionId:c,agent:r,cwd:i,approvalMode:s,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{}};this.sessions.set(c,d),this.store.upsert(xe(d)),this.updateGauges(),hi(),ai(),this.bindDriverLifecycle(d,r,"",e),this.reply(e,n,!0,{sessionId:c})}catch(a){b.error({agent:r,cwd:i,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,i,s,o){let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await Ln(r,i,a.cwd);if(f.length>0){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,approvalMode:a.approvalMode};e.send(JSON.stringify(h))}this.resendPendingApproval(a,e),this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=s||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=I.startTimer("driver.spawn"),h=this.createDriver(i),g=await h.start(c,r,u),p=f();b.info({sessionId:g,agent:i,spawnMs:p},"session resumed"),I.increment("session.resume",{agent:i}),v.emit("session.resume",{sessionId:g,agent:i,cwd:c});let m={sessionId:g,agent:i,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{}};this.sessions.set(g,m),this.store.upsert(xe(m)),this.updateGauges(),this.bindDriverLifecycle(m,i," (resumed)",e);let S=await Ln(r,i,c);if(S.length>0){b.info({sessionId:r,historyCount:S.length},"sending history messages");let J={type:"session.history",sessionId:g,messages:S,approvalMode:u};e.send(JSON.stringify(J))}this.reply(e,n,!0,{sessionId:g})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>200&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-200))}async sendMessage(e,n,r,i,s,o){let a=this.sessions.get(r);if(!a||!a.driver){let l,c="",u,d="",f=new Date().toISOString(),h=new Date().toISOString(),g=this.store.find(r);if(g)l=g.agent,c=g.cwd||"",u=g.approvalMode,d=g.title,f=g.createdAt,h=g.lastActivityAt;else{let m=(await jt(s)).find(S=>S.sessionId===r);m?(l=m.agent,c=m.cwd||"",d=m.title??"",f=m.createdAt,h=m.lastActivityAt):s&&(l=s)}if(!u&&a&&(u=a.approvalMode),!l){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:l,source:g?"record":"scanner"},"auto-reconnecting session"),I.increment("session.reconnect",{agent:l}),v.emit("session.reconnect",{sessionId:r,agent:l,source:g?"record":"scanner"});try{let p=this.createDriver(l);await p.start(c,r,u),a?(a.approvalMode=u,a.driver=p,a.active=!0,a.clients.add(e),a.lastActivityAt=h,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=a.acceptedClientMessageIds??[],a.syntheticApprovalRetries=a.syntheticApprovalRetries??{}):(a={sessionId:r,agent:l,cwd:c,approvalMode:u,driver:p,clients:new Set([e]),title:d,createdAt:f,lastActivityAt:h,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{}},this.sessions.set(r,a)),this.bindDriverLifecycle(a,l," (reconnected)"),this.store.upsert(xe(a)),this.updateGauges()}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(a.clients.add(e),o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),v.emit("session.send",{sessionId:r,agent:a.agent,messagePreview:i.slice(0,100)}),ot(a.title)){let l=si(i,50);l&&l!==a.title&&(a.title=l),this.store.upsert(xe(a))}this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=i,o&&this.rememberAcceptedClientMessage(a,o),a.driver.sendPrompt(i),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async approve(e,n,r,i,s){let o=this.sessions.get(r);o&&(o.pendingApproval=void 0);let a=o?.syntheticApprovalRetries[i];if(o&&a&&ri(i)){delete o.syntheticApprovalRetries[i],v.emit("approval.response",{sessionId:r,requestId:i,approved:s}),this.touchSession(o.sessionId),this.reply(e,n,!0),s&&await this.retrySyntheticClaudeApproval(o,a);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(v.emit("approval.response",{sessionId:r,requestId:i,approved:s}),this.touchSession(o.sessionId),!o.driver.respondApproval(i,s)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.isResponding=!0,this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",i=this.createDriver(e.agent);await i.start(e.cwd,e.sessionId,r),e.driver=i,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(xe(e)),this.updateGauges(),this.touchSession(e.sessionId),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),i.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,this.updateGauges(),this.touchSession(e.sessionId),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,i){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}let o=s.approvalMode;if(s.approvalMode=i,this.store.upsert(xe(s)),b.info({sessionId:r,agent:s.agent,oldMode:o,newMode:i},"approval mode changed"),s.driver&&(s.driver.setApprovalMode(i),s.agent==="codex"&&s.active&&o!==i))try{s.driver.stop();let a=this.createDriver("codex");await a.start(s.cwd,s.sessionId,i),s.driver=a,this.bindDriverLifecycle(s,"codex"," (mode change)"),b.info({sessionId:r},"codex driver restarted with new approval mode")}catch(a){b.error({sessionId:r,error:String(a)},"failed to restart codex after approval mode change"),s.driver=null,s.active=!1,this.updateGauges()}this.reply(e,n,!0,{approvalMode:i})}interrupt(e,n,r){let i=this.sessions.get(r);if(!i?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}v.emit("session.interrupt",{sessionId:r,agent:i.agent}),i.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:i.agent},"stopping session"),v.emit("session.stop",{sessionId:r,agent:i.agent}),i.driver?.stop(),i.active=!1,i.driver=null,this.updateGauges(),this.touchSession(i.sessionId),this.reply(e,n,!0)}deleteSession(e,n,r){let i=this.sessions.get(r);i&&(b.info({sessionId:r,agent:i.agent},"deleting session"),i.driver?.stop(),this.sessions.delete(r)),v.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),hi(),ai(),this.reply(e,n,!0)}async sendHistory(e,n,r,i){let s=this.sessions.get(r);s&&s.clients.add(e);let o=s?.cwd??this.store.find(r)?.cwd??"",a=await Ln(r,i,o);b.info({sessionId:r,historyCount:a.length,isResponding:s?.isResponding,approvalMode:s?.approvalMode},"sending history");let l={type:"session.history",sessionId:r,messages:a,isResponding:s?.isResponding||void 0,approvalMode:s?.approvalMode};e.send(JSON.stringify(l)),s&&this.resendPendingApproval(s,e),this.reply(e,n,!0)}async listSessions(e,n,r,i,s,o=50,a){try{let l=await yl({agent:r,cwd:i,search:s,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new Cn;case"codex":return new kn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let i=JSON.stringify(n),s=r.clients.size,o=0,a=0;for(let l of r.clients)l.readyState===1?(l.send(i),o++):a++;if(a>0&&I.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:o,total:s},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let l=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(l,c,{sessionId:e,agent:r.agent});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,i,s){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:i,error:s};e.send(JSON.stringify(o))}};function yi(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Ul=require("child_process");function cp(t,e){return(0,Ul.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function up(t){let e=t.split(`
|
|
40
|
+
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Hl(t,e=cp){let n;try{n=up(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let i=e("ps",["-p",String(r),"-o","command="]);return i?{pid:r,command:i}:{pid:r}}catch{return{pid:r}}})}var ft=require("fs"),_i=require("os"),Wl=require("crypto"),Gl=require("path");function jl(t){return(0,Wl.randomBytes)(t).toString("base64url")}function dp(){return`d_${jl(12)}`}function fp(){return(0,_i.hostname)()}function hp(){let t=(0,_i.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function pp(t){return{daemonId:dp(),daemonSecret:jl(32),displayName:fp(),canonicalHost:hp(),port:t,createdAt:new Date().toISOString()}}function ql(t,e){(0,ft.mkdirSync)((0,Gl.dirname)(e),{recursive:!0}),(0,ft.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
41
|
+
`,"utf8")}function zl(t,e=Ka){try{let r=(0,ft.readFileSync)(e,"utf8"),i=JSON.parse(r);if(typeof i.daemonId=="string"&&typeof i.daemonSecret=="string"&&typeof i.displayName=="string"&&typeof i.canonicalHost=="string"&&typeof i.createdAt=="string"){let s={daemonId:i.daemonId,daemonSecret:i.daemonSecret,displayName:i.displayName,canonicalHost:i.canonicalHost,port:typeof i.port=="number"&&Number.isFinite(i.port)?i.port:t,createdAt:i.createdAt};return s.port!==t&&(s.port=t,ql(s,e)),s}}catch{}let n=pp(t);return ql(n,e),n}var ht=require("crypto"),pt=require("fs"),Vl=require("path");function Si(t){return(0,ht.randomBytes)(t).toString("base64url")}function vi(t){return(0,ht.createHash)("sha256").update(t).digest("hex")}function $l(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,ht.timingSafeEqual)(n,r)}function gp(t){try{let e=(0,pt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function Vt(t,e){(0,pt.mkdirSync)((0,Vl.dirname)(t),{recursive:!0}),(0,pt.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
42
|
+
`,"utf8")}var Bn=class{constructor(e=Za){this.pairingsPath=e;this.records=gp(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${Si(8)}`,r=Si(24),i=new Date(Date.now()+e).toISOString(),s={pairingId:n,pairNonce:r,expiresAt:i};return this.windows.set(r,s),s}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),i=Si(32),s={deviceId:e,deviceName:n,tokenHash:vi(i),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=s:this.records.unshift(s),Vt(this.pairingsPath,this.records),i}validatePairToken(e,n,r=!0){let i=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!i)return!1;let s=vi(n);return $l(i.tokenHash,s)?(r&&(i.lastSeenAt=new Date().toISOString(),Vt(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=vi(e),i=this.records.find(s=>!s.revokedAt&&$l(s.tokenHash,r));return i?(n&&(i.lastSeenAt=new Date().toISOString(),Vt(this.pairingsPath,this.records)),i):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Vt(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Vt(this.pairingsPath,this.records)}};function Dn(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function mp(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Yl(t,e){return mp(t)??e}function yp(t,e){return!!(t&&e&&t===e)}function wi(t,e,n,r=!0){return t?yp(t,e)?!0:!!n(t,r):!1}var Jl=require("child_process");function bi(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Kl(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function _p(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Sp(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Ei(t){return!!t&&!_p(t)&&!Sp(t)}function gt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Zl(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function vp(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let i of r)i.internal||i.family!=="IPv4"||Ei(i.address)&&(Kl(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function wp(t){let e=JSON.parse(t),n=gt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>gt(o)).filter(o=>!!o).filter(o=>Kl(o)&&Ei(o)),i=r[0]??n,s=[...n&&n!==i?[n]:[],...r.filter(o=>o!==i)];return{canonicalHost:i,fallbackHosts:s}}function Ql(t=Jl.execFileSync){try{let e=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return wp(e)}catch{return{fallbackHosts:[]}}}function Xl(t){let e=gt(t.canonicalHost),n=gt(t.configuredCanonicalHost)||gt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...vp(t.interfaces)].map(i=>gt(i)).filter(i=>!!i).filter(i=>Ei(i)).filter((i,s,o)=>i!==n&&o.indexOf(i)===s);return{canonicalHost:n,fallbackHosts:r}}function ec(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var ee=N.child({module:"daemon"}),Yt=N.child({module:"ws"}),Jt=new Nn,D=zl(_.port),Te=new Bn,Fn=new Set,xi=new WeakSet,tc=!1,sc=Date.now(),mt=null;function yt(){let t=Ql();return Xl({canonicalHost:D.canonicalHost,configuredCanonicalHost:_.canonicalHost,configuredFallbackHosts:Zl(_.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,rc.networkInterfaces)()})}async function bp(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function Q(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function oc(){let t=Te.openWindow(),e=yt(),n=e.canonicalHost,r=D.port,i=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(_.relayUrl)try{let s=new URL(_.relayUrl);n=s.hostname,r=s.port?Number(s.port):s.protocol==="https:"?443:80,i=[e.canonicalHost,...i??[]].filter(Boolean)}catch{ee.warn({relayUrl:_.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:n,fallbackHosts:i,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Ep(t){let e=await(0,Fe.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let i=await(0,Fe.stat)((0,Un.join)(t,r)).catch(()=>null);i&&n.push({name:r,isDirectory:i.isDirectory()})}return n.sort((r,i)=>r.isDirectory!==i.isDirectory?r.isDirectory?-1:1:r.name.localeCompare(i.name)),{entries:n}}var Kt=(0,nc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${_.port}`);if(n.pathname==="/health"){let i=yt(),s={status:"ok",version:"0.0.1",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:i.canonicalHost,uptimeSeconds:Math.round((Date.now()-sc)/1e3),activeSessions:Jt.getActiveSessionCount(),pairedDevices:Te.pairedCount(),wsClients:X.clients.size,drivers:Jt.getDriverCounts(),metrics:I.snapshot()};_.relayUrl&&(s.relayUrl=_.relayUrl),Q(e,200,s);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,oc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Te.reset(),Q(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,{status:"stopping"}),setTimeout(()=>Ue("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let i=await bp(t);if(i.daemonId!==D.daemonId||typeof i.pairNonce!="string"||typeof i.deviceId!="string"||typeof i.deviceName!="string"){Q(e,400,{error:"invalid_pair_request"});return}if(!Te.consumeWindow(i.pairNonce)){Q(e,401,{error:"pair_window_expired"});return}let o=Te.issuePairToken(i.deviceId,i.deviceName),a=yt();Q(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:D.port,deviceId:i.deviceId,pairToken:o})}catch(i){Q(e,400,{error:String(i)})}return}let r=Yl(t.headers.authorization,n.searchParams.get("token"));if(!wi(r,_.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s),!1)){e.writeHead(401),e.end("Unauthorized");return}if(n.pathname==="/file"){let i=n.searchParams.get("path");if(!i){e.writeHead(400),e.end("Missing path parameter");return}try{let s=Mn(i);if(!(await(0,Fe.stat)(s)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Un.extname)(s).toLowerCase(),c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf"}[a]||"application/octet-stream",u=await(0,Fe.readFile)(s);e.writeHead(200,{"Content-Type":c,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end("Vibelet Daemon v0.0.1")}),X=new lr.default({server:Kt});Kt.on("connection",t=>{Fn.add(t),t.on("close",()=>{Fn.delete(t)})});X.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${_.port}`).searchParams.get("token");if(wi(r,_.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s)))xi.add(t);else if(r){t.close(4001,"Unauthorized");return}Yt.info({clients:X.clients.size},"client connected"),I.increment("ws.connect"),I.gauge("ws.clients",X.clients.size),v.emit("ws.connect",{clients:X.clients.size}),t.on("message",async i=>{try{let s=JSON.parse(ec(i));if(!s||typeof s.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(s.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=s;if(!xi.has(t)){if(o.action==="auth.hello"&&o.daemonId===D.daemonId&&Te.validatePairToken(o.deviceId,o.pairToken)){xi.add(t),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:D.daemonId,displayName:D.displayName}}));return}if(o.action==="auth.hello"){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)v.emitApp(a.event,a.level,a.data??{},a.ts);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await Ep(o.path);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(s.action==="push.register"){yi(s,{registerToken:gi,unregisterToken:mi,respond:a=>t.send(JSON.stringify(a))});return}if(s.action==="push.unregister"){yi(s,{registerToken:gi,unregisterToken:mi,respond:a=>t.send(JSON.stringify(a))});return}await Jt.handle(t,o)}catch(s){Yt.error({error:String(s)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(s)}))}}),t.on("close",()=>{Yt.info({clients:X.clients.size},"client disconnected"),I.increment("ws.disconnect"),I.gauge("ws.clients",X.clients.size),v.emit("ws.disconnect",{clients:X.clients.size}),Jt.removeClient(t)}),t.on("error",i=>{Yt.error({error:i.message},"websocket error")})});function Ti(){for(let t of Fn)try{t.destroy()}catch{}Fn.clear()}function ac(){let t=el({auditPath:st,stdoutLogPath:Qa,stderrLogPath:Xa,auditMaxBytes:_.auditMaxBytes,logMaxBytes:_.daemonLogMaxBytes});t.trimmedFiles>0&&ee.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function xp(){mt||(mt=setInterval(ac,_.storageHousekeepingIntervalMs),mt.unref())}function Tp(){mt&&(clearInterval(mt),mt=null)}function Ue(t,e=0){if(!tc){tc=!0,ee.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-sc)/1e3)}),I.stopPeriodicLog(),Tp(),Jt.shutdown();for(let n of X.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}X.close(n=>{n&&ee.error({error:String(n)},"websocket close error")}),Kt.close(n=>{if(n){ee.error({error:String(n)},"http close error"),Ti(),process.exit(1);return}Ti(),process.exit(e)}),setTimeout(()=>{ee.error("force exiting after shutdown timeout"),Ti(),process.exit(e||1)},3e3).unref()}}X.on("error",t=>{Yt.error({error:t.message},"wss error")});Kt.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Hl(_.port).filter(n=>n.pid!==process.pid);ee.error({port:_.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else ee.error({error:String(t)},"server error");Ue(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>Ue("SIGINT"));process.once("SIGTERM",()=>Ue("SIGTERM"));process.once("SIGHUP",()=>Ue("SIGHUP"));process.once("SIGTTIN",()=>Ue("SIGTTIN"));process.once("SIGTSTP",()=>Ue("SIGTSTP"));process.on("uncaughtException",t=>{ee.error({error:String(t),stack:t.stack},"uncaughtException"),v.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{ee.error({reason:String(t)},"unhandledRejection"),v.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});Kt.listen(_.port,async()=>{ac(),v.emit("daemon.start",{port:_.port}),I.startPeriodicLog(),xp(),ee.info({port:_.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:yt().canonicalHost,fallbackHosts:yt().fallbackHosts,claudePath:_.claudePath,codexPath:_.codexPath,auditMaxBytes:_.auditMaxBytes,daemonLogMaxBytes:_.daemonLogMaxBytes,storageHousekeepingIntervalMs:_.storageHousekeepingIntervalMs},"daemon started");let t=yt(),e=oc();process.stdout.write(`
|
|
43
|
+
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
44
|
+
\u2551 Vibelet Daemon v0.0.1 \u2551
|
|
45
|
+
\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
|
|
46
|
+
\u2551 Port: ${String(_.port).padEnd(28)}\u2551
|
|
47
|
+
\u2551 ID: ${D.daemonId.slice(0,28).padEnd(28)}\u2551
|
|
48
|
+
\u2551 Host: ${t.canonicalHost.slice(0,28).padEnd(28)}\u2551
|
|
49
|
+
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
|
|
50
|
+
|
|
51
|
+
Pair with: npx @vibelet/cli
|
|
52
|
+
Host: ${t.canonicalHost}
|
|
53
|
+
Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
|
|
54
|
+
|
|
55
|
+
Claude: ${_.claudePath}
|
|
56
|
+
Codex: ${_.codexPath}
|
|
57
|
+
`);try{let n=await ic.default.toString(JSON.stringify(e),{type:"terminal",small:!0});process.stdout.write(`
|
|
58
|
+
Scan this QR code with Vibelet app:
|
|
59
|
+
|
|
60
|
+
${n}
|
|
61
|
+
`)}catch{}});
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vibelet/cli",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "macOS CLI for installing and running the Vibelet daemon",
|
|
5
|
+
"files": [
|
|
6
|
+
"bin/vibelet.mjs",
|
|
7
|
+
"dist/index.cjs",
|
|
8
|
+
"README.md",
|
|
9
|
+
"package.json"
|
|
10
|
+
],
|
|
11
|
+
"bin": {
|
|
12
|
+
"vibelet": "bin/vibelet.mjs"
|
|
13
|
+
},
|
|
14
|
+
"os": [
|
|
15
|
+
"darwin",
|
|
16
|
+
"linux",
|
|
17
|
+
"win32"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=18"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "pnpm -C packages/shared build && pnpm -C daemon build && pnpm -C daemon build:release",
|
|
27
|
+
"prepack": "pnpm build",
|
|
28
|
+
"dev:app": "pnpm -C app dev",
|
|
29
|
+
"dev:daemon": "pnpm -C daemon dev"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"qrcode": "^1.5.4"
|
|
33
|
+
}
|
|
34
|
+
}
|