GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / testcode/202609051152/atlas/cartridges

Streaming Parquet Bridge V9 5 and 1 more file

A JavaScript file in the cartridges folder of GlobalGrid2050 that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using SHA-256 from the data-GridAtlas repository.

641 lines of JavaScript from globalgrid2050, in 2 files. Topic: Maps, GIS and field navigation. Section 503 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. Streaming Parquet Bridge V9 5 interaction · globalgrid2050 / testcode/202609051152/atlas/cartridges/202609041945-streaming-parquet-bridge-v9-5.js lines 1–328
  2. Atlas Receiver V9 7 ingest · globalgrid2050 / testcode/202609051152/pipeline/scripts/core/atlas-receiver-v9-7.js lines 1–313

Streaming Parquet Bridge V9 5

A JavaScript file in the cartridges folder of GlobalGrid2050 that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using SHA-256 from the data-GridAtlas repository.

Set aside from the main view: 95% of its lines are the same as atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Streaming Parquet Bridge V9 5; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9476 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js:1-336 480000111fe12306a4d250fa9b246ab5de22f865
  • sha256 4a6b594f7705bc4d7d62cbe69d2e40726d12f9a759896430cfe5eb00d830d23e
  • target sha256 fa1c05e0f0cef8425c60b1746e77c2fe4919b352d11b9de70323cf4a70b70bdc
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / testcode/202609051152/atlas/cartridges/202609041945-streaming-parquet-bridge-v9-5.js · lines 1–328 of 328 · version 2026-09-04 19:45 · Not reached from any entry point (candidate for review) · pattern scheduleRuntimePrewarm (shared by 3 files)

