GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Unified Native Gazetteer and 4 more files

A JavaScript file in the atlas folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

700 lines of JavaScript from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 593 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. Unified Destination Contract transform · gridatlas / atlas/modules/unified-destination-contract.mjs lines 1–76
  2. Unified Destination Unlimited transform · gridatlas / atlas/modules/unified-destination-unlimited.mjs lines 1–76
  3. Unified Layer Catalogue transform · gridatlas / atlas/modules/unified-layer-catalogue.mjs lines 1–91
  4. Unified Layer Search UI interaction · gridatlas / atlas/modules/unified-layer-search-ui.mjs lines 1–105
  5. Unified Native Gazetteer geodesy · gridatlas / atlas/modules/unified-native-gazetteer.js lines 1–352

Unified Destination Contract

A JavaScript module in the atlas folder of GridAtlas that creates destination gate (`createDestinationGate`) and validates destination leg (`validateDestinationLeg`). It creates destination gate (`createDestinationGate`) and validates destination leg (`validateDestinationLeg`).

transformgridatlas / atlas/modules/unified-destination-contract.mjs · lines 1–76 of 76 · pattern validDestinationCoordinate (shared by 2 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including createDestinationGate, invalidate, onInput, beginRequest, publish.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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.
Downstream impact
Used directly by 1 file: Unified Destination Contract Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
GridAtlas V9.201 — synchronous search ownership; no DOM, GPS or network side effects.
Why it matters
Checked by Unified Destination Contract Test.
Application
gridatlas · atlas/modules · JavaScript module
Uses
none found
Used by
imported by Unified Destination Contract Test (import), mentioned in Standalone (comment link)
Produces
createDestinationGate, validDestinationCoordinate, validateDestinationLeg
Defines here
createDestinationGate, invalidate, onInput, beginRequest, publish, transfer, validDestinationCoordinate, validateDestinationLeg
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/unified-destination-contract.mjs:1-76 · blob ba1cc05ae1b2bbd9e53881dabd504fe1c64e0183 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// GridAtlas V9.201 — synchronous search ownership; no DOM, GPS or network side effects.
export function createDestinationGate() {
  let epoch = 0;
  let input = null;
  let request = null;
  let accepted = new Map();
  function invalidate() {
    epoch += 1;
    input = null;
    request = null;
    accepted = new Map();
  }
  function onInput(query) {
    invalidate();
    if (typeof query !== 'string') throw new TypeError('query must be a string');
    input = Object.freeze({epoch, query: query.trim()});
    return input;
  }
  function beginRequest(ticket) {
    if (ticket !== input || !input?.query) return null;
    accepted = new Map();
    request = Object.freeze({epoch, query: input.query});
    return request;
  }
  function publish(ticket, results) {
    if (!request || ticket !== request) return null;
    if (!Array.isArray(results)) throw new TypeError('results must be an array');
    const next = new Map();
    for (const item of results) {
      if (typeof item?.id !== 'string' || !item.id.trim() || next.has(item.id))
        throw new TypeError('result identities must be nonempty and unique');
      if (!validDestinationCoordinate(item.at)) throw new RangeError('invalid destination coordinate');
      const handle = Object.freeze({
        id: item.id,
        at: Object.freeze([...item.at]),
        label: typeof item.label === 'string' ? item.label : item.id,
        provider: typeof item.provider === 'string' ? item.provider : null,
        precision: typeof item.precision === 'string' ? item.precision : null,
        epoch
      });
      next.set(item.id, handle);
    }
    accepted = next;
    return Object.freeze([...next.values()]);
  }
  // Caller must supply a synchronous, atomic controller operation. A rejected
  // operation must not mutate navigation state or GPS ownership.
  function transfer(handle, commit) {
    if (!handle || accepted.get(handle.id) !== handle)
      return Object.freeze({ok:false, reason:'stale-result'});
    if (typeof commit !== 'function') throw new TypeError('commit must be a function');
    const outcome = commit(handle);
    if (outcome?.then) throw new TypeError('destination commit must be synchronous');
    if (outcome?.ok !== true) return Object.freeze({ok:false, reason:outcome?.reason || 'destination-rejected'});
    invalidate();
    return Object.freeze({ok:true});
  }
  return Object.freeze({onInput, beginRequest, publish, invalidate, transfer});
}

export function validDestinationCoordinate(at) {
  return Array.isArray(at) && at.length === 2 &&
    at.every(n => typeof n === 'number' && Number.isFinite(n)) &&
    Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90;
}

export function validateDestinationLeg(previous, destination, distanceKm) {
  if (!validDestinationCoordinate(destination) ||
      (previous !== null && !validDestinationCoordinate(previous)))
    return Object.freeze({ok:false, reason:'invalid-coordinate'});
  if (previous === null) return Object.freeze({ok:true, km:null});
  if (typeof distanceKm !== 'function') throw new TypeError('distanceKm must be a function');
  const km = distanceKm(previous, destination);
  if (!Number.isFinite(km) || km < 0) return Object.freeze({ok:false, reason:'invalid-distance'});
  return Object.freeze(km <= 2 ? {ok:true, km} : {ok:false, reason:'over-limit', km});
}

Unified Destination Unlimited

A JavaScript module in the atlas folder of GridAtlas that creates destination gate (`createDestinationGate`) and validates destination leg (`validateDestinationLeg`). It creates destination gate (`createDestinationGate`) and validates destination leg (`validateDestinationLeg`).

Set aside from the main view: 97% of its lines are the same as atlas/modules/unified-destination-contract.mjs (gridatlas), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Unified Destination Contract; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9683 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/unified-destination-contract.mjs:1-76 ba1cc05ae1b2bbd9e53881dabd504fe1c64e0183
  • sha256 4c8aea582d96b27a9b930f2760446d5c88a577b0d92df0c027fcf1fdcd3268f2
  • target sha256 66884efa77ab4760d3ce0816fe6258ec36315da45da957195bc5d52799adfabd
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformgridatlas / atlas/modules/unified-destination-unlimited.mjs · lines 1–76 of 76 · Not reached from any entry point (candidate for review) · pattern validDestinationCoordinate (shared by 2 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including createDestinationGate, invalidate, onInput, beginRequest, publish.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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.
Downstream impact
Used directly by 1 file: Distance Dock Proof (gridatlas).
What it achieves
GridAtlas V9.201 — synchronous search ownership; no DOM, GPS or network side effects.
Why it matters
Imported by Distance Dock Proof.
Application
gridatlas · atlas/modules · JavaScript module
Uses
none found
Used by
imported by Distance Dock Proof (import)
Produces
createDestinationGate, validDestinationCoordinate, validateDestinationLeg
Defines here
createDestinationGate, invalidate, onInput, beginRequest, publish, transfer, validDestinationCoordinate, validateDestinationLeg
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/unified-destination-unlimited.mjs:1-76 · blob a3b2f55fa6a682e79597849e5a5eaa99a152ff7e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// GridAtlas V9.201 — synchronous search ownership; no DOM, GPS or network side effects.
export function createDestinationGate() {
  let epoch = 0;
  let input = null;
  let request = null;
  let accepted = new Map();
  function invalidate() {
    epoch += 1;
    input = null;
    request = null;
    accepted = new Map();
  }
  function onInput(query) {
    invalidate();
    if (typeof query !== 'string') throw new TypeError('query must be a string');
    input = Object.freeze({epoch, query: query.trim()});
    return input;
  }
  function beginRequest(ticket) {
    if (ticket !== input || !input?.query) return null;
    accepted = new Map();
    request = Object.freeze({epoch, query: input.query});
    return request;
  }
  function publish(ticket, results) {
    if (!request || ticket !== request) return null;
    if (!Array.isArray(results)) throw new TypeError('results must be an array');
    const next = new Map();
    for (const item of results) {
      if (typeof item?.id !== 'string' || !item.id.trim() || next.has(item.id))
        throw new TypeError('result identities must be nonempty and unique');
      if (!validDestinationCoordinate(item.at)) throw new RangeError('invalid destination coordinate');
      const handle = Object.freeze({
        id: item.id,
        at: Object.freeze([...item.at]),
        label: typeof item.label === 'string' ? item.label : item.id,
        provider: typeof item.provider === 'string' ? item.provider : null,
        precision: typeof item.precision === 'string' ? item.precision : null,
        epoch
      });
      next.set(item.id, handle);
    }
    accepted = next;
    return Object.freeze([...next.values()]);
  }
  // Caller must supply a synchronous, atomic controller operation. A rejected
  // operation must not mutate navigation state or GPS ownership.
  function transfer(handle, commit) {
    if (!handle || accepted.get(handle.id) !== handle)
      return Object.freeze({ok:false, reason:'stale-result'});
    if (typeof commit !== 'function') throw new TypeError('commit must be a function');
    const outcome = commit(handle);
    if (outcome?.then) throw new TypeError('destination commit must be synchronous');
    if (outcome?.ok !== true) return Object.freeze({ok:false, reason:outcome?.reason || 'destination-rejected'});
    invalidate();
    return Object.freeze({ok:true});
  }
  return Object.freeze({onInput, beginRequest, publish, invalidate, transfer});
}

export function validDestinationCoordinate(at) {
  return Array.isArray(at) && at.length === 2 &&
    at.every(n => typeof n === 'number' && Number.isFinite(n)) &&
    Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90;
}

export function validateDestinationLeg(previous, destination, distanceKm) {
  if (!validDestinationCoordinate(destination) ||
      (previous !== null && !validDestinationCoordinate(previous)))
    return Object.freeze({ok:false, reason:'invalid-coordinate'});
  if (previous === null) return Object.freeze({ok:true, km:null});
  if (typeof distanceKm !== 'function') throw new TypeError('distanceKm must be a function');
  const km = distanceKm(previous, destination);
  if (!Number.isFinite(km) || km < 0) return Object.freeze({ok:false, reason:'invalid-distance'});
  return Object.freeze({ok:true, km});
}

Unified Layer Catalogue

A JavaScript module in the atlas folder of GridAtlas that works with canonical voltage (`canonicalVoltage`) (units: kV). It normalizes layer text (`normalizeLayerText`) and creates layer catalogue (`createLayerCatalogue`).

transformgridatlas / atlas/modules/unified-layer-catalogue.mjs · lines 1–91 of 91 · pattern register (shared by 59 files)

What it does
It calculates its inputs. Defines 7 functions or classes, including canonicalVoltage, normalizeLayerText, createLayerCatalogue, cmp, register.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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.
Downstream impact
Used directly by 3 files: Unified Layer Search UI (gridatlas); Unified Catalogue Independent Test (gridatlas); Unified Layer Catalogue Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Metadata only: no DOM, network or map ownership.
Why it matters
Imported by Unified Layer Search UI. Checked by 2 tests, including Unified Catalogue Independent Test.
Application
gridatlas · atlas/modules · JavaScript module
Uses
none found
Used by
imported by Unified Layer Search UI (import), imported by Unified Catalogue Independent Test (dynamic import), imported by Unified Layer Catalogue Test (import)
Produces
normalizeLayerText, createLayerCatalogue
Defines here
canonicalVoltage, normalizeLayerText, createLayerCatalogue, cmp, register, remove, search
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/unified-layer-catalogue.mjs:1-91 · blob 7d3d43a4b0c1b88dcb0240e996693ea53d6bf468 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Metadata only: no DOM, network or map ownership. Agent 2 supplies native registry and external selectedIds.
// Shift decimal digits exactly, avoiding binary rounding in V-to-kV conversion.
function canonicalVoltage(quantity, unit) {
  const [whole, fraction = ''] = quantity.split('.');
  const digits = whole + fraction;
  const point = whole.length - (unit === 'v' ? 3 : 0);
  const padded = point <= 0 ? '0.' + '0'.repeat(-point) + digits
    : point >= digits.length ? digits + '0'.repeat(point - digits.length)
    : digits.slice(0, point) + '.' + digits.slice(point);
  const [integer, decimal = ''] = padded.split('.');
  const tail = decimal.replace(/0+$/, '');
  return (integer.replace(/^0+(?=\d)/, '') || '0') + (tail ? '.' + tail : '') + 'kv';
}
export function normalizeLayerText(value) {
  return String(value ?? '').normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase()
    .replace(/(?<!\d)\.(?!\d)|(?<=\d)\.(?!\d)/g, ' ')
    .replace(/(\d+(?:\.\d+)?|\.\d+)\s*(?:[-‐‑‒–—]\s*)?(kv|v)\b/g, (_, n, unit) => canonicalVoltage(n, unit))
    .replace(/(?<!\d)\.|\.(?!\d)/g, ' ')
    .replace(/[^\p{L}\p{N}.]+/gu, ' ').trim().replace(/\s+/g, ' ');
}

export function createLayerCatalogue(initial = []) {
  const records = new Map();
  let sorted = [];
  const cmp = (a,b) => a < b ? -1 : a > b ? 1 : 0;
  function register(entries) {
    if (!Array.isArray(entries)) throw new TypeError('Expected metadata array');
    const batch = new Map();
    for (const raw of entries) {
      if (!raw || typeof raw.id !== 'string' || !raw.id.trim() || typeof raw.label !== 'string' || !raw.label.trim()) throw new TypeError('Stable id and label required');
      const id = raw.id.trim();
      if (batch.has(id)) throw new Error(`Duplicate layer id: ${id}`);
      const aliases = raw.aliases ?? [];
      if (!Array.isArray(aliases) || aliases.some(a => typeof a !== 'string')) throw new TypeError('Aliases must be strings');
      const record = {id, label:raw.label.trim(), aliases:Object.freeze([...aliases])};
      for (const key of ['category','technology','voltage','region','operator','availability']) {
        if (raw[key] != null) {
          if (typeof raw[key] !== 'string') throw new TypeError(`${key} must be text`);
          record[key] = raw[key];
        }
      }
      Object.freeze(record);
      const name = normalizeLayerText(record.label), machine = normalizeLayerText(id);
      const terms = [name,machine,...aliases.map(normalizeLayerText),...['category','technology','voltage','region','operator','availability'].map(k => normalizeLayerText(record[k]))].filter(Boolean);
      const tokens = [...new Set(terms.join(' ').split(' '))];
      batch.set(id,{record,name,machine,terms,tokens});
    }
    for (const [id,entry] of batch) records.set(id,entry);
    sorted = [...records.values()].sort((a,b)=>cmp(a.name,b.name)||cmp(a.record.id,b.record.id));
    return records.size;
  }
  function remove(id) {
    if (!records.delete(id)) return false;
    sorted = sorted.filter(x=>x.record.id!==id);
    return true;
  }
  function search(query = '', {page=1,pageSize=100,selectedOnly=false,selectedIds=new Set()} = {}) {
    if (!Number.isSafeInteger(page)||page<1||!Number.isSafeInteger(pageSize)||pageSize<1||pageSize>100) throw new RangeError('page >= 1 and pageSize 1..100 required');
    if (!Number.isSafeInteger((page-1)*pageSize)) throw new RangeError('Page offset too large');
    if (!selectedIds || typeof selectedIds.has !== 'function') throw new TypeError('Read-only selectedIds.has required');
    const q = normalizeLayerText(query), parts = q.split(' ').filter(Boolean);
    // Complete voltage tokens are constraints, not fuzzy text.
    const voltages = parts.filter(p => /^\d+(?:\.\d+)?kv$/.test(p));
    const buckets = [[],[],[],[],[]];
    for (const entry of sorted) {
      if (selectedOnly && !selectedIds.has(entry.record.id)) continue;
      if (!voltages.every(v => entry.tokens.includes(v))) continue;
      let rank = 4;
      if (q) {
        if (entry.machine===q || entry.name===q) rank=0;
        else if (entry.name.startsWith(q)||entry.machine.startsWith(q)) rank=1;
        else if (entry.terms.some(t=>t===q)) rank=2;
        else if (parts.every(p=>entry.tokens.some(t=>t.startsWith(p)))) rank=3;
        else if (!parts.every(p=>entry.tokens.some(t=>t.includes(p)))) continue;
      }
      buckets[rank].push(entry.record);
    }
    const total = buckets.reduce((n,b)=>n+b.length,0);
    let skip = (page-1)*pageSize;
    const rows = [];
    for (const bucket of buckets) {
      if (skip>=bucket.length) {skip-=bucket.length;continue;}
      rows.push(...bucket.slice(skip,skip+pageSize-rows.length));
      skip=0;
      if (rows.length===pageSize) break;
    }
    return {total,page,pageSize,rows};
  }
  register(initial);
  return Object.freeze({register,remove,search,get size(){return records.size;}});
}

Unified Layer Search UI

A JavaScript module in the atlas folder of GridAtlas that resets page (`resetPage`).

interactiongridatlas / atlas/modules/unified-layer-search-ui.mjs · lines 1–105 of 105 · Not reached from any entry point (candidate for review) · pattern inventory (shared by 18 files)

What it does
It draws its content. Defines 10 functions or classes, including tidy, installUnifiedLayerSearch, inventory, make, button. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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.
What it achieves
It resets page (`resetPage`) and is built from the tidy step (`tidy`) and the install unified layer search helper (`installUnifiedLayerSearch`). G201-06: additive search projection over the existing native Grid menu. It responds to click, input and change events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · JavaScript module
Uses
Unified Layer Catalogue (import)
Used by
none found
Produces
installUnifiedLayerSearch
Defines here
tidy, installUnifiedLayerSearch, inventory, make, button, clearProjection, render, resetPage, refresh, onNativeChange
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/unified-layer-search-ui.mjs:1-105 · blob 658a739e4705749d9f16c4a64fc8d406842aa1ea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// G201-06: additive search projection over the existing native Grid menu.
// No layer is hydrated here. Native proxy inputs retain their original listeners.
import {createLayerCatalogue} from './unified-layer-catalogue.mjs';
const installations = new WeakMap();
const selector = 'input[type="checkbox"][data-layer-id],input[type="checkbox"][data-pn-layer]';
const proxySelector = '.gm-layer[data-gridatlas-layer-key]';
const tidy = text => String(text || '').replace(/\s+/g,' ').trim();
export function installUnifiedLayerSearch(doc = document) {
  if (installations.has(doc)) return installations.get(doc);
  const host = doc.getElementById('scada-ui-container');
  const panel = doc.querySelector('.gm-panel-grid');
  const head = panel?.querySelector('.gm-panel-head');
  const body = panel?.querySelector('.gm-panel-body');
  if (!host || !head || !body) return null;
  function inventory() {
    const native = new Map(), proxies = new Map(), entries = [];
    for (const input of host.querySelectorAll(selector)) {
      const engine = input.getAttribute('data-layer-id');
      const key = engine ? 'engine:'+engine : 'pipeline:'+input.getAttribute('data-pn-layer');
      const label = input.closest('label');
      const span = label?.querySelector('[data-base-label],[data-pn-label],span');
      const stable = tidy(span?.getAttribute('data-base-label') || span?.textContent || label?.textContent || key);
      const name = stable.replace(/\s+\[(?:WAIT|LOAD|OK|FAIL)[^\]]*\]\s*$/i,'');
      if (native.has(key) || !name) return null;
      native.set(key,input);
      const category = tidy(input.closest('.key-group')?.querySelector('.key-title')?.textContent);
      const aliases = /(^|[:_\-])ukpn($|[:_\-])/i.test(key) ? ['UKPN','UK Power Networks'] : [];
      entries.push({id:key,label:name,category,aliases});
    }
    for (const row of body.querySelectorAll(proxySelector)) {
      const key = row.getAttribute('data-gridatlas-layer-key');
      if (!native.has(key) || proxies.has(key)) return null;
      proxies.set(key,row);
    }
    if (!native.size || native.size !== proxies.size) return null;
    return {native,proxies,entries};
  }
  let data = inventory();
  if (!data) return null; // never conceal an incomplete native menu
  let index = createLayerCatalogue(data.entries), page=1, disposed=false;
  const ui=doc.createElement('section'); ui.id='unified-layer-search';
  ui.setAttribute('aria-label','Search infrastructure layers');
  const make=(tag,text)=>{const e=doc.createElement(tag); if(text)e.textContent=text; return e;};
  const query=make('input'); query.type='search'; query.placeholder='Search layers'; query.setAttribute('aria-label','Search layers');
  const button=text=>{const e=make('button',text);e.type='button';return e;};
  const clear=button('Clear'), prev=button('Previous'), next=button('Next');
  const selected=make('input'); selected.type='checkbox';
  const selectedLabel=make('label'); selectedLabel.append(selected,doc.createTextNode(' Selected only'));
  const count=make('span'); count.setAttribute('role','status'); count.setAttribute('aria-live','polite');
  const line=make('div'); line.className='unified-layer-search-line'; line.append(query,clear);
  const controls=make('div'); controls.className='unified-layer-search-line'; controls.append(selectedLabel,count);
  const pager=make('div'); pager.className='unified-layer-search-line'; pager.append(prev,next);
  ui.append(line,controls,pager);
  // Search controls are not native menu commands. Keep the existing Grid
  // panel open on Clear, filter, and pagination; native proxy clicks are untouched.
  ui.addEventListener('click',event=>event.stopPropagation());
  const style=make('style'); style.textContent=`
    #unified-layer-search{padding:4px 0;color:inherit;font:inherit}
    #unified-layer-search .unified-layer-search-line{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
    #unified-layer-search input[type=search]{min-width:0;flex:1;min-height:44px;font-size:16px;color:inherit;background:#071418;border:1px solid #4a8b96;padding:4px 8px}
    #unified-layer-search button{width:auto;min-height:44px;flex:0 0 auto}
    #unified-layer-search label{min-height:44px;display:flex;align-items:center;cursor:pointer}
    #unified-layer-search [role=status]{flex:1;text-align:right}
    .gm-panel-grid .gm-layer[data-unified-layer-filtered]{display:none!important}
    #unified-layer-search [hidden]{display:none!important}`;
  function clearProjection() {for(const row of data.proxies.values()) row.removeAttribute('data-unified-layer-filtered');}
  function render() {
    if (disposed) return null;
    const start=doc.defaultView.performance.now();
    const selectedIds=new Set([...data.native].filter(([,input])=>input.checked).map(([key])=>key));
    const options={page,pageSize:100,selectedOnly:selected.checked,selectedIds};
    let result=index.search(query.value,options);
    const pages=Math.max(1,Math.ceil(result.total/100));
    if(page>pages){page=pages;result=index.search(query.value,{...options,page});}
    const visible=new Set(result.rows.map(r=>r.id));
    for(const [key,row] of data.proxies) row.toggleAttribute('data-unified-layer-filtered',!visible.has(key));
    if(doc.activeElement?.closest?.('[data-unified-layer-filtered]'))query.focus();
    count.textContent=result.total+' of '+index.size+' layers';
    prev.disabled=page===1;next.disabled=page===pages;pager.hidden=pages===1;
    ui.dataset.page=String(page);ui.dataset.total=String(result.total);
    ui.dataset.searchRenderMs=String(doc.defaultView.performance.now()-start);
    return result;
  }
  function resetPage(){page=1;render();}
  function refresh(){
    const latest=inventory();
    if(!latest){clearProjection();ui.hidden=true;return null;}
    clearProjection();data=latest;index=createLayerCatalogue(data.entries);ui.hidden=false;return render();
  }
  query.addEventListener('input',resetPage);
  clear.addEventListener('click',()=>{query.value='';resetPage();query.focus();});
  selected.addEventListener('change',resetPage);
  prev.addEventListener('click',()=>{page=Math.max(1,page-1);render();});
  next.addEventListener('click',()=>{page++;render();});
  function onNativeChange(){if(!panel.hidden)render();}
  doc.addEventListener('change',onNativeChange);
  const observer=new doc.defaultView.MutationObserver(()=>{if(!panel.hidden)refresh();});
  observer.observe(panel,{attributes:true,attributeFilter:['hidden']});
  head.append(ui); (doc.head||doc.documentElement).append(style);
  const api=Object.freeze({render,refresh,dispose(){
    if(disposed)return;disposed=true;observer.disconnect();doc.removeEventListener('change',onNativeChange);
    clearProjection();ui.remove();style.remove();installations.delete(doc);
  }});
  installations.set(doc,api); render(); return api;
}

Unified Native Gazetteer

A JavaScript file in the atlas folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

Set aside from the main view: 91% of its lines are the same as atlas/cartridges/202611180026-place-global-search-v9-5.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Place Global Search V9 5; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9074 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-place-global-search-v9-5.js:1-931 c3ef9b6b82b3e983feb93015b168fed3d11322b9
  • sha256 d34e4ea12d80c28eb8adb0075154eac9581ae7b189f416997b3deab5d48377c8
  • target sha256 575721ea584187c2b9b857408a3e6136879d7f6876f1e6d7a0b925051124a49c
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/unified-native-gazetteer.js · lines 1–352 of 973 · Not reached from any entry point (candidate for review) · pattern loadDerivedCoordinates (shared by 4 files)

What it does
It maps REPD projects, offshore coordinates, postcodes and the REPD register. Defines 44 functions or classes, including invalidateSearch, invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink. 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 'atlas'): 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: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202611132345.parquet; JSON file repd_v9_manifest_202611132345.json; JSON file offshore-coordinates.json; DuckDB queries. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). V9.201 candidate derivative; original native gazetteer remains byte-identical. It responds to gridatlas, click and input events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · 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
none found
Produces
invalidateSearch, invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime
Defines here
invalidateSearch, invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise, runtime, resetOfficialRuntime, installMapCapture, buildWhere, buildScore, rowObject, queryOfficialRepd, hasSafeMapPoint, loadDerivedCoordinates
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/unified-native-gazetteer.js:1-352 · blob b6991e464f618824f20edd55ed8060d8abdc1bea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* V9.201 candidate derivative; original 202611132345 native gazetteer remains byte-identical. */

