openapi-forge-cli 0.1.25

OpenAPI Forge command-line interface
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
//! End-to-end CLI test: parse a `forge.toml`, run a transformer →
//! generator pipeline against an `ir.json`, write outputs.
//!
//! Uses the same plugin artifacts as `forge-host`'s `tests/plugins.rs` —
//! both expect them to have been built first via
//! `cargo build --release --manifest-path plugins/Cargo.toml`.

use std::path::{Path, PathBuf};

use assert_cmd::Command;

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("..")
        .canonicalize()
        .unwrap()
}

fn plugin_artifact(name: &str) -> PathBuf {
    let path = repo_root()
        .join("plugins/target/wasm32-wasip2/release")
        .join(format!("{name}.wasm"));
    if !path.exists() {
        panic!(
            "plugin artifact missing at {}.\nBuild plugins first:\n    \
             cargo build --release --manifest-path plugins/Cargo.toml",
            path.display()
        );
    }
    path
}

const SAMPLE_IR: &str = r#"{
  "info": { "title": "test-api", "version": "1.0.0" },
  "operations": [
    {
      "id": "getThing",
      "method": "get",
      "path_template": "/things/{id}",
      "responses": []
    }
  ],
  "types": [],
  "security_schemes": [],
  "servers": []
}"#;

#[test]
fn generate_pipeline_writes_files() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    std::fs::write(project.join("ir.json"), SAMPLE_IR).unwrap();

    let xform_wasm = plugin_artifact("transformer_noop");
    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
ir = "ir.json"

[[transformers]]
wasm = "{xform}"

[generator]
wasm = "{gen}"

[output]
dir = "out"
"#,
        xform = xform_wasm.display(),
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();

    let out_path = project.join("out/ir.txt");
    let out = std::fs::read_to_string(&out_path).expect("output file");
    assert!(out.contains("title:    test-api"), "body: {out}");
    assert!(out.contains("GET /things/{id}"), "body: {out}");
}

/// Multi-pipeline layout: a single `forge.toml` declares two
/// `[[pipelines]]`, each its own transforms → generator stack writing to
/// its own `[output]`. Both must run from one `forge generate`, sharing the
/// top-level `[input]`. Exercises shared-input fallback, per-pipeline
/// output dirs, and the per-pipeline config block.
#[test]
fn generate_multiple_pipelines() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");
    let spec = std::fs::read_to_string(&petstore).expect("read petstore spec");
    std::fs::write(project.join("spec.json"), spec).unwrap();

    let xform_wasm = plugin_artifact("transformer_noop");
    let ts_wasm = plugin_artifact("generator_typescript_fetch");
    let dump_wasm = plugin_artifact("generator_debug_dump");

    // Pipeline `ts` chains a transformer into the TypeScript generator;
    // pipeline `dump` runs the debug-dump generator straight off the shared
    // input. Neither declares its own [input].
    let toml = format!(
        r#"
[input]
spec = "spec.json"

[[pipelines]]
name = "ts"

[[pipelines.transformers]]
wasm = "{xform}"

[pipelines.generator]
wasm = "{ts}"
config = {{ packageName = "petstore-client" }}

[pipelines.output]
dir = "out/ts"

[[pipelines]]
name = "dump"

[pipelines.generator]
wasm = "{dump}"

[pipelines.output]
dir = "out/dump"
"#,
        xform = xform_wasm.display(),
        ts = ts_wasm.display(),
        dump = dump_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();

    // First pipeline's TypeScript output.
    let client =
        std::fs::read_to_string(project.join("out/ts/src/client.ts")).expect("ts client.ts");
    assert!(client.contains("export class ApiClient"), "{client}");
    let pkg =
        std::fs::read_to_string(project.join("out/ts/package.json")).expect("ts package.json");
    assert!(pkg.contains("\"name\": \"petstore-client\""), "{pkg}");

    // Second pipeline's debug-dump output, written to a separate dir.
    let dump = std::fs::read_to_string(project.join("out/dump/ir.txt")).expect("dump ir.txt");
    assert!(dump.contains("title:"), "{dump}");
}

/// Mixing the single-pipeline top-level stack with `[[pipelines]]` is
/// ambiguous and must be rejected with a clear error rather than silently
/// preferring one.
#[test]
fn generate_mixed_layout_fails() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    std::fs::write(project.join("ir.json"), SAMPLE_IR).unwrap();
    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
ir = "ir.json"

[generator]
wasm = "{gen}"

[output]
dir = "out"

[[pipelines]]
name = "extra"

[pipelines.generator]
wasm = "{gen}"

[pipelines.output]
dir = "out2"
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .failure()
        .stderr(predicates::str::contains(
            "mixes the single-pipeline layout",
        ));
}