What it does
It loads grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 16 functions or classes, including invariant, requestPath, mapReadyKey, legacyStem, sha256Hex. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: data source: data-gridatlas data; GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson.
What it achieves
It maps ready key (`mapReadyKey`), gets manifest (`getManifest`) and gets runtime (`getRuntime`). Defines `invariant`, `requestPath`, `mapReadyKey` and 13 more. It responds to abort events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609051152/atlas/cartridges · script
Uses
Data GridAtlas — Data GridAtlas Page (estate URL)
Used by
mentioned in Standalone (comment link)
Produces
invariant, requestPath, mapReadyKey, legacyStem, sha256Hex, getManifest, sharedDuckDBRuntime, promise, getRuntime, scheduleRuntimePrewarm, start, resolvePartition
Defines here
invariant, requestPath, mapReadyKey, legacyStem, sha256Hex, getManifest, sharedDuckDBRuntime, promise, getRuntime, scheduleRuntimePrewarm, start, resolvePartition, rowObject, queryOnDemand, task, abort
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/atlas/cartridges/202609041945-streaming-parquet-bridge-v9-5.js:1-328 · blob b1148fb58db8a623fe561247d45729c5e6be8e9c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, storage · domain stage: experimental · users: none · canonical: duplicate_candidate
(() => {
  'use strict';

  const GENERATION = '202609041945';
  const DATA_BASE = 'https://ventusltd.github.io/data-gridatlas/202608291237-data-gridatlas/';
  const MANIFEST_URL = `${DATA_BASE}data/manifest.json`;
  const MANIFEST_SHA256 = '3246dbdaa042ae8352ec9b7128cb6c2fe65e4f1aba0534302510661828df2526';
  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';
  const CRITICAL_RELEASE_PATH = 'data/grid_400kv.geojson';
  const CRITICAL_RUNTIME_URL = '../cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson';
  const MAP_READY_PATHS = new Set([
    'data/grid_400kv.geojson',
    'data/grid_275kv.geojson',
    'data/grid_220kv.geojson',
    'data/grid_132kv.geojson',
    'data/grid_66kv.geojson',
    'data/grid_substations.geojson',
    'data/power_plants.geojson',
    'data/industrial_offtakers.geojson',
    'data/datacentres.geojson',
    'data/airports.geojson',
    'data/railways.geojson'
  ]);

  const nativeFetch = window.fetch.bind(window);
  const sourceCache = new Map();
  let manifestPromise = null;
  let runtimePromise = null;

  const state = {
    schema: 'gridatlas.maplibre-worker-fetch-bridge.v1',
    generation: GENERATION,
    data_release: '202608291237-data-gridatlas',
    architecture: {
      map_ready_same_origin_geojson: true,
      critical_400kv_maplibre_worker_source: true,
      critical_400kv_window_prefetch: false,
      critical_400kv_main_thread_json_parse: false,
      preload_browser_duckdb: 'AFTER_CRITICAL_SOURCE',
      serialized_preload_queue: false,
      topology_pre_snapped: true,
      analytical_search_duckdb_retained: true
    },
    critical_source: {
      release_copy_path: CRITICAL_RELEASE_PATH,
      runtime_url: CRITICAL_RUNTIME_URL,
      cache_identity: 'CONTENT_ADDRESSED_STABLE_URL',
      delivery: 'MAPLIBRE_WORKER_DIRECT_URL',
      eager_window_prefetch: false,
      window_fetch_hits: 0
    },
    map_ready_requests: 0,
    map_ready_paths: [...MAP_READY_PATHS],
    parquet_requests: 0,
    duckdb_runtime_started: false,
    duckdb_runtime_started_at_ms: null,
    duckdb_runtime_shared: false,
    intercepted_on_demand: 0,
    loaded_on_demand: {},
    failures: [],
    streamed_responses: 0,
    released_payloads: 0,
    stream_failures: [],
    runtime_prewarm: { requested: false, started: false, completed: false, failed: null }
  };
  window.__GRIDATLAS_MAP_READY__ = state;

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

  function requestPath(input) {
    try {
      const raw = typeof input === 'string' ? input : input?.url;
      return new URL(raw, window.location.href).pathname;
    } catch {
      return '';
    }
  }

  function mapReadyKey(pathname) {
    const marker = '/data/';
    const index = pathname.toLowerCase().lastIndexOf(marker);
    if (index < 0) return '';
    return `data/${decodeURIComponent(pathname.slice(index + marker.length)).toLowerCase()}`;
  }

  function legacyStem(pathname) {
    const name = decodeURIComponent(pathname.split('/').pop() || '').toLowerCase();
    if (name === 'repd_master.json') return 'repd_master_v8_oracle';
    if (name === 'heavy_emitters_uk.json') return 'heavy_emitters_uk';
    if (name.endsWith('.geojson')) return name.slice(0, -8);
    return '';
  }

  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 getManifest() {
    manifestPromise ||= (async () => {
      const response = await nativeFetch(MANIFEST_URL, { cache: 'no-store' });
      invariant(response.ok, `manifest HTTP ${response.status}`);
      const bytes = await response.arrayBuffer();
      invariant(await sha256Hex(bytes) === MANIFEST_SHA256, 'data manifest SHA-256 mismatch');
      const manifest = JSON.parse(new TextDecoder().decode(bytes));
      invariant(manifest?.schema === 'data-gridatlas.v8-transplant-manifest.v1', 'data manifest schema mismatch');
      invariant(manifest?.closure?.sources === 56, 'V8 source closure mismatch');
      invariant(manifest?.closure?.layers === 60, 'V8 layer closure mismatch');
      invariant(manifest?.closure?.features === 541282, 'V8 feature closure mismatch');
      return manifest;
    })();
    return manifestPromise;
  }

  /* ONE DuckDB runtime for the whole page.
     ----------------------------------------------------------------------
     This cartridge and the uk-gazetteer-flyto search lane each built their
     own. Both were correctly memoised internally, so neither was a fault by
     itself; nothing coordinated between them because they are separate
     cartridges by design. Measured on the live page at an iPhone 13 profile,
     202609041500: duckdb-eh.wasm fetched TWICE, 5.92 MB each, 11.84 MB of a
     12.81 MB arrival - and, which matters more on a phone, two WebAssembly
     heaps and two workers alive at once. iOS Safari caps per-tab memory hard
     where a desktop does not.

     The broker below is deliberately duplicated verbatim into the search
     lane rather than imported. Cartridges are composed as independent
     scripts with no shared module loader between them, so there is nothing
     to import from; the CONTRACT is the window key and the shape it holds,
     not this function. Whichever cartridge asks first builds the runtime and
     the other awaits the same promise, so it is order-independent - which
     matters because composition order is a manifest decision, not a
     guarantee this code should rely on.

     A rejected runtime is dropped rather than cached, so a retry rebuilds
     instead of inheriting a dead promise. And note what is NOT here: nobody
     terminates a shared database. The search lane's retry closes only its
     own connection - see the note there. */
  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 };
    })();
    /* Assigned synchronously, before the first await inside the IIFE can
       yield, so two callers in the same task cannot both build one. */
    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 getRuntime() {
    runtimePromise ||= (async () => {
      state.duckdb_runtime_started = true;
      state.duckdb_runtime_started_at_ms = performance.now();
      const shared = await sharedDuckDBRuntime(DUCKDB_MODULE);
      state.duckdb_runtime_shared = true;
      return { database: shared.database, worker: shared.worker };
    })();
    return runtimePromise;
  }

  function scheduleRuntimePrewarm() {
    state.runtime_prewarm.requested = true;
    let checks = 0;
    const poll = setInterval(() => {
      checks += 1;
      let criticalReady = false;
      try {
        const map = window.__GRIDATLAS_V9_MAP__;
        criticalReady = Boolean(map && map.getSource('src-400') && map.isSourceLoaded('src-400'));
      } catch {}
      if (!criticalReady && checks < 240) return;
      clearInterval(poll);
      const start = () => {
        state.runtime_prewarm.started = true;
        getRuntime().then(() => {
          state.runtime_prewarm.completed = true;
        }).catch(error => {
          state.runtime_prewarm.failed = String(error?.message || error);
          state.failures.push({ pathname: 'duckdb-runtime-prewarm', message: state.runtime_prewarm.failed });
        });
      };
      if (typeof requestIdleCallback === 'function') requestIdleCallback(start, { timeout: 2000 });
      else setTimeout(start, 0);
    }, 250);
  }

  queueMicrotask(scheduleRuntimePrewarm);

  async function resolvePartition(pathname) {
    const stem = legacyStem(pathname);
    invariant(stem, `unsupported V8 data path: ${pathname}`);
    const alias = stem === 'uk_metros_trams' ? 'uk_metros_trams_root' : stem;
    const expected = `partitions/${alias}.parquet`.toLowerCase();
    const manifest = await getManifest();
    const artifact = (manifest.artifacts || []).find(
      item => String(item.path || '').toLowerCase() === expected
    );
    invariant(artifact, `no V9 Parquet partition for V8 source ${pathname}`);
    invariant(/^[a-f0-9]{64}$/.test(artifact.sha256 || ''), `bad partition digest for ${artifact.path}`);
    return artifact;
  }

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

  async function queryOnDemand(pathname) {
    if (sourceCache.has(pathname)) return sourceCache.get(pathname);
    const task = (async () => {
      const artifact = await resolvePartition(pathname);
      const parquetUrl = `${DATA_BASE}data/${artifact.path}`;
      const { database } = await getRuntime();
      const connection = await database.connect();
      state.parquet_requests += 1;
      try {
        const escaped = parquetUrl.replaceAll("'", "''");
        const table = await connection.query(`
          SELECT source_id, feature_index, feature_id, geometry_json, properties_json
          FROM read_parquet('${escaped}')
          ORDER BY feature_index
        `);
        const features = table.toArray().map(raw => {
          const row = rowObject(raw);
          return {
            type: 'Feature',
            id: row.feature_id || `${row.source_id}:${row.feature_index}`,
            geometry: JSON.parse(String(row.geometry_json)),
            properties: JSON.parse(String(row.properties_json || '{}'))
          };
        });
        state.loaded_on_demand[pathname] = {
          parquet: artifact.path,
          rows: features.length,
          sha256: artifact.sha256
        };
        return { type: 'FeatureCollection', features };
      } finally {
        await connection.close();
      }
    })();
    sourceCache.set(pathname, task);
    try {
      return await task;
    } catch (error) {
      sourceCache.delete(pathname);
      state.failures.push({ pathname, message: String(error?.message || error) });
      throw error;
    }
  }

  window.fetch = async function gridAtlasMaplibreWorkerFetch(input, init = undefined) {
    const pathname = requestPath(input);
    const readyKey = mapReadyKey(pathname);

    if (MAP_READY_PATHS.has(readyKey)) {
      state.map_ready_requests += 1;
      if (readyKey === CRITICAL_RELEASE_PATH) state.critical_source.window_fetch_hits += 1;
      return nativeFetch(input, { ...(init || {}), cache: 'force-cache' });
    }

    if (!legacyStem(pathname)) return nativeFetch(input, init);

    state.intercepted_on_demand += 1;
    if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');

    // Return response headers before DuckDB imports, downloads, queries and serialises the body.
    // This preserves the native fetch contract expected by the V8 engine: its 15 s timer protects
    // response establishment, while response.json() may continue consuming a streamed body.
    state.streamed_responses += 1;
    const encoder = new TextEncoder();
    let bodyController = null;
    let aborted = false;
    const abort = () => {
      aborted = true;
      try { bodyController?.error(new DOMException('Aborted', 'AbortError')); } catch {}
    };
    init?.signal?.addEventListener('abort', abort, { once: true });
    const body = new ReadableStream({
      start(controller) {
        bodyController = controller;
        queryOnDemand(pathname).then(payload => {
          if (aborted || init?.signal?.aborted) return abort();
          const serialised = JSON.stringify(payload);
          sourceCache.delete(pathname);
          state.released_payloads += 1;
          controller.enqueue(encoder.encode(serialised));
          controller.close();
        }).catch(error => {
          sourceCache.delete(pathname);
          state.stream_failures.push({ pathname, message: String(error?.message || error) });
          try { controller.error(error); } catch {}
        });
      },
      cancel() { aborted = true; }
    });
    return new Response(body, {
      status: 200,
      headers: {
        'Content-Type': 'application/geo+json; charset=utf-8',
        'Cache-Control': 'private, max-age=3600',
        'X-GridAtlas-Data-Plane': 'V9-PARQUET-DUCKDB-STREAMED-RESPONSE'
      }
    });
  };
})();