(() => {
  'use strict';

  const PARQUET_URL = 'https://ventusltd.github.io/gridatlas/data/repd_projects_202611132345.parquet';
  const PARQUET_SHA256 = 'cc9b7f046fe24497114c9cc356d7d0e54830890722af90a83c397eab1056d789';
  const MANIFEST_URL = 'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202611132345.json';
  const MANIFEST_SHA256 = 'b90bda5acaa2ff2a3bddd0267a6814ea599c915f0284920f4d354c8c5447f3fb';
  const GEOCODER_BASE = 'https://api.postcodes.io';
  const GLOBAL_GEOCODER_URL = 'https://nominatim.openstreetmap.org/search';
  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 SOURCE_GENERATION = '202609040229';
  const RUNTIME_GENERATION = String(
    document.documentElement?.dataset?.gridatlasGeneration || SOURCE_GENERATION
  );

  const state = {
    schema: 'gridatlas.v9-place-global-search.v5',
    generation: RUNTIME_GENERATION,
    source_generation: SOURCE_GENERATION,
    version: 'v9.106',
    geocoder: GEOCODER_BASE,
    global_geocoder: GLOBAL_GEOCODER_URL,
    geocoder_providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],
    geocoder_requests: 0,
    global_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,
    identity_retry_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;
  let destinationGate = null;
  void import(new URL('../../../atlas/modules/unified-destination-contract.mjs', location.href)).then(module => {destinationGate=module.createDestinationGate();}).catch(error => console.error('SatNav destination integration unavailable',error));
  function invalidateSearch() {
    ++activeQuerySerial; clearTimeout(debounceTimer); debounceTimer=null; destinationGate?.invalidate();
  }

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

  function arrivalCoordinator() {
    const measure = window.__GRIDATLAS_NEON_LINKS__?.measure;
    if (!measure?.arrivalGate || typeof measure.claimPendingArrival !== 'function'
        || typeof measure.invalidatePendingArrival !== 'function') return null;
    return measure;
  }

  function markDeepLinkCancelled(reason, epoch = null) {
    const prior = state.deep_link;
    if (!prior?.repd_ref || prior.status === 'ABSENT'
        || prior.status === 'IDLE' || prior.status === 'CANCELLED') return;
    state.deep_link = {
      ...prior,
      status: 'CANCELLED',
      resolved: false,
      mapped: false,
      cancelled_by: String(reason || 'user-navigation'),
      cancelled_epoch: Number.isInteger(epoch) ? epoch : null
    };
    document.body.dataset.gridatlasRepdDeepLink = 'cancelled';
  }

  function invalidatePendingDeepLink(reason) {
    const coordinator = arrivalCoordinator();
    if (!coordinator) {
      markDeepLinkCancelled(reason);
      return null;
    }
    const epoch = coordinator.invalidatePendingArrival(reason);
    /* The shared owner dispatches this synchronously. Keep the direct call as
       a fail-soft fallback for a DOM shim without CustomEvent. */
    markDeepLinkCancelled(reason, epoch);
    return epoch;
  }

  window.addEventListener('gridatlas:arrival-invalidated', (event) => {
    markDeepLinkCancelled(event?.detail?.reason, event?.detail?.epoch);
  });

  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 === '202611132345', 'REPD generation mismatch');
      invariant(manifest?.closure?.rows === 11329, 'REPD row closure mismatch');
      invariant(manifest?.closure?.postcodes === 9765, 'REPD postcode closure mismatch');
      invariant(manifest?.closure?.addresses === 11319, 'REPD address closure mismatch');
      invariant(manifest?.parquet?.sha256 === PARQUET_SHA256, 'REPD Parquet identity mismatch');
      return manifest;
    })();
    return manifestPromise;
  }

  /* ONE DuckDB runtime for the whole page. Duplicated verbatim from
     202608301825-streaming-parquet-bridge-v9-5.js, deliberately: cartridges
     are composed as independent scripts with no shared module loader, so
     there is nothing to import from. The CONTRACT is the window key and the
     shape it holds, not this function, and whichever cartridge asks first
     builds it - so neither depends on composition order.

     Why it exists: this lane and the bridge each built their own runtime.
     Measured live at an iPhone 13 profile, 202609041500: duckdb-eh.wasm
     fetched twice at 5.92 MB, 11.84 MB of a 12.81 MB arrival, and two
     WebAssembly heaps alive at once on a device that caps per-tab memory. */
  function sharedDuckDBRuntime(moduleUrl) {
    const KEY = '__GRIDATLAS_DUCKDB_RUNTIME__';
    const held = window[KEY];
    if (held && held.module_url === moduleUrl) return held.promise;
    const promise = (async () => {
      const duckdb = await import(moduleUrl);
      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);
      }
      return { duckdb, database, worker };
    })();
    window[KEY] = { module_url: moduleUrl, promise, claimed_at_ms: performance.now() };
    promise.catch(() => {
      if (window[KEY] && window[KEY].promise === promise) delete window[KEY];
    });
    return promise;
  }

  async function runtime() {
    runtimePromise ||= (async () => {
      await verifyManifest();
      const shared = await sharedDuckDBRuntime(DUCKDB_MODULE);
      /* A connection each. DuckDB supports many connections on one database,
         which is what makes the sharing safe: the lanes stay independent at
         the level they actually need to be. */
      const connection = await shared.database.connect();
      return { connection, database: shared.database, worker: shared.worker, shared: true };
    })();
    return runtimePromise;
  }

  async function resetOfficialRuntime() {
    const previous = runtimePromise;
    runtimePromise = null;
    manifestPromise = null;
    if (!previous) return;
    try {
      const active = await previous;
      try { await active.connection?.close?.(); } catch (_) { /* best effort */ }
      /* A SHARED database is never terminated here. Retry owns this lane's
         connection, not the page's runtime: the streaming-parquet bridge is
         serving every V8 data layer from the same database, and tearing it
         down to retry a search would take the map's data plane with it.
         Closing the connection is the whole of what this lane owns.
         The `shared` flag is set by runtime() above; the terminate path is
         kept for a runtime this lane built alone, so behaviour is unchanged
         if the broker is ever absent. */
      if (!active.shared) {
        try { await active.database?.terminate?.(); } catch (_) { /* best effort */ }
        try { active.worker?.terminate?.(); } catch (_) { /* best effort */ }
      }
    } catch (_) {
      // A rejected cached promise is exactly what retry is replacing.
    }
  }

  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, stillOwned = 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, TRY_CAST(repd_ref AS BIGINT) ASC NULLS LAST, capacity_mw DESC NULLS LAST, name ASC
      LIMIT 25
    `;
    const table = await connection.query(sql);
    if (serial !== null && serial !== activeQuerySerial) return [];
    if (stillOwned && !stillOwned()) 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;
  }

  /* Coordinates the register does not carry, derived from Crown Estate lease
     geometry by tools/offshore/reconcile_offshore_coordinates.py and published
     beside the Atlas. Loaded once, lazily, and never treated as authoritative:
     it locates a project the register has already named.

     Loaded over XMLHttpRequest rather than fetch, deliberately. The composer
     executes cartridges from a blob: origin, where fetch resolves 200 and then
     throws TypeError reading the body; XHR against the same absolute URL
     returns the file. Measured, in this Atlas, twice. */
  let derivedIndex = null;
  function loadDerivedCoordinates() {
    if (derivedIndex) return derivedIndex;
    derivedIndex = new Promise((resolve) => {
      try {
        const url = new URL('../../data/offshore-coordinates.json', document.baseURI).href;
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onload = () => {
          if (xhr.status < 200 || xhr.status >= 300) { resolve({}); return; }
          try {
            const payload = JSON.parse(xhr.responseText);
            const index = {};
            for (const row of payload.coordinates || []) {
              if (row && row.repd_ref && Number.isFinite(row.longitude) && Number.isFinite(row.latitude)) {
                index[String(row.repd_ref)] = row;
              }
            }
            resolve(index);
          } catch (_) { resolve({}); }
        };
        // An absent or unreachable file is not an error here. It means no