@intentius/behold 0.29.27 → 0.29.29

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/cli.js CHANGED
@@ -471,9 +471,9 @@ function renderConflictReport(report) {
471
471
  }
472
472
  const grouped = /* @__PURE__ */ new Map();
473
473
  for (const conflict of conflicts) {
474
- const list3 = grouped.get(conflict.manager) ?? [];
475
- if (!list3.includes(conflict.field)) list3.push(conflict.field);
476
- grouped.set(conflict.manager, list3);
474
+ const list4 = grouped.get(conflict.manager) ?? [];
475
+ if (!list4.includes(conflict.field)) list4.push(conflict.field);
476
+ grouped.set(conflict.manager, list4);
477
477
  }
478
478
  const count = new Set(conflicts.map((c) => c.field)).size;
479
479
  const lines2 = [
@@ -1034,9 +1034,9 @@ async function createK8sClient(options2 = {}) {
1034
1034
  };
1035
1035
  }
1036
1036
  async function resolveByGvk(apiVersion, kind, signal) {
1037
- const list4 = await apiResourceList(apiVersion, signal);
1038
- if (!list4) return void 0;
1039
- const entry = (list4.resources ?? []).find((r) => r.kind === kind && !(r.name ?? "").includes("/"));
1037
+ const list5 = await apiResourceList(apiVersion, signal);
1038
+ if (!list5) return void 0;
1039
+ const entry = (list5.resources ?? []).find((r) => r.kind === kind && !(r.name ?? "").includes("/"));
1040
1040
  return entry ? toInfo(apiVersion, entry) : void 0;
1041
1041
  }