Atlas Receiver V9 7

A JavaScript module in the core folder of GlobalGrid2050 that fetches receivers and the Renewable Energy Planning Database (REPD) register from the ventus-grid-engine and GridAtlas repositories.

ingestglobalgrid2050 / testcode/202609051152/pipeline/scripts/core/atlas-receiver-v9-7.js · lines 1–313 of 313 · version 2026-09-05 11:52 · pattern verifyAtlasReceiver (shared by 2 files)

What it does
It fetches receivers and the REPD register. Defines 10 functions or classes, including stripTrailingSlash, isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register, 132kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: gridatlas data; JSON file receivers.json. Voltage levels named: 132kV.
Downstream impact
Used directly by 7 files: Canonical Project Table (globalgrid2050); Projects V9 1 (globalgrid2050); Projects V9 2 (globalgrid2050); Projects V9 3 (globalgrid2050); and 3 more. Reached from 196 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
It verifies atlas receiver v9 (`verifyAtlasReceiverV9_7`), loads atlas receiver v9 (`loadAtlasReceiverV9_7`) and builds atlas deep link v9 (`buildAtlasDeepLinkV9_7`). On the MAP button in this app was measured pointing at the V8 overlay the engine now publishes as retired. Its code works with 132 kV and 500 MW.
Why it matters
Imported by 7 files, including Canonical Project Table, Projects V9 1 and Projects V9 2.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts/core · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
imported by Canonical Project Table (import), imported by Projects V9 1 (import), imported by Projects V9 2 (import), imported by Projects V9 3 (import), imported by Projects V9 4 (import), imported by Projects V9 5 (import), imported by Projects V9 5 1 (import), mentioned in Standalone (comment link)
Produces
isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7, verifyAtlasReceiverV9_7, loadAtlasReceiverV9_7, atlasCentresOnRepdPointV9_7, buildAtlasDeepLinkV9_7, atlasUnavailableReasonV9_7
Defines here
stripTrailingSlash, isRetiredReceiverV9_7, atlasReceiverV9_7, atlasReceiverFailureV9_7, primeAtlasReceiverV9_7, verifyAtlasReceiverV9_7, loadAtlasReceiverV9_7, atlasCentresOnRepdPointV9_7, buildAtlasDeepLinkV9_7, atlasUnavailableReasonV9_7
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/core/atlas-receiver-v9-7.js:1-313 · blob 57823989d87737a95a86e9a06f8b1c18e66564ec · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: experimental · users: none · canonical: production_core
/* ── WHICH RECEIVER A MAP LINK IS BUILT AGAINST ──────────────────────────────
 *
 * On 2026-09-05 the MAP button in this app was measured pointing at the V8
 * overlay the engine now publishes as retired — a page that still serves, so
 * nothing 404'd and no link checker ever went red, but which carries zero
 * engine cartridges and no current.json. Measured the same day: that shell has
 * 0 cartridge references and 0 current.json references; the canonical shell has
 * 20 and 3. An arrival there is silently inert. Vikram hit it on Longfield
 * (REPD 8162) and reported "grid engine didnt compute or fire via map button".
 * It was never going to.
 *
 * Driven live for this change, same project, same parameters:
 *
 *   retired receiver    zero __GRIDATLAS_* globals, no module list, no nearest()
 *                       function, and the page never even names Longfield
 *   canonical receiver  14 engine modules including networkTopology,
 *                       electricalDistance, ratingEnvelope and corridorEstimate;
 *                       the arrival popup reads "Longfield solar 500 MW ...
 *                       CM3 3AS · Essex REPD 8162 · awaiting construction", and
 *                       the engine's own nearest() answers BRAINTREE at 9.44 km,
 *                       400/132 kV, NGET, 4 transformers, 4 circuits
 *
 * WHERE THE ROUTE COMES FROM.
 * ventus-grid-engine/deeplink/receivers.json names the canonical route, the
 * retired ones, and why. This module carries a compiled copy of that document
 * and fetches the published one to verify it. The compiled copy is not a second
 * opinion: testcode/drivers/link-targets.mjs reads both and fails offline if
 * they disagree, so the engine still retires a receiver once, in the place that
 * knows, and this file cannot drift away from it unnoticed. See the long note
 * on COMPILED_CONTRACT below for why the earlier no-copy design had to change.
 *
 * WHAT HAPPENS WHEN THE PUBLISHED DOCUMENT CANNOT BE READ.
 * The compiled contract stands and the links keep working. There is still no
 * fallback to a RETIRED route — that is what shipped a dead button for weeks,
 * and a live contract naming this route retired withdraws the links on the
 * spot. The difference is between falling back to a route the engine has
 * disowned, which must never happen, and standing on the engine's own last
 * published answer while a handshake is slow, which is the only sane thing to
 * do on a phone.
 *
 * ORDER NO LONGER MATTERS, AND THAT IS THE POINT.
 * The previous design made the first table paint wait on a cross-origin fetch,
 * because callers are synchronous — a table row renders one link at a time — so
 * the route had to be known before the first render. Measured 2026-09-05: no row
 * of 7,680 could appear until a request to ventusltd.github.io completed, on a
 * page whose <tbody> starts empty. buildAtlasDeepLinkV9_7() now answers from
 * module import, before any network exists, and verifyAtlasReceiverV9_7() runs
 * beside the payload with nothing waiting on it.
 */

