invoket 0.1.6 → 0.1.8

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/src/cli.ts CHANGED
@@ -1,551 +1,15 @@
1
1
  #!/usr/bin/env bun
2
2
  import { Context } from "./context";
3
-
4
- // Supported parameter types
5
- type ParamType = "string" | "number" | "boolean" | "object" | "array";
6
-
7
- // Flag metadata for a parameter
8
- interface FlagMeta {
9
- long: string; // e.g., "--name"
10
- short?: string; // e.g., "-n"
11
- aliases?: string[]; // e.g., ["--environment"]
12
- }
13
-
14
- // Parameter metadata extracted from TypeScript
15
- interface ParamMeta {
16
- name: string;
17
- type: ParamType;
18
- required: boolean;
19
- isRest: boolean;
20
- flag?: FlagMeta;
21
- }
22
-
23
- interface TaskMeta {
24
- description: string;
25
- params: ParamMeta[];
26
- }
27
-
28
- // Parsed CLI arguments
29
- interface ParsedArgs {
30
- positional: string[];
31
- flags: Map<string, string | boolean>;
32
- }
33
-
34
- interface DiscoveredTasks {
35
- root: Map<string, TaskMeta>;
36
- namespaced: Map<string, Map<string, TaskMeta>>; // namespace -> method -> meta
37
- classDoc: string | null;
38
- }
39
-
40
- // Extract class-level JSDoc for Tasks class
41
- function extractClassDoc(source: string): string | null {
42
- const match = source.match(
43
- /\/\*\*\s*([^*]*(?:\*(?!\/)[^*]*)*)\*\/\s*export\s+class\s+Tasks/,
44
- );
45
- if (!match) return null;
46
-
47
- const lines = match[1]
48
- .split("\n")
49
- .map((line) => line.replace(/^\s*\*?\s*/, "").trim())
50
- .filter((line) => line && !line.startsWith("@"));
51
-
52
- return lines[0] || null;
53
- }
54
-
55
- // Parse command to extract namespace and method
56
- function parseCommand(command: string): {
57
- namespace: string | null;
58
- method: string;
59
- } {
60
- const colonIdx = command.indexOf(":");
61
- const dotIdx = command.indexOf(".");
62
-
63
- let sepIdx = -1;
64
- if (colonIdx !== -1 && dotIdx !== -1) {
65
- sepIdx = Math.min(colonIdx, dotIdx);
66
- } else if (colonIdx !== -1) {
67
- sepIdx = colonIdx;
68
- } else if (dotIdx !== -1) {
69
- sepIdx = dotIdx;
70
- }
71
-
72
- if (sepIdx !== -1) {
73
- return {
74
- namespace: command.slice(0, sepIdx),
75
- method: command.slice(sepIdx + 1),
76
- };
77
- }
78
-
79
- return { namespace: null, method: command };
80
- }
81
-
82
- // Extract methods from a class definition in source
83
- function extractMethodsFromClass(
84
- source: string,
85
- className: string,
86
- ): Map<string, TaskMeta> {
87
- const methods = new Map<string, TaskMeta>();
88
-
89
- // Find the class body
90
- const classPattern = new RegExp(
91
- `class\\s+${className}\\s*(?:extends\\s+\\w+)?\\s*\\{([\\s\\S]*?)\\n\\}`,
92
- );
93
- const classMatch = source.match(classPattern);
94
- if (!classMatch) return methods;
95
-
96
- const classBody = classMatch[1];
97
-
98
- // Match method declarations with JSDoc
99
- const methodPattern =
100
- /\/\*\*\s*([^*]*(?:\*(?!\/)[^*]*)*)\*\/\s*async\s+(\w+)\s*\(\s*c\s*:\s*Context\s*(?:,\s*([^)]+))?\s*\)/g;
101
-
102
- let match;
103
- while ((match = methodPattern.exec(classBody)) !== null) {
104
- const [, jsdoc, methodName, paramsStr] = match;
105
-
106
- // Skip private methods and constructor
107
- if (methodName.startsWith("_") || methodName === "constructor") {
108
- continue;
109
- }
110
-
111
- const description =
112
- jsdoc
113
- .split("\n")
114
- .map((line) => line.replace(/^\s*\*?\s*/, "").trim())
115
- .filter((line) => line && !line.startsWith("@"))[0] || "";
116
-
117
- const params = parseParams(paramsStr, jsdoc);
118
- methods.set(methodName, { description, params });
119
- }
120
-
121
- return methods;
122
- }
123
-
124
- // Extract @flag annotations from JSDoc
125
- function extractFlagAnnotations(
126
- jsdoc: string,
127
- ): Map<string, { short?: string; aliases?: string[] }> {
128
- const flags = new Map<string, { short?: string; aliases?: string[] }>();
129
-
130
- // Match @flag paramName -s --alias1 --alias2
131
- const flagPattern = /@flag\s+(\w+)\s+([^\n@]*)/g;
132
- let match;
133
-
134
- while ((match = flagPattern.exec(jsdoc)) !== null) {
135
- const [, paramName, flagsStr] = match;
136
- const parts = flagsStr.trim().split(/\s+/);
137
-
138
- let short: string | undefined;
139
- const aliases: string[] = [];
140
-
141
- for (const part of parts) {
142
- if (part.startsWith("--")) {
143
- aliases.push(part);
144
- } else if (part.startsWith("-") && part.length === 2) {
145
- short = part;
146
- }
147
- }
148
-
149
- flags.set(paramName, {
150
- short: short,
151
- aliases: aliases.length > 0 ? aliases : undefined,
152
- });
153
- }
154
-
155
- return flags;
156
- }
157
-
158
- // Parse parameter string into ParamMeta array
159
- function parseParams(
160
- paramsStr: string | undefined,
161
- jsdoc: string = "",
162
- ): ParamMeta[] {
163
- const params: ParamMeta[] = [];
164
- if (!paramsStr) return params;
165
-
166
- const flagAnnotations = extractFlagAnnotations(jsdoc);
167
-
168
- // Check for rest parameter first: ...name: type
169
- const restMatch = paramsStr.match(/\.\.\.(\w+)\s*:\s*(\w+\[\]|\w+)/);
170
- if (restMatch) {
171
- const [, name, rawType] = restMatch;
172
- params.push({
173
- name,
174
- type: rawType.endsWith("[]") ? "array" : "string",
175
- required: false,
176
- isRest: true,
177
- // Rest params don't get flags
178
- });
179
- return params;
180
- }
181
-
182
- const paramPattern =
183
- /(\w+)\s*:\s*(\w+\[\]|Record<[^>]+>|\{[^}]*\}|string|number|boolean|\w+)(?:\s*=\s*[^,)]+)?/g;
184
- let paramMatch;
185
-
186
- while ((paramMatch = paramPattern.exec(paramsStr)) !== null) {
187
- const [fullMatch, name, rawType] = paramMatch;
188
- const hasDefault = fullMatch.includes("=");
189
-
190
- let type: ParamType;
191
- if (rawType === "string") {
192
- type = "string";
193
- } else if (rawType === "number") {
194
- type = "number";
195
- } else if (rawType === "boolean") {
196
- type = "boolean";
197
- } else if (rawType.endsWith("[]")) {
198
- type = "array";
199
- } else {
200
- type = "object";
201
- }
202
-
203
- // Build flag metadata
204
- const annotation = flagAnnotations.get(name);
205
- const flag: FlagMeta = {
206
- long: `--${name}`,
207
- short: annotation?.short,
208
- aliases: annotation?.aliases,
209
- };
210
-
211
- params.push({ name, type, required: !hasDefault, isRest: false, flag });
212
- }
213
-
214
- return params;
215
- }
216
-
217
- // Discover all tasks including namespaced ones (source parsing only)
218
- function discoverAllTasks(source: string): DiscoveredTasks {
219
- const root = extractMethodsFromClass(source, "Tasks");
220
- const namespaced = new Map<string, Map<string, TaskMeta>>();
221
- const classDoc = extractClassDoc(source);
222
-
223
- // Find namespace assignments in Tasks class: propertyName = new ClassName()
224
- const nsPattern = /(\w+)\s*=\s*new\s+(\w+)\s*\(\s*\)/g;
225
- let nsMatch;
226
-
227
- while ((nsMatch = nsPattern.exec(source)) !== null) {
228
- const [, propName, className] = nsMatch;
229
-
230
- // Skip private namespaces
231
- if (propName.startsWith("_")) continue;
232
-
233
- const nsMethods = extractMethodsFromClass(source, className);
234
- if (nsMethods.size > 0) {
235
- namespaced.set(propName, nsMethods);
236
- }
237
- }
238
-
239
- return { root, namespaced, classDoc };
240
- }
241
-
242
- // Discover methods from runtime instance (for imported namespaces)
243
- function discoverRuntimeNamespaces(
244
- instance: any,
245
- discovered: DiscoveredTasks,
246
- ): void {
247
- // Find namespace properties on the instance
248
- for (const propName of Object.getOwnPropertyNames(instance)) {
249
- // Skip private, already discovered, or non-objects
250
- if (propName.startsWith("_")) continue;
251
- if (discovered.namespaced.has(propName)) continue;
252
-
253
- const prop = instance[propName];
254
- if (!prop || typeof prop !== "object" || Array.isArray(prop)) continue;
255
-
256
- // Discover methods from this namespace at runtime
257
- const methods = new Map<string, TaskMeta>();
258
- let proto = Object.getPrototypeOf(prop);
259
-
260
- while (proto && proto !== Object.prototype) {
261
- for (const methodName of Object.getOwnPropertyNames(proto)) {
262
- if (
263
- methodName === "constructor" ||
264
- methodName.startsWith("_") ||
265
- typeof prop[methodName] !== "function"
266
- ) {
267
- continue;
268
- }
269
-
270
- // No type info for imported methods - treat args as strings
271
- if (!methods.has(methodName)) {
272
- methods.set(methodName, { description: "", params: [] });
273
- }
274
- }
275
- proto = Object.getPrototypeOf(proto);
276
- }
277
-
278
- if (methods.size > 0) {
279
- discovered.namespaced.set(propName, methods);
280
- }
281
- }
282
- }
283
-
284
- // Parse TypeScript source to extract method signatures and types (legacy, for compatibility)
285
- async function extractTaskMeta(source: string): Promise<Map<string, TaskMeta>> {
286
- const { root, namespaced } = discoverAllTasks(source);
287
-
288
- // Combine root and namespaced for backward compat
289
- const all = new Map(root);
290
- for (const [ns, methods] of namespaced) {
291
- for (const [method, meta] of methods) {
292
- all.set(method, meta); // This flattens - we'll fix in main()
293
- }
294
- }
295
-
296
- return all;
297
- }
298
-
299
- // Convert CLI arg to typed value
300
- function coerceArg(value: string, type: ParamType): unknown {
301
- switch (type) {
302
- case "number": {
303
- if (value === "") {
304
- throw new Error(`Expected number, got ""`);
305
- }
306
- const n = Number(value);
307
- if (Number.isNaN(n)) {
308
- throw new Error(`Expected number, got "${value}"`);
309
- }
310
- return n;
311
- }
312
- case "boolean":
313
- if (value === "true" || value === "1") return true;
314
- if (value === "false" || value === "0") return false;
315
- throw new Error(`Expected boolean, got "${value}"`);
316
- case "object":
317
- case "array": {
318
- try {
319
- const parsed = JSON.parse(value);
320
- if (type === "array" && !Array.isArray(parsed)) {
321
- throw new Error(`Expected array, got ${typeof parsed}`);
322
- }
323
- if (
324
- type === "object" &&
325
- (typeof parsed !== "object" ||
326
- Array.isArray(parsed) ||
327
- parsed === null)
328
- ) {
329
- throw new Error(
330
- `Expected object, got ${Array.isArray(parsed) ? "array" : typeof parsed}`,
331
- );
332
- }
333
- return parsed;
334
- } catch (e) {
335
- if (e instanceof SyntaxError) {
336
- throw new Error(`Invalid JSON: ${e.message}`);
337
- }
338
- throw e;
339
- }
340
- }
341
- case "string":
342
- default:
343
- return value;
344
- }
345
- }
346
-
347
- // Parse CLI arguments into flags and positional args
348
- function parseCliArgs(args: string[]): ParsedArgs {
349
- const positional: string[] = [];
350
- const flags = new Map<string, string | boolean>();
351
- let stopFlagParsing = false;
352
-
353
- for (let i = 0; i < args.length; i++) {
354
- const arg = args[i];
355
-
356
- if (stopFlagParsing) {
357
- positional.push(arg);
358
- continue;
359
- }
360
-
361
- if (arg === "--") {
362
- stopFlagParsing = true;
363
- continue;
364
- }
365
-
366
- // --flag=value
367
- if (arg.startsWith("--") && arg.includes("=")) {
368
- const eqIdx = arg.indexOf("=");
369
- const name = arg.slice(2, eqIdx);
370
- const value = arg.slice(eqIdx + 1);
371
- flags.set(name, value);
372
- continue;
373
- }
374
-
375
- // --no-flag (boolean negation)
376
- if (arg.startsWith("--no-")) {
377
- const name = arg.slice(5);
378
- flags.set(name, false);
379
- continue;
380
- }
381
-
382
- // --flag (may be boolean or need next arg)
383
- if (arg.startsWith("--")) {
384
- const name = arg.slice(2);
385
- const nextArg = args[i + 1];
386
-
387
- // If next arg exists and doesn't look like a flag, use it as value
388
- if (nextArg !== undefined && !nextArg.startsWith("-")) {
389
- flags.set(name, nextArg);
390
- i++; // Skip next arg
391
- } else {
392
- flags.set(name, true); // Boolean flag
393
- }
394
- continue;
395
- }
396
-
397
- // -f=value (short with equals)
398
- if (arg.startsWith("-") && arg.length > 2 && arg.includes("=")) {
399
- const eqIdx = arg.indexOf("=");
400
- const name = arg.slice(1, eqIdx);
401
- const value = arg.slice(eqIdx + 1);
402
- flags.set(name, value);
403
- continue;
404
- }
405
-
406
- // -f value or -f (boolean)
407
- if (arg.startsWith("-") && arg.length === 2) {
408
- const name = arg.slice(1);
409
- const nextArg = args[i + 1];
410
-
411
- if (nextArg !== undefined && !nextArg.startsWith("-")) {
412
- flags.set(name, nextArg);
413
- i++;
414
- } else {
415
- flags.set(name, true);
416
- }
417
- continue;
418
- }
419
-
420
- // Positional argument
421
- positional.push(arg);
422
- }
423
-
424
- return { positional, flags };
425
- }
426
-
427
- // Resolve arguments from parsed CLI args using param metadata
428
- function resolveArgs(params: ParamMeta[], parsed: ParsedArgs): unknown[] {
429
- const result: unknown[] = [];
430
- const usedPositional = new Set<number>();
431
-
432
- for (const param of params) {
433
- // Handle rest parameters - collect all remaining positional args
434
- if (param.isRest) {
435
- const remaining = parsed.positional.filter(
436
- (_, i) => !usedPositional.has(i),
437
- );
438
- result.push(...remaining);
439
- break;
440
- }
441
-
442
- let value: string | boolean | undefined;
443
-
444
- // Try to get value from flags first
445
- if (param.flag) {
446
- // Check long flag (without --)
447
- const longName = param.flag.long.slice(2);
448
- if (parsed.flags.has(longName)) {
449
- value = parsed.flags.get(longName);
450
- }
451
- // Check short flag (without -)
452
- else if (param.flag.short) {
453
- const shortName = param.flag.short.slice(1);
454
- if (parsed.flags.has(shortName)) {
455
- value = parsed.flags.get(shortName);
456
- }
457
- }
458
- // Check aliases
459
- if (value === undefined && param.flag.aliases) {
460
- for (const alias of param.flag.aliases) {
461
- const aliasName = alias.slice(2);
462
- if (parsed.flags.has(aliasName)) {
463
- value = parsed.flags.get(aliasName);
464
- break;
465
- }
466
- }
467
- }
468
- }
469
-
470
- // Fall back to positional if no flag found
471
- if (value === undefined) {
472
- for (let i = 0; i < parsed.positional.length; i++) {
473
- if (!usedPositional.has(i)) {
474
- value = parsed.positional[i];
475
- usedPositional.add(i);
476
- break;
477
- }
478
- }
479
- }
480
-
481
- // Handle missing values
482
- if (value === undefined) {
483
- if (param.required) {
484
- throw new Error(
485
- `Missing required argument: <${param.name}> (${param.type})`,
486
- );
487
- }
488
- break; // Optional param not provided, stop processing
489
- }
490
-
491
- // Coerce and add to result
492
- // Boolean flags that are already boolean don't need coercion
493
- if (typeof value === "boolean" && param.type === "boolean") {
494
- result.push(value);
495
- } else {
496
- result.push(coerceArg(String(value), param.type));
497
- }
498
- }
499
-
500
- return result;
501
- }
502
-
503
- // Format param for help display
504
- function formatParam(param: ParamMeta): string {
505
- if (param.isRest) {
506
- return `[${param.name}...]`;
507
- }
508
- return param.required ? `<${param.name}>` : `[${param.name}]`;
509
- }
510
-
511
- // Format flag info for display
512
- function formatFlagInfo(param: ParamMeta): string {
513
- if (!param.flag || param.isRest) return "";
514
-
515
- const parts: string[] = [param.flag.long];
516
- if (param.flag.short) {
517
- parts.push(param.flag.short);
518
- }
519
- if (param.flag.aliases) {
520
- parts.push(...param.flag.aliases);
521
- }
522
- return parts.join(", ");
523
- }
524
-
525
- // Display help for a specific task
526
- function showTaskHelp(command: string, meta: TaskMeta): void {
527
- const paramStr = meta.params.map(formatParam).join(" ");
528
- const signature = paramStr ? `${command} ${paramStr}` : command;
529
-
530
- console.log(`Usage: invt ${signature}\n`);
531
-
532
- if (meta.description) {
533
- console.log(`${meta.description}\n`);
534
- }
535
-
536
- if (meta.params.length > 0) {
537
- console.log("Arguments:");
538
- for (const param of meta.params) {
539
- const reqStr = param.required ? "(required)" : "(optional)";
540
- const typeStr = param.isRest ? `${param.type}...` : param.type;
541
- const flagStr = formatFlagInfo(param);
542
- const flagDisplay = flagStr ? ` ${flagStr}` : "";
543
- console.log(
544
- ` ${param.name.padEnd(15)} ${typeStr.padEnd(10)} ${reqStr}${flagDisplay}`,
545
- );
546
- }
547
- }
548
- }
3
+ import {
4
+ discoverAllTasks,
5
+ discoverRuntimeNamespaces,
6
+ parseCommand,
7
+ parseCliArgs,
8
+ resolveArgs,
9
+ formatParam,
10
+ printTaskList,
11
+ showTaskHelp,
12
+ } from "./parser";
549
13
 
