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