In this section
- Build Payload ingest · pipelinenews / tools/intelligence/cartridges/table-locality-sort/build_payload.py lines 1–291
- Proof render · pipelinenews / tools/intelligence/cartridges/table-locality-sort/proof.mjs lines 1–409
Build Payload
A Python command-line tool in the table locality sort folder of PipelineNews that fetches the Renewable Energy Planning Database (REPD) register, postcodes and wind, using SHA-256 from postcodes.io.
ingestpipelinenews / tools/intelligence/cartridges/table-locality-sort/build_payload.py · lines 1–291 of 291 · Entry point
- What it does
- It fetches the REPD register, postcodes and wind. Defines 8 functions or classes, including norm_pc, post, get, one_line, town_from. Uses libraries argparse, csv, hashlib, io, json. Side effects: makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: the REPD register, postcodes, wind.
- Inputs & outputs
- In: data source: postcodes.io; CSV file repd.csv; JSON file 202608270055-8ab1807551bc-v8-fast-projects.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the norm pc helper (`norm_pc`), the post step (`post`) and the get step (`get`). Build the locality payload: town, postcode and planning authority per REPD ref. It accepts `--limit` and `--gen`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- pipelinenews · tools/intelligence/cartridges/table-locality-sort · Python CLI
- Uses
- argparse, csv, hashlib, io, json, os, re, sys
- Used by
- none found
- Produces
- norm_pc, post, get, one_line, town_from, looks_like_a_town, town_from_address, main
- Defines here
- norm_pc, post, get, one_line, town_from, looks_like_a_town, town_from_address, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/table-locality-sort/build_payload.py:1-291 · blob 782923811d839def13874a18115425f656813781 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Build the locality payload: town, postcode and planning authority per REPD ref.
WHERE EACH FIELD COMES FROM, AND WHY
------------------------------------
POSTCODE is an official REPD column ("Post Code"). It is copied, never derived.
Roughly a third of the register has none -- offshore wind has no postcode, and
that is a correct blank, not a gap to fill.
TOWN is not a REPD column. There is no town in the source. It is resolved from
the postcode through the ONS Postcode Directory (api.postcodes.io, the same
geocoder gridatlas already uses), preferring:
bua ONS Built-Up Area -- the named settlement. This is the town.
parish civil parish -- the right answer for a rural site with no BUA.
ward electoral ward -- Scotland has neither BUAs nor civil parishes in
ONSPD, so the ward is the most local official name available there.
and falling back, only when there is no postcode at all, to the last segment of
the REPD Address that is neither a postcode nor the project's own county. That
fallback is marked `derived` in the payload so the UI can say so. A town this
app cannot source is null. It is never guessed.
The lookup runs HERE, at build time, and is baked into the payload. The table
makes no network call.
python build_payload.py # writes data/{GEN}-locality.json
python build_payload.py --limit 200 # sample run
"""
import argparse
import csv
import hashlib
import io
import json
import os
import re
import sys
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
# cartridges/<name>/ -> cartridges -> intelligence -> tools -> pipelinenews
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
WORKSPACE = os.path.dirname(REPO)
REPD_CSV = os.path.join(WORKSPACE, "globalgrid2050", "repd.csv")
PROJECTS = os.path.join(
REPO, "releases", "202608311610-pipelinenews",
"data", "202608270055-8ab1807551bc-v8-fast-projects.json")
OUT = os.path.join(HERE, "data", "{GEN}-locality.json")
API = "https://api.postcodes.io/postcodes"
BATCH = 100
# A full UK postcode. REPD also carries bare outcodes ("TD14"), which the bulk
# endpoint cannot resolve -- those go to the outcode endpoint instead.
FULL_PC = re.compile(r"^[A-Z]{1,2}\d[A-Z\d]?\d[A-Z]{2}$", re.I)
OUTCODE = re.compile(r"^[A-Z]{1,2}\d[A-Z\d]?$", re.I)
# ONS writes the absence of a built-up area as a sentence, not as null.
NOT_A_PLACE = re.compile(r"non[- ]national park|^england\b|^wales\b|^scotland\b", re.I)
def norm_pc(raw):
s = (raw or "").strip().upper()
s = re.sub(r"\s+", " ", s)
if not s:
return ""
body = s.replace(" ", "")
if FULL_PC.match(body):
return body[:-3] + " " + body[-3:]
if OUTCODE.match(body):
return body
return ""
def post(url, payload):
req = urllib.request.Request(
url, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=45) as r:
return json.loads(r.read().decode("utf-8"))
def get(url):
with urllib.request.urlopen(url, timeout=45) as r:
return json.loads(r.read().decode("utf-8"))
def one_line(value):
"""Collapse a name onto one line.
REPD address lines are free text and some of them carry an embedded CRLF:
ref 3139 derives the town "North Lewis / Isle of Lewis" across a CRLF. A
two-line town is not a town, it does not cluster with anything, and it
renders as two lines inside one table cell.
"""
if not value:
return None
return re.sub(r"\s+", " ", value).strip() or None
def town_from(node):
"""Pick the settlement name out of an ONSPD record."""
for key in ("bua", "parish", "admin_ward"):
v = (node or {}).get(key)
# An outcode record answers with a LIST -- several parishes span one
# outcode, and a list of parishes is not a town. Only a scalar counts.
if isinstance(v, str) and v.strip() and not NOT_A_PLACE.search(v):
return one_line(v), "ward" if key == "admin_ward" else key
return None, None
# What a town name is NOT. REPD's Address is free text, and its last segment is
# frequently a whole site description rather than a place: "Lands east of
# Feystown Road Glenarm; extending between an area situated approximately 750m
# east of 54 Feystown Road ..." was being served as a TOWN, 237 characters
# wide, which is what forced the column open and left a gap on every other row.
#
# Scanning EARLIER segments instead was measured and is worse: it turns
# offshore sites into "Offshore" and "Greater Wash region", and it demotes
# Brettabister to Shetland. So the rule stays "last segment", and a last
# segment that does not look like a place name yields null.
NOT_A_TOWN = re.compile(
r"""(
\d # house number, road number, postcode fragment
| \b(land|lands|site|sites|field|fields|farmland|adjacent|approximately
|north|south|east|west|northeast|northwest|southeast|southwest
|junction|extending|between|situated|proposed|windfarm
|townlands?|nr|near|off|opposite|rear|former)\b
)""",
re.I | re.X)
TOWN_MAX = 32 # longest genuine value the rule keeps; the median town is 13
def looks_like_a_town(value):
return bool(value) and len(value) <= TOWN_MAX and not NOT_A_TOWN.search(value)
def town_from_address(address, county):
"""Last address segment, but only if it reads as a place name.
Measured over the 2,750 rows with no postcode to resolve: 1,587 yield a
town-shaped value and 1,163 yield null. A null is the honest answer for a
site whose address is a description -- offshore wind especially, where
there is no town to name.
"""
county = (county or "").strip().lower()
parts = [p.strip() for p in (address or "").split(",") if p.strip()]
for part in reversed(parts):
if norm_pc(part):
continue
if part.lower() == county:
continue
if len(part) < 3 or part.isdigit():
continue
candidate = one_line(part)
return candidate if looks_like_a_town(candidate) else None
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--gen", default="{GEN}")
a = ap.parse_args()
rows = list(csv.DictReader(io.open(REPD_CSV, encoding="cp1252", newline="")))
by_ref = {r["Ref ID"].strip(): r for r in rows}
print("REPD register: %d rows" % len(rows))
doc = json.loads(io.open(PROJECTS, encoding="utf-8").read())
fields = doc["fields"]
i_ref = fields.index("repd_ref")
i_county = fields.index("county")
counties = doc["dictionaries"]["county"]
wanted = []
for row in doc["rows"]:
ref = str(row[i_ref]).strip()
rec = by_ref.get(ref)
if not rec:
continue
ci = row[i_county]
county = counties[ci] if isinstance(ci, int) and 0 <= ci < len(counties) else ""
wanted.append((ref, rec, county))
if a.limit:
wanted = wanted[:a.limit]
print("app projects joined to the register: %d of %d"
% (len(wanted), len(doc["rows"])))
# ---- resolve every distinct postcode once ----------------------------
full, outs = set(), set()
for _ref, rec, _c in wanted:
pc = norm_pc(rec.get("Post Code"))
if not pc:
continue
(outs if OUTCODE.match(pc) else full).add(pc)
print("distinct postcodes: %d full, %d outcode-only" % (len(full), len(outs)))
resolved = {}
full = sorted(full)
for n in range(0, len(full), BATCH):
chunk = full[n:n + BATCH]
try:
res = post(API, {"postcodes": chunk})
except Exception as exc: # noqa: BLE001
print(" batch %d failed (%s) -- those postcodes stay unresolved"
% (n // BATCH, exc))
continue
for item in res.get("result", []):
if item.get("result"):
resolved[item["query"].upper()] = item["result"]
sys.stdout.write("\r resolved %d/%d" % (len(resolved), len(full)))
sys.stdout.flush()
time.sleep(0.15)
print("\r resolved %d/%d full postcodes " % (len(resolved), len(full)))
# Outcodes are deliberately NOT looked up. An outcode spans many parishes
# and built-up areas, so ONSPD answers with lists, and a list of parishes
# is not a town. Those rows keep their outcode and take the address-derived
# town instead, marked as derived.
print(" %d outcode-only postcodes kept as-is; town falls back to address"
% len(outs))
# ---- assemble --------------------------------------------------------
out = {}
stats = {"postcode": 0, "bua": 0, "parish": 0, "ward": 0, "derived": 0,
"none": 0, "authority": 0}
for ref, rec, county in wanted:
pc = norm_pc(rec.get("Post Code"))
town = source = None
if pc and pc in resolved:
town, source = town_from(resolved[pc])
if not town:
town = town_from_address(rec.get("Address"), county)
source = "derived" if town else None
authority = (rec.get("Planning Authority") or "").strip() or None
if pc:
stats["postcode"] += 1
if authority:
stats["authority"] += 1
stats[source or "none"] = stats.get(source or "none", 0) + 1
out[ref] = {
"town": town,
"town_source": source,
"postcode": pc or None,
"authority": authority,
}
payload = {
"schema": "pipelinenews.locality.v1",
"generation": a.gen,
"usage_context": "NON_COMMERCIAL_OPEN_SOURCE",
"sources": {
"postcode": "DESNZ Renewable Energy Planning Database, column "
"'Post Code', Open Government Licence v3.0. Copied, "
"not derived.",
"authority": "DESNZ REPD, column 'Planning Authority', OGL v3.0.",
"town": "Resolved at build time from the postcode via the ONS "
"Postcode Directory (api.postcodes.io): ONS Built-Up Area "
"where one exists, otherwise civil parish. Where the "
"register carries no postcode, the last segment of the "
"REPD Address is used, but only when it reads as a place "
"name rather than a site description -- marked "
"town_source='derived'. Never guessed; null where "
"unsourceable, which includes most offshore wind.",
},
"town_source_values": ["bua", "parish", "ward", "derived", None],
"counts": stats,
"projects": len(out),
"network_at_runtime": False,
"locality": out,
}
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
path = OUT.replace("{GEN}", a.gen) if a.gen != "{GEN}" else OUT
io.open(path, "w", encoding="utf-8", newline="").write(body)
digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
io.open(path + ".sha256", "w", encoding="utf-8", newline="").write(
digest + " " + os.path.basename(path) + "\n")
print("\nwrote %s (%d bytes)" % (os.path.basename(path), len(body.encode("utf-8"))))
for k in ("postcode", "authority", "bua", "parish", "ward", "derived", "none"):
print(" %-10s %6d" % (k, stats.get(k, 0)))
return 0
if __name__ == "__main__":
raise SystemExit(main())Proof
A JavaScript module in the table locality sort folder of PipelineNews that fetches postcodes and the Renewable Energy Planning Database (REPD) register.
renderpipelinenews / tools/intelligence/cartridges/table-locality-sort/proof.mjs · lines 1–409 of 453 · Not reached from any entry point (candidate for review) · pattern clickAndRead (shared by 2 files)
- What it does
- It fetches postcodes and the REPD register. Defines 13 functions or classes, including check, $, rowsOf, cellsOf, refOf. Uses libraries node:fs/promises, node:path, node:url, node:crypto, jsdom. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: JSON file 202608270055-8ab1807551bc-v8-fast-projects.json; command-line arguments.
- What it achieves
- It runs search (`runSearch`) and is built from the check step (`check`) and the rows of helper (`rowsOf`). Table-locality-sort render proof.
- Why it matters
- No other file in the estate was found to import it.
- Application
- pipelinenews · tools/intelligence/cartridges/table-locality-sort · JavaScript module
- Uses
- node:fs/promises, node:path, node:url, node:crypto, jsdom
- Used by
- none found
- Produces
- check, $, rowsOf, cellsOf, refOf, townOf, postcodeOf, countyOf, clickAndRead, expected, settle, runSearch
- Defines here
- check, $, rowsOf, cellsOf, refOf, townOf, postcodeOf, countyOf, clickAndRead, expected, settle, runSearch, townsOfRows
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/table-locality-sort/proof.mjs:1-409 · blob 98ded15d48c2376c0e2ce8a6ac90ca90cdde7f44 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* table-locality-sort render proof.
*
* This cartridge does not add a panel. It changes the project table itself --
* two new columns and four new sortable headings -- so the only proof worth
* anything is booting the whole app against the real release and reading the
* table it produces.
*
* It re-derives every expected answer from the payloads independently rather
* than asking the app what it thinks. A sort assertion that compares the app's
* output to the app's own comparator proves nothing.
*
* Usage:
* node proof.mjs <path-to-release-dir> <generation>
*
* It is NOT a browser: it proves the code runs, the columns carry the right
* values, and every heading reorders the rows correctly. It does not prove
* layout or that a human can read the result.
*/
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { webcrypto } from "node:crypto";
import { JSDOM } from "jsdom";
const root = process.argv[2];
const gen = process.argv[3];
if (!root || !gen) {
console.error("usage: node proof.mjs <release-dir> <generation>");
process.exit(2);
}
let passed = 0;
const failures = [];
function check(label, condition, detail = "") {
if (condition) {
passed += 1;
} else {
failures.push(`${label}${detail ? ` -- ${detail}` : ""}`);
}
}
// ---------------------------------------------------------------- the DOM --
const html = await readFile(join(root, "index.html"), "utf8");
const dom = new JSDOM(html, {
url: "http://localhost/",
pretendToBeVisual: true, // gives requestAnimationFrame; the gauges need it
runScripts: "outside-only",
});
const { window } = dom;
// Serve the release directory over the fetch the app already uses. No network:
// a pathname maps straight onto a file, and anything missing is a real 404 so
// a wrong path fails loudly instead of silently resolving.
window.fetch = async (input) => {
const url = new URL(input instanceof URL ? input.href : String(input?.url ?? input),
"http://localhost/");
const file = join(root, decodeURIComponent(url.pathname).replace(/^\//, ""));
try {
const body = await readFile(file, "utf8");
return { ok: true, status: 200, json: async () => JSON.parse(body), text: async () => body };
} catch {
return { ok: false, status: 404, json: async () => ({}), text: async () => "" };
}
};
// app.mjs is a browser module: it reaches for document, Option, CustomEvent,
// requestAnimationFrame and the rest of what the DOM would have handed it.
//
// Lifting the WHOLE window onto globalThis looks tempting and blows the stack:
// jsdom's own setTimeout resolves through the global it is being copied over,
// and recurses until the stack ends. Timers stay Node's. Only the DOM surface
// the app actually touches is transplanted.
const FROM_WINDOW = [
"document", "location", "history", "navigator", "screen", "matchMedia",
"getComputedStyle", "requestAnimationFrame", "cancelAnimationFrame",
"Event", "CustomEvent", "EventTarget", "AbortController", "AbortSignal",
"Node", "Element", "HTMLElement", "HTMLInputElement", "HTMLSelectElement",
"HTMLOptionElement", "Option", "Image", "DocumentFragment", "NodeList",
"DOMParser", "XMLHttpRequest", "FormData", "Blob", "URL", "URLSearchParams",
"MutationObserver", "IntersectionObserver", "ResizeObserver",
"localStorage", "sessionStorage", "innerWidth", "innerHeight",
];
for (const key of FROM_WINDOW) {
let value;
try { value = window[key]; } catch { continue; }
if (value === undefined) continue;
// Node 24 defines several of these on globalThis as getter-only (navigator
// and crypto among them), so a plain assignment throws. Redefine instead.
try {
Object.defineProperty(globalThis, key, { value, writable: true, configurable: true });
} catch { /* non-configurable on this runtime; the app can live without it */ }
}
for (const [key, value] of [["window", window],
["fetch", window.fetch],
["crypto", webcrypto],
["addEventListener", window.addEventListener.bind(window)],
["dispatchEvent", window.dispatchEvent.bind(window)]]) {
Object.defineProperty(globalThis, key, { value, writable: true, configurable: true });
}
// ------------------------------------------------------------ boot the app --
const appUrl = pathToFileURL(join(root, "assets", "202608291447-app.mjs")).href;
await import(appUrl);
const ready = await new Promise((resolve) => {
const started = Date.now();
const poll = setInterval(() => {
if (window.document.body.dataset.fastReady === "true") { clearInterval(poll); resolve(true); }
else if (window.document.body.dataset.fastFailed === "true") { clearInterval(poll); resolve(false); }
else if (Date.now() - started > 60000) { clearInterval(poll); resolve(false); }
}, 40);
});
check("app boots", ready, window.document.body.dataset.fastFailed === "true"
? "boot() threw and the table failed closed" : "timed out");
if (!ready) {
console.error("\nthe app did not boot; nothing below can be trusted\n");
console.error(failures.join("\n"));
process.exit(1);
}
const doc = window.document;
const $ = (sel) => doc.querySelector(sel);
const rowsOf = () => [...doc.querySelectorAll("#tbody tr")];
const cellsOf = (tr) => [...tr.querySelectorAll("td")];
// ------------------------------------------------------- the payload, again --
const locality = JSON.parse(await readFile(join(root, "data", `${gen}-locality.json`), "utf8"));
const projects = JSON.parse(await readFile(
join(root, "data", "202608270055-8ab1807551bc-v8-fast-projects.json"), "utf8"));
const F = Object.fromEntries(projects.fields.map((name, index) => [name, index]));
const refOf = (row) => String(row[F.repd_ref]);
const townOf = (row) => locality.locality[refOf(row)]?.town || "";
const postcodeOf = (row) => locality.locality[refOf(row)]?.postcode || "";
const countyOf = (row) => projects.dictionaries.county[row[F.county]] || "";
// ------------------------------------------------------------- the columns --
const headings = [...doc.querySelectorAll("thead th")].map((th) => th.textContent.replace(/\s+/g, " ").trim());
// The count is not hard-coded: a later cartridge may legitimately add a
// column, and this proof owns TOWN and POSTCODE, not the table's width. It
// asserts the columns it added and that the body agrees with the header.
check("table has at least the 13 columns this cartridge left behind",
headings.length >= 13, `found ${headings.length}: ${headings.join(" | ")}`);
check("TOWN column present", headings.some((h) => h.startsWith("TOWN")), headings.join(" | "));
check("POSTCODE column present", headings.some((h) => h.startsWith("POSTCODE")), headings.join(" | "));
check("TOWN sits between COUNTY and POSTCODE",
headings.findIndex((h) => h.startsWith("COUNTY")) + 1 === headings.findIndex((h) => h.startsWith("TOWN"))
&& headings.findIndex((h) => h.startsWith("TOWN")) + 1 === headings.findIndex((h) => h.startsWith("POSTCODE")),
headings.join(" | "));
// Derive the cell indices from the headings rather than hard-coding them.
// Hard-coded ones were wrong the moment this cartridge inserted two columns,
// which is exactly the mistake the columns exist to make visible.
const COL = Object.fromEntries(["COUNTY", "TOWN", "POSTCODE", "OFFICIAL CAPACITY"]
.map((name) => [name, headings.findIndex((h) => h.startsWith(name))]));
check("every column this proof reads was found",
Object.values(COL).every((index) => index >= 0), JSON.stringify(COL));
const first = rowsOf();
check("rows render", first.length > 0, `${first.length} rows`);
check("every row has one cell per heading",
first.every((tr) => cellsOf(tr).length === headings.length),
`${headings.length} headings, row widths: ${[...new Set(first.map((tr) => cellsOf(tr).length))].join(",")}`);
const failColspan = (await readFile(join(root, "assets", "202608291447-app.mjs"), "utf8"))
.match(/colspan="(\d+)" class="fast-fail"/);
check("fail-closed row would span the whole table",
failColspan !== null && Number(failColspan[1]) === headings.length,
failColspan ? `colspan ${failColspan[1]}, ${headings.length} headings` : "no fail-closed row found");
// ---------------------------------------------------- the values in the cells --
let townMatches = 0;
let postcodeMatches = 0;
let dimmedDerived = 0;
for (const tr of first) {
const ref = tr.id.replace(/^repd-/, "");
const place = locality.locality[ref] || {};
const town = cellsOf(tr)[COL.TOWN].textContent.trim();
const postcode = cellsOf(tr)[COL.POSTCODE].textContent.trim();
if (town === (place.town || "-")) townMatches += 1;
if (postcode === (place.postcode || "-")) postcodeMatches += 1;
if (place.town_source === "derived" && cellsOf(tr)[COL.TOWN].querySelector(".derived")) dimmedDerived += 1;
}
check("every TOWN cell matches the payload", townMatches === first.length,
`${townMatches}/${first.length}`);
check("every POSTCODE cell matches the payload", postcodeMatches === first.length,
`${postcodeMatches}/${first.length}`);
const derivedOnPage = first.filter((tr) =>
locality.locality[tr.id.replace(/^repd-/, "")]?.town_source === "derived").length;
check("address-derived towns are marked as such", dimmedDerived === derivedOnPage,
`${dimmedDerived}/${derivedOnPage} dimmed`);
// A town this app cannot source must be a dash, never a guess.
const unsourceable = Object.values(locality.locality).filter((p) => !p.town).length;
check("payload leaves unsourceable towns null, not guessed",
unsourceable === (locality.counts.none || 0), `${unsourceable} null vs counts.none ${locality.counts.none}`);
check("postcodes are copied from REPD, never invented",
Object.values(locality.locality).every((p) => p.postcode === null || /^[A-Z]{1,2}\d[A-Z\d]?( \d[A-Z]{2})?$/.test(p.postcode)));
// ------------------------------------------------------------- the sorting --
const clickAndRead = (buttonId) => {
$(buttonId).dispatchEvent(new window.Event("click", { bubbles: true }));
return rowsOf().map((tr) => tr.id.replace(/^repd-/, ""));
};
// Independently re-derived expectation: filter nothing, sort the payload the
// way the column claims to, and take the first window.
const WINDOW = 100;
const allRefs = projects.rows.map((row, index) => index);
function expected(keyFn, direction, numeric = false) {
const copy = [...allRefs];
copy.sort((left, right) => {
const a = keyFn(projects.rows[left]);
const b = keyFn(projects.rows[right]);
if (numeric) return direction * (a - b) || left - right;
if (!a && !b) return left - right;
if (!a) return 1; // blanks last, both directions
if (!b) return -1;
return direction * String(a).localeCompare(String(b), "en-GB") || left - right;
});
return copy.slice(0, WINDOW).map((index) => refOf(projects.rows[index]));
}
const cases = [
["sortTown ascending", "#sortTown", () => expected(townOf, 1), "town_asc", "townHeader", "ascending"],
["sortTown descending", "#sortTown", () => expected(townOf, -1), "town_desc", "townHeader", "descending"],
["sortPostcode ascending", "#sortPostcode", () => expected(postcodeOf, 1), "postcode_asc", "postcodeHeader", "ascending"],
["sortPostcode descending", "#sortPostcode", () => expected(postcodeOf, -1), "postcode_desc", "postcodeHeader", "descending"],
["sortCounty ascending", "#sortCounty", () => expected(countyOf, 1), "county_asc", "countyHeader", "ascending"],
["sortCounty descending", "#sortCounty", () => expected(countyOf, -1), "county_desc", "countyHeader", "descending"],
];
for (const [label, button, wanted, mode, header, aria] of cases) {
const got = clickAndRead(button);
const want = wanted();
check(label, got.join(",") === want.join(","),
`first 5 got ${got.slice(0, 5).join(",")} want ${want.slice(0, 5).join(",")}`);
check(`${label} syncs the sort control`, $("#sortProjects").value === mode, $("#sortProjects").value);
check(`${label} sets aria-sort`, doc.getElementById(header).getAttribute("aria-sort") === aria,
doc.getElementById(header).getAttribute("aria-sort"));
}
// Capacity: descending is the payload's own order, so prove both directions
// against the numbers rather than against the row order.
const capacityFirst = clickAndRead("#sortCapacity");
check("capacity heading first click leaves the default largest-first",
$("#sortProjects").value === "capacity_asc" || $("#sortProjects").value === "capacity_desc",
$("#sortProjects").value);
const capacityMode = $("#sortProjects").value;
const capacities = rowsOf().map((tr) =>
Number(cellsOf(tr)[COL["OFFICIAL CAPACITY"]].textContent.replace(/[^\d.]/g, "")));
if (capacityMode === "capacity_asc") {
check("capacity ascending really ascends",
capacities.every((v, i) => i === 0 || capacities[i - 1] <= v),
`${capacities.slice(0, 5).join(",")}`);
} else {
check("capacity descending really descends",
capacities.every((v, i) => i === 0 || capacities[i - 1] >= v),
`${capacities.slice(0, 5).join(",")}`);
}
clickAndRead("#sortCapacity");
const flipped = rowsOf().map((tr) => Number(cellsOf(tr)[COL["OFFICIAL CAPACITY"]].textContent.replace(/[^\d.]/g, "")));
check("capacity heading flips direction on the second click",
capacityMode === "capacity_asc"
? flipped.every((v, i) => i === 0 || flipped[i - 1] >= v)
: flipped.every((v, i) => i === 0 || flipped[i - 1] <= v),
`${flipped.slice(0, 5).join(",")}`);
check("capacity heading first click did produce a full page", capacityFirst.length === WINDOW,
`${capacityFirst.length}`);
// The heading that already worked must still work.
clickAndRead("#sortUpdated");
check("REPD UPDATED still sorts", ["updated_desc", "updated_asc"].includes($("#sortProjects").value),
$("#sortProjects").value);
check("only the active column shows a direction",
["countyHeader", "townHeader", "postcodeHeader", "capacityHeader"]
.every((id) => doc.getElementById(id).getAttribute("aria-sort") === "none"));
// Blanks last, in both directions -- the reason locality sorting is useful at all.
$("#sortProjects").value = "postcode_asc";
$("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
const ascPostcodes = rowsOf().map((tr) => cellsOf(tr)[COL.POSTCODE].textContent.trim());
check("ascending postcode page carries no blanks while values remain",
!ascPostcodes.includes("-"), `${ascPostcodes.filter((p) => p === "-").length} blanks on page 1`);
$("#sortProjects").value = "postcode_desc";
$("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
const descPostcodes = rowsOf().map((tr) => cellsOf(tr)[COL.POSTCODE].textContent.trim());
check("descending postcode page carries no blanks either",
!descPostcodes.includes("-"), `${descPostcodes.filter((p) => p === "-").length} blanks on page 1`);
// -------------------------------------------------------------- provenance --
const note = $("#localityNote").textContent;
const sourced = (locality.counts.bua || 0) + (locality.counts.parish || 0) + (locality.counts.ward || 0);
check("the UI states where town came from",
note.includes(sourced.toLocaleString("en-GB")) && note.includes("ONS"), note);
check("the UI states how many postcodes are official",
note.includes((locality.counts.postcode || 0).toLocaleString("en-GB")), note);
check("no network at runtime is declared and true", locality.network_at_runtime === false);
// The sort model must accept every mode the UI can produce, or a deep link breaks.
const options = [...doc.querySelectorAll("#sortProjects option")].map((o) => o.value);
check("every sort option is a recognised mode",
options.every((value) => {
$("#sortProjects").value = value;
$("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
return rowsOf().length > 0;
}), options.join(","));
// ------------------------------------------- the column that was too wide --
// A single 237-character address line was being served as a TOWN. With the
// column set to nowrap that one value sized the column for all 7,510 rows,
// which is the gap between TOWN and POSTCODE.
// Two different rules, deliberately. An address-derived town is capped at 32
// because past that it stops being a place name and starts being a site
// description. An ONS value is an official name and is never truncated --
// "Chafford Hundred, West Thurrock and Purfleet-on-Thames" is a real ward.
// The column is kept narrow by the CSS cap, not by editing ONS.
const derivedTowns = Object.values(locality.locality)
.filter((p) => p.town_source === "derived").map((p) => p.town);
const onsTowns = Object.values(locality.locality)
.filter((p) => p.town && p.town_source !== "derived").map((p) => p.town);
check("no address-derived town exceeds the 32-character rule",
Math.max(...derivedTowns.map((t) => t.length)) <= 32,
`longest ${JSON.stringify(derivedTowns.sort((a, b) => b.length - a.length)[0])}`);
check("ONS names are kept whole, and none is absurd",
Math.max(...onsTowns.map((t) => t.length)) <= 60,
`longest ${JSON.stringify(onsTowns.sort((a, b) => b.length - a.length)[0])}`);
check("the 237-character address description is gone",
Math.max(...Object.values(locality.locality).map((p) => (p.town || "").length)) < 100);
check("no town spans more than one line",
Object.values(locality.locality).every((p) => !/[\r\n]/.test(p.town || "")));
check("address-derived towns read as place names, not site descriptions",
Object.values(locality.locality)
.filter((p) => p.town_source === "derived")
.every((p) => p.town.length <= 32 && !/\d/.test(p.town)),
JSON.stringify(Object.values(locality.locality)
.filter((p) => p.town_source === "derived" && (p.town.length > 32 || /\d/.test(p.town)))
.slice(0, 3).map((p) => p.town)));
const css = await readFile(join(root, "index.html"), "utf8");
check("the TOWN cell is capped and ellipsised rather than nowrapped open",
css.includes(".town-cell > span") && css.includes("text-overflow: ellipsis"));
check("every rendered TOWN value carries its full text on hover",
rowsOf().every((tr) => {
const span = cellsOf(tr)[COL.TOWN].querySelector("span");
return !span || span.getAttribute("title");
}));
// ------------------------------------------------- the horizontal scrollbar --
check("the table area is bounded on desktop so its scrollbar is reachable",
css.includes(".tablewrap { max-height: calc(100vh - 270px)"), "no desktop max-height");
check("the table declares a min-width wide enough for 13 columns",
/\.tablewrap table \{ min-width: 16\d\dpx/.test(css), "min-width not raised past 1500px");
check("the scrollbar is given a visible track and thumb",
css.includes("::-webkit-scrollbar-thumb") && css.includes("scrollbar-color"));
// ---------------------------------------------------------- the search bar --
// One bar, covering everything. County was always searchable through the
// prebuilt index; town, postcode and authority are the new terms.
//
// The handler debounces 120ms and then awaits the 1.9 MB search supplement, so
// reading the rows straight after dispatching the event reads the PREVIOUS
// result. Every search below waits for the app to settle first.
const searchBox = $("#search");
const settle = () => new Promise((resolve) => {
const started = Date.now();
const poll = setInterval(() => {
const meta = $("#resultsMeta").textContent || "";
if (!meta.includes("loading") || Date.now() - started > 30000) {
clearInterval(poll);
setTimeout(resolve, 30);
}
}, 25);
});
const runSearch = async (text) => {
searchBox.value = text;
searchBox.dispatchEvent(new window.Event("input", { bubbles: true }));
await settle();
return rowsOf();
};
const townsOfRows = (trs) => trs.map((tr) =>
locality.locality[tr.id.replace(/^repd-/, "")]?.town || "");
check("the placeholder names what the bar covers",
/TOWN/.test(searchBox.placeholder) && /POSTCODE/.test(searchBox.placeholder)
&& /COUNTY/.test(searchBox.placeholder), searchBox.placeholder);
// A term that finds nothing must find nothing. If this passes trivially then
// every assertion below it is meaningless, so it goes first.
check("a term in none of the fields finds nothing",
(await runSearch("zzzznotaplacezzzz")).length === 0,
`${(await runSearch("zzzznotaplacezzzz")).length} rows`);
check("clearing the box restores the full table",
(await runSearch("")).length === WINDOW);
// Choose a town held by only a handful of projects, so the whole answer fits
// inside one 100-row window and the assertion can be exact.
const byTown = new Map();
for (const [ref, place] of Object.entries(locality.locality)) {
if (!place.town || place.town_source === "derived") continue;
if (!/^[A-Za-z][A-Za-z' -]{5,19}$/.test(place.town)) continue;
byTown.set(place.town, [...(byTown.get(place.town) || []), ref]);
}
const [sampleTown, sampleRefs] = [...byTown.entries()]
.find(([, refs]) => refs.length >= 2 && refs.length <= 6);
const townHits = await runSearch(sampleTown);
check(`town search finds rows ("${sampleTown}")`, townHits.length > 0, `${townHits.length} rows`);
check("town search returns every project in that town",
sampleRefs.every((ref) => townHits.some((tr) => tr.id === `repd-${ref}`)),