GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / stars / library

Standalone (part 4)

A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.

700 lines of JavaScript from stars, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1566 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Standalone geodesy · stars / library/standalone.mjs lines 2640–3339

Standalone

A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 2 comment: // Generated by the modular star 2026-12-05T23:26:43.596Z. Each export is one family's earliest-seen copy, unchanged; the comment links its source.

geodesystars / library/standalone.mjs · lines 2640–3339 of 12585 (continued from section 1562) · Entry point · pattern segmentConductors (shared by 2 files)

What it does
It maps REPD master, heavy emitters UK, notice and substations. Defines 1111 functions or classes, including f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: substations, 750kV, 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: data source: gridatlas data; JSON file repd_master.json; JSON file heavy_emitters_uk.json; JSON file notice.json; form fields (user input). Out: canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 1.5kV, 1500V.
Downstream impact
Used directly by 4 files: Code (stars, https://ventusltd.github.io/stars/code.html); Proof (stars); Modular Star Workflow (stars); Testcode — Code Record Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-record/). Reached from 383 other entry points, including Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/); Generate (code-generator, https://ventusltd.github.io/code-generator/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html).
What it achieves
It snaps coordinate (`snapCoordinate`), paints cursor (`paintCursor`) and sets plan (`setPlan`). Compiled library of self-contained JavaScript functions that appear in two or more places across Ventusltd code. Its code works with 33 kV, 132 kV and 275 kV. It responds to abort events.
Why it matters
Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 1 other page. Run by Proof and Modular Star Workflow.
Application
stars · library · JavaScript module
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), Declared Connections (estate URL)
Used by
named by URL in Code (estate URL), run by Proof (script call), run by Modular Star Workflow (workflow run), named by URL in Testcode — Code Record Page (estate URL)
Produces
f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf, f8775_parametersOf, f5168_escapeHTML, f8321_suppliedArrivalFields, f8850__anonymous_, f8786_crossing, f8788_legality, f8789_startNodes
Defines here
f1587_bytesToHex, f1685_invariant, f1811_lineFeature, f1936_bearingDeg, f3411__anonymous_, f3412_escapeHtml, f3416_number, f4603_repdRecords, f4607_displayStatuses, f145218_spreadAt, f145220_slopeAt, f145224_revealPercentiles, f145812_dcOrder, f145822_compoundBox, f145827_placer, point, box, f145855_inflate, f146343_blockCounts, f146441_solidLines, f146445_drawingToGround, f146447_cableLines, f146456_toSpine, f146458_coverage, f146471_frameOf, f146472_inside, f146488_pack, L, f146494_layoutDiagram, f23160_articleIdentity
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc library/standalone.mjs:2640-3339 · blob fc3d8c8b93e14d4a56b8a26da47071d60bc5bc4d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
  const items = payload?.[adapter.input_collection];
  if (!Array.isArray(items)) throw new Error(`missing source collection ${adapter.input_collection}`);
  const required = ["headline", "url", "source", "published"];
  for (const [index, item] of items.entries()) {
    for (const field of required) {
      if (!String(item?.[field] || "").trim()) throw new Error(`source item ${index} missing ${field}`);
    }
  }
  return items;
};

// Family #1587 · element #1587 · 95 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311343/assets/202608282200-federated-relationships.mjs#L16-L18
export const f1587_bytesToHex = function bytesToHex(bytes) {
  return [...bytes].map((value) => value.toString(16).padStart(2, "0")).join("");
};

// Family #1685 · element #1685 · 92 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311343/assets/202608311343-project-intelligence.mjs#L41-L43
export const f1685_invariant = function invariant(condition, message) {
  if (!condition) throw new Error(`Project intelligence cartridge: ${message}`);
};

// Family #1811 · element #1811 · 90 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311530/assets/202608311530-grid-proximity.mjs#L345-L351
export const f1811_lineFeature = function lineFeature(from, to, properties) {
    return {
      type: "Feature",
      geometry: { type: "LineString", coordinates: [from, to] },
      properties,
    };
  };

// Family #1936 · element #1936 · 88 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311558/assets/202608311558-grid-proximity.mjs#L591-L597
export const f1936_bearingDeg = function bearingDeg(lon1, lat1, lon2, lat2) {
    const D = Math.PI / 180;
    const p1 = lat1 * D; const p2 = lat2 * D; const dl = (lon2 - lon1) * D;
    const y = Math.sin(dl) * Math.cos(p2);
    const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
    return (Math.atan2(y, x) / D + 360) % 360;
  };

// Family #3411 · element #3411 · 55 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608312339/assets/202608312339-gb-electricity-context.mjs#L17-L19
export const f3411__anonymous_ = character => ({
    "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
  })[character];

// Family #3412 · element #3412 · 55 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608312339/assets/202608312339-gb-electricity-context.mjs#L16-L20
export const f3412_escapeHtml = function escapeHtml(value) {
  return String(value ?? "").replace(/[&<>"']/g, character => ({
    "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
  })[character]);
};

// Family #3416 · element #3416 · 55 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608312339/assets/202608312339-gb-electricity-context.mjs#L63-L68
export const f3416_number = function number(value, digits = 0) {
  return Number(value).toLocaleString("en-GB", {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  });
};

// Family #4603 · element #4603 · 29 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202609040144/assets/202609040044-wider-fleet.mjs#L117-L126
export const f4603_repdRecords = function repdRecords(row) {
  const records = Array.isArray(row.repd_records) ? row.repd_records : [row];
  const seen = new Set();
  return records.filter((record) => {
    const ref = String(record?.ref ?? "").trim();
    if (!ref || seen.has(ref)) return false;
    seen.add(ref);
    return true;
  });
};

// Family #4607 · element #4607 · 29 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202609040144/assets/202609040044-wider-fleet.mjs#L144-L149
export const f4607_displayStatuses = (row) => {
  const statuses = Array.isArray(row.repd_records)
    ? [...new Set(row.repd_records.map(({ status }) => status).filter(Boolean))]
    : [row.s];
  return statuses.join(" / ");
};

// Family #145218 · element #145218 · 25 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/piles.mjs#L90-L94
export const f145218_spreadAt = (s, g, b) => {
  let hi = -Infinity, lo = Infinity;
  for (let i = 0; i < s.length; i++) { const d = g[i] - b * s[i]; if (d > hi) hi = d; if (d < lo) lo = d; }
  return { hi, lo, w: hi - lo };
};

