GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / neural-link-between-agents / FIXES/NL-016/gridatlas/tools

Networks and 5 more files

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that reads grid 400kV, grid 132kV, grid substations and ne 10m coastline, using Douglas-Peucker.

479 lines of Python and JavaScript and CSS from neural-link-between-agents, particle-physics-drawing-engine, sld, in 6 files. Topic: Grid network and substations. Section 450 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. GridAtlas Nearest Substation Check electrical · neural-link-between-agents / FIXES/NL-016/gridatlas/tools/nearest_substation_check.mjs lines 1–66
  2. Networks storage · particle-physics-drawing-engine / tools/networks.py lines 1–122
  3. Single-Line Diagram (SLD) — App interaction · sld / assets/app.js lines 1–64
  4. Components render · sld / data/upstream/powsybl/components.css lines 1–58
  5. Single-Line Diagram (SLD) Build Catalogue storage · sld / scripts/build_catalogue.py lines 1–56
  6. Single-Line Diagram (SLD) Build Site ingest · sld / scripts/build_site.py lines 1–113

GridAtlas Nearest Substation Check

A JavaScript module in the tools folder of Neural Link Between Agents that reads grid substations. It is built from the grab step (`grab`) and the nearest step (`nearest`).

electricalneural-link-between-agents / FIXES/NL-016/gridatlas/tools/nearest_substation_check.mjs · lines 1–66 of 66 · Not reached from any entry point (candidate for review) · pattern nearest (shared by 21 files)

What it does
It loads grid substations. Defines grab, nearest. Uses libraries node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): 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.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; command-line arguments.
What it achieves
Nearest-substation QA for the October preview records, using GridAtlas's own shipped code, not a re-implementation: - `distanceKm`: `atlas/modules/202609011950-geodesy.js`, run in node:vm with a window stub; - `voltagesKv`, `representativePoint`, `MIN_KV/LINK_COUNT/MAX_LINK_KM`: extracted verbatim from the live single-line diagram (SLD)-sandbox cartridge `atlas/cartridges/202609241334-sld-sandbox-v9-8.js` and evaluated.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-016/gridatlas/tools · JavaScript module
Uses
node:fs, node:vm
Used by
none found
Produces
grab, nearest
Defines here
grab, nearest
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-016/gridatlas/tools/nearest_substation_check.mjs:1-66 · blob aa16f7ba06a6a23c6f41db68ef9a9206dc55feef · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer, ai_agent · canonical: unreached_review
// Nearest-substation QA for the October preview records, using GridAtlas's own shipped code, not a re-implementation:
//  - distanceKm: atlas/modules/202609011950-geodesy.js, run in node:vm with a window stub;
//  - voltagesKv, representativePoint, MIN_KV/LINK_COUNT/MAX_LINK_KM: extracted verbatim from the live sld-sandbox
//    cartridge atlas/cartridges/202609241334-sld-sandbox-v9-8.js and evaluated;
//  - substations: atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson (the payload the live link code reads).
// Usage: node nearest_substation_check.mjs <gridatlas work dir> <q2.parquet-as-json> <oct.parquet-as-json> <out.json>
import fs from 'node:fs';
import vm from 'node:vm';
const [W, q2f, octf, out] = process.argv.slice(2);
const ctx = { window: {}, Math, Number, String, Array, Object, JSON };
vm.createContext(ctx);
vm.runInContext(fs.readFileSync(`${W}/atlas/modules/202609011950-geodesy.js`, 'utf8'), ctx);
const distanceKm = ctx.window.__GRIDATLAS_MODULES__.geodesy.distanceKm;
const sld = fs.readFileSync(`${W}/atlas/cartridges/202609241334-sld-sandbox-v9-8.js`, 'utf8');
const grab = (name) => { const i = sld.indexOf(`function ${name}(`); let d = 0, j = sld.indexOf('{', i);
  for (let k = j; k < sld.length; k++) { if (sld[k] === '{') d++; else if (sld[k] === '}' && --d === 0) return sld.slice(i, k + 1); } };