#[test]
fn generate_from_petstore_spec() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");
    let spec = std::fs::read_to_string(&petstore).expect("read petstore spec");
    std::fs::write(project.join("spec.json"), spec).unwrap();

    let gen_wasm = plugin_artifact("generator_typescript_fetch");

    let toml = format!(
        r#"
[input]
spec = "spec.json"

[generator]
wasm = "{gen}"
config = {{ packageName = "petstore-client" }}

[output]
dir = "out"
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();

    let out_root = project.join("out");
    let client = std::fs::read_to_string(out_root.join("src/client.ts")).expect("client.ts");
    assert!(client.contains("export class ApiClient"), "{client}");
    assert!(client.contains("async listPets"), "{client}");
    assert!(client.contains("async createPet"), "{client}");
    assert!(client.contains("async showPetById"), "{client}");

    let models = std::fs::read_to_string(out_root.join("src/models.ts")).expect("models.ts");
    assert!(models.contains("export interface Pet {"), "{models}");
    assert!(
        models.contains("export type Pets = Array<Pet>;"),
        "{models}"
    );

    let pkg = std::fs::read_to_string(out_root.join("package.json")).expect("package.json");
    assert!(pkg.contains("\"name\": \"petstore-client\""), "{pkg}");
}

#[test]
fn unsupported_spec_feature_halts_with_diagnostic() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    // `not` composition is out-of-scope: parser must emit an error and
    // halt before running the generator.
    let bad_spec = r#"{
        "openapi": "3.0.3",
        "info": { "title": "x", "version": "1" },
        "paths": {},
        "components": {
            "schemas": {
                "Bad": {
                    "not": { "type": "string" }
                }
            }
        }
    }"#;
    std::fs::write(project.join("spec.json"), bad_spec).unwrap();
    let gen_wasm = plugin_artifact("generator_debug_dump");
    let toml = format!(
        r#"
[input]
spec = "spec.json"

[generator]
wasm = "{gen}"

[output]
dir = "out"
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .failure()
        .stderr(predicates::str::contains("parser/E-COMPOSITION-NOT"));
}

#[test]
fn generator_config_passes_validation() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");
    let spec = std::fs::read_to_string(&petstore).expect("read petstore spec");
    std::fs::write(project.join("spec.json"), spec).unwrap();

    let gen_wasm = plugin_artifact("generator_typescript_fetch");
    // Both `packageName` and `baseUrl` are declared in the generator's
    // schema.json — both should pass validation.
    let toml = format!(
        r#"
[input]
spec = "spec.json"

[generator]
wasm = "{gen}"
config = {{ packageName = "petstore-client", baseUrl = "https://example.com" }}

[output]
dir = "out"
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();
}

#[test]
fn generator_config_fails_validation() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");
    let spec = std::fs::read_to_string(&petstore).expect("read petstore spec");
    std::fs::write(project.join("spec.json"), spec).unwrap();

    let gen_wasm = plugin_artifact("generator_typescript_fetch");
    // `bogusKey` is rejected because the schema sets
    // `additionalProperties: false`.
    let toml = format!(
        r#"
[input]
spec = "spec.json"

[generator]
wasm = "{gen}"
config = {{ bogusKey = "nope" }}

[output]
dir = "out"
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .failure()
        .stderr(predicates::str::contains("config validation failed"))
        .stderr(predicates::str::contains("bogusKey"));
}

/// Config-less mode: no `forge.toml` on disk. The pipeline shape is
/// passed entirely via CLI flags (`--input`, `--transformer`,
/// `--generator`, `-o`). Mirrors `generate_from_petstore_spec` but with
/// every knob coming from the command line and additionally chains a
/// transformer to exercise the repeatable `--transformer` flag.
#[test]
fn generate_config_less_from_spec() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");
    let xform_wasm = plugin_artifact("transformer_noop");
    let gen_wasm = plugin_artifact("generator_typescript_fetch");
    let out_dir = project.join("out");

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg("-i")
        .arg(&petstore)
        .arg("--transformer")
        .arg(&xform_wasm)
        .arg("--generator")
        .arg(&gen_wasm)
        .arg("-o")
        .arg(&out_dir)
        .assert()
        .success();

    let client = std::fs::read_to_string(out_dir.join("src/client.ts")).expect("client.ts");
    assert!(client.contains("export class ApiClient"), "{client}");
    assert!(client.contains("async listPets"), "{client}");

    // No forge.toml was written; lock in the contract that config-less
    // mode does not depend on one being present in the run directory.
    assert!(
        !project.join("forge.toml").exists(),
        "config-less run must not depend on forge.toml"
    );
}