// Family #145220 · element #145220 · 25 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/piles.mjs#L132-L136
export const f145220_slopeAt = function slopeAt(groundAt, x, y, h) {
  const gx = (groundAt(x + h, y) - groundAt(x - h, y)) / (2 * h);
  const gy = (groundAt(x, y + h) - groundAt(x, y - h)) / (2 * h);
  return { gx, gy };
};

// Family #145224 · element #145224 · 25 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/piles.mjs#L274-L278
export const f145224_revealPercentiles = function revealPercentiles(piles) {
  const v = piles.map((p) => p.reveal).sort((a, b) => a - b);
  if (!v.length) return [];
  return [0, 5, 25, 50, 75, 95, 100].map((q) => v[Math.min(v.length - 1, Math.max(0, Math.ceil(q / 100 * v.length) - 1))]);
};

// Family #145812 · element #145812 · 24 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/station.mjs#L84-L90
export const f145812_dcOrder = function dcOrder(n, wiring = 'sequential') {
  if (wiring === 'sequential') return Array.from({ length: n }, (_, i) => i);
  const a = [];
  for (let i = 0; i < n; i += 2) a.push(i);
  for (let i = n % 2 ? n - 2 : n - 1; i >= 1; i -= 2) a.push(i);
  return a;
};

// Family #145822 · element #145822 · 24 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/station.mjs#L171-L174
export const f145822_compoundBox = function compoundBox(transformers) {
  const xs = transformers.map(p => p[0]), ys = transformers.map(p => p[1]);
  return [Math.min(...xs) - 12, Math.min(...ys) - 12, Math.max(...xs) + 12, Math.max(...ys) + 12];
};

// Family #145827 · element #145827 · 24 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/station.mjs#L215-L224
export const f145827_placer = function placer(at = [0, 0, 0], heading = 0) {
  const c = Math.cos(heading), s = Math.sin(heading), z0 = at[2] || 0;
  const point = ([x, y, z = 0]) => [at[0] + x * c + y * s, at[1] - x * s + y * c, z0 + z];
  const box = b => {
    const q = [[b.min[0], b.min[1]], [b.max[0], b.min[1]], [b.max[0], b.max[1]], [b.min[0], b.max[1]]].map(([x, y]) => point([x, y, 0]));
    const xs = q.map(p => p[0]), ys = q.map(p => p[1]);
    return { ...b, min: [Math.min(...xs), Math.min(...ys), z0 + b.min[2]], max: [Math.max(...xs), Math.max(...ys), z0 + b.max[2]], quad: q.map(p => [p[0], p[1]]) };
  };
  return { point, box };
};

// Family #145855 · element #145855 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/lidar-stream/r5.mjs#L124-L128
export const f145855_inflate = async function inflate(bytes) {
  if (typeof DecompressionStream !== 'function') throw Error('this browser cannot inflate deflate-compressed GeoTIFF');
  const s = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate'));
  return new Uint8Array(await new Response(s).arrayBuffer());
};

// Family #146343 · element #146343 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/block-build.mjs#L239-L246
export const f146343_blockCounts = function blockCounts(b) {
  const i = b.summary.inventory;
  return { tables: i.tables, tableKwp: i.tableKwp, blockKwp: b.summary.blockKwp, strings: i.totalStrings, connectedStrings: i.connectedStrings,
    spareStrings: i.spareStrings, inverters: i.inverters, stringsPerInverter: [...new Set(i.stringsPerInverter)], inverterKVA: i.inverterKVA,
    transformers: i.transformers, transformerMVA: i.transformerMVA, stationMVA: i.aggregateTransformerMVA, acPhaseCables: i.acPhaseCables,
    dcHomeCables: i.dcHomeCables, dcRoutes: b.cables.dc.length, acRoutes: b.cables.ac.length, stations: b.mv.stations.length,
    rings: b.mv.rings.length, gridTransformers: b.mv.grid.units, gridMVA: b.mv.grid.mva, pocKv: b.mv.poc.kv };
};

// Family #146441 · element #146441 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/mv-network.mjs#L45-L55
export const f146441_solidLines = function solidLines(solids) {
  const v = [];
  for (const s of solids) {
    const q = s.quad, z0 = s.min[2], z1 = s.max[2];
    for (let i = 0; i < 4; i++) {
      const a = q[i], b = q[(i + 1) % 4];
      v.push(a[0], a[1], z0, b[0], b[1], z0, a[0], a[1], z1, b[0], b[1], z1, a[0], a[1], z0, a[0], a[1], z1);
    }
  }
  return new Float32Array(v);
};

// Family #146445 · element #146445 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/mv-network.mjs#L76-L82
export const f146445_drawingToGround = function drawingToGround({ at = [0, 0], metresPerUnit = 1, heading = 0, yDown = false } = {}) {
  const c = Math.cos(heading), s = Math.sin(heading);
  return (x, y) => {
    const u = x * metresPerUnit, v = (yDown ? -y : y) * metresPerUnit;
    return [at[0] + u * c + v * s, at[1] - u * s + v * c];
  };
};

// Family #146447 · element #146447 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/mv-network.mjs#L120-L127
export const f146447_cableLines = function cableLines(cables, kind = null) {
  const v = [];
  for (const c of cables) {
    if (kind && c.kind !== kind) continue;
    for (let i = 1; i < c.points.length; i++) v.push(...c.points[i - 1], ...c.points[i]);
  }
  return new Float32Array(v);
};

// Family #146456 · element #146456 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-feeders.mjs#L24-L28
export const f146456_toSpine = function toSpine(pt, net) {
  if (pt.line === 'track') return { parts: [{ key: 't' + pt.k, a: pt.u, b: net.us }], v: net.tracks[pt.k] };
  if (pt.line === 'access') return { parts: [{ key: 'a', a: pt.u, b: net.us }], v: net.cv };
  return { parts: [], v: pt.v };
};