const consts = sld.match(/const MIN_KV = (\d+);[\s\S]*?const LINK_COUNT = (\d+);[\s\S]*?const MAX_LINK_KM = (\d+);/);
const MIN_KV = +consts[1], LINK_COUNT = +consts[2], MAX_LINK_KM = +consts[3];
const voltagesKv = new Function(`${grab('voltagesKv')}; return voltagesKv;`)();
const representativePoint = new Function(`${grab('representativePoint')}; return representativePoint;`)();
const subsRaw = JSON.parse(fs.readFileSync(`${W}/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson`, 'utf8')).features;
const subs = [];
for (const f of subsRaw) { // the same qualifying filter as loadSubstations()
  const kv = voltagesKv(f.properties); if (!kv.length || Math.max(...kv) < MIN_KV - 0.5) continue;
  const at = representativePoint(f.geometry); if (!at) continue;
  subs.push({ at, kv: kv.filter(v => v >= MIN_KV - 0.5).sort((a, b) => b - a), name: f.properties?.name || '' });
}
const nearest = (lon, lat) => subs.map(s => ({ ...s, km: distanceKm(lon, lat, s.at[0], s.at[1]) })).sort((a, b) => a.km - b.km);
const q2 = new Map(JSON.parse(fs.readFileSync(q2f, 'utf8')).map(r => [r.repd_ref, r]));
const oct = JSON.parse(fs.readFileSync(octf, 'utf8'));
const res = { substations_loaded: subsRaw.length, substations_qualifying: subs.length, MIN_KV, LINK_COUNT, MAX_LINK_KM, groups: {} };
const rows = [];
for (const r of oct) {
  const old = q2.get(r.repd_ref);
  const kind = !old ? 'added' : (Math.abs(old.longitude - r.longitude) > 1e-6 || Math.abs(old.latitude - r.latitude) > 1e-6) ? 'moved' : null;
  if (!kind) continue;
  const placeholder = r.longitude === 0 && r.latitude === 0;
  const row = { kind, repd_ref: r.repd_ref, name: r.name, technology: r.technology, status: r.status, capacity_mw: r.capacity_mw,
    region: r.region, county: r.county, lon: r.longitude, lat: r.latitude, placeholder };
  if (!placeholder) {
    const n = nearest(r.longitude, r.latitude);
    row.nearest = { name: n[0].name || 'Unnamed substation', kv: n[0].kv[0], km: +n[0].km.toFixed(3) };
    row.drawn_links = n.filter(s => s.km <= MAX_LINK_KM).slice(0, LINK_COUNT).length;
    if (old && kind === 'moved') row.moved_km = +distanceKm(old.longitude, old.latitude, r.longitude, r.latitude).toFixed(3);
    // coarse sanity: a Scottish record south of 54.6 N, or an English/Welsh record north of 55.9 N
    row.region_lat_mismatch = (/scotland/i.test(r.region || '') && r.latitude < 54.6) || (/^(?!.*scotland)/i.test(r.region || '') && /england|wales|london|midlands|east|west|south|north|yorkshire/i.test(r.region || '') && r.latitude > 55.9);
  }
  rows.push(row);
}
for (const k of ['added', 'moved']) {
  const g = rows.filter(r => r.kind === k), m = g.filter(r => !r.placeholder);
  const kms = m.map(r => r.nearest.km).sort((a, b) => a - b);
  res.groups[k] = { records: g.length, placeholder_no_map: g.filter(r => r.placeholder).map(r => `${r.repd_ref} ${r.name}`),
    measured: m.length, nearest_km_median: kms[Math.floor(kms.length / 2)], nearest_km_p95: kms[Math.floor(kms.length * 0.95)], nearest_km_max: kms[kms.length - 1],
    beyond_40km_no_links: m.filter(r => r.drawn_links === 0).map(r => `${r.repd_ref} ${r.name} [${r.technology}] ${r.nearest.km} km to ${r.nearest.name}`),
    region_lat_mismatch: m.filter(r => r.region_lat_mismatch).map(r => `${r.repd_ref} ${r.name} region=${r.region} county=${r.county} lat=${r.lat}`),
    moved_over_5km: k === 'moved' ? m.filter(r => r.moved_km > 5).map(r => `${r.repd_ref} ${r.name} moved ${r.moved_km} km`) : undefined };
}
// Known source-coordinate faults that the nearest-substation answer inherits.
res.salters_lane = rows.concat(oct.filter(r => ['18561', '18562'].includes(r.repd_ref)).map(r => ({ repd_ref: r.repd_ref, name: r.name, county: r.county, lon: r.longitude, lat: r.latitude,
  nearest: (() => { const n = nearest(r.longitude, r.latitude)[0]; return { name: n.name, kv: n.kv[0], km: +n.km.toFixed(3) }; })() })))
  .filter(r => ['18561', '18562'].includes(r.repd_ref)).filter((r, i, a) => a.findIndex(x => x.repd_ref === r.repd_ref && !!x.kind === !!r.kind) === i);
res.rows = rows;
fs.writeFileSync(out, JSON.stringify(res, null, 1));
const { rows: _, ...summary } = res;
console.log(JSON.stringify(summary, null, 1).slice(0, 6000));

Networks

A Python command-line tool in the tools folder of Particle Physics Drawing Engine that reads grid 400kV, grid 132kV, grid substations and ne 10m coastline, using Douglas-Peucker.

storageparticle-physics-drawing-engine / tools/networks.py · lines 1–122 of 122 · Entry point

What it does
It loads grid 400kV, grid 132kV, grid substations and ne 10m coastline. Defines dp, normalise, from_lines, write, main. Uses libraries argparse, json, math, os, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV, 132kV (all 132kV or above)): 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: 400kV, 132kV. README: "`tools/networks.py` turns any GridAtlas layer into a draw on the one wafer."
Inputs & outputs
In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_substations.geojson; GeoJSON file ne_10m_coastline.geojson; GeoJSON file ne_110m_coastline.geojson; command-line arguments. Out: JSON file. Voltage levels named: 400kV, 132kV.
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 normalise step (`normalise`), the from lines helper (`from_lines`) and the write step (`write`). Real systems as network files the wafer draws with its own dust. Its code works with 132 kV and 400 kV. It accepts `--gg`, `--ne` and `--shotwick`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
particle-physics-drawing-engine · tools · Python CLI
Uses
argparse, json, math, os, sys
Used by
none found
Produces
dp, normalise, from_lines, write, main
Defines here
dp, normalise, from_lines, write, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
particle-physics-drawing-engine@d3d28cc760761dab210dc3850577ee73c23fe8c5 tools/networks.py:1-122 · blob 6c4f1432fc1a3e2bc2a068e4ab4b0cfc9297040c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""networks.py: real systems as network files the wafer draws with its own dust.

Each output is {"name","source","attribution","law","stations":[[x,y,name],...],"edges":[[i,j],...]} with x,y in
[-0.9, 0.9], north up, equirectangular scaled by cos(mean latitude), so the drawing keeps its shape. Lines are
simplified by Douglas-Peucker so a file stays small; the tolerance is printed with the counts. Nothing is invented:
every node is a vertex of the source geometry or a point in the source data.