const RECEIVERS_URL = "https://ventusltd.github.io/ventus-grid-engine/deeplink/receivers.json";
const RECEIVERS_SCHEMA = "ventus.grid-engine.deeplink-receivers.v1";

/* The parameters the deep-link contract names, in its own order. `project` and
 * `capacity_mw` are deliberately NOT sent: the contract's PARAMS does not carry
 * them, and the canonical receiver resolves the project's identity, name,
 * capacity, postcode and status from the REPD reference on its own — verified
 * live on REPD 8162 and on REPD 13429, which has no REPD coordinate at all. */
const CONTRACT_PARAMS = Object.freeze(["repd_ref", "technology", "latitude", "longitude", "zoom"]);

/* How long a stalled socket may hold the verification open. Nothing waits on
 * it any more, so this is only about not leaking a request for ever; iOS
 * Safari's own ceiling is of the order of 60-75 s, which is not a bound. */
const VERIFY_TIMEOUT_MS = 5000;

/* ── THE COMPILED-IN CONTRACT, AND WHY IT IS NOT THE OLD MISTAKE ────────────
 *
 * The version of this module shipped at 202609050353 held no route at all and
 * built no link until a cross-origin fetch to ventusltd.github.io resolved.
 * Measured 2026-09-05 that fetch sat inside the same Promise.all that gates the
 * first table paint, so not one of 7,680 rows could appear until a request to a
 * SECOND ORIGIN completed — a full DNS + TCP + TLS handshake before the first
 * row, on a cold mobile radio, on a page with an empty <tbody> and no
 * placeholder. 59 ms on a wired link, which is why it was invisible on desktop.
 * And it had no fallback: had that request failed, every row would have
 * rendered NO MAP plus an explanatory paragraph. 7,680 dead cells.
 *
 * WHAT MAKES A DEFAULT SAFE THIS TIME. The original defect was seven copies of
 * a route in seven plugins, none of which the engine could correct. This is one
 * copy, in one module, of the engine's own published document — and it is
 * PINNED to that document by a gate that reads both:
 *
 *     testcode/drivers/link-targets.mjs
 *       "the compiled-in receiver contract matches the engine's published one"
 *
 * If ventus-grid-engine/deeplink/receivers.json ever names a different
 * canonical route, or retires this one, that driver goes red offline, in the
 * estate's own instrument, before anything ships. A hard-coded route the estate
 * cannot notice drifting is the fault; a hard-coded route the estate checks
 * every run is a cache. The difference is the gate, and the gate exists.
 *
 * AND THE LIVE DOCUMENT STILL WINS. verifyAtlasReceiverV9_7() fetches it after
 * the table has painted. If it names a different canonical route, that route
 * replaces this one and the MAP cells re-render. If it names THIS route as
 * retired, the links are withdrawn and the cells say so — the engine keeps the
 * power to retire a receiver once, in the place that knows. What it no longer
 * has is the power to leave the page with no links at all because a handshake
 * was slow. */