// Family #146458 · element #146458 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-feeders.mjs#L40-L54
export const f146458_coverage = function coverage(intervals) {
  const ev = [];
  for (const { a, b } of intervals) { ev.push([Math.min(a, b), 1], [Math.max(a, b), -1]); }
  ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const out = [];
  let c = 0, last = null;
  for (const [x, d] of ev) {
    if (c > 0 && last !== null && x > last) {
      const prev = out[out.length - 1];
      if (prev && prev.c === c && Math.abs(prev.b - last) < 1e-9) prev.b = x; else out.push({ a: last, b: x, c });
    }
    c += d; last = x;
  }
  return out;
};

// Family #146471 · element #146471 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-layout.mjs#L65-L68
export const f146471_frameOf = function frameOf(layout) {
  const swap = layout !== 'south';
  return { swap, uv: (e, n) => (swap ? [n, e] : [e, n]), en: (u, v) => (swap ? [v, u] : [u, v]) };
};

// Family #146472 · element #146472 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-layout.mjs#L69-L76
export const f146472_inside = function inside(poly, x, y) {
  let c = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
  }
  return c;
};

// Family #146488 · element #146488 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-template.mjs#L197-L224
export const f146488_pack = function pack(feeders, n) {
  const load = new Array(n).fill(0), out = new Array(feeders.length);
  feeders.map((f, i) => [f.loadMVA, i]).sort((a, b) => b[0] - a[0]).forEach(([l, i]) => {
    const t = load.indexOf(Math.min(...load)); out[i] = t; load[t] += l;
  });
  const L = i => feeders[i].loadMVA;
  for (let pass = 0, better = true; better && pass < 200; pass++) {
    better = false;
    const hi = load.indexOf(Math.max(...load));
    for (let i = 0; i < out.length && !better; i++) {
      if (out[i] !== hi) continue;
      for (let t = 0; t < n && !better; t++) {
        if (t === hi) continue;
        if (Math.max(load[hi] - L(i), load[t] + L(i)) < load[hi] - 1e-9) {        // move i to t
          load[hi] -= L(i); load[t] += L(i); out[i] = t; better = true; break;
        }
        for (let j = 0; j < out.length; j++) {                                    // swap i with j on t
          if (out[j] !== t || L(j) >= L(i)) continue;
          const d = L(i) - L(j);
          if (Math.max(load[hi] - d, load[t] + d) < load[hi] - 1e-9) {
            load[hi] -= d; load[t] += d; out[i] = t; out[j] = hi; better = true; break;
          }
        }
      }
    }
  }
  return out;
};

// Family #146494 · element #146494 · 22 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/plant-template.mjs#L249-L267
export const f146494_layoutDiagram = function layoutDiagram(d) {
  const pos = new Map(), boards = d.nodes.filter(n => n.kind === 'switchboard');
  const byBoard = boards.map(b => d.feeders.filter(f => f.board === b.id));
  let x = 0;
  boards.forEach((b, i) => {
    const w = Math.max(1, byBoard[i].length);
    pos.set(b.id, { x: x + (w - 1) / 2, y: 2 });
    byBoard[i].forEach((f, j) => f.chain.forEach((s, k) => {
      const n = s.id.slice(1);
      pos.set(`R${n}`, { x: x + j, y: 3 + k }); pos.set(s.id, { x: x + j + 0.4, y: 3 + k }); pos.set(`A${n}`, { x: x + j + 0.4, y: 3.4 + k });
    }));
    x += w + 1;
  });
  const gts = d.nodes.filter(n => n.kind === 'grid-transformer');
  gts.forEach((g, i) => { const b = pos.get(`MVB${i + 1}`) || { x: i * 2 }; pos.set(g.id, { x: b.x, y: 1 }); });
  const mid = (Math.max(0, ...[...pos.values()].map(v => v.x))) / 2;
  pos.set('POC', { x: mid, y: 0 }); pos.set('HF', { x: mid + 1, y: 0 });
  return d.nodes.map(n => ({ ...n, ...(pos.get(n.id) || { x: 0, y: 0 }) }));
};

// Family #23160 · element #23160 · 17 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/testcode/202609060232/pipeline/assets/202609060232-bbc-rss-pipeline-model.mjs#L6-L13
export const f23160_articleIdentity = function articleIdentity(value) {
  try {
    const url = new URL(value);
    const match = url.pathname.match(/^\/news\/articles\/([a-z0-9]+)\/?$/i);
    if (url.protocol !== 'https:' || !['www.bbc.co.uk','www.bbc.com'].includes(url.hostname) || !match) return null;
    return {id:'bbc:'+match[1].toLowerCase(), url:`https://www.bbc.co.uk/news/articles/${match[1].toLowerCase()}`};
  } catch { return null; }
};

// Family #73330 · element #73330 · 4 places in 2 repositories · https://github.com/Ventusltd/code-generator/blob/3897d83efcd0259d21dce87704b0c33118fe2c2e/apps/substation-finder/Ps/202608282348-verify-v9-6-2-equivalence.mjs#L25-L28
export const f73330_firstNumber = function firstNumber(text) {
  const match = String(text).replaceAll(",", "").match(/\d+(?:\.\d+)?/u);
  return match ? Number(match[0]) : Number.NaN;
};

// Family #175938 · element #175938 · 4 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L306-L308
export const f175938_trainCoordinate = function trainCoordinate(at) {
  return Array.isArray(at) && at.length === 2 && at.every(v => typeof v === 'number' && Number.isFinite(v)) && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90 && !(at[0] === 0 && at[1] === 0);
};

// Family #175951 · element #175951 · 4 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L414-L423
export const f175951_normaliseJourneyLaw = function normaliseJourneyLaw(value = {}) {
  if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !['schema','mustVisitStationIds','allowedVoltageBands','fallback','allowTransformers'].includes(key))) throw new Error('Journey law must use the supported declarative fields only.');
  if(value.schema != null && value.schema !== 'gridatlas.journey-law.v1') throw new Error('Unknown journey law schema.');
  const ids=value.mustVisitStationIds ?? [],bands=value.allowedVoltageBands ?? null,fallback=value.fallback ?? 'documented-only',allowTransformers=value.allowTransformers ?? true;
  if(!Array.isArray(ids)||ids.length>90||ids.some(id=>typeof id!=='string'||!id.trim()||/[\u0000-\u001f\u007f]/.test(id)))throw new Error('Ordered must-visit entries require stable station IDs.');
  const supported=new Set(['400','275','220','132','66','33','11','other','unknown']);
  if(bands!==null&&(!Array.isArray(bands)||bands.some(b=>typeof b!=='string'||!supported.has(b))))throw new Error('Choose supported source voltage bands.');
  if(!['documented-only','user-opted-hypothetical'].includes(fallback)||typeof allowTransformers!=='boolean')throw new Error('Choose documented-only or explicit user hypothetical fallback and a boolean transformer gate.');
  return {schema:'gridatlas.journey-law.v1',mustVisitStationIds:ids.slice(),allowedVoltageBands:bands===null?null:[...new Set(bands)],fallback,allowTransformers};
};