550
14
  // Main CLI entry point
551
15
  async function main() {
@@ -602,26 +66,7 @@ export class Tasks {
602
66
  }
603
67
 
604
68
  console.log("Available tasks:\n");
605
-
606
- // Root tasks
607
- for (const [name, meta] of discovered.root) {
608
- const paramStr = meta.params.map(formatParam).join(" ");
609
- const signature = paramStr ? `${name} ${paramStr}` : name;
610
- console.log(` ${signature}`);
611
- }
612
-
613
- // Namespaced tasks
614
- for (const [ns, methods] of discovered.namespaced) {
615
- console.log(`\n${ns}:`);
616
- for (const [name, meta] of methods) {
617
- const paramStr = meta.params.map(formatParam).join(" ");
618
- const signature = paramStr
619
- ? `${ns}:${name} ${paramStr}`
620
- : `${ns}:${name}`;
621
- console.log(` ${signature}`);
622
- }
623
- }
624
-
69
+ printTaskList(discovered);
625
70
  console.log("\nUsage: invt <task> [args...]");
626
71
  console.log(" invt <task> -h Show help for a specific task");
627
72
  return;
@@ -630,25 +75,7 @@ export class Tasks {
630
75
  // List flag
631
76
  if (args[0] === "-l" || args[0] === "--list") {
632
77
  console.log("Available tasks:\n");
633
-
634
- // Root tasks
635
- for (const [name, meta] of discovered.root) {
636
- const paramStr = meta.params.map(formatParam).join(" ");
637
- const signature = paramStr ? `${name} ${paramStr}` : name;
638
- console.log(` ${signature}`);
639
- }
640
-
641
- // Namespaced tasks
642
- for (const [ns, methods] of discovered.namespaced) {
643
- console.log(`\n${ns}:`);
644
- for (const [name, meta] of methods) {
645
- const paramStr = meta.params.map(formatParam).join(" ");
646
- const signature = paramStr
647
- ? `${ns}:${name} ${paramStr}`
648
- : `${ns}:${name}`;
649
- console.log(` ${signature}`);
650
- }
651
- }
78
+ printTaskList(discovered);
652
79
  return;
653
80
  }
654
81
 
@@ -660,7 +87,7 @@ export class Tasks {
660
87
 
661
88
  const { namespace, method: methodName } = parseCommand(command);
662
89
 
663
- let meta: TaskMeta | undefined;
90
+ let meta;
664
91
  let method: Function | undefined;
665
92
  let thisArg: any = instance;
666
93
 
package/src/context.ts CHANGED
@@ -17,6 +17,16 @@ export interface RunOptions {
17
17
  cwd?: string;
18
18
  }
19
19
 
20
+ export class CommandError extends Error {
21
+ result: RunResult;
22
+
23
+ constructor(message: string, result: RunResult) {
24
+ super(message);
25
+ this.name = "CommandError";
26
+ this.result = result;
27
+ }
28
+ }
29
+
20
30
  export class Context {
21
31
  cwd: string;
22
32
  private options: RunOptions;
@@ -70,11 +80,10 @@ export class Context {
70
80
  };
71
81
 
72
82
  if (!opts.warn && runResult.failed) {
73
- const error = new Error(
83
+ throw new CommandError(
74
84
  `Command failed with exit code ${runResult.code}: ${command}`,
85
+ runResult,
75
86
  );
76
- (error as any).result = runResult;
77
- throw error;
78
87
  }
79
88
 
80
89
  // When streaming, output already went to terminal; otherwise write captured output