1042
1042
  async function resolveByResourceString(resource, group, signal) {
@@ -1059,8 +1059,8 @@ async function createK8sClient(options2 = {}) {
1059
1059
  (r) => (r.shortNames ?? []).some((s) => s.toLowerCase() === needle)
1060
1060
  ];
1061
1061
  for (const matches of matchers) {
1062
- for (const { gv, list: list4 } of lists) {
1063
- const entry = (list4?.resources ?? []).find((r) => !(r.name ?? "").includes("/") && matches(r));
1062
+ for (const { gv, list: list5 } of lists) {
1063
+ const entry = (list5?.resources ?? []).find((r) => !(r.name ?? "").includes("/") && matches(r));
1064
1064
  if (entry) return toInfo(gv, entry);
1065
1065
  }
1066
1066
  }
@@ -1101,7 +1101,7 @@ async function createK8sClient(options2 = {}) {
1101
1101
  throw err;
1102
1102
  }
1103
1103
  }
1104
- async function list3(selector, opts = {}) {
1104
+ async function list4(selector, opts = {}) {
1105
1105
  const info = await resolveOrThrow(selector, opts.signal);
1106
1106
  const items = [];
1107
1107
  let cont;
@@ -1339,9 +1339,9 @@ async function createK8sClient(options2 = {}) {
1339
1339
  return void 0;
1340
1340
  }
1341
1341
  async function resourcesOf(apiVersion, signal) {
1342
- const list4 = await apiResourceList(apiVersion, signal);
1343
- if (!list4) return [];
1344
- return (list4.resources ?? []).filter((r) => !(r.name ?? "").includes("/")).map((entry) => toInfo(apiVersion, entry));
1342
+ const list5 = await apiResourceList(apiVersion, signal);
1343
+ if (!list5) return [];
1344
+ return (list5.resources ?? []).filter((r) => !(r.name ?? "").includes("/")).map((entry) => toInfo(apiVersion, entry));
1345
1345
  }
1346
1346
  return {
1347
1347
  provenance,
@@ -1350,7 +1350,7 @@ async function createK8sClient(options2 = {}) {
1350
1350
  read,
1351
1351
  pathFor,
1352
1352
  readIfPresent,
1353
- list: list3,
1353
+ list: list4,
1354
1354
  readLog,
1355
1355
  watch: watch2,
1356
1356
  apply,
@@ -1430,9 +1430,9 @@ function fieldOwners(object, options2 = {}) {
1430
1430
  for (const set of fieldSetsOf(object)) {
1431
1431
  if (set.subresource !== void 0 && options2.includeSubresources !== true) continue;
1432
1432
  for (const path of set.fields) {
1433
- const list3 = owners.get(path) ?? [];
1434
- if (!list3.includes(set.manager)) list3.push(set.manager);
1435
- owners.set(path, list3);
1433
+ const list4 = owners.get(path) ?? [];
1434
+ if (!list4.includes(set.manager)) list4.push(set.manager);
1435
+ owners.set(path, list4);
1436
1436
  }
1437
1437
  }
1438
1438
  return owners;
@@ -1898,8 +1898,8 @@ function tfTypeOf(address, kind) {
1898
1898
  function boundaryEdgesOf(r) {
1899
1899
  const b = r.boundary;
1900
1900
  if (!b) return [];
1901
- const list3 = Array.isArray(b) ? b : [...b.inbound ?? [], ...b.outbound ?? []];
1902
- return list3.filter((e) => isRecord2(e) && typeof e.survivor === "string" && typeof e.carved === "string");
1901
+ const list4 = Array.isArray(b) ? b : [...b.inbound ?? [], ...b.outbound ?? []];
1902
+ return list4.filter((e) => isRecord2(e) && typeof e.survivor === "string" && typeof e.carved === "string");
1903
1903
  }
1904
1904
  function scoreArithmetic(r) {
1905
1905
  const b = r.breakdown;
@@ -2910,8 +2910,8 @@ function indexRoster(addresses) {
2910
2910
  for (let depth = 1; depth < segments.length; depth++) {
2911
2911
  const callPath = segments.slice(0, depth).join("/");
2912
2912
  const written2 = { address, scope: scopeAbove(instance.scope, depth - 1), key: "" };
2913
- const list3 = calls.get(callPath);
2914
- if (list3) list3.push(written2);
2913
+ const list4 = calls.get(callPath);
2914
+ if (list4) list4.push(written2);
2915
2915
  else calls.set(callPath, [written2]);
2916
2916
  }
2917
2917
  }
@@ -5386,11 +5386,11 @@ function applyCommandFor(state, labels = {}) {
5386
5386
  return `chant carve apply --from ${from} --output ${out} --env ${env} --stack ${stack} --write-source`;
5387
5387
  }
5388
5388
  function carveStatePayload(states, total, labels = () => ({})) {
5389
- const list3 = [...states.values()].sort((a, b) => a.target.localeCompare(b.target));
5389
+ const list4 = [...states.values()].sort((a, b) => a.target.localeCompare(b.target));
5390
5390
  return {
5391
- manifests: list3.length,
5392
- progress: carveProgress(list3, total),
5393
- states: list3.map((s) => ({ ...s, note: carveStageNote(s), applyCommand: applyCommandFor(s, labels(s)) })),
5391
+ manifests: list4.length,
5392
+ progress: carveProgress(list4, total),
5393
+ states: list4.map((s) => ({ ...s, note: carveStageNote(s), applyCommand: applyCommandFor(s, labels(s)) })),
5394
5394
  apply: { human: true, note: APPLY_IS_HUMAN }
5395
5395
  };
5396
5396
  }
@@ -6104,10 +6104,10 @@ function verifySshSignatureWith(armored, message2, namespace, keys) {
6104
6104
  return { ok: false, reason: err instanceof Error ? err.message : String(err) };
6105
6105
  }
6106
6106
  }
6107
- function namespaceAllowed(list3, namespace) {
6108
- if (list3 === void 0) return true;
6107
+ function namespaceAllowed(list4, namespace) {
6108
+ if (list4 === void 0) return true;
6109
6109
  let allowed = false;
6110
- for (const raw of list3.split(",")) {
6110
+ for (const raw of list4.split(",")) {
6111
6111
  const negated = raw.startsWith("!");
6112
6112
  const pattern = negated ? raw.slice(1) : raw;
6113
6113
  const re = new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
@@ -10757,8 +10757,8 @@ function writeScopeOf(raw, members, at2) {
10757
10757
  const out = {};
10758
10758
  for (const [cls, entry] of Object.entries(block)) {
10759
10759
  const pointer = `/writeScope/${cls}`;
10760
- const list3 = entry.members === void 0 || entry.members === "*" ? null : [...entry.members];
10761
- for (const [i, name] of (list3 ?? []).entries()) {
10760
+ const list4 = entry.members === void 0 || entry.members === "*" ? null : [...entry.members];
10761
+ for (const [i, name] of (list4 ?? []).entries()) {
10762
10762
  if (!members.some((m) => m.name === name)) {
10763
10763
  throw new WorkspaceReadError2(
10764
10764
  "declaration-invalid",
@@ -10769,7 +10769,7 @@ function writeScopeOf(raw, members, at2) {
10769
10769
  }
10770
10770
  const records = entry.records === void 0 ? null : Object.fromEntries(Object.entries(entry.records).map(([k, v]) => [k, [...v]]));
10771
10771
  const guarded = (entry.protected ?? []).map((p) => typeof p === "string" ? { path: p, except: [] } : { path: p.path, except: [...p.except ?? []] });
10772
- out[cls] = { members: list3, records, protected: guarded, pointer };
10772
+ out[cls] = { members: list4, records, protected: guarded, pointer };
10773
10773
  }
10774
10774
  return out;
10775
10775
  }
@@ -13856,8 +13856,8 @@ function applyHelmRenderDrift(ir, reports) {
13856
13856
  if (reports.length === 0) return { charts: 0, drifted: 0 };
13857
13857
  const byChart = /* @__PURE__ */ new Map();
13858
13858
  for (const r of reports) {
13859
- const list3 = byChart.get(r.chart);
13860
- if (list3) list3.push(r);
13859
+ const list4 = byChart.get(r.chart);
13860
+ if (list4) list4.push(r);
13861
13861
  else byChart.set(r.chart, [r]);
13862
13862
  }
13863
13863
  let charts = 0;
@@ -14722,9 +14722,9 @@ function enrichedRefs(ir, aws, byId) {
14722
14722
  const producersByName = /* @__PURE__ */ new Map();
14723
14723
  for (const ex of ir.exports ?? []) {
14724
14724
  if (!ex.node || !byId.has(ex.node)) continue;
14725
- const list3 = producersByName.get(ex.name) ?? producersByName.set(ex.name, []).get(ex.name);
14726
- if (isExample(byId.get(ex.node))) list3.push(ex.node);
14727
- else list3.unshift(ex.node);
14725
+ const list4 = producersByName.get(ex.name) ?? producersByName.set(ex.name, []).get(ex.name);
14726
+ if (isExample(byId.get(ex.node))) list4.push(ex.node);
14727
+ else list4.unshift(ex.node);
14728
14728
  }
14729
14729
  const exportNames = [...producersByName.keys()].sort((a, b) => b.length - a.length);
14730
14730
  const bridge = (paramId, producers) => {
@@ -16730,8 +16730,8 @@ async function terragucciOverriders(show) {
16730
16730
  if (text2 === void 0 || name.endsWith(".ts")) continue;
16731
16731
  try {
16732
16732
  const doc = name.endsWith(".json") ? JSON.parse(text2) : parseYAML(text2);
16733
- const list3 = doc?.policy?.override;
16734
- return { principals: Array.isArray(list3) ? list3.filter((x) => typeof x === "string") : [], path: "policy.override" };
16733
+ const list4 = doc?.policy?.override;
16734
+ return { principals: Array.isArray(list4) ? list4.filter((x) => typeof x === "string") : [], path: "policy.override" };
16735
16735
  } catch {
16736
16736
  return { principals: [], path: "policy.override" };
16737
16737
  }
@@ -18492,9 +18492,9 @@ function cardFaces(ir, boxes, opts = {}) {
18492
18492
  ])
18493
18493
  )
18494
18494
  };
18495
- const restore = (svg) => back.size === 0 ? svg : svg.replace(new RegExp(`(${ID_ATTRS.join("|")})="([^"]*)"`, "g"), (whole, attr, value) => {
18495
+ const restore = (svg) => back.size === 0 ? svg : svg.replace(new RegExp(`(${ID_ATTRS.join("|")})="([^"]*)"`, "g"), (whole, attr2, value) => {
18496
18496
  const real = back.get(value);
18497
- return real === void 0 ? whole : `${attr}="${real}"`;
18497
+ return real === void 0 ? whole : `${attr2}="${real}"`;
18498
18498
  }).replaceAll(INVISIBLE, "");
18499
18499
  return { ir: displayIr, overrides, display: minted, restore };
18500
18500
  }
@@ -18904,9 +18904,9 @@ function joinStepEntities(ir, estate) {
18904
18904
  for (const n of estate?.nodes ?? []) {
18905
18905
  byId.set(n.id, n);
18906
18906
  for (const leaf of stringLeaves(n.attrs)) {
18907
- const list3 = byLeaf.get(leaf.value);
18908
- if (list3) {
18909
- if (!list3.includes(n)) list3.push(n);
18907
+ const list4 = byLeaf.get(leaf.value);
18908
+ if (list4) {
18909
+ if (!list4.includes(n)) list4.push(n);
18910
18910
  } else byLeaf.set(leaf.value, [n]);
18911
18911
  }
18912
18912
  }
@@ -19474,23 +19474,23 @@ function routeEdges(svg) {
19474
19474
  ];
19475
19475
  for (const e of pair) {
19476
19476
  const key2 = `${e.card}\0${e.side}`;
19477
- const list3 = sides.get(key2) ?? [];
19478
- list3.push(e);
19479
- sides.set(key2, list3);
19477
+ const list4 = sides.get(key2) ?? [];
19478
+ list4.push(e);
19479
+ sides.set(key2, list4);
19480
19480
  }
19481
19481
  return pair;
19482
19482
  });
19483
- for (const list3 of sides.values()) {
19484
- const card = geo.cards.get(list3[0].card);
19485
- const side = list3[0].side;
19483
+ for (const list4 of sides.values()) {
19484
+ const card = geo.cards.get(list4[0].card);
19485
+ const side = list4[0].side;
19486
19486
  const len = side === "top" || side === "bottom" ? card.w : card.h;
19487
- if (list3.length > 1) {
19488
- const gap = Math.min(PORT_GAP, len * 0.7 / (list3.length - 1));
19489
- list3.sort((p, q) => p.toward - q.toward || p.edge - q.edge);
19490
- list3.forEach((e, k2) => e.offset = (k2 - (list3.length - 1) / 2) * gap);
19487
+ if (list4.length > 1) {
19488
+ const gap = Math.min(PORT_GAP, len * 0.7 / (list4.length - 1));
19489
+ list4.sort((p, q) => p.toward - q.toward || p.edge - q.edge);
19490
+ list4.forEach((e, k2) => e.offset = (k2 - (list4.length - 1) / 2) * gap);
19491
19491
  }
19492
- const shift = clearOfLabels(card, side, list3.map((e) => e.offset), geo.labels);
19493
- if (shift) list3.forEach((e) => e.offset += shift);
19492
+ const shift = clearOfLabels(card, side, list4.map((e) => e.offset), geo.labels);
19493
+ if (shift) list4.forEach((e) => e.offset += shift);
19494
19494
  }
19495
19495
  const cardRects = [...geo.cards.entries()];
19496
19496
  const chips = [];
@@ -20261,15 +20261,15 @@ function packBoxComponents(layout, ir, boxes, bandOf, subgroups) {
20261
20261
  let shelfH = 0;
20262
20262
  const bands = [];
20263
20263
  for (const band of order) {
20264
- const list3 = banded.get(band);
20265
- if (!list3?.length) continue;
20264
+ const list4 = banded.get(band);
20265
+ if (!list4?.length) continue;
20266
20266
  if (shelfH > 0) {
20267
20267
  shelfX = 0;
20268
20268
  shelfY += shelfH + COMPONENT_GAP;
20269
20269
  shelfH = 0;
20270
20270
  }
20271
20271
  const ids2 = [];
20272
- for (const c of list3) {
20272
+ for (const c of list4) {
20273
20273
  if (shelfX > 0 && shelfX + c.w > targetW) {
20274
20274
  shelfX = 0;
20275
20275
  shelfY += shelfH + COMPONENT_GAP;
@@ -21236,9 +21236,9 @@ function joinRun(op, records, gate) {
21236
21236
  const indexOf = new Map(placed.map((p, i) => [p.id, i]));
21237
21237
  for (const record of records) {
21238
21238
  const key2 = `${record.phase}\0${record.fn}`;
21239
- const list3 = byKey.get(key2);
21239
+ const list4 = byKey.get(key2);
21240
21240
  const i = cursor.get(key2) ?? 0;
21241
- const slot = list3?.[i];
21241
+ const slot = list4?.[i];
21242
21242
  if (!slot) {
21243
21243
  unplaced.push(record);
21244
21244
  continue;
@@ -25880,16 +25880,79 @@ function terragucciDemoRoute(app, source2, opts = {}) {
25880
25880
  return c.json(a, "error" in a ? 502 : 200, { "cache-control": "no-store" });
25881
25881
  });
25882
25882
  }
25883
- var disabledPage = `<!doctype html><meta charset=utf-8><title>behold kiosk</title><script type="module">import { initTheme } from "/theme.js"; initTheme();</script><body style="font:16px system-ui;background:var(--bg,#1e1e2e);color:var(--fg,#cdd6f4);padding:2rem"><h3>The kiosk follows a terragucci demo</h3><p style="color:var(--muted,#777a8c)">Start behold with <code>--terragucci &lt;reports source&gt;</code>; the kiosk reads <code>demo.json</code> there.</p></body>`;
25884
- function kioskRoute(app, webRoot2, enabled) {
25883
+ var disabledPage = `<!doctype html><meta charset=utf-8><title>behold \xB7 live demo</title><script type="module">import { initTheme } from "/theme.js"; initTheme();</script><body style="font:16px system-ui;background:var(--bg,#1e1e2e);color:var(--fg,#cdd6f4);padding:2rem"><h3>The kiosk follows a terragucci demo</h3><p style="color:var(--muted,#777a8c)">Start behold with <code>--terragucci &lt;reports source&gt;</code>; the kiosk reads <code>demo.json</code> there.</p></body>`;
25884
+ function kioskRoute(app, webRoot2, enabled, allowedHosts = []) {
25885
25885
  app.get("/kiosk", (c) => {
25886
25886
  if (!enabled) {
25887
25887
  return c.html(disabledPage, 404);
25888
25888
  }
25889
- return new Response(readFileSync32(join43(webRoot2, "kiosk.html"), "utf8"), { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" } });
25889
+ const html = sharePage(readFileSync32(join43(webRoot2, "kiosk.html"), "utf8"), {
25890
+ title: "behold \xB7 live demo",
25891
+ description: "Watch one change go from pull request to apply across real Terraform states.",
25892
+ origin: shareOrigin(c.req.header("host"), c.req.header("x-forwarded-proto"), allowedHosts),
25893
+ path: "/kiosk"
25894
+ });
25895
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" } });
25896
+ });
25897
+ }
25898
+ var SHARE_IMAGE = {
25899
+ path: "/share.png",
25900
+ width: 1200,
25901
+ height: 630,
25902
+ alt: "The pixel behold logo above the word BEHOLD and the line: a live infrastructure loop you can watch."
25903
+ };
25904
+ var SHARE_IMAGE_MAX_AGE_SECS = 86400;
25905
+ function shareOrigin(host, forwardedProto, allowedHosts) {
25906
+ if (!host) return void 0;
25907
+ const m = /^([a-z0-9.-]+)(:\d{1,5})?$/.exec(host.trim().toLowerCase());
25908
+ if (!m) return void 0;
25909
+ const name = m[1];
25910
+ if (!allowedHosts.some((h) => hostName(h) === name)) return void 0;
25911
+ const proto = (forwardedProto ?? "").split(",")[0].trim().toLowerCase() === "https" ? "https" : "http";
25912
+ return `${proto}://${name}${m[2] ?? ""}`;
25913
+ }
25914
+ var attr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
25915
+ function sharePage(html, p) {
25916
+ const tags = [
25917
+ ["property", "og:type", "website"],
25918
+ ["property", "og:site_name", "behold"],
25919
+ ["property", "og:title", p.title],
25920
+ ["property", "og:description", p.description],
25921
+ ["name", "description", p.description],
25922
+ ["name", "twitter:card", "summary_large_image"],
25923
+ ["name", "twitter:title", p.title],
25924
+ ["name", "twitter:description", p.description]
25925
+ ];
25926
+ if (p.origin) {
25927
+ const image = `${p.origin}${SHARE_IMAGE.path}`;
25928
+ tags.push(
25929
+ ["property", "og:url", `${p.origin}${p.path}`],
25930
+ ["property", "og:image", image],
25931
+ ["property", "og:image:type", "image/png"],
25932
+ ["property", "og:image:width", String(SHARE_IMAGE.width)],
25933
+ ["property", "og:image:height", String(SHARE_IMAGE.height)],
25934
+ ["property", "og:image:alt", SHARE_IMAGE.alt],
25935
+ ["name", "twitter:image", image],
25936
+ ["name", "twitter:image:alt", SHARE_IMAGE.alt]
25937
+ );
25938
+ }
25939
+ const head = [`<title>${attr(p.title)}</title>`, ...tags.map(([k, n, v]) => `<meta ${k}="${n}" content="${attr(v)}" />`)].join("\n ");
25940
+ return html.replace(/<title>[^<]*<\/title>/, () => head);
25941
+ }
25942
+ function shareImageRoute(app, webRoot2) {
25943
+ app.get(SHARE_IMAGE.path, () => {
25944
+ const png = readFileSync32(join43(webRoot2, "share.png"));
25945
+ return new Response(new Uint8Array(png), { headers: { "content-type": "image/png", "cache-control": `public, max-age=${SHARE_IMAGE_MAX_AGE_SECS}` } });
25890
25946
  });
25891
25947
  }
25892
25948
  var VENDOR_TOOLS = ["terraform", "terragrunt", "cdk-terrain", "choudoufu", "chant"];
25949
+ var VENDOR_NAMES = {
25950
+ terraform: "Terraform",
25951
+ terragrunt: "Terragrunt",
25952
+ "cdk-terrain": "CDK Terrain",
25953
+ choudoufu: "choudoufu",
25954
+ chant: "chant"
25955
+ };
25893
25956
  var isVendorTool = (v) => VENDOR_TOOLS.includes(v);
25894
25957
  var cycleKey = (tool) => `cycles/${tool}/latest.json`;
25895
25958
  var CYCLE_READ_TTL_MS = 1e4;
@@ -25962,11 +26025,18 @@ function vendorPage(html, tool) {
25962
26025
  return html.replace(/<meta charset="utf-8" \/>/, `<meta charset="utf-8" />
25963
26026
  <meta name="kiosk-tool" content="${tool}" />`);
25964
26027
  }
25965
- function vendorRoutes(app, webRoot2, enabled) {
26028
+ function vendorRoutes(app, webRoot2, enabled, allowedHosts = []) {
25966
26029
  for (const tool of VENDOR_TOOLS) {
25967
26030
  app.get(`/${tool}`, (c) => {
25968
26031
  if (!enabled) return c.html(disabledPage, 404);
25969
- const html = vendorPage(readFileSync32(join43(webRoot2, "kiosk.html"), "utf8"), tool);
26032
+ const name = VENDOR_NAMES[tool];
26033
+ const shared2 = sharePage(readFileSync32(join43(webRoot2, "kiosk.html"), "utf8"), {
26034
+ title: `behold \xB7 ${name}`,
26035
+ description: `Watch ${name} carry one change from pull request to apply, live.`,
26036
+ origin: shareOrigin(c.req.header("host"), c.req.header("x-forwarded-proto"), allowedHosts),
26037
+ path: `/${tool}`
26038
+ });
26039
+ const html = vendorPage(shared2, tool);
25970
26040
  return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" } });
25971
26041
  });
25972
26042
  }
@@ -26320,6 +26390,239 @@ function metricsRoute(app, opts) {
26320
26390
  });
26321
26391
  }
26322
26392
 
26393
+ // src/tempo-traces.ts
26394
+ var SEARCH_TTL_MS = 1e4;
26395
+ var TRACE_TTL_MS = 6e4;
26396
+ var TRACE_CACHE_MAX = 200;
26397
+ var SEARCH_LIMIT = 40;
26398
+ var SEARCH_WINDOW_S = 48 * 3600;
26399
+ var MAX_SPANS = 1500;
26400
+ var RUN = /^[1-9][0-9]{0,15}$/;
26401
+ var JOB = /^[A-Za-z0-9][A-Za-z0-9 ._()-]{0,99}$/;
26402
+ var validRun = (v) => !!v && RUN.test(v);
26403
+ var validJob = (v) => !!v && JOB.test(v);
26404
+ function searchQuery(by) {
26405
+ if ("run" in by) {
26406
+ if (!validRun(by.run)) throw new Error("a run id is digits");
26407
+ return `{ resource.service.name = "terragucci" && resource."cicd.pipeline.run.id" = "${by.run}" }`;
26408
+ }
26409
+ if (!validCommit(by.commit)) throw new Error("a commit is hex");
26410
+ return by.commit.length === 40 || by.commit.length === 64 ? `{ resource.service.name = "terragucci" && resource."vcs.ref.head.revision" = "${by.commit}" }` : `{ resource.service.name = "terragucci" && resource."vcs.ref.head.revision" =~ "${by.commit}.*" }`;
26411
+ }
26412
+ var KEPT_ATTRIBUTES = [
26413
+ "terragucci.stage",
26414
+ "terragucci.phase",
26415
+ "terragucci.wave",
26416
+ "terragucci.root",
26417
+ "terragucci.result",
26418
+ "terragucci.status",
26419
+ "terragucci.gate.status",
26420
+ "terragucci.gate.held_seconds",
26421
+ "terragucci.gate.waiting_since",
26422
+ "terragucci.gate.approved_at",
26423
+ "process.exit.code",
26424
+ "opentofu.resource_instance.address",
26425
+ "opentofu.resource_instance.action",
26426
+ "opentofu.resource.address",
26427
+ "opentofu.resource.type",
26428
+ "opentofu.provider.address",
26429
+ "opentofu.provider.source",
26430
+ "opentofu.state.backend",
26431
+ "rpc.method"
26432
+ ];
26433
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
26434
+ var list3 = (v) => Array.isArray(v) ? v : [];
26435
+ function scalar(v) {
26436
+ if (!isObj(v)) return void 0;
26437
+ if (typeof v.stringValue === "string") return v.stringValue;
26438
+ if (typeof v.boolValue === "boolean") return v.boolValue;
26439
+ if (typeof v.intValue === "string" || typeof v.intValue === "number") return Number(v.intValue);
26440
+ if (typeof v.doubleValue === "number") return v.doubleValue;
26441
+ return void 0;
26442
+ }
26443
+ function attrsOf(v) {
26444
+ const out = {};
26445
+ for (const kv of list3(v)) {
26446
+ if (!isObj(kv) || typeof kv.key !== "string") continue;
26447
+ const s = scalar(kv.value);
26448
+ if (s !== void 0) out[kv.key] = s;
26449
+ }
26450
+ return out;
26451
+ }
26452
+ function idHex(v) {
26453
+ if (typeof v !== "string" || v === "") return null;
26454
+ if (/^[0-9a-f]{16}$|^[0-9a-f]{32}$/i.test(v)) return v.toLowerCase();
26455
+ try {
26456
+ const hex = Buffer.from(v, "base64").toString("hex");
26457
+ return hex.length === 16 || hex.length === 32 ? hex : null;
26458
+ } catch {
26459
+ return null;
26460
+ }
26461
+ }
26462
+ var nanosToMs = (v) => {
26463
+ if (typeof v !== "string" && typeof v !== "number") return void 0;
26464
+ try {
26465
+ const n = BigInt(v);
26466
+ return Number(n / 1000n) / 1e3;
26467
+ } catch {
26468
+ return void 0;
26469
+ }
26470
+ };
26471
+ function trimTrace(traceId, body, repo, maxSpans = MAX_SPANS) {
26472
+ const doc = isObj(body) && isObj(body.trace) ? body.trace : body;
26473
+ const batches = isObj(doc) ? list3(doc.resourceSpans ?? doc.batches) : [];
26474
+ const spans = [];
26475
+ let own;
26476
+ for (const rs of batches) {
26477
+ if (!isObj(rs)) continue;
26478
+ const resource = attrsOf(isObj(rs.resource) ? rs.resource.attributes : void 0);
26479
+ const service = typeof resource["service.name"] === "string" ? resource["service.name"] : "unknown";
26480
+ if (service === "terragucci" && typeof resource["terragucci.project"] === "string") own ??= resource;
26481
+ for (const ss of list3(rs.scopeSpans ?? rs.instrumentationLibrarySpans)) {
26482
+ if (!isObj(ss)) continue;
26483
+ for (const s of list3(ss.spans)) {
26484
+ if (!isObj(s) || typeof s.name !== "string") continue;
26485
+ const id = idHex(s.spanId);
26486
+ const start2 = nanosToMs(s.startTimeUnixNano);
26487
+ const end2 = nanosToMs(s.endTimeUnixNano);
26488
+ if (!id || start2 === void 0 || end2 === void 0) continue;
26489
+ const all = attrsOf(s.attributes);
26490
+ const attrs = {};
26491
+ for (const k of KEPT_ATTRIBUTES) if (all[k] !== void 0) attrs[k] = all[k];
26492
+ const status2 = isObj(s.status) ? s.status : {};
26493
+ const failed = status2.code === 2 || status2.code === "STATUS_CODE_ERROR";
26494
+ spans.push({
26495
+ id,
26496
+ parent: idHex(s.parentSpanId),
26497
+ name: s.name.slice(0, 200),
26498
+ service,
26499
+ start: start2,
26500
+ ms: Math.max(0, Math.round((end2 - start2) * 1e3) / 1e3),
26501
+ ...failed ? { error: typeof status2.message === "string" && status2.message ? status2.message.slice(0, 200) : "error" } : {},
26502
+ attrs
26503
+ });
26504
+ }
26505
+ }
26506
+ }
26507
+ if (!own || !projectIs(String(own["terragucci.project"]), repo) || spans.length === 0) return null;
26508
+ spans.sort((a, b) => a.start - b.start);
26509
+ const stage = spans.find((s) => s.parent === null && typeof s.attrs["terragucci.stage"] === "string") ?? spans.find((s) => s.parent === null) ?? spans[0];
26510
+ const start = Math.min(...spans.map((s) => s.start));
26511
+ const end = Math.max(...spans.map((s) => s.start + s.ms));
26512
+ let kept = spans;
26513
+ if (spans.length > maxSpans) {
26514
+ const byId = new Map(spans.map((s) => [s.id, s]));
26515
+ const depth = (s) => {
26516
+ let d = 0;
26517
+ for (let p = s.parent ? byId.get(s.parent) : void 0; p && d < 64; p = p.parent ? byId.get(p.parent) : void 0) d++;
26518
+ return d;
26519
+ };
26520
+ const order = spans.map((s) => ({ s, d: depth(s) })).sort((a, b) => a.d - b.d || a.s.start - b.s.start);
26521
+ const keep = new Set(order.slice(0, maxSpans).map((x) => x.s));
26522
+ kept = spans.filter((s) => keep.has(s));
26523
+ }
26524
+ const str17 = (v) => typeof v === "string" && v ? v : null;
26525
+ const wave = Number(stage.attrs["terragucci.wave"]);
26526
+ return {
26527
+ trace_id: traceId,
26528
+ project: String(own["terragucci.project"]),
26529
+ job: str17(own["cicd.pipeline.task.name"]),
26530
+ stage: str17(stage.attrs["terragucci.stage"]),
26531
+ wave: Number.isInteger(wave) && wave > 0 ? wave : null,
26532
+ result: str17(stage.attrs["terragucci.result"]),
26533
+ commit: str17(own["vcs.ref.head.revision"]),
26534
+ start,
26535
+ ms: Math.round((end - start) * 1e3) / 1e3,
26536
+ spans: kept,
26537
+ left_out: spans.length - kept.length
26538
+ };
26539
+ }
26540
+ function searchIds(body) {
26541
+ const traces = isObj(body) ? list3(body.traces) : [];
26542
+ return traces.filter(isObj).map((t2) => ({ id: typeof t2.traceID === "string" && /^[0-9a-f]{1,32}$/i.test(t2.traceID) ? t2.traceID.toLowerCase().padStart(32, "0") : null, at: nanosToMs(t2.startTimeUnixNano) ?? 0 })).filter((t2) => t2.id !== null).sort((a, b) => a.at - b.at).map((t2) => t2.id);
26543
+ }
26544
+ function tempoAddress(v) {
26545
+ if (!v) return void 0;
26546
+ try {
26547
+ const u = new URL(v);
26548
+ if (u.protocol !== "http:" && u.protocol !== "https:" || u.search || u.hash) return void 0;
26549
+ return u.toString().replace(/\/+$/, "");
26550
+ } catch {
26551
+ return void 0;
26552
+ }
26553
+ }
26554
+ var Shared = class {
26555
+ constructor(ttl, max) {
26556
+ this.ttl = ttl;
26557
+ this.max = max;
26558
+ }
26559
+ ttl;
26560
+ max;
26561
+ map = /* @__PURE__ */ new Map();
26562
+ get(key2, read) {
26563
+ const t2 = Date.now();
26564
+ const hit = this.map.get(key2);
26565
+ if (hit && t2 - hit.at < this.ttl) return hit.read;
26566
+ for (const [k, v] of this.map) if (t2 - v.at >= this.ttl) this.map.delete(k);
26567
+ while (this.map.size >= this.max) this.map.delete(this.map.keys().next().value);
26568
+ const p = read();
26569
+ this.map.set(key2, { at: t2, read: p });
26570
+ p.catch(() => {
26571
+ if (this.map.get(key2)?.read === p) this.map.delete(key2);
26572
+ });
26573
+ return p;
26574
+ }
26575
+ };
26576
+ function tracesRoute(app, opts) {
26577
+ const fetchFn = opts.fetch ?? fetch;
26578
+ const searches = new Shared(SEARCH_TTL_MS, 100);
26579
+ const traces = new Shared(TRACE_TTL_MS, TRACE_CACHE_MAX);
26580
+ const search = (q) => searches.get(q, async () => {
26581
+ const end = Math.floor(Date.now() / 1e3) + 60;
26582
+ const u = `${opts.tempo}/api/search?${new URLSearchParams({ q, limit: String(SEARCH_LIMIT), start: String(end - SEARCH_WINDOW_S), end: String(end) })}`;
26583
+ const res = await fetchFn(u, { signal: AbortSignal.timeout(8e3), headers: { accept: "application/json" } });
26584
+ if (!res.ok) throw new Error(`Tempo answered ${res.status} to the search`);
26585
+ return searchIds(await res.json());
26586
+ });
26587
+ const trace = (id) => traces.get(id, async () => {
26588
+ const res = await fetchFn(`${opts.tempo}/api/v2/traces/${id}`, { signal: AbortSignal.timeout(8e3), headers: { accept: "application/json" } });
26589
+ if (res.status === 404) return null;
26590
+ if (!res.ok) throw new Error(`Tempo answered ${res.status} to trace ${id}`);
26591
+ return res.json();
26592
+ });
26593
+ app.get("/api/traces", async (c) => {
26594
+ if (!opts.tempo) return c.json({ error: "behold reads no Tempo: start it with --tempo <url>", code: "traces-off" }, 404);
26595
+ const repo = c.req.query("project");
26596
+ if (!validRepo(repo)) return c.json({ error: "project must be a forge repo's <owner>/<name>", code: "traces-project" }, 400);
26597
+ const run3 = c.req.query("run");
26598
+ const commit = c.req.query("commit");
26599
+ const job = c.req.query("job");
26600
+ if (run3 !== void 0 && !validRun(run3)) return c.json({ error: "run must be a pipeline run's id", code: "traces-run" }, 400);
26601
+ if (commit !== void 0 && !validCommit(commit)) return c.json({ error: "commit must be a commit's hex id", code: "traces-commit" }, 400);
26602
+ if (run3 === void 0 && commit === void 0) return c.json({ error: "name a run or a commit", code: "traces-run" }, 400);
26603
+ if (job !== void 0 && !validJob(job)) return c.json({ error: "job must be a job's name", code: "traces-job" }, 400);
26604
+ let found;
26605
+ try {
26606
+ const ids = await search(searchQuery(run3 !== void 0 ? { run: run3 } : { commit }));
26607
+ const bodies = await Promise.all(ids.map((id) => trace(id)));
26608
+ found = ids.map((id, i) => bodies[i] ? trimTrace(id, bodies[i], repo) : null).filter((t2) => t2 !== null);
26609
+ } catch (e) {
26610
+ return c.json({ error: `behold could not read Tempo: ${e instanceof Error ? e.message : String(e)}`, code: "traces-read" }, 502, { "cache-control": "no-store" });
26611
+ }
26612
+ found.sort((a, b) => a.start - b.start);
26613
+ const body = {
26614
+ read: (opts.now ? opts.now() : /* @__PURE__ */ new Date()).toISOString(),
26615
+ repo,
26616
+ project: found[0]?.project ?? null,
26617
+ run: run3 ?? null,
26618
+ commit: commit ?? found[0]?.commit ?? null,
26619
+ jobs: [...new Set(found.map((t2) => t2.job).filter((j) => j !== null))].sort((x, y) => x.localeCompare(y, "en", { numeric: true })),
26620
+ traces: job !== void 0 ? found.filter((t2) => t2.job === job) : found
26621
+ };
26622
+ return c.json(body, 200, { "cache-control": "no-store" });
26623
+ });
26624
+ }
26625
+
26323
26626
  // src/view-repos.ts
26324
26627
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
26325
26628
  import { existsSync as existsSync26, readdirSync as readdirSync16, readFileSync as readFileSync33 } from "node:fs";
@@ -27836,10 +28139,10 @@ function readCatalog(file, catalog) {
27836
28139
  } catch {
27837
28140
  return [];
27838
28141
  }
27839
- const list3 = raw?.demos;
27840
- if (!Array.isArray(list3)) return [];
28142
+ const list4 = raw?.demos;
28143
+ if (!Array.isArray(list4)) return [];
27841
28144
  const catalogDir = dirname17(resolve31(file));
27842
- return list3.filter((e) => validEntry(e)).map((e) => ({ ...e, catalog, catalogDir }));
28145
+ return list4.filter((e) => validEntry(e)).map((e) => ({ ...e, catalog, catalogDir }));
27843
28146
  }
27844
28147
  function validEntry(e) {
27845
28148
  const d = e;
@@ -28417,10 +28720,12 @@ function createApp(cfg, broadcaster = new Broadcaster(), frames = new FrameBuffe
28417
28720
  };
28418
28721
  const estateSourceRoots = async (opts) => (await Promise.all((cfg.projectDirs ?? []).map(async (dir) => [await graphPath(dir, opts), dir]))).flat();
28419
28722
  app.get("/healthz", (c) => c.json({ ok: true, projectDir: cfg.projectDir, env: cfg.env ?? null, frames: frames.size }));
28420
- kioskRoute(app, webRoot, !!cfg.terragucci);
28723
+ kioskRoute(app, webRoot, !!cfg.terragucci, guard.allowedHosts);
28724
+ shareImageRoute(app, webRoot);
28421
28725
  const doraSource = cfg.terragucci && cfg.prometheus ? terragucciSource(cfg.terragucci.source, { ...cfg.terragucci.aws ? { aws: cfg.terragucci.aws } : {}, ...cfg.terragucci.fetch ? { fetch: cfg.terragucci.fetch } : {} }) : void 0;
28422
28726
  metricsRoute(app, { ...cfg.prometheus ? { prometheus: cfg.prometheus } : {}, ...doraSource ? { doraFile: () => doraSource.read("dora.json") } : {} });
28423
- vendorRoutes(app, webRoot, !!cfg.terragucci);
28727
+ tracesRoute(app, cfg.tempo ? { tempo: cfg.tempo } : {});
28728
+ vendorRoutes(app, webRoot, !!cfg.terragucci, guard.allowedHosts);
28424
28729
  app.get("/api/frames", (c) => c.json({ frames: frames.summaries() }));
28425
28730
  app.get("/lanes", (c) => {
28426
28731
  const all = frames.all();
@@ -30894,6 +31199,12 @@ Options:
30894
31199
  and apply seconds, its time at the gate and its changes,
30895
31200
  and the DORA metrics. /api/metrics?project=<owner>/<name>
30896
31201
  answers them, and the kiosk shows them (behold#571).
31202
+ --tempo <url> serve only: the Tempo behold reads a pipeline run's
31203
+ traces from (BEHOLD_TEMPO_URL too), with fixed queries:
31204
+ a search by run id or commit, and a trace by its id.
31205
+ /api/traces?project=<owner>/<name>&run=<id> answers
31206
+ each job's span tree, and the kiosk's job pane draws it
31207
+ as a Trace view (behold#571).
30897
31208
  --terragucci <src> serve/export: paint a terragucci estate from its reports
30898
31209
  (#490). <src> is a report directory (a synced bucket
30899
31210
  prefix, or <prefix>/<project>), s3://bucket/prefix (read
@@ -31039,6 +31350,7 @@ ${USAGE}`);
31039
31350
  let host;
31040
31351
  let hudArg = process.env.BEHOLD_HUD_URL || void 0;
31041
31352
  let prometheusArg = process.env.BEHOLD_PROMETHEUS_URL || void 0;
31353
+ let tempoArg = process.env.BEHOLD_TEMPO_URL || void 0;
31042
31354
  let terragucci;
31043
31355
  let terragucciProject;
31044
31356
  let terragucciPoll;
@@ -31054,6 +31366,7 @@ ${USAGE}`);
31054
31366
  else if (a === "--allow-host") allowHosts.push(...(rest[++i] ?? "").split(","));
31055
31367
  else if (a === "--hud") hudArg = rest[++i];
31056
31368
  else if (a === "--prometheus") prometheusArg = rest[++i];
31369
+ else if (a === "--tempo") tempoArg = rest[++i];
31057
31370
  else if (a === "--terragucci") terragucci = rest[++i];
31058
31371
  else if (a === "--terragucci-project") terragucciProject = rest[++i];
31059
31372
  else if (a === "--terragucci-poll") terragucciPoll = Number(rest[++i]);
@@ -31105,6 +31418,12 @@ ${USAGE}`);
31105
31418
  const prometheus = prometheusAddress(prometheusArg);
31106
31419
  if (prometheusArg && !prometheus) {
31107
31420
  process.stderr.write(`behold serve: --prometheus must be an http or https address with no query, not ${JSON.stringify(prometheusArg)}
31421
+ `);
31422
+ process.exit(2);
31423
+ }
31424
+ const tempo = tempoAddress(tempoArg);
31425
+ if (tempoArg && !tempo) {
31426
+ process.stderr.write(`behold serve: --tempo must be an http or https address with no query, not ${JSON.stringify(tempoArg)}
31108
31427
  `);
31109
31428
  process.exit(2);
31110
31429
  }
@@ -31178,6 +31497,7 @@ ${USAGE}`);
31178
31497
  ...isPublic ? { public: true, layoutWrites: false } : {},
31179
31498
  ...target.workspace && hud ? { hud } : {},
31180
31499
  ...prometheus ? { prometheus } : {},
31500
+ ...tempo ? { tempo } : {},
31181
31501
  ...yodelReport ? { yodelReport: resolve35(yodelReport) } : {},
31182
31502
  ...terragucci ? { terragucci: { source: terragucci, ...terragucciProject ? { project: terragucciProject } : {}, ...terragucciPoll !== void 0 ? { pollSecs: terragucciPoll } : {}, ...terragucciRuns ? { runsSource: terragucciRuns } : {} } } : {}
31183
31503
  });