In this section
- Arrival transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/arrival.mjs lines 1–38
- Attribution transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/attribution.mjs lines 1–75
- Buffers UI ingest · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/buffers-ui.mjs lines 1–58
- Clash transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/clash.mjs lines 1–149
- Design Store render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/design-store.mjs lines 1–377
Arrival
A JavaScript module in the world folder of GlobalGrid2050. It is built from the ease step (`ease`), the turn step (`turn`) and the arrive step (`arrive`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/arrival.mjs · lines 1–38 of 38 · version 2026-09-27 00:05 · Entry point · pattern finished (shared by 2 files)
- What it does
- It calculates its inputs. Defines ease, turn, arrive, finished, pose.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 5 files: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050); and 1 more. Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
- What it achieves
- Fly the camera from where it is now to hover above a target, looking down on it.
- Why it matters
- Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by Substrate, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), imported by Substrate (import), mentioned in Standalone (comment link)
- Produces
- arrive
- Defines here
- ease, turn, arrive, finished, pose
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/arrival.mjs:1-38 · blob 5b634d1575c5cf8b1838313164a9641b10b8e98d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Arrival: fly the camera from where it is now to hover above a target, looking down on it.
// Pure: no imports, no DOM. The caller supplies time; this only says where the camera should be.
// Matches views.mjs PITCH_LIMIT, so the pose we finish in is one the look controls can hold.
const DOWN = -(Math.PI / 2 - 0.01);
// Smooth start and smooth stop: zero speed and zero acceleration at both ends.
const ease = u => u * u * u * (u * (u * 6 - 15) + 10);
// The shortest way round from one heading to another, in radians.
const turn = (from, to) => {
const d = (to - from) % (2 * Math.PI);
return d > Math.PI ? d - 2 * Math.PI : d < -Math.PI ? d + 2 * Math.PI : d;
};
// state: { pos: [x, y, z], yaw, pitch }. target: local [x, y] or [x, y, groundZ].
// Returns pose(t) for t in seconds since the arrival began, giving { pos, yaw, pitch }.
// pose.done(t) says whether it has finished; pose.end is the exact final pose.
// The heading is kept by default, so the ground does not spin under the viewer.
export function arrive(state, target, { height = 120, seconds = 3, yaw = state.yaw, pitch = DOWN } = {}) {
const from = { pos: [...state.pos], yaw: state.yaw, pitch: state.pitch };
const end = Object.freeze({ pos: Object.freeze([target[0], target[1], (target[2] ?? 0) + height]), yaw, pitch });
const dyaw = turn(from.yaw, yaw);
const finished = t => !(seconds > 0) || t >= seconds;
const pose = t => {
if (finished(t)) return { pos: [...end.pos], yaw: end.yaw, pitch: end.pitch };
const k = ease(Math.max(0, t) / seconds);
return {
pos: from.pos.map((p, i) => p + (end.pos[i] - p) * k),
yaw: from.yaw + dyaw * k,
pitch: from.pitch + (end.pitch - from.pitch) * k
};
};
pose.done = finished;
pose.end = end;
pose.seconds = seconds;
return pose;
}Attribution
A JavaScript module in the world folder of GlobalGrid2050 that works with unknown layers (`unknownLayers`) and fill year (`fillYear`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/attribution.mjs · lines 1–75 of 75 · version 2026-09-27 00:05 · Entry point · pattern footerText (shared by 2 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including sourcesFor, unknownLayers, fillYear, licenceOf, footerEntry.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 9 files: Print Sheet (globalgrid2050); Layers UI (globalgrid2050); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050); and 5 more. Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
- What it achieves
- It is built from the sources for helper (`sourcesFor`), the unknown layers helper (`unknownLayers`) and the fill year helper (`fillYear`). Attribution small print, GridAtlas style: credit exactly the data that is on screen.
- Why it matters
- Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by 7 files, including Print Sheet, Layers UI and Substrate, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Print Sheet (import), imported by Layers UI (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Substrate (import), imported by Layers UI (import), imported by Print Sheet (import), preloaded by Solar Design Studio — Site World Page (modulepreload), imported by Substrate (import), and 1 more, mentioned in Standalone (comment link)
- Produces
- sourcesFor, unknownLayers, footerEntry, footerText, aboutList
- Defines here
- sourcesFor, unknownLayers, fillYear, licenceOf, footerEntry, footerText, aboutList
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/attribution.mjs:1-75 · blob db8568b7d157944cf530d16d03846d789a25848d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Attribution small print, GridAtlas style: credit exactly the data that is on screen.
// Pure: no DOM, no fetch. Input is data/attribution.json (see ATTRIBUTION.md).
const SEP = ' · ';
// Source ids used by the loaded layers, in the stable order of attribution.sources.
export function sourcesFor(loadedLayerIds, attribution) {
const wanted = new Set();
for (const layerId of loadedLayerIds || []) {
for (const sid of attribution.layers?.[layerId] || []) wanted.add(sid);
}
return Object.keys(attribution.sources || {}).filter((sid) => wanted.has(sid));
}
// Layer ids the attribution file does not know about (a new layer with no credit entry).
export function unknownLayers(loadedLayerIds, attribution) {
return (loadedLayerIds || []).filter((id) => !(id in (attribution.layers || {})));
}
function fillYear(text, src, year) {
const y = src.year ?? year ?? new Date().getUTCFullYear();
return text.replaceAll('{year}', String(y));
}
function licenceOf(src, attribution) {
return attribution.licences?.[src.licence] || { short: src.licence, long: src.licence, url: src.licence_url || null };
}
// One compact footer entry: the short form if given, else the required line, plus the
// licence short name when the text does not already name the licence.
export function footerEntry(src, attribution, year) {
const lic = licenceOf(src, attribution);
const text = fillYear(src.short || src.line, src, year); // required wording kept exact
const named = [lic.short, lic.long].some((n) => n && text.includes(n));
return named ? text : `${text} (${lic.short})`;
}
// One line for the bottom of the screen, for exactly the loaded layers.
export function footerText(loadedLayerIds, attribution, { year } = {}) {
const seen = new Set();
const out = [];
for (const sid of sourcesFor(loadedLayerIds, attribution)) {
const src = attribution.sources[sid];
if (!src.on_screen) continue;
const entry = footerEntry(src, attribution, year);
if (seen.has(entry)) continue; // e.g. OS Open Rivers and OS Open Roads share one OS line
seen.add(entry);
out.push(entry);
}
return out.join(SEP);
}
// Longer list for the Controls/About panel: full required line, source, licence, links, layers.
export function aboutList(loadedLayerIds, attribution, { year } = {}) {
const loaded = loadedLayerIds || [];
return sourcesFor(loaded, attribution)
.filter((sid) => attribution.sources[sid].on_screen)
.map((sid) => {
const src = attribution.sources[sid];
const lic = licenceOf(src, attribution);
const layers = loaded.filter((l) => (attribution.layers[l] || []).includes(sid));
const notes = layers.map((l) => attribution.layer_notes?.[l]).filter(Boolean);
return {
id: sid,
name: src.name,
line: fillYear(src.line, src, year),
licence: lic.short,
licence_name: lic.long,
licence_url: lic.url || src.licence_url || null,
link: src.link,
layers,
notes: [...new Set(notes)],
};
});
}Buffers UI
A JavaScript module in the world folder of GlobalGrid2050 that fetches cables, using SHA-256.
ingestglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/buffers-ui.mjs · lines 1–58 of 58 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern loadWorldFiles (shared by 2 files)
- What it does
- It fetches cables. Defines 8 functions or classes, including worldFrom, drawnItems, local, loadWorldFiles, cfg. Side effects: makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- What it achieves
- It loads world files (`loadWorldFiles`) and is built from the world from helper (`worldFrom`) and the drawn items helper (`drawnItems`). Page wiring for the Buffers layer.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- Buffers (import), Layers (import)
- Used by
- mentioned in Standalone (comment link)
- Produces
- worldFrom, drawnItems, loadWorldFiles, mountBuffers
- Defines here
- worldFrom, drawnItems, local, loadWorldFiles, cfg, get, mountBuffers, refresh
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/buffers-ui.mjs:1-58 · blob f52a4cca255b5a5bac3aa7e1654de0249a580e8a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// Page wiring for the Buffers layer. While it is switched on, the zones are worked out (buffers.mjs) from the site's
// own data files, fetched through the same hash check as the layers that draw them (the manifest's configs for grid,
// water, ways and canopy hedges), and the drawn design is checked against them (clash.mjs). Zones are local metres,
// so they are rebuilt when the origin moves; clashes are rebuilt when a trench or cable is finished.
import { buildZones, checkClashes } from './buffers.mjs';
import { makeApi } from './layers.mjs';
// The world lists buildZones takes, from the files as the layers read them. Missing files give empty lists.
export function worldFrom({ grid, rivers, roads, hedges } = {}) {
return {
overhead: (grid?.lines || []).filter(l => Array.isArray(l.points)),
water: (rivers?.lines || []).filter(l => Array.isArray(l.points)),
roads: (roads?.lines || []).filter(l => Array.isArray(l.pts)),
hedges: (hedges?.lines || []).filter(l => Array.isArray(l.pts)),
};
}
// Drawn trenches and cables (national-grid paths [{ e, n }]) as clash items in local metres.
export function drawnItems(design, origin) {
const local = path => (path || []).map(p => [p.e - origin.e, p.n - origin.n]);
return [
...(design?.trenches || []).map((t, i) => ({ id: `trench-${i + 1}`, kind: 'trench', points: local(t.path) })),
...(design?.cables || []).map((c, i) => ({ id: `cable-${i + 1}`, kind: 'trench', points: local(c.path) })),
].filter(it => it.points.length >= 2);
}
// Fetches the site files named in the manifest; each one is checked against its SHA-256 before it is used.
export async function loadWorldFiles(manifestUrl, api = null) {
const base = new URL(manifestUrl, location.href);
const manifest = await (await fetch(base, { cache: 'no-cache' })).json();
const a = api || makeApi(new URL('./', base).href);
const cfg = id => (manifest.layers || []).find(l => l.id === id)?.config || null;
const get = c => (c && (c.path || c.index) && c.sha256 ? a.fetchJSON(c.path || c.index, c.sha256).catch(() => null) : null);
const canopy = cfg('canopy');
const [grid, rivers, roads, canopyIndex] = await Promise.all([get(cfg('grid')), get(cfg('water')), get(cfg('ways')?.roads), get(canopy)]);
let hedges = null;
if (canopyIndex?.hedges?.file && canopyIndex.hedges.sha256) {
const dir = canopy.index.slice(0, canopy.index.lastIndexOf('/') + 1);
hedges = await a.fetchJSON(dir + canopyIndex.hedges.file, canopyIndex.hedges.sha256).catch(() => null);
}
return { grid, rivers, roads, hedges };
}
// layer: the buffers layer object. origin(): { e, n, id }. design(): the design in memory. load(): the world files.
// Returns { refresh(on) }: call it after the layer is switched and on a steady tick.
export function mountBuffers({ layer, origin, design, load = () => loadWorldFiles('./world/manifest.json') } = {}) {
if (!layer || typeof layer.setZones !== 'function') return null;
let files = null, loading = null, zonesKey = '', clashKey = '', zones = [];
const refresh = on => {
if (!on) return;
if (!files) { loading ||= Promise.resolve().then(load).then(f => { files = f; refresh(true); }, e => console.warn('buffers: ' + e.message)); return; }
const o = origin(), d = design(), zk = `${o.e},${o.n}`;
if (zk !== zonesKey) { zones = buildZones(worldFrom(files), { origin: o }); layer.setZones(zones); zonesKey = zk; clashKey = ''; }
const ck = `${zk}@${d.trenches.length}@${d.cables.length}`;
if (ck !== clashKey) { layer.setClashes(checkClashes(drawnItems(d, o), zones)); clashKey = ck; }
};
return { refresh };
}Clash
A JavaScript module in the world folder of GlobalGrid2050 that works with segs cross (`segsCross`) and dist to geometry (`distToGeometry`) and calculates planar distances.
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/clash.mjs · lines 1–149 of 149 · version 2026-09-27 00:05 · pattern chainage (shared by 3 files)
- What it does
- It calculates its inputs. Defines 17 functions or classes, including closestOnSeg, segsCross, o, segsOf, distToGeometry.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 3 files: Buffers (globalgrid2050); Overhead Line (OHL) Zones (globalgrid2050); Cmd Run (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It checks clashes (`checkClashes`) and is built from the closest on seg helper (`closestOnSeg`) and the segs cross helper (`segsCross`). Clash check: where a drawn trench, road, pad or table enters a buffer zone, with the rule and its sources.
- Why it matters
- Imported by Buffers, Overhead Line (OHL) Zones and Cmd Run.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- Offset (import)
- Used by
- imported by Buffers (import), imported by Overhead Line (OHL) Zones (import), imported by Cmd Run (import), mentioned in Standalone (comment link)
- Produces
- ITEM_WIDTH, STEP_M, distToGeometry, geometryDistance, itemGeometry, insideStretches, checkClashes
- Defines here
- closestOnSeg, segsCross, o, segsOf, distToGeometry, geometryDistance, take, crossing, itemGeometry, chainage, pointAt, insideStretches, f, at, edge, r2, checkClashes
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/clash.mjs:1-149 · blob 9560ea98993875a3a2820259c5f1c81d7942e650 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Clash check: where a drawn trench, road, pad or table enters a buffer zone, with the rule and its sources.
// Pure: no DOM. Zones come from buildZones (buffers.mjs). The check is exact: it measures the true distance
// from the item to the zone's feature and compares it with the zone distance plus the item's half-width. The
// drawn zone outline is a polygon a little outside the exact zone (see offset.mjs), so an item that just
// touches the dashed line may pass here; the numbers here are the ones to trust.
//
// Items: { id, kind: 'trench' | 'road', points: [[x, y], ...], width? } a path with a width
// { id, kind: 'pad' | 'table', points: [[x, y], ...] } a footprint outline
// Widths missing from a path fall back to ITEM_WIDTH, flagged as assumed in the report.
import { cleanPath, pointInRing } from './offset.mjs';
export const ITEM_WIDTH = { trench: 0.6, road: 4 }; // ASSUMED widths of drawn items without one, metres
export const STEP_M = 0.5; // path sampling for entry and exit chainages
const AREA_KINDS = new Set(['pad', 'table']);
function closestOnSeg(px, py, a, b) {
const dx = b[0] - a[0], dy = b[1] - a[1], L2 = dx * dx + dy * dy;
const t = L2 ? Math.max(0, Math.min(1, ((px - a[0]) * dx + (py - a[1]) * dy) / L2)) : 0;
return [a[0] + dx * t, a[1] + dy * t];
}
function segsCross(a, b, c, d) {
const o = (p, q, r) => Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]));
return o(a, b, c) * o(a, b, d) < 0 && o(c, d, a) * o(c, d, b) < 0;
}
function segsOf(g) {
const p = g.pts, closed = g.closed || g.area, out = [];
if (p.length === 1) return [[p[0], p[0]]];
for (let i = 0; i < (closed ? p.length : p.length - 1); i++) out.push([p[i], p[(i + 1) % p.length]]);
return out;
}
// Pure: distance from a point to a geometry { pts, closed?, area? } (0 inside an area).
export function distToGeometry(g, x, y) {
if (g.area && g.pts.length > 2 && pointInRing(g.pts, x, y)) return 0;
let best = Infinity;
for (const [a, b] of segsOf(g)) { const c = closestOnSeg(x, y, a, b); best = Math.min(best, Math.hypot(x - c[0], y - c[1])); }
return best;
}
// Pure: least distance between two geometries, and the point on the first where it is reached.
export function geometryDistance(g, h) {
const A = segsOf(g), B = segsOf(h);
for (const [a, b] of A) for (const [c, d] of B) if (segsCross(a, b, c, d)) return { d: 0, at: crossing(a, b, c, d) };
if (h.area && h.pts.length > 2 && pointInRing(h.pts, g.pts[0][0], g.pts[0][1])) return { d: 0, at: g.pts[0] };
if (g.area && g.pts.length > 2 && pointInRing(g.pts, h.pts[0][0], h.pts[0][1])) return { d: 0, at: h.pts[0] };
let best = { d: Infinity, at: null };
const take = (dd, at) => { if (dd < best.d) best = { d: dd, at }; };
for (const [a, b] of A) for (const [c, d] of B) {
for (const p of [a, b]) { const q = closestOnSeg(p[0], p[1], c, d); take(Math.hypot(p[0] - q[0], p[1] - q[1]), p); }
for (const p of [c, d]) { const q = closestOnSeg(p[0], p[1], a, b); take(Math.hypot(p[0] - q[0], p[1] - q[1]), q); }
}
return best;
}
function crossing(a, b, c, d) {
const rx = b[0] - a[0], ry = b[1] - a[1], sx = d[0] - c[0], sy = d[1] - c[1];
const t = ((c[0] - a[0]) * sy - (c[1] - a[1]) * sx) / (rx * sy - ry * sx);
return [a[0] + rx * t, a[1] + ry * t];
}
// Pure: an item's core geometry and half-width. Paths keep their centreline; pads and tables their outline.
export function itemGeometry(item) {
const area = AREA_KINDS.has(item.kind);
const pts = cleanPath((item.points || item.pts || []).map(p => [p[0], p[1]]), area);
if (area) return { core: { pts, closed: true, area: true }, half: 0, widthAssumed: false };
const given = +item.width > 0, width = given ? +item.width : ITEM_WIDTH[item.kind] ?? ITEM_WIDTH.trench;
return { core: { pts, closed: false, area: false }, half: width / 2, width, widthAssumed: !given };
}
// Pure: chainages along a path; the point at chainage s.
function chainage(pts) {
const c = [0];
for (let i = 1; i < pts.length; i++) c.push(c[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
return c;
}
function pointAt(pts, cum, s) {
let i = 1;
while (i < pts.length - 1 && cum[i] < s) i++;
const f = cum[i] > cum[i - 1] ? Math.max(0, Math.min(1, (s - cum[i - 1]) / (cum[i] - cum[i - 1]))) : 0;
return [pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * f, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * f];
}
// Pure: stretches of a path whose centreline comes within reach of the geometry: [{ from_m, to_m }].
// Sampled every step metres (and at every vertex), each end refined by bisection to a millimetre.
export function insideStretches(pts, g, reach, step = STEP_M) {
const cum = chainage(pts), L = cum[cum.length - 1];
const f = s => { const p = pointAt(pts, cum, s); return distToGeometry(g, p[0], p[1]) - reach; };
const ss = new Set(cum);
for (let s = 0; s < L; s += step) ss.add(s);
// The distance can dip below reach only around its minima: where a feature vertex projects onto the path, or
// where a feature edge crosses it. Sampling those too means no narrow zone slips between two steps.
const G = segsOf(g);
for (let i = 1; i < pts.length; i++) {
const a = pts[i - 1], b = pts[i], len = cum[i] - cum[i - 1];
if (!(len > 0)) continue;
const at = q => ss.add(cum[i - 1] + Math.hypot(q[0] - a[0], q[1] - a[1]));
for (const p of g.pts) at(closestOnSeg(p[0], p[1], a, b));
for (const [c, d] of G) if (segsCross(a, b, c, d)) at(crossing(a, b, c, d));
}
const S = [...ss].sort((a, b) => a - b);
const edge = (lo, hi) => { let flo = f(lo) < 0; while (hi - lo > 1e-3) { const m = (lo + hi) / 2; if ((f(m) < 0) === flo) lo = m; else hi = m; } return (lo + hi) / 2; };
const out = [];
let open = f(0) < 0 ? 0 : null;
for (let i = 1; i < S.length; i++) {
const inNow = f(S[i]) < 0;
if (open === null && inNow) open = edge(S[i - 1], S[i]);
else if (open !== null && !inNow) { out.push({ from_m: open, to_m: edge(S[i - 1], S[i]) }); open = null; }
}
if (open !== null) out.push({ from_m: open, to_m: L });
return out.map(r => ({ ...r, at: pointAt(pts, cum, r.from_m) }));
}
const r2 = v => Math.round(v * 100) / 100;
// Pure: every place a drawn item enters a zone. A drawn item's own zone is skipped.
// Returns [{ item, itemKind, zone, layer, rule, kind, required_m, clearance_m, intrusion_m, at, stretches, parts,
// sources, note, widthAssumed, message }], deepest first per item.
export function checkClashes(items, zones, { step = STEP_M } = {}) {
const out = [];
for (const item of Array.isArray(items) ? items : []) {
if (!item) continue;
const { core, half, widthAssumed } = itemGeometry(item);
if (!core.pts.length) continue;
const found = [];
for (const z of zones) {
if (z.layer === 'drawn' && String(z.feature) === String(item.id)) continue;
const reach = z.distance + half, g = geometryDistance(core, z.geometry);
if (!(g.d < reach - 1e-9)) continue;
const stretches = core.area ? [] : insideStretches(core.pts, z.geometry, reach, step);
const at = stretches.length ? stretches[0].at : g.at;
const clearance = Math.max(0, g.d - half);
const sources = [...new Set(z.parts.map(p => p.source))];
const where = stretches.length ? ` from ${r2(stretches[0].from_m)} m to ${r2(stretches[0].to_m)} m along it` : '';
found.push({
item: item.id, itemKind: item.kind, zone: z.id, layer: z.layer, rule: z.rule, kind: z.kind,
required_m: r2(z.distance), clearance_m: r2(clearance), intrusion_m: r2(reach - g.d), at: [r2(at[0]), r2(at[1])], stretches,
parts: z.parts, sources, note: z.note, widthAssumed,
message: `${item.kind || 'item'} ${item.id ?? ''} enters the ${z.rule} zone of ${z.id}${where}: ${r2(clearance)} m from the feature, `
+ `${r2(z.distance)} m required (${z.kind}; ${z.parts.map(p => `${p.m} m ${p.what}, ${p.kind}`).join('; ')})`
+ (widthAssumed ? '. Item width assumed' : '')
});
}
out.push(...found.sort((a, b) => b.intrusion_m - a.intrusion_m));
}
return out;
}Design Store
A JavaScript module in the world folder of GlobalGrid2050 that hashes doc (`hashDoc`), creates doc (`createDoc`) and checks params (`checkParams`), using SHA-256.
renderglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/design-store.mjs · lines 1–377 of 377 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern downloadFile (shared by 2 files)
- What it does
- It draws its content. Defines 33 functions or classes, including mm, isObj, canonicalJson, sha256Hex, hashDoc. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 2 files: Project UI (globalgrid2050); Project UI (globalgrid2050).
- What it achieves
- It hashes doc (`hashDoc`), creates doc (`createDoc`) and checks params (`checkParams`). The versioned design document for everything drawn in the world.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import), imported by Project UI (import), mentioned in Standalone (comment link)
- Produces
- SCHEMA, KNOWN_SCHEMAS, LINK_KEY, LINK_VERSION, LIMITS, canonicalJson, sha256Hex, hashDoc, createDoc, validateDoc, normaliseDoc, pointsFromLocal
- Defines here
- mm, isObj, canonicalJson, sha256Hex, hashDoc, createDoc, checkParams, checkPoints, validateDoc, normaliseItem, normaliseDoc, pointsFromLocal, pointsToLocal, itemsToLocal, itemFromLocal, applyOp, at, createHistory, bump, exportFile, downloadFile, importText, b64url, unb64url, pump, makeShareLink, readShareLink, storageKey, pickStorage, noStorage
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/design-store.mjs:1-377 · blob e0d16ead19ce053637d04f4e008de65db1d49e49 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// design-store.mjs: the versioned design document for everything drawn in the world.
// Pure: no imports, no DOM. Browser facilities (crypto.subtle, CompressionStream, localStorage)
// are reached through globalThis or passed in, and every one of them may be missing.
//
// THE DOCUMENT
// { schema: 'world.design.v1', generation, site: { name, origin_e, origin_n },
// items: [{ id, kind, params, points_bng: [[e, n] | [e, n, z], ...] }] }
// Every coordinate is British National Grid metres, rounded to the millimetre. Local metres
// never enter the document: the viewer's origin moves (see origin.mjs) and a design stored in
// local metres would move with it. `kind` is open (trench, cable, road, pad, fence, hdd, pile,
// or anything later); `params` is any plain JSON object the kind needs.
// site.origin_e / origin_n record where the site was set up; they do not move the items.
//
// WHAT IT GUARANTEES
// Canonical JSON (sorted keys, no spaces, -0 written as 0) so the SHA-256 is the same on any
// machine. Import refuses an unknown schema by name and never guesses. Undo and redo keep
// whole snapshots; generation only ever goes up, so no two states share a generation.
export const SCHEMA = 'world.design.v1';
export const KNOWN_SCHEMAS = Object.freeze([SCHEMA]);
export const LINK_KEY = 'design';
export const LINK_VERSION = '1';
export const LIMITS = Object.freeze({
// points and fileBytes agree: 200,000 points of three coordinates export to well under 8 MB.
items: 20000, pointsPerItem: 100000, points: 200000, paramsDepth: 8,
fileBytes: 8 * 1024 * 1024, linkChars: 8000, linkInflatedBytes: 2 * 1024 * 1024, history: 200
});
// National Grid extent with a margin: anything outside is a local-metre mistake, not a design.
const BNG = { eMin: -10000, eMax: 710000, nMin: -10000, nMax: 1310000 };
const KIND = /^[a-z][a-z0-9_-]{0,39}$/;
const ID = /^[A-Za-z0-9_.:-]{1,64}$/;
const mm = v => { const r = Math.round(v * 1000) / 1000; return r === 0 ? 0 : r; };
const isObj = v => v !== null && typeof v === 'object' && !Array.isArray(v);
// ---------- canonical JSON and hash ----------
export function canonicalJson(value) {
if (value === null) return 'null';
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('canonical JSON cannot hold a non-finite number');
return JSON.stringify(value === 0 ? 0 : value);
}
if (typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']';
if (isObj(value)) {
const keys = Object.keys(value).filter(k => value[k] !== undefined).sort();
return '{' + keys.map(k => JSON.stringify(k) + ':' + canonicalJson(value[k])).join(',') + '}';
}
throw new Error(`canonical JSON cannot hold a ${typeof value}`);
}
export async function sha256Hex(text) {
const subtle = globalThis.crypto?.subtle;
if (!subtle) throw new Error('SHA-256 is not available here (no crypto.subtle)');
const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));
return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}
// Hash of the whole document, generation included.
export const hashDoc = doc => sha256Hex(canonicalJson(doc));
// ---------- building and validating ----------
export function createDoc({ name = 'untitled', origin_e, origin_n } = {}) {
const doc = { schema: SCHEMA, generation: 0, site: { name: String(name), origin_e: mm(origin_e), origin_n: mm(origin_n) }, items: [] };
const v = validateDoc(doc);
if (!v.ok) throw new Error(v.errors.join('; '));
return doc;
}
const FORBIDDEN_KEYS = ['__proto__', 'constructor', 'prototype'];
function checkParams(p, depth, path, errors) {
if (depth > LIMITS.paramsDepth) { errors.push(`${path} nests deeper than ${LIMITS.paramsDepth}`); return; }
if (typeof p === 'number') { if (!Number.isFinite(p)) errors.push(`${path} is not a finite number`); return; }
if (p === null || typeof p === 'string' || typeof p === 'boolean') return;
if (Array.isArray(p)) { p.forEach((v, i) => checkParams(v, depth + 1, `${path}[${i}]`, errors)); return; }
if (isObj(p)) {
for (const k of Object.keys(p)) {
if (FORBIDDEN_KEYS.includes(k)) { errors.push(`${path} uses the reserved key "${k}"`); continue; }
checkParams(p[k], depth + 1, `${path}.${k}`, errors);
}
return;
}
errors.push(`${path} is not plain JSON`);
}
function checkPoints(pts, path, errors) {
if (!Array.isArray(pts)) { errors.push(`${path} is not a list`); return 0; }
if (pts.length > LIMITS.pointsPerItem) { errors.push(`${path} has ${pts.length} points, over ${LIMITS.pointsPerItem}`); return pts.length; }
for (let i = 0; i < pts.length; i++) {
const p = pts[i];
if (!Array.isArray(p) || (p.length !== 2 && p.length !== 3) || !p.every(Number.isFinite)) {
errors.push(`${path}[${i}] is not [e, n] or [e, n, z] in metres`); return pts.length;
}
if (p[0] < BNG.eMin || p[0] > BNG.eMax || p[1] < BNG.nMin || p[1] > BNG.nMax) {
errors.push(`${path}[${i}] (${p[0]}, ${p[1]}) is outside the National Grid; local metres are never stored`);
return pts.length;
}
}
return pts.length;
}
// Returns { ok, errors }. Checks shape, not meaning: the store does not know what a trench is.
export function validateDoc(doc) {
const errors = [];
if (!isObj(doc)) return { ok: false, errors: ['the design is not a JSON object'] };
if (typeof doc.schema !== 'string') errors.push('the design has no schema name');
else if (!KNOWN_SCHEMAS.includes(doc.schema)) {
errors.push(`unknown schema "${doc.schema}"; this viewer reads ${KNOWN_SCHEMAS.join(', ')} only`);
return { ok: false, errors };
}
if (!Number.isInteger(doc.generation) || doc.generation < 0) errors.push('generation is not a whole number from 0');
const s = doc.site;
if (!isObj(s)) errors.push('site is missing');
else {
if (typeof s.name !== 'string' || s.name.length > 200) errors.push('site.name is not a short text');
if (!Number.isFinite(s.origin_e) || s.origin_e < BNG.eMin || s.origin_e > BNG.eMax) errors.push('site.origin_e is not a National Grid easting');
if (!Number.isFinite(s.origin_n) || s.origin_n < BNG.nMin || s.origin_n > BNG.nMax) errors.push('site.origin_n is not a National Grid northing');
}
if (!Array.isArray(doc.items)) errors.push('items is not a list');
else {
if (doc.items.length > LIMITS.items) errors.push(`${doc.items.length} items, over the limit of ${LIMITS.items}`);
const seen = new Set();
let total = 0;
doc.items.forEach((it, i) => {
const at = `items[${i}]`;
if (!isObj(it)) { errors.push(`${at} is not an object`); return; }
if (typeof it.id !== 'string' || !ID.test(it.id)) errors.push(`${at}.id is not a short id`);
else if (seen.has(it.id)) errors.push(`${at}.id "${it.id}" is used twice`);
else seen.add(it.id);
if (typeof it.kind !== 'string' || !KIND.test(it.kind)) errors.push(`${at}.kind is not a lower-case name`);
if (!isObj(it.params)) errors.push(`${at}.params is not an object`);
else checkParams(it.params, 1, `${at}.params`, errors);
total += checkPoints(it.points_bng, `${at}.points_bng`, errors);
});
if (total > LIMITS.points) errors.push(`${total} points in all, over the limit of ${LIMITS.points}`);
}
const extra = isObj(doc) ? Object.keys(doc).filter(k => !['schema', 'generation', 'site', 'items'].includes(k)) : [];
if (extra.length) errors.push(`unexpected fields: ${extra.join(', ')}`);
return { ok: errors.length === 0, errors };
}
// A clean copy: points rounded to the millimetre, params deep-copied through JSON.
function normaliseItem(it) {
return {
id: it.id, kind: it.kind,
params: JSON.parse(canonicalJson(it.params ?? {})),
points_bng: (it.points_bng ?? []).map(p => p.map(mm))
};
}
// The stored form of a valid document: fields in order, coordinates to the millimetre.
export const normaliseDoc = doc => ({
schema: doc.schema, generation: doc.generation,
site: { name: doc.site.name, origin_e: mm(doc.site.origin_e), origin_n: mm(doc.site.origin_n) },
items: doc.items.map(normaliseItem)
});
// ---------- local metres <-> grid metres ----------
// `origin` is the viewer's live origin { e, n } (origin.mjs), which may differ from site.origin.
export const pointsFromLocal = (origin, pts) => pts.map(([x, y, z]) =>
z === undefined ? [mm(origin.e + x), mm(origin.n + y)] : [mm(origin.e + x), mm(origin.n + y), mm(z)]);
export const pointsToLocal = (origin, pts) => pts.map(([e, n, z]) =>
z === undefined ? [e - origin.e, n - origin.n] : [e - origin.e, n - origin.n, z]);
// Every item with points in local metres around `origin`, ready to draw.
export const itemsToLocal = (doc, origin) =>
doc.items.map(it => ({ id: it.id, kind: it.kind, params: it.params, points: pointsToLocal(origin, it.points_bng) }));
// Item from a tool working in local metres: { id, kind, params, points } -> stored item.
export const itemFromLocal = (origin, { id, kind, params = {}, points }) =>
({ id, kind, params, points_bng: pointsFromLocal(origin, points) });
// ---------- edits and history ----------
// Pure edit. op: { op: 'add', item } | { op: 'update', id, params?, points_bng? } |
// { op: 'remove', id } | { op: 'site', site: { name?, origin_e?, origin_n? } }. Throws on a bad edit.
export function applyOp(doc, op) {
let items = doc.items, site = doc.site;
const at = id => { const i = items.findIndex(it => it.id === id); if (i < 0) throw new Error(`no item "${id}"`); return i; };
if (op?.op === 'add') items = [...items, normaliseItem(op.item ?? {})];
else if (op?.op === 'update') {
const i = at(op.id), cur = items[i];
const next = normaliseItem({ ...cur, ...(op.params ? { params: op.params } : {}), ...(op.points_bng ? { points_bng: op.points_bng } : {}) });
items = items.map((it, j) => (j === i ? next : it));
} else if (op?.op === 'remove') { const i = at(op.id); items = items.filter((_, j) => j !== i); }
else if (op?.op === 'site') {
const s = { ...site, ...op.site };
site = { name: String(s.name), origin_e: mm(s.origin_e), origin_n: mm(s.origin_n) };
} else throw new Error(`unknown edit "${op?.op}"`);
const next = { schema: doc.schema, generation: doc.generation + 1, site, items };
const v = validateDoc(next);
if (!v.ok) throw new Error(v.errors.join('; '));
return next;
}
// Snapshot history. Undo and redo give the earlier or later content a new, higher generation.
export function createHistory(doc, { limit = LIMITS.history } = {}) {
const v = validateDoc(doc);
if (!v.ok) throw new Error(v.errors.join('; '));
let current = doc;
const past = [], future = [];
const bump = d => ({ ...d, generation: current.generation + 1 });
return {
get doc() { return current; },
get canUndo() { return past.length > 0; },
get canRedo() { return future.length > 0; },
apply(op) {
const next = applyOp(current, op);
past.push(current); if (past.length > limit) past.shift();
future.length = 0; current = next; return current;
},
undo() { if (!past.length) return null; future.push(current); current = bump(past.pop()); return current; },
redo() { if (!future.length) return null; past.push(current); current = bump(future.pop()); return current; },
// Replace everything (an import): undoable back to what was there.
replace(d) {
const r = validateDoc(d); if (!r.ok) throw new Error(r.errors.join('; '));
past.push(current); if (past.length > limit) past.shift();
future.length = 0; current = { ...d, generation: Math.max(d.generation, current.generation + 1) }; return current;
}
};
}
// ---------- export and import ----------
// The file: canonical JSON of the document plus "sha256" of the document without it.
export async function exportFile(doc) {
const v = validateDoc(doc);
if (!v.ok) throw new Error(v.errors.join('; '));
doc = normaliseDoc(doc);
const sha256 = await hashDoc(doc);
const safe = doc.site.name.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-|-$/g, '') || 'design';
const text = canonicalJson({ ...doc, sha256 }) + '\n', bytes = new TextEncoder().encode(text).length;
if (bytes > LIMITS.fileBytes) throw new Error(`the design file would be ${bytes} bytes, over the limit of ${LIMITS.fileBytes}`);
return { filename: `${safe}-g${doc.generation}.design.json`, mime: 'application/json', text, sha256 };
}
// Browser helper; the DOM pieces are passed in so this file stays pure.
export async function downloadFile(doc, { document = globalThis.document, URL = globalThis.URL, Blob = globalThis.Blob } = {}) {
const f = await exportFile(doc);
const url = URL.createObjectURL(new Blob([f.text], { type: f.mime }));
const a = document.createElement('a');
a.href = url; a.download = f.filename; a.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
return f;
}
// Returns { ok: true, doc, sha256 } or { ok: false, errors }. Never throws on bad input.
// A file must carry its sha256; only this viewer's own copies (autosave, share links with their own checksum) may omit it.
export async function importText(text, { maxBytes = LIMITS.fileBytes, unsigned = false } = {}) {
if (typeof text !== 'string') return { ok: false, errors: ['nothing to import'] };
const bytes = new TextEncoder().encode(text).length;
if (bytes > maxBytes) return { ok: false, errors: [`the file is ${bytes} bytes, over the limit of ${maxBytes}`] };
let raw;
try { raw = JSON.parse(text.replace(/^/, '')); } catch (e) { return { ok: false, errors: [`not valid JSON: ${e.message}`] }; }
if (!isObj(raw)) return { ok: false, errors: ['the design is not a JSON object'] };
const { sha256: claimed, ...doc } = raw;
const v = validateDoc(doc);
if (!v.ok) return { ok: false, errors: v.errors };
const clean = normaliseDoc(doc);
const sha256 = await hashDoc(clean);
if (claimed === undefined && !unsigned) {
return { ok: false, errors: ['the file has no sha256 checksum, so it cannot be shown to be unaltered; export it again from the viewer'] };
}
if (claimed !== undefined && claimed !== sha256) {
return { ok: false, errors: [`the file says sha256 ${String(claimed).slice(0, 12)}… but its content hashes to ${sha256.slice(0, 12)}…; it has been altered or damaged`] };
}
return { ok: true, doc: clean, sha256 };
}
// ---------- share link (URL fragment) ----------
// #design=1.<first 12 hex of sha256>.<base64url of deflate-raw canonical JSON>
const b64url = bytes => {
let s = ''; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const unb64url = s => {
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - s.length % 4) % 4));
return Uint8Array.from(bin, c => c.charCodeAt(0));
};
async function pump(bytes, stream, cap) {
const out = new Blob([bytes]).stream().pipeThrough(stream).getReader();
const parts = []; let n = 0;
for (;;) {
const { done, value } = await out.read();
if (done) break;
n += value.length;
if (n > cap) { await out.cancel(); throw new Error(`the link expands past ${cap} bytes; refused`); }
parts.push(value);
}
const all = new Uint8Array(n); let o = 0;
for (const p of parts) { all.set(p, o); o += p.length; }
return all;
}
// Returns { ok: true, fragment, chars } or { ok: false, errors } saying why (too long, no compression).
export async function makeShareLink(doc, { maxChars = LIMITS.linkChars } = {}) {
const v = validateDoc(doc);
if (!v.ok) return { ok: false, errors: v.errors };
if (typeof CompressionStream !== 'function') return { ok: false, errors: ['this browser cannot compress; export the .json instead'] };
const text = canonicalJson(normaliseDoc(doc)), sha = await sha256Hex(text);
const packed = await pump(new TextEncoder().encode(text), new CompressionStream('deflate-raw'), Infinity);
const fragment = `#${LINK_KEY}=${LINK_VERSION}.${sha.slice(0, 12)}.${b64url(packed)}`;
if (fragment.length > maxChars) {
return { ok: false, chars: fragment.length, errors: [`the share link would be ${fragment.length} characters, over the limit of ${maxChars}; export the .json file instead`] };
}
return { ok: true, fragment, chars: fragment.length };
}
// Accepts a whole URL, a fragment or the bare value. Returns { ok, doc, sha256 } or { ok: false, errors }.
export async function readShareLink(link, { maxChars = LIMITS.linkChars, maxBytes = LIMITS.linkInflatedBytes } = {}) {
const s = String(link ?? '');
const hash = s.includes('#') ? s.slice(s.indexOf('#') + 1) : s;
const value = new URLSearchParams(hash).get(LINK_KEY);
if (!value) return { ok: false, errors: ['no design in this link'] };
if (value.length > maxChars) return { ok: false, errors: [`the link is ${value.length} characters, over the limit of ${maxChars}; refused`] };
const parts = value.split('.');
if (parts.length !== 3) return { ok: false, errors: ['the link is damaged or cut short'] };
const [ver, short, body] = parts;
if (ver !== LINK_VERSION) return { ok: false, errors: [`unknown link version "${ver}"; this viewer reads version ${LINK_VERSION} only`] };
if (!/^[0-9a-f]{12}$/.test(short ?? '') || !/^[A-Za-z0-9_-]+$/.test(body ?? '')) return { ok: false, errors: ['the link is damaged or cut short'] };
if (typeof DecompressionStream !== 'function') return { ok: false, errors: ['this browser cannot decompress links'] };
let text;
try { text = new TextDecoder('utf-8', { fatal: true }).decode(await pump(unb64url(body), new DecompressionStream('deflate-raw'), maxBytes)); }
catch (e) {
const cap = /expands past/.test(e?.message ?? '');
if (!cap) console.warn('share link:', e);
return { ok: false, errors: [cap ? e.message : 'the link is damaged or incomplete; ask for it to be sent again'] };
}
const r = await importText(text, { maxBytes, unsigned: true }); // the link carries its own checksum, checked below
if (!r.ok) return r;
if (r.sha256.slice(0, 12) !== short) return { ok: false, errors: ['the link content does not match its checksum; it has been altered'] };
return r;
}
// ---------- local autosave ----------
// Storage can be missing, full, blocked or cleared; every call is wrapped and none of them throws.
// Keyed on where the site is (its origin), not its display name: two sites never share a save, and a rename keeps it.
export const storageKey = site => `world.design:${mm(Number(site?.origin_e))},${mm(Number(site?.origin_n))}`;
const BLOCKED = 'local storage is blocked in this browser';
const pickStorage = s => {
if (s) return { st: s };
try { return { st: globalThis.localStorage ?? null }; } catch { return { st: null, blocked: true }; }
};
const noStorage = p => ({ ok: false, reason: p.blocked ? BLOCKED : 'no local storage here' });
export function autosave(doc, { storage, key = storageKey(doc?.site) } = {}) {
try {
const p = pickStorage(storage), st = p.st;
if (!st) return noStorage(p);
st.setItem(key, canonicalJson(normaliseDoc(doc)));
return { ok: true, key };
} catch (e) { return { ok: false, reason: `autosave failed: ${e?.message ?? e}` }; }
}
// site: { origin_e, origin_n } (a document's site). Returns { ok: true, doc } | { ok: false, reason }.
export async function loadAutosave(site, { storage, key = storageKey(site) } = {}) {
let text;
try {
const p = pickStorage(storage), st = p.st;
if (!st) return noStorage(p);
text = st.getItem(key);
} catch (e) { return { ok: false, reason: `local storage blocked: ${e?.message ?? e}` }; }
if (text == null) return { ok: false, reason: 'nothing saved' };
const r = await importText(text, { unsigned: true });
return r.ok ? { ok: true, doc: r.doc } : { ok: false, reason: `saved copy refused: ${r.errors.join('; ')}` };
}
export function clearAutosave(site, { storage, key = storageKey(site) } = {}) {
try { const { st } = pickStorage(storage); if (!st) return false; st.removeItem(key); return true; } catch { return false; }
}