// Family #175963 · element #175963 · 4 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L586-L605
export const f175963_trainExactBusPath = function trainExactBusPath(eligible, network, from, to) {
  const graph = eligible.graph(), START='@train-exact-start', END='@train-exact-end';
  // Query aliases avoid electrical-distance's same-SITE zero-hop shortcut.
  // They are not source nodes or graph edges: exact source bus IDs remain unchanged.
  const queryGraph = {...graph,nodesOfSite:code => code===START?[from.bus]:code===END?[to.bus]:graph.nodesOfSite(code)};
  const index = {graph:()=>queryGraph,site:key=>key===START?{code:START,name:from.binding.siteCode}
    :key===END?{code:END,name:to.binding.siteCode}:null};
  const result = network.electricalDistance.between(index,START,END,{voltageKv:from.kv,
    maxHops:Number.isInteger(network.maxHops)&&network.maxHops>0?Math.min(10000,network.maxHops):10000});
  if (result?.schema!=='gridatlas.module.electrical-distance.v1'||result.reached!==true
    ||result.from?.code!==START||result.to?.code!==END||!Array.isArray(result.path)) return null;
  const path=result.path;
  if (path.length ? path[0].from_node!==from.bus||path.at(-1).to_node!==to.bus : from.bus!==to.bus) return null;
  if (!path.every((hop,n)=>graph.has(hop.from_node)&&graph.has(hop.to_node)
    &&(!n||path[n-1].to_node===hop.from_node)
    &&graph.edgesAt(hop.from_node).some(edge=>edge.kind===hop.kind&&edge.row[edge.far]===hop.to_node))) return null;
  return {...result,from:{code:from.binding.siteCode},to:{code:to.binding.siteCode},arrival_node:to.bus,
    path:path.map(hop=>{const rows=graph.edgesAt(hop.from_node).filter(edge=>edge.kind===hop.kind&&edge.row[edge.far]===hop.to_node);
      return {...hop,circuit_id:rows.length===1?rows[0].row.circuit_id||rows[0].row.id||null:null};})};
};

// Family #175967 · element #175967 · 4 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L623-L626
export const f175967_validLine = function validLine(line) {
  return Array.isArray(line) && line.length >= 2 && line.length <= 10000 && line.every(at =>
    Array.isArray(at) && at.length === 2 && at.every(Number.isFinite) && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90);
};

