GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/modules

Single-Line Diagram (SLD) Without Layout (part 3)

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 399 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. Single-Line Diagram (SLD) Without Layout geodesy · gridatlas / atlas/modules/202611222130-sld-without-layout.js lines 1401–2100

Single-Line Diagram (SLD) Without Layout

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

Set aside from the main view: 100% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9961 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
  • sha256 6870cfb365c18b90363b664f89623c9217c3d0111a67b87fdd1b6b3a26aeba6b
  • target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202611222130-sld-without-layout.js · lines 1401–2100 of 8986 · version 2026-11-22 21:30 (continued from section 397) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 273 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. 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 stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
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
none found
Used by
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
fitToStatedCapacity, oneMore, bucketOf, policy, namedOffshore, widerFleetNames, widerFleetBuckets, measuredCount, coverage, isProjectTech, layerIdForBucket
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611222130-sld-without-layout.js:1401-2100 · blob ab6fc6992aa26e51a3c82d7e2d26172a50798c60 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
   * is reported rather than hidden, because a layout that quietly lands 7%
   * off the stated capacity is worse than one that says so.
   *
   * WHICH CAPACITY IS BEING MATCHED
   * That is the caller's declared basis, never a guess. REPD's figure is
   * nominally MWelec, but it is reported inconsistently: some schemes state
   * DC, some AC, and the register does not carry the distinction reliably.
   * Matching AC when the figure was DC oversizes the connection by the DC/AC
   * ratio, which is exactly the error that matters for export limitation.
   */
  /* Fit on two variables, because one cannot reach a small project.
     ----------------------------------------------------------------------
     Reported: the numbers do not change when the headline capacity changes.
     Measured, and they do not:

       string   5, 10, 20, 30, 40, 49.9 and 50 MW all produced 44.80 MW
       central  5, 10 and 20 MW all produced 17.60 MW

     The fit moved ONE variable. In string mode that is b_cols, and because
     total_blocks is b_cols x s_subs with s_subs pinned at five, one step of
     b_cols is five blocks — 44.8 MW at the default skid rating. Nothing below
     that is reachable, so a 30 MW solar farm was drawn as a 44.8 MW one, an
     overstatement of half as much again, and every target under 50 MW
     collapsed onto the same layout. The register starts at 1 MW.

     A block is 8.96 MW in string mode and a skid is 4.4 MVA in central. Those
     are the real quanta, and they are reachable as soon as the inner variable
     is allowed to move too. So the search is over both, and it prefers the
     candidate that stays closest to the shape the user already had — a fit
     that reaches the right capacity by rearranging the whole plant is a worse
     answer than one that reaches it by adding a column.

     Bounds are physical rather than generous: a ring main carries a handful of
     skids, not four hundred, so the inner variable stops at twelve. */
  const FIT_OUTER_MAX = 120;
  const FIT_INNER_MAX = 12;

  function fitToStatedCapacity(sld, computeSldStats) {
    sld.fitResidualPct = null;
    sld.fitQuantumMw = null;
    const target = Number(sld.targetMw);
    if (!Number.isFinite(target) || target <= 0) return;
    if (sld.targetBasis !== 'ac' && sld.targetBasis !== 'dc') return;

    const string = sld.inputs.mode === 'string';
    const outerKey = string ? 'b_cols' : 'rings_c';
    const innerKey = string ? 's_subs' : 'mv_per_ring_c';
    const outer0 = sld.inputs[outerKey];
    const inner0 = sld.inputs[innerKey];

    let best = null;
    for (let inner = 1; inner <= FIT_INNER_MAX; inner += 1) {
      sld.inputs[innerKey] = inner;
      for (let outer = 1; outer <= FIT_OUTER_MAX; outer += 1) {
        sld.inputs[outerKey] = outer;
        const s = computeSldStats();
        const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
        if (!Number.isFinite(got) || got <= 0) continue;
        const error = Math.abs(got - target);
        // Ties, and near-ties, go to the layout closest to the one already on
        // screen. Without this the fit rearranges the plant for a rounding
        // difference and the drawing jumps for no reason the user can see.
        const drift = Math.abs(inner - inner0) + Math.abs(outer - outer0) / 100;
        if (!best
            || error < best.error - 1e-9
            || (Math.abs(error - best.error) <= 1e-9 && drift < best.drift)) {
          best = { outer, inner, error, got, drift };
        }
      }
    }
    if (!best) {
      sld.inputs[outerKey] = outer0;
      sld.inputs[innerKey] = inner0;
      return;
    }
    sld.inputs[outerKey] = best.outer;
    sld.inputs[innerKey] = best.inner;
    sld.fitResidualPct = ((best.got - target) / target) * 100;

    // What one more block would have added. A residual means nothing without
    // it: 10% off a plant whose smallest step is 9 MW is exact, and 10% off
    // one whose step is 0.5 MW is a miss.
    const oneMore = (() => {
      sld.inputs[outerKey] = best.outer + 1;
      const s = computeSldStats();
      sld.inputs[outerKey] = best.outer;
      const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
      return Number.isFinite(got) ? Math.abs(got - best.got) : null;
    })();
    sld.fitQuantumMw = oneMore;
  }

  NS.sizingArithmetic = Object.freeze({
    generation: '202609012205',
    DEVELOPMENT_STAGES,
    DEVELOPMENT_SUCCESS,
    BIFACIAL_BY_GCR,
    FIT_OUTER_MAX,
    FIT_INNER_MAX,
    financeNumber,
    physicalInputs,
    buildStats,
    consistency,
    stringStats,
    centralStats,
    applyDevelopmentStageDefaults,
    applyMountingBifacial,
    screeningFinance,
    computeStats,
    fitToStatedCapacity
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   technology-coverage - which technologies the measurement runs for, and
   what each measurement is a measurement OF
   ══════════════════════════════════════════════════════════════════════

   WHAT WAS MEASURED BEFORE THIS MODULE WAS WRITTEN.

   The request was to extend the nearest-substation computation to the twenty
   wider-fleet REPD technologies, on the report that it ran only for the
   spine. Driven in Chrome against the live composition (v9.88, generation
   202609030234) on the wider fleet's own MAP link:

     ?repd_ref=8795 ... &technology=biomass   Caledon Green, Landfill Gas
     ?repd_ref=626  ... &technology=biomass   Pitsea Tipp,   Landfill Gas

   Both arrived, flew, opened the card, ticked the Subs control and DREW THE
   LINKS. Caledon Green measured 1.74 km at 132 kV, 2.98 km at 275 kV and
   5.70 km at 33 kV; Pitsea Tipp named Coryton South Substation at 7.70 km
   and printed its 400 kV scope sentence with the denominator in it. So the
   wider fleet was ALREADY computing, and a change that claimed to enable it
   would have been a change that did nothing while saying it did something.

   There IS a four-member technology allow-list in this estate:

     const allowedTechnologies = new Set(['solar','bess','wind_onshore','wind_offshore']);

   It lives at line 805 of the IMMUTABLE SHELL, atlas/releases/
   202608300453-atlas-v9/ventus-corev8engine.js, inside the shell's own
   focusCanonicalProjectDeepLink(). It rejects every value the wider fleet
   can send, because those four are exactly the four types the wider fleet is
   DEFINED as excluding. Its rejection is caught, and its only effects are a
   console line and a flyTo the arrival lane in this cartridge has already
   performed - which is why the measurement runs anyway. The shell is carried
   forward verbatim by contract and this module does not reach into it.

   WHAT THIS MODULE ACTUALLY CHANGES.

   One thing: OFFSHORE WIND NOW MEASURES. It used to open a card and withhold
   the distance, on the reasoning that a turbine in the North Sea does not
   reach the nearest onshore substation by a straight line. The reasoning
   about routes was right and is kept in full below; the conclusion was
   over-cautious. An offshore project's export cable does land at an onshore
   substation, so the distance to the nearest mapped substation is a real
   measurement of a real thing, provided the card says what it measured.

   WHAT "NEAREST" CANNOT BE MADE TO MEAN HERE, MEASURED RATHER THAN ASSUMED.

   The coordinator asked for an onshore-only filter, so that "nearest onshore
   substation" would mean onshore. The pinned substation product cannot carry
   one. Counted over all 5,800 features of

     atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson

   the only properties present are voltage (5,800), name (4,460), operator
   (3,264), brand (1,310), source (684), type (72), capacity (15) and colour
   (3). The OSM `location` tag - the field that would say offshore, platform
   or underwater - is present on ZERO of them.

   That leaves the name, and the name does not separate them either. Fourteen
   features carry "offshore" in their name; read against their coordinates, at
   least four are ONSHORE substations serving an offshore wind farm, which is
   precisely what an offshore project should be measured to - Hornsea
   (-0.2598, 53.6582) and Hornsea Two (-0.2604, 53.6568) at 400/220 kV,
   Thanet's explicitly-named onshore substation (1.3459, 51.3089), and the
   European Offshore Wind Deployment Centre (-2.0650, 57.2158). The rest are
   genuinely platforms at sea: Neart na Gaoithe North and South, Sheringham
   Shoal 1 and 2, Humber Gateway, Westermost Rough, Rampion, Burbo Bank 2.

   So a name filter would drop Hornsea - a landfall connection - from the very
   search it was supposed to sharpen. No onshore filter is applied, and this
   module says so on the card instead of pretending to one. An offshore
   project is measured against the SAME 5,800 features, at the SAME >=33 kV
   floor, by the SAME straight line as every other technology, and the card
   carries two extra sentences: that the line crosses water and is not the
   export cable, and that the set searched contains substations that are
   themselves offshore - named where one is returned, so the reader can see
   which. A stated limit, rather than a hidden one. A filter whose predicate
   is wrong four times in fourteen is worse than no filter, because it looks
   like precision.

   WHAT DOES NOT CHANGE, AND MUST NOT.

     - The straight line stays. It is the measurement, it is first, and the
       corridor-estimate module still sits beside it saying how far off a
       built route typically is. Nothing here replaces it.
     - Every superlative keeps carrying its sample. This module supplies the
       sample LABEL for each policy so the card cannot print "nearest"
       without printing what it searched.
     - The coordinate denominator stays. The operator publishes connection
       points and only a fraction carry coordinates; that count is computed
       at render time by nearestScope() and is not restated here, because a
       literal would go quietly false the day the pinned product moves.
     - Nothing here grades anything. No verdict word appears anywhere in this
       module, not even to disown one: the sandbox proof greps the served
       bytes for them and cannot tell a comment from a card, which is the
       right way round. A distance and a voltage, stated, and the things a
       distance cannot answer named rather than implied.

   THE ROSTER IS BY NAME ON PURPOSE.

   The Atlas never receives a raw REPD technology. Pipeline News' MAP link
   sends `technology=<t>`, the COLOUR BUCKET - so twenty raw types arrive as
   nine bucket values, and "Landfill Gas" reaches this cartridge as
   "biomass". Every one of the twenty is listed below against its bucket, so
   a proof can assert coverage by REPD name rather than by bucket, and so
   anyone reading this can see that the twenty are accounted for rather than
   assumed.
   ══════════════════════════════════════════════════════════════════════ */

(function installTechnologyCoverage() {
  'use strict';

  const SCHEMA = 'gridatlas.technology-coverage.v1';

  /* The twenty wider-fleet REPD technologies, each against the bucket the
     MAP link actually sends. Counts are the live wider-fleet payload,
     202609030009, 1,104 rows - carried so a drift in either side is visible
     rather than silent. Every one of the 1,104 rows carries a usable
     coordinate pair; none is withheld for want of a location. */
  const WIDER_FLEET = Object.freeze([
    Object.freeze({ repd: 'Landfill Gas',                       bucket: 'biomass',    rows: 275 }),
    Object.freeze({ repd: 'Anaerobic Digestion',                bucket: 'biomass',    rows: 253 }),
    Object.freeze({ repd: 'Biomass (dedicated)',                bucket: 'biomass',    rows: 159 }),
    Object.freeze({ repd: 'EfW Incineration',                   bucket: 'biomass',    rows: 122 }),
    Object.freeze({ repd: 'Small Hydro',                        bucket: 'hydro',      rows: 108 }),
    Object.freeze({ repd: 'Hydrogen',                           bucket: 'hydrogen',   rows: 60 }),
    Object.freeze({ repd: 'Advanced Conversion Technologies',   bucket: 'act',        rows: 37 }),
    Object.freeze({ repd: 'Large Hydro',                        bucket: 'hydro',      rows: 28 }),
    Object.freeze({ repd: 'Pumped Storage Hydroelectricity',    bucket: 'hydro',      rows: 15 }),
    Object.freeze({ repd: 'Tidal Stream',                       bucket: 'tidal',      rows: 14 }),
    Object.freeze({ repd: 'Sewage Sludge Digestion',            bucket: 'biomass',    rows: 12 }),
    Object.freeze({ repd: 'Geothermal',                         bucket: 'geothermal', rows: 5 }),
    Object.freeze({ repd: 'Shoreline Wave',                     bucket: 'tidal',      rows: 4 }),
    Object.freeze({ repd: 'Liquid Air Energy Storage',          bucket: 'caes',       rows: 2 }),
    Object.freeze({ repd: 'Biomass (co-firing)',                bucket: 'biomass',    rows: 2 }),
    Object.freeze({ repd: 'Hot Dry Rocks (HDR)',                bucket: 'geothermal', rows: 2 }),
    Object.freeze({ repd: 'Compressed Air Energy Storage',      bucket: 'caes',       rows: 2 }),
    Object.freeze({ repd: 'Fuel Cell (Hydrogen)',               bucket: 'hydrogen',   rows: 2 }),
    Object.freeze({ repd: 'Flywheels',                          bucket: 'flywheel',   rows: 1 }),
    Object.freeze({ repd: 'Unknown',                            bucket: 'other',      rows: 1 })
  ]);

  /* The spine, for completeness: the four the wider fleet is defined as
     excluding, and the four the shell's allow-list accepts. */
  const SPINE = Object.freeze(['solar', 'bess', 'wind_onshore', 'wind_offshore']);

  /* Offshore wind, in every spelling the register and the engine use. This
     is no longer a withholding set - it selects a DIFFERENT NOTE, not a
     different answer. */
  const OFFSHORE_TECHS = Object.freeze([
    'wind_offshore', 'wind_offshore_operational'
  ]);
  const OFFSHORE = new Set(OFFSHORE_TECHS);

  /* Named as offshore in the substation product. Used only to LABEL a
     returned row, never to remove one - see the header for the four onshore
     substations this pattern also matches, which is exactly why it does not
     filter. */
  const OFFSHORE_NAMED = /\boffshore\b/i;
  const ONSHORE_NAMED = /\bonshore\b/i;

  const PRODUCT = Object.freeze({
    features: 5800,
    with_location_tag: 0,
    offshore_in_name: 14,
    of_those_onshore: 4,
    source: 'atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson'
  });

  /* The sentence the card prints under an offshore project's distances. It
     keeps every word of the old withholding note that was ABOUT ROUTES,
     because none of that reasoning was wrong; it drops only the conclusion
     that therefore nothing should be measured. */
  const OFFSHORE_NOTE =
    'This is a straight line from the project to the nearest mapped '
    + 'substation, and for an offshore project that line crosses water. It is '
    + 'not the export cable and not its length. An offshore project reaches an '
    + 'offshore substation, an export cable and a landfall before anything '
    + 'onshore, and the route inland is then chosen for consent and ground '
    + 'conditions rather than for distance, so the built length is longer than '
    + 'this by an amount no distance can tell you.';

  const OFFSHORE_SET_NOTE =
    'The set searched is the same 5,800 mapped substations used for every '
    + 'other technology. It carries no field saying which of them are onshore: '
    + 'the OSM location tag is absent from all 5,800, and of the 14 whose name '
    + 'contains "offshore" at least 4 are onshore substations serving an '
    + 'offshore wind farm. No onshore filter is applied, because one built on '
    + 'the name would drop those 4 - including Hornsea at 400/220 kV, which is '
    + 'a landfall connection. Where a result is itself named as an offshore '
    + 'substation it is marked below.';

  /* The label under which a measurement is made. The card must never print
     the word "nearest" without one of these beside it. */
  const SAMPLE = Object.freeze({
    mapped_substations: 'nearest of the mapped substations at or above the '
      + 'voltage floor that this search could see'
  });

  function bucketOf(tech) {
    return String(tech == null ? '' : tech).trim();
  }

  /**
   * What the measurement is, for one technology id.
   *
   * There is no `measure: false` branch. Every technology the register or
   * the wider fleet can send is measured; what differs is the note that
   * goes with it. A technology this module has never heard of is measured
   * too - the arrival lane already continues past an unknown id, and
   * refusing arithmetic over two coordinates because a string was
   * unfamiliar is how 109 offshore projects got nothing at all.
   */
  function policy(tech) {
    const id = bucketOf(tech);
    const offshore = OFFSHORE.has(id);
    return Object.freeze({
      technology: id || null,
      measure: true,
      offshore,
      sample: SAMPLE.mapped_substations,
      /* Both notes, in order, for offshore; nothing extra for the rest.
         The generic straight-line-is-not-a-route caveat is the card's own
         and is printed for every technology either way. */
      notes: Object.freeze(offshore ? [OFFSHORE_NOTE, OFFSHORE_SET_NOTE] : [])
    });
  }

  /**
   * Is this substation NAME one of the ones the product calls offshore?
   * Labelling only. A true here marks a row; it never removes one.
   */
  function namedOffshore(name) {
    const text = String(name == null ? '' : name);
    return OFFSHORE_NAMED.test(text) && !ONSHORE_NAMED.test(text);
  }

  /** The roster, by REPD name, for a proof to assert against. */
  function widerFleetNames() {
    return WIDER_FLEET.map(entry => entry.repd);
  }

  /** The bucket values the wider fleet's MAP link can actually send. */
  function widerFleetBuckets() {
    return [...new Set(WIDER_FLEET.map(entry => entry.bucket))].sort();
  }

  /** Every wider-fleet technology measures. Stated as a function so a proof
      cannot pass by reading a literal that stopped being true. */
  function measuredCount() {
    return WIDER_FLEET.filter(entry => policy(entry.bucket).measure).length;
  }

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  NS.technologyCoverage = Object.freeze({
    schema: SCHEMA,
    wider_fleet: WIDER_FLEET,
    spine: SPINE,
    offshore_techs: OFFSHORE_TECHS,
    product: PRODUCT,
    offshore_note: OFFSHORE_NOTE,
    offshore_set_note: OFFSHORE_SET_NOTE,
    sample: SAMPLE,
    policy,
    namedOffshore,
    widerFleetNames,
    widerFleetBuckets,
    measuredCount,
    /* Said once, here, so no caller has to phrase it and none can soften it. */
    not_a_connection: 'A distance to a mapped substation is not a connection, '
      + 'a capacity, a queue position or an offer, for any technology on this '
      + 'list.',
    shell_allow_list_note: 'The four-member technology allow-list in the '
      + 'immutable shell rejects every wider-fleet value and is caught; the '
      + 'arrival lane in this cartridge has already flown and carded by then, '
      + 'so it costs a console line and nothing else. The shell is carried '
      + 'forward verbatim and is not edited here.'
  });
})();

/**
 * GridAtlas cartridge — neon substation links and the SLD layout sandbox.
 *
 * Assembled under the generation named in the header above; this part
 * states no generation of its own, because a second identity inside the
 * same file is one that can disagree with the first. Slot: replace-script for
 * 202608292126-pre-snapped-config-adapter.js.
 *
 * WHAT IT DOES
 * ------------
 * Select a solar, battery or onshore wind project and the map draws animated
 * neon lines from it to the nearest substations at 33 kV and above. The same
 * distances are written onto the project card the engine has just opened,
 * marked BETA, with the reasons a distance is not a connection stated on the
 * card itself rather than hidden in a tooltip.
 *
 * WHY IT REPLACES THE CONFIG ADAPTER RATHER THAN ADDING A SCRIPT
 * -------------------------------------------------------------
 * The composer in atlas/index.html supports exactly one slot, `replace-script`.
 * There is no append slot, and inventing one would mean changing the composer,
 * which is a larger contract change than this feature is worth. So this
 * cartridge carries the pre-snapped config adapter's behaviour VERBATIM -- same
 * layer ids, same closure assertion, same failure mode, same public state
 * object -- and adds the link layer beside it. The immutable shell is not
 * touched, and `__GRIDATLAS_PRE_SNAPPED_CONFIG__` still reports exactly what it
 * reported before, so anything asserting on it keeps working.
 *
 * HOW IT HOOKS IN WITHOUT SHELL MUTATION
 * --------------------------------------
 * Two decorators, both of things the engine has already published by the time
 * this script runs:
 *
 *   window.initVentusMap  wrapped for the pre-snap config, as before.
 *   maplibregl.Map        wrapped to capture the instance, because the engine
 *                         keeps `map` in a closure and returns nothing. The
 *                         engine constructs its map inside initVentusMap, which
 *                         runs after this file, so the constructor is still
 *                         ours to wrap.
 *
 * THE MEASUREMENT
 * ---------------
 * Haversine on R = 6378.137 km, the same constant as ventus-corev8engine.js,
 * pipelinenews and Ventusltd/grid-distance-maths, so a distance read here
 * equals the same distance read there. Substations are mapped as points AND as
 * polygons; a polygon is reduced to its ring mean, because its first vertex is
 * a corner rather than the site.
 *
 * Scope is 33 kV and above. 11 kV is rare for utility-scale export and where it
 * occurs is often a private network behind the meter, so it is not a screening
 * signal. `voltage` is written `33000`, `33000;11000` for two voltages, and
 * `33000:11000` for a transformer ratio -- a 33/11 primary still carries 33 kV.
 *
 * WHAT A LINE IS NOT
 * ------------------
 * A straight line to mapped geometry. Not a cable route, not a connection
 * length, no wayleave, crossing, terrain or consent content. A mapped
 * substation does not confirm capacity, voltage suitability or connection
 * rights, and fault level and thermal headroom cannot be inferred from distance
 * at all -- they need DNO network data such as source impedance and a
 * connection study, alongside right of way, wayleaves and easements, land
 * control and consent. The card says all of that on screen.
 */
(() => {
  'use strict';

  const SLD_STYLES = (window.__GRIDATLAS_MODULES__ || {}).sldStyles;
  if (SLD_STYLES?.schema !== 'gridatlas.module.sld-styles.v1') {
    throw new Error('sld-sandbox requires the sld-styles module');
  }

  const GENERATION = '202609012045';

  /* ══════════════════════════════════════════════════════════════════════
     PART 1 — the pre-snapped config adapter, carried forward unchanged.
     ══════════════════════════════════════════════════════════════════════ */

  const PRE_SNAPPED_LAYER_IDS = new Set(['400', '275', '220', '132', '66']);
  const originalInit = window.initVentusMap;

  if (typeof originalInit !== 'function') {
    throw new Error('V8 engine init function is unavailable before map-ready adapter');
  }

  const state = {
    schema: 'gridatlas.pre-snapped-config-adapter.v1',
    generation: '202608292126',
    applied: false,
    changed_layer_ids: [],
    preserved_preload_flags: true,
    failures: []
  };
  window.__GRIDATLAS_PRE_SNAPPED_CONFIG__ = state;

  window.initVentusMap = function gridAtlasMapReadyInit(options) {
    try {
      const changed = [];
      const config = options.config.map(group => ({
        ...group,
        layers: group.layers.map(layer => {
          if (!PRE_SNAPPED_LAYER_IDS.has(String(layer.id))) return layer;
          if (layer.snap !== true) {
            throw new Error(`expected V8 snap=true for topology layer ${layer.id}`);
          }
          changed.push(String(layer.id));
          return { ...layer, snap: false };
        })
      }));

      const expected = [...PRE_SNAPPED_LAYER_IDS].sort();
      if (JSON.stringify([...changed].sort()) !== JSON.stringify(expected)) {
        throw new Error(`pre-snapped layer closure mismatch: ${JSON.stringify(changed)}`);
      }

      state.applied = true;
      state.changed_layer_ids = changed;
      return originalInit({ ...options, config });
    } catch (error) {
      state.failures.push(String(error?.message || error));
      throw error;
    }
  };

  /* ══════════════════════════════════════════════════════════════════════
     PART 2 — neon substation links.
     ══════════════════════════════════════════════════════════════════════ */

  /* ONE geodesy, and it is the module's.
     ----------------------------------------------------------------------
     This file used to declare R_ATLAS = 6378.137 and its own distanceKm,
     four hundred lines from a second geodesy section, while the assembled
     cartridge ALSO carried the geodesy module in front of it. Two radii and
     two haversines in one served file, agreeing only because nobody had
     changed one of them yet - and on 1 Sep 2026 the all-versions proof
     found that they had in fact stopped agreeing in the last bit.

     The Grid Finding Scope already did this correctly: it calls its module
     and computes nothing itself. Geodesy was the exception. It is not now.
     A missing module is a hard failure at load, not a fallback: a fallback
     would silently restore exactly the duplication this removes. */
  const GEODESY = (window.__GRIDATLAS_MODULES__ || {}).geodesy;
  if (!GEODESY) throw new Error('sld-sandbox requires the geodesy module');
  const R_ATLAS = GEODESY.EARTH_RADIUS_KM;
  const DEG = Math.PI / 180;
  const MIN_KV = 33;
  const LINK_COUNT = 5;              // how many substations to reach for
  const MAX_LINK_KM = 40;            // beyond this, silence is more honest
  const SUBS_URL = 'data/grid_substations.geojson';
  const SUBS_LAYER_ID = 'l-subs';    // engine convention: layer `l-<id>`, source `src-<id>`

  // Project technologies this fires for. Onshore only: an offshore turbine's
  // export route is nothing like a straight line to the nearest onshore
  // substation, so drawing one would be a picture of a lie.
  /* Every technology the register actually uses, and then some.
     ----------------------------------------------------------------------
     This set was solar, bess and two spellings of wind, and it silently
     rejected the rest. Counted against the shipped register: 2,399 onshore
     wind projects and 109 offshore, so 2,508 of 7,680 — a third of the
     register — had a MAP button that did nothing at all. Not an error, not a
     message, nothing: the deep link tested membership and returned.

     The register writes `wind_onshore`. The engine has had a `wind_onshore`
     layer the whole time. Only this list disagreed with both.

     So it no longer decides alone. The list below is the fast path, and
     anything the ENGINE has a layer control for is accepted too — the engine
     owns the layers, so the engine's vocabulary is the authority and this
     stops being a place a technology can be forgotten. */
  const PROJECT_TECHS = new Set([
    'solar', 'solar_operational', 'solar_roof',
    'bess', 'bess_operational',
    'wind', 'wind_onshore', 'wind_onshore_operational',
    'wind_offshore', 'wind_offshore_operational',
    // The rest of the engine's own generation and storage dashboard, read off
    // the live page rather than guessed. Note wind_onshore is NOT among the
    // engine's layer ids -- it has `wind` and `wind_onshore_operational` --
    // yet the register writes wind_onshore for 2,399 projects. Asking the
    // engine alone would still have missed every one of them, which is why the
    // explicit entry above is not redundant with the lookup below.
    'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal',
    'flywheel', 'caes', 'act',
    /* `other` is what the register writes for a category it has no
       bucket for. Over the 11,069-row REPD product this Atlas's search
       lane reads, 25 DESNZ categories normalise to 14 ids and `other` was
       the only one missing here - 4 projects, 2 Unknown and 2 Air Source
       Heat Pumps. Not many; not zero; and written again the next time the
       register gains a category. */
    'other'
  ]);

  /* Which technologies measure, and what each measurement is OF, is owned by
     the technology-coverage module rather than by this file. It is assembled
     into this cartridge ahead of this part, so it is here by the time any of
     this runs; the fallback below exists only so a proof can load this part
     alone, and it reproduces the module's answer rather than a different one.

     Offshore NO LONGER WITHHOLDS. It used to open a card and draw nothing, on
     reasoning about export cables and landfalls that was right about routes
     and wrong about whether to measure at all. An offshore project's export
     cable does land at an onshore substation, so the distance is a
     measurement of something real. What changed is the answer; what did not
     change is a single word of the route reasoning, which the module now
     prints beside the number instead of instead of it. */
  const coverage = (() => {
    try {
      const module = window.__GRIDATLAS_MODULES__?.technologyCoverage;
      if (module && typeof module.policy === 'function') return module;
    } catch (_) { /* fall through to the local reproduction */ }
    const OFF = new Set(['wind_offshore', 'wind_offshore_operational']);
    return {
      policy: (tech) => ({ technology: tech || null, measure: true,
        offshore: OFF.has(String(tech || '')),
        sample: 'nearest of the mapped substations at or above the voltage '
          + 'floor that this search could see',
        notes: [] }),
      namedOffshore: () => false
    };
  })();
  const OFFSHORE_TECHS = new Set(['wind_offshore', 'wind_offshore_operational']);

  function isProjectTech(tech) {
    if (!tech) return false;
    if (PROJECT_TECHS.has(tech)) return true;
    // Ask the engine. If it has a control for this layer, it is a technology
    // this map knows about, whatever this cartridge was written knowing.
    try {
      return Boolean(document.querySelector(
        'input[type=checkbox][data-layer-id="' + String(tech).replace(/"/g, '') + '"]'));
    } catch (error) {
      return false;
    }
  }

  /* Pipeline News' MAP link sends a technology BUCKET, not a layer id, and
     the two are not the same vocabulary. There are exactly thirteen buckets
     it can send -- the four-member spine solar/bess/wind_onshore/
     wind_offshore, plus the nine wider-fleet buckets biomass/hydro/
     hydrogen/act/tidal/geothermal/caes/flywheel/other -- see
     atlas/modules/202609031310-technology-coverage.js SPINE and
     widerFleetBuckets(), which is the one place that list is owned.

     isProjectTech() above tests membership of PROJECT_TECHS, which
     deliberately contains wind_onshore, wind_offshore and other so that an
     arrival for one of them is not abandoned. That membership test answers
     "is this a technology the map recognises", not "is there a layer
     control with this exact id" -- and those are different questions here:

       - wind_onshore and wind_offshore are not layer ids. The engine
         publishes one combined `wind` layer, filtered on tech === 'wind',
         which is inclusive of both orientations and every status (see
         ukConfig's REPD layer group); wind_onshore_operational and
         wind_offshore_operational are narrower operational-only subsets,
         not the general layer. A deep link for either bucket wants the
         general layer switched on, so both resolve to 'wind'.
       - other has never had a layer control at all. 25 DESNZ categories
         normalise to 14 register ids and `other` is the one bucket that
         genuinely has nothing to switch on -- not a bug to retry, a fact
         to state.

     Measured live on v9.107: because isProjectTech('wind_onshore') is
     true, the arrival's own technology_layer.enabled read true while the
     DOM search for a control literally named "wind_onshore" failed every
     time -- 2,508 of 7,680 register rows, a third of it. One table here,
     consulted at the one place a control is actually looked up, so a
     bucket cannot go missing from it the way these three did while still
     passing the membership test that was supposed to catch that. */
  const LAYER_ID_FOR_BUCKET = Object.freeze({
    wind_onshore: 'wind',
    wind_offshore: 'wind',
    other: null   // no layer exists; the caller must say so, not search for one
  });

  function layerIdForBucket(tech) {
    const id = String(tech == null ? '' : tech);
    return Object.prototype.hasOwnProperty.call(LAYER_ID_FOR_BUCKET, id)
      ? LAYER_ID_FOR_BUCKET[id] : id;
  }

  // SCADA on a dark map, not arcade neon. These are the muted siblings of the
  // engine's own layer colours: enough saturation to read as live, low enough
  // not to shout over the basemap or the grid layers underneath.
  const TECH_COLOUR = {
    solar: '#d8c96a', solar_operational: '#d8c96a', solar_roof: '#d8c96a',
    bess: '#d9963c', bess_operational: '#d9963c',
    wind: '#6fb582', wind_onshore: '#6fb582', wind_onshore_operational: '#6fb582',
    // Offshore reads cooler than onshore: it is the one technology here whose
    // links are deliberately not drawn, and it should not look like the others.
    wind_offshore: '#5f9fb5', wind_offshore_operational: '#5f9fb5',
    biomass: '#b58f6f', hydro: '#6f9fd8', hydrogen: '#a98fd8',
    tidal: '#5fb5a8', geothermal: '#b57f6f',
    flywheel: '#9f9fb5', caes: '#9f9fb5', act: '#9f9fb5'
  };
  const SUBSTATION_COLOUR = '#5fbdc2';   // teal, the substation end of a link

  /* ── the 400 kV public record ────────────────────────────────────────
     The nearest-substations list is a measurement and nothing more. But
     the DCO-scale schemes each carry a PUBLIC declared point of connection
     at 400 kV - usually through a new customer substation consented within
     the scheme itself - and this card used to say nothing about it while
     listing closer 33 and 132 kV points, which read as connecting them to
     the wrong network. The rule holds: bind to the public record or say
     nothing. Every entry below is sourced from Development Consent Orders,
     Planning Inspectorate documents, or public project statements; the
     table binds a register identity to a NAMED substation in the served
     payload, and the distance shown is measured, never asserted. */
  const DECLARED_COLOUR = '#d8b64a';   // gold: declared, and the far end exists today
  /* Pink: declared, and the thing at the far end has not been built. One
     Earth's point of connection is a National Grid substation that does not