GLOBALGRID2050 / EXPLORE CODE

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

Place Postcode Search and 1 more file

A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from postcodes.io and the GridAtlas repository.

652 lines of JavaScript from code-generator, in 2 files. Topic: Grid network and substations. Section 310 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. Ventus Corev8engine geodesy · code-generator / apps/substation-finder/Si/ventus-corev8engine.js lines 1282–1427
  2. Place Postcode Search render · code-generator / apps/substation-finder/Ug/202608301136-place-postcode-search.js lines 1–506

Ventus Corev8engine

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line, london underground, UK metros trams and HS2, using haversine. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

Set aside from the main view: 97% of its lines are the same as apps/substation-finder/Si/202609040045-ventus-corev8engine-deep-link-receiver.js (code-generator), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Ventus Corev8engine Deep Link Receiver; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9696 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609040045-ventus-corev8engine-deep-link-receiver.js:1-1460 7537cbc360f3767fcdeff6949e6fa47233f4f23f
  • sha256 23b0705b3b8867da1d1616ba3adb0a4be70e08bb12504432d76b759dd6d54df3
  • target sha256 b1da9baca77c7ddc1b45ce3396c60d1da17e38fdf4faa0a5fc70ea1639a92dfc
  • 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/ventus-corev8engine.js · lines 1282–1427 of 1427 (continued from section 308) · Entry point · pattern focusCanonicalProjectDeepLink (shared by 14 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 58 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.
Inputs & outputs
In: GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json; JSON file build_manifest.json; form fields (user input). Out: interactive map.
Downstream impact
Used directly by 3 files: GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (globalgrid2050, https://globalgrid2050.com/repd_grid_atlasv8/); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 501 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/); Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html). It is itself an entry point, published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). It reads `/uk_renewables_pipeline/v9/data/v9.1/build_manifest.json`. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Loaded by the Renewable Energy Planning Database (REPD) Grid Atlas v8 page in GlobalGrid2050 at https://globalgrid2050.com/repd_grid_atlasv8/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine.
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.
Uses
none found
Used by
loaded by GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (script src), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
none
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/ventus-corev8engine.js:1282-1427 · blob 0a647c32c346770851704727bbf86fb7167e2596 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
            const layer = getLayerConfig(id);
            const layerObject = {
                id: `l-${id}`, type: 'circle', source: TRANSIT_SOURCE_MAP[id], layout: { visibility: 'none' },
                paint: { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 }
            };
            if (layer.filter)  layerObject.filter  = layer.filter; if (layer.minzoom) layerObject.minzoom  = layer.minzoom;
            map.addLayer(layerObject); allLayerIds.push(`l-${id}`);
        });

        map.addSource('src-ev', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
        map.addLayer({ id: 'l-ev', type: 'circle', source: 'src-ev', layout: { visibility: 'none' }, paint: { 'circle-color': '#00ff88', 'circle-radius': 5, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 } });
        allLayerIds.push('l-ev');

        map.addSource('src-repd', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
        REPD_IDS.forEach(id => {
            const layer = getLayerConfig(id);
            if (id === 'solar_roof') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 1.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capaci  … [line shortened here: 513 characters; full line on GitHub]
            }
            if (id === 'solar') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 4.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],4.0,'#ffff00',20.0,'#ffaa00',50.0,'#ff4400',200.0,'#ff0000'], 'circle-radius': ['interpolate',['linear'],['coalesc  … [line shortened here: 638 characters; full line on GitHub]
            }
            if (id === 'solar_operational') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#00ff88',50.0,'#00cc66',200.0,'#009944',350.0,'#006622'], 'circle-radius': ['interpolate',['linear'],['coal  … [line shortened here: 645 characters; full line on GitHub]
            }
            if (id === 'bess_operational') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#ffb3d9',50.0,'#ff69b4',200.0,'#ff1493',350.0,'#cc0066'], 'circle-radius': ['interpolate',['linear'],['coal  … [line shortened here: 645 characters; full line on GitHub]
            }
            if (id === 'wind_onshore_operational') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ffee',50.0,'#00ffcc',200.0,'#00ccaa',350.0,'#008877'], 'circle-radius': ['interpolate',['linear'],['coal  … [line shortened here: 645 characters; full line on GitHub]
            }
            if (id === 'wind_offshore_operational') {
                map.addLayer({ id: `l-${id}-glow`, type: 'circle', source: 'src-repd', filter: ['all', layer.filter, ['>=', ['coalesce', ['get', 'capacity'], 0], 10.0]], layout: { visibility: 'none' }, paint: { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],10.0,'#99ccff',50.0,'#3399ff',200.0,'#0055dd',350.0,'#003399'], 'circle-radius': ['interpolate',['linear'],['coal  … [line shortened here: 645 characters; full line on GitHub]
            }
            const circlePaint = id === 'solar_roof'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffcc00',0.99,'#ffcc00',1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,7,0.5,7,0.99,8,1.0,16,2.0,18,5.0,22,10.0,28], 'circle-stroke-width': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,1,0.99,1,1.0,2], 'circ  … [line shortened here: 449 characters; full line on GitHub]
                : id === 'solar'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffff00',20.0,'#ffcc00',50.0,'#ffaa00',200.0,'#ff6600',500.0,'#ff2200'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 }
                : id === 'solar_operational'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#66ff99',10,'#33ff77',50,'#00dd55',100,'#00bb44',200,'#008833',350,'#006622',500,'#004411'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,10,10,14,50,18,100,22,200,28,350,35,500,42], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
                : id === 'bess_operational'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffccee',10,'#ffb3d9',50,'#ff69b4',100,'#ff1493',200,'#dd0077',350,'#990066',500,'#660044'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
                : id === 'wind_onshore_operational'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ccfff5',10,'#99ffee',50,'#00ffcc',100,'#00ddaa',200,'#00aa88',350,'#007766',500,'#004433'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
                : id === 'wind_offshore_operational'
                ? { 'circle-color': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#cce5ff',10,'#99ccff',50,'#3399ff',100,'#0066ee',200,'#0044bb',350,'#003399',500,'#001166'], 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,12,50,16,100,20,200,26,350,32,500,38], 'circle-stroke-width': 2, 'circle-stroke-color': '#000', 'circle-opacity': 0.90 }
                : { 'circle-color': layer.color, 'circle-radius': ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,8,10,10,50,13,200,17,500,22,1000,28], 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000', 'circle-opacity': 0.85 };

            map.addLayer({ id: `l-${id}`, type: 'circle', source: 'src-repd', filter: layer.filter, layout: { visibility: 'none' }, paint: circlePaint });
            allLayerIds.push(`l-${id}`);
        });

        // ── PERF: seed the visible layer cache from actual map state after all layers are added
        _rebuildVisibleCache(allLayerIds);

        // ── Map Events ────────────────────────────────────────────────────────────

        let _pendingToolClick = null;

        map.getCanvas().addEventListener('mousedown', e => {
            if (!zoneDrawMode) return;
            const lngLat = map.unproject([e.offsetX, e.offsetY]);
            _zoneDrawOnMouseDown({ lngLat, preventDefault: () => e.preventDefault() });
        });

        map.on('click', e => {
            if (measureMode) {
                _pendingToolClick = setTimeout(() => {
                    _pendingToolClick = null;
                    if (!measureClosed) {
                        measurePoints.push([e.lngLat.lng, e.lngLat.lat]);
                        updateMeasureLayers();
                        updateMeasureDisplay();
                    }
                }, CLICK_DEBOUNCE_MS);
                return;
            }
            if (zoneDrawMode) { _zoneDrawOnClick(e); return; }
            if (radiusMode) { doRadiusSearch(e.lngLat.lng, e.lngLat.lat); return; }
            if (radiusAreaMode) { doRadiusAreaMeasure(e.lngLat.lng, e.lngLat.lat); return; }

            if (!_visibleInteractiveIds.length) return;
            const features = map.queryRenderedFeatures(e.point, { layers: _visibleInteractiveIds });

            if (!features.length) return;
            const p    = features[0].properties || {}; const name = p.name || p.SiteName || p['Site Name'] || 'Unnamed Asset';

            if (p.type === 'supermarket') {
                const address = [p.street, p.city, p.postcode].filter(Boolean).join(', '); const area = p.area_m2 ? `${p.area_m2.toLocaleString()} m²` : '';
                openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:${p.colour || '#00ffff'};font-size:13px">${escapeHTML(p.brand || name)}</b><br>${p.name && p.name !== p.brand ? `<span style="color:#fff">${escapeHTML(p.name)}</span><br>` : ''}<span style="color:#888">${escapeHTML(address)}</span><br>${area ? `<span style="color:#ffae00">Area: ${esc  … [line shortened here: 445 characters; full line on GitHub]
            }

            if (p.type === 'elizabeth_line_station') {
                openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#60399E;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">Elizabeth Line Station</span><br><span style="color:#555;font-size:10px">${escapeHTML(p.operator)}</span></div>`); return;
            }

            if (p.type === 'stadium') {
                const club = p.club ? `<span style="color:#fff">${escapeHTML(p.club)}</span><br>` : ''; const cap = p.capacity && p.capacity !== "Unknown" ? `Capacity: ${Number(p.capacity).toLocaleString()}` : 'Capacity: Unknown';
                openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#e5ff00;font-size:13px">${escapeHTML(name)}</b><br>${club}<span style="color:#888">${escapeHTML(p.sport)}</span><br><span style="color:#ffae00">${escapeHTML(cap)}</span></div>`); return;
            }

            if (p.type === 'naei_emitter') {
                const tonnes = p.emission_tco2e ? Number(p.emission_tco2e).toLocaleString('en-GB', { maximumFractionDigits: 0 }) : 'Unknown';
                const dataLabel = p.datatype === 'O' ? 'Self-reported by the company' : p.datatype === 'M' ? 'Estimated by the government' : 'Official figures';
                openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:8px 10px;border:1px solid #ff4400;border-radius:4px;min-width:220px;max-width:280px"><b style="color:#ff4400;font-size:13px">🏭 ${escapeHTML(name)}</b><br><span style="color:#888;font-size:10px">Run by: ${escapeHTML(p.operator || 'Unknown')}</span><br><span style="color:#aaa;font-size:10px">Industry: ${es  … [line shortened here: 952 characters; full line on GitHub]
            }

            const tech = p.tech || ''; const rawTech = p.raw_tech || p.type || tech; const voltage = p.voltage || ''; const capacity = parseFloat(p.capacity) || 0; const powerKw = p.power_kw || null; const connectors = p.connectors || ''; const status = p.status || ''; const operator = p.operator || ''; const mounting = (p.mounting && p.mounting !== 'nan') ? ` | ${escapeHTML(p.mounting)}` : ''; co  … [line shortened here: 808 characters; full line on GitHub]
            openPopup(e.lngLat, `<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHTML(name)}</b><br><span style="color:#888">${escapeHTML(rawTech)}${voltage ? ` | ${escapeHTML(voltage)}` : ''}${mounting}</span><br>${evFields}${capStr ? `<span style="color:#ffae00">${escapeHTML(capStr)}</span>` : ''}${status ? `<span style="color:${stat  … [line shortened here: 578 characters; full line on GitHub]
        });

        map.on('dblclick', e => {
            if (_pendingToolClick) { clearTimeout(_pendingToolClick); _pendingToolClick = null; }
            if (zoneDrawMode) { e.preventDefault(); return; }
            if (!measureMode || measurePoints.length < 2) return;
            e.preventDefault();
            measureClosed = true;
            updateMeasureLayers();
            updateMeasureDisplay();
        });

        window.addEventListener('mouseup', () => { if (zoneDrawMode) _zoneDrawOnMouseUp(); });

        map.on('mousemove', e => {
            if (zoneDrawMode) { _zoneDrawOnMouseMove(e); return; }

            if (measureMode || radiusMode || radiusAreaMode) { map.getCanvas().style.cursor = 'crosshair'; return; }

            if (!_visibleHoverIds.length) { map.getCanvas().style.cursor = ''; return; }

            const now = Date.now();
            if (now - _lastHoverMs < HOVER_THROTTLE_MS) return;
            _lastHoverMs = now;

            if (_lastMouseMoveRaf) return;
            _lastMouseMoveRaf = requestAnimationFrame(() => {
                _lastMouseMoveRaf = null;
                const features = map.queryRenderedFeatures(e.point, { layers: _visibleHoverIds });
                map.getCanvas().style.cursor = features.length ? 'pointer' : '';
            });
        });

        GRID_CONFIG.forEach(group => { group.layers.forEach(layer => { if (layer.preload) hydrateLayer(layer.id); }); });
        focusCanonicalProjectDeepLink();
    });
};

