@kirrosh/zond 0.20.0 → 0.22.0

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +110 -3
  2. package/README.md +26 -15
  3. package/package.json +10 -6
  4. package/src/cli/commands/catalog.ts +62 -0
  5. package/src/cli/commands/ci-init.ts +12 -6
  6. package/src/cli/commands/completions.ts +176 -0
  7. package/src/cli/commands/db.ts +2 -1
  8. package/src/cli/commands/generate.ts +18 -2
  9. package/src/cli/commands/init/agents-md.ts +61 -0
  10. package/src/cli/commands/init/bootstrap.ts +79 -0
  11. package/src/cli/commands/init/skills.ts +45 -0
  12. package/src/cli/commands/init/templates/agents.md +73 -0
  13. package/src/cli/commands/init/templates/markdown.d.ts +4 -0
  14. package/src/cli/commands/init/templates/skills/scenarios.md +97 -0
  15. package/src/cli/commands/init/templates/skills/zond.md +184 -0
  16. package/src/cli/commands/init/templates/zond-config.yml +15 -0
  17. package/src/cli/commands/init.ts +124 -31
  18. package/src/cli/commands/probe-methods.ts +108 -0
  19. package/src/cli/commands/probe-validation.ts +124 -0
  20. package/src/cli/commands/run.ts +99 -10
  21. package/src/cli/commands/serve.ts +52 -19
  22. package/src/cli/commands/sync.ts +28 -1
  23. package/src/cli/commands/update.ts +1 -1
  24. package/src/cli/commands/use.ts +57 -0
  25. package/src/cli/index.ts +21 -591
  26. package/src/cli/program.ts +655 -0
  27. package/src/cli/version.ts +3 -0
  28. package/src/core/context/current.ts +35 -0
  29. package/src/core/diagnostics/db-analysis.ts +11 -2
  30. package/src/core/diagnostics/render-md.ts +112 -0
  31. package/src/core/generator/catalog-builder.ts +179 -0
  32. package/src/core/generator/chunker.ts +14 -2
  33. package/src/core/generator/data-factory.ts +50 -19
  34. package/src/core/generator/guide-builder.ts +1 -1
  35. package/src/core/generator/index.ts +2 -0
  36. package/src/core/generator/openapi-reader.ts +18 -0
  37. package/src/core/generator/serializer.ts +11 -2
  38. package/src/core/generator/suite-generator.ts +106 -7
  39. package/src/core/meta/types.ts +0 -2
  40. package/src/core/parser/schema.ts +3 -1
  41. package/src/core/parser/types.ts +10 -1
  42. package/src/core/parser/variables.ts +90 -2
  43. package/src/core/parser/yaml-parser.ts +50 -1
  44. package/src/core/probe/method-probe.ts +197 -0
  45. package/src/core/probe/negative-probe.ts +657 -0
  46. package/src/core/reporter/console.ts +29 -3
  47. package/src/core/reporter/index.ts +2 -2
  48. package/src/core/reporter/json.ts +5 -2
  49. package/src/core/runner/assertions.ts +4 -1
  50. package/src/core/runner/executor.ts +132 -37
  51. package/src/core/runner/http-client.ts +40 -5
  52. package/src/core/runner/rate-limiter.ts +131 -0
  53. package/src/core/setup-api.ts +4 -1
  54. package/src/core/workspace/root.ts +94 -0
  55. package/src/db/schema.ts +4 -1
  56. package/src/web/routes/api.ts +80 -0
  57. package/src/web/routes/dashboard.ts +15 -0
  58. package/src/web/static/style.css +290 -0
  59. package/src/web/views/explorer-tab.ts +402 -0
package/src/cli/index.ts CHANGED
@@ -1,608 +1,38 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { runCommand } from "./commands/run.ts";
4
- import { validateCommand } from "./commands/validate.ts";
5
- import { serveCommand } from "./commands/serve.ts";
6
- import { coverageCommand } from "./commands/coverage.ts";
7
- import { ciInitCommand } from "./commands/ci-init.ts";
8
- import { initCommand } from "./commands/init.ts";
9
- import { describeCommand } from "./commands/describe.ts";
10
- import { dbCommand } from "./commands/db.ts";
11
- import { requestCommand } from "./commands/request.ts";
12
- import { guideCommand } from "./commands/guide.ts";
13
- import { generateCommand } from "./commands/generate.ts";
14
- import { exportCommand } from "./commands/export.ts";
15
- import { syncCommand } from "./commands/sync.ts";
16
- import { updateCommand } from "./commands/update.ts";
3
+ import { CommanderError } from "commander";
4
+ import { buildProgram, preprocessArgv } from "./program.ts";
17
5
  import { printError } from "./output.ts";
