GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Si

Substation Intelligence V9 63 (part 9)

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of JavaScript from code-generator, in 1 file. Topic: Grid network and substations. Section 291 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. Substation Intelligence V9 63 geodesy · code-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js lines 5601–6300

Substation Intelligence V9 63

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

Set aside from the main view: 100% of its lines are the same as atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9974 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 d94b0de50deddac77643325b10fbe490ce44b8c406dbc6c67e6e7cadbdaa8ec6
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesycode-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js · lines 5601–6300 of 8590 · version 2026-09-06 23:58 (continued from section 283) · Not reached from any entry point (candidate for review) · pattern switchOn (shared by 4 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
code-generator · apps/substation-finder/Si · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
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
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
none found
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
captureMapJpeg, grab, pdfFileStamp, pad, savePdf, say, appendExport, appendEstateLinks, layerCheckbox, buildLayerControls, move, trayRoute, chipStaysOnMap, adoptLate, install, loudFailure, start, tidy, retire, watch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js:5601-6300 · blob 2c8121b277e1b152a96688f6a2e0d7ef83471376 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
        + ' /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R >>'
        + ' /ExtGState << /GsA 7 0 R >> >> /Contents 4 0 R >>',
      '<< /Length ' + content.length + ' >>\nstream\n' + content + '\nendstream',
      '<< /Type /XObject /Subtype /Image /Width ' + pixelWidth + ' /Height ' + pixelHeight
        + ' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '
        + jpegBinary.length + ' >>\nstream\n' + jpegBinary + '\nendstream',
      '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>',
      '<< /Type /ExtGState /ca 0.55 >>'
    ];

    var out = '%PDF-1.4\n%\u00e2\u00e3\u00cf\u00d3\n';
    var offsets = [];
    var i;
    for (i = 0; i < objects.length; i += 1) {
      offsets.push(out.length);
      out += (i + 1) + ' 0 obj\n' + objects[i] + '\nendobj\n';
    }
    var xref = out.length;
    out += 'xref\n0 ' + (objects.length + 1) + '\n0000000000 65535 f \n';
    for (i = 0; i < offsets.length; i += 1) {
      out += ('0000000000' + offsets[i]).slice(-10) + ' 00000 n \n';
    }
    out += 'trailer\n<< /Size ' + (objects.length + 1) + ' /Root 1 0 R >>\n'
      + 'startxref\n' + xref + '\n%%EOF\n';

    var bytes = new Uint8Array(out.length);
    for (i = 0; i < out.length; i += 1) bytes[i] = out.charCodeAt(i) & 0xff;
    return { bytes: bytes, pageW: pageW, pageH: pageH };
  }

  /* JPEG rather than PNG: /DCTDecode embeds the bytes verbatim, so no
     compressor is needed here, and a basemap raster is what JPEG is for.
     Same render-frame discipline as captureMap -- a canvas without
     preserveDrawingBuffer is transparent to any reader outside the frame
     that drew it. */
  function captureMapJpeg(doc, then) {
    var map = mapHandle();
    var canvas = doc.querySelector('.maplibregl-canvas')
      || (map && map.getCanvas ? map.getCanvas() : null);
    if (!canvas) { then(null, null); return; }
    var grab = function () {
      var url = null;
      try { url = canvas.toDataURL('image/jpeg', 0.92); } catch (_) { url = null; }
      if (!url || url.indexOf('data:image/jpeg') !== 0 || looksBlank(canvas)) {
        then(null, canvas);
        return;
      }
      then(url, canvas);
    };
    if (map && map.once && map.triggerRepaint) {
      map.once('render', grab);
      map.triggerRepaint();
    } else {
      grab();
    }
  }

  function pdfFileStamp() {
    var d = new Date();
    var pad = function (n) { return (n < 10 ? '0' : '') + n; };
    return d.getUTCFullYear() + pad(d.getUTCMonth() + 1) + pad(d.getUTCDate())
      + pad(d.getUTCHours()) + pad(d.getUTCMinutes());
  }

  function savePdf(doc, button) {
    var say = function (text) { button.textContent = text; };
    say('... building PDF');
    captureMapJpeg(doc, function (jpegDataUrl, canvas) {
      if (!jpegDataUrl) {
        say('\u2298 The map could not be captured \u2014 try again once it has drawn');
        return;
      }
      var binary;
      try {
        binary = atob(jpegDataUrl.slice(jpegDataUrl.indexOf(',') + 1));
      } catch (_) {
        say('\u2298 The capture could not be decoded');
        return;
      }
      var built = buildMapPdf(binary, canvas.width, canvas.height,
        'GlobalGrid2050 \u00b7 Grid Atlas', attributionText(doc), (generationText() || 'generation unknown')
          + ' · ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC');
      var blob = new Blob([built.bytes], { type: 'application/pdf' });
      var url = URL.createObjectURL(blob);
      var link = doc.createElement('a');
      link.id = 'gridatlas-pdf-download';
      link.href = url;
      link.download = 'globalgrid2050-grid-atlas-' + pdfFileStamp() + '.pdf';
      doc.body.appendChild(link);
      link.click();
      setTimeout(function () {
        URL.revokeObjectURL(url);
        if (link.parentNode) link.parentNode.removeChild(link);
      }, 30000);
      say('\u2713 PDF saved \u00b7 ' + built.pageW + '\u00d7' + built.pageH + ' px, 1:1');
    });
  }

  function appendExport(panel, doc) {
    if (!panel || panel.querySelector('[data-gm-export]')) return 0;
    appendGroup(panel, 'Export this view');

    /* EACH CONTROL IS NAMED, BECAUSE ITS LABEL IS NOT A NAME.
       Both controls carried `data-gm-export="1"` and nothing else, so the only
       way anything outside this function could tell them apart was by reading
       their text. saveImage() REWRITES that text on click -- to "Image saved",
       or to the refusal -- so a caller that found the button by its words lost
       it the moment it used it. The first outcome proof written for this
       feature did exactly that, and its failures were unattributable as a
       result. An id and a typed data attribute are stable across the click,
       across a relabelling, and across translation. The attribute keeps the
       name `data-gm-export` so the "already built" guard above and every
       existing check that looks for it still see it. */
    var print = doc.createElement('button');
    print.id = 'gridatlas-export-print';
    print.setAttribute('data-gm-export', 'print');
    print.setAttribute('type', 'button');
    print.textContent = '⎙ Print · or save as PDF';
    print.addEventListener('click', function () { printView(doc); });
    panel.appendChild(print);

    var pdf = doc.createElement('button');
    pdf.id = 'gridatlas-export-pdf';
    pdf.setAttribute('data-gm-export', 'pdf');
    pdf.setAttribute('type', 'button');
    pdf.textContent = '\u2913 Save this view as a PDF';
    pdf.addEventListener('click', function () { savePdf(doc, pdf); });
    panel.appendChild(pdf);

    var image = doc.createElement('button');
    image.id = 'gridatlas-export-image';
    image.setAttribute('data-gm-export', 'image');
    image.setAttribute('type', 'button');
    image.textContent = '⤓ Save an image of this view';
    image.addEventListener('click', function () { saveImage(doc, image); });
    panel.appendChild(image);

    return 3;
  }

  function appendEstateLinks(panel) {
    if (!panel || panel.querySelector('[data-gm-estate]')) return 0;
    appendGroup(panel, 'Estate');
    var added = 0;
    ESTATE_LINKS.forEach(function (item) {
      var a = document.createElement('a');
      a.setAttribute('data-gm-estate', '1');
      a.setAttribute('role', 'button');
      a.href = item.href;
      a.target = '_blank';
      a.rel = 'noopener';
      a.textContent = item.text;
      panel.appendChild(a);
      added += 1;
    });
    return added;
  }

  /* A measured audit found the v8 panel's own checkboxes at 17x17 px --
     the input element itself, not just its label. A label with a tall
     min-height passes a hit-test at its centre but still measures 17x17
     if something re-measures the <input> node's own rect, the way the
     live audit did. So the proxy <input> here is stretched, invisible,
     over the FULL label (position:absolute;inset:0) -- its own
     getBoundingClientRect() is therefore the whole >=44px control, under
     any measurement method -- and a separate, normally-sized box (built
     from CSS alone, no image) carries the visible tick. */
  function layerCheckbox(kind) {
    var proxy = document.createElement('input');
    proxy.type = kind;
    var box = document.createElement('span');
    box.className = 'gm-layer-box';
    box.setAttribute('aria-hidden', 'true');
    return { proxy: proxy, box: box };
  }

  function buildLayerControls(found) {
    var lastGroup = '';
    found.controls.forEach(function (original) {
      var key = layerKey(original);
      var group = layerGroup(original);
      if (group !== lastGroup) {
        appendGroup(gridBody, group);
        lastGroup = group;
      }
      var label = document.createElement('label');
      label.className = 'gm-layer';
      label.setAttribute('data-gridatlas-layer-key', key);
      var built = layerCheckbox('checkbox');
      var proxy = built.proxy;
      proxy.setAttribute('data-gridatlas-layer-proxy', key);
      var name = document.createElement('span');
      name.className = 'gm-layer-name';
      label.appendChild(proxy);
      label.appendChild(built.box);
      label.appendChild(name);
      gridBody.appendChild(label);
      layerTargets[key] = original;
      layerProxies[key] = proxy;
      proxy.addEventListener('change', function () {
        if (!!original.checked !== !!proxy.checked && typeof original.click === 'function') {
          /* original.click() must remain the implementation: its delegated
             engine listener owns hydration.  Suppress only the document-level
             outside-click closer while that synchronous forwarding runs, so
             the reader can see the tick and its live load state. */
          forwardingLayerChoice = true;
          try { original.click(); }
          finally { forwardingLayerChoice = false; }
        }
        syncLayer(key);
      });
      syncLayer(key);
    });

    var basemaps = array(found.host.querySelectorAll('input[type="radio"][name="bm"]'));
    if (basemaps.length) appendGroup(gridBody, 'Basemap');
    basemaps.forEach(function (original) {
      var label = document.createElement('label');
      label.className = 'gm-layer';
      var built = layerCheckbox('radio');
      var proxy = built.proxy;
      proxy.name = 'gridatlas-menu-basemap';
      proxy.value = original.value;
      proxy.checked = !!original.checked;
      var name = document.createElement('span');
      name.className = 'gm-layer-name';
      name.textContent = cleanText(original.closest('label').textContent) || original.value;
      proxy.addEventListener('change', function () {
        if (proxy.checked && !original.checked && typeof original.click === 'function') original.click();
        closeAll();
      });
      label.appendChild(proxy);
      label.appendChild(built.box);
      label.appendChild(name);
      gridBody.appendChild(label);
    });
  }

  function move(panel, node, label) {
    if (!node || !panel || (bar && bar.contains(node))) return false;
    if (label && node.setAttribute) node.setAttribute('aria-label', label);
    panel.appendChild(node);             // same node: its original listener survives
    if (node.removeAttribute) node.removeAttribute('hidden');
    state.controls_moved += 1;
    return true;
  }

  function trayRoute(node) {
    var text = cleanText(node && node.textContent).toLowerCase();
    if (/\bclear\b|\bscope\b/.test(text)) return 'Scope';
    if (/\bgrid\b|\bsubs\b/.test(text)) return 'Grid';
    return '';
  }

  /* The two chips that must NOT be swallowed by a menu on a phone.
     ------------------------------------------------------------------------
     GRID and SUBS were put on the map deliberately, and the reason is on the
     record: the grid-line and substation switches live in the SCADA panel
     below the map, "which a phone never scrolls to; activation looked
     broken" (composition manifest, mobile_tray, from phone acceptance on
     2026-09-01). Moving every tray button into a dropdown re-created a milder
     form of exactly that fault - measured at an iPhone 13 viewport on
     202609041330, zero layer controls were reachable without first opening a
     menu.

     So on a touch screen or a narrow window these two stay where they were
     designed to be. Everything else still routes into the menus, and desktop
     is unchanged: there the chips are redundant with a menu that is already
     one click away and always visible. */
  function chipStaysOnMap(node) {
    var text = cleanText(node && node.textContent).toLowerCase();
    if (!/\bgrid\b|\bsubs\b/.test(text)) return false;
    /* An UNKNOWN width is not a phone. Reading `(window.innerWidth || 0) <= 700`
       makes a missing or zero width report narrow, which is the wrong way for
       a default to fail: it would strand these chips on the map in any host
       that does not publish a width, including a headless proof fixture. The
       width has to be a real positive number before it argues for a phone. */
    var coarse = false;
    try {
      coarse = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
    } catch (error) {
      coarse = false;
    }
    var width = Number(window.innerWidth);
    var narrow = isFinite(width) && width > 0 && width <= 700;
    /* DESKTOP TOO, ON THE ARCHITECT'S INSTRUCTION.
       "in mobile view the Grid and subs buttons are nice show them on desktop
       TOO". Everything measured above is still true and is deliberately still
       computed; what changed is the conclusion drawn from it for a wide
       screen. The old argument was that on desktop these two are redundant
       with a menu that is always one click away. That is correct and it is
       not the point: GRID and SUBS are the two layers a reader toggles most,
       and a control used constantly belongs under the cursor rather than one
       click inside a menu. Redundancy with a menu is a reason to keep a
       shortcut, not to remove one.

       `coarse` and `narrow` are left in place and still read, so the phone
       measurement they encode -- and the reason it was made -- stays in the
       record rather than being deleted along with its conclusion. */
    return true;
  }

  function adoptLate(doc) {
    if (!bar) return;
    move(panels.View, doc.getElementById('gridatlas-gb-conditions'));
    move(panels.About, doc.getElementById('gridatlas-version-ledger'));
    move(panels.View, doc.getElementById('btn-fullscreen-exit'), 'Exit full screen');

    var curtain = doc.getElementById('fs-curtain-tab');
    if (curtain && !bar.contains(curtain)) {
      curtain.setAttribute('role', 'button');
      curtain.setAttribute('tabindex', '0');
      curtain.setAttribute('aria-label', 'Open the fullscreen layer curtain');
      move(panels.Grid, curtain);
    }

    var tray = doc.getElementById('gridatlas-mobile-tray');
    if (tray) {
      array(tray.querySelectorAll('button')).forEach(function (button) {
        if (chipStaysOnMap(button)) return;   // one tap on a phone, not two
        var route = trayRoute(button);
        if (route) move(panels[route], button);
        else button.hidden = true;       // Tools only revealed the controls now in menus
      });
    }

    move(panels.Scope, doc.getElementById('btn-gridpoint'));

    var disclaimer = doc.querySelector('.disclaimer-box');
    var shoutout = doc.querySelector('.podcast-shoutout');
    move(panels.About, disclaimer);
    move(panels.About, shoutout);

    state.estate_links = appendEstateLinks(panels.About);
    appendEngineModules(panels.File);
    state.export_controls = appendExport(panels.File, doc);
    state.studies = appendStudies(panels.View);

    /* The map attribution moves off the map and into About, LAST, in small
       print.
       ----------------------------------------------------------------------
       Measured live at generation 202609042123, 2026-09-05: .custom-map-attrib
       rendered at x=15 y=47, 401x24 px -- a boxed band immediately under the
       menu bar, over the top-left of the map, which is where a reader arriving
       on a deep link looks first. On a 393x852 phone it wrapped to two lines
       and the architect photographed the consequence: opening EDIT drew
       "Status Colours" UNDERNEATH the attribution box, the two overlapping in
       the same space. His instruction, verbatim: "Attribution bar clashes move
       that to about and in small print at the bottom".

       The credit is owed and is not dropped: it is the same node, moved once,
       text intact, so OpenStreetMap, CARTO and Open Charge Map are still named
       on the page and one tap away. It is appended AFTER the estate links, and
       re-appended on every later adoption pass, so a late DOM rebuild cannot
       leave it above the controls again. appendChild on a node already in the
       panel moves it to the end rather than duplicating it. */
    var attrib = doc.querySelector('.custom-map-attrib');
    if (attrib) {
      if (!bar || !bar.contains(attrib)) move(panels.About, attrib);
      else if (panels.About.lastElementChild !== attrib) panels.About.appendChild(attrib);
      /* The `lastElementChild` test is not tidiness, it is the difference
         between this working and crashing the tab. adoptLate runs from a
         MutationObserver, so an unconditional appendChild here IS a mutation,
         which re-enters adoptLate, which appends again: a feedback loop that
         crashed the renderer outright under the 393x852 arrival gate, while
         the previous generation passed the same gate in the same harness.
         Once the node is already last, this is a no-op and the loop closes. */
    }

    /* The real .scada-brand (VENTUS, again) and .status-legend move once,
       into the restored SCADA panel's head, during install() below -- not
       hidden as a "duplicate" and not here, so a late DOM rebuild cannot
       repeatedly fight over one node's location. */

    /* The panel's own show/hide control stays REACHABLE. It was hidden here as
       "superseded; measured inert", and it is neither: the stylesheet rule
       above was hiding the panel it moved, so its effect could not be seen.
       With the panel restored this is the only control that opens and closes
       it, and hiding it would leave a phone with a collapsed panel and nothing
       to open it with -- which is the fault this generation exists to end. */
    var dashToggle = doc.getElementById('gridatlas-dash-toggle');
    if (dashToggle) dashToggle.hidden = false;

    var stack = doc.querySelector('.map-controls');
    if (stack) {
      var leftovers = array(stack.querySelectorAll('button,input,select,textarea,a'))
        .filter(function (node) { return !node.hidden; });
      if (leftovers.length === 0) stack.setAttribute('data-gridatlas-menu-emptied', '1');
    }

    MENUS.forEach(function (name) {
      state.panel_counts[name] = panels[name] ? panels[name].children.length : 0;
    });
  }

  function install(doc) {
    if (state.installed || doc.getElementById(BAR_ID)) return true;
    var ready = required(doc);
    state.engine_layer_controls = ready.found.engine.length;
    state.pipeline_layer_controls = ready.found.pipeline.length;
    state.layer_controls = ready.found.controls.length;
    if (ready.missing.length) {
      state.waiting_for = ready.missing.slice();
      return false;
    }

    installStyle(doc);
    bar = buildBar(doc);
    buildLayerControls(ready.found);

    /* The search bar is NOT moved. It is the one control a person needs before
       they know which menu to open, and File is closed on arrival -- so moving
       it here left it alive but measuring 0x0, which reads as "the address
       search bar disappears". Same fault the masthead comment below records:
       an always-needed node parked in a collapsed panel. It stays in
       .map-container, where every earlier published version kept it. */
    move(panels.File, ready.nodes.exportButton);
    move(panels.Edit, ready.nodes.statusButton);
    move(panels.View, ready.nodes.fullscreenButton);
    move(panels.Scope, ready.nodes.radiusButton);
    move(panels.Scope, ready.nodes.radiusAreaButton);
    move(panels.Scope, ready.nodes.zoneButton);
    move(panels.Scope, ready.nodes.measureButton);

    /* The VENTUS masthead: fused into the bar's own centre (see buildBar),
       never a closed panel -- the architect's "VENTUS branding has been
       lost" was this node being moved into a collapsed About panel, and
       the measured "flash then vanish" (present for ~1.5s, then torn out)
       was that same move happening after the raw v8 page had already
       painted it once. Moving it here, into brandSlot, keeps it visible
       through the whole transition: raw markup, then fused into the bar,
       never hidden in between. */
    move(brandSlot, ready.nodes.header);

    /* The restored SCADA panel's head: the real .scada-brand (VENTUS,
       again, exactly as v8 rendered it) and .status-legend, moved once --
       not cloned, not hidden as a duplicate. gridHead sits above gridBody
       (built by buildLayerControls) and never enters its column flow. */
    move(gridHead, doc.querySelector('.scada-brand'));
    move(gridHead, doc.querySelector('.status-legend'));

    ready.nodes.host.insertBefore(bar, ready.nodes.host.firstChild);
    doc.documentElement.classList.add('gridatlas-menu-hosted');
    syncAttribClearance(doc);
    if (typeof ResizeObserver === 'function') {
      var barResize = new ResizeObserver(function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      barResize.observe(bar);
      state.attrib_clearance_source = 'ResizeObserver';
    } else if (doc.defaultView && typeof doc.defaultView.addEventListener === 'function') {
      /* No ResizeObserver: a viewport resize is the only other way the
         bar's own height changes (the @media breakpoint), so fall back to
         watching that. */
      doc.defaultView.addEventListener('resize', function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      state.attrib_clearance_source = 'resize-listener';
    }

    /* One document click listener and one change listener, installed once.
       The retry path cannot multiply effects. */
    doc.addEventListener('click', function (event) {
      if (!bar.contains(event.target)) {
        if (!forwardingLayerChoice) closeAll();
      }
      else if (event.target && /^(BUTTON|INPUT)$/.test(event.target.tagName || '')) {
        if (event.target.type !== 'text'
          && !event.target.classList.contains('gm-title')
          && !event.target.hasAttribute('data-gridatlas-layer-proxy')) {
          window.setTimeout ? window.setTimeout(closeAll, 0) : closeAll();
        }
      }
    });
    doc.addEventListener('change', function (event) {
      var key = layerKey(event.target);
      if (key && layerProxies[key]) syncLayer(key);
    });
    state.listeners = 2;

    adoptLate(doc);
    closeAll();
    state.installed = true;
    state.waiting_for = [];
    state.failure = null;
    state.one_identity_surface = true;
    state.mobile_sheet_hit_target_guard = true;
    state.layer_status_mirrored = true;
    state.layer_menu_stays_open = true;

    if (typeof MutationObserver === 'function') {
      observer = new MutationObserver(function () {
        adoptLate(doc);
        syncAll();
      });
      observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
    }
    return true;
  }

  state.install = function () { return install(document); };
  state.closeAll = closeAll;

  function loudFailure(doc) {
    if (state.installed || doc.getElementById(FAILURE_ID)) return;
    var found = inventory(doc);
    state.failure = 'menu not installed: expected 60 engine + 3 Pipeline News layer controls; found '
      + found.engine.length + ' + ' + found.pipeline.length;
    if (window.console && typeof window.console.error === 'function') {
      window.console.error('[GRIDATLAS MENU] ' + state.failure);
    }
    var alert = doc.createElement('div');
    alert.id = FAILURE_ID;
    alert.setAttribute('role', 'alert');
    alert.textContent = state.failure + '. Original controls remain available.';
    alert.style.cssText = 'position:fixed;left:8px;right:8px;top:8px;z-index:10030;'
      + 'padding:8px;background:#280b0b;color:#ffd0d0;border:1px solid #b44;'
      + 'font:11px/1.4 monospace';
    (doc.body || doc.documentElement).appendChild(alert);
  }

  function start() {
    /* Cartridge proofs and prerenderers can provide a deliberately partial
       document. Treat that exactly like any other missing dependency: publish
       the refusal and leave the owner's interface untouched. In particular,
       do not start the 40-second browser retry loop against a non-DOM stub. */
    if (!document.documentElement || typeof document.createElement !== 'function') {
      state.failure = 'menu not installed: full document unavailable';
      return;
    }
    var probe = document.createElement('div');
    if (!probe || typeof probe.setAttribute !== 'function' || !probe.classList) {
      state.failure = 'menu not installed: full DOM element API unavailable';
      return;
    }
    if (install(document)) return;
    if (typeof window.setInterval !== 'function'
      || typeof window.clearInterval !== 'function') return;
    timer = window.setInterval(function () {
      state.tries += 1;
      if (install(document)) {
        window.clearInterval(timer);
        timer = null;
      } else if (state.tries >= MAX_TRIES) {
        window.clearInterval(timer);
        timer = null;
        loudFailure(document);
      }
    }, 250);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', start, { once: true });
  } else {
    start();
  }
}());