const COMPILED_CONTRACT = Object.freeze({
  schema: RECEIVERS_SCHEMA,
  canonical: Object.freeze({
    id: "gridatlas-v9",
    route: "https://ventusltd.github.io/gridatlas/atlas/",
    carries_engine: true,
  }),
  retired: Object.freeze([Object.freeze({
    id: "repd-grid-atlas-v8",
    route: "https://globalgrid2050.com/repd_grid_atlasv8/",
    carries_engine: false,
  })]),
  compiled_from: "ventus-grid-engine/deeplink/receivers.json",
  compiled_utc: "202609051100",
});

let canonicalRoute = "";
let retiredRoutes = [];
let failureReason = "the deep-link contract has not been read yet";
/* WHY a prime failed, not just that it did. "unusable" means the document could
   not be understood - a schema this build does not know, or a contract that
   contradicts itself. "withdrawn" means a document this build DID understand
   instructed it that there is no receiver to link to. Only the second is the
   engine exercising its power to retire a receiver; the first is a document
   this page is in no position to act on, and acting on it is how a schema bump
   in a file on another origin silently stripped every MAP link from the page. */
let failureKind = "unusable";
let pending = null;
let verification = null;

const stripTrailingSlash = (route) => String(route || "").replace(/\/+$/u, "");

