vibelet 0.0.1 → 0.0.2
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 +50 -0
- package/bin/vibelet.mjs +674 -0
- package/dist/index.cjs +61 -0
- package/package.json +25 -4
- package/index.js +0 -2
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Vibelet
|
|
2
|
+
|
|
3
|
+
`@vibelet/cli` is a macOS CLI that installs and manages the Vibelet daemon for remote coding sessions. The same package is also published as `vibelet`.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- macOS
|
|
8
|
+
- Node.js 18 or newer
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npx @vibelet/cli
|
|
14
|
+
npx vibelet
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Or install it globally:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install -g @vibelet/cli
|
|
21
|
+
npm install -g vibelet
|
|
22
|
+
vibelet
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Commands
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
vibelet
|
|
29
|
+
vibelet status
|
|
30
|
+
vibelet logs
|
|
31
|
+
vibelet reset
|
|
32
|
+
vibelet --help
|
|
33
|
+
vibelet --version
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Release
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pnpm publish:dual:dry-run
|
|
40
|
+
pnpm publish:dual
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The dual publish script builds once, then publishes the same CLI bundle to both `@vibelet/cli` and `vibelet`. The dry-run path stages both packages and validates them with `npm pack --dry-run` without touching the registry.
|
|
44
|
+
|
|
45
|
+
## Notes
|
|
46
|
+
|
|
47
|
+
- The npm package publishes the CLI plus a minified daemon runtime bundle.
|
|
48
|
+
- The package is intended for end users of the macOS host daemon, not for importing as a library.
|
|
49
|
+
- The daemon keeps `~/.vibelet/data/audit.jsonl` and `~/.vibelet/logs/daemon.*.log` size-bounded by trimming the oldest content in place.
|
|
50
|
+
- 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,674 @@
|
|
|
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(`Package names:\n`);
|
|
495
|
+
process.stdout.write(` @vibelet/cli\n`);
|
|
496
|
+
process.stdout.write(` vibelet\n\n`);
|
|
497
|
+
process.stdout.write(`Usage:\n`);
|
|
498
|
+
process.stdout.write(` npx ${packageJson.name} Install/start the daemon and print a pairing QR code\n`);
|
|
499
|
+
process.stdout.write(` npx ${packageJson.name} start Same as above\n`);
|
|
500
|
+
process.stdout.write(` npx ${packageJson.name} --relay <url> Use a tunnel URL for remote access\n`);
|
|
501
|
+
process.stdout.write(` npx ${packageJson.name} stop Stop the daemon\n`);
|
|
502
|
+
process.stdout.write(` npx ${packageJson.name} restart Restart the daemon\n`);
|
|
503
|
+
process.stdout.write(` npx ${packageJson.name} status Show service and daemon status\n`);
|
|
504
|
+
process.stdout.write(` npx ${packageJson.name} logs Print recent daemon logs\n`);
|
|
505
|
+
process.stdout.write(` npx ${packageJson.name} reset Reset pairings and print a fresh QR code\n`);
|
|
506
|
+
process.stdout.write(` npx ${packageJson.name} --help Show this help text\n`);
|
|
507
|
+
process.stdout.write(` npx ${packageJson.name} --version Show the installed CLI version\n`);
|
|
508
|
+
process.stdout.write(`\n`);
|
|
509
|
+
process.stdout.write(`You can also invoke the published alias with:\n`);
|
|
510
|
+
process.stdout.write(` npx ${packageJson.name === 'vibelet' ? '@vibelet/cli' : 'vibelet'}\n`);
|
|
511
|
+
process.stdout.write(` vibelet\n`);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function parseRelayArg() {
|
|
515
|
+
const idx = process.argv.indexOf('--relay');
|
|
516
|
+
if (idx === -1) return null;
|
|
517
|
+
const url = process.argv[idx + 1];
|
|
518
|
+
if (!url || url.startsWith('-')) {
|
|
519
|
+
fail('--relay requires a URL argument (e.g. --relay https://abc.trycloudflare.com)');
|
|
520
|
+
}
|
|
521
|
+
// Remove --relay and URL from argv so they don't interfere with command parsing
|
|
522
|
+
process.argv.splice(idx, 2);
|
|
523
|
+
return url;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function loadRelayConfig() {
|
|
527
|
+
try {
|
|
528
|
+
const data = JSON.parse(readFileSync(relayConfigPath, 'utf8'));
|
|
529
|
+
return data.relayUrl || '';
|
|
530
|
+
} catch {
|
|
531
|
+
return '';
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function saveRelayConfig(relayUrl) {
|
|
536
|
+
mkdirSync(vibeletDir, { recursive: true });
|
|
537
|
+
writeFileSync(relayConfigPath, JSON.stringify({ relayUrl }, null, 2) + '\n', 'utf8');
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function clearRelayConfig() {
|
|
541
|
+
rmSync(relayConfigPath, { force: true });
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
async function main() {
|
|
545
|
+
const relayArg = parseRelayArg();
|
|
546
|
+
// --relay "" clears saved relay; --relay <url> saves it; omitted uses saved value
|
|
547
|
+
if (relayArg !== null) {
|
|
548
|
+
if (relayArg) {
|
|
549
|
+
saveRelayConfig(relayArg);
|
|
550
|
+
} else {
|
|
551
|
+
clearRelayConfig();
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
const relayUrl = relayArg || loadRelayConfig();
|
|
555
|
+
if (relayUrl) {
|
|
556
|
+
process.env.VIBELET_RELAY_URL = relayUrl;
|
|
557
|
+
}
|
|
558
|
+
const backend = resolveBackend();
|
|
559
|
+
const command = process.argv[2] ?? 'default';
|
|
560
|
+
|
|
561
|
+
if (command === '--help' || command === '-h' || command === 'help') {
|
|
562
|
+
printHelp();
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
if (command === '--version' || command === '-v' || command === 'version') {
|
|
567
|
+
process.stdout.write(`${packageJson.version}\n`);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (command === 'stop') {
|
|
572
|
+
process.stdout.write('Stopping vibelet daemon...\n');
|
|
573
|
+
if (backend.handlesProcessLifecycle) {
|
|
574
|
+
// macOS launchd / Linux systemd: the service manager owns the process.
|
|
575
|
+
// bootout/stop kills the process and unregisters the service in one step.
|
|
576
|
+
backend.stop();
|
|
577
|
+
} else {
|
|
578
|
+
// Detached process: gracefully shut down via HTTP, then clean up PID file.
|
|
579
|
+
await requestShutdown();
|
|
580
|
+
backend.stop();
|
|
581
|
+
}
|
|
582
|
+
// Verify daemon is actually gone
|
|
583
|
+
const stillAlive = await probeHealth(1_500);
|
|
584
|
+
if (stillAlive) {
|
|
585
|
+
fail('Daemon did not stop in time.');
|
|
586
|
+
}
|
|
587
|
+
process.stdout.write('Daemon stopped.\n');
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (command === 'status') {
|
|
592
|
+
process.stdout.write(`Service (${backend.name}): ${backend.statusLabel()}\n`);
|
|
593
|
+
process.stdout.write(`Runtime: ${existsSync(runtimeDaemonEntryPath) ? runtimeDaemonEntryPath : 'not installed'}\n`);
|
|
594
|
+
const savedRelay = loadRelayConfig();
|
|
595
|
+
if (savedRelay) {
|
|
596
|
+
process.stdout.write(`Relay: ${savedRelay}\n`);
|
|
597
|
+
}
|
|
598
|
+
const health = await probeHealth(1_500);
|
|
599
|
+
if (health) {
|
|
600
|
+
process.stdout.write(JSON.stringify(health, null, 2) + '\n');
|
|
601
|
+
} else {
|
|
602
|
+
process.stdout.write('Daemon is not responding.\n');
|
|
603
|
+
}
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
if (command === 'logs') {
|
|
608
|
+
process.stdout.write(`Stdout: ${stdoutLogPath}\n`);
|
|
609
|
+
process.stdout.write(`Stderr: ${stderrLogPath}\n\n`);
|
|
610
|
+
const logFiles = [stdoutLogPath, stderrLogPath].filter((filePath) => existsSync(filePath));
|
|
611
|
+
if (logFiles.length === 0) {
|
|
612
|
+
process.stdout.write('No daemon logs have been written yet.\n');
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (process.platform === 'win32') {
|
|
616
|
+
for (const logFile of logFiles) {
|
|
617
|
+
const content = readFileSync(logFile, 'utf8');
|
|
618
|
+
const lines = content.split('\n').slice(-80).join('\n');
|
|
619
|
+
process.stdout.write(`==> ${logFile} <==\n${lines}\n`);
|
|
620
|
+
}
|
|
621
|
+
} else {
|
|
622
|
+
const result = spawnSync('tail', ['-n', '80', ...logFiles], { encoding: 'utf8' });
|
|
623
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
624
|
+
if (result.stderr) process.stderr.write(result.stderr);
|
|
625
|
+
}
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
if (command === 'restart') {
|
|
630
|
+
process.stdout.write('Restarting vibelet daemon...\n');
|
|
631
|
+
if (backend.handlesProcessLifecycle) {
|
|
632
|
+
backend.stop();
|
|
633
|
+
} else {
|
|
634
|
+
await requestShutdown();
|
|
635
|
+
backend.stop();
|
|
636
|
+
}
|
|
637
|
+
// Wait for daemon to actually stop
|
|
638
|
+
const stillAlive = await probeHealth(5_000);
|
|
639
|
+
if (stillAlive) {
|
|
640
|
+
fail('Daemon did not stop in time.');
|
|
641
|
+
}
|
|
642
|
+
process.stdout.write('Daemon stopped. Starting...\n');
|
|
643
|
+
ensureRuntimeInstalled();
|
|
644
|
+
backend.install();
|
|
645
|
+
backend.start();
|
|
646
|
+
await printPairingSummary();
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
if (command === 'reset') {
|
|
651
|
+
ensureRuntimeInstalled();
|
|
652
|
+
backend.install();
|
|
653
|
+
backend.start();
|
|
654
|
+
await waitForHealth();
|
|
655
|
+
await postJson('/pair/reset');
|
|
656
|
+
await printPairingSummary();
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
if (command !== 'default' && command !== 'start') {
|
|
661
|
+
printHelp();
|
|
662
|
+
fail(`Unknown command: ${command}`);
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
ensureRuntimeInstalled();
|
|
666
|
+
backend.install();
|
|
667
|
+
backend.start();
|
|
668
|
+
await printPairingSummary();
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
process.on('SIGINT', () => process.exit(0));
|
|
672
|
+
process.on('SIGTERM', () => process.exit(0));
|
|
673
|
+
await main();
|
|
674
|
+
process.exit(0);
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";var gc=Object.create;var Ci=Object.defineProperty;var mc=Object.getOwnPropertyDescriptor;var yc=Object.getOwnPropertyNames;var _c=Object.getPrototypeOf,Sc=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yc(e))!Sc.call(t,i)&&i!==n&&Ci(t,i,{get:()=>e[i],enumerable:!(r=mc(e,i))||r.enumerable});return t};var qe=(t,e,n)=>(n=t!=null?gc(_c(t)):{},vc(e||!t||!t.__esModule?Ci(n,"default",{value:t,enumerable:!0}):n,t));var oe=y((Up,Ri)=>{"use strict";var ki=["nodebuffer","arraybuffer","fragments"],Pi=typeof Blob<"u";Pi&&ki.push("blob");Ri.exports={BINARY_TYPES:ki,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Pi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var St=y((Hp,Qt)=>{"use strict";var{EMPTY_BUFFER:wc}=oe(),Wn=Buffer[Symbol.species];function bc(t,e){if(t.length===0)return wc;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 Wn(n.buffer,n.byteOffset,r):n}function Li(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function Oi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Ec(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Gn(t){if(Gn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Wn(t):ArrayBuffer.isView(t)?e=new Wn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Gn.readOnly=!1),e}Qt.exports={concat:bc,mask:Li,toArrayBuffer:Ec,toBuffer:Gn,unmask:Oi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Qt.exports.mask=function(e,n,r,i,s){s<48?Li(e,n,r,i,s):t.mask(e,n,r,i,s)},Qt.exports.unmask=function(e,n){e.length<32?Oi(e,n):t.unmask(e,n)}}catch{}});var Bi=y((qp,Ni)=>{"use strict";var Mi=Symbol("kDone"),jn=Symbol("kRun"),zn=class{constructor(e){this[Mi]=()=>{this.pending--,this[jn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[jn]()}[jn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mi])}}};Ni.exports=zn});var wt=y((Wp,Hi)=>{"use strict";var vt=require("zlib"),Di=St(),Tc=Bi(),{kStatusCode:Fi}=oe(),Ic=Buffer[Symbol.species],xc=Buffer.from([0,0,255,255]),en=Symbol("permessage-deflate"),ae=Symbol("total-length"),We=Symbol("callback"),he=Symbol("buffers"),Ge=Symbol("error"),Xt,Vn=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,!Xt){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Xt=new Tc(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){Xt.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){Xt.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"?vt.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=vt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[en]=this,this._inflate[ae]=0,this._inflate[he]=[],this._inflate.on("error",Cc),this._inflate.on("data",Ui)}this._inflate[We]=r,this._inflate.write(e),n&&this._inflate.write(xc),this._inflate.flush(()=>{let s=this._inflate[Ge];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=Di.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"?vt.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=vt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[he]=[],this._deflate.on("data",Ac)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(vt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=Di.concat(this._deflate[he],this._deflate[ae]);n&&(s=new Ic(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)})}};Hi.exports=Vn;function Ac(t){this[he].push(t),this[ae]+=t.length}function Ui(t){if(this[ae]+=t.length,this[en]._maxPayload<1||this[ae]<=this[en]._maxPayload){this[he].push(t);return}this[Ge]=new RangeError("Max payload size exceeded"),this[Ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ge][Fi]=1009,this.removeListener("data",Ui),this.reset()}function Cc(t){if(this[en]._inflate=null,this[Ge]){this[We](this[Ge]);return}t[Fi]=1007,this[We](t)}});var je=y((Gp,tn)=>{"use strict";var{isUtf8:qi}=require("buffer"),{hasBlob:kc}=oe(),Pc=[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 Rc(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 Lc(t){return kc&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}tn.exports={isBlob:Lc,isValidStatusCode:Rc,isValidUTF8:$n,tokenChars:Pc};if(qi)tn.exports.isValidUTF8=function(t){return t.length<24?$n(t):qi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");tn.exports.isValidUTF8=function(e){return e.length<32?$n(e):t(e)}}catch{}});var Qn=y((jp,Yi)=>{"use strict";var{Writable:Oc}=require("stream"),Wi=wt(),{BINARY_TYPES:Mc,EMPTY_BUFFER:Gi,kStatusCode:Nc,kWebSocket:Bc}=oe(),{concat:Yn,toArrayBuffer:Dc,unmask:Fc}=St(),{isValidStatusCode:Uc,isValidUTF8:ji}=je(),nn=Buffer[Symbol.species],G=0,zi=1,Vi=2,$i=3,Jn=4,Kn=5,rn=6,Zn=class extends Oc{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Mc[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Bc]=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 nn(r.buffer,r.byteOffset+e,r.length-e),new nn(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 nn(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 zi:this.getPayloadLength16(e);break;case Vi:this.getPayloadLength64(e);break;case $i:this.getMask();break;case Jn:this.getData(e);break;case Kn:case rn: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[Wi.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=zi:this._payloadLength===127?this._state=Vi: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=$i:this._state=Jn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Jn}getData(e){let n=Gi;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&&Fc(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Kn,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wi.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=Yn(r,n):this._binaryType==="arraybuffer"?i=Dc(Yn(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=G):(this._state=rn,setImmediate(()=>{this.emit("message",i,!0),this._state=G,this.startLoop(e)}))}else{let i=Yn(r,n);if(!this._skipUTF8Validation&&!ji(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Kn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=G):(this._state=rn,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,Gi),this.end();else{let r=e.readUInt16BE(0);if(!Uc(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new nn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ji(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=rn,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[Nc]=i,o}};Yi.exports=Zn});var tr=y((Vp,Zi)=>{"use strict";var{Duplex:zp}=require("stream"),{randomFillSync:Hc}=require("crypto"),Ji=wt(),{EMPTY_BUFFER:qc,kWebSocket:Wc,NOOP:Gc}=oe(),{isBlob:ze,isValidStatusCode:jc}=je(),{mask:Ki,toBuffer:xe}=St(),j=Symbol("kByteLength"),zc=Buffer.alloc(4),sn=8*1024,Ae,Ve=sn,K=0,Vc=1,$c=2,Xn=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=Gc,this[Wc]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||zc,n.generateMask?n.generateMask(r):(Ve===sn&&(Ae===void 0&&(Ae=Buffer.alloc(sn)),Hc(Ae,0,sn),Ve=0),r[0]=Ae[Ve++],r[1]=Ae[Ve++],r[2]=Ae[Ve++],r[3]=Ae[Ve++]),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?(Ki(e,r,c,s,a),[c]):(Ki(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=qc;else{if(typeof e!="number"||!jc(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=xe(e),i=e.length,s=xe.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=xe(e),i=e.length,s=xe.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[Ji.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=xe(e),a=e.length,l=xe.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=$c,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(er,this,a,i);return}this._bufferedBytes-=r[j];let o=xe(s);n?this.dispatch(o,n,r,i):(this._state=K,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Yc,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[Ji.extensionName];this._bufferedBytes+=r[j],this._state=Vc,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");er(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)}};Zi.exports=Xn;function er(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 Yc(t,e,n){er(t,e,n),t.onerror(e)}});var os=y(($p,ss)=>{"use strict";var{kForOnEventAttribute:bt,kListener:nr}=oe(),Qi=Symbol("kCode"),Xi=Symbol("kData"),es=Symbol("kError"),ts=Symbol("kMessage"),ns=Symbol("kReason"),$e=Symbol("kTarget"),rs=Symbol("kType"),is=Symbol("kWasClean"),le=class{constructor(e){this[$e]=null,this[rs]=e}get target(){return this[$e]}get type(){return this[rs]}};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[Qi]=n.code===void 0?0:n.code,this[ns]=n.reason===void 0?"":n.reason,this[is]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Qi]}get reason(){return this[ns]}get wasClean(){return this[is]}};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[es]=n.error===void 0?null:n.error,this[ts]=n.message===void 0?"":n.message}get error(){return this[es]}get message(){return this[ts]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var Et=class extends le{constructor(e,n={}){super(e),this[Xi]=n.data===void 0?null:n.data}get data(){return this[Xi]}};Object.defineProperty(Et.prototype,"data",{enumerable:!0});var Jc={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[bt]&&i[nr]===e&&!i[bt])return;let r;if(t==="message")r=function(s,o){let a=new Et("message",{data:o?s:s.toString()});a[$e]=this,on(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[$e]=this,on(e,this,a)};else if(t==="error")r=function(s){let o=new Ye("error",{error:s,message:s.message});o[$e]=this,on(e,this,o)};else if(t==="open")r=function(){let s=new le("open");s[$e]=this,on(e,this,s)};else return;r[bt]=!!n[bt],r[nr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[nr]===e&&!n[bt]){this.removeListener(t,n);break}}};ss.exports={CloseEvent:Ce,ErrorEvent:Ye,Event:le,EventTarget:Jc,MessageEvent:Et};function on(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var rr=y((Yp,as)=>{"use strict";var{tokenChars:Tt}=je();function ne(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Kc(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&&Tt[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&&Tt[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(Tt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),i=!1}else if(s)if(Tt[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&&Tt[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(", ")}as.exports={format:Zc,parse:Kc}});var un=y((Zp,Ss)=>{"use strict";var Qc=require("events"),Xc=require("https"),eu=require("http"),us=require("net"),tu=require("tls"),{randomBytes:nu,createHash:ru}=require("crypto"),{Duplex:Jp,Readable:Kp}=require("stream"),{URL:ir}=require("url"),pe=wt(),iu=Qn(),su=tr(),{isBlob:ou}=je(),{BINARY_TYPES:ls,CLOSE_TIMEOUT:au,EMPTY_BUFFER:an,GUID:lu,kForOnEventAttribute:sr,kListener:cu,kStatusCode:uu,kWebSocket:O,NOOP:ds}=oe(),{EventTarget:{addEventListener:du,removeEventListener:fu}}=os(),{format:hu,parse:pu}=rr(),{toBuffer:gu}=St(),fs=Symbol("kAborted"),or=[8,13],ce=["CONNECTING","OPEN","CLOSING","CLOSED"],mu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends Qc{constructor(e,n,r){super(),this._binaryType=ls[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=an,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]),hs(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ls.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 iu({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new su(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",Su),i.on("drain",vu),i.on("error",wu),i.on("message",bu),i.on("ping",Eu),i.on("pong",Tu),s.onerror=Iu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ms),e.on("data",cn),e.on("end",ys),e.on("error",_s),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())}),gs(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){ar(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||an,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){ar(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||an,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){ar(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||an,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(T,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(T.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(T.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[sr])return e[cu];return null},set(e){for(let n of this.listeners(t))if(n[sr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[sr]:!0})}})});T.prototype.addEventListener=du;T.prototype.removeEventListener=fu;Ss.exports=T;function hs(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:au,protocolVersion:or[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,!or.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${or.join(", ")})`);let s;if(e instanceof ir)s=e;else try{s=new ir(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;ln(t,p);return}let c=o?443:80,u=nu(16).toString("base64"),d=o?Xc.request:eu.request,f=new Set,h;if(i.createConnection=i.createConnection||(o?_u:yu),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"]=hu({[pe.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!mu.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[fs]||(g=t._req=null,ln(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 ir(m,e)}catch{let I=new SyntaxError(`Invalid URL: ${m}`);ln(t,I);return}hs(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!==T.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=ru("sha1").update(u+lu).digest("base64");if(p.headers["sec-websocket-accept"]!==fe){q(t,m,"Invalid Sec-WebSocket-Accept header");return}let I=p.headers["sec-websocket-protocol"],L;if(I!==void 0?f.size?f.has(I)||(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}I&&(t._protocol=I);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=pu(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 ln(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function yu(t){return t.path=t.socketPath,us.connect(t)}function _u(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=us.isIP(t.host)?"":t.host),tu.connect(t)}function q(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,q),e.setHeader?(e[fs]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ln,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ar(t,e,n){if(e){let r=ou(e)?e.size:gu(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 Su(t,e){let n=this[O];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[O]!==void 0&&(n._socket.removeListener("data",cn),process.nextTick(ps,n._socket),t===1005?n.close():n.close(t,e))}function vu(){let t=this[O];t.isPaused||t._socket.resume()}function wu(t){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",cn),process.nextTick(ps,e._socket),e.close(t[uu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function cs(){this[O].emitClose()}function bu(t,e){this[O].emit("message",t,e)}function Eu(t){let e=this[O];e._autoPong&&e.pong(t,!this._isServer,ds),e.emit("ping",t)}function Tu(t){this[O].emit("pong",t)}function ps(t){t.resume()}function Iu(t){let e=this[O];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,gs(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function gs(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ms(){let t=this[O];if(this.removeListener("close",ms),this.removeListener("data",cn),this.removeListener("end",ys),t._readyState=T.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",cs),t._receiver.on("finish",cs))}function cn(t){this[O]._receiver.write(t)||this.pause()}function ys(){let t=this[O];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function _s(){let t=this[O];this.removeListener("error",_s),this.on("error",ds),t&&(t._readyState=T.CLOSING,this.destroy())}});var Es=y((Xp,bs)=>{"use strict";var Qp=un(),{Duplex:xu}=require("stream");function vs(t){t.emit("close")}function Au(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ws(t){this.removeListener("error",ws),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Cu(t,e){let n=!0,r=new xu({...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(vs,r);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(vs,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",Au),r.on("error",ws),r}bs.exports=Cu});var Is=y((eg,Ts)=>{"use strict";var{tokenChars:ku}=je();function Pu(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&&ku[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}Ts.exports={parse:Pu}});var Ls=y((ng,Rs)=>{"use strict";var Ru=require("events"),dn=require("http"),{Duplex:tg}=require("stream"),{createHash:Lu}=require("crypto"),xs=rr(),ke=wt(),Ou=Is(),Mu=un(),{CLOSE_TIMEOUT:Nu,GUID:Bu,kWebSocket:Du}=oe(),Fu=/^[+/0-9A-Za-z]{22}==$/,As=0,Cs=1,Ps=2,lr=class extends Ru{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Nu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Mu,...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=dn.createServer((r,i)=>{let s=dn.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=Uu(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=As}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===Ps){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(It,this);return}if(e&&this.once("close",e),this._state!==Cs)if(this._state=Cs,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(It,this):process.nextTick(It,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{It(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",ks);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||!Fu.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)){xt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ou.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 xt(n,g||401,p,m);this.completeUpgrade(d,s,c,e,n,r,i)});return}if(!this.options.verifyClient(f))return xt(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[Du])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>As)return xt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Lu("sha1").update(n+Bu).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",ks),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(It,this)})),a(u,i)}};Rs.exports=lr;function Uu(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 It(t){t._state=Ps,t.emit("close")}function ks(){this.destroy()}function xt(t,e,n,r){n=n||dn.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} ${dn.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 xt(n,r,i,s)}});var ur=y((ig,Os)=>{Os.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ge=y(Re=>{var dr,ju=[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 ju[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.');dr=e};Re.isKanjiModeEnabled=function(){return typeof dr<"u"};Re.toSJIS=function(e){return dr(e)}});var fn=y(z=>{z.L={bit:1};z.M={bit:0};z.Q={bit:3};z.H={bit:2};function zu(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 zu(e)}catch{return n}}});var Bs=y((ag,Ns)=>{function Ms(){this.buffer=[],this.length=0}Ms.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++}};Ns.exports=Ms});var Fs=y((lg,Ds)=>{function At(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)}At.prototype.set=function(t,e,n,r){let i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)};At.prototype.get=function(t,e){return this.data[t*this.size+e]};At.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};At.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ds.exports=At});var Us=y(hn=>{var Vu=ge().getSymbolSize;hn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Vu(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()};hn.getPositions=function(e){let n=[],r=hn.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 Ws=y(qs=>{var $u=ge().getSymbolSize,Hs=7;qs.getPositions=function(e){let n=$u(e);return[[0,0],[n-Hs,0],[0,n-Hs]]}});var Gs=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 Yu(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,Yu(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 hr=y(fr=>{var me=fn(),pn=[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],gn=[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];fr.getBlocksCount=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}};fr.getTotalCodewordsCount=function(e,n){switch(n){case me.L:return gn[(e-1)*4+0];case me.M:return gn[(e-1)*4+1];case me.Q:return gn[(e-1)*4+2];case me.H:return gn[(e-1)*4+3];default:return}}});var js=y(yn=>{var Ct=new Uint8Array(512),mn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Ct[n]=e,mn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Ct[n]=Ct[n-255]})();yn.log=function(e){if(e<1)throw new Error("log("+e+")");return mn[e]};yn.exp=function(e){return Ct[e]};yn.mul=function(e,n){return e===0||n===0?0:Ct[mn[e]+mn[n]]}});var zs=y(kt=>{var pr=js();kt.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]^=pr.mul(e[i],n[s]);return r};kt.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]^=pr.mul(n[o],i);let s=0;for(;s<r.length&&r[s]===0;)s++;r=r.slice(s)}return r};kt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=kt.mul(n,new Uint8Array([1,pr.exp(r)]));return n}});var Ys=y((gg,$s)=>{var Vs=zs();function gr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}gr.prototype.initialize=function(e){this.degree=e,this.genPoly=Vs.generateECPolynomial(this.degree)};gr.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=Vs.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};$s.exports=gr});var mr=y(Js=>{Js.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var yr=y(ue=>{var Ks="[0-9]+",Ju="[A-Z $%*+\\-./:]+",Pt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Pt=Pt.replace(/u/g,"\\u");var Ku="(?:(?![A-Z0-9 $%*+\\-./:]|"+Pt+`)(?:.|[\r
|
|
8
|
+
]))+`;ue.KANJI=new RegExp(Pt,"g");ue.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ue.BYTE=new RegExp(Ku,"g");ue.NUMERIC=new RegExp(Ks,"g");ue.ALPHANUMERIC=new RegExp(Ju,"g");var Zu=new RegExp("^"+Pt+"$"),Qu=new RegExp("^"+Ks+"$"),Xu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ue.testKanji=function(e){return Zu.test(e)};ue.testNumeric=function(e){return Qu.test(e)};ue.testAlphanumeric=function(e){return Xu.test(e)}});var ye=y(C=>{var ed=mr(),_r=yr();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(!ed.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 _r.testNumeric(e)?C.NUMERIC:_r.testAlphanumeric(e)?C.ALPHANUMERIC:_r.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 td(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 td(e)}catch{return n}}});var to=y(Oe=>{var _n=ge(),nd=hr(),Zs=fn(),_e=ye(),Sr=mr(),Xs=7973,Qs=_n.getBCHDigit(Xs);function rd(t,e,n){for(let r=1;r<=40;r++)if(e<=Oe.getCapacity(r,n,t))return r}function eo(t,e){return _e.getCharCountIndicator(t,e)+4}function id(t,e){let n=0;return t.forEach(function(r){let i=eo(r.mode,e);n+=i+r.getBitsLength()}),n}function sd(t,e){for(let n=1;n<=40;n++)if(id(t,n)<=Oe.getCapacity(n,e,_e.MIXED))return n}Oe.from=function(e,n){return Sr.isValid(e)?parseInt(e,10):n};Oe.getCapacity=function(e,n,r){if(!Sr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=_e.BYTE);let i=_n.getSymbolTotalCodewords(e),s=nd.getTotalCodewordsCount(e,n),o=(i-s)*8;if(r===_e.MIXED)return o;let a=o-eo(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=Zs.from(n,Zs.M);if(Array.isArray(e)){if(e.length>1)return sd(e,i);if(e.length===0)return 1;r=e[0]}else r=e;return rd(r.mode,r.getLength(),i)};Oe.getEncodedBits=function(e){if(!Sr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;_n.getBCHDigit(n)-Qs>=0;)n^=Xs<<_n.getBCHDigit(n)-Qs;return e<<12|n}});var so=y(io=>{var vr=ge(),ro=1335,od=21522,no=vr.getBCHDigit(ro);io.getEncodedBits=function(e,n){let r=e.bit<<3|n,i=r<<10;for(;vr.getBCHDigit(i)-no>=0;)i^=ro<<vr.getBCHDigit(i)-no;return(r<<10|i)^od}});var ao=y((wg,oo)=>{var ad=ye();function Je(t){this.mode=ad.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))};oo.exports=Je});var co=y((bg,lo)=>{var ld=ye(),wr=["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=ld.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=wr.indexOf(this.data[n])*45;r+=wr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(wr.indexOf(this.data[n]),6)};lo.exports=Ke});var fo=y((Eg,uo)=>{var cd=ye();function Ze(t){this.mode=cd.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)};uo.exports=Ze});var po=y((Tg,ho)=>{var ud=ye(),dd=ge();function Qe(t){this.mode=ud.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=dd.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)}};ho.exports=Qe});var go=y((Ig,br)=>{"use strict";var Rt={single_source_shortest_paths:function(t,e,n){var r={},i={};i[e]=0;var s=Rt.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=Rt.single_source_shortest_paths(t,e,n);return Rt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Rt.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 br<"u"&&(br.exports=Rt)});var Eo=y(Xe=>{var w=ye(),_o=ao(),So=co(),vo=fo(),wo=po(),Lt=yr(),Sn=ge(),fd=go();function mo(t){return unescape(encodeURIComponent(t)).length}function Ot(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 bo(t){let e=Ot(Lt.NUMERIC,w.NUMERIC,t),n=Ot(Lt.ALPHANUMERIC,w.ALPHANUMERIC,t),r,i;return Sn.isKanjiModeEnabled()?(r=Ot(Lt.BYTE,w.BYTE,t),i=Ot(Lt.KANJI,w.KANJI,t)):(r=Ot(Lt.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 Er(t,e){switch(e){case w.NUMERIC:return _o.getBitsLength(t);case w.ALPHANUMERIC:return So.getBitsLength(t);case w.KANJI:return wo.getBitsLength(t);case w.BYTE:return vo.getBitsLength(t)}}function hd(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 pd(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:mo(r.data)}]);break;case w.BYTE:e.push([{data:r.data,mode:w.BYTE,length:mo(r.data)}])}}return e}function gd(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]=Er(n[f].lastCount+c.length,c.mode)-Er(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Er(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 yo(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&&!Sn.isKanjiModeEnabled()&&(n=w.BYTE),n){case w.NUMERIC:return new _o(t);case w.ALPHANUMERIC:return new So(t);case w.KANJI:return new wo(t);case w.BYTE:return new vo(t)}}Xe.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(yo(r,null)):r.data&&n.push(yo(r.data,r.mode)),n},[])};Xe.fromString=function(e,n){let r=bo(e,Sn.isKanjiModeEnabled()),i=pd(r),s=gd(i,n),o=fd.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(hd(a))};Xe.rawSplit=function(e){return Xe.fromArray(bo(e,Sn.isKanjiModeEnabled()))}});var kr=y(To=>{var wn=ge(),Tr=fn(),md=Bs(),yd=Fs(),_d=Us(),Sd=Ws(),Ar=Gs(),Cr=hr(),vd=Ys(),vn=to(),wd=so(),bd=ye(),Ir=Eo();function Ed(t,e){let n=t.size,r=Sd.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 Td(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 Id(t,e){let n=_d.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 xd(t,e){let n=t.size,r=vn.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 xr(t,e,n){let r=t.size,i=wd.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 Ad(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 Cd(t,e,n){let r=new md;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),bd.getCharCountIndicator(l.mode,t)),l.write(r)});let i=wn.getSymbolTotalCodewords(t),s=Cr.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 kd(r,t,e)}function kd(t,e,n){let r=wn.getSymbolTotalCodewords(e),i=Cr.getTotalCodewordsCount(e,n),s=r-i,o=Cr.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 vd(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),I=0,L,W;for(L=0;L<S;L++)for(W=0;W<o;W++)L<p[W].length&&(fe[I++]=p[W][L]);for(L=0;L<f;L++)for(W=0;W<o;W++)fe[I++]=m[W][L];return fe}function Pd(t,e,n,r){let i;if(Array.isArray(t))i=Ir.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Ir.rawSplit(t);c=vn.getBestVersionForData(u,n)}i=Ir.fromString(t,c||40)}else throw new Error("Invalid data");let s=vn.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=Cd(e,n,i),a=wn.getSymbolSize(e),l=new yd(a);return Ed(l,e),Td(l),Id(l,e),xr(l,n,0),e>=7&&xd(l,e),Ad(l,o),isNaN(r)&&(r=Ar.getBestMask(l,xr.bind(null,l,n))),Ar.applyMask(r,l),xr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:i}}To.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Tr.M,i,s;return typeof n<"u"&&(r=Tr.from(n.errorCorrectionLevel,Tr.M),i=vn.from(n.version),s=Ar.from(n.maskPattern),n.toSJISFunc&&wn.setToSJISFunction(n.toSJISFunc)),Pd(e,i,r,s)}});var Pr=y((Cg,xo)=>{"use strict";var Rd=require("util"),Io=require("stream"),Z=xo.exports=function(){Io.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Rd.inherits(Z,Io);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 Lr=y(Rr=>{"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]}];Rr.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};Rr.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 Or=y((Pg,Ao)=>{"use strict";Ao.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 Mr=y((Rg,ko)=>{"use strict";var Ld=Lr(),Od=Or();function Co(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var et=ko.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=Ld.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Co(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Co(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=Od(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 Lo=y((Lg,Ro)=>{"use strict";var Md=require("util"),Po=Pr(),Nd=Mr(),Bd=Ro.exports=function(t){Po.call(this);let e=[],n=this;this._filter=new Nd(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Md.inherits(Bd,Po)});var tt=y((Og,Oo)=>{"use strict";Oo.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 Dr=y((Mg,Mo)=>{"use strict";var Nr=[];(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;Nr[t]=e}})();var Br=Mo.exports=function(){this._crc=-1};Br.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Nr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Br.prototype.crc32=function(){return this._crc^-1};Br.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Nr[(e^t[n])&255]^e>>>8;return e^-1}});var Fr=y((Ng,No)=>{"use strict";var R=tt(),Dd=Dr(),M=No.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 Dd,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 Ur=y(Do=>{"use strict";var Bo=Lr(),Fd=[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]}],Ud=[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 Hd(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 qd(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);Fd[r](e,i,d,s),s+=r}return s}function Wd(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);Ud[r](e,d,f,s)}i.resetAfterLine()}}Do.dataToBitMap=function(t,e){let n=e.width,r=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=Hd(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=Bo.getImagePasses(n,r),f=Bo.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=qd(d[h],l,f,s,t,u):Wd(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 Hr=y((Dg,Fo)=>{"use strict";function Gd(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 jd(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 zd(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}}Fo.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?Gd(t,l,r,i,a):(o&&jd(t,l,r,i,o),n!==8&&(n===16&&(l=Buffer.alloc(r*i*4)),zd(t,l,r,i,n))),l}});var qo=y((Fg,Ho)=>{"use strict";var Vd=require("util"),qr=require("zlib"),Uo=Pr(),$d=Lo(),Yd=Fr(),Jd=Ur(),Kd=Hr(),re=Ho.exports=function(t){Uo.call(this),this._parser=new Yd(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()};Vd.inherits(re,Uo);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=qr.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,qr.Z_MIN_CHUNK);this._inflate=qr.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 $d(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=Jd.dataToBitMap(t,this._bitmapInfo);e=Kd(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Go=y((Ug,Wo)=>{"use strict";var V=tt();Wo.exports=function(t,e,n,r){let i=[V.COLORTYPE_COLOR_ALPHA,V.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=V.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=V.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 V.COLORTYPE_COLOR_ALPHA:S=s[u+3],g=s[u],p=s[u+1],m=s[u+2];break;case V.COLORTYPE_COLOR:g=s[u],p=s[u+1],m=s[u+2];break;case V.COLORTYPE_ALPHA:S=s[u+1],g=s[u],p=g,m=g;break;case V.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 V.COLORTYPE_COLOR_ALPHA:case V.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 V.COLORTYPE_ALPHA:case V.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 Vo=y((Hg,zo)=>{"use strict";var jo=Or();function Zd(t,e,n,r,i){for(let s=0;s<n;s++)r[i+s]=t[e+s]}function Qd(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++)r+=Math.abs(t[s]);return r}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=t[e+o]-a;r[i+o]=l}}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=t[e+s]-o;i+=Math.abs(a)}return i}function tf(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 nf(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 rf(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 sf(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 of(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]-jo(a,l,c);r[i+o]=u}}function af(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]-jo(o,a,l);i+=Math.abs(c)}return i}var lf={0:Zd,1:Xd,2:tf,3:rf,4:of},cf={0:Qd,1:ef,2:nf,3:sf,4:af};zo.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=cf[s[h]](t,l,o,i);g<f&&(u=s[h],f=g)}}c[a]=u,a++,lf[u](t,l,o,c,a,i),a+=o,l+=o}return c}});var Wr=y((qg,$o)=>{"use strict";var B=tt(),uf=Dr(),df=Go(),ff=Vo(),hf=require("zlib"),ve=$o.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||hf.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=df(t,e,n,this._options),i=B.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ff(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(uf.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 Zo=y((Wg,Ko)=>{"use strict";var pf=require("util"),Yo=require("stream"),gf=tt(),mf=Wr(),Jo=Ko.exports=function(t){Yo.call(this);let e=t||{};this._packer=new mf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};pf.inherits(Jo,Yo);Jo.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(gf.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 ra=y((Mt,na)=>{"use strict";var Qo=require("assert").ok,nt=require("zlib"),yf=require("util"),Xo=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 _f(t){return new Me(t)}function ea(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(Qo(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}Qo(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>=Xo)throw ea(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Xo.toString(16)+" bytes");let h=Buffer.concat(l,c);return ea(this),h};yf.inherits(Me,nt.Inflate);function Sf(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 ta(t,e){return Sf(new Me(e),t)}na.exports=Mt=ta;Mt.Inflate=Me;Mt.createInflate=_f;Mt.inflateSync=ta});var Gr=y((Gg,sa)=>{"use strict";var ia=sa.exports=function(t){this._buffer=t,this._reads=[]};ia.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ia.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 aa=y(oa=>{"use strict";var vf=Gr(),wf=Mr();oa.process=function(t,e){let n=[],r=new vf(t);return new wf(e,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var da=y((zg,ua)=>{"use strict";var la=!0,ca=require("zlib"),bf=ra();ca.deflateSync||(la=!1);var Ef=Gr(),Tf=aa(),If=Fr(),xf=Ur(),Af=Hr();ua.exports=function(t,e){if(!la)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(I){n=I}let i;function s(I){i=I}function o(I){i.transColor=I}function a(I){i.palette=I}function l(){i.alpha=!0}let c;function u(I){c=I}let d=[];function f(I){d.push(I)}let h=new Ef(t);if(new If(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=ca.inflateSync(p);else{let L=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;m=bf(p,{chunkSize:L,maxLength:L})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=Tf.process(m,i);p=null;let J=xf.dataToBitMap(S,i);S=null;let fe=Af(J,i);return i.data=fe,i.gamma=c||0,i}});var ga=y((Vg,pa)=>{"use strict";var fa=!0,ha=require("zlib");ha.deflateSync||(fa=!1);var Cf=tt(),kf=Wr();pa.exports=function(t,e){if(!fa)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 kf(n),i=[];i.push(Buffer.from(Cf.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=ha.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 ma=y(jr=>{"use strict";var Pf=da(),Rf=ga();jr.read=function(t,e){return Pf(t,e||{})};jr.write=function(t,e){return Rf(t,e)}});var Sa=y(_a=>{"use strict";var Lf=require("util"),ya=require("stream"),Of=qo(),Mf=Zo(),Nf=ma(),F=_a.PNG=function(t){ya.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 Of(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 Mf(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"))};Lf.inherits(F,ya);F.sync=Nf;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 Nt=y(Ne=>{function va(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:va(e.color.dark||"#000000ff"),light:va(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 wa=y(ie=>{var Bf=require("fs"),Df=Sa().PNG,zr=Nt();ie.render=function(e,n){let r=zr.getOptions(n),i=r.rendererOpts,s=zr.getImageWidth(e.modules.size,r);i.width=s,i.height=s;let o=new Df(i);return zr.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=Bf.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 ba=y(bn=>{var Ff=Nt(),Uf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Hf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function qf(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}bn.render=function(t,e,n){let r=Ff.getOptions(e),i=Uf;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=Hf);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+=qf(f,h,i)}a+=c+`
|
|
15
|
+
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};bn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),o=bn.render(n,r);s.writeFile(e,o,i)}});var Ta=y(Ea=>{Ea.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 Ca=y(Aa=>{var Wf="\x1B[47m",Gf="\x1B[40m",Vr="\x1B[37m",$r="\x1B[30m",Be="\x1B[0m",jf=Wf+$r,zf=Gf+Vr,Vf=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"}},Ia=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 Ia(t,e,n,r)+Ia(t,e,n,r+1)};Aa.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?zf:jf,c=Vf(o,s?$r:Vr,s?Vr:$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 Pa=y(ka=>{var $f=Ta(),Yf=Ca();ka.render=function(t,e,n){return e&&e.small?Yf.render(t,e,n):$f.render(t,e,n)}});var Jr=y(La=>{var Jf=Nt();function Ra(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Yr(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Kf(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?Yr("M",l+n,.5+c+n):Yr("m",i,0),i=0,s=!1),l+1<e&&t[a+1]||(r+=Yr("h",o),o=0)):i++}return r}La.render=function(e,n,r){let i=Jf.getOptions(n),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,l=i.color.light.a?"<path "+Ra(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Ra(i.color.dark,"stroke")+' d="'+Kf(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 Oa=y(En=>{var Zf=Jr();En.render=Zf.render;En.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">'+En.render(n,r);s.writeFile(e,a,i)}});var Ma=y(Tn=>{var Kr=Nt();function Qf(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 Xf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Tn.render=function(e,n,r){let i=r,s=n;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),n||(s=Xf()),i=Kr.getOptions(i);let o=Kr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),l=a.createImageData(o,o);return Kr.qrToImageData(l.data,e,i),Qf(a,s,o),a.putImageData(l,0,0),s};Tn.renderToDataURL=function(e,n,r){let i=r;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),i||(i={});let s=Tn.render(e,n,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Ba=y(Bt=>{var eh=ur(),Zr=kr(),Na=Ma(),th=Jr();function Qr(t,e,n,r,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!eh())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=Zr.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Zr.create(n,r);i(null,t(l,e,r))}catch(l){i(l)}}Bt.create=Zr.create;Bt.toCanvas=Qr.bind(null,Na.render);Bt.toDataURL=Qr.bind(null,Na.renderToDataURL);Bt.toString=Qr.bind(null,function(t,e,n){return th.render(t,n)})});var Ha=y(we=>{var Da=ur(),Xr=kr(),nh=wa(),Fa=ba(),rh=Pa(),Ua=Oa();function Dt(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(Da())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function ih(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function In(t){switch(t){case"svg":return Ua;case"txt":case"utf8":return Fa;case"png":case"image/png":default:return nh}}function sh(t){switch(t){case"svg":return Ua;case"terminal":return rh;case"utf8":default:return Fa}}function Ft(t,e,n){if(!n.cb)return new Promise(function(r,i){try{let s=Xr.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=Xr.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}we.create=Xr.create;we.toCanvas=Ba().toCanvas;we.toString=function(e,n,r){let i=Dt(e,n,r),s=i.opts?i.opts.type:void 0,o=sh(s);return Ft(o.render,e,i)};we.toDataURL=function(e,n,r){let i=Dt(e,n,r),s=In(i.opts.type);return Ft(s.renderToDataURL,e,i)};we.toBuffer=function(e,n,r){let i=Dt(e,n,r),s=In(i.opts.type);return Ft(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&&!Da())throw new Error("Too few arguments provided");let s=Dt(n,r,i),o=s.opts.type||ih(e),l=In(o).renderToFile.bind(null,e);return Ft(l,n,s)};we.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Dt(n,r,e.emit.bind(e,"error")),o=In("png").renderToFileStream.bind(null,e);Ft(o,n,i)}});var Wa=y((om,qa)=>{qa.exports=Ha()});var lc=require("http");var Hu=qe(Es(),1),qu=qe(Qn(),1),Wu=qe(tr(),1),Gu=qe(un(),1),cr=qe(Ls(),1);var Fe=require("fs/promises"),Hn=require("path"),cc=require("os"),uc=qe(Wa(),1);var it=require("child_process"),Ga=require("fs"),U=require("path"),Ht=require("os"),oh=["fnm_multishells"],ah=6e4;function be(t){return oh.some(e=>t.includes(e))}function ti(){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 ja(){if(rt&&!be(rt.PATH??""))return rt;for(let t of ti())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 lh(t=ja()){let e=(0,Ht.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 ei(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 xn(){let t=ja(),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=lh(t),e.HOME||(e.HOME=(0,Ht.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Ut(t,e=3e3){try{return(0,it.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:xn()}).trim()||null}catch{return null}}function ch(t){for(let e of ti())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 uh(){let t=(0,Ht.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 dh(){for(let t of uh())if(Ut(t))return t;try{let t=(0,it.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:xn()}).trim();if(t&&!t.includes("cmux")&&Ut(t))return t}catch{}}function fh(){let t=(0,Ht.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 hh(){let t;for(let n of fh())if(Ut(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:xn()}).trim();if(n&&Ut(n)){if(!be(n))return n;t=t??n}}catch{}let e=ch("codex");if(e&&Ut(e)){if(!be(e))return e;t=t??e}return t}function za(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>ah||!(0,Ga.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 ph=za(dh,"claude"),gh=za(hh,"codex");function mh(t,e){return{command:ti()[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:ei("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:ei("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:ei("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return ph()},get codexPath(){return gh()},isTransientPath:be,execViaLoginShell:mh,buildSanitizedEnv:xn};var jl=require("fs/promises");var al=require("child_process"),ll=require("fs");var Va={debug:10,info:20,warn:30,error:40},yh=process.env.VIBE_LOG_LEVEL||"info";function $a(t,e,n){if(Va[t]<Va[yh])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 Ya(t={}){function e(n,r,i){typeof r=="string"?$a(n,t,r):$a(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=>Ya({...t,...n})}}var N=Ya({module:"daemon"});var Cn=require("fs"),il=require("path");var Ja=require("os"),$=require("path"),qt=(0,$.join)((0,Ja.homedir)(),".vibelet"),Ka=(0,$.join)(qt,"logs"),Za=(0,$.join)(qt,"data"),_h=(0,$.join)(qt,"runtime"),cm=(0,$.join)(_h,"current"),Qa=(0,$.join)(qt,"identity.json"),Xa=(0,$.join)(qt,"pairings.json"),An=(0,$.join)(Za,"sessions.json"),st=(0,$.join)(Za,"audit.jsonl"),el=(0,$.join)(Ka,"daemon.stdout.log"),tl=(0,$.join)(Ka,"daemon.stderr.log");var H=require("fs");function Sh(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 Wt(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=Sh(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 nl(t){let e=[Wt(t.auditPath,{maxBytes:t.auditMaxBytes}),Wt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Wt(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 rl=!1,vh=new Set(["ts","event","source","appEvent","level"]);function wh(t={}){let e={};for(let[n,r]of Object.entries(t))vh.has(n)||(e[n]=r);return e}function bh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...wh(n)}}function Eh(){rl||((0,Cn.mkdirSync)((0,il.dirname)(st),{recursive:!0}),rl=!0)}var ni=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},i){this.write(bh(e,n,r,i))}write(e){Eh();try{let n=JSON.stringify(e)+`
|
|
25
|
+
`;Wt(st,{maxBytes:_.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Cn.appendFileSync)(st,n)}catch{}}},v=new ni;var Y=N.child({module:"claude"}),cl="claude-permission-denial:",Th=/\u001B\[[0-?]*[ -/]*[@-~]/g;function ri(t){process.stderr.write(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
|
|
26
|
+
`)}function Ih(t){return typeof t=="string"?t:JSON.stringify(t)}function xh(t){return/requested permissions|haven't granted/i.test(t)}function sl(t){return t.replace(Th,"").replace(/\s+/g," ").trim()}function Ah(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Ch(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function kh(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function ol(t){let e=sl(t.resultText??""),n=(t.stderrLines??[]).map(sl).filter(Boolean).slice(-3),r=[e,...n].find(s=>!!s&&Ch(s));if(r)return kh(r);let i=[e,...n].find(s=>!!s&&!Ah(s));return i?t.exitCode!=null&&i!==e?`Claude exited with code ${t.exitCode}: ${i}`:i:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function ii(t){return t.startsWith(cl)}var kn=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"),ri(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.proc=(0,al.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,ll.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:ol({stderrLines:this.lastStderr,exitCode: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=Ih(i.content);i.is_error===!0&&typeof i.tool_use_id=="string"&&xh(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){ri("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:ol({resultText:r,stderrLines:this.lastStderr})});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:`${cl}${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;ri("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 fl=require("child_process"),hl=require("fs");var si=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)}},x=new si;var dl=require("node:fs"),oi=require("node:path"),Ph="@vibelet/cli";function ul(t){try{let e=JSON.parse((0,dl.readFileSync)(t,"utf8"));if(e.name===Ph&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Rh(){return"0.0.2"}var ot=Rh();var k=N.child({module:"codex"}),Pn=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,fl.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,hl.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=x.startTimer("rpc.duration");if(await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ot}}),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=x.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"),Cl=require("fs"),kl=require("readline"),A=require("path"),de=require("os");var Lh=new Set(["New session","Resumed session","Untitled session"]),Oh=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Mh(t){return t.replace(/\s+/g," ").trim()}function Rn(t){return typeof t!="string"?void 0:Mh(t)||void 0}function pl(t){let e=Rn(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 at(t){let e=Rn(t);return!e||Lh.has(e)||pl(e)}function Nh(t){for(let e of t.replace(/\r/g,"").split(`
|
|
33
|
+
`)){let n=Rn(e);if(n&&!Bh(n)&&!Dh(n))return n}}function Bh(t){return Oh.some(e=>t.startsWith(e))}function Dh(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Fh(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 ai(t,e=80){if(typeof t!="string")return;let n=Nh(t);if(!n)return;let r=Fh(n),s=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!s||pl(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=Rn(n);if(!(!r||at(r)))return r}return ai(e)}var ml=require("child_process"),lt=require("fs/promises"),Ee=require("path"),li=require("os"),yl=require("util");var Uh=(0,yl.promisify)(ml.execFile),Hh=3e3,Gt=null;function ci(){Gt=null}function qh(t){return t.replace(/^['"]|['"]$/g,"")}function Wh(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(qh)}function _l(t){let e=Wh(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 Gh(t,e){let n=_l(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 Ln(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function jh(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function zh(t){let e=Gh(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=>jh(t.agent,i));if(n.length!==1)return null;let r=ct(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 Vh(t,e){let n=t,r=e;return(Ln(e.confidence)>Ln(t.confidence)||Ln(e.confidence)===Ln(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 $h(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,i=e.get(r);e.set(r,i?Vh(i,n):n)}return[...e.values()]}async function ui(t,e){try{let{stdout:n}=await Uh(t,e,{maxBuffer:8388608});return n}catch{return""}}async function gl(t){if(!t.sessionFilePath)return t;let e=await jt(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function Yh(t){return(await ui("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
|
|
34
|
+
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Jh(t){let n=(await ui("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 Kh(){return(await ui("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=_l(i);return!Number.isFinite(r)||!s?null:{pid:r,command:i,agent:s.agent}}).filter(e=>!!e)}async function Zh(){let t=await Kh();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await Yh(e.pid),sessionFiles:await Jh(e.pid)})))}function Qh(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Xh(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ee.join)((0,li.homedir)(),".claude","projects",Qh(e)),l=(await(0,lt.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,lt.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=ct(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ee.join)((0,li.homedir)(),".codex","sessions"),r=null;async function i(o){let a=await(0,lt.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,lt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await jt(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 Sl(){if(Gt&&Date.now()<Gt.expiresAt)return Gt.value;let t=await Zh(),e=await Promise.all(t.map(async r=>{let i=zh(r);if(i)return gl(i);let s=await Xh(r.agent,r.cwd);return s?gl({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:s.sessionId,confidence:"low",sessionFilePath:s.filePath}):null})),n=$h(e.filter(r=>r!==null));return Gt={value:n,expiresAt:Date.now()+Hh},n}var wl=N.child({module:"inventory"}),ut={daemonActive:3,externalRunning:2,idle:1},vl={high:3,medium:2,low:1};function bl(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function ep(t,e){let n=t.runtime.needsAttention?1:0;return(e.runtime.needsAttention?1:0)-n||ut[e.runtime.state]-ut[t.runtime.state]||bl(t,e)}function tp(t,e){return ut[e.state]>ut[t.state]?e:ut[e.state]<ut[t.state]?t:vl[e.confidence]>vl[t.confidence]?e:t}function np(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function rp(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function ip(t,e){return e?t?!(at(e)&&!at(t)):!0:!1}function di(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function sp(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:di()}}function op(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 ap(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 lp(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=ip(i.title,n.title)?n.title:i.title,o=n.cwd||i.cwd,a=tp(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:rp(i.lastActivityAt,n.lastActivityAt);t.set(r,{...i,cwd:o,title:s,createdAt:np(i.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a})}}function cp(...t){let e=new Map;for(let n of t)lp(e,n);return[...e.values()]}function up(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&&wl.debug({total:t.length,filtered:o.length,search:r,contentMatchIds:i?.size??0},"filter applied"),o}function dp(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 fp(t,e,n,r,i,s,o){let a=s?1/0:Math.max(1,e||50),l=cp(t.sessionRecords.map(sp),t.scannedSessions,t.runningSessions.map(m=>op(m,t.scannedAt)),t.activeSessions.map(ap)),c=up(l,r,i,s,o),u=c.filter(m=>m.runtime.state!=="idle").sort(ep),d=c.filter(m=>m.runtime.state==="idle").sort(bl),f=dp(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 El(t){let e=new Date().toISOString(),[n,r,i]=await Promise.all([zt(t.agent,t.cwd),Sl(),t.search?Tl(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&wl.info({search:t.search,contentMatches:i?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),fp({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 Pl(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 Rl=5e3,hi=Pl(Rl),pi=Pl(Rl);function gi(){hi.clear(),pi.clear()}function Ll(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}function*Ol(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 fi=512*1024;async function Ml(t,e){if(e<=fi)return(0,P.readFile)(t,"utf-8");let n=await(0,P.open)(t,"r");try{let r=Buffer.alloc(fi),{bytesRead:i}=await n.read(r,0,fi,0);return r.toString("utf-8",0,i)}finally{await n.close()}}function mi(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 Nl(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?mi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Vt(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 hp(t){return t?.type!=="user"||t.message?.role!=="user"?"":Vt(t.message.content)}function Bl(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Dl(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:di()}}function ct(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 pp(t,e){let n=await Ml(t,e),r=Ol(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=hp(u),f=De([],d);f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ct("claude",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function gp(t,e){let n=await Ml(t,e),r=Ol(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=Nl(u),f=d&&!Bl(d)?De([],d):void 0;f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ct("codex",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function jt(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 pp(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 gp(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 Il(t){let e=(0,A.join)((0,de.homedir)(),".claude","projects");try{let n;t?n=[Ll(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=>jt(o,"claude")))).filter(o=>o!==null).map(o=>Dl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list claude sessions"),[]}}async function xl(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=>jt(o,"codex")))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>Dl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list codex sessions"),[]}}async function zt(t,e){let r=`list:${(0,de.homedir)()}:${t??"all"}:${e??""}`,i=hi.get(r);if(i)return i;let s;if(t==="claude")s=await Il(e);else if(t==="codex")s=await xl(e);else{let[o,a]=await Promise.all([Il(e),xl(e)]);s=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return hi.set(r,s),s}async function Tl(t,e){let r=`search:${(0,de.homedir)()}:${t}:${e??"all"}`,i=pi.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=>Al(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=>Al(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()]),pi.set(r,s),s}async function Al(t,e,n){let r=(0,Cl.createReadStream)(t,{encoding:"utf-8"}),i=(0,kl.createInterface)({input:r,crlfDelay:1/0}),s=n==="claude"?mp:yp,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||ct(n,t):null}function mp(t){return t?.type==="user"&&t.message?.role==="user"||t?.type==="assistant"&&t.message?.role==="assistant"?Vt(t.message.content):""}function yp(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return mi(t.payload.content)}let e=Nl(t);return e||""}async function On(t,e,n){let r=[];if(e==="claude"){let i=(0,A.join)((0,de.homedir)(),".claude","projects");try{let s=n?[Ll(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=Vt(u.message.content);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=Vt(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 Fl(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=mi(l.payload.content);if(!u||c==="user"&&Bl(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 Fl(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 Fl(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 dt=require("fs"),Ul=require("path");var _p=500,Mn=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()},_p)}loadFromDisk(){try{let e=(0,dt.readFileSync)(An,"utf-8");return JSON.parse(e).map(n=>({...n,lastActivityAt:n.lastActivityAt??n.createdAt}))}catch{return[]}}saveToDisk(){(0,dt.mkdirSync)((0,Ul.dirname)(An),{recursive:!0}),(0,dt.writeFileSync)(An,JSON.stringify(this.records,null,2))}};var Hl=require("path"),ql=require("os");function Nn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Hl.join)((0,ql.homedir)(),t.slice(2)):t}var $t=N.child({module:"push"}),Sp="https://exp.host/--/api/v2/push/send",ft=new Set;function yi(t){ft.add(t),$t.info({token:t,total:ft.size},"push token registered")}function _i(t){ft.delete(t),$t.info({token:t,total:ft.size},"push token unregistered")}async function Wl(t,e,n){if(ft.size===0)return;let r=[...ft].map(i=>({to:i,sound:"default",title:t,body:e,data:n}));try{let i=await fetch(Sp,{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"}),vp="Done.",Gl=180;function Te(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt}}var Bn=class{constructor(e=Wl){this.pushSender=e;this.startIdleSweep()}sessions=new Map;store=new Mn;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"),x.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"),x.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(Te(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"&&ii(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}),x.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<=Gl?n:`${n.slice(0,Math.max(1,Gl-3)).trimEnd()}...`:vp}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(Te(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++;x.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=Nn(i),b.info({agent:r,cwd:i,approvalMode:s,continueSession:o},"creating session");try{if(!(await(0,jl.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 zt(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=x.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"),x.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(Te(d)),this.updateGauges(),gi(),ci(),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 On(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=x.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"),x.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(Te(m)),this.updateGauges(),this.bindDriverLifecycle(m,i," (resumed)",e);let S=await On(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 zt(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"),x.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(Te(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)}),at(a.title)){let l=ai(i,50);l&&l!==a.title&&(a.title=l),this.store.upsert(Te(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&&ii(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(Te(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(Te(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(),gi(),ci(),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 On(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 El({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 kn;case"codex":return new Pn;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&&x.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 Si(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var zl=require("child_process");function wp(t,e){return(0,zl.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function bp(t){let e=t.split(`
|
|
40
|
+
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Vl(t,e=wp){let n;try{n=bp(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 ht=require("fs"),vi=require("os"),Yl=require("crypto"),Jl=require("path");function Kl(t){return(0,Yl.randomBytes)(t).toString("base64url")}function Ep(){return`d_${Kl(12)}`}function Tp(){return(0,vi.hostname)()}function Ip(){let t=(0,vi.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function xp(t){return{daemonId:Ep(),daemonSecret:Kl(32),displayName:Tp(),canonicalHost:Ip(),port:t,createdAt:new Date().toISOString()}}function $l(t,e){(0,ht.mkdirSync)((0,Jl.dirname)(e),{recursive:!0}),(0,ht.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
41
|
+
`,"utf8")}function Zl(t,e=Qa){try{let r=(0,ht.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,$l(s,e)),s}}catch{}let n=xp(t);return $l(n,e),n}var pt=require("crypto"),gt=require("fs"),Xl=require("path");function wi(t){return(0,pt.randomBytes)(t).toString("base64url")}function bi(t){return(0,pt.createHash)("sha256").update(t).digest("hex")}function Ql(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,pt.timingSafeEqual)(n,r)}function Ap(t){try{let e=(0,gt.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 Yt(t,e){(0,gt.mkdirSync)((0,Xl.dirname)(t),{recursive:!0}),(0,gt.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
42
|
+
`,"utf8")}var Dn=class{constructor(e=Xa){this.pairingsPath=e;this.records=Ap(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_${wi(8)}`,r=wi(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=wi(32),s={deviceId:e,deviceName:n,tokenHash:bi(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),Yt(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=bi(n);return Ql(i.tokenHash,s)?(r&&(i.lastSeenAt=new Date().toISOString(),Yt(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=bi(e),i=this.records.find(s=>!s.revokedAt&&Ql(s.tokenHash,r));return i?(n&&(i.lastSeenAt=new Date().toISOString(),Yt(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(),Yt(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Yt(this.pairingsPath,this.records)}};function Fn(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Cp(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function ec(t,e){return Cp(t)??e}function kp(t,e){return!!(t&&e&&t===e)}function Ei(t,e,n,r=!0){return t?kp(t,e)?!0:!!n(t,r):!1}var tc=require("child_process");function Ti(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function nc(t){if(!Ti(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Pp(t){if(!Ti(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Rp(t){if(!Ti(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Ii(t){return!!t&&!Pp(t)&&!Rp(t)}function mt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function rc(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Lp(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let i of r)i.internal||i.family!=="IPv4"||Ii(i.address)&&(nc(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Op(t){let e=JSON.parse(t),n=mt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>mt(o)).filter(o=>!!o).filter(o=>nc(o)&&Ii(o)),i=r[0]??n,s=[...n&&n!==i?[n]:[],...r.filter(o=>o!==i)];return{canonicalHost:i,fallbackHosts:s}}function ic(t=tc.execFileSync){try{let e=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Op(e)}catch{return{fallbackHosts:[]}}}function sc(t){let e=mt(t.canonicalHost),n=mt(t.configuredCanonicalHost)||mt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Lp(t.interfaces)].map(i=>mt(i)).filter(i=>!!i).filter(i=>Ii(i)).filter((i,s,o)=>i!==n&&o.indexOf(i)===s);return{canonicalHost:n,fallbackHosts:r}}function oc(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"}),Jt=N.child({module:"ws"}),Kt=new Bn,D=Zl(_.port),Ie=new Dn,Un=new Set,xi=new WeakSet,ac=!1,dc=Date.now(),yt=null;function _t(){let t=ic();return sc({canonicalHost:D.canonicalHost,configuredCanonicalHost:_.canonicalHost,configuredFallbackHosts:rc(_.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,cc.networkInterfaces)()})}async function Mp(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 fc(){let t=Ie.openWindow(),e=_t(),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 Np(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,Hn.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 Zt=(0,lc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${_.port}`);if(n.pathname==="/health"){let i=_t(),s={status:"ok",version:ot,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:i.canonicalHost,uptimeSeconds:Math.round((Date.now()-dc)/1e3),activeSessions:Kt.getActiveSessionCount(),pairedDevices:Ie.pairedCount(),wsClients:X.clients.size,drivers:Kt.getDriverCounts(),metrics:x.snapshot()};_.relayUrl&&(s.relayUrl=_.relayUrl),Q(e,200,s);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Fn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,fc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Fn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Ie.reset(),Q(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Fn(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 Mp(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(!Ie.consumeWindow(i.pairNonce)){Q(e,401,{error:"pair_window_expired"});return}let o=Ie.issuePairToken(i.deviceId,i.deviceName),a=_t();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=ec(t.headers.authorization,n.searchParams.get("token"));if(!Ei(r,_.legacyToken,(i,s)=>Ie.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=Nn(i);if(!(await(0,Fe.stat)(s)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Hn.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 v${ot}`)}),X=new cr.default({server:Zt});Zt.on("connection",t=>{Un.add(t),t.on("close",()=>{Un.delete(t)})});X.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${_.port}`).searchParams.get("token");if(Ei(r,_.legacyToken,(i,s)=>Ie.validateAnyPairToken(i,s)))xi.add(t);else if(r){t.close(4001,"Unauthorized");return}Jt.info({clients:X.clients.size},"client connected"),x.increment("ws.connect"),x.gauge("ws.clients",X.clients.size),v.emit("ws.connect",{clients:X.clients.size}),t.on("message",async i=>{try{let s=JSON.parse(oc(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&&Ie.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 Np(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"){Si(s,{registerToken:yi,unregisterToken:_i,respond:a=>t.send(JSON.stringify(a))});return}if(s.action==="push.unregister"){Si(s,{registerToken:yi,unregisterToken:_i,respond:a=>t.send(JSON.stringify(a))});return}await Kt.handle(t,o)}catch(s){Jt.error({error:String(s)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(s)}))}}),t.on("close",()=>{Jt.info({clients:X.clients.size},"client disconnected"),x.increment("ws.disconnect"),x.gauge("ws.clients",X.clients.size),v.emit("ws.disconnect",{clients:X.clients.size}),Kt.removeClient(t)}),t.on("error",i=>{Jt.error({error:i.message},"websocket error")})});function Ai(){for(let t of Un)try{t.destroy()}catch{}Un.clear()}function hc(){let t=nl({auditPath:st,stdoutLogPath:el,stderrLogPath:tl,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 Bp(){yt||(yt=setInterval(hc,_.storageHousekeepingIntervalMs),yt.unref())}function Dp(){yt&&(clearInterval(yt),yt=null)}function Ue(t,e=0){if(!ac){ac=!0,ee.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-dc)/1e3)}),x.stopPeriodicLog(),Dp(),Kt.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")}),Zt.close(n=>{if(n){ee.error({error:String(n)},"http close error"),Ai(),process.exit(1);return}Ai(),process.exit(e)}),setTimeout(()=>{ee.error("force exiting after shutdown timeout"),Ai(),process.exit(e||1)},3e3).unref()}}X.on("error",t=>{Jt.error({error:t.message},"wss error")});Zt.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Vl(_.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)})});Zt.listen(_.port,async()=>{hc(),v.emit("daemon.start",{port:_.port}),x.startPeriodicLog(),Bp(),ee.info({port:_.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:_t().canonicalHost,fallbackHosts:_t().fallbackHosts,claudePath:_.claudePath,codexPath:_.codexPath,auditMaxBytes:_.auditMaxBytes,daemonLogMaxBytes:_.daemonLogMaxBytes,storageHousekeepingIntervalMs:_.storageHousekeepingIntervalMs},"daemon started");let t=_t(),e=fc();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 v${ot} \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 or npx vibelet
|
|
52
|
+
Host: ${t.canonicalHost}
|
|
53
|
+
Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
|
|
54
|
+
|
|
55
|
+
Claude: ${_.claudePath}
|
|
56
|
+
Codex: ${_.codexPath}
|
|
57
|
+
`);try{let n=await uc.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
CHANGED
|
@@ -1,7 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vibelet",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
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
|
+
"dependencies": {
|
|
26
|
+
"qrcode": "^1.5.4"
|
|
27
|
+
}
|
|
7
28
|
}
|
package/index.js
DELETED