/// Without `--input` and without a `forge.toml` in the project dir, the
/// run must fail with a clear "failed to read forge.toml" error rather
/// than silently doing the wrong thing.
#[test]
fn generate_no_config_no_args_fails() {
    let dir = tempfile::tempdir().unwrap();
    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(dir.path())
        .assert()
        .failure()
        .stderr(predicates::str::contains("forge.toml"));
}

/// Config-less mode requires `--generator`. Asserting the dedicated
/// error surfaces keeps the contract obvious for future contributors.
#[test]
fn generate_config_less_requires_generator() {
    let dir = tempfile::tempdir().unwrap();
    let petstore = repo_root().join("fixtures/e2e/petstore/spec.json");

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg("-i")
        .arg(&petstore)
        .arg("-o")
        .arg(dir.path().join("out"))
        .assert()
        .failure()
        .stderr(predicates::str::contains("--generator is required"));
}

/// `[limits]` in `forge.toml` overrides the built-in sandbox limits.
/// Raising every knob must still let a normal run succeed.
#[test]
fn generate_with_raised_limits_succeeds() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    std::fs::write(project.join("ir.json"), SAMPLE_IR).unwrap();

    let xform_wasm = plugin_artifact("transformer_noop");
    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
ir = "ir.json"

[[transformers]]
wasm = "{xform}"

[generator]
wasm = "{gen}"

[output]
dir = "out"

[limits.transformer]
fuel = 10000000000
wall_clock_ms = 10000

[limits.generator]
fuel = 100000000000
memory_bytes = 1073741824
output_files_max = 50000
output_total_bytes_max = 1073741824
output_per_file_bytes_max = 134217728
"#,
        xform = xform_wasm.display(),
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();

    let out = std::fs::read_to_string(project.join("out/ir.txt")).expect("output file");
    assert!(out.contains("title:    test-api"), "body: {out}");
}

/// Lowered limits are enforced, not just parsed: a one-unit fuel budget
/// must trap the generator with a fuel-exhaustion error.
#[test]
fn generate_with_tiny_fuel_limit_fails() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    std::fs::write(project.join("ir.json"), SAMPLE_IR).unwrap();

    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
ir = "ir.json"

[generator]
wasm = "{gen}"

[output]
dir = "out"

[limits.generator]
fuel = 1
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .failure()
        .stderr(predicates::str::contains("exceeded Fuel"));
}

/// A typo'd key in `[limits]` fails the run loudly instead of silently
/// keeping the default.
#[test]
fn generate_with_unknown_limit_key_fails() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    std::fs::write(project.join("ir.json"), SAMPLE_IR).unwrap();

    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
ir = "ir.json"

[generator]
wasm = "{gen}"

[output]
dir = "out"

[limits.generator]
feul = 100
"#,
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .failure()
        .stderr(predicates::str::contains("failed to parse forge.toml"));
}

#[test]
fn ir_version_subcommand() {
    Command::cargo_bin("forge")
        .unwrap()
        .arg("ir-version")
        .assert()
        .success()
        .stdout(predicates::str::starts_with("0."));
}

/// Regression: the CLI previously read the spec into memory and called
/// `forge_parser::parse_str_with_file`, which has no file-based $ref
/// resolver. Specs that split paths / components across sibling files
/// (Stripe, GitHub, …) every external `$ref` would surface as
/// `parser/E-EXTERNAL-REF` and halt the run with hundreds of diagnostics.
/// The parser already supports split-document specs via `parse_path` (#56);
/// this test points the CLI at `fixtures/real-world/multi-tenant-shape/`,
/// which exercises that exact layout, and asserts the run succeeds end
/// to end.
#[test]
fn generate_from_split_document_spec() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let fixture = repo_root().join("fixtures/real-world/multi-tenant-shape");
    let gen_wasm = plugin_artifact("generator_debug_dump");

    let toml = format!(
        r#"
[input]
spec = "{spec}"

[generator]
wasm = "{gen}"

[output]
dir = "out"
"#,
        spec = fixture.join("spec.json").display(),
        gen = gen_wasm.display(),
    );
    std::fs::write(project.join("forge.toml"), toml).unwrap();

    Command::cargo_bin("forge")
        .unwrap()
        .arg("generate")
        .arg(project)
        .assert()
        .success();

    // Operations resolved from sibling files actually appear in the IR.
    let out = std::fs::read_to_string(project.join("out/ir.txt")).expect("output");
    assert!(out.contains("listUsers"), "missing listUsers: {out}");
    assert!(out.contains("createUser"), "missing createUser: {out}");
    assert!(out.contains("getDocument"), "missing getDocument: {out}");
    assert!(
        out.contains("uploadDocumentAttachment"),
        "missing uploadDocumentAttachment: {out}"
    );
    assert!(
        out.contains("updateNoteSavedView"),
        "missing updateNoteSavedView: {out}"
    );
}