Place Postcode Search

A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from postcodes.io and the GridAtlas repository.

rendercode-generator / apps/substation-finder/Ug/202608301136-place-postcode-search.js · lines 1–506 of 506 · version 2026-08-30 11:36 · pattern waitForCapturedMap (shared by 8 files)

What it does
It maps REPD projects, postcodes and the REPD register. Defines 25 functions or classes, including invariant, escapeHtml, sqlString, normaliseCompact, parseGroups. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
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: postcodes, the REPD register.
Inputs & outputs
In: data source: gridatlas data; data source: postcodes.io; Parquet file repd_projects_202608290716.parquet; JSON file repd_v9_manifest_202608290716.json; DuckDB queries. Out: interactive map.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It normalises compact (`normaliseCompact`), parses groups (`parseGroups`) and verifies manifest (`verifyManifest`). Its `buildWhere` function gives SQL predicate from query text (VEDIC: query). It responds to click, input and keydown events.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
code-generator · apps/substation-finder/Ug · script
VEDIC
QUERY (GG2050-VEDIC-000046): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_predicate
VEDIC
SCORE (GG2050-VEDIC-000047): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_sort_expression
VEDIC
UK GEOCODE (GG2050-VEDIC-000048): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → uk_location_candidates
Uses
none found
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
invariant, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, runtime, installMapCapture, buildWhere, buildScore, rowObject
Defines here
invariant, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, runtime, installMapCapture, buildWhere, buildScore, rowObject, queryOfficialRepd, hasSafeMapPoint, setDeepLink, selectResult, geocoderGet, joinParts, queryUkGazetteer, selectLocation, renderResults, executeSearch, waitForCapturedMap, receiveExactRepdDeepLink, bindSearch
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/Ug/202608301136-place-postcode-search.js:1-506 · blob 9ec0ba631740b3b35e5e40a0f4ea40e7c130ff4c · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
(() => {
  'use strict';

  const PARQUET_URL = 'https://ventusltd.github.io/gridatlas/data/repd_projects_202608290716.parquet';
  const PARQUET_SHA256 = '174040c37f3d63742d6fdd7af722a8cfdf3fb53de3ff85ff1142d22fdac4866b';
  const MANIFEST_URL = 'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202608290716.json';
  const MANIFEST_SHA256 = '8850567ff9f1d2b6996b4e0d9707320030f3466a0b821cdcfc5325322b8be8c8';
  const GEOCODER_BASE = 'https://api.postcodes.io';
  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';
  const FALSE_ORIGIN = Object.freeze({ latitude: 49.766807, longitude: -7.55716 });

  const state = {
    schema: 'gridatlas.v9-place-postcode-search.v2',
    generation: '202608301136',
    geocoder: GEOCODER_BASE,
    geocoder_requests: 0,
    geocoder_failures: [],
    last_location_selection: null,
    parquet_url: PARQUET_URL,
    parquet_sha256: PARQUET_SHA256,
    ready: false,
    map_captured: false,
    query_count: 0,
    last_query: '',
    last_results: [],
    last_selection: null,
    failures: [],
    deep_link: { status: 'IDLE', repd_ref: null, resolved: false, mapped: false }
  };
  window.__GRIDATLAS_PLACE_SEARCH__ = state;

  let runtimePromise = null;
  let manifestPromise = null;
  let debounceTimer = null;
  let activeQuerySerial = 0;

  function invariant(condition, message) {
    if (!condition) throw new Error(message);
  }

  function escapeHtml(value) {
    return String(value ?? '')
      .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  }

  function sqlString(value) {
    return `'${String(value).replaceAll("'", "''")}'`;
  }

  function normaliseCompact(value) {
    return String(value ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');
  }

  function parseGroups(query) {
    return String(query ?? '')
      .trim()
      .toLowerCase()
      .split(/\s+/)
      .map(group => group.split('/').map(term => term.replace(/[^a-z0-9]/g, '')).filter(Boolean))
      .filter(group => group.length);
  }

  async function sha256Hex(bytes) {
    const digest = await crypto.subtle.digest('SHA-256', bytes);
    return [...new Uint8Array(digest)].map(value => value.toString(16).padStart(2, '0')).join('');
  }

  async function verifyManifest() {
    manifestPromise ||= (async () => {
      const response = await fetch(MANIFEST_URL, { cache: 'no-store' });
      invariant(response.ok, `REPD manifest HTTP ${response.status}`);
      const bytes = await response.arrayBuffer();
      invariant(await sha256Hex(bytes) === MANIFEST_SHA256, 'REPD manifest SHA-256 mismatch');
      const manifest = JSON.parse(new TextDecoder().decode(bytes));
      invariant(manifest?.schema === 'gridatlas.build-manifest.v1', 'REPD manifest schema mismatch');
      invariant(manifest?.generation === '202608290716', 'REPD generation mismatch');
      invariant(manifest?.closure?.rows === 11069, 'REPD row closure mismatch');
      invariant(manifest?.closure?.postcodes === 9505, 'REPD postcode closure mismatch');
      invariant(manifest?.closure?.addresses === 11059, 'REPD address closure mismatch');
      invariant(manifest?.parquet?.sha256 === PARQUET_SHA256, 'REPD Parquet identity mismatch');
      return manifest;
    })();
    return manifestPromise;
  }

  async function runtime() {
    runtimePromise ||= (async () => {
      await verifyManifest();
      const duckdb = await import(DUCKDB_MODULE);
      const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
      invariant(bundle?.mainModule && bundle?.mainWorker, 'DuckDB-WASM bundle unavailable');
      const workerUrl = URL.createObjectURL(new Blob([
        `importScripts(${JSON.stringify(bundle.mainWorker)});`
      ], { type: 'text/javascript' }));
      const worker = new Worker(workerUrl);
      const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
      const database = new duckdb.AsyncDuckDB(logger, worker);
      try {
        await database.instantiate(bundle.mainModule, bundle.pthreadWorker);
      } finally {
        URL.revokeObjectURL(workerUrl);
      }
      const connection = await database.connect();
      return { connection, database, worker };
    })();
    return runtimePromise;
  }

  function installMapCapture() {
    if (!window.maplibregl?.Map || window.__GRIDATLAS_V9_MAP_CAPTURE_INSTALLED__) return;
    const NativeMap = window.maplibregl.Map;
    const ProxyMap = new Proxy(NativeMap, {
      construct(target, args, newTarget) {
        const instance = Reflect.construct(target, args, newTarget);
        window.__GRIDATLAS_V9_MAP__ = instance;
        state.map_captured = true;
        return instance;
      }
    });
    window.maplibregl.Map = ProxyMap;
    window.__GRIDATLAS_V9_MAP_CAPTURE_INSTALLED__ = true;
  }

  installMapCapture();

  function buildWhere(query) {
    const groups = parseGroups(query);
    invariant(groups.length > 0, 'empty search query');
    const searchable = `lower(concat_ws(' ', coalesce(name,''), coalesce(repd_address_display,''), coalesce(repd_postcode,''), coalesce(county,''), coalesce(planning_authority,''), coalesce(repd_ref,'')))`;
    const compactPostcode = `regexp_replace(upper(coalesce(repd_postcode,'')), '[^A-Z0-9]', '', 'g')`;
    const compactRef = `regexp_replace(upper(coalesce(repd_ref,'')), '[^A-Z0-9]', '', 'g')`;
    return groups.map(group => {
      const alternatives = [];
      for (const term of group) {
        const compact = normaliseCompact(term);
        alternatives.push(`${searchable} LIKE ${sqlString(`%${term}%`)}`);
        if (compact) {
          alternatives.push(`${compactPostcode} LIKE ${sqlString(`%${compact}%`)}`);
          alternatives.push(`${compactRef} = ${sqlString(compact)}`);
        }
      }
      return `(${alternatives.join(' OR ')})`;
    }).join(' AND ');
  }

  function buildScore(query) {
    const compact = normaliseCompact(query);
    const firstTerm = parseGroups(query).flat()[0] || '';
    const clauses = [];
    if (compact) {
      clauses.push(`CASE WHEN regexp_replace(upper(coalesce(repd_postcode,'')), '[^A-Z0-9]', '', 'g') = ${sqlString(compact)} THEN 10000 ELSE 0 END`);
      clauses.push(`CASE WHEN upper(coalesce(repd_ref,'')) = ${sqlString(compact)} THEN 9000 ELSE 0 END`);
    }
    if (firstTerm) {
      clauses.push(`CASE WHEN lower(coalesce(name,'')) = ${sqlString(firstTerm)} THEN 2000 ELSE 0 END`);
      clauses.push(`CASE WHEN lower(coalesce(name,'')) LIKE ${sqlString(`${firstTerm}%`)} THEN 500 ELSE 0 END`);
      clauses.push(`CASE WHEN lower(coalesce(repd_address_display,'')) LIKE ${sqlString(`%${firstTerm}%`)} THEN 200 ELSE 0 END`);
    }
    return clauses.length ? clauses.join(' + ') : '0';
  }

  function rowObject(row) {
    return row && typeof row.toJSON === 'function' ? row.toJSON() : row;
  }

  async function queryOfficialRepd(query, serial = null) {
    const trimmed = String(query ?? '').trim();
    if (trimmed.length < 2) return [];
    const { connection } = await runtime();
    const sql = `
      SELECT
        repd_ref, name, repd_address_display, repd_postcode, county,
        planning_authority, technology, status, capacity_mw, longitude, latitude,
        (${buildScore(trimmed)}) AS search_score
      FROM read_parquet(${sqlString(PARQUET_URL)})
      WHERE ${buildWhere(trimmed)}
      ORDER BY search_score DESC, capacity_mw DESC NULLS LAST, name ASC
      LIMIT 25
    `;
    const table = await connection.query(sql);
    if (serial !== null && serial !== activeQuerySerial) return [];
    const results = table.toArray().map(rowObject).map(row => ({
      repd_ref: String(row.repd_ref ?? ''),
      name: String(row.name ?? ''),
      address: String(row.repd_address_display ?? ''),
      postcode: String(row.repd_postcode ?? ''),
      county: String(row.county ?? ''),
      planning_authority: String(row.planning_authority ?? ''),
      technology: String(row.technology ?? ''),
      status: String(row.status ?? ''),
      capacity_mw: row.capacity_mw == null ? null : Number(row.capacity_mw),
      longitude: row.longitude == null ? null : Number(row.longitude),
      latitude: row.latitude == null ? null : Number(row.latitude),
      score: Number(row.search_score || 0)
    }));
    state.query_count += 1;
    state.last_query = trimmed;
    state.last_results = results.slice(0, 25);
    return results;
  }

  function hasSafeMapPoint(result) {
    if (!Number.isFinite(result.longitude) || !Number.isFinite(result.latitude)) return false;
    if (Math.abs(result.longitude) < 1e-12 && Math.abs(result.latitude) < 1e-12) return false;
    if (Math.abs(result.latitude - FALSE_ORIGIN.latitude) < 1e-9 && Math.abs(result.longitude - FALSE_ORIGIN.longitude) < 1e-9) return false;
    return result.longitude >= -180 && result.longitude <= 180 && result.latitude >= -90 && result.latitude <= 90;
  }

  function setDeepLink(result) {
    const url = new URL(window.location.href);
    url.searchParams.set('repd_ref', result.repd_ref);
    history.replaceState(history.state, '', url);
  }

  function selectResult(result) {
    setDeepLink(result);
    const map = window.__GRIDATLAS_V9_MAP__;
    const canMap = hasSafeMapPoint(result) && map && typeof map.flyTo === 'function';
    state.last_selection = {
      repd_ref: result.repd_ref,
      name: result.name,
      postcode: result.postcode,
      mapped: Boolean(canMap),
      longitude: result.longitude,
      latitude: result.latitude
    };
    if (!canMap) return;
    map.flyTo({ center: [result.longitude, result.latitude], zoom: 12, duration: 1200, essential: true });
    const cap = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
    const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
    new window.maplibregl.Popup({ maxWidth: '340px' })
      .setLngLat([result.longitude, result.latitude])
      .setHTML(`<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHtml(result.name)}</b><br><span style="color:#888">${escapeHtml(result.technology)}</span>${cap ? `<br><span style="color:#ffae00">${escapeHtml(cap)}</span>` : ''}<br><span style="color:#aaa;font-size:10px">${escapeHtml(location)}</span><br><span style="color:#555;font-siz  … [line shortened here: 488 characters; full line on GitHub]
      .addTo(map);
  }

  // ---- 202608301136 UK gazetteer lane (LOCATION_ONLY, never claims REPD identity) ----
  const FULL_POSTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?[0-9][A-Z]{2}$/;
  const OUTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?$/;
  let locationPopup = null;

  async function geocoderGet(path, query) {
    state.geocoder_requests += 1;
    try {
      const response = await fetch(`${GEOCODER_BASE}${path}`, { cache: 'default' });
      if (response.status === 404) return null;
      if (!response.ok) throw new Error(`postcodes.io ${response.status} for ${path}`);
      const body = await response.json();
      return body?.result ?? null;
    } catch (error) {
      state.geocoder_failures.push({
        query: String(query ?? ''),
        path,
        message: String(error?.message || error)
      });
      throw error;
    }
  }

  function joinParts(...parts) {
    return parts.filter(Boolean).join(' · ');
  }

  async function queryUkGazetteer(query) {
    const raw = String(query ?? '').trim();
    if (raw.length < 2) return [];
    const compact = normaliseCompact(raw);
    const out = [];
    try {
      if (FULL_POSTCODE.test(compact)) {
        const result = await geocoderGet(`/postcodes/${encodeURIComponent(compact)}`, raw);
        if (result && Number.isFinite(result.longitude) && Number.isFinite(result.latitude)) {
          out.push({
            kind: 'postcode',
            label: result.postcode,
            sublabel: joinParts(result.admin_district, result.admin_county, result.region),
            longitude: result.longitude,
            latitude: result.latitude
          });
          return out;
        }
      } else if (OUTCODE.test(compact)) {
        const result = await geocoderGet(`/outcodes/${encodeURIComponent(compact)}`, raw);
        if (result && Number.isFinite(result.longitude) && Number.isFinite(result.latitude)) {
          out.push({
            kind: 'postcode_district',
            label: result.outcode,
            sublabel: joinParts(
              Array.isArray(result.admin_district) ? result.admin_district.join(', ') : result.admin_district,
              Array.isArray(result.region) ? result.region.join(', ') : result.region
            ),
            longitude: result.longitude,
            latitude: result.latitude
          });
          return out;
        }
      }

      const places = await geocoderGet(`/places?q=${encodeURIComponent(raw)}&limit=8`, raw);
      for (const place of Array.isArray(places) ? places : []) {
        if (!Number.isFinite(place.longitude) || !Number.isFinite(place.latitude)) continue;
        out.push({
          kind: 'place',
          label: place.name_1,
          sublabel: joinParts(place.local_type, place.county_unitary, place.region),
          longitude: place.longitude,
          latitude: place.latitude
        });
      }
    } catch (error) {
      console.warn('[V9 UK GAZETTEER]', error);
    }
    return out;
  }

  function selectLocation(result) {
    const url = new URL(window.location.href);
    url.searchParams.delete('repd_ref');
    history.replaceState(history.state, '', url);
    const map = window.__GRIDATLAS_V9_MAP__;
    const canMap = hasSafeMapPoint(result) && map && typeof map.flyTo === 'function';
    state.last_location_selection = { ...result, mapped: Boolean(canMap) };
    if (!canMap) return;
    const zoom = result.kind === 'postcode' ? 13 : result.kind === 'postcode_district' ? 11 : 12;
    map.flyTo({ center: [result.longitude, result.latitude], zoom, duration: 1200, essential: true });
    if (locationPopup) locationPopup.remove();
    locationPopup = new window.maplibregl.Popup({ maxWidth: '300px' })
      .setLngLat([result.longitude, result.latitude])
      .setHTML(`<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHtml(result.label)}</b><br><span style="color:#aaa;font-size:10px">${escapeHtml(result.sublabel)}</span><br><span style="color:#555;font-size:9px">Location only · postcodes.io · no project identity claimed</span></div>`)
      .addTo(map);
  }

  function renderResults(repdResults, resultsEl, locationResults = []) {
    resultsEl.innerHTML = '';
    if (!repdResults.length && !locationResults.length) {
      const empty = document.createElement('div');
      empty.className = 'search-no-results';
      empty.textContent = 'No REPD project, UK postcode or place match';
      resultsEl.appendChild(empty);
      resultsEl.style.display = 'block';
      return;
    }

    for (const result of repdResults) {
      const item = document.createElement('div');
      item.className = 'search-result-item';
      item.dataset.repdRef = result.repd_ref;
      const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
      const capacity = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
      item.innerHTML = `<b>${escapeHtml(result.name)}</b><br><span>${escapeHtml(location)}</span>${capacity ? `<br><span style="color:#ffae00">${escapeHtml(capacity)}</span>` : ''}<span style="color:#555"> · REPD ${escapeHtml(result.repd_ref)}</span>`;
      item.addEventListener('click', event => {
        event.preventDefault();
        event.stopPropagation();
        resultsEl.style.display = 'none';
        selectResult(result);
      });
      resultsEl.appendChild(item);
    }

    if (locationResults.length) {
      const divider = document.createElement('div');
      divider.className = 'search-no-results';
      divider.textContent = 'UK location';
      resultsEl.appendChild(divider);
      for (const result of locationResults) {
        const item = document.createElement('div');
        item.className = 'search-result-item';
        item.dataset.locationKind = result.kind;
        item.innerHTML = `<b>${escapeHtml(result.label)}</b><br><span>${escapeHtml(result.sublabel)}</span><span style="color:#555"> · fly to only, not a REPD project</span>`;
        item.addEventListener('click', event => {
          event.preventDefault();
          event.stopPropagation();
          resultsEl.style.display = 'none';
          selectLocation(result);
        });
        resultsEl.appendChild(item);
      }
    }
    resultsEl.style.display = 'block';
  }

  async function executeSearch(input, resultsEl) {
    const serial = ++activeQuerySerial;
    const query = input.value.trim();
    if (query.length < 2) {
      resultsEl.innerHTML = '';
      resultsEl.style.display = 'none';
      return;
    }
    resultsEl.style.display = 'block';
    resultsEl.innerHTML = '<div class="search-no-results">Searching REPD projects and UK postcodes / places…</div>';
    try {
      const [results, locations] = await Promise.all([
        queryOfficialRepd(query, serial),
        queryUkGazetteer(query)
      ]);
      if (serial !== activeQuerySerial) return;
      renderResults(results, resultsEl, locations);
    } catch (error) {
      if (serial !== activeQuerySerial) return;
      state.failures.push({ query, message: String(error?.message || error) });
      resultsEl.innerHTML = '<div class="search-no-results">Search unavailable — V8 map remains usable</div>';
      resultsEl.style.display = 'block';
      console.error('[V9 PLACE SEARCH]', error);
    }
  }

  async function waitForCapturedMap(timeoutMs = 60000) {
    const started = performance.now();
    while (performance.now() - started < timeoutMs) {
      const map = window.__GRIDATLAS_V9_MAP__;
      if (map && typeof map.flyTo === 'function') return map;
      await new Promise(resolve => setTimeout(resolve, 50));
    }
    throw new Error('GridAtlas map was not captured for exact REPD deep link');
  }

  async function receiveExactRepdDeepLink(input, resultsEl) {
    const repdRef = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
    if (!repdRef) {
      state.deep_link = { status: 'ABSENT', repd_ref: null, resolved: false, mapped: false };
      return;
    }

    state.deep_link = { status: 'RECEIVING', repd_ref: repdRef, resolved: false, mapped: false };
    try {
      invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
      input.value = repdRef;
      const results = await queryOfficialRepd(repdRef);
      const exact = results.find(result => String(result.repd_ref) === repdRef);
      invariant(exact, `official REPD identity ${repdRef} was not found`);
      renderResults(results, resultsEl);
      await waitForCapturedMap();
      selectResult(exact);
      invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
      invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
      document.body.dataset.gridatlasRepdRef = repdRef;
      document.body.dataset.gridatlasRepdDeepLink = 'resolved';
      state.deep_link = {
        status: 'RESOLVED',
        repd_ref: repdRef,
        resolved: true,
        mapped: true,
        name: exact.name,
        postcode: exact.postcode,
        longitude: exact.longitude,
        latitude: exact.latitude
      };
    } catch (error) {
      const message = String(error?.message || error);
      state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
      state.deep_link = { status: 'FAILED', repd_ref: repdRef, resolved: false, mapped: false, message };
      document.body.dataset.gridatlasRepdDeepLink = 'failed';
      console.error('[V9 EXACT REPD DEEP LINK]', error);
    }
  }

  function bindSearch() {
    const input = document.getElementById('search-input');
    const button = document.getElementById('search-btn');
    const resultsEl = document.getElementById('search-results');
    invariant(input && button && resultsEl, 'V8 search controls missing');
    input.setAttribute('placeholder', 'Search project, UK postcode or town...');
    input.setAttribute('aria-label', 'Search project, UK postcode or town');

    input.addEventListener('input', event => {
      event.stopImmediatePropagation();
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => executeSearch(input, resultsEl), 180);
    }, true);

    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopImmediatePropagation();
        clearTimeout(debounceTimer);
        executeSearch(input, resultsEl);
      } else if (event.key === 'Escape') {
        event.stopImmediatePropagation();
        resultsEl.style.display = 'none';
      }
    }, true);

    button.addEventListener('click', event => {
      event.preventDefault();
      event.stopImmediatePropagation();
      clearTimeout(debounceTimer);
      executeSearch(input, resultsEl);
    }, true);

    state.ready = true;
  }

  window.addEventListener('DOMContentLoaded', () => {
    try {
      bindSearch();
      const input = document.getElementById('search-input');
      const resultsEl = document.getElementById('search-results');
      void receiveExactRepdDeepLink(input, resultsEl);
    } catch (error) {
      state.failures.push({ phase: 'bind', message: String(error?.message || error) });
      console.error('[V9 PLACE SEARCH INIT]', error);
    }
  }, { once: true });
})();