GLOBALGRID2050 / EXPLORE CODE

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

Place Global Search Arrival Identity

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 the GridAtlas repository.

389 lines of JavaScript from code-generator, in 1 file. Topic: Grid network and substations. Section 268 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. Place Global Search Arrival Identity render · code-generator / apps/substation-finder/Ps/202609040229-place-global-search-arrival-identity.js lines 399–787

Place Global Search Arrival Identity

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 the GridAtlas repository.

Set aside from the main view: 96% of its lines are the same as apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js (code-generator), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with UK Gazetteer Flyto; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9552 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js:1-817 f5ba42357785598131bb4f19d0c6027f6bc88dc7
  • sha256 a40137cbae040a9e72329ce38fa8f3c6b9adc88689fb43e7a18a95222bca2401
  • target sha256 ea193b7347ed222bca92c393256001047d198fae617483bacdb4d4a0540b7068
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

rendercode-generator / apps/substation-finder/Ps/202609040229-place-global-search-arrival-identity.js · lines 399–787 of 787 · version 2026-09-04 02:29 (continued from section 267) · pattern invalidatePendingDeepLink (shared by 7 files)

What it does
It maps REPD projects, postcodes and the REPD register. Defines 39 functions or classes, including invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml. 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; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202608290716.parquet; JSON file repd_v9_manifest_202608290716.json; DuckDB queries. Out: interactive map.
Downstream impact
Used directly by 3 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); 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 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). Its `buildWhere` function gives SQL predicate from query text (VEDIC: query). It responds to gridatlas, click and input events.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine.
Application
code-generator · apps/substation-finder/Ps · 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), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
Defines here
queryGlobalGazetteer, dedupeGlobalLocations, selectLocation, renderResults, renderLocationLane, executeSearch, waitForCapturedMap, suppliedArrivalFields, numberOrNull, textOrNull, receiveExactRepdDeepLink, stillOwned, retryExactRepdDeepLink, 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/Ps/202609040229-place-global-search-arrival-identity.js:399-787 · blob fb987aa326171609fd112e36d7a2676461e92e4a · 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
          });
          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',
            provider: 'postcodes.io',
            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',
          provider: 'postcodes.io',
          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;
  }

  async function queryGlobalGazetteer(query) {
    const raw = String(query ?? '').trim();
    if (raw.length < 2) return [];
    const compact = normaliseCompact(raw);
    if (FULL_POSTCODE.test(compact) || OUTCODE.test(compact)) return [];
    state.global_geocoder_requests += 1;
    try {
      const url = new URL(GLOBAL_GEOCODER_URL);
      url.searchParams.set('format', 'jsonv2');
      url.searchParams.set('limit', '8');
      url.searchParams.set('addressdetails', '1');
      url.searchParams.set('accept-language', 'en');
      url.searchParams.set('q', raw);
      const response = await fetch(url, {
        cache: 'default',
        headers: { Accept: 'application/json' }
      });
      if (!response.ok) throw new Error(`Nominatim ${response.status}`);
      const body = await response.json();
      const out = [];
      for (const row of Array.isArray(body) ? body : []) {
        const longitude = Number(row.lon);
        const latitude = Number(row.lat);
        if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) continue;
        const display = String(row.display_name || '').trim();
        const label = String(row.name || row.address?.city || row.address?.town || row.address?.village || display.split(',')[0] || raw).trim();
        out.push({
          kind: 'global_place',
          provider: 'Nominatim / OpenStreetMap',
          label,
          sublabel: display || raw,
          longitude,
          latitude
        });
      }
      return out;
    } catch (error) {
      state.geocoder_failures.push({
        query: raw,
        path: GLOBAL_GEOCODER_URL,
        provider: 'Nominatim / OpenStreetMap',
        message: String(error?.message || error)
      });
      console.warn('[V9.5 GLOBAL GAZETTEER]', error);
      return [];
    }
  }

  function dedupeGlobalLocations(ukResults, globalResults) {
    return globalResults.filter(globalResult => !ukResults.some(ukResult => {
      const sameLabel = String(globalResult.label).trim().toLowerCase() === String(ukResult.label).trim().toLowerCase();
      const close = Math.abs(globalResult.longitude - ukResult.longitude) < 0.03 && Math.abs(globalResult.latitude - ukResult.latitude) < 0.03;
      return sameLabel && close;
    }));
  }

  function selectLocation(result) {
    invalidatePendingDeepLink('location-search-selection');
    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 : result.kind === 'global_place' ? 12 : 12;
    const provider = result.provider || 'postcodes.io';
    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 · ${escapeHtml(provider)} · no project identity claimed</span></div>`)
      .addTo(map);
  }

  function renderResults(repdResults, resultsEl, ukResults = [], globalResults = []) {
    resultsEl.innerHTML = '';
    if (!repdResults.length && !ukResults.length && !globalResults.length) {
      const empty = document.createElement('div');
      empty.className = 'search-no-results';
      empty.textContent = 'No REPD project, postcode, address 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);
    }

    function renderLocationLane(title, locations) {
      if (!locations.length) return;
      const divider = document.createElement('div');
      divider.className = 'search-no-results';
      divider.textContent = title;
      resultsEl.appendChild(divider);
      for (const result of locations) {
        const item = document.createElement('div');
        item.className = 'search-result-item';
        item.dataset.locationKind = result.kind;
        item.dataset.locationProvider = result.provider || '';
        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);
      }
    }

    renderLocationLane('UK location', ukResults);
    renderLocationLane('Global location', globalResults);
    resultsEl.style.display = 'block';
  }

  async function executeSearch(input, resultsEl, includeGlobal = false) {
    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, postcodes, addresses and places…</div>';
    try {
      const [results, ukLocations, rawGlobalLocations] = await Promise.all([
        queryOfficialRepd(query, serial),
        queryUkGazetteer(query),
        includeGlobal ? queryGlobalGazetteer(query) : Promise.resolve([])
      ]);
      if (serial !== activeQuerySerial) return;
      const globalLocations = dedupeGlobalLocations(ukLocations, rawGlobalLocations);
      renderResults(results, resultsEl, ukLocations, globalLocations);
    } 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.5 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');
  }

  function suppliedArrivalFields(params, repdRef) {
    const numberOrNull = (name) => {
      const raw = params.get(name);
      if (raw === null || String(raw).trim() === '') return null;
      const value = Number(raw);
      return Number.isFinite(value) ? value : null;
    };
    const textOrNull = (name) => {
      const value = String(params.get(name) || '').trim();
      return value || null;
    };
    return Object.freeze({
      repd_ref: repdRef,
      name: textOrNull('project'),
      technology: textOrNull('technology'),
      capacity_mw: numberOrNull('capacity_mw'),
      longitude: numberOrNull('longitude'),
      latitude: numberOrNull('latitude'),
      // Pipeline News 0144 does not send status. Retain it only when another
      // authorised producer explicitly supplies it; never present it as an
      // official active-register value.
      supplied_status: textOrNull('status')
    });
  }

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

    const arrival = suppliedArrivalFields(params, repdRef);
    let coordinator = null;
    let ownerEpoch = null;
    try {
      invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
      coordinator = arrivalCoordinator();
      invariant(coordinator, 'shared arrival coordinator unavailable');
      if (Number.isInteger(expectedOwnerEpoch)) {
        if (!coordinator.arrivalGate.isCurrent(expectedOwnerEpoch)) return;
        ownerEpoch = expectedOwnerEpoch;
      } else {
        ownerEpoch = coordinator.claimPendingArrival(window.location.search);
      }
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'RECEIVING',
        resolved: false, mapped: false,
        identity_source: 'ACTIVE_REGISTER_PENDING'
      };
      const stillOwned = () => coordinator.arrivalGate.isCurrent(ownerEpoch);
      const querySerial = ++activeQuerySerial;
      input.value = repdRef;
      const results = await queryOfficialRepd(repdRef, querySerial, stillOwned);
      if (!stillOwned() || querySerial !== activeQuerySerial) return;
      const exact = results.find(result => String(result.repd_ref) === repdRef);
      if (!exact) {
        // A successful query with no exact row is evidence about this active
        // snapshot, not a network failure and not evidence that the supplied
        // project never existed. Keep the link's point and identity separate.
        renderResults(results, resultsEl);
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'not-in-active-register';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          status: 'NOT_IN_ACTIVE_REGISTER',
          resolved: false,
          mapped: false,
          supplied_point_usable: hasSafeMapPoint(arrival),
          identity_source: 'ARRIVAL_LINK',
          official_active_register_match: false,
          statement: 'No exact identity in the active-register snapshot; supplied arrival fields retained.'
        };
        return;
      }
      renderResults(results, resultsEl);
      await waitForCapturedMap();
      if (!stillOwned()) return;
      if (!selectResult(exact, { deepLinkEpoch: ownerEpoch })) return;
      if (!stillOwned()) return;
      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',
        owner_epoch: ownerEpoch,
        repd_ref: repdRef,
        resolved: true,
        mapped: true,
        name: exact.name,
        postcode: exact.postcode,
        longitude: exact.longitude,
        latitude: exact.latitude,
        technology: exact.technology,
        capacity_mw: exact.capacity_mw,
        status_value: exact.status,
        identity_source: 'OFFICIAL_ACTIVE_REGISTER',
        official_active_register_match: true
      };
    } catch (error) {
      if (coordinator && Number.isInteger(ownerEpoch)
          && !coordinator.arrivalGate.isCurrent(ownerEpoch)) return;
      const message = String(error?.message || error);
      state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'FAILED',
        resolved: false, mapped: false, message,
        identity_source: 'ACTIVE_REGISTER_CHECK_FAILED'
      };
      document.body.dataset.gridatlasRepdDeepLink = 'failed';
      console.error('[V9 EXACT REPD DEEP LINK]', error);
    }
  }

  async function retryExactRepdDeepLink(input, resultsEl, ownerEpoch) {
    const coordinator = arrivalCoordinator();
    invariant(coordinator, 'shared arrival coordinator unavailable for retry');
    invariant(Number.isInteger(ownerEpoch), 'identity retry requires one shared owner epoch');
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    state.identity_retry_count += 1;
    await resetOfficialRuntime();
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    return receiveExactRepdDeepLink(input, resultsEl, ownerEpoch);
  }

  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, address, postcode or place...');
    input.setAttribute('aria-label', 'Search project, address, postcode or place');

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

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

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

    state.retry_exact_deep_link = (ownerEpoch) =>
      retryExactRepdDeepLink(input, resultsEl, ownerEpoch);
    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 });
})();