// Family #175981 · element #175981 · 4 places in 2 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/202611180026-grid-vicinity.js#L629-L808
export const f175981_createTrainRide = function createTrainRide({map, geodesy, palette = {}, onState = () => {}, reducedMotion = false, readPlanEpoch = null,
  requestFrame = globalThis.requestAnimationFrame?.bind(globalThis),
  cancelFrame = globalThis.cancelAnimationFrame?.bind(globalThis),
  setTimer = globalThis.setTimeout?.bind(globalThis), clearTimer = globalThis.clearTimeout?.bind(globalThis)} = {}) {
  if (!map || typeof geodesy?.distanceKm !== 'function') throw Error('Map and canonical geodesy required.');
  const prefix = 'gridatlas-train-', sources = new Map(), layers = new Map();
  const colour = palette.SUBSTATION_COLOUR || palette.substation || '#5fbdc2'; // Existing SLD substation colour.
  const flowColour = palette.FLOW_COLOUR || '#bfe9ee';
  const customerColour = palette.CUSTOMER_SUBSTATION_COLOUR || '#e0b050'; // Existing SLD_COLOUR.node customer_substation glyph.
  // Same 24 cached dash patterns as the existing SLD neon renderer; no atlas growth per frame.
  const flowPatterns = Array.from({length: 24}, (_, i) => Object.freeze([0.001,
    Math.max(0.001, i / 24 * 1.5), 0.42, Math.max(0.001, 1.5 - i / 24 * 1.5)]));
  let lastDashIndex = -1;
  let alive = true, plan = null, pinStops = [], playing = false, handle = null, legIndex = 0, fraction = 0, epoch = 0, measures = [], prefixStop = 0;
  let lastTime = null, lastPaint = -Infinity, cameraFollow = false, durationMs = 2400, unavailable = null;
  let retryHandle = null, retryCount = 0;
  const state = () => ({schema: 'gridatlas.train.motion.v1', alive, playing, legIndex, fraction,
    stopIndex: fraction === 1 ? legIndex + 1 : legIndex, reducedMotion: !!reducedMotion,
    cameraFollow, unavailable, approvedThroughStop: prefixStop, evidence: plan?.legs[legIndex]?.evidence || null,
    electricalFlow: 'UNKNOWN', simulated: !!plan?.simulated, stops: plan?.stops.length || pinStops.length});
  const notify = () => onState(state());
  const collection = features => ({type: 'FeatureCollection', features});
  const point = (at, properties = {}) => ({type: 'Feature', properties, geometry: {type: 'Point', coordinates: at}});
  function cancel() { epoch++; if (handle !== null) cancelFrame?.(handle); handle = null; lastTime = null; }
  function schedule() { const token = epoch; handle = requestFrame(time => { if (token === epoch) tick(time); }); }
  function pause() { playing = false; cancel(); notify(); return state(); }
  function cancelRetry() { if(retryHandle!==null)clearTimer?.(retryHandle);retryHandle=null;retryCount=0; }
  function waitForStyle() {
    unavailable = retryCount < 12 ? 'Map style is loading; drawing will retry briefly.' : 'Map style is not ready. Retry Draw when the map is ready.';
    if(retryHandle===null && retryCount<12 && typeof setTimer==='function') {
      retryCount++;retryHandle=setTimer(()=>{retryHandle=null;if(alive)paint();},250);
    }
    notify();return false;
  }
  function ensure() {
    if (!alive || !plan && !pinStops.length) return false;
    const sourceIds = ['routes', 'stops', 'cursor'].map(id => prefix + id);
    const layerIds = ['route-gis', 'route-topology', 'route-simulated', 'flow', 'stops', 'proposals', 'cursor'].map(id => prefix + id);
    for (const id of sourceIds) {
      const existing = map.getSource(id);
      if (existing && existing !== sources.get(id)) { unavailable = 'Source ID belongs to another module'; pause(); return false; }
    }
    for (const id of layerIds) {
      const existing = map.getLayer(id);
      if (existing && existing !== layers.get(id)) { unavailable = 'Layer ID belongs to another module'; pause(); return false; }
    }
    // Existing verified sources remain writable while their own setData is
    // pending. Global isStyleLoaded also includes that work; it is not a
    // readiness test for an owned source or for each animation frame.
    if(sourceIds.some(id=>!map.getSource(id)) && map.isStyleLoaded?.()===false) return waitForStyle();
    for (const id of sourceIds) if (!map.getSource(id)) {
      map.addSource(id, {type: 'geojson', data: collection([])}); sources.set(id, map.getSource(id));
    }
    const add = spec => { if (!map.getLayer(spec.id)) { map.addLayer(spec); layers.set(spec.id, map.getLayer(spec.id)); if (spec.id === prefix + 'flow') lastDashIndex = -1; } };
    const line = {type: 'line', source: prefix + 'routes', layout: {'line-cap': 'round', 'line-join': 'round'}};
    add({...line, id: prefix + 'route-gis', filter: ['==', ['get', 'evidence'], 'GIS_REVIEWED'],
      paint: {'line-color': colour, 'line-width': 1.8, 'line-opacity': 0.8}});
    add({...line, id: prefix + 'route-topology', filter: ['==', ['get', 'evidence'], 'TOPOLOGY_ONLY'],
      paint: {'line-color': colour, 'line-width': 1.4, 'line-opacity': 0.65, 'line-dasharray': [5, 2]}});
    add({...line, id: prefix + 'route-simulated', filter: ['==', ['get', 'evidence'], 'SIMULATED'],
      paint: {'line-color': colour, 'line-width': 1.4, 'line-opacity': 0.65, 'line-dasharray': [1, 3]}});
    // Existing l-neon-flow rhythm, confined to our own overlay.
    add({...line, id: prefix + 'flow',filter:['==',['get','evidence'],'GIS_REVIEWED'], paint: {'line-color': flowColour, 'line-width': 1.2,
      'line-opacity': reducedMotion ? 0 : 0.45, 'line-dasharray': [0.2, 3.2]}});
    add({id: prefix + 'stops', type: 'circle', source: prefix + 'stops', filter:['!=',['get','proposed'],true],paint: {
      'circle-color': colour, 'circle-radius': 3, 'circle-opacity': 0.8}});
    add({id:prefix+'proposals',type:'circle',source:prefix+'stops',filter:['==',['get','proposed'],true],paint:{
      'circle-color':customerColour,'circle-radius':5,'circle-stroke-color':'#000c10','circle-stroke-width':1.5,'circle-opacity':0.9}});
    add({id: prefix + 'cursor', type: 'circle', source: prefix + 'cursor', paint: {
      'circle-color': colour, 'circle-radius': 5, 'circle-stroke-color': '#000c10', 'circle-stroke-width': 1.5}});
    cancelRetry();unavailable = null; return true;
  }
  function position() {
    const line = plan?.legs[legIndex]?.coordinates;
    if (!line) return plan?.stops[legIndex]?.at || null;
    if (fraction === 1) return line.at(-1);
    const cumulative = measures[legIndex], wanted = cumulative.at(-1) * fraction;
    let lo = 1, hi = cumulative.length - 1;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (cumulative[mid] < wanted) lo = mid + 1; else hi = mid; }
    const i = lo - 1, span = cumulative[lo] - cumulative[i], t = span ? (wanted - cumulative[i]) / span : 0;
    return [line[i][0] + (line[lo][0] - line[i][0]) * t, line[i][1] + (line[lo][1] - line[i][1]) * t];
  }
  function paint() {
    if(plan && readPlanEpoch && readPlanEpoch()!==plan.planEpoch){clearPlan();return;}
    if (!ensure()) return;
    sources.get(prefix + 'routes').setData(collection((plan?.legs||[]).slice(0,prefixStop).filter(l => l.coordinates).map(l => ({type: 'Feature',
      properties: {evidence: l.evidence, label: l.label}, geometry: {type: 'LineString', coordinates: l.coordinates}}))));
    sources.get(prefix + 'stops').setData(stopData(plan?.stops||pinStops));
    paintCursor();
  }
  function paintCursor() {
    if (!alive || !plan || !sources.has(prefix + 'cursor') || map.getSource(prefix + 'cursor') !== sources.get(prefix + 'cursor')) return;
    const at = position(); sources.get(prefix + 'cursor').setData(collection(at ? [point(at, {meaning: 'User journey heading; electrical flow unknown'})] : []));
    if (cameraFollow && playing && at) map.easeTo?.({center: at, duration: 0});
  }
  function tick(time) {
    handle = null; if (!alive || !playing) return;
    if (readPlanEpoch && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return; }
    if(!sources.has(prefix+'cursor') || map.getSource(prefix+'cursor')!==sources.get(prefix+'cursor')) {pause();return;}
    if (lastTime === null) lastTime = time;
    fraction += Math.max(0, Math.min(250, time - lastTime)) / durationMs; lastTime = time;
    if (fraction >= 1) {
      if (legIndex < plan.legs.length - 1) { legIndex++; fraction = 0; } else { fraction = 1; playing = false; }
    }
    if (time - lastPaint >= 33 || !playing) {
      lastPaint = time; paintCursor();
      const layer = map.getLayer(prefix + 'cursor');
      if (layer === layers.get(prefix + 'cursor')) map.setPaintProperty(prefix + 'cursor', 'circle-radius', 5 + Math.sin(fraction * Math.PI) * 1.5);
      const dashIndex = Math.floor(fraction * 24) % 24;
      if (dashIndex !== lastDashIndex && map.getLayer(prefix + 'flow') === layers.get(prefix + 'flow')) {
        lastDashIndex = dashIndex; map.setPaintProperty(prefix + 'flow', 'line-dasharray', flowPatterns[dashIndex]);
      }
      notify();
    }
    if (playing) schedule();
  }
  function setPlan(next) {
    if (!alive) throw Error('Train ride is destroyed.');
    // Reject stale asynchronous results before clearing or painting any current ride.
    if(readPlanEpoch && next?.planEpoch!==readPlanEpoch())throw Error('Stale journey plan epoch.');
    clearPlan({stops:pinStops});
    if (next?.schema !== 'gridatlas.train.route-plan.v1' || !Array.isArray(next.legs) || !next.legs.length
      || !Array.isArray(next.stops) || next.stops.length !== next.legs.length + 1
      || next.legs.reduce((n, leg) => n + (leg.coordinates?.length || 0), 0) > 20000) throw Error('Invalid or oversized journey plan.');
    // Snapshot input so later UI edits cannot mutate an active ride.
    const copy = JSON.parse(JSON.stringify(next)); plan = copy; pinStops = copy.stops;
    const gap = plan.legs.findIndex(leg => !leg.coordinates || leg.evidence === 'MISSING');
    prefixStop = gap < 0 ? plan.legs.length : gap;
    measures = plan.legs.map(leg => { const cumulative = [0];
      for (let i = 1; i < (leg.coordinates?.length || 0); i++) cumulative.push(cumulative.at(-1) + geodesy.distanceKm(...leg.coordinates[i - 1], ...leg.coordinates[i]));
      return cumulative; });
    legIndex = 0; fraction = 0; paint(); notify(); return state();
  }
  function play(options = {}) {
    if (readPlanEpoch && plan && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return false; }
    if (!alive || !plan?.playable || prefixStop !== plan.legs.length || unavailable) return false;
    cameraFollow = options.cameraFollow === true;
    if (Number.isFinite(options.durationMs)) durationMs = Math.max(500, Math.min(30000, options.durationMs));
    if (reducedMotion) { step(); return false; }
    if (typeof requestFrame !== 'function') return false;
    if (playing) return true;
    if (legIndex === plan.legs.length - 1 && fraction === 1) { legIndex = 0; fraction = 0; }
    playing = true; lastTime = null; schedule(); notify(); return true;
  }
  function seekStop(index) {
    if (readPlanEpoch && plan && readPlanEpoch() !== plan.planEpoch) { clearPlan(); return false; }
    if (!alive || !plan || !Number.isInteger(index) || index < 0 || index > prefixStop || index >= plan.stops.length) return false;
    pause(); legIndex = index === prefixStop && index > 0 ? index - 1 : index;
    fraction = index === prefixStop && index > 0 ? 1 : 0;
    paintCursor(); notify(); return true;
  }
  function step() { const next = state().stopIndex + 1; return next <= prefixStop && seekStop(next); }
  function stopData(stops) { return collection(stops.map((stop,i)=>point(stop.at,{stationId:stop.id||stop.stationId,stopIndex:i,
    proposed:stop.proposed===true,kind:stop.proposed?'customer_substation':'source_substation',label:stop.proposed?'PROPOSED SESSION ONLY':stop.name||''}))); }
  function clearPlan({stops=[]}={}) {
    if (!alive) return false;
    if (!Array.isArray(stops) || stops.length>90 || stops.some(stop=>!Array.isArray(stop.at)||stop.at.length!==2
      ||!stop.at.every(Number.isFinite)||Math.abs(stop.at[0])>180||Math.abs(stop.at[1])>90)) throw Error('Invalid selected station pins.');
    cameraFollow=false;cancelRetry();pause();plan=null;measures=[];prefixStop=0;legIndex=0;fraction=0;
    pinStops=JSON.parse(JSON.stringify(stops.filter(stop=>!stop.invalid)));
    if(ensure()) for(const [suffix,data]of [['routes',collection([])],['cursor',collection([])],['stops',stopData(pinStops)]]) {
      const id=prefix+suffix;if(map.getSource(id)===sources.get(id))sources.get(id).setData(data);
    }
    // Empty selections still clear existing owned layers/sources without adding any.
    if(!pinStops.length)for(const suffix of ['routes','cursor','stops']){const id=prefix+suffix;
      if(sources.has(id)&&map.getSource(id)===sources.get(id))sources.get(id).setData(collection([]));}
    notify();return true;
  }
  function styleReload() { if (!alive) return; cancelRetry();pause(); paint(); }
  function removed() { if (!alive) return; alive = false; playing = false; cancelRetry();cancel(); sources.clear(); layers.clear(); map.off('style.load', styleReload); notify(); }
  function destroy() {
    if (!alive) return; cancelRetry();pause();
    for (const [id, layer] of [...layers].reverse()) if (map.getLayer(id) === layer) map.removeLayer(id);
    for (const [id, source] of sources) if (map.getSource(id) === source) map.removeSource(id);
    sources.clear(); layers.clear(); alive = false;
    map.off('style.load', styleReload); map.off('remove', removed); notify();
  }
  map.on('style.load', styleReload); map.on('remove', removed);
  return Object.freeze({setPlan, clearPlan, play, pause, step, seekStop, destroy, snapshot: state});
};

