loadam 0.2.2 → 0.2.4

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
@@ -282,8 +282,8 @@ var SESSION_SCHEMA_VERSION = 1;
282
282
  var SESSIONS_DIR = "sessions";
283
283
  async function createSession(input) {
284
284
  const startedAt = /* @__PURE__ */ new Date();
285
- const slug = input.slug ? sanitizeSlug(input.slug) : input.command;
286
- const id = `${formatTimestamp(startedAt)}-${slug}`;
285
+ const slug2 = input.slug ? sanitizeSlug(input.slug) : input.command;
286
+ const id = `${formatTimestamp(startedAt)}-${slug2}`;
287
287
  const root = resolve(input.outRoot, SESSIONS_DIR);
288
288
  const dir = resolve(root, id);
289
289
  await mkdir(dir, { recursive: true });
@@ -319,6 +319,9 @@ async function createSession(input) {
319
319
  await writeFile(full, contents);
320
320
  if (!meta.artefacts.includes(relPath)) meta.artefacts.push(relPath);
321
321
  },
322
+ registerArtefact(relPath) {
323
+ if (!meta.artefacts.includes(relPath)) meta.artefacts.push(relPath);
324
+ },
322
325
  async finalize({ exitCode, thresholds, summary }) {
323
326
  const endedAt = /* @__PURE__ */ new Date();
324
327
  meta.endedAt = endedAt.toISOString();
@@ -1606,6 +1609,14 @@ function slugify(s) {
1606
1609
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1607
1610
  }
1608
1611
 
1612
+ // src/util/target.ts
1613
+ function resolveTarget(flag) {
1614
+ if (typeof flag === "string" && flag.length > 0) return flag;
1615
+ const env = process.env.LOADAM_TARGET;
1616
+ if (typeof env === "string" && env.length > 0) return env;
1617
+ return void 0;
1618
+ }
1619
+
1609
1620
  // src/commands/contract.ts
1610
1621
  function registerContractCommand(program) {
1611
1622
  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 +1634,9 @@ async function runContract(spec, opts) {
1623
1634
  parseIR(ir);
1624
1635
  const specSource = await readFile4(specPath, "utf8");
1625
1636
  const examples = Number.parseInt(opts.examples ?? "25", 10);
1637
+ const target = resolveTarget(opts.target);
1626
1638
  const result = compileContract(ir, specSource, {
1627
- baseUrl: opts.target,
1639
+ baseUrl: target,
1628
1640
  examples: Number.isFinite(examples) ? examples : 25
1629
1641
  });
1630
1642
  const outDir = resolve4(opts.output);
@@ -1644,10 +1656,10 @@ async function runContract(spec, opts) {
1644
1656
  specSource,
1645
1657
  ir,
1646
1658
  irJson: JSON.stringify(ir, null, 2),
1647
- target: opts.target ?? null,
1659
+ target: target ?? null,
1648
1660
  envVars: result.envVars ?? [],
1649
1661
  flags: {
1650
- target: opts.target ?? null,
1662
+ target: target ?? null,
1651
1663
  examples
1652
1664
  },
1653
1665
  slug: `contract-${ir.meta.title ?? "run"}`
@@ -1932,10 +1944,14 @@ function severityBadge(s) {
1932
1944
 
1933
1945
  // src/commands/diff.ts
1934
1946
  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));
1947
+ 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
1948
  }
1937
1949
  async function runDiff(spec, opts) {
1938
1950
  const out = makeOutput(!!opts.json);
1951
+ const target = resolveTarget(opts.target);
1952
+ if (!target) {
1953
+ throw new Error("--target is required (or set LOADAM_TARGET env var)");
1954
+ }
1939
1955
  const specPath = resolve5(spec);
1940
1956
  out.start(`Parsing OpenAPI spec: ${specPath}`);
1941
1957
  const specSource = await readFile5(specPath, "utf8");
@@ -1945,9 +1961,9 @@ async function runDiff(spec, opts) {
1945
1961
  const headers = parseKvPairs(opts.header ?? [], ":");
1946
1962
  const pathParams = parseKvPairs(opts.pathParam ?? [], "=");
1947
1963
  const timeoutMs = Number.parseInt(opts.timeoutMs ?? "5000", 10);
1948
- out.start(`Probing ${ir.operations.length} operations on ${opts.target}\u2026`);
1964
+ out.start(`Probing ${ir.operations.length} operations on ${target}\u2026`);
1949
1965
  const { probes, skipped } = await probeOperations(ir, {
1950
- baseUrl: opts.target,
1966
+ baseUrl: target,
1951
1967
  headers,
1952
1968
  pathParams,
1953
1969
  timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : 5e3,
@@ -1962,10 +1978,10 @@ async function runDiff(spec, opts) {
1962
1978
  specSource,
1963
1979
  ir,
1964
1980
  irJson: JSON.stringify(ir, null, 2),
1965
- target: opts.target,
1981
+ target,
1966
1982
  envVars: [],
1967
1983
  flags: {
1968
- target: opts.target,
1984
+ target,
1969
1985
  timeoutMs,
1970
1986
  mutating: !!opts.mutating,
1971
1987
  failOn: opts.failOn ?? "error",
@@ -1976,7 +1992,7 @@ async function runDiff(spec, opts) {
1976
1992
  });
1977
1993
  const report = renderMarkdownReport({
1978
1994
  ir,
1979
- baseUrl: opts.target,
1995
+ baseUrl: target,
1980
1996
  findings,
1981
1997
  skipped
1982
1998
  });
@@ -2016,7 +2032,7 @@ async function runDiff(spec, opts) {
2016
2032
  });
2017
2033
  out.result({
2018
2034
  command: "diff",
2019
- target: opts.target,
2035
+ target,
2020
2036
  probed: probes.length,
2021
2037
  skipped: skipped.length,
2022
2038
  findings: findings.length,
@@ -2625,8 +2641,9 @@ async function runMcp(spec, opts) {
2625
2641
  const ir = await fromOpenApiFile(specPath);
2626
2642
  inferResourceGraph(ir);
2627
2643
  parseIR(ir);
2644
+ const target = resolveTarget(opts.target);
2628
2645
  const result = compileMcp(ir, {
2629
- baseUrl: opts.target,
2646
+ baseUrl: target,
2630
2647
  includeWrites: !!opts.writes,
2631
2648
  exclude: opts.exclude
2632
2649
  });
@@ -2669,13 +2686,23 @@ import { join as join2, resolve as resolve9 } from "path";
2669
2686
  // ../report/dist/index.js
2670
2687
  function renderReport(input) {
2671
2688
  const { meta, loadamVersion } = input;
2672
- const passed = meta.exitCode === 0 && (meta.thresholds?.failed.length ?? 0) === 0;
2689
+ const overall = computeOverall(meta, input.k6Summaries, input.operations);
2673
2690
  const dataPayload = {
2674
2691
  meta,
2675
2692
  k6Summaries: input.k6Summaries ?? null,
2676
2693
  contractFailures: input.contractFailures ?? null,
2694
+ operations: input.operations ?? null,
2677
2695
  loadamVersion
2678
2696
  };
2697
+ const hasEndpoints = (input.operations?.length ?? 0) > 0;
2698
+ const sideSections = [
2699
+ renderThresholds(meta),
2700
+ renderK6Section(input.k6Summaries, hasEndpoints),
2701
+ input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
2702
+ input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
2703
+ renderRunDetails(meta)
2704
+ ].filter((s) => s !== "").join("\n");
2705
+ const mainBlock = renderEndpoints(input.operations, input.k6Summaries);
2679
2706
  return [
2680
2707
  "<!doctype html>",
2681
2708
  `<html lang="en">`,
@@ -2684,40 +2711,109 @@ function renderReport(input) {
2684
2711
  `<meta name="viewport" content="width=device-width,initial-scale=1" />`,
2685
2712
  `<meta name="generator" content="loadam ${esc(loadamVersion)}" />`,
2686
2713
  `<title>${esc(reportTitle(meta))}</title>`,
2687
- `<style>${STYLES}</style>`,
2714
+ `<style>${STYLES}${dynamicTabStyles(input.k6Summaries)}${dynamicEndpointStyles(input.operations)}</style>`,
2688
2715
  "</head>",
2689
2716
  "<body>",
2690
- renderHeader(meta, passed),
2717
+ renderHeader(meta, overall, input.k6Summaries),
2718
+ renderFailureReason(meta, overall, input.k6Summaries, input.contractFailures),
2691
2719
  renderSummary(meta, input.k6Summaries),
2692
- renderThresholds(meta),
2693
- renderK6Metrics(input.k6Summaries),
2694
- input.driftMarkdown ? renderDrift(input.driftMarkdown) : "",
2695
- input.contractFailures && input.contractFailures.length > 0 ? renderContract(input.contractFailures) : "",
2696
- renderRunDetails(meta),
2720
+ // Two-column layout: endpoints fill the main column on the left, while
2721
+ // run-level data (thresholds, k6 results, drift, contract findings, run
2722
+ // details) lives in a sticky sidebar on the right so a reader never has
2723
+ // to scroll past a long endpoint list to see the overall numbers.
2724
+ mainBlock ? `<div class="page-grid"><div class="page-main">${mainBlock}</div><aside class="page-side">${sideSections}</aside></div>` : sideSections,
2697
2725
  renderFooter(meta, loadamVersion),
2698
2726
  `<script type="application/json" id="loadam-data">${escScript(JSON.stringify(dataPayload))}</script>`,
2727
+ DOWNLOAD_SCRIPT,
2699
2728
  "</body>",
2700
2729
  "</html>",
2701
2730
  ""
2702
2731
  ].join("\n");
2703
2732
  }
2704
- function renderHeader(meta, passed) {
2705
- const status = passed ? "PASSED" : "FAILED";
2706
- const cls = passed ? "ok" : "bad";
2733
+ function renderHeader(meta, overall, k6) {
2734
+ const modeLabel = describeModes(meta, k6);
2735
+ const chipText = overall.detail ? `${overall.detail} \xB7 ${overall.label}` : overall.label;
2707
2736
  return `
2737
+ <div class="brand-row">
2738
+ <a class="brand" href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener" title="loadam on GitHub">
2739
+ <svg class="brand-mark" viewBox="0 0 24 24" fill="none" aria-hidden="true">
2740
+ <defs><linearGradient id="loadam-g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f59e0b"/><stop offset="1" stop-color="#ef4444"/></linearGradient></defs>
2741
+ <path d="M3 18 A 9 9 0 0 1 21 18" stroke="url(#loadam-g)" stroke-width="2.5" stroke-linecap="round"/>
2742
+ <path d="M12 18 L17 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
2743
+ <circle cx="12" cy="18" r="1.6" fill="currentColor"/>
2744
+ </svg>
2745
+ <span class="brand-name">load<span class="brand-name-am">am</span></span>
2746
+ </a>
2747
+ <span class="brand-tag">load tests &amp; contract checks from OpenAPI</span>
2748
+ </div>
2708
2749
  <header class="hdr">
2709
2750
  <div class="hdr-left">
2710
- <div class="cmd">${esc(meta.command)}</div>
2751
+ <div class="cmd">${esc(meta.command)}${modeLabel ? ` \xB7 ${esc(modeLabel)}` : ""} <span class="status-chip ${overall.cls}">${esc(chipText)}</span></div>
2711
2752
  <h1>${esc(meta.spec.title ?? "Untitled API")}</h1>
2712
2753
  <div class="sub">${esc(meta.spec.version ?? "")} \xB7 target <code>${esc(meta.target ?? "\u2014")}</code></div>
2713
2754
  </div>
2714
2755
  <div class="hdr-right">
2715
- <span class="badge ${cls}">${status}</span>
2716
2756
  <div class="when">${esc(meta.startedAt)}</div>
2717
2757
  ${typeof meta.durationMs === "number" ? `<div class="dur">${(meta.durationMs / 1e3).toFixed(2)}s</div>` : ""}
2758
+ <div class="actions">
2759
+ <button type="button" class="act" data-loadam-download="html" title="Download this HTML report">\u2B07 Report</button>
2760
+ <button type="button" class="act" data-loadam-download="json" title="Download raw run data as JSON">\u2B07 Data</button>
2761
+ <button type="button" class="act" data-loadam-print title="Print or save as PDF">\u2399 Print</button>
2762
+ </div>
2718
2763
  </div>
2719
2764
  </header>`;
2720
2765
  }
2766
+ function describeModes(meta, k6) {
2767
+ if (meta.command !== "test") return void 0;
2768
+ const labels = k6 ? Object.keys(k6) : [];
2769
+ if (labels.length > 0) return labels.join(" + ");
2770
+ const flagMode = meta.flags.mode;
2771
+ if (typeof flagMode === "string" && flagMode !== "skip") return flagMode;
2772
+ return "generated only";
2773
+ }
2774
+ function renderFailureReason(meta, overall, k6, contractFailures) {
2775
+ if (overall.cls === "ok" || overall.cls === "muted") return "";
2776
+ const reasons = [];
2777
+ const failedThresh = (meta.thresholds?.failed ?? []).filter((n) => !isSentinelThreshold(n));
2778
+ if (failedThresh.length > 0) {
2779
+ const PREVIEW = 3;
2780
+ const head = failedThresh.slice(0, PREVIEW).map((t) => `<code>${esc(t)}</code>`).join(", ");
2781
+ const rest = failedThresh.slice(PREVIEW);
2782
+ const more = rest.length > 0 ? ` <details class="more"><summary>+${rest.length} more</summary>${rest.map((t) => `<code>${esc(t)}</code>`).join(", ")}</details>` : "";
2783
+ reasons.push(
2784
+ `<strong>${failedThresh.length}</strong> threshold${failedThresh.length === 1 ? "" : "s"} failed: ${head}${more}`
2785
+ );
2786
+ }
2787
+ if (k6) {
2788
+ for (const [name, s] of Object.entries(k6)) {
2789
+ const checks = s.root_group?.checks;
2790
+ if (!checks) continue;
2791
+ const entries = Object.values(checks);
2792
+ const failed = entries.filter((c) => c.fails > 0);
2793
+ const totalChecks = entries.length;
2794
+ if (failed.length > 0) {
2795
+ reasons.push(
2796
+ `<strong>${name}</strong>: ${failed.length}/${totalChecks} operation check${failed.length === 1 ? "" : "s"} failed`
2797
+ );
2798
+ }
2799
+ }
2800
+ }
2801
+ if (contractFailures && contractFailures.length > 0) {
2802
+ reasons.push(
2803
+ `<strong>${contractFailures.length}</strong> contract test${contractFailures.length === 1 ? "" : "s"} failed`
2804
+ );
2805
+ }
2806
+ if (reasons.length === 0 && typeof meta.exitCode === "number" && meta.exitCode !== 0) {
2807
+ reasons.push(`Process exited with code <code>${meta.exitCode}</code>`);
2808
+ }
2809
+ if (reasons.length === 0) return "";
2810
+ const heading = overall.cls === "bad" ? "Why this failed" : "Issues to investigate";
2811
+ return `
2812
+ <section class="reason ${overall.cls}">
2813
+ <h2>${heading}</h2>
2814
+ <ul>${reasons.map((r) => `<li>${r}</li>`).join("")}</ul>
2815
+ </section>`;
2816
+ }
2721
2817
  function renderSummary(meta, k6) {
2722
2818
  const cells = [];
2723
2819
  if (meta.summary) {
@@ -2757,45 +2853,454 @@ function renderSummary(meta, k6) {
2757
2853
  }
2758
2854
  function renderThresholds(meta) {
2759
2855
  const t = meta.thresholds;
2760
- if (!t || t.passed.length === 0 && t.failed.length === 0) return "";
2856
+ if (!t) return "";
2857
+ const failed = t.failed.filter((n) => !isSentinelThreshold(n));
2858
+ const passed = t.passed.filter((n) => !isSentinelThreshold(n));
2859
+ if (failed.length === 0 && passed.length === 0) return "";
2860
+ const PREVIEW = 4;
2861
+ const failedHead = failed.slice(0, PREVIEW);
2862
+ const failedRest = failed.slice(PREVIEW);
2863
+ const passedHead = passed.slice(0, PREVIEW);
2864
+ const passedRest = passed.slice(PREVIEW);
2865
+ const summary = [];
2866
+ if (failed.length > 0) summary.push(`<span class="bad">${failed.length} failed</span>`);
2867
+ if (passed.length > 0) summary.push(`<span class="ok">${passed.length} passed</span>`);
2761
2868
  return `
2762
2869
  <section>
2763
- <h2>Thresholds</h2>
2870
+ <h2>Thresholds <span class="muted">(${summary.join(" \xB7 ")})</span></h2>
2764
2871
  <ul class="thr">
2765
- ${t.failed.map((x) => `<li class="bad">\u2717 ${esc(x)}</li>`).join("\n ")}
2766
- ${t.passed.map((x) => `<li class="ok">\u2713 ${esc(x)}</li>`).join("\n ")}
2872
+ ${failedHead.map((x) => `<li class="bad">\u2717 ${esc(x)}</li>`).join("\n ")}
2873
+ ${failedRest.length > 0 ? `<li class="thr-more"><details><summary>+${failedRest.length} more failed</summary><ul class="thr">${failedRest.map((x) => `<li class="bad">\u2717 ${esc(x)}</li>`).join("")}</ul></details></li>` : ""}
2874
+ ${passedHead.map((x) => `<li class="ok">\u2713 ${esc(x)}</li>`).join("\n ")}
2875
+ ${passedRest.length > 0 ? `<li class="thr-more"><details><summary>+${passedRest.length} more passed</summary><ul class="thr">${passedRest.map((x) => `<li class="ok">\u2713 ${esc(x)}</li>`).join("")}</ul></details></li>` : ""}
2767
2876
  </ul>
2768
2877
  </section>`;
2769
2878
  }
2770
- function renderK6Metrics(k6) {
2771
- if (!k6 || Object.keys(k6).length === 0) return "";
2772
- const blocks = [];
2773
- for (const [name, s] of Object.entries(k6)) {
2774
- const metrics = s.metrics ?? {};
2775
- const dur = metrics.http_req_duration?.values;
2776
- if (!dur) continue;
2777
- const rows = [
2778
- ["min", fmtMs(dur.min)],
2779
- ["med", fmtMs(dur.med)],
2780
- ["avg", fmtMs(dur.avg)],
2781
- ["p(90)", fmtMs(dur["p(90)"])],
2782
- ["p(95)", fmtMs(dur["p(95)"])],
2783
- ["p(99)", fmtMs(dur["p(99)"])],
2784
- ["max", fmtMs(dur.max)]
2785
- ];
2786
- blocks.push(`
2787
- <div class="metric-block">
2788
- <h3>${esc(name)} \xB7 http_req_duration</h3>
2879
+ function renderEndpoints(ops, k6) {
2880
+ if (!ops || ops.length === 0) return "";
2881
+ const runs = k6 ? Object.entries(k6) : [];
2882
+ const checkLookup = /* @__PURE__ */ new Map();
2883
+ for (const op of ops) checkLookup.set(op.id, []);
2884
+ for (const [run, summary] of runs) {
2885
+ const checks = summary.root_group?.checks;
2886
+ if (!checks) continue;
2887
+ for (const c of Object.values(checks)) {
2888
+ const opId = c.name.split(/\s+/)[0];
2889
+ if (opId && checkLookup.has(opId)) {
2890
+ checkLookup.get(opId)?.push({ run, check: c });
2891
+ }
2892
+ }
2893
+ }
2894
+ const opMetrics = collectOpMetrics(ops, k6);
2895
+ const groups = /* @__PURE__ */ new Map();
2896
+ for (const op of ops) {
2897
+ const tag = op.tags?.[0] ?? "default";
2898
+ if (!groups.has(tag)) groups.set(tag, []);
2899
+ groups.get(tag)?.push(op);
2900
+ }
2901
+ const opSlug = (op) => slug(`ep-${op.id}`);
2902
+ const sidebar = Array.from(groups.entries()).map(([tag, list]) => {
2903
+ const items = list.map((op, _i) => {
2904
+ const status = endpointStatus(checkLookup.get(op.id) ?? []);
2905
+ const id = opSlug(op);
2906
+ const rateLabel = status.rate === null ? "" : fmtRate(status.rate);
2907
+ const p95 = opMetrics.get(op.id)?.p95;
2908
+ const p95Label = typeof p95 === "number" ? `${Math.round(p95)}ms` : "";
2909
+ return `<label for="${esc(id)}" class="ep-item ${status.cls}" data-state="${status.cls}" title="${esc(op.method.toUpperCase())} ${esc(op.path)}">
2910
+ <span class="ep-item-row">
2911
+ <span class="ep-method ${esc(op.method.toLowerCase())}">${esc(op.method.toUpperCase())}</span>
2912
+ <span class="ep-item-path">${esc(op.path)}</span>
2913
+ <span class="ep-item-dot ${status.cls}" aria-label="${esc(status.label)}"></span>
2914
+ </span>
2915
+ ${rateLabel || p95Label ? `<span class="ep-item-meta">${rateLabel ? `<span class="ep-item-rate ${status.cls}">${esc(rateLabel)}</span> <span class="ep-item-state ${status.cls}">${esc(status.label)}</span>` : ""}${p95Label ? ` <span class="ep-item-p95">p95 ${esc(p95Label)}</span>` : ""}</span>` : ""}
2916
+ </label>`;
2917
+ }).join("\n ");
2918
+ return `<div class="ep-group">
2919
+ <div class="ep-group-h">${esc(tag)}</div>
2920
+ ${items}
2921
+ </div>`;
2922
+ }).join("\n ");
2923
+ const radios = ops.map((op, i) => {
2924
+ const id = opSlug(op);
2925
+ return `<input type="radio" name="loadam-endpoint" id="${esc(id)}" class="ep-radio"${i === 0 ? " checked" : ""}>`;
2926
+ }).join("");
2927
+ const totals = ops.map((op) => endpointStatus(checkLookup.get(op.id) ?? []));
2928
+ const failedCount = totals.filter((t) => t.cls === "bad").length;
2929
+ const flakyCount = totals.filter((t) => t.cls === "warn").length;
2930
+ const passedCount = totals.filter((t) => t.cls === "ok").length;
2931
+ const noDataCount = totals.length - failedCount - flakyCount - passedCount;
2932
+ const parts = [`${ops.length} endpoint${ops.length === 1 ? "" : "s"}`];
2933
+ if (runs.length > 0) {
2934
+ parts.push(`${passedCount} passed`);
2935
+ if (flakyCount > 0) parts.push(`${flakyCount} flaky`);
2936
+ if (failedCount > 0) parts.push(`${failedCount} failed`);
2937
+ if (noDataCount > 0) parts.push(`${noDataCount} no data`);
2938
+ }
2939
+ const headline = parts.join(" \xB7 ");
2940
+ const filterRadios = [
2941
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-all" class="ep-filter-radio" checked>`,
2942
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-bad" class="ep-filter-radio">`,
2943
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-warn" class="ep-filter-radio">`,
2944
+ `<input type="radio" name="loadam-ep-filter" id="ep-filter-ok" class="ep-filter-radio">`
2945
+ ].join("");
2946
+ const filterChips = `<div class="ep-filter">
2947
+ <label for="ep-filter-all" title="Show all endpoints">All ${ops.length}</label>
2948
+ <label for="ep-filter-bad" class="bad" title="Show failed endpoints only">Failed ${failedCount}</label>
2949
+ <label for="ep-filter-warn" class="warn" title="Show flaky endpoints only">Flaky ${flakyCount}</label>
2950
+ <label for="ep-filter-ok" class="ok" title="Show passed endpoints only">Passed ${passedCount}</label>
2951
+ </div>`;
2952
+ const panes = ops.map((op) => {
2953
+ const opChecks = checkLookup.get(op.id) ?? [];
2954
+ const status = endpointStatus(opChecks);
2955
+ const id = opSlug(op);
2956
+ const rateLabel = status.rate === null ? "" : ` <span class="ep-pill-rate">${esc(fmtRate(status.rate))}</span>`;
2957
+ const pill = `<span class="ep-pill ${status.cls}">${esc(status.label)}${rateLabel}</span>`;
2958
+ const runStrip = opChecks.map(({ run, check }) => {
2959
+ const total = check.passes + check.fails;
2960
+ const rate = total > 0 ? check.passes / total : 0;
2961
+ const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
2962
+ const pct = total > 0 ? fmtRate(rate) : "";
2963
+ return `<span class="ep-run ${cls}"><strong>${esc(run)}</strong> ${check.passes}/${total} passed${pct ? ` \xB7 ${pct}` : ""}</span>`;
2964
+ }).join("");
2965
+ const checkRows = opChecks.map(({ run, check }) => {
2966
+ const total = check.passes + check.fails;
2967
+ const rate = total > 0 ? check.passes / total : 0;
2968
+ const cls = rate >= PASS_RATE_OK ? "ok" : rate >= PASS_RATE_WARN ? "warn" : "bad";
2969
+ const pct = total > 0 ? ` <span class="muted">(${fmtRate(rate)})</span>` : "";
2970
+ return `<tr class="${cls}"><th>${esc(run)}</th><td>${esc(check.name)}</td><td>${check.passes}/${total} passed${pct}</td></tr>`;
2971
+ }).join("");
2972
+ const detail = checkRows ? `<table class="kv ep-detail"><thead><tr><th>run</th><th>check</th><th>result</th></tr></thead><tbody>${checkRows}</tbody></table>` : `<p class="hint">No k6 checks recorded for this operation.</p>`;
2973
+ const metricsBlock = renderOpMetricsBlock(opMetrics.get(op.id));
2974
+ const tags = (op.tags ?? []).map((t) => `<span class="ep-tag">${esc(t)}</span>`).join("");
2975
+ return `<div class="ep-pane" data-ep="${esc(id)}">
2976
+ <div class="ep-pane-h">
2977
+ <span class="ep-method ${esc(op.method.toLowerCase())}">${esc(op.method.toUpperCase())}</span>
2978
+ <span class="ep-path"><code>${esc(op.path)}</code></span>
2979
+ ${pill}
2980
+ </div>
2981
+ ${op.summary ? `<p class="ep-pane-sum">${esc(op.summary)}</p>` : ""}
2982
+ ${tags ? `<div class="ep-tags">${tags}</div>` : ""}
2983
+ ${runStrip ? `<div class="ep-runs">${runStrip}</div>` : ""}
2984
+ ${metricsBlock}
2985
+ ${detail}
2986
+ </div>`;
2987
+ }).join("\n ");
2988
+ return `
2989
+ <section class="endpoints">
2990
+ <h2>Endpoints <span class="muted">(${esc(headline)})</span></h2>
2991
+ <p class="hint">Status uses pass-rate tiers: <span class="tier ok">passed \u2265 ${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier warn">flaky ${PASS_RATE_WARN * 100}\u2013${PASS_RATE_OK * 100}%</span> \xB7 <span class="tier bad">failed &lt; ${PASS_RATE_WARN * 100}%</span>.</p>
2992
+ <div class="ep-layout">
2993
+ ${filterRadios}
2994
+ ${radios}
2995
+ <aside class="ep-sidebar">
2996
+ ${filterChips}
2997
+ ${sidebar}
2998
+ </aside>
2999
+ <div class="ep-main">
3000
+ ${panes}
3001
+ </div>
3002
+ </div>
3003
+ </section>`;
3004
+ }
3005
+ var PASS_RATE_OK = 0.99;
3006
+ var PASS_RATE_WARN = 0.95;
3007
+ function endpointStatus(opChecks) {
3008
+ if (opChecks.length === 0) return { cls: "muted", label: "no data", rate: null };
3009
+ let passes = 0;
3010
+ let total = 0;
3011
+ for (const { check } of opChecks) {
3012
+ passes += check.passes;
3013
+ total += check.passes + check.fails;
3014
+ }
3015
+ if (total === 0) return { cls: "muted", label: "no data", rate: null };
3016
+ const rate = passes / total;
3017
+ if (rate >= PASS_RATE_OK) return { cls: "ok", label: "passed", rate };
3018
+ if (rate >= PASS_RATE_WARN) return { cls: "warn", label: "flaky", rate };
3019
+ return { cls: "bad", label: "failed", rate };
3020
+ }
3021
+ function fmtRate(rate) {
3022
+ if (rate === null) return "";
3023
+ const pct = rate * 100;
3024
+ return Number.isInteger(pct) ? `${pct}%` : `${pct.toFixed(1)}%`;
3025
+ }
3026
+ function computeOverall(meta, k6, ops) {
3027
+ const thresholdsFailed = (meta.thresholds?.failed ?? []).some((n) => !isSentinelThreshold(n));
3028
+ if (ops && ops.length > 0 && k6) {
3029
+ const lookup = /* @__PURE__ */ new Map();
3030
+ for (const op of ops) lookup.set(op.id, []);
3031
+ for (const summary of Object.values(k6)) {
3032
+ const checks = summary.root_group?.checks;
3033
+ if (!checks) continue;
3034
+ for (const c of Object.values(checks)) {
3035
+ const opId = c.name.split(/\s+/)[0];
3036
+ if (opId && lookup.has(opId)) lookup.get(opId)?.push(c);
3037
+ }
3038
+ }
3039
+ let okN = 0;
3040
+ let warnN = 0;
3041
+ let badN = 0;
3042
+ let withData = 0;
3043
+ for (const op of ops) {
3044
+ const opChecks = lookup.get(op.id) ?? [];
3045
+ const status = endpointStatus(opChecks.map((check) => ({ run: "", check })));
3046
+ if (status.cls === "ok") {
3047
+ okN++;
3048
+ withData++;
3049
+ } else if (status.cls === "warn") {
3050
+ warnN++;
3051
+ withData++;
3052
+ } else if (status.cls === "bad") {
3053
+ badN++;
3054
+ withData++;
3055
+ }
3056
+ }
3057
+ if (withData > 0) {
3058
+ const detail = `${okN}/${ops.length} endpoints`;
3059
+ if (badN === 0 && warnN === 0) {
3060
+ return { cls: "ok", label: "passed", detail };
3061
+ }
3062
+ const passingRate = (okN + warnN * 0.5) / ops.length;
3063
+ if (badN === 0) return { cls: "warn", label: "flaky", detail };
3064
+ if (passingRate >= PASS_RATE_WARN) return { cls: "warn", label: "partial", detail };
3065
+ if (passingRate >= 0.5) return { cls: "warn", label: "partial", detail };
3066
+ return { cls: "bad", label: "failed", detail };
3067
+ }
3068
+ }
3069
+ if (k6) {
3070
+ let passes = 0;
3071
+ let total = 0;
3072
+ for (const summary of Object.values(k6)) {
3073
+ const checks = summary.root_group?.checks;
3074
+ if (!checks) continue;
3075
+ for (const c of Object.values(checks)) {
3076
+ passes += c.passes;
3077
+ total += c.passes + c.fails;
3078
+ }
3079
+ }
3080
+ if (total > 0) {
3081
+ const rate = passes / total;
3082
+ const detail = fmtRate(rate);
3083
+ if (rate >= PASS_RATE_OK && !thresholdsFailed) {
3084
+ return { cls: "ok", label: "passed", detail };
3085
+ }
3086
+ if (rate >= PASS_RATE_WARN && !thresholdsFailed) {
3087
+ return { cls: "warn", label: "flaky", detail };
3088
+ }
3089
+ return { cls: "bad", label: "failed", detail };
3090
+ }
3091
+ }
3092
+ if (thresholdsFailed || meta.exitCode !== void 0 && meta.exitCode !== 0) {
3093
+ return { cls: "bad", label: "failed", detail: "" };
3094
+ }
3095
+ return { cls: "ok", label: "passed", detail: "" };
3096
+ }
3097
+ function collectOpMetrics(ops, k6) {
3098
+ const out = /* @__PURE__ */ new Map();
3099
+ for (const op of ops) out.set(op.id, { perRun: /* @__PURE__ */ new Map(), p95: null });
3100
+ if (!k6) return out;
3101
+ for (const [runName, summary] of Object.entries(k6)) {
3102
+ const metrics = summary.metrics;
3103
+ if (!metrics) continue;
3104
+ for (const op of ops) {
3105
+ const latencyKey = Object.keys(metrics).find(
3106
+ (k) => k.startsWith("loadam_op_latency{") && k.includes(`name:${op.id}`)
3107
+ );
3108
+ const p95 = latencyKey && typeof metrics[latencyKey]?.values?.["p(95)"] === "number" ? metrics[latencyKey].values["p(95)"] : null;
3109
+ const buckets = {};
3110
+ let total = 0;
3111
+ for (const [k, m] of Object.entries(metrics)) {
3112
+ if (!k.startsWith("loadam_op_status{") || !k.includes(`name:${op.id}`)) continue;
3113
+ const bucket = (k.match(/bucket:([0-9]xx)/) ?? [])[1];
3114
+ if (!bucket) continue;
3115
+ const count = typeof m.values?.count === "number" ? m.values.count : 0;
3116
+ if (count > 0) {
3117
+ buckets[bucket] = count;
3118
+ total += count;
3119
+ }
3120
+ }
3121
+ const entry = out.get(op.id);
3122
+ if (entry) {
3123
+ entry.perRun.set(runName, { p95, buckets, total });
3124
+ if (runName === "load" && p95 !== null) entry.p95 = p95;
3125
+ else if (entry.p95 === null && p95 !== null) entry.p95 = p95;
3126
+ }
3127
+ }
3128
+ }
3129
+ return out;
3130
+ }
3131
+ function isSentinelThreshold(name) {
3132
+ const stripped = name.replace(/^[a-zA-Z0-9_-]+:\s+/, "");
3133
+ return stripped.startsWith("loadam_op_latency") || stripped.startsWith("loadam_op_status");
3134
+ }
3135
+ var BUCKET_ORDER = ["1xx", "2xx", "3xx", "4xx", "5xx"];
3136
+ var BUCKET_CLASS = {
3137
+ "1xx": "muted",
3138
+ "2xx": "ok",
3139
+ "3xx": "ok",
3140
+ "4xx": "bad",
3141
+ "5xx": "bad"
3142
+ };
3143
+ function renderOpMetricsBlock(metrics) {
3144
+ if (!metrics || metrics.perRun.size === 0) return "";
3145
+ const rows = [];
3146
+ for (const [run, m] of metrics.perRun) {
3147
+ if (m.total === 0 && m.p95 === null) continue;
3148
+ const segments = BUCKET_ORDER.filter((b) => (m.buckets[b] ?? 0) > 0).map((b) => {
3149
+ const count = m.buckets[b] ?? 0;
3150
+ const pct = m.total > 0 ? count / m.total * 100 : 0;
3151
+ return `<span class="bkt ${BUCKET_CLASS[b]}" style="width:${pct.toFixed(2)}%" title="${b} \xB7 ${count} req \xB7 ${pct.toFixed(1)}%">${b} ${count}</span>`;
3152
+ }).join("");
3153
+ const p95 = m.p95 !== null ? `${Math.round(m.p95)}ms` : "\u2014";
3154
+ rows.push(`<tr>
3155
+ <th>${esc(run)}</th>
3156
+ <td class="num">${m.total}</td>
3157
+ <td class="num">${esc(p95)}</td>
3158
+ <td><div class="bkt-bar">${segments || `<span class="muted">no data</span>`}</div></td>
3159
+ </tr>`);
3160
+ }
3161
+ if (rows.length === 0) return "";
3162
+ return `<table class="kv ep-metrics">
3163
+ <thead><tr><th>run</th><th>requests</th><th>p95</th><th>status codes</th></tr></thead>
3164
+ <tbody>${rows.join("")}</tbody>
3165
+ </table>`;
3166
+ }
3167
+ function renderK6Section(k6, hasEndpoints) {
3168
+ if (!k6) return "";
3169
+ const entries = Object.entries(k6);
3170
+ if (entries.length === 0) return "";
3171
+ const blocks = entries.map(([name, summary]) => ({ name, html: renderK6Block(name, summary, hasEndpoints) })).filter((b) => b.html !== "");
3172
+ if (blocks.length === 0) return "";
3173
+ if (blocks.length === 1) {
3174
+ return `<section><h2>k6 results</h2>${blocks[0]?.html ?? ""}</section>`;
3175
+ }
3176
+ const tabs = blocks.map((b, i) => {
3177
+ const id = `loadam-tab-${slug(b.name)}`;
3178
+ return `
3179
+ <input type="radio" name="loadam-k6-tab" id="${esc(id)}" class="tab-input"${i === 0 ? " checked" : ""}>`;
3180
+ }).join("");
3181
+ const labels = blocks.map((b) => {
3182
+ const id = `loadam-tab-${slug(b.name)}`;
3183
+ return `<label for="${esc(id)}" class="tab-label">${esc(b.name)}</label>`;
3184
+ }).join("");
3185
+ const panes = blocks.map((b) => `<div class="tab-pane" data-tab="${esc(slug(b.name))}">${b.html}</div>`).join("");
3186
+ return `
3187
+ <section class="tabs">
3188
+ <h2>k6 results <span class="tab-hint">(${blocks.length} runs \u2014 click to switch)</span></h2>${tabs}
3189
+ <div class="tab-bar">${labels}</div>
3190
+ ${panes}
3191
+ </section>`;
3192
+ }
3193
+ function renderK6Block(name, summary, hasEndpoints) {
3194
+ const metrics = summary.metrics ?? {};
3195
+ const dur = metrics.http_req_duration?.values;
3196
+ const reqs = metrics.http_reqs?.values;
3197
+ const failed = metrics.http_req_failed?.values;
3198
+ const headlineCells = [];
3199
+ if (dur && typeof dur["p(95)"] === "number")
3200
+ headlineCells.push({ label: "p95", value: fmtMs(dur["p(95)"]) });
3201
+ if (reqs && typeof reqs.count === "number")
3202
+ headlineCells.push({ label: "requests", value: String(reqs.count) });
3203
+ if (reqs && typeof reqs.rate === "number")
3204
+ headlineCells.push({ label: "rps", value: `${reqs.rate.toFixed(1)}/s` });
3205
+ if (failed && typeof failed.rate === "number")
3206
+ headlineCells.push({ label: "errors", value: `${(failed.rate * 100).toFixed(2)}%` });
3207
+ const headline = headlineCells.length > 0 ? `<div class="cards inner">${headlineCells.map(
3208
+ (c) => `<div class="card"><div class="card-v">${esc(c.value)}</div><div class="card-l">${esc(c.label)}</div></div>`
3209
+ ).join("")}</div>` : "";
3210
+ const latency = dur ? `
3211
+ <h3>http_req_duration</h3>
2789
3212
  <table class="kv">
2790
3213
  <tbody>
2791
- ${rows.map(([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(v)}</td></tr>`).join("\n ")}
3214
+ ${[
3215
+ ["min", fmtMs(dur.min)],
3216
+ ["med", fmtMs(dur.med)],
3217
+ ["avg", fmtMs(dur.avg)],
3218
+ ["p(90)", fmtMs(dur["p(90)"])],
3219
+ ["p(95)", fmtMs(dur["p(95)"])],
3220
+ ["p(99)", fmtMs(dur["p(99)"])],
3221
+ ["max", fmtMs(dur.max)]
3222
+ ].map(([k, v]) => `<tr><th>${esc(k)}</th><td>${esc(v)}</td></tr>`).join("")}
2792
3223
  </tbody>
2793
3224
  </table>
2794
- ${renderPercentileBars(dur)}
2795
- </div>`);
2796
- }
2797
- if (blocks.length === 0) return "";
2798
- return `<section><h2>Latency</h2>${blocks.join("\n")}</section>`;
3225
+ ${renderPercentileBars(dur)}` : "";
3226
+ const checks = summary.root_group?.checks;
3227
+ const checkBlock = checks ? hasEndpoints ? renderChecksSummary(checks) : renderChecks(checks) : "";
3228
+ if (!headline && !latency && !checkBlock) return "";
3229
+ return `
3230
+ <div class="metric-block">
3231
+ ${headline}
3232
+ ${latency}
3233
+ ${checkBlock}
3234
+ </div>`;
3235
+ }
3236
+ function renderChecksSummary(checks) {
3237
+ const entries = Object.values(checks);
3238
+ if (entries.length === 0) return "";
3239
+ let ok = 0;
3240
+ let warn = 0;
3241
+ let bad = 0;
3242
+ let totalPasses = 0;
3243
+ let totalInvocations = 0;
3244
+ for (const c of entries) {
3245
+ const t = c.passes + c.fails;
3246
+ totalPasses += c.passes;
3247
+ totalInvocations += t;
3248
+ const r = t > 0 ? c.passes / t : 0;
3249
+ if (r >= PASS_RATE_OK) ok++;
3250
+ else if (r >= PASS_RATE_WARN) warn++;
3251
+ else bad++;
3252
+ }
3253
+ const cls = bad > 0 ? "bad" : warn > 0 ? "warn" : "ok";
3254
+ const overallRate = totalInvocations > 0 ? totalPasses / totalInvocations : 0;
3255
+ const parts = [`<strong>${ok}</strong>/${entries.length} passed`];
3256
+ if (warn > 0) parts.push(`<span class="warn-text">${warn} flaky</span>`);
3257
+ if (bad > 0) parts.push(`<span class="bad-text">${bad} failed</span>`);
3258
+ return `
3259
+ <div class="chk-line"><span class="chk-tag ${cls}">checks</span> ${parts.join(" \xB7 ")} <span class="muted">\xB7 ${esc(fmtRate(overallRate))} overall</span></div>`;
3260
+ }
3261
+ function renderChecks(checks) {
3262
+ const entries = Object.values(checks);
3263
+ if (entries.length === 0) return "";
3264
+ const failed = entries.filter((c) => c.fails > 0);
3265
+ const passed = entries.length - failed.length;
3266
+ const summaryLine = `${passed}/${entries.length} passed${failed.length > 0 ? ` \xB7 ${failed.length} failed` : ""}`;
3267
+ const row = (c, kind) => {
3268
+ const total = c.passes + c.fails;
3269
+ return `<tr class="${kind}"><th>${esc(c.name)}</th><td><span class="chk-count">${c.passes}<span class="chk-sep">/</span>${total}</span> <span class="chk-word">passed</span></td></tr>`;
3270
+ };
3271
+ const failedRows = failed.map((c) => row(c, "bad")).join("");
3272
+ const passedRows = entries.filter((c) => c.fails === 0).map((c) => row(c, "ok")).join("");
3273
+ return `
3274
+ <h3>Per-operation checks <span class="muted">(${esc(summaryLine)})</span></h3>
3275
+ <p class="hint">Each row shows <em>passed / invoked</em>: how many times this assertion held vs. how many times it ran (one invocation per request).</p>
3276
+ <table class="kv checks">
3277
+ <tbody>${failedRows}${passedRows}</tbody>
3278
+ </table>`;
3279
+ }
3280
+ function slug(s) {
3281
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "tab";
3282
+ }
3283
+ function dynamicEndpointStyles(ops) {
3284
+ if (!ops || ops.length === 0) return "";
3285
+ return ops.map((op) => {
3286
+ const id = slug(`ep-${op.id}`);
3287
+ return `
3288
+ .ep-layout > input#${id}:checked ~ .ep-main .ep-pane[data-ep="${id}"]{display:block}
3289
+ .ep-layout > input#${id}:checked ~ .ep-sidebar label[for="${id}"]{background:var(--card);color:var(--fg);box-shadow:inset 2px 0 0 var(--acc)}`;
3290
+ }).join("");
3291
+ }
3292
+ function dynamicTabStyles(k6) {
3293
+ if (!k6) return "";
3294
+ const names = Object.keys(k6);
3295
+ if (names.length < 2) return "";
3296
+ const rules = names.map((n) => {
3297
+ const s = slug(n);
3298
+ const id = `loadam-tab-${s}`;
3299
+ return `
3300
+ section.tabs > input#${id}:checked ~ .tab-bar label[for="${id}"]{background:var(--card);color:var(--fg);border-color:var(--brd);border-bottom-color:var(--card)}
3301
+ section.tabs > input#${id}:checked ~ .tab-pane[data-tab="${s}"]{display:block}`;
3302
+ }).join("\n");
3303
+ return rules;
2799
3304
  }
2800
3305
  function renderPercentileBars(dur) {
2801
3306
  const max = dur.max ?? Math.max(...Object.values(dur));
@@ -2859,7 +3364,7 @@ function renderRunDetails(meta) {
2859
3364
  function renderFooter(meta, version) {
2860
3365
  return `
2861
3366
  <footer>
2862
- Generated by <a href="https://github.com/anonxhash/loadam">loadam ${esc(version)}</a> \xB7
3367
+ Generated by <a href="https://github.com/DesmondSanctity/loadam" target="_blank" rel="noopener">loadam ${esc(version)}</a> \xB7
2863
3368
  schema v${meta.schemaVersion} \xB7
2864
3369
  IR <code>${esc(meta.irDigest.slice(0, 12))}</code>
2865
3370
  </footer>`;
@@ -2883,18 +3388,20 @@ var STYLES = `
2883
3388
  :root{
2884
3389
  --bg:#fafafa;--fg:#111;--mut:#666;--brd:#e5e5e5;--card:#fff;
2885
3390
  --ok:#15803d;--ok-bg:#dcfce7;--bad:#b91c1c;--bad-bg:#fee2e2;
3391
+ --warn:#a16207;--warn-bg:#fef3c7;
2886
3392
  --acc:#2563eb;--bar:#3b82f6;--code:#f4f4f5;
2887
3393
  }
2888
3394
  @media (prefers-color-scheme:dark){
2889
3395
  :root{
2890
3396
  --bg:#0a0a0a;--fg:#f5f5f5;--mut:#a1a1aa;--brd:#27272a;--card:#18181b;
2891
3397
  --ok:#86efac;--ok-bg:#14532d;--bad:#fca5a5;--bad-bg:#7f1d1d;
3398
+ --warn:#fcd34d;--warn-bg:#78350f;
2892
3399
  --acc:#60a5fa;--bar:#3b82f6;--code:#27272a;
2893
3400
  }
2894
3401
  }
2895
3402
  *{box-sizing:border-box}
2896
3403
  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}
2897
- body{max-width:960px;margin:0 auto;padding:24px 20px 60px}
3404
+ body{max-width:1200px;margin:0 auto;padding:24px 20px 60px}
2898
3405
  h1{font-size:20px;margin:0 0 4px}
2899
3406
  h2{font-size:15px;margin:24px 0 12px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
2900
3407
  h3{font-size:14px;margin:16px 0 8px;font-weight:600}
@@ -2902,11 +3409,23 @@ code{font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--
2902
3409
  a{color:var(--acc);text-decoration:none}
2903
3410
  a:hover{text-decoration:underline}
2904
3411
  section{margin-top:8px}
3412
+ .brand-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding-bottom:14px;margin-bottom:16px;border-bottom:1px solid var(--brd)}
3413
+ .brand{display:inline-flex;align-items:center;gap:8px;color:var(--fg);text-decoration:none;font-weight:700;font-size:16px;letter-spacing:-0.01em;line-height:1}
3414
+ .brand:hover{text-decoration:none;opacity:.8}
3415
+ .brand svg.brand-mark{width:22px;height:22px;display:block;color:var(--fg)}
3416
+ .brand-name{font-family:ui-sans-serif,system-ui,-apple-system,sans-serif}
3417
+ .brand-name-am{background:linear-gradient(135deg,#f59e0b,#ef4444);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;color:transparent}
3418
+ .brand-tag{font-size:11px;color:var(--mut);text-transform:uppercase;letter-spacing:.08em;font-weight:500}
3419
+ @media (max-width:600px){.brand-tag{display:none}}
2905
3420
  .hdr{display:flex;justify-content:space-between;align-items:flex-start;gap:24px;padding-bottom:16px;border-bottom:1px solid var(--brd)}
2906
- .hdr-left .cmd{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:600}
3421
+ .hdr-left .cmd{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:600;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
2907
3422
  .hdr-left .sub{color:var(--mut);font-size:13px;margin-top:4px}
2908
3423
  .hdr-right{text-align:right}
2909
- .hdr-right .when,.hdr-right .dur{font-size:12px;color:var(--mut);margin-top:4px;font-variant-numeric:tabular-nums}
3424
+ .hdr-right .when,.hdr-right .dur{font-size:12px;color:var(--mut);margin-top:2px;font-variant-numeric:tabular-nums}
3425
+ .status-chip{display:inline-block;padding:2px 8px;border-radius:3px;font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase}
3426
+ .status-chip.ok{background:var(--ok-bg);color:var(--ok)}
3427
+ .status-chip.warn{background:var(--warn-bg);color:var(--warn)}
3428
+ .status-chip.bad{background:var(--bad-bg);color:var(--bad)}
2910
3429
  .badge{display:inline-block;padding:4px 10px;border-radius:4px;font-size:11px;font-weight:700;letter-spacing:.06em}
2911
3430
  .badge.ok{background:var(--ok-bg);color:var(--ok)}
2912
3431
  .badge.bad{background:var(--bad-bg);color:var(--bad)}
@@ -2933,11 +3452,194 @@ table.kv th{font-weight:500;color:var(--mut);width:160px;white-space:nowrap}
2933
3452
  .failures li{background:var(--bad-bg);border:1px solid var(--bad);border-radius:4px;padding:8px 12px;margin-bottom:6px}
2934
3453
  .failures .ftest{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;font-weight:600}
2935
3454
  .failures pre{margin:6px 0 0;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap}
3455
+ .reason{background:var(--bad-bg);border:1px solid var(--bad);border-radius:6px;padding:12px 16px;margin-top:20px}
3456
+ .reason.warn{background:var(--warn-bg);border-color:var(--warn)}
3457
+ .reason h2{margin:0 0 8px;color:var(--bad);text-transform:uppercase;letter-spacing:.04em;font-size:12px}
3458
+ .reason.warn h2{color:var(--warn)}
3459
+ .reason ul{margin:0;padding:0 0 0 18px}
3460
+ .reason li{margin:4px 0;font-size:13px}
3461
+ .reason details.more{display:inline;margin-left:6px}
3462
+ .reason details.more summary{display:inline;cursor:pointer;color:var(--mut);font-size:12px;list-style:none}
3463
+ .reason details.more summary::-webkit-details-marker{display:none}
3464
+ .reason details.more summary:hover{color:var(--fg)}
3465
+ .reason details.more[open] summary{display:block;margin-bottom:4px}
3466
+ .thr li.thr-more{list-style:none;margin-left:-18px}
3467
+ .thr li.thr-more details summary{cursor:pointer;font-size:11px;color:var(--mut);padding:2px 0}
3468
+ .thr li.thr-more details summary:hover{color:var(--fg)}
3469
+ .thr li.thr-more details ul.thr{margin-top:4px;padding-left:14px}
3470
+ .reason code{background:rgba(0,0,0,.12)}
3471
+ .muted{color:var(--mut);font-weight:400;font-size:11px}
3472
+ table.checks tr.bad th,table.checks tr.bad td{color:var(--bad);background:var(--bad-bg)}
3473
+ table.checks tr.warn th,table.checks tr.warn td{color:var(--warn);background:var(--warn-bg)}
3474
+ table.checks tr.ok th{color:var(--mut)}
3475
+ table.checks tr.ok td{color:var(--ok)}
3476
+ .ep-detail tr.bad th,.ep-detail tr.bad td{color:var(--bad);background:var(--bad-bg)}
3477
+ .ep-detail tr.warn th,.ep-detail tr.warn td{color:var(--warn);background:var(--warn-bg)}
3478
+ .ep-detail tr.ok th{color:var(--mut)}
3479
+ .ep-detail tr.ok td{color:var(--ok)}
3480
+ .tier{display:inline-block;padding:1px 7px;border-radius:9px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}
3481
+ .tier.ok{background:var(--ok-bg);color:var(--ok)}
3482
+ .tier.warn{background:var(--warn-bg);color:var(--warn)}
3483
+ .tier.bad{background:var(--bad-bg);color:var(--bad)}
3484
+ .cards.inner{margin-top:0;margin-bottom:12px;grid-template-columns:repeat(auto-fit,minmax(110px,1fr))}
3485
+ section.tabs > input.tab-input{position:absolute;opacity:0;pointer-events:none}
3486
+ section.tabs > .tab-bar{display:flex;gap:0;border-bottom:1px solid var(--brd);margin-top:4px}
3487
+ section.tabs > .tab-bar .tab-label{padding:8px 16px;cursor:pointer;font-size:13px;font-weight:500;color:var(--mut);border:1px solid transparent;border-bottom:none;border-radius:4px 4px 0 0;margin-bottom:-1px;user-select:none}
3488
+ section.tabs > .tab-bar .tab-label:hover{color:var(--fg)}
3489
+ section.tabs > .tab-pane{display:none;padding-top:14px}
3490
+ section.tabs > h2 .tab-hint{font-size:11px;font-weight:400;color:var(--mut);text-transform:none;letter-spacing:0;margin-left:6px}
3491
+ .actions{display:flex;gap:6px;margin-top:8px;justify-content:flex-end;flex-wrap:wrap}
3492
+ .act{font:inherit;font-size:11px;padding:4px 9px;border:1px solid var(--brd);background:var(--card);color:var(--fg);border-radius:4px;cursor:pointer;letter-spacing:.02em}
3493
+ .act:hover{background:var(--code);border-color:var(--mut)}
3494
+ .hint{color:var(--mut);font-size:12px;margin:4px 0 8px}
3495
+ .page-grid{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:24px;align-items:start;margin-top:20px}
3496
+ .page-main{min-width:0}
3497
+ .page-side{position:sticky;top:16px;max-height:calc(100vh - 32px);overflow-y:auto;font-size:13px;padding-right:4px}
3498
+ .page-side h2{margin-top:8px;font-size:11px}
3499
+ .page-side section{margin-top:16px}
3500
+ .page-side section:first-child{margin-top:0}
3501
+ .page-side .cards{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
3502
+ .page-side .card{padding:8px 10px}
3503
+ .page-side .card-v{font-size:15px}
3504
+ .page-side .metric-block{padding:10px 12px}
3505
+ .page-side table.kv th{width:90px;font-size:12px}
3506
+ .page-side table.kv td{font-size:12px}
3507
+ .page-side section.tabs > .tab-bar .tab-label{padding:6px 10px;font-size:12px}
3508
+ .page-side .bar-row{grid-template-columns:48px 1fr 64px}
3509
+ .page-side .bars{margin-top:6px}
3510
+ @media (max-width:900px){
3511
+ .page-grid{grid-template-columns:1fr;gap:0}
3512
+ .page-side{position:static;max-height:none;padding-right:0}
3513
+ }
3514
+ .chk-count{font-variant-numeric:tabular-nums;font-weight:600}
3515
+ .chk-sep{opacity:.5;margin:0 1px}
3516
+ .chk-word{color:var(--mut);font-size:12px;margin-left:2px}
3517
+ .chk-line{font-size:12px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:8px;padding:6px 8px;background:var(--code);border-radius:4px}
3518
+ .chk-tag{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.04em;color:var(--mut);padding:2px 6px;border-radius:3px;background:var(--card)}
3519
+ .chk-tag.ok{color:var(--ok)}
3520
+ .chk-tag.warn{color:var(--warn);background:var(--warn-bg)}
3521
+ .chk-tag.bad{color:var(--bad);background:var(--bad-bg)}
3522
+ .bad-text{color:var(--bad);font-weight:600}
3523
+ .warn-text{color:var(--warn);font-weight:600}
3524
+ section.endpoints{margin-top:24px}
3525
+ .ep-layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:0;border:1px solid var(--brd);border-radius:6px;background:var(--card);overflow:hidden;min-height:520px}
3526
+ .ep-layout > .ep-radio{position:absolute;opacity:0;pointer-events:none}
3527
+ .ep-sidebar{border-right:1px solid var(--brd);background:var(--bg);max-height:820px;overflow-y:auto;padding:6px 0}
3528
+ .ep-group{padding:6px 0}
3529
+ .ep-group + .ep-group{border-top:1px solid var(--brd)}
3530
+ .ep-group-h{font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);padding:4px 12px;font-weight:600}
3531
+ .ep-item{display:flex;flex-direction:column;gap:2px;padding:7px 12px;cursor:pointer;font-size:12px;border-left:2px solid transparent;color:var(--mut);user-select:none}
3532
+ .ep-item:hover{background:var(--code);color:var(--fg)}
3533
+ .ep-item-row{display:flex;align-items:center;gap:8px;min-width:0}
3534
+ .ep-item-path{font:12px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
3535
+ .ep-item-meta{display:flex;align-items:center;gap:6px;padding-left:62px;font-size:10px}
3536
+ .ep-item-state{text-transform:uppercase;letter-spacing:.04em;font-weight:600;font-size:9px;opacity:.85}
3537
+ .ep-item-state.ok{color:var(--ok)}
3538
+ .ep-item-state.warn{color:var(--warn)}
3539
+ .ep-item-state.bad{color:var(--bad)}
3540
+ .ep-item-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;background:var(--brd)}
3541
+ .ep-item-dot.ok{background:var(--ok)}
3542
+ .ep-item-dot.warn{background:var(--warn)}
3543
+ .ep-item-dot.bad{background:var(--bad)}
3544
+ .ep-item-dot.muted{background:var(--mut);opacity:.5}
3545
+ .ep-item-rate{font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--mut);font-variant-numeric:tabular-nums;flex-shrink:0}
3546
+ .ep-item-rate.ok{color:var(--ok)}
3547
+ .ep-item-rate.warn{color:var(--warn)}
3548
+ .ep-item-rate.bad{color:var(--bad)}
3549
+ .ep-item-p95{font:10px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--mut);font-variant-numeric:tabular-nums;margin-left:auto;flex-shrink:0;opacity:.85}
3550
+ .ep-main{padding:18px 20px;overflow-x:auto}
3551
+ .ep-pane{display:none}
3552
+ .ep-pane-h{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:6px}
3553
+ .ep-pane-sum{margin:4px 0 12px;color:var(--mut);font-size:13px}
3554
+ .ep-method{display:inline-block;min-width:54px;text-align:center;padding:3px 8px;border-radius:3px;font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:700;letter-spacing:.04em;color:#fff;background:#6b7280}
3555
+ .ep-method.get{background:#2563eb}
3556
+ .ep-method.post{background:#15803d}
3557
+ .ep-method.put{background:#d97706}
3558
+ .ep-method.patch{background:#7c3aed}
3559
+ .ep-method.delete{background:#b91c1c}
3560
+ .ep-path{font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:600}
3561
+ .ep-path code{background:transparent;padding:0;font-size:13px}
3562
+ .ep-pill{font-size:10px;padding:2px 8px;border-radius:10px;font-weight:600;text-transform:uppercase;letter-spacing:.05em}
3563
+ .ep-pill.ok{background:var(--ok-bg);color:var(--ok)}
3564
+ .ep-pill.warn{background:var(--warn-bg);color:var(--warn)}
3565
+ .ep-pill.bad{background:var(--bad-bg);color:var(--bad)}
3566
+ .ep-pill.muted{background:var(--code);color:var(--mut)}
3567
+ .ep-pill-rate{font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:none;letter-spacing:0;font-weight:500;margin-left:4px;opacity:.85}
3568
+ .ep-runs{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0}
3569
+ .ep-run{font-size:12px;padding:3px 8px;border-radius:3px;background:var(--code);font-variant-numeric:tabular-nums}
3570
+ .ep-run.bad{background:var(--bad-bg);color:var(--bad)}
3571
+ .ep-run.warn{background:var(--warn-bg);color:var(--warn)}
3572
+ .ep-run.ok{background:var(--ok-bg);color:var(--ok)}
3573
+ .ep-run strong{font-weight:600;margin-right:4px;text-transform:uppercase;letter-spacing:.04em;font-size:11px}
3574
+ .ep-tags{display:flex;gap:4px;flex-wrap:wrap;margin-top:4px}
3575
+ .ep-tag{font-size:10px;padding:2px 6px;background:var(--code);color:var(--mut);border-radius:3px;text-transform:uppercase;letter-spacing:.04em}
3576
+ .ep-detail{margin-top:10px}
3577
+ .ep-detail th:first-child{width:60px;text-transform:uppercase;font-size:10px;letter-spacing:.04em}
3578
+ .ep-metrics{margin:10px 0 4px;font-size:12px}
3579
+ .ep-metrics th{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
3580
+ .ep-metrics td.num{font-variant-numeric:tabular-nums;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
3581
+ .bkt-bar{display:flex;height:14px;border-radius:3px;overflow:hidden;background:var(--code);font-size:10px;line-height:14px;font-variant-numeric:tabular-nums;min-width:160px}
3582
+ .bkt{display:inline-block;text-align:center;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:clip;padding:0 4px;letter-spacing:.02em;font-weight:600}
3583
+ .bkt.ok{background:var(--ok)}
3584
+ .bkt.warn{background:var(--warn)}
3585
+ .bkt.bad{background:var(--bad)}
3586
+ .bkt.muted{background:var(--mut);opacity:.6}
3587
+ .ep-filter{display:flex;gap:4px;padding:8px 10px;border-bottom:1px solid var(--brd);background:var(--card)}
3588
+ .ep-layout > .ep-filter-radio{position:absolute;opacity:0;pointer-events:none}
3589
+ .ep-filter label{font-size:10px;text-transform:uppercase;letter-spacing:.05em;font-weight:600;padding:4px 8px;border-radius:3px;cursor:pointer;color:var(--mut);background:var(--code);user-select:none}
3590
+ .ep-filter label:hover{color:var(--fg)}
3591
+ .ep-filter label.ok{color:var(--ok)}
3592
+ .ep-filter label.warn{color:var(--warn)}
3593
+ .ep-filter label.bad{color:var(--bad)}
3594
+ /* Active chip + matching item visibility \u2014 pure CSS via :checked ~ siblings. */
3595
+ .ep-layout > input#ep-filter-all:checked ~ .ep-sidebar label[for="ep-filter-all"]{background:var(--acc);color:#fff}
3596
+ .ep-layout > input#ep-filter-bad:checked ~ .ep-sidebar label[for="ep-filter-bad"]{background:var(--bad);color:#fff}
3597
+ .ep-layout > input#ep-filter-warn:checked ~ .ep-sidebar label[for="ep-filter-warn"]{background:var(--warn);color:#fff}
3598
+ .ep-layout > input#ep-filter-ok:checked ~ .ep-sidebar label[for="ep-filter-ok"]{background:var(--ok);color:#fff}
3599
+ .ep-layout > input#ep-filter-bad:checked ~ .ep-sidebar .ep-item:not([data-state="bad"]){display:none}
3600
+ .ep-layout > input#ep-filter-warn:checked ~ .ep-sidebar .ep-item:not([data-state="warn"]){display:none}
3601
+ .ep-layout > input#ep-filter-ok:checked ~ .ep-sidebar .ep-item:not([data-state="ok"]){display:none}
3602
+ /* Hide group headers whose children are all filtered out. Cheap heuristic:
3603
+ when a non-"All" filter is active and a group has no children matching
3604
+ its tier, we leave the header visible \u2014 minor visual noise but no JS. */
3605
+ @media (max-width:720px){
3606
+ .ep-layout{grid-template-columns:1fr;min-height:0}
3607
+ .ep-sidebar{max-height:240px;border-right:none;border-bottom:1px solid var(--brd)}
3608
+ }
3609
+ @media print{
3610
+ .actions{display:none}
3611
+ .ep-layout{grid-template-columns:1fr;border:none}
3612
+ .ep-sidebar{display:none}
3613
+ .ep-pane{display:block!important;break-inside:avoid;border-bottom:1px solid var(--brd);padding-bottom:12px;margin-bottom:12px}
3614
+ }
2936
3615
  footer{margin-top:40px;padding-top:16px;border-top:1px solid var(--brd);color:var(--mut);font-size:12px;text-align:center}
2937
3616
  `;
3617
+ var DOWNLOAD_SCRIPT = `<script>(function(){
3618
+ var d=document,el=d.getElementById('loadam-data');
3619
+ if(!el)return;
3620
+ var data;try{data=JSON.parse(el.textContent||'{}')}catch(e){return}
3621
+ var name=(data&&data.meta&&data.meta.id)||'loadam-report';
3622
+ function dl(blob,filename){
3623
+ var url=URL.createObjectURL(blob);
3624
+ var a=d.createElement('a');a.href=url;a.download=filename;
3625
+ d.body.appendChild(a);a.click();d.body.removeChild(a);
3626
+ setTimeout(function(){URL.revokeObjectURL(url)},1000);
3627
+ }
3628
+ var bH=d.querySelector('[data-loadam-download="html"]');
3629
+ if(bH)bH.addEventListener('click',function(){
3630
+ var html='<!doctype html>\\n'+d.documentElement.outerHTML;
3631
+ dl(new Blob([html],{type:'text/html'}),name+'.html');
3632
+ });
3633
+ var bJ=d.querySelector('[data-loadam-download="json"]');
3634
+ if(bJ)bJ.addEventListener('click',function(){
3635
+ dl(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}),name+'.json');
3636
+ });
3637
+ var bP=d.querySelector('[data-loadam-print]');
3638
+ if(bP)bP.addEventListener('click',function(){window.print()});
3639
+ })();</script>`;
2938
3640
 
2939
3641
  // src/commands/report.ts
2940
- var VERSION = true ? "0.2.2" : "0.0.0";
3642
+ var VERSION = true ? "0.2.4" : "0.0.0";
2941
3643
  function registerReportCommand(program) {
2942
3644
  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));
2943
3645
  }
@@ -2963,10 +3665,25 @@ async function runReport(id, opts) {
2963
3665
  } catch {
2964
3666
  }
2965
3667
  }
3668
+ let operations;
3669
+ try {
3670
+ const ir = JSON.parse(await readFile6(join2(dir, "ir.json"), "utf8"));
3671
+ if (Array.isArray(ir.operations) && ir.operations.length > 0) {
3672
+ operations = ir.operations.map((o) => ({
3673
+ id: o.id,
3674
+ method: o.method,
3675
+ path: o.path,
3676
+ summary: o.summary,
3677
+ tags: o.tags
3678
+ }));
3679
+ }
3680
+ } catch {
3681
+ }
2966
3682
  const html = renderReport({
2967
3683
  meta,
2968
3684
  k6Summaries: Object.keys(k6Summaries).length > 0 ? k6Summaries : void 0,
2969
3685
  driftMarkdown,
3686
+ operations,
2970
3687
  loadamVersion: VERSION
2971
3688
  });
2972
3689
  const outPath = opts.output ? resolve9(opts.output) : join2(dir, "report.html");
@@ -3004,7 +3721,79 @@ async function openInBrowser(path) {
3004
3721
 
3005
3722
  // src/commands/show.ts
3006
3723
  import { readFile as readFile7, readdir as readdir2 } from "fs/promises";
3007
- import { join as join3, resolve as resolve10 } from "path";
3724
+ import { join as join4, resolve as resolve10 } from "path";
3725
+
3726
+ // src/util/k6.ts
3727
+ import { spawn as spawn2 } from "child_process";
3728
+ import { constants, access } from "fs/promises";
3729
+ import { delimiter, join as join3 } from "path";
3730
+ async function findK6Binary() {
3731
+ const path = process.env.PATH ?? "";
3732
+ const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3733
+ for (const dir of path.split(delimiter)) {
3734
+ if (!dir) continue;
3735
+ for (const ext of exts) {
3736
+ const candidate = join3(dir, `k6${ext}`);
3737
+ try {
3738
+ await access(candidate, constants.X_OK);
3739
+ return candidate;
3740
+ } catch {
3741
+ }
3742
+ }
3743
+ }
3744
+ return null;
3745
+ }
3746
+ async function runK6(opts) {
3747
+ const bin = await findK6Binary();
3748
+ if (!bin) {
3749
+ throw new Error(
3750
+ "k6 not found on PATH. Install it from https://grafana.com/docs/k6/latest/set-up/install-k6/ and try again."
3751
+ );
3752
+ }
3753
+ const args = ["run"];
3754
+ if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3755
+ args.push(...opts.args ?? [], opts.script);
3756
+ return await new Promise((resolveExit, reject) => {
3757
+ const child = spawn2(bin, args, {
3758
+ cwd: opts.cwd,
3759
+ env: { ...process.env, ...opts.env },
3760
+ stdio: "inherit"
3761
+ });
3762
+ child.on("error", reject);
3763
+ child.on("close", (code) => resolveExit(code ?? 0));
3764
+ });
3765
+ }
3766
+ async function digestK6Summary(path) {
3767
+ try {
3768
+ const { readFile: readFile10 } = await import("fs/promises");
3769
+ const text = await readFile10(path, "utf8");
3770
+ const data = JSON.parse(text);
3771
+ const passed = [];
3772
+ const failed = [];
3773
+ const metrics = {};
3774
+ for (const [name, m] of Object.entries(data.metrics ?? {})) {
3775
+ if (name.startsWith("loadam_op_latency") || name.startsWith("loadam_op_status")) {
3776
+ continue;
3777
+ }
3778
+ if (m.thresholds) {
3779
+ for (const [expr, info] of Object.entries(m.thresholds)) {
3780
+ (info.ok ? passed : failed).push(`${name}: ${expr}`);
3781
+ }
3782
+ }
3783
+ if (m.values) {
3784
+ if (typeof m.values["p(95)"] === "number") metrics[`${name}.p95`] = m.values["p(95)"];
3785
+ if (typeof m.values.rate === "number") metrics[`${name}.rate`] = m.values.rate;
3786
+ if (typeof m.values.count === "number") metrics[`${name}.count`] = m.values.count;
3787
+ if (typeof m.values.avg === "number") metrics[`${name}.avg`] = m.values.avg;
3788
+ }
3789
+ }
3790
+ return { passed, failed, metrics };
3791
+ } catch {
3792
+ return null;
3793
+ }
3794
+ }
3795
+
3796
+ // src/commands/show.ts
3008
3797
  function registerShowCommand(program) {
3009
3798
  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));
3010
3799
  }
@@ -3012,7 +3801,7 @@ async function runShow(id, opts) {
3012
3801
  const out = makeOutput(!!opts.json);
3013
3802
  const root = resolve10(opts.root);
3014
3803
  const meta = await resolveSessionId(root, id);
3015
- const dir = join3(root, "sessions", meta.id);
3804
+ const dir = join4(root, "sessions", meta.id);
3016
3805
  if (out.json) {
3017
3806
  out.result({ ...meta });
3018
3807
  return;
@@ -3050,17 +3839,49 @@ async function runShow(id, opts) {
3050
3839
  }
3051
3840
  if (meta.command === "diff") {
3052
3841
  try {
3053
- const drift = await readFile7(join3(dir, "drift.md"), "utf8");
3842
+ const drift = await readFile7(join4(dir, "drift.md"), "utf8");
3054
3843
  out.info("");
3055
3844
  out.info("\u2500\u2500\u2500\u2500 drift.md \u2500\u2500\u2500\u2500");
3056
3845
  process.stdout.write(drift);
3057
3846
  } catch {
3058
3847
  }
3059
3848
  }
3849
+ if (meta.command === "test") {
3850
+ try {
3851
+ const entries = await readdir2(dir);
3852
+ const summaryFile = entries.find((e) => /^k6-.*-summary\.json$/.test(e));
3853
+ if (summaryFile) {
3854
+ const digest = await digestK6Summary(join4(dir, summaryFile));
3855
+ if (digest) {
3856
+ out.info("");
3857
+ out.info(`\u2500\u2500\u2500\u2500 ${summaryFile} \u2500\u2500\u2500\u2500`);
3858
+ const headline = [];
3859
+ const dur = digest.metrics["http_req_duration.p95"];
3860
+ const cnt = digest.metrics["http_reqs.count"];
3861
+ const rate = digest.metrics["http_reqs.rate"];
3862
+ const failRate = digest.metrics["http_req_failed.rate"];
3863
+ if (typeof dur === "number")
3864
+ headline.push(["http_req_duration p95", `${dur.toFixed(1)}ms`]);
3865
+ if (typeof cnt === "number") headline.push(["http_reqs count", `${cnt}`]);
3866
+ if (typeof rate === "number") headline.push(["http_reqs rate", `${rate.toFixed(2)}/s`]);
3867
+ if (typeof failRate === "number")
3868
+ headline.push(["http_req_failed rate", `${(failRate * 100).toFixed(2)}%`]);
3869
+ for (const [k, v] of headline) out.info(` ${k}: ${v}`);
3870
+ if (digest.passed.length || digest.failed.length) {
3871
+ out.info(
3872
+ ` Thresholds: ${digest.passed.length} passed \xB7 ${digest.failed.length} failed`
3873
+ );
3874
+ for (const t of digest.failed) out.info(` \u2717 ${t}`);
3875
+ }
3876
+ }
3877
+ }
3878
+ } catch {
3879
+ }
3880
+ }
3060
3881
  }
3061
3882
 
3062
3883
  // src/commands/test.ts
3063
- import { mkdir as mkdir4, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
3884
+ import { mkdir as mkdir4, readFile as readFile9, stat as stat2, writeFile as writeFile8 } from "fs/promises";
3064
3885
  import { dirname as dirname3, join as join5, resolve as resolve12 } from "path";
3065
3886
 
3066
3887
  // ../data/dist/index.js
@@ -3388,9 +4209,21 @@ function emitFlowJs(ctx) {
3388
4209
  return `// AUTO-GENERATED by @loadam/test-k6
3389
4210
  import http from 'k6/http';
3390
4211
  import { check } from 'k6';
4212
+ import { Counter, Trend } from 'k6/metrics';
3391
4213
  import { SharedArray } from 'k6/data';
3392
4214
  import { authHeaders, buildUrl } from './config.js';
3393
4215
 
4216
+ const opLatency = new Trend('loadam_op_latency', true);
4217
+ const opStatus = new Counter('loadam_op_status');
4218
+
4219
+ function __statusBucket(s) {
4220
+ if (s < 200) return '1xx';
4221
+ if (s < 300) return '2xx';
4222
+ if (s < 400) return '3xx';
4223
+ if (s < 500) return '4xx';
4224
+ return '5xx';
4225
+ }
4226
+
3394
4227
  const fixtures = new SharedArray('loadam-fixtures', function () {
3395
4228
  return [JSON.parse(open('./fixtures.json'))];
3396
4229
  });
@@ -3464,6 +4297,8 @@ function emitOpCall(op, _index) {
3464
4297
  ${pathParamLines.join("\n")}
3465
4298
  const resp = ${requestLine};
3466
4299
  check(resp, { ${JSON.stringify(`${op.id} 2xx-3xx`)}: (r) => r.status >= 200 && r.status < 400 });
4300
+ opLatency.add(resp.timings.duration, { name: ${opIdLit} });
4301
+ opStatus.add(1, { name: ${opIdLit}, bucket: __statusBucket(resp.status) });
3467
4302
  ${captureId}
3468
4303
  }
3469
4304
  `;
@@ -3486,7 +4321,7 @@ function emitRequestCall(op, headersExpr, pathParamObj, queryParamObj) {
3486
4321
  function safeIdent(s) {
3487
4322
  return s.replace(/[^A-Za-z0-9_]/g, "_");
3488
4323
  }
3489
- function emitSmokeJs() {
4324
+ function emitSmokeJs(ctx) {
3490
4325
  return `// AUTO-GENERATED by @loadam/test-k6 \u2014 smoke test
3491
4326
  import { runFlow } from './flow.js';
3492
4327
 
@@ -3497,7 +4332,7 @@ export const options = {
3497
4332
  checks: ['rate>=0.95'],
3498
4333
  http_req_failed: ['rate<0.05'],
3499
4334
  http_req_duration: ['p(95)<2000'],
3500
- },
4335
+ ${emitOpThresholds(ctx)} },
3501
4336
  };
3502
4337
 
3503
4338
  export default function () {
@@ -3505,7 +4340,7 @@ export default function () {
3505
4340
  }
3506
4341
  `;
3507
4342
  }
3508
- function emitLoadJs() {
4343
+ function emitLoadJs(ctx) {
3509
4344
  return `// AUTO-GENERATED by @loadam/test-k6 \u2014 load test
3510
4345
  import { runFlow } from './flow.js';
3511
4346
 
@@ -3519,7 +4354,7 @@ export const options = {
3519
4354
  checks: ['rate>=0.95'],
3520
4355
  http_req_failed: ['rate<0.05'],
3521
4356
  http_req_duration: ['p(95)<1000'],
3522
- },
4357
+ ${emitOpThresholds(ctx)} },
3523
4358
  };
3524
4359
 
3525
4360
  export default function () {
@@ -3527,6 +4362,18 @@ export default function () {
3527
4362
  }
3528
4363
  `;
3529
4364
  }
4365
+ function emitOpThresholds(ctx) {
4366
+ const buckets = ["1xx", "2xx", "3xx", "4xx", "5xx"];
4367
+ const lines = [];
4368
+ for (const op of ctx.sequencedOps) {
4369
+ lines.push(` 'loadam_op_latency{name:${op.id}}': ['p(95)<999999'],`);
4370
+ for (const b of buckets) {
4371
+ lines.push(` 'loadam_op_status{name:${op.id},bucket:${b}}': ['count>=0'],`);
4372
+ }
4373
+ }
4374
+ return lines.length === 0 ? "" : `${lines.join("\n")}
4375
+ `;
4376
+ }
3530
4377
  function emitFixturesJson(pool) {
3531
4378
  return `${JSON.stringify(pool, null, 2)}
3532
4379
  `;
@@ -3612,8 +4459,8 @@ function compileK6(ir, opts = {}) {
3612
4459
  const files = {
3613
4460
  "config.js": emitConfigJs(ctx),
3614
4461
  "flow.js": emitFlowJs(ctx),
3615
- "smoke.js": emitSmokeJs(),
3616
- "load.js": emitLoadJs(),
4462
+ "smoke.js": emitSmokeJs(ctx),
4463
+ "load.js": emitLoadJs(ctx),
3617
4464
  "fixtures.json": emitFixturesJson(fixtures.byOperationId),
3618
4465
  "package.json": emitPackageJson2(ctx),
3619
4466
  ".env.example": emitEnvExample3(ctx),
@@ -3705,73 +4552,6 @@ async function readEnvFile(path) {
3705
4552
  }
3706
4553
  }
3707
4554
 
3708
- // src/util/k6.ts
3709
- import { spawn as spawn2 } from "child_process";
3710
- import { constants, access } from "fs/promises";
3711
- import { delimiter, join as join4 } from "path";
3712
- async function findK6Binary() {
3713
- const path = process.env.PATH ?? "";
3714
- const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3715
- for (const dir of path.split(delimiter)) {
3716
- if (!dir) continue;
3717
- for (const ext of exts) {
3718
- const candidate = join4(dir, `k6${ext}`);
3719
- try {
3720
- await access(candidate, constants.X_OK);
3721
- return candidate;
3722
- } catch {
3723
- }
3724
- }
3725
- }
3726
- return null;
3727
- }
3728
- async function runK6(opts) {
3729
- const bin = await findK6Binary();
3730
- if (!bin) {
3731
- throw new Error(
3732
- "k6 not found on PATH. Install it from https://grafana.com/docs/k6/latest/set-up/install-k6/ and try again."
3733
- );
3734
- }
3735
- const args = ["run"];
3736
- if (opts.summaryPath) args.push(`--summary-export=${opts.summaryPath}`);
3737
- args.push(...opts.args ?? [], opts.script);
3738
- return await new Promise((resolveExit, reject) => {
3739
- const child = spawn2(bin, args, {
3740
- cwd: opts.cwd,
3741
- env: { ...process.env, ...opts.env },
3742
- stdio: "inherit"
3743
- });
3744
- child.on("error", reject);
3745
- child.on("close", (code) => resolveExit(code ?? 0));
3746
- });
3747
- }
3748
- async function digestK6Summary(path) {
3749
- try {
3750
- const { readFile: readFile10 } = await import("fs/promises");
3751
- const text = await readFile10(path, "utf8");
3752
- const data = JSON.parse(text);
3753
- const passed = [];
3754
- const failed = [];
3755
- const metrics = {};
3756
- for (const [name, m] of Object.entries(data.metrics ?? {})) {
3757
- if (m.thresholds) {
3758
- for (const [expr, info] of Object.entries(m.thresholds)) {
3759
- (info.ok ? passed : failed).push(`${name}: ${expr}`);
3760
- }
3761
- }
3762
- if (m.values) {
3763
- if (typeof m.values["p(95)"] === "number") metrics[`${name}.p95`] = m.values["p(95)"];
3764
- if (typeof m.values.rate === "number") metrics[`${name}.rate`] = m.values.rate;
3765
- if (typeof m.values.count === "number") metrics[`${name}.count`] = m.values.count;
3766
- if (typeof m.values.avg === "number") metrics[`${name}.avg`] = m.values.avg;
3767
- }
3768
- }
3769
- return { passed, failed, metrics };
3770
- } catch {
3771
- return null;
3772
- }
3773
- }
3774
-
3775
4555
  // src/commands/test.ts
3776
4556
  var VALID_MODES = ["smoke", "load", "both", "skip"];
3777
4557
  function registerTestCommand(program) {
@@ -3791,10 +4571,15 @@ async function runTest(spec, opts) {
3791
4571
  const ir = await fromOpenApiFile(specPath);
3792
4572
  inferResourceGraph(ir);
3793
4573
  parseIR(ir);
4574
+ out.success(`Parsed ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}`);
3794
4575
  const fixtureSize = Number.parseInt(opts.fixtureSize ?? "10", 10);
3795
4576
  const seed = Number.parseInt(opts.seed ?? "1", 10);
4577
+ const target = resolveTarget(opts.target);
4578
+ out.start(
4579
+ `Generating k6 scripts for ${ir.operations.length} operation${ir.operations.length === 1 ? "" : "s"}\u2026`
4580
+ );
3796
4581
  const result = compileK6(ir, {
3797
- baseUrl: opts.target,
4582
+ baseUrl: target,
3798
4583
  fixtureSize: Number.isFinite(fixtureSize) ? fixtureSize : 10,
3799
4584
  seed: Number.isFinite(seed) ? seed : 1
3800
4585
  });
@@ -3811,7 +4596,8 @@ async function runTest(spec, opts) {
3811
4596
  out.info(
3812
4597
  ` ${ir.operations.length} operations \xB7 ${fixtureCount} ops with fixtures \xB7 ${result.fixtures.size} samples each`
3813
4598
  );
3814
- const interactive = !opts.json && isInteractive(!!opts.noInteractive);
4599
+ const noInteractiveFlag = opts.interactive === false;
4600
+ const interactive = !opts.json && isInteractive(noInteractiveFlag);
3815
4601
  const requestedMode = parseModeFlag(opts.mode);
3816
4602
  let envAction = "not-needed";
3817
4603
  let runResult = null;
@@ -3850,21 +4636,21 @@ async function runTest(spec, opts) {
3850
4636
  specSource,
3851
4637
  ir,
3852
4638
  irJson: JSON.stringify(ir, null, 2),
3853
- target: opts.target ?? result.baseUrl,
4639
+ target: target ?? result.baseUrl,
3854
4640
  envVars: result.auth.envVars,
3855
4641
  flags: {
3856
4642
  mode,
3857
- target: opts.target ?? null,
4643
+ target: target ?? null,
3858
4644
  fixtureSize,
3859
4645
  seed,
3860
- noInteractive: !!opts.noInteractive,
4646
+ noInteractive: noInteractiveFlag,
3861
4647
  json: !!opts.json
3862
4648
  },
3863
4649
  slug: `${mode}-${ir.meta.title ?? "run"}`
3864
4650
  });
3865
4651
  if (!out.json) out.info(` Session: ${session.id}`);
3866
4652
  if (mode !== "skip") {
3867
- runResult = await maybeRunWithSession({ mode, cwd: outDir, out, session });
4653
+ runResult = await maybeRunWithSession({ mode, cwd: outDir, out, session, interactive });
3868
4654
  } else if (!interactive && !out.json) {
3869
4655
  out.step("");
3870
4656
  out.step("Next steps:");
@@ -3912,8 +4698,16 @@ function parseModeFlag(raw) {
3912
4698
  function getSessionRoot(outDir) {
3913
4699
  return resolve12(outDir, "..");
3914
4700
  }
4701
+ async function fileExists(p) {
4702
+ try {
4703
+ await stat2(p);
4704
+ return true;
4705
+ } catch {
4706
+ return false;
4707
+ }
4708
+ }
3915
4709
  async function maybeRunWithSession(input) {
3916
- const { mode, cwd, out, session } = input;
4710
+ const { mode, cwd, out, session, interactive } = input;
3917
4711
  if (mode === "skip") return { mode };
3918
4712
  const bin = await findK6Binary();
3919
4713
  if (!bin) {
@@ -3938,6 +4732,7 @@ async function maybeRunWithSession(input) {
3938
4732
  }
3939
4733
  const summaryPath = join5(session.dir, "k6-smoke-summary.json");
3940
4734
  result.smokeExit = await runK6({ cwd, script: "smoke.js", summaryPath });
4735
+ if (await fileExists(summaryPath)) session.registerArtefact("k6-smoke-summary.json");
3941
4736
  const digest = await digestK6Summary(summaryPath);
3942
4737
  if (digest) {
3943
4738
  allPassed.push(...digest.passed.map((t) => `smoke: ${t}`));
@@ -3951,7 +4746,7 @@ async function maybeRunWithSession(input) {
3951
4746
  }
3952
4747
  }
3953
4748
  if (mode === "load" || mode === "both") {
3954
- if (mode === "both") {
4749
+ if (mode === "both" && interactive) {
3955
4750
  const cont = await confirmContinue("Smoke complete. Continue with load test?");
3956
4751
  if (!cont) {
3957
4752
  await session.finalize({
@@ -3968,6 +4763,7 @@ async function maybeRunWithSession(input) {
3968
4763
  }
3969
4764
  const summaryPath = join5(session.dir, "k6-load-summary.json");
3970
4765
  result.loadExit = await runK6({ cwd, script: "load.js", summaryPath });
4766
+ if (await fileExists(summaryPath)) session.registerArtefact("k6-load-summary.json");
3971
4767
  const digest = await digestK6Summary(summaryPath);
3972
4768
  if (digest) {
3973
4769
  allPassed.push(...digest.passed.map((t) => `load: ${t}`));
@@ -4071,16 +4867,16 @@ function banner() {
4071
4867
  ${TAGLINE}
4072
4868
  `;
4073
4869
  }
4074
- const cyan = "\x1B[36m";
4870
+ const amber = "\x1B[38;5;208m";
4075
4871
  const dim = "\x1B[2m";
4076
4872
  const reset = "\x1B[0m";
4077
- return `${cyan}${ART}${reset}
4873
+ return `${amber}${ART}${reset}
4078
4874
  ${dim}${TAGLINE}${reset}
4079
4875
  `;
4080
4876
  }
4081
4877
 
4082
4878
  // src/program.ts
4083
- var VERSION2 = true ? "0.2.2" : "0.0.0";
4879
+ var VERSION2 = true ? "0.2.4" : "0.0.0";
4084
4880
  function buildProgram() {
4085
4881
  const program = new Command();
4086
4882
  program.name("loadam").description(