Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
809 lines (747 loc) · 29 KB
/
Copy pathcli.js
File metadata and controls
809 lines (747 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/**
* @module @krusch/toolkit/cli
* @description Atomic single-instance lockfiles (`wx` + live-PID + `staleMs` reclamation),
* `AbortController`-backed daemon signal handlers, atomic JSONL telemetry writers,
* and prototype-safe CLI command/envelope runners (`INV-LEGO-01`, `INV-LEGO-10`).
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { okEnvelope, errorEnvelope } from './http.js';
const DEFAULT_STALE_MS = 3_600_000;
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5000;
/**
* Determine whether an OS process ID is currently alive.
* `process.kill(pid, 0)` returning `true` or throwing `EPERM` means the process is alive;
* throwing `ESRCH` means the process does not exist.
*
* @param {number} pid - Candidate process ID
* @returns {boolean}
*/
function isPidAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch (err) {
if (err && err.code === 'EPERM') {
return true;
}
return false;
}
}
/**
* Parse lockfile text safely, supporting JSON payloads or plain numeric PID strings.
*
* @param {string} raw - Raw lockfile contents
* @returns {{ pid: number|null, startedAt: number|null, nonce: string|null }}
*/
function parseLockPayload(raw) {
const trimmed = typeof raw === 'string' ? raw.trim() : '';
if (!trimmed) {
return { pid: null, startedAt: null, nonce: null };
}
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === 'object') {
const pid = Number.isInteger(parsed.pid) && parsed.pid > 0 ? parsed.pid : null;
const startedAt = Number.isFinite(parsed.startedAt) ? parsed.startedAt : null;
const nonce = typeof parsed.nonce === 'string' ? parsed.nonce : null;
return { pid, startedAt, nonce };
}
} catch {
if (/^\d+$/.test(trimmed)) {
const numericPid = Number(trimmed);
if (Number.isInteger(numericPid) && numericPid > 0) {
return { pid: numericPid, startedAt: null, nonce: null };
}
}
}
return { pid: null, startedAt: null, nonce: null };
}
/**
* Read existing lockfile metadata and inode without throwing on `ENOENT`.
*
* @param {string} resolvedPath - Absolute lockfile path
* @returns {{ exists: boolean, ino: number|null, mtimeMs: number|null, pid: number|null, startedAt: number|null, nonce: string|null }}
*/
function readExistingLockState(resolvedPath) {
try {
const stat = fs.statSync(resolvedPath);
const raw = fs.readFileSync(resolvedPath, 'utf8');
const { pid, startedAt, nonce } = parseLockPayload(raw);
return {
exists: true,
ino: stat.ino,
mtimeMs: stat.mtimeMs,
pid,
startedAt,
nonce,
};
} catch (err) {
if (err && err.code === 'ENOENT') {
return { exists: false, ino: null, mtimeMs: null, pid: null, startedAt: null, nonce: null };
}
throw err;
}
}
/**
* Attempt a single exclusive atomic lockfile write (`O_CREAT | O_EXCL`).
*
* @param {string} resolvedPath - Absolute lockfile path
* @param {string} payload - Serialized JSON lock metadata
* @returns {boolean} `true` if created exclusively, `false` on `EEXIST`
*/
function tryWriteExclusiveLock(resolvedPath, payload) {
try {
fs.writeFileSync(resolvedPath, payload, { flag: 'wx', mode: 0o600 });
return true;
} catch (err) {
if (err && err.code === 'EEXIST') {
return false;
}
throw err;
}
}
/**
* Unlink a lockfile in `finally` ONLY if its `nonce` still matches this invocation.
*
* @param {string} resolvedPath - Absolute lockfile path
* @param {string} expectedNonce - Nonce generated by the acquiring invocation
*/
function releaseLockIfOwned(resolvedPath, expectedNonce) {
try {
const raw = fs.readFileSync(resolvedPath, 'utf8');
const { nonce } = parseLockPayload(raw);
if (nonce === expectedNonce) {
fs.unlinkSync(resolvedPath);
}
} catch {
// Ignore ENOENT or unreadable/reclaimed lockfile during teardown
}
}
/**
* Acquire an exclusive single-instance lockfile (`wx`), reclaiming dead-PID (`ESRCH`) or
* expired (`staleMs`) locks safely, executing `fn`, and unlinking only our own `nonce` in `finally`.
*
* @param {string} lockFilePath - Path to lockfile
* @param {(ctx: { lockFilePath: string, pid: number, nonce: string }) => Promise<unknown>|unknown} fn - Critical section callback
* @param {object} [options={}] - Lock configuration
* @param {number} [options.staleMs=3600000] - Maximum lock age in milliseconds before stale reclamation
* @param {string} [options.tool='cli.lock'] - Tool identifier for `INV-LEGO-01` envelopes
* @param {boolean} [options.rethrow=false] - Re-throw callback exceptions instead of wrapping in `errorEnvelope`
* @returns {Promise<{ ok: boolean, tool: string, summary: string, data?: object, error?: object }>}
*/
export async function withSingleInstanceLock(
lockFilePath,
fn,
{ staleMs = DEFAULT_STALE_MS, tool = 'cli.lock', rethrow = false } = {}
) {
if (typeof lockFilePath !== 'string' || lockFilePath.trim().length === 0) {
throw new TypeError('[cli] withSingleInstanceLock requires a non-empty lockFilePath string.');
}
if (typeof fn !== 'function') {
throw new TypeError('[cli] withSingleInstanceLock requires a callback function.');
}
const resolvedPath = path.resolve(lockFilePath);
fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
const nonce = crypto.randomUUID();
const payload = JSON.stringify({
pid: process.pid,
nonce,
hostname: os.hostname(),
startedAt: Date.now(),
});
let acquired = tryWriteExclusiveLock(resolvedPath, payload);
let holderPid = null;
if (!acquired) {
const existing = readExistingLockState(resolvedPath);
if (!existing.exists) {
// Lock vanished between initial `wx` and `readFileSync` — retry `wx` once.
acquired = tryWriteExclusiveLock(resolvedPath, payload);
if (!acquired) {
holderPid = readExistingLockState(resolvedPath).pid;
}
} else {
holderPid = existing.pid;
const effectiveStartedAt = existing.startedAt ?? existing.mtimeMs;
const isStale =
Number.isFinite(staleMs) &&
staleMs > 0 &&
Number.isFinite(effectiveStartedAt) &&
Date.now() - effectiveStartedAt > staleMs;
const isDead = existing.pid !== null && !isPidAlive(existing.pid);
if (isDead || isStale) {
try {
const currentStat = fs.statSync(resolvedPath);
if (currentStat.ino === existing.ino) {
fs.unlinkSync(resolvedPath);
}
} catch (unlinkErr) {
if (!unlinkErr || unlinkErr.code !== 'ENOENT') {
throw unlinkErr;
}
}
acquired = tryWriteExclusiveLock(resolvedPath, payload);
if (!acquired) {
holderPid = readExistingLockState(resolvedPath).pid ?? holderPid;
}
}
}
}
if (!acquired) {
return errorEnvelope(
'LOCK_HELD',
`Lock already held by PID ${holderPid || 'unknown'}`,
{ pid: holderPid || null, lockFilePath: resolvedPath },
tool
);
}
try {
const result = await fn({ lockFilePath: resolvedPath, pid: process.pid, nonce });
return okEnvelope(tool, 'Completed locked execution', {
lockFilePath: resolvedPath,
result,
});
} catch (err) {
if (rethrow) {
throw err;
}
return errorEnvelope(
String(err?.code || 'LOCK_EXECUTION_ERROR'),
err?.message || String(err),
{ lockFilePath: resolvedPath },
tool
);
} finally {
releaseLockIfOwned(resolvedPath, nonce);
}
}
/**
* Attach idempotent, `AbortController`-backed daemon signal handlers without leaking `process` listeners.
*
* @param {((reason: string) => Promise<unknown>|unknown)|null} [cleanupFn=null] - Optional async teardown callback
* @param {object} [options={}] - Signal handling options
* @param {string[]} [options.signals=['SIGTERM', 'SIGINT']] - OS signals to intercept
* @param {number} [options.timeoutMs=5000] - Maximum grace period for `cleanupFn`
* @param {boolean} [options.exitProcess=false] - Whether to call `process.exit(...)` after shutdown
* @param {object|null} [options.logger=null] - Optional structured logger
* @returns {{ signal: AbortSignal, shutdown: (reason?: string) => Promise<void>, detach: () => void }}
*/
export function attachDaemonSignals(
cleanupFn = null,
{
signals = ['SIGTERM', 'SIGINT'],
timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,
exitProcess = false,
logger = null,
} = {}
) {
const controller = new AbortController();
const validSignals = Array.isArray(signals)
? signals.filter((sig) => typeof sig === 'string' && sig.trim().length > 0)
: ['SIGTERM', 'SIGINT'];
const effectiveTimeoutMs =
Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS;
const listeners = [];
let shutdownPromise = null;
const detach = () => {
while (listeners.length > 0) {
const { sig, handler } = listeners.pop();
process.off(sig, handler);
}
};
const shutdown = (reason = 'manual') => {
if (shutdownPromise) {
return shutdownPromise;
}
detach();
if (!controller.signal.aborted) {
controller.abort(reason);
}
shutdownPromise = (async () => {
logger?.info?.(`Initiating daemon shutdown (${reason})...`);
let timer = null;
let exitCode = 0;
const timeoutGuard = new Promise((_, reject) => {
timer = setTimeout(() => {
const err = new Error(`Daemon shutdown timed out after ${effectiveTimeoutMs}ms`);
err.code = 'SHUTDOWN_TIMEOUT';
reject(err);
}, effectiveTimeoutMs);
timer.unref?.();
});
try {
await Promise.race([
(async () => {
if (typeof cleanupFn === 'function') {
await cleanupFn(reason);
}
})(),
timeoutGuard,
]);
logger?.info?.(`Daemon shutdown completed (${reason}).`);
} catch (err) {
exitCode = 1;
logger?.error?.(`Daemon shutdown failed (${reason}): ${err?.message || err}`, err);
throw err;
} finally {
if (timer) {
clearTimeout(timer);
}
if (exitProcess === true) {
process.exit(exitCode);
}
}
})();
return shutdownPromise;
};
for (const sig of validSignals) {
const handler = async () => {
try {
await shutdown(sig);
} catch (err) {
logger?.error?.(`Daemon signal shutdown error on ${sig}: ${err?.message || err}`, err);
}
};
listeners.push({ sig, handler });
process.on(sig, handler);
}
return { signal: controller.signal, shutdown, detach };
}
/**
* Serialize and atomically append a single NDJSON / JSONL record line (`0o600`).
*
* @param {string} filePath - Target `.jsonl` file path
* @param {unknown} record - JSON-serializable telemetry record
* @returns {{ ok: true, bytesWritten: number, filePath: string }}
*/
export function appendJsonlRecord(filePath, record) {
if (typeof filePath !== 'string' || filePath.trim().length === 0) {
throw new TypeError('[cli] appendJsonlRecord requires a non-empty filePath string.');
}
if (record === undefined || typeof record === 'function' || typeof record === 'symbol') {
throw new TypeError('[cli] appendJsonlRecord requires a JSON-serializable record.');
}
const serialized = JSON.stringify(record);
if (typeof serialized !== 'string') {
throw new TypeError('[cli] appendJsonlRecord requires a JSON-serializable record.');
}
const safeLine = `${serialized.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')}\n`;
const resolvedPath = path.resolve(filePath);
fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
fs.appendFileSync(resolvedPath, safeLine, { encoding: 'utf8', mode: 0o600 });
return {
ok: true,
bytesWritten: Buffer.byteLength(safeLine, 'utf8'),
filePath: resolvedPath,
};
}
/**
* Copy caller commands onto a null-prototype dictionary so `Object.prototype` keys
* (`constructor`, `toString`, `__proto__`, etc.) can never resolve as CLI commands.
*
* @param {Record<string, object|Function>} rawCommands - Caller command definitions
* @returns {Record<string, { name: string, description: string, summary: string, options: object, run: Function }>}
*/
function normalizeCommandsMap(rawCommands) {
const registry = Object.create(null);
if (!rawCommands || typeof rawCommands !== 'object') {
return registry;
}
for (const key of Object.keys(rawCommands)) {
if (key === '__proto__' || key.trim().length === 0) {
continue;
}
const entry = rawCommands[key];
if (typeof entry === 'function') {
registry[key] = {
name: key,
description: '',
summary: '',
options: Object.create(null),
run: entry,
};
continue;
}
if (entry && typeof entry === 'object') {
const runner = typeof entry.run === 'function' ? entry.run : entry.handler;
if (typeof runner === 'function') {
registry[key] = {
name: key,
description: String(entry.description || ''),
summary: String(entry.summary || ''),
options:
entry.options && typeof entry.options === 'object'
? entry.options
: Object.create(null),
run: runner,
};
}
}
}
return registry;
}
/**
* Merge built-in CLI flags (`--json`, `--help`/`-h`, `--version`/`-v`) with global and command options,
* avoiding short-flag collisions if a caller explicitly claims `-h` or `-v`.
*
* @param {object} globalOptions - CLI-wide `parseArgs` options
* @param {object} [commandOptions={}] - Command-specific `parseArgs` options
* @returns {Record<string, object>}
*/
function buildMergedOptions(globalOptions = {}, commandOptions = {}) {
const customEntries = [];
for (const src of [globalOptions, commandOptions]) {
if (!src || typeof src !== 'object') continue;
for (const key of Object.keys(src)) {
if (key === '__proto__') continue;
const spec = src[key];
if (spec && typeof spec === 'object') {
customEntries.push([key, spec]);
}
}
}
const usedShorts = new Set(
customEntries
.filter(([key]) => key !== 'help' && key !== 'version')
.map(([, spec]) => spec.short)
.filter((shortFlag) => typeof shortFlag === 'string' && shortFlag.length === 1)
);
const merged = Object.create(null);
merged.json = { type: 'boolean', default: false };
merged.help = usedShorts.has('h')
? { type: 'boolean', default: false }
: { type: 'boolean', short: 'h', default: false };
merged.version = usedShorts.has('v')
? { type: 'boolean', default: false }
: { type: 'boolean', short: 'v', default: false };
for (const [key, spec] of customEntries) {
merged[key] = { ...spec };
}
return merged;
}
/**
* Detect `--json` in raw `argv` prior to `--` option terminator so early `parseArgs` errors
* still honor JSON output mode.
*
* @param {string[]} argv - Raw CLI argument vector
* @returns {boolean}
*/
function detectRawJsonFlag(argv) {
for (const token of argv) {
if (token === '--') break;
if (token === '--json' || token === '--json=true') {
return true;
}
}
return false;
}
/**
* Check whether a command handler return value already conforms to `INV-LEGO-01`.
*
* @param {unknown} candidate - Handler return value
* @returns {boolean}
*/
function isLegoEnvelope(candidate) {
return (
candidate !== null &&
typeof candidate === 'object' &&
typeof candidate.ok === 'boolean' &&
typeof candidate.tool === 'string' &&
typeof candidate.summary === 'string'
);
}
/**
* Render formatted `--help` usage text for a `defineCli` instance.
*
* @param {object} meta - CLI metadata
* @returns {string}
*/
function renderCliHelp({ cliName, cliVersion, cliDescription, commandRegistry, baseOptions }) {
const commandNames = Object.keys(commandRegistry);
const hasSubcommands = commandNames.some((cmd) => cmd !== 'default');
const usageTarget = hasSubcommands ? ' <command>' : '';
const lines = [
`${cliName} v${cliVersion}${cliDescription ? ` — ${cliDescription}` : ''}`,
'',
`Usage: ${cliName}${usageTarget} [options]`,
];
if (commandNames.length > 0) {
lines.push('', 'Commands:');
const padWidth = Math.max(12, ...commandNames.map((cmd) => cmd.length + 2));
for (const cmdName of commandNames) {
const cmd = commandRegistry[cmdName];
const desc = cmd.description || cmd.summary || '';
lines.push(` ${cmdName.padEnd(padWidth)}${desc}`.trimEnd());
}
}
lines.push('', 'Options:');
for (const optName of Object.keys(baseOptions)) {
const spec = baseOptions[optName];
const shortPart = spec.short ? `-${spec.short}, ` : ' ';
const valHint = spec.type === 'string' ? ` <${optName}>` : '';
const desc = spec.description ? ` ${spec.description}` : '';
lines.push(` ${shortPart}--${optName}${valHint}${desc}`);
}
return lines.join('\n');
}
/**
* Build non-conflicting discovery options across global and command options so string flags
* preceding a subcommand preserve their value arity during preliminary positional discovery.
*
* @param {Record<string, object>} baseOptions - Merged global + built-in options
* @param {Record<string, object>} commandRegistry - Normalized command map
* @returns {Record<string, object>}
*/
function buildDiscoveryOptions(baseOptions, commandRegistry) {
const discovery = Object.create(null);
const usedShorts = new Set();
for (const key of Object.keys(baseOptions)) {
discovery[key] = baseOptions[key];
if (baseOptions[key]?.short) {
usedShorts.add(baseOptions[key].short);
}
}
for (const cmdName of Object.keys(commandRegistry)) {
const cmdOpts = commandRegistry[cmdName].options;
if (!cmdOpts || typeof cmdOpts !== 'object') continue;
for (const optKey of Object.keys(cmdOpts)) {
if (optKey === '__proto__' || Object.hasOwn(discovery, optKey)) continue;
const spec = cmdOpts[optKey];
if (!spec || typeof spec !== 'object') continue;
const copy = { ...spec };
if (copy.short && usedShorts.has(copy.short)) {
delete copy.short;
} else if (copy.short) {
usedShorts.add(copy.short);
}
discovery[optKey] = copy;
}
}
return discovery;
}
/**
* Define a zero-boilerplate, prototype-safe CLI with built-in `--json`, `--help`, `--version`,
* `node:util` `parseArgs` validation, and deterministic `INV-LEGO-01` envelope output.
*
* @param {object} [config={}] - CLI definition
* @param {string} [config.name='krusch-cli'] - CLI binary/tool name
* @param {string} [config.version='1.0.0'] - Semantic version string
* @param {string} [config.description=''] - Human-readable CLI summary
* @param {Record<string, object>} [config.options={}] - Global `parseArgs` option definitions
* @param {Record<string, object|Function>} [config.commands={}] - Subcommand definitions
* @returns {{ name: string, version: string, formatHelp: () => string, run: (argv?: string[], io?: { stdout?: Function, stderr?: Function }) => Promise<object> }}
*/
export function defineCli({
name = 'krusch-cli',
version = '1.0.0',
description = '',
options = {},
commands = {},
} = {}) {
const cliName = String(name || 'krusch-cli');
const cliVersion = String(version || '1.0.0');
const cliDescription = String(description || '');
const globalOptions = options && typeof options === 'object' ? options : {};
const commandRegistry = normalizeCommandsMap(commands);
const baseOptions = buildMergedOptions(globalOptions);
const discoveryOptions = buildDiscoveryOptions(baseOptions, commandRegistry);
const formatHelp = () =>
renderCliHelp({
cliName,
cliVersion,
cliDescription,
commandRegistry,
baseOptions,
});
const emitError = (resolvedIo, jsonMode, code, message, details = null, err = undefined) => {
const envelope = errorEnvelope(code, message, details, cliName);
if (jsonMode) {
resolvedIo.stdout(JSON.stringify(envelope));
} else {
resolvedIo.stderr(`Error [${code}]: ${message}`);
}
return err !== undefined
? { exitCode: 1, result: envelope, error: err }
: { exitCode: 1, result: envelope };
};
async function run(argv = process.argv.slice(2), io = {}) {
const safeArgv = Array.isArray(argv) ? argv.map((arg) => String(arg)) : [];
const resolvedIo = {
stdout:
typeof io?.stdout === 'function'
? io.stdout
: (line) => process.stdout.write(`${line}\n`),
stderr:
typeof io?.stderr === 'function'
? io.stderr
: (line) => process.stderr.write(`${line}\n`),
};
let jsonMode = detectRawJsonFlag(safeArgv);
let prelimPositionals = [];
let prelimValues = Object.create(null);
try {
const prelim = parseArgs({
args: safeArgv,
options: discoveryOptions,
strict: false,
allowPositionals: true,
});
prelimPositionals = prelim.positionals;
prelimValues = prelim.values;
if (typeof prelimValues.json === 'boolean') {
jsonMode = prelimValues.json || jsonMode;
}
} catch (err) {
return emitError(
resolvedIo,
jsonMode,
'INVALID_ARGS',
err?.message || String(err),
null,
err
);
}
const firstPositional = prelimPositionals[0];
const hasDefaultCommand = Object.hasOwn(commandRegistry, 'default');
if (firstPositional !== undefined && !Object.hasOwn(commandRegistry, firstPositional)) {
if (prelimValues.version === true) {
const verEnvelope = okEnvelope(cliName, `${cliName} v${cliVersion}`, {
name: cliName,
version: cliVersion,
});
resolvedIo.stdout(jsonMode ? JSON.stringify(verEnvelope) : `${cliName} ${cliVersion}`);
return { exitCode: 0, result: verEnvelope };
}
if (prelimValues.help === true) {
const helpText = formatHelp();
const helpEnvelope = okEnvelope(cliName, `Displayed help for ${cliName}`, {
name: cliName,
version: cliVersion,
help: helpText,
});
resolvedIo.stdout(jsonMode ? JSON.stringify(helpEnvelope) : helpText);
return { exitCode: 0, result: jsonMode ? helpEnvelope : helpText };
}
return emitError(resolvedIo, jsonMode, 'UNKNOWN_COMMAND', `Unknown command: ${firstPositional}`, {
command: firstPositional,
availableCommands: Object.keys(commandRegistry),
});
}
const cmdName =
firstPositional !== undefined
? firstPositional
: hasDefaultCommand
? 'default'
: null;
const targetCommand = cmdName !== null ? commandRegistry[cmdName] : null;
const activeOptions = targetCommand
? buildMergedOptions(globalOptions, targetCommand.options)
: baseOptions;
let values;
let positionals;
try {
const parsed = parseArgs({
args: safeArgv,
options: activeOptions,
strict: true,
allowPositionals: true,
});
values = parsed.values;
positionals = parsed.positionals;
jsonMode = Boolean(values.json);
} catch (err) {
return emitError(
resolvedIo,
jsonMode,
'INVALID_ARGS',
err?.message || String(err),
null,
err
);
}
if (values.version === true) {
const verEnvelope = okEnvelope(cliName, `${cliName} v${cliVersion}`, {
name: cliName,
version: cliVersion,
});
resolvedIo.stdout(jsonMode ? JSON.stringify(verEnvelope) : `${cliName} ${cliVersion}`);
return { exitCode: 0, result: verEnvelope };
}
if (values.help === true || !targetCommand) {
const helpText = formatHelp();
const helpEnvelope = okEnvelope(cliName, `Displayed help for ${cliName}`, {
name: cliName,
version: cliVersion,
commands: Object.keys(commandRegistry),
help: helpText,
});
resolvedIo.stdout(jsonMode ? JSON.stringify(helpEnvelope) : helpText);
return { exitCode: 0, result: jsonMode ? helpEnvelope : helpText };
}
const restPositionals = firstPositional !== undefined ? positionals.slice(1) : positionals;
try {
const res = await targetCommand.run({
values,
positionals: restPositionals,
rawArgv: safeArgv,
io: resolvedIo,
});
if (jsonMode) {
const wrapped = isLegoEnvelope(res)
? res
: res && typeof res === 'object' && res.ok === false
? errorEnvelope(
res.code || res.error?.code || 'CLI_ERROR',
res.message || res.error?.message || `${cmdName} failed`,
res.details ?? res.error?.details ?? null,
cliName
)
: okEnvelope(
cliName,
targetCommand.summary || `${cmdName} completed`,
res ?? {}
);
resolvedIo.stdout(JSON.stringify(wrapped));
return {
exitCode: res?.ok === false ? 1 : 0,
result: wrapped,
};
}
if (res && typeof res === 'object' && res.ok === false) {
const errMsg = res.error?.message || res.message || res.summary || `${cmdName} failed`;
const errCode = res.error?.code || res.code || 'CLI_ERROR';
resolvedIo.stderr(`Error [${errCode}]: ${errMsg}`);
}
return {
exitCode: res?.ok === false ? 1 : 0,
result: res,
};
} catch (err) {
const errCode =
err && typeof err.code === 'string' && err.code.length > 0 ? err.code : 'CLI_ERROR';
const errMsg =
err && typeof err.message === 'string' && err.message.length > 0
? err.message
: String(err);
const envelope = errorEnvelope(errCode, errMsg, null, cliName);
if (jsonMode) {
resolvedIo.stdout(JSON.stringify(envelope));
} else {
resolvedIo.stderr(`Error [${errCode}]: ${errMsg}`);
}
return { exitCode: 1, result: envelope, error: err };
}
}
return {
name: cliName,
version: cliVersion,
formatHelp,
run,
};
}