// Family #1600 · element #1600 · 93 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311343/assets/202608291447-app.mjs#L222-L224
export const f1600_invariant = function invariant(condition, message) {
  if (!condition) throw new Error(`PipelineNews V9 timestamped runtime: ${message}`);
};

// Family #1981 · element #1981 · 81 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311645/assets/202608291447-app.mjs#L146-L153
export const f1981_compareText = function compareText(leftText, rightText, direction) {
  const left = leftText || "";
  const right = rightText || "";
  if (!left && !right) return 0;
  if (!left) return 1;
  if (!right) return -1;
  return direction * left.localeCompare(right, "en-GB");
};

// Family #2314 · element #2314 · 75 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608311816/assets/202608291447-app.mjs#L595-L597
export const f2314_formatMw = function formatMw(value) {
  return value.toLocaleString("en-GB", { maximumFractionDigits: 2 });
};

// Family #3091 · element #3091 · 62 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202608312145/assets/202608311610-grid-proximity.mjs#L258-L264
export const f3091_value = (r, k) => (
      k === "_tkm" ? (r.circuit_transmission ? r.circuit_transmission.km : Infinity)
        : k === "_gp" ? (r.circuit ? r.circuit.km : Infinity)
        : k === "_ckm" ? (r.circuit ? r.circuit.km : Infinity)
        : k === "_ckv" ? (r.circuit ? r.circuit.kv : -1)
          : k === "_skm" ? (r.substation ? r.substation.km : Infinity)
            : r[k]);