/* Arrival tidy - the search machinery gets out of the way once it has answered.

   MEASURED, on v9.96 at 393x852, arriving at ?repd_ref=12588 the way a shared
   link arrives: the map canvas was topmost at 13 per cent of 3,200 sampled
   viewport points and the app's own controls at 87. Three of those controls
   were the SEARCH, not the answer - the results list still open at
   [40,136,302,92] holding the project the reader had already been taken to,
   the box holding "12588", a reference the reader never typed, and the
   identity repeated in the results row, the search bar and the card header.

   A deep link is not a search. The reader asked for one project by name and
   got it; the list of how it was found is scaffolding, and scaffolding left
   up is clutter. So on a RESOLVED arrival the list is dismissed and the box
   is emptied back to its placeholder.

   WHAT THIS DELIBERATELY DOES NOT DO

   - It does not touch a FAILED arrival. When the identity could not be
     resolved the results are the only thing on screen that explains why, and
     hiding them would leave a reader with a map and no account of it.
   - It does not clear a box the reader has touched. Focus or a keystroke
     retires this permanently, so a reader who starts typing while the
     arrival is still resolving never has their text taken away.
   - It does not clear a box holding something other than the ref, which is
     the same rule stated for the case where another lane wrote there first.
   - It hides with `style.display = 'none'`, which is what the shell's own
     Escape key and map click do. This is the product's mechanism, not a new
     one, so nothing has to be taught how to bring it back.

   It runs only where there is a MutationObserver. The cartridge proofs
   execute composed cartridges under node:vm against a window stub that has
   neither observers nor timers, and a module that throws there takes the
   whole cartridge down with it - which is exactly how v9.92 shipped a menu
   bar that broke the sandbox proof. Where there is no observer there is no
   arrival either, so doing nothing is the correct answer rather than a
   degraded one. */