export function isRetiredReceiverV9_7(route) {
  return retiredRoutes.includes(stripTrailingSlash(route));
}

export function atlasReceiverV9_7() {
  return canonicalRoute;
}

export function atlasReceiverFailureV9_7() {
  return canonicalRoute ? "" : failureReason;
}

/* Exposed so a test can drive every branch of this module without a network —
 * a check that can only run online is a check that quietly stops running. It
 * takes the contract DOCUMENT, never a bare route, so there is still no way to
 * name a receiver by hand and have this module believe it. */
export function primeAtlasReceiverV9_7(document_) {
  canonicalRoute = "";
  retiredRoutes = [];
  failureReason = "";
  pending = null;
  if (!document_ || document_.schema !== RECEIVERS_SCHEMA) {
    failureReason = `deep-link contract schema is ${document_ && document_.schema}, expected ${RECEIVERS_SCHEMA}`;
    failureKind = "unusable";
    return "";
  }
  const route = document_.canonical && document_.canonical.route;
  if (!route) {
    failureReason = "the deep-link contract names no canonical receiver";
    failureKind = "withdrawn";
    return "";
  }
  if (document_.canonical.carries_engine !== true) {
    failureReason = "the deep-link contract's canonical receiver does not claim to carry the engine";
    failureKind = "withdrawn";
    return "";
  }
  retiredRoutes = (Array.isArray(document_.retired) ? document_.retired : [])
    .map((entry) => stripTrailingSlash(entry && entry.route))
    .filter(Boolean);
  if (isRetiredReceiverV9_7(route)) {
    // The contract contradicting itself must fail loudly, not resolve itself.
    retiredRoutes = [];
    failureReason = "the deep-link contract names its own canonical receiver as retired";
    failureKind = "unusable";
    return "";
  }
  canonicalRoute = route;
  failureKind = "";
  return canonicalRoute;
}

