GLOBALGRID2050 / EXPLORE CODE

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

Streaming Parquet Bridge 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.

449 lines of JavaScript from globalgrid2050, in 2 files. Topic: Maps, GIS and field navigation. Section 505 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. UK Gazetteer Flyto energy-data · globalgrid2050 / testcode/202609051214/atlas/cartridges/202609051214-uk-gazetteer-flyto.js lines 701–816
  2. Streaming Parquet Bridge interaction · globalgrid2050 / testcode/202609051344/atlas/cartridges/202609051344-streaming-parquet-bridge.js lines 1–333

UK Gazetteer Flyto

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

Set aside from the main view: 100% 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). 99% of lines shared with UK Gazetteer Flyto; read that one first. All set-aside files, with reasons. Nothing was deleted.

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

energy-dataglobalgrid2050 / testcode/202609051214/atlas/cartridges/202609051214-uk-gazetteer-flyto.js · lines 701–816 of 816 · version 2026-09-05 12:14 (continued from section 504) · Not reached from any entry point (candidate for review) · pattern queryPipelineIdentity (shared by 2 files)

What it does
It maps REPD projects, postcodes and the REPD register. Defines 40 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 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: 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.
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). Place-global-search-v9-5. It responds to gridatlas, click and input events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609051214/atlas/cartridges · 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
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
Defines here
retryExactRepdDeepLink, bindSearch
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/202609051214/atlas/cartridges/202609051214-uk-gazetteer-flyto.js:701-816 · blob 7f0923854d5296b3ab9855372dd56637ddc86f1d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: duplicate_candidate
        };
        return;
      }
      renderResults(results, resultsEl);
      if (!hasSafeMapPoint(exact)) {
        state.deep_link = {...exact, owner_epoch:ownerEpoch, status:'IDENTIFIED_NO_GEOMETRY', resolved:true, mapped:false, official_active_register_match:false};
        document.body.dataset.gridatlasRepdRef=repdRef;
        document.body.dataset.gridatlasRepdDeepLink='identified-no-geometry';
        resultsEl.innerHTML = '<h3>' + escapeHtml(exact.name) + '</h3><p>REPD ' + escapeHtml(repdRef) + ' / ' + escapeHtml(String(exact.capacity_mw)) + ' MW</p><p>Location unavailable: this Pipeline REPD snapshot supplies no coordinates. No map pin or grid-distance calculation can be shown.</p>';
        Object.assign(resultsEl.style,{display:'block',position:'fixed',top:'128px',left:'12px',right:'12px',width:'auto',maxWidth:'420px',maxHeight:'60vh',overflow:'auto',zIndex:'6000',padding:'16px',background:'#08151c',color:'#e2f8ff',boxSizing:'border-box'});
        return;
      }
      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: exact.identity_source || 'OFFICIAL_ACTIVE_REGISTER',
        official_active_register_match: !exact.identity_source
      };
    } 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 });
})();

Streaming Parquet Bridge

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: 93% 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). 93% 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.9336 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js:1-336 480000111fe12306a4d250fa9b246ab5de22f865
  • sha256 80ebac3061f634433554c6dc992b21a34405e5afd2a9b09f968086229b8d8b2c
  • target sha256 fa1c05e0f0cef8425c60b1746e77c2fe4919b352d11b9de70323cf4a70b70bdc
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / testcode/202609051344/atlas/cartridges/202609051344-streaming-parquet-bridge.js · lines 1–333 of 333 · version 2026-09-05 13:44 · 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/202609051344/atlas/cartridges · script
Uses
Data GridAtlas — Data GridAtlas Page (estate URL)
Used by
none found
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/202609051344/atlas/cartridges/202609051344-streaming-parquet-bridge.js:1-333 · blob 98b025e842d7a6856dcc7cc6aa2db6a1edcf3ada · 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);
    // A pinned 722 KB GeoJSON keeps industrial identities and works without
    // a second-origin Parquet/WASM round trip before a site can be selected.
    if (legacyStem(pathname) === 'heavy_emitters_uk') {
      return nativeFetch(new URL('./data/heavy_emitters_uk.json', location.href), {...(init || {}), cache:'force-cache'});
    }
    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'
      }
    });
  };
})();