// Family #18686 · element #18686 · 26 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051932/tool-layers/dismissal.js#L2-L16
export const f18686_bindLayerDismissal = function bindLayerDismissal(layer, frame, close) {
  const handle = event => {
    if (event.key !== 'Escape' || event.defaultPrevented || layer.style.display === 'none') return;
    event.preventDefault(); close();
  };
  let child;
  const detachChild = () => { child?.removeEventListener('keydown', handle); child = undefined; };
  const loaded = () => {
    detachChild();
    try { child = frame.contentDocument; child?.addEventListener('keydown',handle); } catch { /* Cross-origin navigation keeps the parent close control. */ }
  };
  layer.addEventListener('keydown', handle);
  frame.addEventListener('load',loaded);
  return () => {detachChild(); layer.removeEventListener('keydown',handle); frame.removeEventListener('load',loaded);};
};

// Family #19444 · element #19444 · 22 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051940/tool-layers/readiness.js#L11-L17
export const f19444__anonymous_ = canvas=>{
      try {const bytes=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data;
        let opaque=0;const colors=new Set();
        for(let i=0;i<bytes.length;i+=64) if(bytes[i+3]) {opaque++;colors.add(bytes[i]+','+bytes[i+1]+','+bytes[i+2]);}
        return opaque>=8 && colors.size>=2;
      } catch {return false;} return false;
    };

// Family #19825 · element #19825 · 20 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051945/tool-layers/viewport.js#L2-L16
export const f19825_applyToolViewport = function applyToolViewport(layer, bar, frame) {
  Object.assign(layer.style,{boxSizing:'border-box',width:'100%',height:'100%',overflow:'hidden'});
  if(globalThis.CSS?.supports('height','100dvh')) layer.style.height='100dvh';
  Object.assign(bar.style,{
    display:'grid',gridTemplateColumns:'minmax(0,1fr) minmax(100px,auto)',
    columnGap:'12px',rowGap:'2px',flexShrink:'0',boxSizing:'border-box',
    paddingTop:'max(6px, env(safe-area-inset-top))',paddingBottom:'6px',
    paddingLeft:'max(12px, env(safe-area-inset-left))',paddingRight:'max(12px, env(safe-area-inset-right))'
  });
  const title=bar.querySelector('strong'), status=bar.querySelector('[data-tool-readiness]'), close=bar.querySelector('button');
  Object.assign(title.style,{gridColumn:'1',gridRow:'1',minWidth:'0',overflowWrap:'anywhere'});
  Object.assign(status.style,{gridColumn:'1',gridRow:'2',fontSize:'12px',minWidth:'0',overflowWrap:'anywhere'});
  Object.assign(close.style,{gridColumn:'2',gridRow:'1 / 3',minHeight:'44px',maxWidth:'min(220px,45vw)',whiteSpace:'normal'});
  Object.assign(frame.style,{display:'block',minWidth:'0',minHeight:'0',width:'100%',flex:'1 1 0',boxSizing:'border-box'});
};

// Family #5152 · element #5152 · 19 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202609050309/assets/202608291447-app.mjs#L1898-L1901
export const f5152__anonymous_ = (response) => {
        if (!response.ok) throw new Error(`genome HTTP ${response.status}`);
        return response.json();
      };

// Family #5153 · element #5153 · 19 places in 2 repositories · https://github.com/Ventusltd/globalgrid2050/blob/32ae2ded87b626ab573efa6887547f2128c55304/pipelinenews_intelligence/202609050309/assets/202608291447-app.mjs#L1902-L1907
export const f5153__anonymous_ = (genome) => {
        if (!Array.isArray(genome?.nodes) || !genome.nodes.length) {
          throw new Error("genome carries no nodes");
        }
        return genome;
      };

// Family #147204 · element #147204 · 19 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/world/ostn15.mjs#L17-L26
export const f147204_decodeBlock = function decodeBlock(buffer) {
  const dv = new DataView(buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
  const magic = String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2), dv.getUint8(3));
  if (magic !== 'O15B' || dv.getUint16(4, true) !== 1) throw Error('not an OSTN15 block (O15B version 1)');
  const cols = dv.getUint16(6, true), rows = dv.getUint16(8, true);
  if (dv.byteLength !== 16 + cols * rows * 8) throw Error(`OSTN15 block is ${dv.byteLength} bytes, expected ${16 + cols * rows * 8}`);
  const v = new Int32Array(cols * rows * 2);
  for (let k = 0; k < v.length; k++) v[k] = dv.getInt32(16 + 4 * k, true);
  return { lat0: dv.getInt16(12, true), lon0: dv.getInt16(14, true), cols, rows, v };
};

// Family #20202 · element #20202 · 18 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051948/tool-layers/focus-boundary.js#L2-L24
export const f20202_bindFocusBoundary = function bindFocusBoundary(layer, frame, close) {
  let child;
  const items = () => [...(child?.querySelectorAll('a[href],button,input,select,textarea,[tabindex]') || [])]
    .filter(node => !node.disabled && node.tabIndex >= 0 && !node.closest('[inert]') && node.getClientRects().length && child.defaultView.getComputedStyle(node).visibility !== 'hidden');
  const handle = event => {
    if(event.key !== 'Tab' || event.defaultPrevented || layer.style.display === 'none' || !child) return;
    const nodes=items(), first=nodes[0], last=nodes.at(-1);
    const controls=layer.querySelectorAll ? [...layer.querySelectorAll('button')].filter(node=>!node.disabled && node.tabIndex>=0 && node.getClientRects().length && node.ownerDocument.defaultView.getComputedStyle(node).visibility!=='hidden') : [close];
    const firstControl=controls[0] || close, lastControl=controls.at(-1) || close;
    let target;
    if(event.target===firstControl && event.shiftKey) target=last || lastControl;
    else if(event.target===lastControl && !event.shiftKey) target=first || firstControl;
    else if(event.shiftKey && event.target===first) target=lastControl;
    else if(!event.shiftKey && event.target===last) target=firstControl;
    if(target) {event.preventDefault();target.focus();}
  };
  const loaded = () => {
    child?.removeEventListener('keydown',handle); child=undefined;
    try {child=frame.contentDocument;child?.addEventListener('keydown',handle);} catch { /* Parent close remains keyboard accessible after cross-origin navigation. */ }
  };
  layer.addEventListener('keydown',handle);frame.addEventListener('load',loaded);
  return () => {child?.removeEventListener('keydown',handle);layer.removeEventListener('keydown',handle);frame.removeEventListener('load',loaded);};
};