18
- import { getRuntimeInfo } from "./runtime.ts";
19
- import { getDb } from "../db/schema.ts";
20
- import { findCollectionByNameOrId } from "../db/queries.ts";
21
- import type { ReporterName } from "../core/reporter/types.ts";
6
+ import { VERSION } from "./version.ts";
22
7
 
23
- import { version as pkgVersion } from "../../package.json";
24
- export const VERSION = pkgVersion;
8
+ export { VERSION };
25
9
 
26
- export interface ParsedArgs {
27
- command: string | undefined;
28
- positional: string[];
29
- flags: Record<string, string | boolean>;
30
- }
31
-
32
- /**
33
- * Strip MSYS/Git Bash automatic path conversion.
34
- * Git Bash on Windows converts "/foo" → "C:/Program Files/Git/foo".
35
- * Detect and reverse this for flags that expect API paths (e.g. --path /users).
36
- */
37
- const MSYS_PREFIX_RE = /^[A-Z]:[\\/](?:Program Files[\\/]Git|msys64|usr)[\\/]/i;
38
-
39
- function stripMsysPath(value: string): string {
40
- if (!MSYS_PREFIX_RE.test(value)) return value;
41
- // Extract the original path: "C:/Program Files/Git/products" → "/products"
42
- const stripped = value.replace(MSYS_PREFIX_RE, "/");
43
- return stripped;
44
- }
45
-
46
- /** Flags whose values are API paths, not filesystem paths — subject to MSYS fix */
47
- const API_PATH_FLAGS = new Set(["path", "json-path"]);
48
-
49
- export function parseArgs(argv: string[]): ParsedArgs {
50
- // argv: [bunPath, scriptPath, ...userArgs]
51
- const args = argv.slice(2);
52
- let command: string | undefined;
53
- const positional: string[] = [];
54
- const flags: Record<string, string | boolean> = {};
55
-
56
- let i = 0;
57
- while (i < args.length) {
58
- const arg = args[i]!;
59
-
60
- if (arg.startsWith("--")) {
61
- const eqIndex = arg.indexOf("=");
62
- if (eqIndex !== -1) {
63
- // --flag=value
64
- const key = arg.slice(2, eqIndex);
65
- let val = arg.slice(eqIndex + 1);
66
- if (API_PATH_FLAGS.has(key)) val = stripMsysPath(val);
67
- flags[key] = val;
68
- } else {
69
- const key = arg.slice(2);
70
- const next = args[i + 1];
71
- if (next !== undefined && !next.startsWith("-")) {
72
- flags[key] = API_PATH_FLAGS.has(key) ? stripMsysPath(next) : next;
73
- i++;
74
- } else {
75
- flags[key] = true;
76
- }
77
- }
78
- } else if (arg.startsWith("-") && arg.length === 2) {
79
- // Short flag: -h, -v
80
- flags[arg.slice(1)] = true;
81
- } else if (command === undefined) {
82
- command = arg;
83
- } else {
84
- positional.push(arg);
85
- }
86
-
87
- i++;
88
- }
89
-
90
- return { command, positional, flags };
91
- }
92
-
93
- function printUsage(): void {
94
- console.log(`zond - API Testing Platform
95
-
96
- Usage:
97
- zond run <path> Run API tests
98
- zond validate <path> Validate test files without running
99
- zond coverage Analyze API test coverage
100
- zond init Register a new API for testing
101
- zond describe <spec> Describe endpoints from OpenAPI spec
102
- zond db <subcommand> Query the test database
103
- zond request <method> <url> Send an ad-hoc HTTP request
104
- zond generate <spec> Generate test suites from OpenAPI spec
105
- zond guide <spec> Generate test generation guide from OpenAPI spec
106
- zond serve Start web dashboard
107
- zond ui Alias for 'serve --open' (start dashboard & open browser)
108
- zond ci init Generate CI/CD workflow (GitHub Actions, GitLab CI)
109
- zond export postman <path> Export YAML tests as Postman Collection v2.1
110
- zond sync <spec> Detect new/removed endpoints and generate tests for new ones
111
- zond update Check for updates and self-update the binary
112
-
113
- Options for 'run':
114
- --dry-run Show requests without sending them (exit code always 0)
115
- --env-var KEY=VALUE Inject env variable (repeatable, overrides env file)
116
- --api <name> Use API collection (resolves test path automatically)
117
- --env <name> Use environment file (.env.<name>.yaml)
118
- --report <format> Output format: console, json, junit (default: console)
119
- --timeout <ms> Override request timeout
120
- --bail Stop on first suite failure
121
- --no-db Do not save results to zond.db
122
- --db <path> Path to SQLite database file (default: zond.db)
123
- --auth-token <token> Auth token injected as {{auth_token}} variable
124
- --safe Run only GET tests (read-only, safe mode)
125
- --tag <tag> Filter suites by tag (repeatable, comma-separated, OR logic)
126
- --exclude-tag <tag> Exclude suites by tag (repeatable, comma-separated)
127
- --method <method> Filter tests by HTTP method (e.g. GET, POST)
128
-
129
- Options for 'init':
130
- --name <name> API name (auto-detected from spec title if omitted)
131
- --spec <path> Path to OpenAPI spec file
132
- --base-url <url> Override base URL
133
- --force Overwrite existing API collection
134
-
135
- Options for 'describe':
136
- --compact List all endpoints briefly
137
- --list-params List all unique parameters across all endpoints
138
- --method <method> HTTP method for single endpoint detail
139
- --path <path> Endpoint path for single endpoint detail
140
-
141
- Options for 'db':
142
- zond db collections List all API collections
143
- zond db runs [--limit N] List recent test runs
144
- zond db run <id> [--verbose] Show run details (--method GET, --status 403 to filter)
145
- zond db diagnose <id> Diagnose run failures (--limit N examples per group, --verbose for all)
146
- zond db compare <idA> <idB> Compare two runs
147
-
148
- Options for 'request':
149
- --header <H> Request header "Name: Value" (repeatable)
150
- --body <json> Request body (JSON string)
151
- --env <name> Environment for variable interpolation
152
- --api <name> Collection name (loads env from its directory)
153
- --json-path <path> Extract value from response (dot notation)
154
-
155
- Options for 'generate':
156
- --output <dir> Output directory for generated test files (required)
157
- --tag <tag> Generate only for endpoints with this tag
158
- --uncovered-only Skip endpoints already covered by existing tests
159
-
160
- Options for 'guide':
161
- --tests-dir <dir> Filter to uncovered endpoints only
162
- --tag <tag> Generate only for endpoints with this tag
163
-
164
- Options for 'coverage':
165
- --api <name> Use API collection (auto-resolves spec and tests dir)
166
- --spec <path> Path to OpenAPI spec (required unless --api used)
167
- --tests <dir> Path to test files directory (required unless --api used)
168
- --fail-on-coverage N Exit 1 when coverage percentage is below N (0–100)
169
- --run-id <number> Cross-reference with a test run for pass/fail/5xx breakdown
170
-
171
- Options for 'serve' / 'ui':
172
- --port <port> Server port (default: 8080)
173
- --host <host> Server host (default: 0.0.0.0)
174
- --db <path> Path to SQLite database file (default: zond.db)
175
- --open Open dashboard in browser after starting
176
- --watch Enable dev mode with hot reload (auto-refresh browser on file changes)
177
-
178
- Options for 'ci init':
179
- --github Generate GitHub Actions workflow
180
- --gitlab Generate GitLab CI config
181
- --dir <path> Project root directory (default: current directory)
182
- --force Overwrite existing CI config
183
-
184
- Options for 'export postman':
185
- --output <file> Output file path (default: collection.postman.json)
186
- --env <file> Also export .env.yaml as Postman environment
187
- --collection-name <name> Collection name (default: derived from path)
188
-
189
- Options for 'sync':
190
- --tests <dir> Path to test files directory (required)
191
- --dry-run Show what would be generated without writing files
192
- --tag <tag> Limit sync to endpoints with this tag
193
-
194
- Options for 'update':
195
- --check Only check for updates, do not download
196
-
197
- General:
198
- --json Output in JSON envelope format (available for all commands)
199
- --help, -h Show this help
200
- --version, -v Show version`);
201
- }
202
-
203
- const VALID_REPORTERS = new Set<string>(["console", "json", "junit"]);
204
-
205
- async function main(): Promise<number> {
206
- const { command, positional, flags } = parseArgs(process.argv);
207
- const jsonFlag = flags["json"] === true;
208
-
209
- // Help
210
- if (command === "help" || command === "--help" || flags["help"] === true || flags["h"] === true) {
211
- printUsage();
212
- return 0;
213
- }
214
-
215
- // Version
216
- if (command === "--version" || flags["version"] === true || flags["v"] === true) {
217
- console.log(`zond ${VERSION} (${getRuntimeInfo()})`);
218
- return 0;
219
- }
220
-
221
- if (!command) {
222
- printUsage();
223
- return 0;
224
- }
225
-
226
- switch (command) {
227
- case "run": {
228
- let path = positional[0];
229
- const apiFlag = typeof flags["api"] === "string" ? flags["api"] : undefined;
230
- if (!path && apiFlag) {
231
- try {
232
- getDb(typeof flags["db"] === "string" ? flags["db"] : undefined);
233
- const col = findCollectionByNameOrId(apiFlag);
234
- if (!col) { printError(`API '${apiFlag}' not found`); return 1; }
235
- path = col.test_path;
236
- } catch (err) {
237
- printError(`Failed to resolve --api: ${(err as Error).message}`);
238
- return 2;
239
- }
240
- }
241
- if (!path) {
242
- printError("Missing path argument. Usage: zond run <path> or zond run --api <name>");
243
- return 2;
244
- }
245
-
246
- const report = (flags["report"] as string) ?? "console";
247
- if (!VALID_REPORTERS.has(report)) {
248
- printError(`Unknown reporter: ${report}. Available: console, json, junit`);
249
- return 2;
250
- }
251
-
252
- const timeoutRaw = flags["timeout"];
253
- let timeout: number | undefined;
254
- if (typeof timeoutRaw === "string") {
255
- timeout = parseInt(timeoutRaw, 10);
256
- if (isNaN(timeout) || timeout <= 0) {
257
- printError(`Invalid timeout value: ${timeoutRaw}`);
258
- return 2;
259
- }
260
- }
261
-
262
- // Collect all --tag, --exclude-tag, and --env-var flags (parseArgs only stores last one, so re-parse)
263
- const tagValues: string[] = [];
264
- const excludeTagValues: string[] = [];
265
- const envVarValues: string[] = [];
266
- const rawRunArgs = process.argv.slice(2);
267
- for (let i = 0; i < rawRunArgs.length; i++) {
268
- const arg = rawRunArgs[i]!;
269
- if (arg === "--tag" && rawRunArgs[i + 1]) {
270
- tagValues.push(rawRunArgs[i + 1]!);
271
- i++;
272
- } else if (arg.startsWith("--tag=")) {
273
- tagValues.push(arg.slice("--tag=".length));
274
- } else if (arg === "--exclude-tag" && rawRunArgs[i + 1]) {
275
- excludeTagValues.push(rawRunArgs[i + 1]!);
276
- i++;
277
- } else if (arg.startsWith("--exclude-tag=")) {
278
- excludeTagValues.push(arg.slice("--exclude-tag=".length));
279
- } else if (arg === "--env-var" && rawRunArgs[i + 1]) {
280
- envVarValues.push(rawRunArgs[i + 1]!);
281
- i++;
282
- } else if (arg.startsWith("--env-var=")) {
283
- envVarValues.push(arg.slice("--env-var=".length));
284
- }
285
- }
286
- // Support comma-separated: --tag smoke,crud → ["smoke", "crud"]
287
- const tags = tagValues.flatMap(v => v.split(",")).filter(Boolean);
288
- const excludeTags = excludeTagValues.flatMap(v => v.split(",")).filter(Boolean);
289
-
290
- return runCommand({
291
- path,
292
- env: typeof flags["env"] === "string" ? flags["env"] : undefined,
293
- report: report as ReporterName,
294
- timeout,
295
- bail: flags["bail"] === true,
296
- noDb: flags["no-db"] === true,
297
- dbPath: typeof flags["db"] === "string" ? flags["db"] : undefined,
298
- authToken: typeof flags["auth-token"] === "string" ? flags["auth-token"] : undefined,
299
- safe: flags["safe"] === true,
300
- tag: tags.length > 0 ? tags : undefined,
301
- excludeTag: excludeTags.length > 0 ? excludeTags : undefined,
302
- method: typeof flags["method"] === "string" ? flags["method"] : undefined,
303
- envVars: envVarValues.length > 0 ? envVarValues : undefined,
304
- dryRun: flags["dry-run"] === true,
305
- json: jsonFlag,
306
- });
307
- }
308
-
309
- case "validate": {
310
- const path = positional[0];
311
- if (!path) {
312
- printError("Missing path argument. Usage: zond validate <path>");
313
- return 2;
314
- }
315
-
316
- return validateCommand({ path, json: jsonFlag });
317
- }
318
-
319
- case "ui":
320
- case "serve": {
321
- const portRaw = flags["port"];
322
- let port: number | undefined;
323
- if (typeof portRaw === "string") {
324
- port = parseInt(portRaw, 10);
325
- if (isNaN(port) || port <= 0) {
326
- printError(`Invalid port value: ${portRaw}`);
327
- return 2;
328
- }
329
- }
330
- return serveCommand({
331
- port,
332
- host: typeof flags["host"] === "string" ? flags["host"] : undefined,
333
- dbPath: typeof flags["db"] === "string" ? flags["db"] : undefined,
334
- watch: flags["watch"] === true,
335
- open: command === "ui" || flags["open"] === true,
336
- });
337
- }
338
-
339
- case "ci": {
340
- const ciSub = positional[0];
341
- if (ciSub !== "init") {
342
- printError("Usage: zond ci init [--github|--gitlab] [--force]");
343
- return 2;
344
- }
345
- let platform: "github" | "gitlab" | undefined;
346
- if (flags["github"] === true) platform = "github";
347
- else if (flags["gitlab"] === true) platform = "gitlab";
348
- return ciInitCommand({
349
- platform,
350
- force: flags["force"] === true,
351
- dir: typeof flags["dir"] === "string" ? flags["dir"] : undefined,
352
- json: jsonFlag,
353
- });
354
- }
355
-
356
- case "coverage": {
357
- let spec = flags["spec"] as string | undefined;
358
- let tests = flags["tests"] as string | undefined;
359
- const coverageApiFlag = typeof flags["api"] === "string" ? flags["api"] : undefined;
360
-
361
- if (coverageApiFlag) {
362
- try {
363
- getDb(typeof flags["db"] === "string" ? flags["db"] : undefined);
364
- const col = findCollectionByNameOrId(coverageApiFlag);
365
- if (!col) { printError(`API '${coverageApiFlag}' not found`); return 1; }
366
- if (!spec && col.openapi_spec) spec = col.openapi_spec;
367
- if (!tests && col.test_path) tests = col.test_path;
368
- } catch (err) {
369
- printError(`Failed to resolve --api: ${(err as Error).message}`);
370
- return 2;
371
- }
372
- }
373
-
374
- if (typeof spec !== "string") {
375
- printError("Missing --spec <path>. Usage: zond coverage --spec <path> --tests <dir>");
376
- return 2;
377
- }
378
- if (typeof tests !== "string") {
379
- printError("Missing --tests <dir>. Usage: zond coverage --spec <path> --tests <dir>");
380
- return 2;
381
- }
382
- const failOnCoverageRaw = flags["fail-on-coverage"];
383
- let failOnCoverage: number | undefined;
384
- if (typeof failOnCoverageRaw === "string") {
385
- failOnCoverage = parseInt(failOnCoverageRaw, 10);
386
- if (isNaN(failOnCoverage) || failOnCoverage < 0 || failOnCoverage > 100) {
387
- printError(`Invalid --fail-on-coverage value: ${failOnCoverageRaw} (must be 0–100)`);
388
- return 2;
389
- }
390
- }
391
- const runIdRaw = flags["run-id"];
392
- let runId: number | undefined;
393
- if (typeof runIdRaw === "string") {
394
- runId = parseInt(runIdRaw, 10);
395
- if (isNaN(runId)) {
396
- printError(`Invalid --run-id value: ${runIdRaw} (must be a number)`);
397
- return 2;
398
- }
399
- }
400
- return coverageCommand({ spec, tests, failOnCoverage, runId, json: jsonFlag });
401
- }
402
-
403
- case "init": {
404
- return initCommand({
405
- name: typeof flags["name"] === "string" ? flags["name"] : undefined,
406
- spec: typeof flags["spec"] === "string" ? flags["spec"] : positional[0],
407
- baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : undefined,
408
- dir: typeof flags["dir"] === "string" ? flags["dir"] : undefined,
409
- force: flags["force"] === true,
410
- insecure: flags["insecure"] === true,
411
- dbPath: typeof flags["db"] === "string" ? flags["db"] : undefined,
412
- json: jsonFlag,
413
- });
414
- }
415
-
416
- case "describe": {
417
- const specPath = positional[0];
418
- if (!specPath) {
419
- printError("Missing spec path. Usage: zond describe <spec> [--compact | --method <M> --path <P>]");
420
- return 2;
421
- }
422
- return describeCommand({
423
- specPath,
424
- compact: flags["compact"] === true,
425
- listParams: flags["list-params"] === true,
426
- method: typeof flags["method"] === "string" ? flags["method"] : undefined,
427
- path: typeof flags["path"] === "string" ? flags["path"] : undefined,
428
- json: jsonFlag,
429
- });
430
- }
431
-
432
- case "db": {
433
- const dbSub = positional[0];
434
- if (!dbSub) {
435
- printError("Missing subcommand. Usage: zond db <collections|runs|run|diagnose|compare> [args]");
436
- return 2;
437
- }
438
- const limitRaw = flags["limit"];
439
- let limit: number | undefined;
440
- if (typeof limitRaw === "string") {
441
- limit = parseInt(limitRaw, 10);
442
- if (isNaN(limit) || limit <= 0) limit = undefined;
443
- }
444
- const statusRaw = flags["status"];
445
- let statusFilter: number | undefined;
446
- if (typeof statusRaw === "string") {
447
- statusFilter = parseInt(statusRaw, 10);
448
- if (isNaN(statusFilter)) statusFilter = undefined;
449
- }
450
-
451
- return dbCommand({
452
- subcommand: dbSub,
453
- positional: positional.slice(1),
454
- limit,
455
- verbose: flags["verbose"] === true,
456
- dbPath: typeof flags["db"] === "string" ? flags["db"] : undefined,
457
- json: jsonFlag,
458
- method: typeof flags["method"] === "string" ? flags["method"] : undefined,
459
- status: statusFilter,
460
- });
461
- }
462
-
463
- case "request": {
464
- const method = positional[0];
465
- const url = positional[1];
466
- if (!method || !url) {
467
- printError("Missing arguments. Usage: zond request <METHOD> <URL> [--header H] [--body JSON]");
468
- return 2;
469
- }
470
- // Collect all --header flags
471
- const headerValues: string[] = [];
472
- const rawArgs = process.argv.slice(2);
473
- for (let i = 0; i < rawArgs.length; i++) {
474
- const arg = rawArgs[i]!;
475
- if (arg === "--header" && rawArgs[i + 1]) {
476
- headerValues.push(rawArgs[i + 1]!);
477
- i++;
478
- } else if (arg.startsWith("--header=")) {
479
- headerValues.push(arg.slice("--header=".length));
480
- }
481
- }
482
-
483
- const timeoutRaw = flags["timeout"];
484
- let timeout: number | undefined;
485
- if (typeof timeoutRaw === "string") {
486
- timeout = parseInt(timeoutRaw, 10);
487
- if (isNaN(timeout) || timeout <= 0) timeout = undefined;
488
- }
489
-
490
- return requestCommand({
491
- method,
492
- url,
493
- headers: headerValues.length > 0 ? headerValues : undefined,
494
- body: typeof flags["body"] === "string" ? flags["body"] : undefined,
495
- timeout,
496
- env: typeof flags["env"] === "string" ? flags["env"] : undefined,
497
- api: typeof flags["api"] === "string" ? flags["api"] : undefined,
498
- jsonPath: typeof flags["json-path"] === "string" ? flags["json-path"] : undefined,
499
- dbPath: typeof flags["db"] === "string" ? flags["db"] : undefined,
500
- json: jsonFlag,
501
- });
502
- }
503
-
504
- case "generate": {
505
- const specPath = positional[0];
506
- if (!specPath) {
507
- printError("Missing spec path. Usage: zond generate <spec> --output <dir> [--tag <tag>] [--uncovered-only] [--json]");
508
- return 2;
509
- }
510
- const output = typeof flags["output"] === "string" ? flags["output"] : undefined;
511
- if (!output) {
512
- printError("Missing --output <dir>. Usage: zond generate <spec> --output <dir>");
513
- return 2;
514
- }
515
- return generateCommand({
516
- specPath,
517
- output,
518
- tag: typeof flags["tag"] === "string" ? flags["tag"] : undefined,
519
- uncoveredOnly: flags["uncovered-only"] === true,
520
- json: jsonFlag,
521
- });
522
- }
523
-
524
- case "guide": {
525
- const specPath = positional[0];
526
- if (!specPath) {
527
- printError("Missing spec path. Usage: zond guide <spec> [--tests-dir <dir>] [--tag <tag>]");
528
- return 2;
529
- }
530
- return guideCommand({
531
- specPath,
532
- testsDir: typeof flags["tests-dir"] === "string" ? flags["tests-dir"] : undefined,
533
- tag: typeof flags["tag"] === "string" ? flags["tag"] : undefined,
534
- json: jsonFlag,
535
- });
536
- }
537
-
538
- case "export": {
539
- const subcommand = positional[0];
540
- if (subcommand !== "postman") {
541
- printError(`Unknown export subcommand: ${subcommand ?? "(none)"}. Usage: zond export postman <path>`);
542
- return 2;
543
- }
544
- const testsPath = positional[1];
545
- if (!testsPath) {
546
- printError("Missing tests path. Usage: zond export postman <path> [--output <file>]");
547
- return 2;
548
- }
549
- return exportCommand({
550
- testsPath,
551
- output: typeof flags["output"] === "string" ? flags["output"] : "collection.postman.json",
552
- env: typeof flags["env"] === "string" ? flags["env"] : undefined,
553
- collectionName: typeof flags["collection-name"] === "string" ? flags["collection-name"] : undefined,
554
- json: jsonFlag,
555
- });
556
- }
557
-
558
- case "update":
559
- case "self-update": {
560
- return updateCommand({
561
- check: flags["check"] === true,
562
- json: jsonFlag,
563
- });
564
- }
565
-
566
- case "sync": {
567
- const specPath = positional[0];
568
- if (!specPath) {
569
- printError("Missing spec path. Usage: zond sync <spec> --tests <dir> [--dry-run] [--tag <tag>]");
570
- return 2;
571
- }
572
- const testsDir = typeof flags["tests"] === "string" ? flags["tests"] : undefined;
573
- if (!testsDir) {
574
- printError("Missing --tests <dir>. Usage: zond sync <spec> --tests <dir>");
575
- return 2;
10
+ async function main(): Promise<void> {
11
+ const program = buildProgram();
12
+ try {
13
+ await program.parseAsync(preprocessArgv(process.argv));
14
+ } catch (err) {
15
+ if (err instanceof CommanderError) {
16
+ // Help/version — commander prints content itself, exit 0
17
+ if (err.code === "commander.helpDisplayed" || err.code === "commander.version" || err.code === "commander.help") {
18
+ process.exitCode = 0;
19
+ return;
576
20
  }
577
- return syncCommand({
578
- specPath,
579
- testsDir,
580
- dryRun: flags["dry-run"] === true,
581
- tag: typeof flags["tag"] === "string" ? flags["tag"] : undefined,
582
- json: jsonFlag,
583
- });
584
- }
585
-
586
- default: {
587
- printError(`Unknown command: ${command}`);
588
- printUsage();
589
- return 2;
21
+ // Unknown command / unknown option / missing argument — exit 2 (already printed by commander/showHelpAfterError)
22
+ process.exitCode = 2;
23
+ return;
590
24
  }
25
+ printError(err instanceof Error ? err.message : String(err));
26
+ process.exitCode = 2;
591
27
  }
592
28
  }
593
29
 
594
- // Only run when executed directly, not when imported
595
30
  const scriptPath = process.argv[1]?.replaceAll("\\", "/") ?? "";
596
31
  const metaFile = import.meta.filename?.replaceAll("\\", "/") ?? "";
597
32
  const isMain = scriptPath === metaFile
598
33
  || scriptPath.endsWith("cli/index.ts")
599
34
  || import.meta.main === true;
35
+
600
36
  if (isMain) {
601
- try {
602
- const code = await main();
603
- process.exitCode = code;
604
- } catch (err) {
605
- printError(err instanceof Error ? err.message : String(err));
606
- process.exitCode = 2;
607
- }
37
+ await main();
608
38
  }