Sources (all public): grid_400kv.geojson, grid_132kv.geojson, grid_substations.geojson at globalgrid2050.com
(OpenStreetMap-derived, ODbL); Natural Earth coastlines (public domain); a REPD project from Pipeline News.
"""
import argparse, json, math, os, sys

OSM = "© OpenStreetMap contributors, Open Database Licence (ODbL); published at globalgrid2050.com"
NE = "Natural Earth (naturalearthdata.com), public domain"


def dp(points, tol):
    """Douglas-Peucker on [x,y] points."""
    if len(points) < 3:
        return points
    if points[0] == points[-1]:                       # a closed ring (an island): split it, or it collapses to a line
        h = len(points) // 2
        return dp(points[:h + 1], tol)[:-1] + dp(points[h:], tol)
    (x1, y1), (x2, y2) = points[0], points[-1]
    dx, dy = x2 - x1, y2 - y1
    L = math.hypot(dx, dy) or 1e-12
    imax, dmax = 0, -1.0
    for i in range(1, len(points) - 1):
        px, py = points[i]
        d = abs(dy * px - dx * py + x2 * y1 - y2 * x1) / L
        if d > dmax:
            imax, dmax = i, d
    if dmax > tol:
        return dp(points[:imax + 1], tol)[:-1] + dp(points[imax:], tol)
    return [points[0], points[-1]]


def normalise(pts):
    lat0 = sum(p[1] for p in pts) / len(pts)
    c = math.cos(math.radians(lat0))
    xs = [p[0] * c for p in pts]; ys = [p[1] for p in pts]
    x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
    sc = max(x1 - x0, y1 - y0) or 1
    return [[round((x - x0) / sc * 1.8 - 0.9 * (x1 - x0) / sc, 4), round((y - y0) / sc * 1.8 - 0.9 * (y1 - y0) / sc, 4)] for x, y in zip(xs, ys)]


def from_lines(features, tol, name_key="name", bbox=None, min_pts=2):
    """LineString features -> nodes and edges, vertices shared by exact coordinate."""
    idx, nodes, edges, kept = {}, [], set(), 0
    for f in features:
        g = f["geometry"]
        parts = [g["coordinates"]] if g["type"] == "LineString" else (g["coordinates"] if g["type"] == "MultiLineString" else [])
        label = (f.get("properties") or {}).get(name_key, "") or ""
        for coords in parts:
            pts = [[float(c[0]), float(c[1])] for c in coords]
            if bbox:
                pts = [p for p in pts if bbox[0] <= p[0] <= bbox[2] and bbox[1] <= p[1] <= bbox[3]]
            if len(pts) < min_pts:
                continue
            pts = dp(pts, tol); kept += 1
            ids = []
            for p in pts:
                k = (round(p[0], 5), round(p[1], 5))
                if k not in idx:
                    idx[k] = len(nodes); nodes.append([p[0], p[1], label if len(nodes) == 0 or label else ""])
                ids.append(idx[k])
            for a, b in zip(ids, ids[1:]):
                if a != b:
                    edges.add((a, b) if a < b else (b, a))
    return nodes, sorted(edges), kept


def write(out, name, source, attribution, law, nodes, edges):
    xy = normalise([[n[0], n[1]] for n in nodes]) if nodes else []
    net = {"name": name, "source": source, "attribution": attribution, "law": law,
           "stations": [[p[0], p[1], n[2]] for p, n in zip(xy, nodes)], "edges": edges}
    p = os.path.join(out, f"{name}-network.json")
    json.dump(net, open(p, "w", encoding="utf-8"), separators=(",", ":"), ensure_ascii=False)
    print(f"{name}: {len(nodes)} nodes, {len(edges)} edges, {os.path.getsize(p):,} bytes -> {p}")
    return p


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--gg", default=r"C:\Users\vikra\Documents\GitHub\globalgrid2050", help="globalgrid2050 clone")
    ap.add_argument("--ne", default=r"E:\particles-runs\data", help="folder with ne_10m_coastline.geojson and ne_110m_coastline.geojson")
    ap.add_argument("--shotwick", default="", help="lon,lat of Shotwick Solar Farm from Pipeline News")
    ap.add_argument("--out", default="out/networks")
    ap.add_argument("--tol", type=float, default=0.002, help="simplification tolerance in degrees")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    gj = lambda f: json.load(open(f, encoding="utf-8"))["features"]

    f400 = gj(os.path.join(a.gg, "grid_400kv.geojson")); n, e, k = from_lines(f400, a.tol)
    write(a.out, "grid400", "globalgrid2050.com/grid_400kv.geojson, 400 kV overhead lines and cables", OSM, f"vertices of {k} lines simplified at {a.tol} deg, edges between consecutive vertices", n, e)
    f132 = gj(os.path.join(a.gg, "grid_132kv.geojson")); n, e, k = from_lines(f132, a.tol)
    write(a.out, "grid132", "globalgrid2050.com/grid_132kv.geojson, 132 kV lines", OSM, f"vertices of {k} lines simplified at {a.tol} deg", n, e)
    subs = gj(os.path.join(a.gg, "grid_substations.geojson"))
    n = [[float(f["geometry"]["coordinates"][0]), float(f["geometry"]["coordinates"][1]), (f.get("properties") or {}).get("name", "") or ""] for f in subs if f["geometry"]["type"] == "Point"]
    write(a.out, "substations", "globalgrid2050.com/grid_substations.geojson, substations", OSM, "one node per substation, no edges: the particles cluster at each", n, [])
    uk = gj(os.path.join(a.ne, "ne_10m_coastline.geojson")); n, e, k = from_lines(uk, a.tol * 2, bbox=(-11.0, 49.5, 2.5, 61.0), min_pts=3)
    write(a.out, "uk", "Natural Earth 10 m coastline, clipped to the British Isles", NE, f"coastline vertices simplified at {a.tol * 2} deg", n, e)
    world = gj(os.path.join(a.ne, "ne_110m_coastline.geojson")); n, e, k = from_lines(world, 0.0, min_pts=3)
    write(a.out, "world", "Natural Earth 110 m coastline", NE, "coastline vertices, unsimplified", n, e)
    # the grid as one picture: 400 kV and 132 kV lines with every substation, the transmission and sub-transmission system
    n1, e1, k1 = from_lines(f400, a.tol); n2, e2, k2 = from_lines(f132, a.tol)
    subs_nodes = [[float(f["geometry"]["coordinates"][0]), float(f["geometry"]["coordinates"][1]), (f.get("properties") or {}).get("name", "") or ""] for f in subs if f["geometry"]["type"] == "Point"]
    o1 = len(n1); o2 = o1 + len(n2)
    write(a.out, "grid", "globalgrid2050.com: grid_400kv.geojson, grid_132kv.geojson and grid_substations.geojson together", OSM,
          f"{k1} 400 kV lines and {k2} 132 kV lines as edges, simplified at {a.tol} deg; {len(subs_nodes)} substations as nodes without edges", n1 + n2 + subs_nodes, e1 + [[i + o1, j + o1] for i, j in e2])
    if a.shotwick:
        lon, lat = (float(v) for v in a.shotwick.split(","))
        box = (lon - 0.6, lat - 0.4, lon + 0.6, lat + 0.4)
        n1, e1, k1 = from_lines(f400, a.tol / 2, bbox=box); n2, e2, k2 = from_lines(f132, a.tol / 2, bbox=box)
        off = len(n1); nodes = n1 + n2 + [[lon, lat, "Shotwick Solar Farm (REPD, Pipeline News)"]]
        edges = e1 + [[i + off, j + off] for i, j in e2]
        write(a.out, "shotwick", "Shotwick Solar Farm from Pipeline News (REPD), with the 400 kV and 132 kV lines within about 60 x 80 km from globalgrid2050.com", OSM + "; REPD via Pipeline News", f"{k1} 400 kV and {k2} 132 kV lines around the site, simplified at {a.tol / 2} deg; the site is the last node", nodes, edges)


if __name__ == "__main__":
    main()

Single-Line Diagram (SLD) — App

A JavaScript file in the assets folder that draws SLD educational draft. It renders cards (`renderCards`), adds part (`addPart`) and renders canvas (`renderCanvas`).

interactionsld / assets/app.js · lines 1–64 of 64 · Not reached from any entry point (candidate for review) · pattern preview (shared by 2 files)

What it does
It draws SLD educational draft. Defines 16 functions or classes, including $, text, svg, say, label. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file sld-educational-draft.json; JSON file library.json.
What it achieves
Educational drawing state is deliberately separate from electrical topology. It reads `data/library.json`. It responds to click, keydown and input events.
Why it matters
No other file in the estate was found to import it.
Application
sld · assets · script
Uses
none found
Used by
none found
Produces
$, text, svg, say, label, key, preview, renderCards, addPart, choose, renderCanvas, move
Defines here
$, text, svg, say, label, key, preview, renderCards, addPart, choose, renderCanvas, move, remove, validateDraft, download, exportSVG
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 assets/app.js:1-64 · blob 050a97f79892534e2f275999f9e1cc73da664ae2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/* Educational drawing state is deliberately separate from electrical topology. */
'use strict';
const $ = id => document.getElementById(id);
const NS = 'http://www.w3.org/2000/svg';
let components = [], byId = new Map(), selected = null, connecting = false, start = null;
let draft = {schema_version: 'sld-educational-draft/1', educational_only: true, instances: [], connections: []};
const text = (tag, value, cls) => {const e = document.createElement(tag); e.textContent = value; if(cls)e.className=cls; return e;};
const svg = (tag, attrs={}) => {const e=document.createElementNS(NS,tag); for(const [k,v] of Object.entries(attrs))e.setAttribute(k,String(v)); return e;};
const say = value => {$('status').textContent=value;};
const label = c => c.label || c.display_label || c.type.replaceAll('_',' ').toLowerCase();
const key = c => c.id || c.type;
const preview = c => c.preview || `assets/previews/${c.type}.svg`;
function renderCards(){
  const query=$('search').value.trim().toLowerCase();
  const matches=components.filter(c=>`${label(c)} ${c.type} ${c.description||''}`.toLowerCase().includes(query));
  $('cards').replaceChildren(); $('count').textContent=`${matches.length} / ${components.length} components`; $('empty').hidden=!!matches.length;
  for(const c of matches){
    const card=text('article','','card');const img=document.createElement('img');img.src=preview(c);img.alt=`${label(c)} research preview`;img.className='preview';img.loading='lazy';card.append(img,text('span','RESEARCH / NOT APPROVED','badge'),text('h3',label(c)),text('div',c.type,'type'));
    const details=document.createElement('details');details.append(text('summary','Source & details'));
    details.append(text('p','PowSyBl · ConvergenceLibrary · MPL-2.0. Not approved for engineering use.'));
    details.append(text('p',`${(c.anchorPoints||c.anchors||[]).length} graphical anchors. Electrical terminal mapping requires separate review.`));
    if(!(c.subComponents||[]).length)details.append(text('p','Renderer primitive: illustrative preview, no standalone upstream SVG.'));
    const source=document.createElement('a');source.href='https://github.com/powsybl/powsybl-diagram/tree/952186b5b34d1e4e472a04fb663b3654b54e3022/single-line-diagram/single-line-diagram-core/src/main/resources/ConvergenceLibrary';source.textContent='Original source ↗';source.target='_blank';source.rel='noopener noreferrer';details.append(source);card.append(details);
    const add=text('button','+ Add to draft');add.type='button';add.dataset.component=key(c);add.addEventListener('click',()=>addPart(c));card.append(add);$('cards').append(card);
  }
}
function addPart(c){if(draft.instances.length>=200){say('Draft limit: 200 parts.');return;}const n=draft.instances.length;const item={id:crypto.randomUUID(),component_id:key(c),x:100+(n%7)*125,y:100+(Math.floor(n/7)%4)*115};draft.instances.push(item);selected=item.id;renderCanvas();say(`Added ${label(c)}. Select it to move or connect.`);}
function choose(id){
  selected=id;
  if(connecting){if(start&&start!==id){const exists=draft.connections.some(e=>[e.from,e.to].includes(start)&&[e.from,e.to].includes(id));if(!exists&&draft.connections.length<400)draft.connections.push({from:start,to:id,kind:'illustrative-centre-link'});start=null;say('Illustrative link added. Crossings are not junctions.');}else{start=id;say('Choose another part to connect its graphical centre.');  … [line shortened here: 402 characters; full line on GitHub]
  renderCanvas();
}
function renderCanvas(){
  const canvas=$('canvas');canvas.replaceChildren();
  canvas.append(svg('rect',{width:1000,height:560,fill:'#f5f5f5'}));
  const caption=svg('text',{x:16,y:24,fill:'#555','font-size':12});caption.textContent='EDUCATIONAL DRAFT / RATINGS UNKNOWN / CENTRE LINKS ONLY';canvas.append(caption);
  for(const e of draft.connections){const a=draft.instances.find(n=>n.id===e.from),b=draft.instances.find(n=>n.id===e.to);canvas.append(svg('line',{x1:a.x,y1:a.y,x2:b.x,y2:b.y,stroke:'#333','stroke-width':2,'stroke-dasharray':'5 4'}));}
  for(const n of draft.instances){const c=byId.get(n.component_id);const group=svg('g',{transform:`translate(${n.x},${n.y})`,tabindex:0,role:'button','aria-label':`${label(c)}, select part`,class:`instance${selected===n.id?' selected':''}`,'data-instance':n.id});group.append(svg('rect',{x:-42,y:-40,width:84,height:80,fill:'#fff',stroke:'#aaa',rx:4}));group.append(svg('image',{href:preview(c),x:-30  … [line shortened here: 749 characters; full line on GitHub]
}
function move(dx,dy){const n=draft.instances.find(n=>n.id===selected);if(!n){say('Select a part first.');return;}n.x=Math.max(48,Math.min(952,n.x+dx));n.y=Math.max(75,Math.min(510,n.y+dy));renderCanvas();say('Part moved.');}
function remove(){if(!selected)return;draft.instances=draft.instances.filter(n=>n.id!==selected);draft.connections=draft.connections.filter(e=>e.from!==selected&&e.to!==selected);selected=null;start=null;renderCanvas();say('Selected part and its links removed.');}
function validateDraft(value){
  if(!value||typeof value!=='object'||value.schema_version!=='sld-educational-draft/1'||value.educational_only!==true)throw Error('Expected an SLD educational draft, version 1.');
  if(!Array.isArray(value.instances)||value.instances.length>200||!Array.isArray(value.connections)||value.connections.length>400)throw Error('Invalid draft size.');
  const ids=new Set();const instances=value.instances.map(n=>{if(!n||typeof n.id!=='string'||!/^[a-zA-Z0-9_-]{1,80}$/.test(n.id)||ids.has(n.id)||!byId.has(n.component_id)||!Number.isFinite(n.x)||!Number.isFinite(n.y)||n.x<48||n.x>952||n.y<75||n.y>510)throw Error('Invalid or duplicate part, component or position.');ids.add(n.id);return{id:n.id,component_id:n.component_id,x:n.x,y:n.y};});
  const pairs=new Set();const connections=value.connections.map(e=>{if(!e||!ids.has(e.from)||!ids.has(e.to)||e.from===e.to||e.kind!=='illustrative-centre-link')throw Error('Invalid connection.');const pair=[e.from,e.to].sort().join('|');if(pairs.has(pair))throw Error('Duplicate connection.');pairs.add(pair);return{from:e.from,to:e.to,kind:e.kind};});
  return{schema_version:'sld-educational-draft/1',educational_only:true,instances,connections};
}
function download(data,name,type){const url=URL.createObjectURL(new Blob([data],{type}));const a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
async function exportSVG(){
  const copy=$('canvas').cloneNode(true);copy.setAttribute('xmlns',NS);copy.setAttribute('width','1000');copy.setAttribute('height','560');
  for(const img of copy.querySelectorAll('image')){const url=new URL(img.getAttribute('href'),location.href);if(url.origin!==location.origin)throw Error('External preview rejected.');const response=await fetch(url);if(!response.ok)throw Error('Preview unavailable.');const bytes=new Uint8Array(await response.arrayBuffer());let binary='';for(const b of bytes)binary+=String.fromCharCode(b);img.setAtt  … [line shortened here: 458 characters; full line on GitHub]
  copy.querySelectorAll('[tabindex]').forEach(e=>{e.removeAttribute('tabindex');e.removeAttribute('role');e.removeAttribute('class');});download(new XMLSerializer().serializeToString(copy),'sld-educational-draft.svg','image/svg+xml');say('Exported a self-contained educational SVG.');
}
$('search').addEventListener('input',renderCards);
$('connect').addEventListener('click',()=>{connecting=!connecting;start=null;$('connect').setAttribute('aria-pressed',String(connecting));say(connecting?'Select two parts. Links are illustrative, not electrical terminals.':'Selection mode.');});
for(const [id,dx,dy] of [['move-left',-10,0],['move-up',0,-10],['move-down',0,10],['move-right',10,0]])$(id).addEventListener('click',()=>move(dx,dy));
$('delete').addEventListener('click',remove);
$('clear').addEventListener('click',()=>{draft.instances=[];draft.connections=[];selected=null;start=null;renderCanvas();say('Draft cleared.');});
$('export').addEventListener('click',()=>{download(JSON.stringify(draft,null,2),'sld-educational-draft.json','application/json');say('Exported educational draft JSON.');});
$('export-svg').addEventListener('click',()=>exportSVG().catch(e=>say(`Export failed: ${e.message}`)));
$('import').addEventListener('change',async e=>{try{const file=e.target.files[0];if(!file)return;if(file.size>1_000_000)throw Error('Maximum file size is 1 MB.');draft=validateDraft(JSON.parse(await file.text()));selected=null;start=null;renderCanvas();say(`Imported ${draft.instances.length} parts. Unknown extra fields were discarded.`);}catch(err){say(`Import rejected: ${err.message}`);}finally{e  … [line shortened here: 421 characters; full line on GitHub]
document.addEventListener('keydown',e=>{if(['INPUT','TEXTAREA','SELECT','BUTTON'].includes(e.target.tagName)||e.target.isContentEditable)return;const offsets={ArrowLeft:[-10,0],ArrowRight:[10,0],ArrowUp:[0,-10],ArrowDown:[0,10]};if(offsets[e.key]&&selected){e.preventDefault();move(...offsets[e.key]);}if(e.key==='Delete')remove();});
fetch('data/library.json').then(r=>{if(!r.ok)throw Error('Library request failed.');return r.json();}).then(data=>{components=data.components||data.symbols||[];if(!components.length)throw Error('Library contains no components.');byId=new Map(components.map(c=>[key(c),c]));renderCards();renderCanvas();}).catch(e=>{$('count').textContent='Library unavailable';say(`${e.message} Please try again later  … [line shortened here: 407 characters; full line on GitHub]

Components

A style sheet in the powsybl folder of Single-Line Diagram (SLD).

rendersld / data/upstream/powsybl/components.css · lines 1–58 of 58 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
sld · data/upstream/powsybl · style sheet
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 data/upstream/powsybl/components.css:1-58 · blob 9c1ca4436f8d41c55e50af7b595ee5f38d0e451c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/* ----------------------------------------------------------------------- */
/* File : components.css ------------------------------------------------- */
/* Stroke black */
.sld-disconnector {stroke-width: 3; stroke: black; fill: none}
/* Stroke blue */
.sld-breaker {stroke-width: 2; stroke: blue; fill:white}
.sld-load-break-switch {stroke: blue; fill: white}
/* Stroke --sld-vl-color with fallback black */
.sld-bus-connection {fill: var(--sld-vl-color, black)}
.sld-cell-shape-flat .sld-bus-connection {visibility: hidden}
.sld-busbar-section {stroke: var(--sld-vl-color, black); stroke-width: 3; fill: none}
/* Stroke --sld-vl-color with fallback red */
.sld-wire {stroke: var(--sld-vl-color, #c80000); fill: none}
.sld-wire.sld-boundary-line {stroke-width: 2px}
.sld-wire.sld-tie-line {stroke-width: 2px}
/* Stroke --sld-vl-color with fallback blue */
.sld-load {stroke: var(--sld-vl-color, blue); fill: none}
.sld-battery {stroke: var(--sld-vl-color, blue); fill: none}
.sld-generator {stroke: var(--sld-vl-color, blue); fill: none}
.sld-two-wt {stroke: var(--sld-vl-color, blue); fill: none}
.sld-three-wt {stroke: var(--sld-vl-color, blue); fill: none}
.sld-winding {stroke: var(--sld-vl-color, blue); fill: none}
.sld-capacitor {stroke: var(--sld-vl-color, blue); fill: none}
.sld-inductor {stroke: var(--sld-vl-color, blue); fill: none}
.sld-pst {stroke: var(--sld-vl-color, blue); fill: none}
.sld-pst-arrow {stroke: black; fill: none}
.sld-svc {stroke: var(--sld-vl-color, blue); fill: none}
.sld-vsc {stroke: var(--sld-vl-color, blue); font-size: 7.43px; fill: none}
.sld-lcc {stroke: var(--sld-vl-color, blue); font-size: 7.43px; fill: none}
.sld-ground {stroke: var(--sld-vl-color, blue); fill: none}
/* Stroke none & fill: --sld-vl-color */
.sld-node-infos {stroke: none; fill: var(--sld-vl-color, black)}
/* Stroke none & fill: black */
.sld-node {stroke: none; fill: black}
.sld-flash {stroke: none; fill: black}
.sld-lock {stroke: none; fill: black}
.sld-unknown {stroke: none; fill: black}
/* Fonts */
.sld-label {stroke: none; fill: black; font: 8px serif}
.sld-bus-legend-info {font: 10px serif}
.sld-graph-label {font: 12px serif}
/* Specific */
.sld-grid {stroke: #003700; stroke-dasharray: 1,10}
.sld-feeder-info.sld-active-power {fill:black}
.sld-feeder-info.sld-reactive-power {fill:blue}
.sld-feeder-info.sld-current {fill:purple}
.sld-frame {fill: var(--sld-background-color, transparent)}
/* Stroke maroon for fictitious switch */
.sld-breaker.sld-fictitious {stroke: maroon}
.sld-disconnector.sld-fictitious {stroke: maroon}
.sld-load-break-switch.sld-fictitious {stroke: maroon}
.sld-busbar-section.sld-fictitious {stroke: var(--sld-vl-color, #c80000); stroke-width: 1}
/* ground disconnector specific */
.sld-ground-disconnection-attach {stroke: var(--sld-vl-color, #c80000); fill: none}
.sld-open .sld-ground-disconnection-ground {stroke: black; fill: none}
.sld-closed .sld-ground-disconnection-ground {stroke: var(--sld-vl-color, #c80000); fill: none}
.sld-ground-disconnection .sld-sw-open {stroke: black; fill: none}
.sld-ground-disconnection .sld-sw-closed {stroke: black; fill: none}

Single-Line Diagram (SLD) Build Catalogue

A Python command-line tool in the scripts folder that reads components. It is built from the build step (`build`).

storagesld / scripts/build_catalogue.py · lines 1–56 of 56 · Entry point

What it does
It loads components. Defines build, main. Uses libraries argparse, copy, json, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file components.json; JSON file library.json; command-line arguments.
Downstream impact
Used directly by 2 files: Test Sources (sld); Single-Line Diagram (SLD) Pages Workflow (sld).
What it achieves
Build a deterministic research catalogue from hash-verified local sources. It accepts `--data` and `--config`.
Why it matters
Run by Single-Line Diagram (SLD) Pages Workflow. Checked by Test Sources.
Application
sld · scripts · Python CLI
Uses
Single-Line Diagram (SLD) Fetch Sources (import), argparse, copy, json, pathlib
Used by
imported by Test Sources (sys.path import), run by Single-Line Diagram (SLD) Pages Workflow (workflow run)
Produces
build, main
Defines here
build, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/build_catalogue.py:1-56 · blob c72ee93cd756f114a3cbe03550fb325c3364ad14 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Build a deterministic research catalogue from hash-verified local sources."""
import argparse
import copy
import json
from pathlib import Path
from fetch_sources import ROOT, check_offline