(function arrivalTidy() {
  if (typeof document === 'undefined' || typeof window === 'undefined') return;
  if (typeof MutationObserver !== 'function') return;

  var ref = '';
  try {
    ref = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
  } catch (_) { return; }
  if (!ref) return;

  var typed = false;
  var done = false;

  function tidy() {
    if (done) return true;
    var state = document.body && document.body.dataset
      ? document.body.dataset.gridatlasRepdDeepLink : '';
    if (state !== 'resolved') return state === 'failed';   /* failed: stop watching, change nothing */
    var results = document.getElementById('search-results');
    var input = document.getElementById('search-input');
    if (!results || !input) return false;
    if (!typed) {
      results.style.display = 'none';
      if (input.value === ref) input.value = '';
    }
    done = true;
    return true;
  }

  function retire() { typed = true; }

  function watch() {
    var input = document.getElementById('search-input');
    if (input) {
      input.addEventListener('focus', retire, { once: true });
      input.addEventListener('input', retire, { once: true });
    }
    if (tidy()) return;
    var observer = new MutationObserver(function () {
      if (tidy()) observer.disconnect();
    });
    observer.observe(document.body, {
      attributes: true, attributeFilter: ['data-gridatlas-repd-deep-link']
    });
    window.__GRIDATLAS_ARRIVAL_TIDY__ = {
      installed: true,
      repd_ref: ref,
      get dismissed() { return done; },
      get retired_by_reader() { return typed; }
    };
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', watch, { once: true });
  } else {
    watch();
  }
}());