/* The receiver is known at import, from the compiled-in contract above, before
 * any network exists. Every branch of primeAtlasReceiverV9_7() still applies to
 * it — a compiled contract that failed its own schema or named its canonical
 * route as retired would leave canonicalRoute empty here exactly as a fetched
 * one would, and the drift gate would already have gone red. */
primeAtlasReceiverV9_7(COMPILED_CONTRACT);

/* VERIFICATION, NOT PRECONDITION. Nothing awaits this before painting. It is
 * fired beside the project payload, resolves whenever it resolves, and reports
 * whether the page's links have to change. `changed` is the only reason to
 * re-render, and on a correct estate it is always false — the compiled contract
 * is pinned to the published one by a gate, so a re-render is the signal that
 * something drifted, not a routine cost every reader pays.
 *
 * It cannot make things worse: a failure, a timeout, a malformed document or a
 * schema bump all leave the compiled-in route standing and record why. The one
 * thing it CAN do is withdraw the links, and only on the engine's explicit
 * instruction — a document this build understood that names no usable canonical
 * receiver.
 *
 * That paragraph was false when it was written. Until 2026-09-05 every prime
 * failure took the same branch, so a schema this build did not recognise was
 * treated as an instruction and stripped the links, returning verified:true.
 * The difference is now carried by failureKind, and `withdrawn` reports it
 * separately from `verified` so a caller cannot read "the document was read"
 * as "the links are correct". */