def build(config, data_dir):
    data_dir = Path(data_dir)
    lock = check_offline(config, data_dir)
    entries = {entry["path"]: entry for entry in lock["files"]}
    raw = json.loads((data_dir / "upstream/powsybl/components.json").read_text(encoding="utf-8"))
    components = []
    for original in raw:
        component = copy.deepcopy(original)
        component.update(id=original["type"], source_id="powsybl", production_enabled=False,
                         standards_status="unverified", source_ref="upstream/powsybl/components.json")
        for part in component.get("subComponents", []):
            part["asset_path"] = "upstream/powsybl/" + part["fileName"]
            if part["asset_path"] not in entries:
                raise ValueError(f"Unverified component asset: {part['asset_path']}")
        components.append(component)
    powsybl = next(source for source in config["sources"] if source["id"] == "powsybl")
    unique = {part["fileName"] for component in raw for part in component.get("subComponents", [])}
    if len(raw) != powsybl["expected_components"] or len(unique) != powsybl["expected_svgs"]:
        raise ValueError("Catalogue count mismatch")
    sources = []
    for source in config["sources"]:
        item = {key: source[key] for key in ("id", "title", "kind", "revision", "licence", "url")}
        item.update(status="acquired", production_enabled=False, standards_status="unverified",
                    files=[entry for entry in lock["files"] if entry["source_id"] == source["id"]])
        sources.append(item)
    return {"schema_version": "1.0", "production_enabled": False, "standards_status": "unverified",
            "components": sorted(components, key=lambda item: item["id"]), "sources": sources,
            "assets": {"css": "upstream/powsybl/components.css"},
            "counts": {"components": len(raw), "svg_files": len(unique)},
            "networks": [{"id": "send", "source_id": "send", "format": "OpenDSS",
                          "execution_allowed": False, "production_enabled": False,
                          "files": [entry["path"] for entry in lock["files"] if entry.get("archive_member")]}],
            "references": config["references"]}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data", type=Path, default=ROOT / "data")
    parser.add_argument("--config", type=Path, default=ROOT / "sources.yaml")
    args = parser.parse_args()
    result = build(json.loads(args.config.read_text(encoding="utf-8")), args.data)
    path = args.data / "library.json"
    path.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
    print(f"Built {path}: {result['counts']}")