// Family #20589 · element #20589 · 16 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051953/tool-layers/readiness.js#L2-L24
export const f20589_inspectToolReadiness = function inspectToolReadiness(id, doc) {
  if(!doc || doc.readyState !== 'complete') return {interface:'loading',drawing:'pending',label:'Loading tool'};
  const identity={'module-layout':'#ml_status','cable-geometry-visualiser':'#route_name','gis-sld-financial-sandbox':'#btn_draw'}[id];
  if(identity && !doc.querySelector(identity))return {interface:'unrecognised',drawing:'unreported',label:'Tool interface not recognised'};
  if(id==='module-layout') {
    const ready=doc.querySelector('#ml_status')?.textContent.includes('Ready. Draw at map centre or pick a site.');
    return {interface:'loaded',drawing:ready?'ready':'pending',label:ready?'Map ready':'Loading map'};
  }
  if(id==='cable-geometry-visualiser') {
    const canvases=[...doc.querySelectorAll('canvas')];
    const expected=['formation_canvas','trench_canvas','bend_canvas'];
    const ready=canvases.length===3 && expected.every(id=>canvases.some(c=>c.id===id)) && canvases.every(canvas=>{
      try {const bytes=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data;
        let opaque=0;const colors=new Set();
        for(let i=0;i<bytes.length;i+=64) if(bytes[i+3]) {opaque++;colors.add(bytes[i]+','+bytes[i+1]+','+bytes[i+2]);}
        return opaque>=8 && colors.size>=2;
      } catch {return false;} return false;
    });
    return {interface:'loaded',drawing:ready?'ready':'pending',label:ready?'Drawings ready':'Loading drawings'};
  }
  if(id==='gis-sld-financial-sandbox' && doc.querySelector('#btn_draw')) return {interface:'loaded',drawing:'unreported',label:'Interface loaded'};
  return {interface:'unrecognised',drawing:'unreported',label:'Tool interface not recognised'};
};

// Family #20593 · element #20593 · 16 places in 2 repositories · https://github.com/Ventusltd/testcode/blob/a8a215982b13d6e2f6019b40bf0bef5755719773/sandbox/202609051953/tool-layers/recovery.js#L1-L3
export const f20593_shouldOfferRecovery = function shouldOfferRecovery(state) {
  return state.interface==='unrecognised' || state.timedOut==='true';
};

// Family #147599 · element #147599 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/block-build.mjs#L40-L43
export const f147599_pileTotals = P => ({ revealAdjust: P.summary.revealAdjust, outsideBand: P.summary.revealHigh + P.summary.revealLow,
  twistTables: P.summary.twistTables, gradingTables: P.summary.tablesNeedingGrading, cutM3: P.summary.cutM3, fillM3: P.summary.fillM3,
  totalPileLengthM: P.summary.totalPileLengthM, embeddedM: P.piles.reduce((t, p) => t + p.embed, 0), embedM: P.assumed.embedMin,
  revealAdjustM: P.assumed.revealAdjust, twistTolDeg: P.assumed.twistTolDeg });

// Family #147690 · element #147690 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-derive.mjs#L27-L30
export const f147690_formationOf = function formationOf(formation, od) {
  return formation === 'flat' ? { span: 5 * od, height: od, centres: [[-2 * od, od / 2], [0, od / 2], [2 * od, od / 2]] }
    : { span: 2 * od, height: od * (1 + Math.sqrt(3) / 2), centres: [[-od / 2, od / 2], [od / 2, od / 2], [0, od / 2 + od * Math.sqrt(3) / 2]] };
};

// Family #147691 · element #147691 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-derive.mjs#L33-L38
export const f147691_cableFor = function cableFor(catalogue, size, metal = 'al') {
  const list = catalogue?.cables || [];
  const want = metal === 'cu' ? new RegExp(`^33kv-1c-cu-xlpe-${size}(-|$)`) : new RegExp(`^33kv-1c-al-xlpe-${size}$`);
  const c = list.find(x => want.test(x.id));
  return c ? { id: c.id, od: c.od_mm / 1000, odMm: c.od_mm, armoured: /armoured/.test(c.id), status: c.status || 'catalogue' } : null;
};

// Family #147692 · element #147692 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-derive.mjs#L41-L48
export const f147692_bendOf = function bendOf(catalogue, cable) {
  if (!cable) return null;
  const rules = (catalogue?.rules || []).filter(x => x.voltage_kv === 33 && x.construction === (cable.armoured ? 'single_core_armoured' : 'single_core_unarmoured'));
  const m = when => rules.find(x => x.when === when)?.multiple_of_od ?? null;
  const inst = m('installation'), fin = m('final');
  return { installM: inst ? inst * cable.od : null, finalM: fin ? fin * cable.od : null, installX: inst, finalX: fin,
    source: rules.find(x => x.when === 'installation')?.source || 'no rule in the catalogue' };
};

// Family #147694 · element #147694 · 16 places in 2 repositories · https://github.com/Ventusltd/energy-transition-simulator/blob/a165ce6d56cb22271828874d68d570e8fa5e428a/prototype/mod/engine/cmd-derive.mjs#L59-L63
export const f147694_shoelace = function shoelace(pts) {
  let a = 0;
  for (let i = 0; i < pts.length; i++) { const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % pts.length]; a += x0 * y1 - x1 * y0; }
  return a / 2;
};