loadam 0.2.1 → 0.2.3

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/dist/index.js CHANGED
@@ -1606,6 +1606,14 @@ function slugify(s) {
1606
1606
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1607
1607
  }
1608
1608
 
1609
+ // src/util/target.ts
1610
+ function resolveTarget(flag) {
1611
+ if (typeof flag === "string" && flag.length > 0) return flag;
1612
+ const env = process.env.LOADAM_TARGET;
1613
+ if (typeof env === "string" && env.length > 0) return env;
1614
+ return void 0;
1615
+ }
1616
+
1609
1617
  // src/commands/contract.ts
1610
1618
  function registerContractCommand(program) {
1611
1619
  program.command("contract").description("Compile an OpenAPI spec into a Schemathesis property-based contract suite.").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option(
@@ -1623,8 +1631,9 @@ async function runContract(spec, opts) {
1623
1631
  parseIR(ir);
1624
1632
  const specSource = await readFile4(specPath, "utf8");
1625
1633
  const examples = Number.parseInt(opts.examples ?? "25", 10);
1634
+ const target = resolveTarget(opts.target);
1626
1635
  const result = compileContract(ir, specSource, {
1627
- baseUrl: opts.target,
1636
+ baseUrl: target,
1628
1637
  examples: Number.isFinite(examples) ? examples : 25
1629
1638
  });
1630
1639
  const outDir = resolve4(opts.output);
@@ -1644,10 +1653,10 @@ async function runContract(spec, opts) {
1644
1653
  specSource,
1645
1654
  ir,
1646
1655
  irJson: JSON.stringify(ir, null, 2),
1647
- target: opts.target ?? null,
1656
+ target: target ?? null,
1648
1657
  envVars: result.envVars ?? [],
1649
1658
  flags: {
1650
- target: opts.target ?? null,
1659
+ target: target ?? null,
1651
1660
  examples
1652
1661
  },
1653
1662
  slug: `contract-${ir.meta.title ?? "run"}`
@@ -1932,10 +1941,14 @@ function severityBadge(s) {
1932
1941
 
1933
1942
  // src/commands/diff.ts
1934
1943
  function registerDiffCommand(program) {
1935
- program.command("diff").description("Probe a live API and report drift against the spec (Markdown).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").requiredOption("--target <url>", "base URL of the live API").option("-o, --output <path>", "write report to this file (otherwise stdout)").option("--timeout-ms <n>", "per-request timeout", "5000").option("--mutating", "also probe mutating ops (DANGEROUS \u2014 not for prod)", false).option("-H, --header <kv...>", 'additional headers, repeatable, "Name: value" form').option("--path-param <kv...>", 'fallback path-param values, repeatable, "name=value" form').option("--fail-on <severity>", "exit non-zero when findings of this severity exist", "error").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runDiff));
1944
+ program.command("diff").description("Probe a live API and report drift against the spec (Markdown).").argument("<spec>", "path to OpenAPI 3.x spec (YAML or JSON)").option("--target <url>", "base URL of the live API (or set LOADAM_TARGET)").option("-o, --output <path>", "write report to this file (otherwise stdout)").option("--timeout-ms <n>", "per-request timeout", "5000").option("--mutating", "also probe mutating ops (DANGEROUS \u2014 not for prod)", false).option("-H, --header <kv...>", 'additional headers, repeatable, "Name: value" form').option("--path-param <kv...>", 'fallback path-param values, repeatable, "name=value" form').option("--fail-on <severity>", "exit non-zero when findings of this severity exist", "error").option("--json", "emit a single JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runDiff));
1936
1945
  }
1937
1946
  async function runDiff(spec, opts) {
1938
1947
  const out = makeOutput(!!opts.json);
1948
+ const target = resolveTarget(opts.target);
1949
+ if (!target) {
1950
+ throw new Error("--target is required (or set LOADAM_TARGET env var)");
1951
+ }
1939
1952
  const specPath = resolve5(spec);
1940
1953
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1941
1954
  const specSource = await readFile5(specPath, "utf8");
@@ -1945,9 +1958,9 @@ async function runDiff(spec, opts) {
1945
1958
  const headers = parseKvPairs(opts.header ?? [], ":");
1946
1959
  const pathParams = parseKvPairs(opts.pathParam ?? [], "=");
1947
1960
  const timeoutMs = Number.parseInt(opts.timeoutMs ?? "5000", 10);
1948
- out.start(`Probing ${ir.operations.length} operations on ${opts.target}\u2026`);
1961
+ out.start(`Probing ${ir.operations.length} operations on ${target}\u2026`);
1949
1962
  const { probes, skipped } = await probeOperations(ir, {
1950
- baseUrl: opts.target,
1963
+ baseUrl: target,
1951
1964
  headers,
1952
1965
  pathParams,
1953
1966
  timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : 5e3,
@@ -1962,10 +1975,10 @@ async function runDiff(spec, opts) {
1962
1975
  specSource,
1963
1976
  ir,
1964
1977
  irJson: JSON.stringify(ir, null, 2),
1965
- target: opts.target,
1978
+ target,
1966
1979
  envVars: [],
1967
1980
  flags: {
1968
- target: opts.target,
1981
+ target,
1969
1982
  timeoutMs,
1970
1983
  mutating: !!opts.mutating,
1971
1984
  failOn: opts.failOn ?? "error",
@@ -1976,7 +1989,7 @@ async function runDiff(spec, opts) {
1976
1989
  });
1977
1990
  const report = renderMarkdownReport({
1978
1991
  ir,
1979
- baseUrl: opts.target,
1992
+ baseUrl: target,
1980
1993
  findings,
1981
1994
  skipped
1982
1995
  });
@@ -2016,7 +2029,7 @@ async function runDiff(spec, opts) {
2016
2029
  });
2017
2030
  out.result({
2018
2031
  command: "diff",
2019
- target: opts.target,
2032
+ target,
2020
2033
  probed: probes.length,
2021
2034
  skipped: skipped.length,
2022
2035
  findings: findings.length,
@@ -2625,8 +2638,9 @@ async function runMcp(spec, opts) {
2625
2638
  const ir = await fromOpenApiFile(specPath);
2626
2639
  inferResourceGraph(ir);
2627
2640
  parseIR(ir);
2641
+ const target = resolveTarget(opts.target);
2628
2642
  const result = compileMcp(ir, {
2629
- baseUrl: opts.target,
2643
+ baseUrl: target,
2630
2644
  includeWrites: !!opts.writes,
2631
2645
  exclude: opts.exclude
2632
2646
  });
@@ -2661,17 +2675,427 @@ async function runMcp(spec, opts) {
2661
2675
  });
2662
2676
  }
2663
2677
 
2664
- // src/commands/show.ts
2665
- import { readFile as readFile6, readdir as readdir2 } from "fs/promises";
2678
+ // src/commands/report.ts
2679
+ import { spawn } from "child_process";
2680
+ import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
2666
2681
  import { join as join2, resolve as resolve9 } from "path";
2682
+
2683
+ // ../report/dist/index.js
2684
+ function renderReport(input) {
2685
+ const { meta, loadamVersion } = input;
2686
+ const passed = meta.exitCode === 0 && (meta.thresholds?.failed.length ?? 0) === 0;
2687
+ const dataPayload = {
2688
+ meta,
2689
+ k6Summaries: input.k6Summaries ?? null,
2690
+ contractFailures: input.contractFailures ?? null,
2691
+ loadamVersion
2692
+ };
2693
+ return [
2694
+ "<!doctype html>",
2695
+ `<html lang="en">`,
2696
+ "<head>",
2697
+ `<meta charset="utf-8" />`,
2698
+ `<meta name="viewport" content="width=device-width,initial-scale=1" />`,
2699
+ `<meta name="generator" content="loadam ${esc(loadamVersion)}" />`,
2700
+ `<title>${esc(reportTitle(meta))}</title>`,
2701
+ `<style>${STYLES}</style>`,
2702
+ "</head>",
2703
+ "<body>",
2704
+ renderHeader(meta, passed),
2705
+ renderSummary(meta, input.k6Summaries),
2706
+ renderThresholds(meta),
2707
+ renderK6Metrics(input.k6Summaries),
2708
+ input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
2709
+ input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
2710
+ renderRunDetails(meta),
2711
+ renderFooter(meta, loadamVersion),
2712
+ `<script type="application/json" id="loadam-data">${escScript(JSON.stringify(dataPayload))}</script>`,
2713
+ "</body>",
2714
+ "</html>",
2715
+ ""
2716
+ ].join("\n");
2717
+ }
2718
+ function renderHeader(meta, passed) {
2719
+ const status = passed ? "PASSED" : "FAILED";
2720
+ const cls = passed ? "ok" : "bad";
2721
+ return `
2722
+ <header class="hdr">
2723
+ <div class="hdr-left">
2724
+ <div class="cmd">${esc(meta.command)}</div>
2725
+ <h1>${esc(meta.spec.title ?? "Untitled API")}</h1>
2726
+ <div class="sub">${esc(meta.spec.version ?? "")} \xB7 target <code>${esc(meta.target ?? "\u2014")}</code></div>
2727
+ </div>
2728
+ <div class="hdr-right">
2729
+ <span class="badge ${cls}">${status}</span>
2730
+ <div class="when">${esc(meta.startedAt)}</div>
2731
+ ${typeof meta.durationMs === "number" ? `<div class="dur">${(meta.durationMs / 1e3).toFixed(2)}s</div>` : ""}
2732
+ </div>
2733
+ </header>`;
2734
+ }
2735
+ function renderSummary(meta, k6) {
2736
+ const cells = [];
2737
+ if (meta.summary) {
2738
+ for (const [k, v] of Object.entries(meta.summary)) {
2739
+ cells.push({ label: k, value: String(v) });
2740
+ }
2741
+ }
2742
+ if (k6) {
2743
+ for (const [name, s] of Object.entries(k6)) {
2744
+ const dur = s.metrics?.http_req_duration?.values;
2745
+ if (dur && typeof dur["p(95)"] === "number") {
2746
+ cells.push({ label: `${name} p95`, value: `${dur["p(95)"].toFixed(0)} ms` });
2747
+ }
2748
+ const reqs = s.metrics?.http_reqs?.values;
2749
+ if (reqs && typeof reqs.count === "number") {
2750
+ cells.push({ label: `${name} reqs`, value: String(reqs.count) });
2751
+ }
2752
+ if (reqs && typeof reqs.rate === "number") {
2753
+ cells.push({ label: `${name} rps`, value: `${reqs.rate.toFixed(1)}/s` });
2754
+ }
2755
+ const failed = s.metrics?.http_req_failed?.values;
2756
+ if (failed && typeof failed.rate === "number") {
2757
+ cells.push({
2758
+ label: `${name} fail`,
2759
+ value: `${(failed.rate * 100).toFixed(2)}%`
2760
+ });
2761
+ }
2762
+ }
2763
+ }
2764
+ if (cells.length === 0) return "";
2765
+ return `
2766
+ <section class="cards">
2767
+ ${cells.map(
2768
+ (c) => `<div class="card"><div class="card-v">${esc(c.value)}</div><div class="card-l">${esc(c.label)}</div></div>`
2769
+ ).join("\n ")}
2770
+ </section>`;
2771
+ }
2772
+ function renderThresholds(meta) {
2773
+ const t = meta.thresholds;
2774
+ if (!t || t.passed.length === 0 && t.failed.length === 0) return "";
2775
+ return `
2776
+ <section>
2777
+ <h2>Thresholds</h2>
2778
+ <ul class="thr">
2779
+ ${t.failed.map((x) => `<li class="bad">\u2717 ${esc(x)}</li>`).join("\n ")}
2780
+ ${t.passed.map((x) => `<li class="ok">\u2713 ${esc(x)}</li>`).join("\n ")}
2781
+ </ul>
2782
+ </section>`;
2783
+ }
2784
+ function renderK6Metrics(k6) {
2785
+ if (!k6 || Object.keys(k6).length === 0) return "";
2786
+ const blocks = [];
2787
+ for (const [name, s] of Object.entries(k6)) {
2788
+ const metrics = s.metrics ?? {};
2789
+ const dur = metrics.http_req_duration?.values;
2790
+ if (!dur) continue;
2791
+ const rows = [
2792
+ ["min", fmtMs(dur.min)],
2793
+ ["med", fmtMs(dur.med)],
2794
+ ["avg", fmtMs(dur.avg)],
2795
+ ["p(90)", fmtMs(dur["p(90)"])],
2796
+ ["p(95)", fmtMs(dur["p(95)"])],
2797
+ ["p(99)", fmtMs(dur["p(99)"])],
2798
+ ["max", fmtMs(dur.max)]
2799
+ ];
2800
+ blocks.push(`
2801
+ <div class="metric-block">
2802
+ <h3>${esc(name)} \xB7 http_req_duration</h3>
2803
+ <table class="kv">
2804
+ <tbody>
2805
+ ${rows.map(([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(v)}</td></tr>`).join("\n ")}
2806
+ </tbody>
2807
+ </table>
2808
+ ${renderPercentileBars(dur)}
2809
+ </div>`);
2810
+ }
2811
+ if (blocks.length === 0) return "";
2812
+ return `<section><h2>Latency</h2>${blocks.join("\n")}</section>`;
2813
+ }
2814
+ function renderPercentileBars(dur) {
2815
+ const max = dur.max ?? Math.max(...Object.values(dur));
2816
+ if (!Number.isFinite(max) || max <= 0) return "";
2817
+ const bars = [
2818
+ ["med", dur.med ?? 0],
2819
+ ["p(90)", dur["p(90)"] ?? 0],
2820
+ ["p(95)", dur["p(95)"] ?? 0],
2821
+ ["p(99)", dur["p(99)"] ?? 0],
2822
+ ["max", max]
2823
+ ];
2824
+ return `
2825
+ <div class="bars">
2826
+ ${bars.map(([k, v]) => {
2827
+ const pct = Math.max(2, Math.round(v / max * 100));
2828
+ return `<div class="bar-row"><span class="bar-l">${esc(k)}</span><div class="bar"><div class="bar-fill" style="width:${pct}%"></div></div><span class="bar-v">${esc(fmtMs(v))}</span></div>`;
2829
+ }).join("\n ")}
2830
+ </div>`;
2831
+ }
2832
+ function renderDrift(md) {
2833
+ return `
2834
+ <section>
2835
+ <h2>Drift findings</h2>
2836
+ <pre class="drift">${esc(md)}</pre>
2837
+ </section>`;
2838
+ }
2839
+ function renderContract(failures) {
2840
+ return `
2841
+ <section>
2842
+ <h2>Contract failures (${failures.length})</h2>
2843
+ <ul class="failures">
2844
+ ${failures.map(
2845
+ (f) => `<li><div class="ftest">${esc(f.test)}</div>${f.message ? `<pre>${esc(f.message)}</pre>` : ""}</li>`
2846
+ ).join("\n ")}
2847
+ </ul>
2848
+ </section>`;
2849
+ }
2850
+ function renderRunDetails(meta) {
2851
+ const flagRows = Object.entries(meta.flags).map(
2852
+ ([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(String(v))}</td></tr>`
2853
+ );
2854
+ const envRow = meta.envVars.length > 0 ? `<tr><th>env vars</th><td>${meta.envVars.map((e) => `<code>${esc(e)}</code>`).join(" ")}</td></tr>` : "";
2855
+ return `
2856
+ <section>
2857
+ <h2>Run details</h2>
2858
+ <table class="kv">
2859
+ <tbody>
2860
+ <tr><th>session id</th><td><code>${esc(meta.id)}</code></td></tr>
2861
+ <tr><th>spec</th><td><code>${esc(meta.spec.path)}</code></td></tr>
2862
+ <tr><th>spec sha256</th><td><code>${esc(meta.spec.sha256.slice(0, 16))}\u2026</code></td></tr>
2863
+ <tr><th>IR digest</th><td><code>${esc(meta.irDigest.slice(0, 16))}\u2026</code></td></tr>
2864
+ <tr><th>started</th><td>${esc(meta.startedAt)}</td></tr>
2865
+ ${meta.endedAt ? `<tr><th>ended</th><td>${esc(meta.endedAt)}</td></tr>` : ""}
2866
+ ${typeof meta.exitCode === "number" ? `<tr><th>exit code</th><td>${meta.exitCode}</td></tr>` : ""}
2867
+ ${envRow}
2868
+ ${flagRows.join("\n ")}
2869
+ </tbody>
2870
+ </table>
2871
+ </section>`;
2872
+ }
2873
+ function renderFooter(meta, version) {
2874
+ return `
2875
+ <footer>
2876
+ Generated by <a href="https://github.com/anonxhash/loadam">loadam ${esc(version)}</a> \xB7
2877
+ schema v${meta.schemaVersion} \xB7
2878
+ IR <code>${esc(meta.irDigest.slice(0, 12))}</code>
2879
+ </footer>`;
2880
+ }
2881
+ function reportTitle(meta) {
2882
+ const t = meta.spec.title ?? "loadam";
2883
+ return `${t} \xB7 ${meta.command} \xB7 ${meta.id}`;
2884
+ }
2885
+ function fmtMs(n) {
2886
+ if (typeof n !== "number" || !Number.isFinite(n)) return "\u2014";
2887
+ if (n >= 1e3) return `${(n / 1e3).toFixed(2)} s`;
2888
+ return `${n.toFixed(0)} ms`;
2889
+ }
2890
+ function esc(s) {
2891
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2892
+ }
2893
+ function escScript(s) {
2894
+ return s.replace(/<\/script/gi, "<\\/script");
2895
+ }
2896
+ var STYLES = `
2897
+ :root{
2898
+ --bg:#fafafa;--fg:#111;--mut:#666;--brd:#e5e5e5;--card:#fff;
2899
+ --ok:#15803d;--ok-bg:#dcfce7;--bad:#b91c1c;--bad-bg:#fee2e2;
2900
+ --acc:#2563eb;--bar:#3b82f6;--code:#f4f4f5;
2901
+ }
2902
+ @media (prefers-color-scheme:dark){
2903
+ :root{
2904
+ --bg:#0a0a0a;--fg:#f5f5f5;--mut:#a1a1aa;--brd:#27272a;--card:#18181b;
2905
+ --ok:#86efac;--ok-bg:#14532d;--bad:#fca5a5;--bad-bg:#7f1d1d;
2906
+ --acc:#60a5fa;--bar:#3b82f6;--code:#27272a;
2907
+ }
2908
+ }
2909
+ *{box-sizing:border-box}
2910
+ html,body{margin:0;padding:0;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
2911
+ body{max-width:960px;margin:0 auto;padding:24px 20px 60px}
2912
+ h1{font-size:20px;margin:0 0 4px}
2913
+ h2{font-size:15px;margin:24px 0 12px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
2914
+ h3{font-size:14px;margin:16px 0 8px;font-weight:600}
2915
+ code{font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--code);padding:1px 6px;border-radius:3px}
2916
+ a{color:var(--acc);text-decoration:none}
2917
+ a:hover{text-decoration:underline}
2918
+ section{margin-top:8px}
2919
+ .hdr{display:flex;justify-content:space-between;align-items:flex-start;gap:24px;padding-bottom:16px;border-bottom:1px solid var(--brd)}
2920
+ .hdr-left .cmd{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:600}
2921
+ .hdr-left .sub{color:var(--mut);font-size:13px;margin-top:4px}
2922
+ .hdr-right{text-align:right}
2923
+ .hdr-right .when,.hdr-right .dur{font-size:12px;color:var(--mut);margin-top:4px;font-variant-numeric:tabular-nums}
2924
+ .badge{display:inline-block;padding:4px 10px;border-radius:4px;font-size:11px;font-weight:700;letter-spacing:.06em}
2925
+ .badge.ok{background:var(--ok-bg);color:var(--ok)}
2926
+ .badge.bad{background:var(--bad-bg);color:var(--bad)}
2927
+ .cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-top:20px}
2928
+ .card{background:var(--card);border:1px solid var(--brd);border-radius:6px;padding:12px 14px}
2929
+ .card-v{font-size:18px;font-weight:600;font-variant-numeric:tabular-nums}
2930
+ .card-l{font-size:11px;color:var(--mut);text-transform:uppercase;letter-spacing:.04em;margin-top:2px}
2931
+ .thr{list-style:none;padding:0;margin:0}
2932
+ .thr li{padding:4px 8px;border-radius:3px;margin:2px 0;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
2933
+ .thr li.ok{color:var(--ok)}
2934
+ .thr li.bad{background:var(--bad-bg);color:var(--bad);font-weight:600}
2935
+ table.kv{border-collapse:collapse;width:100%;font-size:13px}
2936
+ table.kv th,table.kv td{padding:6px 10px;text-align:left;border-bottom:1px solid var(--brd);vertical-align:top}
2937
+ table.kv th{font-weight:500;color:var(--mut);width:160px;white-space:nowrap}
2938
+ .metric-block{background:var(--card);border:1px solid var(--brd);border-radius:6px;padding:12px 16px;margin-bottom:12px}
2939
+ .bars{margin-top:10px}
2940
+ .bar-row{display:grid;grid-template-columns:60px 1fr 80px;gap:10px;align-items:center;font-size:12px;font-variant-numeric:tabular-nums;margin:3px 0}
2941
+ .bar-l{color:var(--mut)}
2942
+ .bar{background:var(--code);height:8px;border-radius:4px;overflow:hidden}
2943
+ .bar-fill{background:var(--bar);height:100%}
2944
+ .bar-v{text-align:right;color:var(--fg)}
2945
+ .drift{background:var(--card);border:1px solid var(--brd);border-radius:6px;padding:12px 16px;overflow-x:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap}
2946
+ .failures{list-style:none;padding:0;margin:0}
2947
+ .failures li{background:var(--bad-bg);border:1px solid var(--bad);border-radius:4px;padding:8px 12px;margin-bottom:6px}
2948
+ .failures .ftest{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;font-weight:600}
2949
+ .failures pre{margin:6px 0 0;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap}
2950
+ footer{margin-top:40px;padding-top:16px;border-top:1px solid var(--brd);color:var(--mut);font-size:12px;text-align:center}
2951
+ `;
2952
+
2953
+ // src/commands/report.ts
2954
+ var VERSION = true ? "0.2.3" : "0.0.0";
2955
+ function registerReportCommand(program) {
2956
+ program.command("report").description("Render a self-contained HTML report for an archived session.").argument("[id]", 'session ID, prefix, or "latest" (default: latest)', "latest").option("--root <dir>", "session archive root", "./loadam-out").option("-o, --output <path>", "write to this path instead of <session>/report.html").option("--open", "open the report in your default browser after writing", false).option("--json", "emit a JSON summary on stdout (CI mode)", false).action(withFriendlyErrors(runReport));
2957
+ }
2958
+ async function runReport(id, opts) {
2959
+ const out = makeOutput(!!opts.json);
2960
+ const root = resolve9(opts.root);
2961
+ const meta = await resolveSessionId(root, id);
2962
+ const dir = join2(root, "sessions", meta.id);
2963
+ const k6Summaries = {};
2964
+ for (const a of meta.artefacts) {
2965
+ if (a.startsWith("k6-") && a.endsWith("-summary.json")) {
2966
+ const label = a.replace(/^k6-/, "").replace(/-summary\.json$/, "");
2967
+ try {
2968
+ k6Summaries[label] = JSON.parse(await readFile6(join2(dir, a), "utf8"));
2969
+ } catch {
2970
+ }
2971
+ }
2972
+ }
2973
+ let driftMarkdown;
2974
+ if (meta.command === "diff") {
2975
+ try {
2976
+ driftMarkdown = await readFile6(join2(dir, "drift.md"), "utf8");
2977
+ } catch {
2978
+ }
2979
+ }
2980
+ const html = renderReport({
2981
+ meta,
2982
+ k6Summaries: Object.keys(k6Summaries).length > 0 ? k6Summaries : void 0,
2983
+ driftMarkdown,
2984
+ loadamVersion: VERSION
2985
+ });
2986
+ const outPath = opts.output ? resolve9(opts.output) : join2(dir, "report.html");
2987
+ await writeFile6(outPath, html, "utf8");
2988
+ const sizeKb = Math.round(Buffer.byteLength(html, "utf8") / 1024);
2989
+ if (!out.json) {
2990
+ out.success(`Wrote ${outPath} (${sizeKb} KB)`);
2991
+ }
2992
+ out.result({
2993
+ command: "report",
2994
+ sessionId: meta.id,
2995
+ path: outPath,
2996
+ sizeBytes: Buffer.byteLength(html, "utf8"),
2997
+ opened: false
2998
+ });
2999
+ if (opts.open) {
3000
+ await openInBrowser(outPath);
3001
+ if (!out.json) out.info("Opened in default browser");
3002
+ }
3003
+ }
3004
+ async function openInBrowser(path) {
3005
+ const platform = process.platform;
3006
+ const cmd = platform === "darwin" ? "open" : platform === "win32" ? "start" : "xdg-open";
3007
+ const args = platform === "win32" ? ["", path] : [path];
3008
+ try {
3009
+ const child = spawn(cmd, args, {
3010
+ detached: true,
3011
+ stdio: "ignore",
3012
+ shell: platform === "win32"
3013
+ });
3014
+ child.unref();
3015
+ } catch {
3016
+ }
3017
+ }
3018
+
3019
+ // src/commands/show.ts
3020
+ import { readFile as readFile7, readdir as readdir2 } from "fs/promises";
3021
+ import { join as join4, resolve as resolve10 } from "path";
3022
+
3023
+ // src/util/k6.ts
3024
+ import { spawn as spawn2 } from "child_process";
3025
+ import { constants, access } from "fs/promises";
3026
+ import { delimiter, join as join3 } from "path";
3027
+ async function findK6Binary() {
3028
+ const path = process.env.PATH ?? "";
3029
+ const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3030
+ for (const dir of path.split(delimiter)) {
3031
+ if (!dir) continue;
3032
+ for (const ext of exts) {
3033
+ const candidate = join3(dir, `k6${ext}`);
3034
+ try {
3035
+ await access(candidate, constants.X_OK);
3036
+ return candidate;
3037
+ } catch {
3038
+ }
3039
+ }
3040
+ }
3041
+ return null;
3042
+ }
3043
+ async function runK6(opts) {
3044
+ const bin = await findK6Binary();
3045
+ if (!bin) {
3046
+ throw new Error(
3047
+ "k6 not found on PATH. Install it from https://grafana.com/docs/k6/latest/set-up/install-k6/ and try again."
3048
+ );
3049
+ }
3050
+ const args = ["run"];
3051
+ if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3052
+ args.push(...opts.args ?? [], opts.script);
3053
+ return await new Promise((resolveExit, reject) => {
3054
+ const child = spawn2(bin, args, {
3055
+ cwd: opts.cwd,
3056
+ env: { ...process.env, ...opts.env },
3057
+ stdio: "inherit"
3058
+ });
3059
+ child.on("error", reject);
3060
+ child.on("close", (code) => resolveExit(code ?? 0));
3061
+ });
3062
+ }
3063
+ async function digestK6Summary(path) {
3064
+ try {
3065
+ const { readFile: readFile10 } = await import("fs/promises");
3066
+ const text = await readFile10(path, "utf8");
3067
+ const data = JSON.parse(text);
3068
+ const passed = [];
3069
+ const failed = [];
3070
+ const metrics = {};
3071
+ for (const [name, m] of Object.entries(data.metrics ?? {})) {
3072
+ if (m.thresholds) {
3073
+ for (const [expr, info] of Object.entries(m.thresholds)) {
3074
+ (info.ok ? passed : failed).push(`${name}: ${expr}`);
3075
+ }
3076
+ }
3077
+ if (m.values) {
3078
+ if (typeof m.values["p(95)"] === "number") metrics[`${name}.p95`] = m.values["p(95)"];
3079
+ if (typeof m.values.rate === "number") metrics[`${name}.rate`] = m.values.rate;
3080
+ if (typeof m.values.count === "number") metrics[`${name}.count`] = m.values.count;
3081
+ if (typeof m.values.avg === "number") metrics[`${name}.avg`] = m.values.avg;
3082
+ }
3083
+ }
3084
+ return { passed, failed, metrics };
3085
+ } catch {
3086
+ return null;
3087
+ }
3088
+ }
3089
+
3090
+ // src/commands/show.ts
2667
3091
  function registerShowCommand(program) {
2668
3092
  program.command("show").description("Show details of an archived session.").argument("<id>", 'session ID, prefix, or "latest"').option("--root <dir>", "session archive root", "./loadam-out").option("--json", "emit the meta.json payload on stdout", false).action(withFriendlyErrors(runShow));
2669
3093
  }
2670
3094
  async function runShow(id, opts) {
2671
3095
  const out = makeOutput(!!opts.json);
2672
- const root = resolve9(opts.root);
3096
+ const root = resolve10(opts.root);
2673
3097
  const meta = await resolveSessionId(root, id);
2674
- const dir = join2(root, "sessions", meta.id);
3098
+ const dir = join4(root, "sessions", meta.id);
2675
3099
  if (out.json) {
2676
3100
  out.result({ ...meta });
2677
3101
  return;
@@ -2709,18 +3133,50 @@ async function runShow(id, opts) {
2709
3133
  }
2710
3134
  if (meta.command === "diff") {
2711
3135
  try {
2712
- const drift = await readFile6(join2(dir, "drift.md"), "utf8");
3136
+ const drift = await readFile7(join4(dir, "drift.md"), "utf8");
2713
3137
  out.info("");
2714
3138
  out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
2715
3139
  process.stdout.write(drift);
2716
3140
  } catch {
2717
3141
  }
2718
3142
  }
3143
+ if (meta.command === "test") {
3144
+ try {
3145
+ const entries = await readdir2(dir);
3146
+ const summaryFile = entries.find((e) => /^k6-.*-summary\.json$/.test(e));
3147
+ if (summaryFile) {
3148
+ const digest = await digestK6Summary(join4(dir, summaryFile));
3149
+ if (digest) {
3150
+ out.info("");
3151
+ out.info(`\u2500\u2500\u2500\u2500 ${summaryFile} \u2500\u2500\u2500\u2500`);
3152
+ const headline = [];
3153
+ const dur = digest.metrics["http_req_duration.p95"];
3154
+ const cnt = digest.metrics["http_reqs.count"];
3155
+ const rate = digest.metrics["http_reqs.rate"];
3156
+ const failRate = digest.metrics["http_req_failed.rate"];
3157
+ if (typeof dur === "number")
3158
+ headline.push(["http_req_duration p95", `${dur.toFixed(1)}ms`]);
3159
+ if (typeof cnt === "number") headline.push(["http_reqs count", `${cnt}`]);
3160
+ if (typeof rate === "number") headline.push(["http_reqs rate", `${rate.toFixed(2)}/s`]);
3161
+ if (typeof failRate === "number")
3162
+ headline.push(["http_req_failed rate", `${(failRate * 100).toFixed(2)}%`]);
3163
+ for (const [k, v] of headline) out.info(` ${k}: ${v}`);
3164
+ if (digest.passed.length || digest.failed.length) {
3165
+ out.info(
3166
+ ` Thresholds: ${digest.passed.length} passed \xB7 ${digest.failed.length} failed`
3167
+ );
3168
+ for (const t of digest.failed) out.info(` \u2717 ${t}`);
3169
+ }
3170
+ }
3171
+ }
3172
+ } catch {
3173
+ }
3174
+ }
2719
3175
  }
2720
3176
 
2721
3177
  // src/commands/test.ts
2722
- import { mkdir as mkdir4, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
2723
- import { dirname as dirname3, join as join4, resolve as resolve11 } from "path";
3178
+ import { mkdir as mkdir4, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
3179
+ import { dirname as dirname3, join as join5, resolve as resolve12 } from "path";
2724
3180
 
2725
3181
  // ../data/dist/index.js
2726
3182
  import { faker } from "@faker-js/faker";
@@ -2773,20 +3229,20 @@ function inferKindFromFieldName(field) {
2773
3229
  const root = m[1];
2774
3230
  return root.charAt(0).toUpperCase() + root.slice(1);
2775
3231
  }
2776
- function expandRefs(node, resolve12, seen) {
2777
- if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve12, seen));
3232
+ function expandRefs(node, resolve13, seen) {
3233
+ if (Array.isArray(node)) return node.map((n) => expandRefs(n, resolve13, seen));
2778
3234
  if (!node || typeof node !== "object") return node;
2779
3235
  const obj = node;
2780
3236
  if (typeof obj.$ref === "string") {
2781
3237
  if (seen.has(obj.$ref)) return {};
2782
- const target = resolve12(obj.$ref);
3238
+ const target = resolve13(obj.$ref);
2783
3239
  if (target === void 0) return obj;
2784
3240
  const next = new Set(seen);
2785
3241
  next.add(obj.$ref);
2786
- return expandRefs(target, resolve12, next);
3242
+ return expandRefs(target, resolve13, next);
2787
3243
  }
2788
3244
  const out = {};
2789
- for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve12, seen);
3245
+ for (const [k, v] of Object.entries(obj)) out[k] = expandRefs(v, resolve13, seen);
2790
3246
  return out;
2791
3247
  }
2792
3248
 
@@ -3282,8 +3738,8 @@ function compileK6(ir, opts = {}) {
3282
3738
  }
3283
3739
 
3284
3740
  // src/util/interactive.ts
3285
- import { chmod, readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
3286
- import { resolve as resolve10 } from "path";
3741
+ import { chmod, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
3742
+ import { resolve as resolve11 } from "path";
3287
3743
  import { confirm, password, select } from "@inquirer/prompts";
3288
3744
  function isInteractive(noInteractiveFlag) {
3289
3745
  if (noInteractiveFlag) return false;
@@ -3320,7 +3776,7 @@ async function confirmContinue(message) {
3320
3776
  return await confirm({ message, default: true });
3321
3777
  }
3322
3778
  async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
3323
- const path = resolve10(dir, ".env");
3779
+ const path = resolve11(dir, ".env");
3324
3780
  const existing = await readEnvFile(path);
3325
3781
  const written = [];
3326
3782
  const preserved = [];
@@ -3340,14 +3796,14 @@ async function writeEnvFile(dir, baseUrl, vars, opts = {}) {
3340
3796
  }
3341
3797
  const body = `${Object.entries(existing).map(([k, v]) => `${k}=${v}`).join("\n")}
3342
3798
  `;
3343
- await writeFile6(path, body, "utf8");
3799
+ await writeFile7(path, body, "utf8");
3344
3800
  await chmod(path, 384).catch(() => {
3345
3801
  });
3346
3802
  return { path, written, preserved };
3347
3803
  }
3348
3804
  async function readEnvFile(path) {
3349
3805
  try {
3350
- const text = await readFile7(path, "utf8");
3806
+ const text = await readFile8(path, "utf8");
3351
3807
  const out = {};
3352
3808
  for (const raw of text.split(/\r?\n/)) {
3353
3809
  const line = raw.trim();
@@ -3364,73 +3820,6 @@ async function readEnvFile(path) {
3364
3820
  }
3365
3821
  }
3366
3822
 
3367
- // src/util/k6.ts
3368
- import { spawn } from "child_process";
3369
- import { constants, access } from "fs/promises";
3370
- import { delimiter, join as join3 } from "path";
3371
- async function findK6Binary() {
3372
- const path = process.env.PATH ?? "";
3373
- const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3374
- for (const dir of path.split(delimiter)) {
3375
- if (!dir) continue;
3376
- for (const ext of exts) {
3377
- const candidate = join3(dir, `k6${ext}`);
3378
- try {
3379
- await access(candidate, constants.X_OK);
3380
- return candidate;
3381
- } catch {
3382
- }
3383
- }
3384
- }
3385
- return null;
3386
- }
3387
- async function runK6(opts) {
3388
- const bin = await findK6Binary();
3389
- if (!bin) {
3390
- throw new Error(
3391
- "k6 not found on PATH. Install it from https://grafana.com/docs/k6/latest/set-up/install-k6/ and try again."
3392
- );
3393
- }
3394
- const args = ["run"];
3395
- if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3396
- args.push(...opts.args ?? [], opts.script);
3397
- return await new Promise((resolveExit, reject) => {
3398
- const child = spawn(bin, args, {
3399
- cwd: opts.cwd,
3400
- env: { ...process.env, ...opts.env },
3401
- stdio: "inherit"
3402
- });
3403
- child.on("error", reject);
3404
- child.on("close", (code) => resolveExit(code ?? 0));
3405
- });
3406
- }
3407
- async function digestK6Summary(path) {
3408
- try {
3409
- const { readFile: readFile9 } = await import("fs/promises");
3410
- const text = await readFile9(path, "utf8");
3411
- const data = JSON.parse(text);
3412
- const passed = [];
3413
- const failed = [];
3414
- const metrics = {};
3415
- for (const [name, m] of Object.entries(data.metrics ?? {})) {
3416
- if (m.thresholds) {
3417
- for (const [expr, info] of Object.entries(m.thresholds)) {
3418
- (info.ok ? passed : failed).push(`${name}: ${expr}`);
3419
- }
3420
- }
3421
- if (m.values) {
3422
- if (typeof m.values["p(95)"] === "number") metrics[`${name}.p95`] = m.values["p(95)"];
3423
- if (typeof m.values.rate === "number") metrics[`${name}.rate`] = m.values.rate;
3424
- if (typeof m.values.count === "number") metrics[`${name}.count`] = m.values.count;
3425
- if (typeof m.values.avg === "number") metrics[`${name}.avg`] = m.values.avg;
3426
- }
3427
- }
3428
- return { passed, failed, metrics };
3429
- } catch {
3430
- return null;
3431
- }
3432
- }
3433
-
3434
3823
  // src/commands/test.ts
3435
3824
  var VALID_MODES = ["smoke", "load", "both", "skip"];
3436
3825
  function registerTestCommand(program) {
@@ -3444,25 +3833,26 @@ function registerTestCommand(program) {
3444
3833
  }
3445
3834
  async function runTest(spec, opts) {
3446
3835
  const out = makeOutput(!!opts.json);
3447
- const specPath = resolve11(spec);
3836
+ const specPath = resolve12(spec);
3448
3837
  out.start(`Parsing OpenAPI spec: ${specPath}`);
3449
- const specSource = await readFile8(specPath, "utf8");
3838
+ const specSource = await readFile9(specPath, "utf8");
3450
3839
  const ir = await fromOpenApiFile(specPath);
3451
3840
  inferResourceGraph(ir);
3452
3841
  parseIR(ir);
3453
3842
  const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
3454
3843
  const seed = Number.parseInt(opts.seed ?? "1", 10);
3844
+ const target = resolveTarget(opts.target);
3455
3845
  const result = compileK6(ir, {
3456
- baseUrl: opts.target,
3846
+ baseUrl: target,
3457
3847
  fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
3458
3848
  seed: Number.isFinite(seed) ? seed : 1
3459
3849
  });
3460
- const outDir = resolve11(opts.output);
3850
+ const outDir = resolve12(opts.output);
3461
3851
  await mkdir4(outDir, { recursive: true });
3462
3852
  for (const [rel, contents] of Object.entries(result.files)) {
3463
- const full = resolve11(outDir, rel);
3853
+ const full = resolve12(outDir, rel);
3464
3854
  await mkdir4(dirname3(full), { recursive: true });
3465
- await writeFile7(full, contents, "utf8");
3855
+ await writeFile8(full, contents, "utf8");
3466
3856
  }
3467
3857
  const fileCount = Object.keys(result.files).length;
3468
3858
  const fixtureCount = Object.keys(result.fixtures.byOperationId).length;
@@ -3509,11 +3899,11 @@ async function runTest(spec, opts) {
3509
3899
  specSource,
3510
3900
  ir,
3511
3901
  irJson: JSON.stringify(ir, null, 2),
3512
- target: opts.target ?? result.baseUrl,
3902
+ target: target ?? result.baseUrl,
3513
3903
  envVars: result.auth.envVars,
3514
3904
  flags: {
3515
3905
  mode,
3516
- target: opts.target ?? null,
3906
+ target: target ?? null,
3517
3907
  fixtureSize,
3518
3908
  seed,
3519
3909
  noInteractive: !!opts.noInteractive,
@@ -3569,7 +3959,7 @@ function parseModeFlag(raw) {
3569
3959
  return raw;
3570
3960
  }
3571
3961
  function getSessionRoot(outDir) {
3572
- return resolve11(outDir, "..");
3962
+ return resolve12(outDir, "..");
3573
3963
  }
3574
3964
  async function maybeRunWithSession(input) {
3575
3965
  const { mode, cwd, out, session } = input;
@@ -3595,7 +3985,7 @@ async function maybeRunWithSession(input) {
3595
3985
  out.step("");
3596
3986
  out.step("Running k6 smoke test...");
3597
3987
  }
3598
- const summaryPath = join4(session.dir, "k6-smoke-summary.json");
3988
+ const summaryPath = join5(session.dir, "k6-smoke-summary.json");
3599
3989
  result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath });
3600
3990
  const digest = await digestK6Summary(summaryPath);
3601
3991
  if (digest) {
@@ -3625,7 +4015,7 @@ async function maybeRunWithSession(input) {
3625
4015
  out.step("");
3626
4016
  out.step("Running k6 load test...");
3627
4017
  }
3628
- const summaryPath = join4(session.dir, "k6-load-summary.json");
4018
+ const summaryPath = join5(session.dir, "k6-load-summary.json");
3629
4019
  result.loadExit = await runK6({ cwd, script: "load.js", summaryPath });
3630
4020
  const digest = await digestK6Summary(summaryPath);
3631
4021
  if (digest) {
@@ -3739,12 +4129,12 @@ ${dim}${TAGLINE}${reset}
3739
4129
  }
3740
4130
 
3741
4131
  // src/program.ts
3742
- var VERSION = true ? "0.2.1" : "0.0.0";
4132
+ var VERSION2 = true ? "0.2.3" : "0.0.0";
3743
4133
  function buildProgram() {
3744
4134
  const program = new Command();
3745
4135
  program.name("loadam").description(
3746
4136
  "Generate test rigs and MCP servers from any API spec. From spec to running rig in 60s."
3747
- ).version(VERSION, "-v, --version", "print version").addHelpText("beforeAll", banner());
4137
+ ).version(VERSION2, "-v, --version", "print version").addHelpText("beforeAll", banner());
3748
4138
  registerInitCommand(program);
3749
4139
  registerAuthCommands(program);
3750
4140
  registerTestCommand(program);
@@ -3753,9 +4143,10 @@ function buildProgram() {
3753
4143
  registerMcpCommand(program);
3754
4144
  registerHistoryCommand(program);
3755
4145
  registerShowCommand(program);
4146
+ registerReportCommand(program);
3756
4147
  registerCleanCommand(program);
3757
4148
  registerCompletionCommand(program);
3758
- registerUpdateCommand(program, VERSION);
4149
+ registerUpdateCommand(program, VERSION2);
3759
4150
  return program;
3760
4151
  }
3761
4152
  export {