if __name__ == "__main__":
    main()

Single-Line Diagram (SLD) Build Site

A Python command-line tool in the scripts folder that works with local file (`local_file`). It is built from the safe SVG helper (`safe_svg`) and the build step (`build`).

ingestsld / scripts/build_site.py · lines 1–113 of 113 · Entry point · pattern local_file (shared by 2 files)

What it does
It loads data. Defines local_file, safe_svg, build. Uses libraries pathlib, argparse, copy, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file library.json; command-line arguments.
Downstream impact
Used directly by 1 file: Single-Line Diagram (SLD) Pages Workflow (sld).
What it achieves
Build safe, local educational previews from the pinned component catalogue. It accepts `--out`.
Why it matters
Run by Single-Line Diagram (SLD) Pages Workflow.
Application
sld · scripts · Python CLI
Uses
pathlib, argparse, copy, json, re, shutil, xml.etree.ElementTree
Used by
run by Single-Line Diagram (SLD) Pages Workflow (workflow run)
Produces
local_file, safe_svg, build
Defines here
local_file, safe_svg, build
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/build_site.py:1-113 · blob 67c2878ac98d63d4467d1ff956605b21cc0c0d12 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Build safe, local educational previews from the pinned component catalogue.

Source files are never rewritten. The generated previews are derivatives and retain
PowSyBl's MPL-2.0 attribution. Electrical terminals are not inferred from anchors.
"""
from pathlib import Path
import argparse
import copy
import json
import re
import shutil
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
OUT = ROOT / "assets" / "previews"
NS = "http://www.w3.org/2000/svg"
ET.register_namespace("", NS)
ALLOWED = {"svg", "g", "path", "circle", "ellipse", "line", "polyline", "polygon", "rect", "text", "tspan", "title", "desc", "defs", "clipPath"}


def local_file(relative):
    path = (DATA / relative).resolve()
    if not path.is_relative_to(DATA.resolve()):
        raise ValueError("Asset path leaves data directory")
    return path


def safe_svg(path):
    raw = path.read_bytes()
    if b"<!DOCTYPE" in raw.upper() or b"<!ENTITY" in raw.upper():
        raise ValueError(f"DTD/entity rejected: {path}")
    root = ET.fromstring(raw)
    for node in root.iter():
        tag = node.tag.split("}")[-1]
        if tag not in ALLOWED:
            raise ValueError(f"Unsupported SVG element {tag}: {path}")
        for key, value in node.attrib.items():
            attr = key.split("}")[-1].lower()
            if attr.startswith("on") or attr in {"href", "src"} or "url(" in value.lower() or "javascript:" in value.lower():
                raise ValueError(f"Unsafe SVG attribute: {path}")
    return root


def build():
    library = json.loads((DATA / "library.json").read_text(encoding="utf-8"))
    css = local_file(library["assets"]["css"]).read_text(encoding="utf-8")
    if re.search(r"url\s*\(|@import|</style", css, re.I):
        raise ValueError("External/embedded content in upstream CSS")
    OUT.mkdir(parents=True, exist_ok=True)
    count = 0
    for c in library["components"]:
        name = c["type"]
        if not re.fullmatch(r"[A-Z0-9_]+", name):
            raise ValueError("Invalid component type")
        width = float(c.get("size", {}).get("width", 20)) or 20
        height = float(c.get("size", {}).get("height", 20)) or 20
        if not (0 < width < 10000 and 0 < height < 10000):
            raise ValueError("Invalid component dimensions")
        subs = c.get("subComponents", [])
        variants = ["closed", "open"] if any(s.get("name") == "OPEN" for s in subs) else ["closed"]
        for state in variants:
            root = ET.Element(f"{{{NS}}}svg", {"viewBox":f"-12 -12 {width+24:g} {height+24:g}", "width":"160", "height":"100", "role":"img"})
            ET.SubElement(root, f"{{{NS}}}title").text = f"{name}: research preview ({state})"
            ET.SubElement(root, f"{{{NS}}}desc").text = "Derived from PowSyBl ConvergenceLibrary, MPL-2.0. Not engineering approved."
            ET.SubElement(root, f"{{{NS}}}style").text = css
            outer = ET.SubElement(root, f"{{{NS}}}g", {"class":f"{c.get('styleClass','')} sld-{state}"})
            for sub in subs:
                if sub.get("name") in {"OPEN", "CLOSED"} and sub["name"].lower() != state:
                    continue
                # Directional arrow alternatives must not be overlaid.
                if sub.get("name") == "DOWN" and any(s.get("name") == "UP" for s in subs):
                    continue
                source = safe_svg(local_file(sub["asset_path"]))
                group = ET.SubElement(outer, f"{{{NS}}}g", {"class":sub.get("styleClass", "")})
                # Preserve root attributes affecting geometry as well as child transforms.
                for attr in ("transform", "style", "fill", "stroke", "stroke-width"):
                    if attr in source.attrib:
                        group.set(attr, source.attrib[attr])
                for child in source:
                    group.append(copy.deepcopy(child))
            if not subs:
                if name == "BUSBAR_SECTION":
                    ET.SubElement(outer, f"{{{NS}}}line", {"x1":"0", "y1":str(height/2), "x2":str(width), "y2":str(height/2), "stroke":"#172a16", "stroke-width":"3"})
                elif name == "TEE_POINT":
                    ET.SubElement(outer, f"{{{NS}}}path", {"d":f"M0,{height/2} H{width} M{width/2},{height/2} V{height}","stroke":"#172a16","fill":"none"})
                    ET.SubElement(outer, f"{{{NS}}}circle", {"cx":str(width/2), "cy":str(height/2), "r":"2", "fill":"#172a16"})
                else:
                    ET.SubElement(outer, f"{{{NS}}}text", {"x":str(width/2), "y":str(height/2), "text-anchor":"middle", "font-size":"8", "fill":"#172a16"}).text = "? %" if "PERCENTAGE" in name else "? A"
            out = OUT / f"{name}{'-open' if state == 'open' else ''}.svg"
            ET.ElementTree(root).write(out, encoding="utf-8", xml_declaration=True)
            count += 1
    print(f"Built {count} local previews for {len(library['components'])} components.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--out", help="Optional deployment directory beneath repository root")
    args = parser.parse_args()
    build()
    if args.out:
        destination = (ROOT / args.out).resolve()
        if not destination.is_relative_to(ROOT) or destination == ROOT or destination.parts[len(ROOT.parts)] in {"assets", "data", "docs", "scripts", "tests", ".git"}:
            raise ValueError("Output must be a separate directory beneath repository root")
        destination.mkdir(parents=True, exist_ok=True)
        # Explicit allowlist excludes git metadata, scripts, credentials and local runtime files.
        for name in ("index.html", "LICENSE", "README.md"):
            if (ROOT / name).is_file():
                shutil.copy2(ROOT / name, destination / name)
        for name in ("assets", "data", "docs"):
            if (ROOT / name).is_dir():
                shutil.copytree(ROOT / name, destination / name, dirs_exist_ok=True)
        print(f"Packaged static site at {destination}")