export async function verifyAtlasReceiverV9_7() {
  if (verification) return verification;
  const before = canonicalRoute;
  verification = (async () => {
    try {
      /* `cache: "no-store"` was here. It discarded the response and refused the
         HTTP cache, so every load made a fresh cross-origin round trip for a
         document the server itself publishes as cacheable for ten minutes
         (Cache-Control: max-age=600, Access-Control-Allow-Origin: *).
         AbortSignal.timeout bounds a stalled socket, which nothing did. */
      const response = await fetch(RECEIVERS_URL, {
        mode: "cors",
        signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const live = await response.json();
      const route = primeAtlasReceiverV9_7(live);
      if (!route) {
        const reason = atlasReceiverFailureV9_7();
        if (failureKind === "unusable") {
          /* The document arrived but this build cannot read it — an unknown
             schema, or a contract that names its own canonical route retired.
             That is not an instruction, it is a document we are in no position
             to act on, and the comment above has always said so. Measured on
             2026-09-05: it did the opposite. A schema bump on a file hosted on
             a SECOND ORIGIN removed every MAP link from this page and reported
             verified:true while doing it. Stand on the compiled contract, which
             is pinned to the published one by a gate, and say why. */
          primeAtlasReceiverV9_7(COMPILED_CONTRACT);
          return { route: canonicalRoute, changed: false, verified: false, withdrawn: false, reason };
        }
        /* A document this build DID understand, instructing that there is no
           receiver to link to. This is the engine retiring a receiver once, in
           the place that knows, and it is the whole reason the contract is read
           at all. verified:true says the document was read and honoured; it is
           `withdrawn` that says the links are gone, so the two are no longer
           conflated in one flag. */
        return { route: "", changed: before !== "", verified: true, withdrawn: true, reason };
      }
      return { route, changed: route !== before, verified: true, withdrawn: false, reason: "" };
    } catch (error) {
      /* Keep the compiled-in contract. It is pinned to the published one by
         testcode/drivers/link-targets.mjs, so standing on it is standing on the
         last verified reading of the engine's own document, not on a guess. */
      primeAtlasReceiverV9_7(COMPILED_CONTRACT);
      return {
        route: canonicalRoute,
        changed: false,
        verified: false,
        withdrawn: false,
        reason: `the deep-link contract at ${RECEIVERS_URL} could not be read (${(error && error.message) || error}); the compiled-in contract of ${COMPILED_CONTRACT.compiled_utc} still applies`,
      };
    }
  })();
  return verification;
}

/* Kept so nothing that imported the old name breaks, and so a caller that only
 * wants the route still gets one. It no longer gates anything: the route is
 * already there when this is called. */
export async function loadAtlasReceiverV9_7() {
  if (!pending) pending = verifyAtlasReceiverV9_7().then((result) => result.route);
  return pending;
}

/* True when this record carries a REPD coordinate the map can centre on. The
 * 28 records that do not are still linkable: the receiver resolves them from
 * the REPD reference and centres on its own geometry, which was measured on
 * REPD 13429 (Ossian) — it arrives and names the project. They are labelled
 * rather than denied a button, because a button that silently does nothing is
 * exactly what hid this defect. */
export function atlasCentresOnRepdPointV9_7(project) {
  return Boolean(project) && project.geometry_status === "valid";
}

export function buildAtlasDeepLinkV9_7(project) {
  if (!canonicalRoute) return "";
  if (!project || project.repd_ref === undefined || project.repd_ref === null || project.repd_ref === "") return "";
  const values = {
    repd_ref: project.repd_ref,
    technology: project.technology,
  };
  if (atlasCentresOnRepdPointV9_7(project)) {
    values.latitude = project.latitude;
    values.longitude = project.longitude;
    values.zoom = "12";
  }
  const url = new URL(canonicalRoute);
  for (const key of CONTRACT_PARAMS) {
    const value = values[key];
    if (value === undefined || value === null || value === "") continue;
    url.searchParams.set(key, String(value));
  }
  return url.href;
}

/* What the cell says when there is no link. One sentence, in the row, because
 * a title attribute is unreachable on a phone and unreachable is how this hid. */
export function atlasUnavailableReasonV9_7(project) {
  if (!canonicalRoute) return `MAP unavailable: ${atlasReceiverFailureV9_7()}`;
  if (!project || project.repd_ref === undefined || project.repd_ref === null || project.repd_ref === "") {
    return "MAP unavailable: this record carries no REPD reference to resolve";
  }
  return "";
}