/**
 * Module: pipeline-news-layers
 *
 * A PIPELINE NEWS (REPD) section in the layer dashboard, beside TOPOLOGY,
 * ASSETS and TRANSIT, that summons the rest of the pipeline around whatever
 * project is currently selected.
 *
 * Vikram: "summon other pipeline items within the atlas after clicking the
 * map ... under REPD pipelinenews under its own section like topology, assets
 * etc". Arriving from Pipeline News you land on one project with five links to
 * substations and nothing else of the pipeline in view. These three controls
 * put the neighbours back: what else is being built within reach, of the same
 * technology, of the twenty technologies Pipeline News' own spine does not
 * carry, or of anything at all.
 *
 * WHY IT DOES NOT USE data-layer-id
 * ---------------------------------
 * The engine delegates a `change` listener on #scada-ui-container and on
 * #fs-curtain-keys, and any checkbox carrying `data-layer-id` is routed to its
 * own handleLayerToggle -- which would be handed an id it has no config for.
 * These controls carry `data-pn-layer` instead and are handled here. Same
 * lesson as the wider-fleet tabs in Pipeline News: borrow the styling, never
 * the attribute that another owner dispatches on.
 *
 * WHAT IT IS NOT
 * --------------
 * It draws register points near a selection. It does not measure them, rank
 * them, bind them to the selected project, or imply any relationship between
 * them. Two projects near each other share a map square and nothing else --
 * not a circuit, not a connection, not a queue position. The labels say
 * "within 25 km" and stop there.
 *
 * Depends on: geodesy.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.pipelineNewsLayers) return;

  const geodesy = NS.geodesy;
  if (!geodesy) {
    throw new Error('pipeline-news-layers requires the geodesy module');
  }