hacklab 26.922.5 → 26.926.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +340 -29
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
5
|
// package.json
|
|
6
|
-
var version = "26.
|
|
6
|
+
var version = "26.926.1";
|
|
7
7
|
|
|
8
8
|
// src/auth.ts
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
@@ -123,19 +123,72 @@ Waiting for you to connect your account…`);
|
|
|
123
123
|
throw new Error("CLI sign-in expired. Run the command again to retry.");
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
-
// src/
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
126
|
+
// src/daemon.ts
|
|
127
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
128
|
+
import { once as once2 } from "node:events";
|
|
129
|
+
import { realpathSync } from "node:fs";
|
|
130
|
+
import { mkdir as mkdir3, readFile as readFile3, rm as rm3, stat, writeFile as writeFile3 } from "node:fs/promises";
|
|
131
|
+
import { homedir as homedir3 } from "node:os";
|
|
132
|
+
import { join as join3 } from "node:path";
|
|
133
|
+
import { text as text2 } from "node:stream/consumers";
|
|
130
134
|
|
|
131
135
|
// src/sync.ts
|
|
132
136
|
import { spawn as spawn2 } from "node:child_process";
|
|
137
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
133
138
|
import { once } from "node:events";
|
|
134
139
|
import { createRequire } from "node:module";
|
|
135
140
|
import { text } from "node:stream/consumers";
|
|
136
|
-
|
|
141
|
+
|
|
142
|
+
// src/origin.ts
|
|
143
|
+
function cliOrigin() {
|
|
144
|
+
return "https://hacklab.so";
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/state.ts
|
|
148
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
149
|
+
import { mkdir as mkdir2, readFile as readFile2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
150
|
+
import { homedir as homedir2 } from "node:os";
|
|
151
|
+
import { join as join2 } from "node:path";
|
|
152
|
+
var stateDirectory = join2(homedir2(), ".config", "hacklab", "state");
|
|
153
|
+
function statePath(origin, directory) {
|
|
154
|
+
return join2(directory, `${createHash2("sha256").update(origin).digest("hex")}.json`);
|
|
155
|
+
}
|
|
156
|
+
async function readState(origin, directory = stateDirectory) {
|
|
157
|
+
try {
|
|
158
|
+
const value = JSON.parse(await readFile2(statePath(origin, directory), "utf8"));
|
|
159
|
+
return value && typeof value === "object" ? value : {};
|
|
160
|
+
} catch {
|
|
161
|
+
return {};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function writeState(origin, state, directory = stateDirectory) {
|
|
165
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
166
|
+
const path = statePath(origin, directory);
|
|
167
|
+
const temporary = `${path}.${randomUUID2()}.tmp`;
|
|
168
|
+
try {
|
|
169
|
+
await writeFile2(temporary, JSON.stringify(state), { mode: 384, flag: "wx" });
|
|
170
|
+
await rename2(temporary, path);
|
|
171
|
+
} finally {
|
|
172
|
+
await rm2(temporary, { force: true });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/sync.ts
|
|
177
|
+
var dayMs = 24 * 60 * 60 * 1000;
|
|
178
|
+
var sinceWindowDays = 2;
|
|
179
|
+
var defaultIntervalSeconds = 15 * 60;
|
|
180
|
+
function sinceDate(from) {
|
|
181
|
+
const date = new Date(from - sinceWindowDays * dayMs);
|
|
182
|
+
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
|
183
|
+
return local.toISOString().slice(0, 10);
|
|
184
|
+
}
|
|
185
|
+
var describeType = (value) => value === undefined ? "missing" : value === null ? "null" : Array.isArray(value) ? "an array" : typeof value === "object" ? "an object" : `a ${typeof value}`;
|
|
186
|
+
async function collectUsage(since) {
|
|
137
187
|
const require2 = createRequire(import.meta.url);
|
|
138
|
-
const
|
|
188
|
+
const args = [require2.resolve("ccusage/src/cli.js"), "session", "--json"];
|
|
189
|
+
if (since)
|
|
190
|
+
args.push("--since", since);
|
|
191
|
+
const child = spawn2(process.execPath, args, { stdio: ["ignore", "pipe", "inherit"] });
|
|
139
192
|
const [body, [exitCode]] = await Promise.all([text(child.stdout), once(child, "close")]);
|
|
140
193
|
if (exitCode !== 0)
|
|
141
194
|
throw new Error(`ccusage failed (exit ${exitCode}). Nothing synced.`);
|
|
@@ -145,8 +198,12 @@ async function collectUsage() {
|
|
|
145
198
|
} catch {
|
|
146
199
|
throw new Error("ccusage returned invalid JSON. Nothing synced.");
|
|
147
200
|
}
|
|
148
|
-
|
|
149
|
-
|
|
201
|
+
const totals = report?.totals;
|
|
202
|
+
if (!Array.isArray(report?.session)) {
|
|
203
|
+
throw new Error(`Unexpected ccusage report: session is ${describeType(report?.session)}, expected an array. Nothing synced.`);
|
|
204
|
+
}
|
|
205
|
+
if (typeof totals !== "object" || totals === null || Array.isArray(totals)) {
|
|
206
|
+
throw new Error(`Unexpected ccusage report: totals is ${describeType(totals)}, expected an object. Nothing synced.`);
|
|
150
207
|
}
|
|
151
208
|
if (Buffer.byteLength(body) > 20 * 1024 * 1024)
|
|
152
209
|
throw new Error("Usage report exceeds 20 MB. Nothing synced.");
|
|
@@ -169,7 +226,7 @@ async function readResult(response) {
|
|
|
169
226
|
return {};
|
|
170
227
|
}
|
|
171
228
|
}
|
|
172
|
-
async function uploadUsage(origin, token, body) {
|
|
229
|
+
async function uploadUsage(origin, token, body, quiet = false) {
|
|
173
230
|
const response = await fetch(`${origin}/api/token-usage`, {
|
|
174
231
|
method: "POST",
|
|
175
232
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
|
@@ -184,59 +241,313 @@ async function uploadUsage(origin, token, body) {
|
|
|
184
241
|
}
|
|
185
242
|
if (result.ok !== true)
|
|
186
243
|
throw new Error("Hacklab did not confirm the sync. Run hacklab sync to retry.");
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
244
|
+
if (!quiet) {
|
|
245
|
+
console.log(`Synced ${plural(result.sessions ?? 0, "usage session")} to Hacklab.`);
|
|
246
|
+
if (result.duplicates)
|
|
247
|
+
console.log(`Merged ${plural(result.duplicates, "repeated session")}.`);
|
|
248
|
+
if (result.skipped)
|
|
249
|
+
console.log(`Skipped ${plural(result.skipped, "unreadable session")}. ${describeIssues(result)}`.trim());
|
|
250
|
+
if (result.sessions === 0)
|
|
251
|
+
console.log("No usage found. Use your coding agent, then run hacklab sync again.");
|
|
252
|
+
}
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
var fingerprint = (body) => createHash3("sha256").update(body).digest("hex");
|
|
256
|
+
function nextInterval(result, current) {
|
|
257
|
+
const proposed = result.nextSyncSeconds;
|
|
258
|
+
return typeof proposed === "number" && Number.isFinite(proposed) && proposed >= 60 ? Math.min(Math.trunc(proposed), 24 * 60 * 60) : current;
|
|
194
259
|
}
|
|
195
260
|
async function sync() {
|
|
196
261
|
const origin = cliOrigin();
|
|
197
262
|
const token = await authenticate(origin);
|
|
198
263
|
console.log("Collecting ccusage session data…");
|
|
199
264
|
const body = await collectUsage();
|
|
200
|
-
await uploadUsage(origin, token, body);
|
|
265
|
+
const result = await uploadUsage(origin, token, body);
|
|
266
|
+
const state = await readState(origin);
|
|
267
|
+
const now = new Date().toISOString();
|
|
268
|
+
await writeState(origin, {
|
|
269
|
+
...state,
|
|
270
|
+
fingerprint: fingerprint(body),
|
|
271
|
+
fingerprintSince: "",
|
|
272
|
+
lastSyncedAt: now,
|
|
273
|
+
lastFullSyncAt: now,
|
|
274
|
+
intervalSeconds: nextInterval(result, state.intervalSeconds)
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
async function backgroundSync() {
|
|
278
|
+
const origin = cliOrigin();
|
|
279
|
+
const token = await readCredential(origin);
|
|
280
|
+
if (!token)
|
|
281
|
+
throw new Error("No saved Hacklab authorization. Run hacklab login to reconnect this machine.");
|
|
282
|
+
const state = await readState(origin);
|
|
283
|
+
const now = Date.now();
|
|
284
|
+
const lastSyncedAt = state.lastSyncedAt ? Date.parse(state.lastSyncedAt) : Number.NaN;
|
|
285
|
+
const interval = (state.intervalSeconds ?? defaultIntervalSeconds) * 1000;
|
|
286
|
+
if (Number.isFinite(lastSyncedAt) && now - lastSyncedAt < interval)
|
|
287
|
+
return "too-soon";
|
|
288
|
+
const lastFullSyncAt = state.lastFullSyncAt ? Date.parse(state.lastFullSyncAt) : Number.NaN;
|
|
289
|
+
const full = !Number.isFinite(lastFullSyncAt) || now - lastFullSyncAt >= dayMs;
|
|
290
|
+
const since = full ? "" : sinceDate(Number.isFinite(lastSyncedAt) ? lastSyncedAt : now);
|
|
291
|
+
const body = await collectUsage(since || undefined);
|
|
292
|
+
const current = fingerprint(body);
|
|
293
|
+
if (!full && since === state.fingerprintSince && current === state.fingerprint) {
|
|
294
|
+
await writeState(origin, { ...state, lastSyncedAt: new Date(now).toISOString() });
|
|
295
|
+
return "unchanged";
|
|
296
|
+
}
|
|
297
|
+
const result = await uploadUsage(origin, token, body, true);
|
|
298
|
+
const timestamp = new Date().toISOString();
|
|
299
|
+
await writeState(origin, {
|
|
300
|
+
...state,
|
|
301
|
+
fingerprint: current,
|
|
302
|
+
fingerprintSince: since,
|
|
303
|
+
lastSyncedAt: timestamp,
|
|
304
|
+
lastFullSyncAt: full ? timestamp : state.lastFullSyncAt,
|
|
305
|
+
intervalSeconds: nextInterval(result, state.intervalSeconds)
|
|
306
|
+
});
|
|
307
|
+
return "synced";
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/daemon.ts
|
|
311
|
+
var label = "so.hacklab.sync";
|
|
312
|
+
var logPath = join3(homedir3(), ".config", "hacklab", "daemon.log");
|
|
313
|
+
var plistPath = join3(homedir3(), "Library", "LaunchAgents", `${label}.plist`);
|
|
314
|
+
var systemdDirectory = join3(homedir3(), ".config", "systemd", "user");
|
|
315
|
+
var servicePath = join3(systemdDirectory, "hacklab-sync.service");
|
|
316
|
+
var timerPath = join3(systemdDirectory, "hacklab-sync.timer");
|
|
317
|
+
var maxLogBytes = 1024 * 1024;
|
|
318
|
+
var daemonSupported = process.platform === "darwin" || process.platform === "linux";
|
|
319
|
+
|
|
320
|
+
class DaemonError extends Error {
|
|
321
|
+
}
|
|
322
|
+
async function run(command, args) {
|
|
323
|
+
const child = spawn3(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
324
|
+
const [out, err, [code]] = await Promise.all([
|
|
325
|
+
text2(child.stdout),
|
|
326
|
+
text2(child.stderr),
|
|
327
|
+
once2(child, "close").catch(() => [1])
|
|
328
|
+
]);
|
|
329
|
+
return { code: code ?? 1, output: `${out}${err}`.trim() };
|
|
330
|
+
}
|
|
331
|
+
function command() {
|
|
332
|
+
const entry = process.argv[1];
|
|
333
|
+
if (!entry)
|
|
334
|
+
throw new DaemonError("Could not locate the Hacklab CLI on this machine.");
|
|
335
|
+
return [process.execPath, realpathSync(entry), "sync", "--daemon"];
|
|
336
|
+
}
|
|
337
|
+
var escapeXml = (value) => value.replace(/[<>&'"]/g, (character) => ({ "<": "<", ">": ">", "&": "&", "'": "'", '"': """ })[character]);
|
|
338
|
+
function plist(seconds) {
|
|
339
|
+
const args = command().map((value) => ` <string>${escapeXml(value)}</string>`).join(`
|
|
340
|
+
`);
|
|
341
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
342
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
343
|
+
<plist version="1.0">
|
|
344
|
+
<dict>
|
|
345
|
+
<key>Label</key><string>${escapeXml(label)}</string>
|
|
346
|
+
<key>ProgramArguments</key>
|
|
347
|
+
<array>
|
|
348
|
+
${args}
|
|
349
|
+
</array>
|
|
350
|
+
<key>StartInterval</key><integer>${seconds}</integer>
|
|
351
|
+
<key>RunAtLoad</key><false/>
|
|
352
|
+
<key>ProcessType</key><string>Background</string>
|
|
353
|
+
<key>LowPriorityIO</key><true/>
|
|
354
|
+
<key>Nice</key><integer>5</integer>
|
|
355
|
+
<key>StandardOutPath</key><string>${escapeXml(logPath)}</string>
|
|
356
|
+
<key>StandardErrorPath</key><string>${escapeXml(logPath)}</string>
|
|
357
|
+
</dict>
|
|
358
|
+
</plist>
|
|
359
|
+
`;
|
|
360
|
+
}
|
|
361
|
+
var units = (seconds) => ({
|
|
362
|
+
service: `[Unit]
|
|
363
|
+
Description=Hacklab usage sync
|
|
364
|
+
|
|
365
|
+
[Service]
|
|
366
|
+
Type=oneshot
|
|
367
|
+
Nice=5
|
|
368
|
+
ExecStart=${command().map((value) => JSON.stringify(value)).join(" ")}
|
|
369
|
+
`,
|
|
370
|
+
timer: `[Unit]
|
|
371
|
+
Description=Hacklab usage sync every ${Math.round(seconds / 60)} minutes
|
|
372
|
+
|
|
373
|
+
[Timer]
|
|
374
|
+
OnBootSec=2min
|
|
375
|
+
OnUnitActiveSec=${seconds}s
|
|
376
|
+
AccuracySec=1min
|
|
377
|
+
RandomizedDelaySec=60
|
|
378
|
+
Persistent=true
|
|
379
|
+
|
|
380
|
+
[Install]
|
|
381
|
+
WantedBy=timers.target
|
|
382
|
+
`
|
|
383
|
+
});
|
|
384
|
+
async function exists(path) {
|
|
385
|
+
try {
|
|
386
|
+
await stat(path);
|
|
387
|
+
return true;
|
|
388
|
+
} catch {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async function installLaunchd(seconds) {
|
|
393
|
+
await mkdir3(join3(homedir3(), "Library", "LaunchAgents"), { recursive: true });
|
|
394
|
+
await mkdir3(join3(homedir3(), ".config", "hacklab"), { recursive: true, mode: 448 });
|
|
395
|
+
await writeFile3(plistPath, plist(seconds), { mode: 420 });
|
|
396
|
+
const target = `gui/${process.getuid?.() ?? ""}`;
|
|
397
|
+
await run("launchctl", ["bootout", `${target}/${label}`]);
|
|
398
|
+
const bootstrap = await run("launchctl", ["bootstrap", target, plistPath]);
|
|
399
|
+
if (bootstrap.code === 0)
|
|
400
|
+
return plistPath;
|
|
401
|
+
const legacy = await run("launchctl", ["load", "-w", plistPath]);
|
|
402
|
+
if (legacy.code === 0)
|
|
403
|
+
return plistPath;
|
|
404
|
+
await rm3(plistPath, { force: true });
|
|
405
|
+
throw new DaemonError(`launchctl refused the Hacklab launch agent.${bootstrap.output ? ` ${bootstrap.output}` : ""}`);
|
|
406
|
+
}
|
|
407
|
+
async function installSystemd(seconds) {
|
|
408
|
+
const probe = await run("systemctl", ["--user", "--version"]);
|
|
409
|
+
if (probe.code !== 0)
|
|
410
|
+
throw new DaemonError("systemd user services are unavailable on this machine.");
|
|
411
|
+
await mkdir3(systemdDirectory, { recursive: true });
|
|
412
|
+
const { service, timer } = units(seconds);
|
|
413
|
+
await writeFile3(servicePath, service, { mode: 420 });
|
|
414
|
+
await writeFile3(timerPath, timer, { mode: 420 });
|
|
415
|
+
await run("systemctl", ["--user", "daemon-reload"]);
|
|
416
|
+
const enable = await run("systemctl", ["--user", "enable", "--now", "hacklab-sync.timer"]);
|
|
417
|
+
if (enable.code !== 0) {
|
|
418
|
+
await rm3(servicePath, { force: true });
|
|
419
|
+
await rm3(timerPath, { force: true });
|
|
420
|
+
throw new DaemonError(`systemd refused the Hacklab timer.${enable.output ? ` ${enable.output}` : ""}`);
|
|
421
|
+
}
|
|
422
|
+
return timerPath;
|
|
423
|
+
}
|
|
424
|
+
async function installDaemon(seconds = defaultIntervalSeconds) {
|
|
425
|
+
if (!daemonSupported)
|
|
426
|
+
throw new DaemonError("Background sync is only available on macOS and Linux.");
|
|
427
|
+
return process.platform === "darwin" ? installLaunchd(seconds) : installSystemd(seconds);
|
|
428
|
+
}
|
|
429
|
+
async function uninstallDaemon() {
|
|
430
|
+
if (process.platform === "darwin") {
|
|
431
|
+
if (!await exists(plistPath))
|
|
432
|
+
return false;
|
|
433
|
+
await run("launchctl", ["bootout", `gui/${process.getuid?.() ?? ""}/${label}`]);
|
|
434
|
+
await run("launchctl", ["unload", "-w", plistPath]);
|
|
435
|
+
await rm3(plistPath, { force: true });
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
if (process.platform === "linux") {
|
|
439
|
+
if (!await exists(timerPath))
|
|
440
|
+
return false;
|
|
441
|
+
await run("systemctl", ["--user", "disable", "--now", "hacklab-sync.timer"]);
|
|
442
|
+
await rm3(timerPath, { force: true });
|
|
443
|
+
await rm3(servicePath, { force: true });
|
|
444
|
+
await run("systemctl", ["--user", "daemon-reload"]);
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
var daemonInstalled = () => exists(process.platform === "darwin" ? plistPath : timerPath);
|
|
450
|
+
var daemonPath = () => process.platform === "darwin" ? plistPath : timerPath;
|
|
451
|
+
async function trimLog() {
|
|
452
|
+
try {
|
|
453
|
+
const { size } = await stat(logPath);
|
|
454
|
+
if (size <= maxLogBytes)
|
|
455
|
+
return;
|
|
456
|
+
const body = await readFile3(logPath, "utf8");
|
|
457
|
+
await writeFile3(logPath, body.slice(-maxLogBytes / 2), { mode: 384 });
|
|
458
|
+
} catch {}
|
|
201
459
|
}
|
|
202
460
|
|
|
203
461
|
// src/index.ts
|
|
204
462
|
var help = `Hacklab CLI
|
|
205
463
|
|
|
206
464
|
Usage:
|
|
207
|
-
hacklab sync
|
|
208
|
-
hacklab login
|
|
209
|
-
hacklab logout
|
|
210
|
-
hacklab
|
|
211
|
-
hacklab
|
|
465
|
+
hacklab sync Sign in, upload usage, and keep this machine in sync
|
|
466
|
+
hacklab login Sign in without uploading
|
|
467
|
+
hacklab logout Clear saved authorization
|
|
468
|
+
hacklab daemon status Show whether background sync is installed
|
|
469
|
+
hacklab daemon uninstall Stop syncing in the background
|
|
470
|
+
hacklab daemon install Start syncing in the background
|
|
471
|
+
hacklab --help Show help
|
|
472
|
+
hacklab --version Show version
|
|
473
|
+
`;
|
|
474
|
+
var commands = ["sync", "login", "logout", "daemon"];
|
|
475
|
+
var daemonActions = ["install", "uninstall", "status"];
|
|
476
|
+
async function offerDaemon() {
|
|
477
|
+
if (process.env.HACKLAB_NO_DAEMON === "1" || !daemonSupported)
|
|
478
|
+
return;
|
|
479
|
+
if (await daemonInstalled())
|
|
480
|
+
return;
|
|
481
|
+
try {
|
|
482
|
+
await installDaemon();
|
|
483
|
+
} catch (error) {
|
|
484
|
+
console.error(`
|
|
485
|
+
Could not install background sync: ${error instanceof Error ? error.message : "unknown error"}
|
|
486
|
+
Your usage was uploaded. Run hacklab sync again whenever you want to update it.`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async function runDaemonCommand(action) {
|
|
490
|
+
if (action === "status") {
|
|
491
|
+
const installed = await daemonInstalled();
|
|
492
|
+
console.log(installed ? `Background sync is installed at ${daemonPath()}.
|
|
493
|
+
Log: ${logPath}` : "Background sync is not installed. Run hacklab daemon install to start it.");
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (action === "uninstall") {
|
|
497
|
+
console.log(await uninstallDaemon() ? "Background sync removed. Run hacklab sync to upload manually." : "Background sync was not installed.");
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
await installDaemon();
|
|
501
|
+
console.log(`Background sync installed at ${daemonPath()}. Hacklab updates every 15 minutes.`);
|
|
502
|
+
}
|
|
212
503
|
try {
|
|
213
504
|
const { values, positionals } = parseArgs({
|
|
214
505
|
args: process.argv.slice(2),
|
|
215
506
|
options: {
|
|
216
507
|
help: { type: "boolean", short: "h" },
|
|
217
|
-
version: { type: "boolean", short: "v" }
|
|
508
|
+
version: { type: "boolean", short: "v" },
|
|
509
|
+
daemon: { type: "boolean" }
|
|
218
510
|
},
|
|
219
511
|
allowPositionals: true
|
|
220
512
|
});
|
|
221
|
-
|
|
513
|
+
const [command, action] = positionals;
|
|
514
|
+
if (positionals.length > 2 || command && !commands.includes(command)) {
|
|
515
|
+
throw new Error("Unknown command. Run hacklab --help for usage.");
|
|
516
|
+
}
|
|
517
|
+
if (command === "daemon" ? !daemonActions.includes(action ?? "") : positionals.length > 1) {
|
|
222
518
|
throw new Error("Unknown command. Run hacklab --help for usage.");
|
|
223
519
|
}
|
|
224
520
|
if (values.help) {
|
|
225
521
|
console.log(help);
|
|
226
522
|
} else if (values.version) {
|
|
227
523
|
console.log(version);
|
|
228
|
-
} else if (
|
|
524
|
+
} else if (command === "login") {
|
|
229
525
|
await authenticate(cliOrigin());
|
|
230
526
|
console.log("Signed in to Hacklab. Run hacklab sync to upload usage.");
|
|
231
|
-
} else if (
|
|
527
|
+
} else if (command === "logout") {
|
|
528
|
+
await uninstallDaemon();
|
|
232
529
|
await removeCredential(cliOrigin());
|
|
233
530
|
console.log("Saved CLI authorization cleared. Run hacklab sync to sign in again.");
|
|
234
|
-
} else if (
|
|
531
|
+
} else if (command === "daemon") {
|
|
532
|
+
await runDaemonCommand(action);
|
|
533
|
+
} else if (command === "sync" && values.daemon) {
|
|
534
|
+
await trimLog();
|
|
535
|
+
const outcome = await backgroundSync();
|
|
536
|
+
if (outcome === "synced")
|
|
537
|
+
console.log(`${new Date().toISOString()} synced`);
|
|
538
|
+
} else if (command === "sync") {
|
|
235
539
|
await sync();
|
|
540
|
+
await offerDaemon();
|
|
236
541
|
} else {
|
|
237
542
|
console.log(help);
|
|
238
543
|
}
|
|
239
544
|
} catch (error) {
|
|
240
|
-
|
|
545
|
+
const message = error instanceof Error ? error.message : "Could not run Hacklab CLI.";
|
|
546
|
+
if (error instanceof DaemonError) {
|
|
547
|
+
console.error(`${message}
|
|
548
|
+
Run hacklab sync to upload manually.`);
|
|
549
|
+
} else {
|
|
550
|
+
console.error(process.argv.includes("--daemon") ? `${new Date().toISOString()} ${message}` : message);
|
|
551
|
+
}
|
|
241
552
|
process.exitCode = 1;
|
|
242
553
|
}
|