In this section
- Controls Layout Browser render · testcode / sandbox/tools/controls-layout.browser.cjs lines 1–109
- Iterate Arrival render · testcode / sandbox/tools/iterate-arrival.py lines 1–63
- Iterate Layout render · testcode / sandbox/tools/iterate-layout.py lines 1–54
- Measurement Controls Browser render · testcode / sandbox/tools/measurement-controls.browser.cjs lines 1–52
- Measurement Readouts Browser render · testcode / sandbox/tools/measurement-readouts.browser.cjs lines 1–26
- Morgan Location storage · testcode / sandbox/tools/morgan-location.py lines 1–36
- PDF Export Browser render · testcode / sandbox/tools/pdf-export.browser.mjs lines 1–186
- PDF Render Check storage · testcode / sandbox/tools/pdf-render-check.py lines 1–41
Controls Layout Browser
A JavaScript module in the tools folder of Testcode. It is built from the check step (`check`), the rect step (`rect`) and the color step (`color`).
rendertestcode / sandbox/tools/controls-layout.browser.cjs · lines 1–109 of 109 · Entry point · pattern color (shared by 2 files)
- What it does
- Defines check, rect, color. Uses libraries node:fs, node:path, node:http, node:child_process. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- Out: JSON file results.json.
- Downstream impact
- Used directly by 9 files: Composition Guard Workflow (testcode); Controls Layout Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); and 5 more.
- What it achieves
- Chrome layout regression against the real composed candidate, including its remote shell.
- Why it matters
- Run by 9 workflows and scripts, including Composition Guard Workflow, Controls Layout Workflow and Measurement Clearance Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, node:http, node:child_process
- Used by
- run by Composition Guard Workflow (workflow run), run by Controls Layout Workflow (workflow run), run by Measurement Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Offshore Route Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Tool Recovery Workflow (workflow run), run by Vertex Limit Workflow (workflow run), and 1 more
- Produces
- check, rect, color
- Defines here
- check, rect, color
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/controls-layout.browser.cjs:1-109 · blob 24fd566dd12e64fdd3199f416c86b02c7a11fb87 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unknown
/* Chrome layout regression against the real composed candidate, including its remote shell. */
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const {execFileSync} = require('node:child_process');
let playwright;
try { playwright = require(process.env.PLAYWRIGHT_MODULE || 'playwright'); }
catch (error) {
const installed = 'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright';
if (process.env.PLAYWRIGHT_MODULE || !fs.existsSync(installed)) throw error;
playwright = require(installed);
}
const root = path.resolve(__dirname, '../..');
const generation = process.env.TEST_GENERATION || '202609060228';
if (!/^\d{12}$/.test(generation)) throw new Error('TEST_GENERATION must be a twelve-digit immutable generation');
const output = path.resolve(process.env.TEST_OUTPUT || 'controls-layout-artifacts');
fs.mkdirSync(output, {recursive: true});
const report = {generation, commit: execFileSync('git', ['rev-parse', 'HEAD'], {cwd: root, encoding: 'utf8'}).trim(), checks: [], profiles: [], limitations: ['393px Chrome touch emulation is not a physical phone.', 'The composed Atlas imports a remote immutable shell and map dependencies; this is a network browser gate, not an offline or deployment acceptance gate.']};
function check(name, ok, detail) { report.checks.push({name, ok: !!ok, detail}); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${ok?'':': '+JSON.stringify(detail)}`); fs.writeFileSync(path.join(output,'results.json'),JSON.stringify(report,null,2)+'\n'); }
const server = http.createServer((req, res) => {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
const relative = pathname.startsWith('/testcode/') ? '/sandbox/' + pathname.slice(10) : pathname;
let file = path.resolve(root, '.' + relative);
if (!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; }
try {
if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
const mime = {'.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.css': 'text/css'};
res.writeHead(200, {'Content-Type': mime[path.extname(file)] || 'application/octet-stream'});
// Historical immutable dependencies use committed bytes, avoiding Windows checkout CRLF conversion.
const repoPath=path.relative(root,file).split(path.sep).join('/');
if(repoPath.startsWith('sandbox/202609051906/')) {
res.end(execFileSync('git',['show','HEAD:'+repoPath],{cwd:root,maxBuffer:64*1024*1024}));
} else fs.createReadStream(file).pipe(res);
} catch { res.writeHead(404).end(); }
});
(async () => {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
report.base = process.env.TEST_BASE || `http://127.0.0.1:${server.address().port}/testcode/${generation}/atlas/`;
const browser = await playwright.chromium.launch({headless: true, ...(process.env.CHROME_CHANNEL === 'chromium' ? {} : {channel: process.env.CHROME_CHANNEL || 'chrome'})});
report.browser = browser.version();
try {
for (const profile of [{name: 'desktop', viewport: {width: 1440, height: 900}}, {name: 'mobile-393', viewport: {width: 393, height: 852}, isMobile: true, hasTouch: true, deviceScaleFactor: 1}]) {
const {name, ...options} = profile;
const context = await browser.newContext(options);
const page = await context.newPage();
page.setDefaultTimeout(15000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const result = {name, errors}; report.profiles.push(result);
try {
await page.goto(report.base, {waitUntil: 'domcontentloaded', timeout: 60000});
await page.waitForFunction(() => document.querySelector('#codex-tool-layers>button') && document.querySelector('#gridatlas-dash-toggle') && document.querySelector('#atlas-map-controls-layout'), null, {timeout: 60000});
await page.waitForFunction(() => document.querySelector('.gm-title') && document.querySelector('.search-bar-wrapper[data-testcode-search="persistent"]') && document.querySelector('a[href*="/spider_printer"]'), null, {timeout: 60000});
result.layout = await page.evaluate(() => {
const rect = el => { const r = el.getBoundingClientRect(); return {x:r.x,y:r.y,right:r.right,bottom:r.bottom,width:r.width,height:r.height}; };
const color = el => {const c = getComputedStyle(el); return [c.backgroundColor,c.color,c.borderTopColor];};
const layer = document.querySelector('#gridatlas-dash-toggle');
const tray = document.querySelector('#codex-tool-layers');
const search = document.querySelector('.search-bar-wrapper[data-testcode-search="persistent"]');
return {width: innerWidth, height:innerHeight, scroll:document.documentElement.scrollWidth, layers:rect(layer), layerColor:color(layer), tray:rect(tray), buttons:[...tray.querySelectorAll(':scope>button')].map(el=>({text:el.textContent.trim(),rect:rect(el),color:color(el)})), search:search&&rect(search), input:document.querySelector('#search-input')&&rect(document.querySelector('#search- … [line shortened here: 563 characters; full line on GitHub]
});
const f = result.layout;
check(name+' exact viewport and generation', f.width===options.viewport.width && f.generation===generation, f);
check(name+' three named tools', f.buttons.length===3 && f.buttons.some(b=>/GIS.*SLD/.test(b.text)) && f.buttons.some(b=>/Module Layout/.test(b.text)) && f.buttons.some(b=>/Cable Geometry/.test(b.text)), f.buttons);
check(name+' tools above Layers at right', f.tray.bottom<=f.layers.y && f.tray.right<=f.width && f.tray.right>=f.width-30 && f.tray.y>f.height/2, f);
check(name+' buttons match Layers colors', f.buttons.every(b=>JSON.stringify(b.color)===JSON.stringify(f.layerColor)), f);
check(name+' controls within viewport', f.scroll<=f.width && f.buttons.every(b=>b.rect.x>=0 && b.rect.right<=f.width && b.rect.height>=44), f);
check(name+' Elements label', f.elements.length>0 && f.elements.every(label=>label==='Elements'), f.elements);
check(name+' visible usable address field', f.search && f.search.x>=0 && f.search.right<=f.width && f.input?.width>=(name==='desktop'?450:250), {search:f.search,input:f.input});
const titles = page.locator('.gm-title');
const count = await titles.count();
check(name+' menus exist', count>0, count);
result.menus=[];
for(let i=0;i<count;i++) {
const title=titles.nth(i);
if(!await title.isVisible()) continue;
await title.click();
check(name+' tools yield to open menu '+i, await page.locator('#codex-tool-layers').evaluate(el=>getComputedStyle(el).visibility==='hidden' && getComputedStyle(el).pointerEvents==='none'), 'Tray hidden and non-interactive while menu expanded');
const menu=await title.evaluate(el=>{
const panel=el.closest('.gm-menu')?.querySelector('.gm-panel');
if(!panel || panel.hidden || !panel.getBoundingClientRect().height) return {label:el.textContent,open:false};
const r=panel.getBoundingClientRect();
const left=Math.max(0,r.left),right=Math.min(innerWidth,r.right),top=Math.max(0,r.top),bottom=Math.min(innerHeight,r.bottom);
const samples=[];
for(const fx of [.1,.5,.9])for(const fy of [.1,.5,.9]){
const x=left+(right-left)*fx,y=top+(bottom-top)*fy,hit=document.elementFromPoint(x,y);
samples.push({x,y,clear:!!hit&&(hit===panel||panel.contains(hit)),hit:hit?.id||hit?.className,obstruction:hit&&!panel.contains(hit)?hit.outerHTML.slice(0,320):null});
}
return {label:el.textContent.trim(),open:true,samples};
});
result.menus.push(menu);
check(name+' unobstructed menu '+menu.label,menu.open && menu.samples.every(s=>s.clear),menu);
await page.screenshot({path:path.join(output,`${name}-menu-${i}.png`)});
await page.keyboard.press('Escape');
check(name+' tools return after menu '+i,await page.locator('#codex-tool-layers').isVisible(),'Tray visible again after Escape');
}
await page.screenshot({path:path.join(output,name+'.png')});
check(name+' no uncaught script errors', errors.length===0, errors);
} catch(error) {check(name+' completed',false,error.stack); await page.screenshot({path:path.join(output,name+'-failure.png')}).catch(()=>{});}
finally {await context.close();}
}
} finally {await browser.close();}
})().catch(error=>check('harness completed',false,error.stack)).finally(()=>{
report.finished=new Date().toISOString();
fs.writeFileSync(path.join(output,'results.json'),JSON.stringify(report,null,2)+'\n');
server.close();
process.exitCode=report.checks.some(check=>!check.ok)?1:0;
});
Iterate Arrival
A Python module in the tools folder of Testcode that fetches published and the Renewable Energy Planning Database (REPD) register, using SHA-256. It is built from the sha step (`sha`).
rendertestcode / sandbox/tools/iterate-arrival.py · lines 1–63 of 63 · Not reached from any entry point (candidate for review) · pattern patch (shared by 11 files)
- What it does
- It fetches published and the REPD register. Defines read, write, patch, sha. Uses libraries pathlib, json, shutil, hashlib, datetime. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file PUBLISHED.json; JSON file verification.json; JSON file current.json; JSON file release.json; DuckDB queries.
- What it achieves
- Defines `read`, `write`, `patch` and 1 more. It reads `current.json` and writes `current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · Python module
- Uses
- pathlib, json, shutil, hashlib, datetime
- Used by
- none found
- Produces
- read, write, patch, sha
- Defines here
- read, write, patch, sha
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/iterate-arrival.py:1-63 · blob 0cca6695a10e0d33fe0db40bb4d596c01cd6ab47 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
from pathlib import Path
import json,shutil,hashlib,datetime
R=Path(__file__).resolve().parents[1]; OLD='202609051152'; G='202609051214'; D=R/G
assert not (D/'PUBLISHED.json').exists()
shutil.copytree(R/OLD,D,dirs_exist_ok=True,ignore=shutil.ignore_patterns('evidence*','PUBLISHED.json','*console.txt','live-*','verification.json'))
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def patch(s,a,b):assert a in s,a[:90];return s.replace(a,b)
def sha(b):return hashlib.sha256(b).hexdigest()
# Identity snapshots are taken from the same immutable partitions Pipeline reads.
source=Path('C:/Users/vikra/globalgrid-testcode-publication/uk_renewables_pipeline/v9.7/data/v9.1/projects');buckets={};inputs=[]
for p in source.glob('*.json'):
raw=p.read_bytes();inputs.append({'path':p.name,'sha256':sha(raw)});data=json.loads(raw);rows=data if isinstance(data,list) else data['projects']
for row in rows:
ref=str(row['repd_ref']);b=buckets.setdefault(str(int(ref)//1000),{});b[ref]={k:row.get(k) for k in ['repd_ref','name','technology','status','capacity_mw','longitude','latitude','county','planning_authority','geometry_status']};b[ref].update(identity_source='PIPELINE_REPD_SNAPSHOT',address='',postcode='')
for bucket,rows in buckets.items():write(D/'atlas/data/repd-identities'/f'{bucket}.json',json.dumps(rows,separators=(',',':'),ensure_ascii=False)+'\n')
A=D/'atlas';current=json.loads(read(A/'current.json'))
for item in current['cartridges']:
p=A/item['path'];s=read(p);s=s.replace(OLD,G)
if item['id']=='uk-gazetteer-flyto':
s=patch(s,' async function receiveExactRepdDeepLink(',''' async function queryPipelineIdentity(ref) {
if (!/^\\d+$/.test(ref)) return null;
const url = new URL('./data/repd-identities/' + Math.floor(Number(ref)/1000) + '.json', window.location.href);
const response = await fetch(url, {cache:'force-cache'});
if (response.status === 404) return null;
if (!response.ok) throw new Error('Pipeline identity snapshot HTTP ' + response.status);
const records = await response.json();
return Object.prototype.hasOwnProperty.call(records, ref) ? records[ref] : null;
}
async function receiveExactRepdDeepLink(''')
s=patch(s,'const results = await queryOfficialRepd(repdRef, querySerial, stillOwned);','const snapshot = await queryPipelineIdentity(repdRef);\n const results = snapshot ? [snapshot] : await queryOfficialRepd(repdRef, querySerial, stillOwned);')
s=patch(s,' renderResults(results, resultsEl);\n await waitForCapturedMap();',''' renderResults(results, resultsEl);
if (!hasSafeMapPoint(exact)) {
state.deep_link = {...exact, owner_epoch:ownerEpoch, status:'IDENTIFIED_NO_GEOMETRY', resolved:true, mapped:false, official_active_register_match:false};
document.body.dataset.gridatlasRepdRef=repdRef;
document.body.dataset.gridatlasRepdDeepLink='identified-no-geometry';
return;
}
await waitForCapturedMap();''')
s=patch(s,"identity_source: 'OFFICIAL_ACTIVE_REGISTER',\n official_active_register_match: true", "identity_source: exact.identity_source || 'OFFICIAL_ACTIVE_REGISTER',\n official_active_register_match: !exact.identity_source")
if item['id']=='sld-sandbox':
s=patch(s,"|| dl.status === 'NOT_IN_ACTIVE_REGISTER'", "|| dl.status === 'NOT_IN_ACTIVE_REGISTER' || dl.status === 'IDENTIFIED_NO_GEOMETRY'")
s=patch(s,"let name = q.get('project') || 'Deep-linked project';","let name = q.get('project') || (repdRef ? 'REPD ' + repdRef : 'Shared map point');")
s=patch(s," } else if (owner?.status === 'NOT_IN_ACTIVE_REGISTER') {", """ } else if (owner?.status === 'IDENTIFIED_NO_GEOMETRY') {
link.deep_link_identity = 'identified-no-geometry';
link.identity_verification = {status:owner.status, repd_ref:repdRef, name:owner.name, identity_source:owner.identity_source};
injectStatusStyle();
showStatus(owner.name + ' (REPD ' + repdRef + ') - ' + owner.capacity_mw + ' MW. Location unavailable: this Pipeline REPD snapshot supplies no coordinates. No map pin or grid-distance calculation can be shown.', 'unavailable');
return;
} else if (owner?.status === 'NOT_IN_ACTIVE_REGISTER') {""")
s=patch(s,'if (discrepancyKm <= 0.001) {','if (discrepancyKm <= 0.001 && resolved.name === currentArrival.name && resolved.technology === currentArrival.tech && Number(resolved.capacity_mw) === Number(currentArrival.stated)) {')
# Every changed byte has a new cartridge and verified hash.
if s!=read(p):
target=f'cartridges/{G}-{item["id"]}.js';write(A/target,s);p.unlink();item.update(path='./'+target,sha256=sha(s.encode()),generation=G,version='testcode-'+G);item.pop('assembled_from',None)
current.update(generation=G,previous_generation=OLD,composition_id=G+'-testcode-atlas',live_route='/testcode/'+G+'/atlas/')
write(A/'current.json',json.dumps(current,indent=2)+'\n')
for p in [D/'index.html',D/'pipeline/index.html',A/'source/menu-bar.js']:
write(p,read(p).replace(OLD,G))
# Present outgoing identity immediately; the receiver independently resolves its pinned snapshot.
p=D/'pipeline/scripts/plugins/projects-v9-5-1.js';s=read(p);s=patch(s,' const href = canonicalHref ?', ' let href = canonicalHref ?');s=patch(s,'window.location.href).href : "";', 'window.location.href).href : "";\n if (href) { const u = new URL(href); u.searchParams.set("project", project.name); u.searchParams.set("capacity_mw", project.capacity_mw); href=u.href; }');write(p,s)
write(D/'release.json',json.dumps({'generation':G,'built_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'predecessor':OLD,'identity_records':sum(len(x) for x in buckets.values()),'partition_inputs':inputs,'changes':['Exact Pipeline arrivals use pinned same-origin identity shards instead of DuckDB/Parquet.','Missing geometry is a named terminal result, without invented coordinates.', … [line shortened here: 644 characters; full line on GitHub]
write(R/'LATEST.txt',G+'\n');print(G)Iterate Layout
A Python module in the tools folder of Testcode that draws published and the Renewable Energy Planning Database (REPD) register, using SHA-256.
rendertestcode / sandbox/tools/iterate-layout.py · lines 1–54 of 54 · Not reached from any entry point (candidate for review) · pattern change (shared by 3 files)
- What it does
- It draws published and the REPD register. Defines read, write, change. Uses libraries pathlib, json, shutil, hashlib, datetime. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file PUBLISHED.json; JSON file current.json; JSON file release.json.
- What it achieves
- Defines `read`, `write` and `change`. It reads `current.json` and writes `current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · Python module
- Uses
- pathlib, json, shutil, hashlib, datetime
- Used by
- none found
- Produces
- read, write, change
- Defines here
- read, write, change
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/iterate-layout.py:1-54 · blob c310f234e0673c48de96ffd322d0d2ed085abaf8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
from pathlib import Path
import json,shutil,hashlib,datetime
R=Path(__file__).resolve().parents[1];OLD='202609051214';G='202609051300';D=R/G
assert not (D/'PUBLISHED.json').exists()
shutil.copytree(R/OLD,D,dirs_exist_ok=True,ignore=shutil.ignore_patterns('evidence*','*console.txt','PUBLISHED.json','live-*'))
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def change(s,a,b):assert a in s,a[:80];return s.replace(a,b)
A=D/'atlas';j=json.loads(read(A/'current.json'))
for x in j['cartridges']:
p=A/x['path'];s=read(p).replace(OLD,G)
if x['id']=='substation-intelligence':s+='\n'+read(R/'tools/arrival-layout.js')
if x['id']=='sld-sandbox':
s=change(s,' addCardBar(content);',''' addCardBar(content);
content.querySelector('.testcode-location-source')?.remove();
const provenance=window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.location_provenance;
if(provenance && content.textContent.includes(window.__GRIDATLAS_PLACE_SEARCH__.deep_link.name)){
const note=document.createElement('p');note.className='testcode-location-source';note.style.cssText='color:#ffd18a;padding:8px;border:1px solid #97783f';note.textContent=provenance.notice+' ';
const a=document.createElement('a');a.href=provenance.source_item;a.target='_blank';a.rel='noopener';a.textContent='Source';note.append(a);content.insertBefore(note,content.children[1]||null);
}''')
s=change(s,' function boundCardToMap() {',' function boundCardToMap() {\n if (document.documentElement.classList.contains("testcode-arrival")) return;')
s=change(s," function reflect() {", " if (new URLSearchParams(location.search).has('repd_ref')) collapsed = true;\n\n function reflect() {")
s=change(s,' function honourRequestedZoom(map) {',' function honourRequestedZoom(map) {\n if (repdRef) return; // Frame the project and connection endpoints after selection.')
s=change(s,' if (technologyKnown) enableTechnologyLayer(currentArrival.tech);'," link.technology_layer.reason = 'Other projects are available in Layers; arrival shows the selected project and connections.';")
s=change(s,' lastSelection = { origin, name, tech, direction, links, statedMw: statedMw || null };',''' lastSelection = { origin, name, tech, direction, links, statedMw: statedMw || null };
if (new URLSearchParams(location.search).has('repd_ref')) {
if (!map.__testcodeUserMovementBound) {
map.__testcodeUserMovementBound=true;
for (const event of ['dragstart','zoomstart','rotatestart']) map.on(event,e=>{if(e.originalEvent)map.__testcodeUserMoved=true;});
}
const frame = (force=false) => {
if (!lastSelection || (!force && map.__testcodeUserMoved)) return;
const points=[lastSelection.origin,...lastSelection.links.map(l=>l.at),currentNearest400?.at,currentDeclared?.at].filter(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite));
if (!points.length) return;
map.resize();
const narrow=innerWidth<=700, h=map.getContainer().clientHeight;
const padding=narrow?{left:28,right:28,top:125,bottom:Math.min(h*.5,innerHeight*.4+90)}:{left:380,right:70,top:85,bottom:70};
map.fitBounds([[Math.min(...points.map(p=>p[0])),Math.min(...points.map(p=>p[1]))],[Math.max(...points.map(p=>p[0])),Math.max(...points.map(p=>p[1]))]],{padding,maxZoom:lastSelection.tech==='wind_offshore'?8.5:13,duration:700});
link.context_frame={points:points.length,coordinates:points.map(p=>p.slice()),padding,project:lastSelection.name};
};
requestAnimationFrame(()=>frame());
let button=document.getElementById('testcode-fit');
if(!button){button=document.createElement('button');button.id='testcode-fit';button.type='button';button.textContent='Fit connections';map.getContainer().parentElement.append(button);}
button.onclick=()=>frame(true);
}''')
s=change(s,' window.enterFullscreen?.();',' // Full-viewport arrival CSS keeps controls visible without automatic element fullscreen.')
s=change(s,' link.arrival_fullscreen = true;',' link.arrival_fullscreen = false;')
s=change(s," showStatus(owner.name + ' (REPD ' + repdRef + ') - ' + owner.capacity_mw + ' MW. Location unavailable: this Pipeline REPD snapshot supplies no coordinates. No map pin or grid-distance calculation can be shown.', 'unavailable');", " // The identity owner displays the named missing-location details once.")
if s!=read(p):
dest=f'cartridges/{G}-{x["id"]}.js';write(A/dest,s);p.unlink();x.update(path='./'+dest,sha256=hashlib.sha256(s.encode()).hexdigest(),generation=G,version='testcode-'+G)
j.update(generation=G,previous_generation=OLD,composition_id=G+'-testcode-atlas',live_route='/testcode/'+G+'/atlas/');write(A/'current.json',json.dumps(j,indent=2)+'\n')
for p in [D/'index.html',D/'pipeline/index.html',A/'source/menu-bar.js']:write(p,read(p).replace(OLD,G))
write(D/'release.json',json.dumps({'generation':G,'predecessor':OLD,'built_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'changes':['Separate search and project card positions.','Full-height arrival map with a collapsible layers drawer.','Fit project and connection endpoints in remaining map area; preserve user pans.','Retain pinned Pipeline identity and explicit missing-coordinate … [line shortened here: 457 characters; full line on GitHub]
print(G)Measurement Controls Browser
A JavaScript module in the tools folder of Testcode covering dock. It is built from the overlap step (`overlap`).
rendertestcode / sandbox/tools/measurement-controls.browser.cjs · lines 1–52 of 52 · Entry point · pattern overlap (shared by 3 files)
- What it does
- It lists and searches dock. Defines check, coords, rect, overlap. Uses libraries node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: GeoJSON file dock.geojson; command-line arguments. Out: JSON file results.json.
- Downstream impact
- Used directly by 5 files: Composition Guard Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); and 1 more.
- What it achieves
- Defines `check`, `coords`, `rect` and 1 more.
- Why it matters
- Run by 5 workflows and scripts, including Composition Guard Workflow, Measurement Clearance Workflow and Measurement Readouts Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- run by Composition Guard Workflow (workflow run), run by Measurement Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Vertex Limit Workflow (workflow run)
- Produces
- check, coords, rect, overlap
- Defines here
- check, coords, rect, overlap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/measurement-controls.browser.cjs:1-52 · blob 5a955f7bec060f1f686f1db01ca40fda6105b429 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
const fs=require('node:fs'),path=require('node:path');
let pw;try{pw=require('playwright');}catch{pw=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const base=process.argv[2],out=path.resolve(process.env.TEST_OUTPUT||'measurement-controls-artifacts');fs.mkdirSync(out,{recursive:true});const reports=[];
const engine=process.env.BROWSER_ENGINE||'chromium';
if(!['chromium','firefox','webkit'].includes(engine))throw Error('Unsupported browser engine: '+engine);
(async()=>{const browser=await pw[engine].launch();
try{for(const viewport of [{width:320,height:568},{width:393,height:852},{width:667,height:375},{width:1440,height:900}]){
const phone=viewport.width<700,context=await browser.newContext({viewport,...(engine==='firefox'?{}:{isMobile:phone}),hasTouch:phone}),page=await context.newPage(),r={viewport,checks:[],errors:[]};reports.push(r);
const check=(name,pass,detail)=>{r.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
page.on('pageerror',e=>r.errors.push(e.message));const activate=l=>phone?l.tap():l.click();
try{
await page.goto(base,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line')&&document.querySelector('#gridatlas-dash-toggle'));
const scope=page.locator('.gm-title').filter({hasText:/^Scope$/}),layers=page.locator('#gridatlas-dash-toggle');
const home=await layers.evaluate(e=>e.parentElement.tagName);await activate(scope);await activate(page.locator('#btn-zonedraw'));await page.keyboard.press('Escape');
const ring=[[1,51],[1.01,51],[1.01,51.01],[1,51.01],[1,51]];
await page.locator('#zonedraw-file').setInputFiles({name:'dock.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates[0].length===5&&!window.__GRIDATLAS_V9_MAP__.isMoving());
const coords=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates);
const held=await coords();
const layout=await page.evaluate(()=>{
const button=document.querySelector('#gridatlas-dash-toggle'),rail=document.querySelector('#gridatlas-measurement-dock'),values=rail.querySelector('.measurement-dock-values'),canvas=document.querySelector('#map canvas');
const rect=e=>{const q=e.getBoundingClientRect();return{x:q.x,y:q.y,right:q.right,bottom:q.bottom,width:q.width,height:q.height};};
const overlap=(a,b)=>a.x<b.right&&a.right>b.x&&a.y<b.bottom&&a.bottom>b.y;
const a=rect(button);return{inRail:rail.contains(button),button:a,rail:rect(rail),canvas:rect(canvas),overlapsCanvas:overlap(a,rect(canvas)),overlapsReadouts:overlap(a,rect(values)),badge:getComputedStyle(document.querySelector('#testcode-compute-receipt')).visibility,overflow:document.documentElement.scrollWidth>innerWidth};
});
check('Existing Layers launcher is inside the measurement controls',layout.inRail,layout);
check('Layers launcher does not cover the drawing or measurement values',!layout.overlapsCanvas&&!layout.overlapsReadouts,layout);
check('Layers retains a 44 pixel target without page overflow',layout.button.height>=44&&!layout.overflow,layout);
check('Diagnostic badge yields while measurements are open',layout.badge==='hidden');
check('Version link yields while measurements are open',await page.locator('.testcode-identity').evaluate(e=>getComputedStyle(e).visibility==='hidden'));
const before=await page.evaluate(()=>window.__GRIDATLAS_DASH__.collapsed);await activate(layers);
check('The original Layers handler still changes its panel',await page.evaluate(()=>window.__GRIDATLAS_DASH__.collapsed)!==before);
check('Opening Layers retains the exact polygon',JSON.stringify(await coords())===JSON.stringify(held));
const panelBounds=await page.locator('.scada-wrapper').evaluate(e=>{const a=e.getBoundingClientRect(),b=document.querySelector('#gridatlas-measurement-dock').getBoundingClientRect();return{clear:!(a.left<b.right&&a.right>b.left&&a.top<b.bottom&&a.bottom>b.top),inside:a.left>=0&&a.right<=innerWidth&&a.top>=0&&a.bottom<=innerHeight};});
check('Open Layers panel stays inside the viewport and clear of measurements',panelBounds.clear&&panelBounds.inside,panelBounds);
const lastOption=page.locator('.scada-wrapper input[type="checkbox"]').last();await lastOption.scrollIntoViewIfNeeded();
check('The last layer option remains reachable by scrolling its panel',await lastOption.evaluate(e=>{const r=e.getBoundingClientRect();return document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)===e;}));
await activate(layers);await activate(scope);await activate(page.locator('#btn-zonedraw'));await page.keyboard.press('Escape');
check('Leaving measurement returns the same Layers control to its home',await layers.evaluate((e,tag)=>e.parentElement.tagName===tag&&getComputedStyle(e).position==='fixed',home));
check('Diagnostic badge visibility returns without changing its receipt',await page.locator('#testcode-compute-receipt').evaluate(e=>getComputedStyle(e).visibility==='visible'&&e.textContent.startsWith('TEST CODE')));
check('Version link returns after measurement closes',await page.locator('.testcode-identity').evaluate(e=>getComputedStyle(e).visibility==='visible'));
await activate(scope);await activate(page.locator('#btn-radius-area'));await page.keyboard.press('Escape');
check('Circle measurements reuse the same clear Layers control',await layers.evaluate(e=>!!e.closest('#gridatlas-measurement-dock')));
await activate(scope);await activate(page.locator('#btn-zonedraw'));await page.keyboard.press('Escape');
check('Switching measurement modes preserves every polygon vertex',JSON.stringify(await coords())===JSON.stringify(held));
check('There is exactly one Layers launcher after repeated moves',await layers.count()===1);
check('Control relocation causes no script errors',r.errors.length===0,r.errors);
await page.screenshot({path:path.join(out,viewport.width+'-clear.png')});
}catch(e){r.error=e.stack;check('Measurement control review completes',false,e.message);await page.screenshot({path:path.join(out,viewport.width+'-failure.png')}).catch(()=>{});}
finally{await context.close();}
}}finally{await browser.close();}
})().catch(e=>{reports.push({error:e.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,engine,reports},null,2));if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});Measurement Readouts Browser
A JavaScript module in the tools folder of Testcode.
rendertestcode / sandbox/tools/measurement-readouts.browser.cjs · lines 1–26 of 26 · Entry point · pattern coords (shared by 6 files)
- What it does
- It lists and searches its content. Defines check, coords. Uses libraries node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: command-line arguments. Out: JSON file results.json.
- Downstream impact
- Used directly by 1 file: Measurement Readouts Workflow (testcode).
- What it achieves
- Defines `check` and `coords`.
- Why it matters
- Run by Measurement Readouts Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- run by Measurement Readouts Workflow (workflow run)
- Produces
- check, coords
- Defines here
- check, coords
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/measurement-readouts.browser.cjs:1-26 · blob 67600beff48cc27e84534460412fcc6b5b87274a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
const fs=require('node:fs'),path=require('node:path');
let pw;try{pw=require('playwright');}catch{pw=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const base=process.argv[2],out=path.resolve(process.env.TEST_OUTPUT||'measurement-readouts-artifacts');fs.mkdirSync(out,{recursive:true});const reports=[];
(async()=>{const browser=await pw.chromium.launch();try{for(const viewport of [{width:320,height:568},{width:393,height:852},{width:1440,height:900}]){
const phone=viewport.width<700,context=await browser.newContext({viewport,isMobile:phone,hasTouch:phone}),page=await context.newPage(),r={viewport,checks:[],errors:[]};reports.push(r);
const check=(name,pass,detail)=>{r.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};const activate=l=>phone?l.tap():l.click();page.on('pageerror',e=>r.errors.push(e.message));
try{
await page.goto(base);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line'));
await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[1,51],zoom:14}));
await activate(page.locator('.gm-title').filter({hasText:/^Scope$/}));await activate(page.locator('#btn-zonedraw'));await page.keyboard.press('Escape');
const box=await page.locator('#map canvas').boundingBox();if(phone)await page.touchscreen.tap(box.x+box.width/2,box.y+box.height/2);else await page.mouse.click(box.x+box.width/2,box.y+box.height/2);
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features.length&&!window.__GRIDATLAS_V9_MAP__.isMoving());
const coords=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates);
const held=await coords();
for(const label of ['Square Metres','Hectares']){
const info=await page.locator('.measurement-dock-values span').filter({hasText:new RegExp('^'+label+'$')}).evaluate(e=>{const value=e.nextElementSibling,a=e.getBoundingClientRect(),b=value.getBoundingClientRect(),r=e.closest('#gridatlas-measurement-dock').getBoundingClientRect(),m=document.querySelector('#map canvas').getBoundingClientRect();const inside=q=>q.left>=r.left&&q.right<=r.right&&q.t … [line shortened here: 678 characters; full line on GitHub]
check(label+' and its value are visible immediately after drawing',info.visible,info);
check(label+' stays outside the active map canvas',info.clear,info);
}
await page.screenshot({path:path.join(out,viewport.width+'-fresh-measurements.png')});
await activate(page.locator('#btn-zonedraw-reset'));check('Reset remains reachable in the controls',!(await coords()));
await activate(page.locator('#btn-zonedraw-undo'));check('Undo after Reset restores every drawn coordinate',JSON.stringify(await coords())===JSON.stringify(held));
const layers=page.locator('#gridatlas-dash-toggle'),collapsed=await page.evaluate(()=>window.__GRIDATLAS_DASH__.collapsed);await activate(layers);check('Original Layers control remains reachable',await page.evaluate(()=>window.__GRIDATLAS_DASH__.collapsed)!==collapsed);await activate(layers);
check('Control use retains the outline and causes no errors',JSON.stringify(await coords())===JSON.stringify(held)&&r.errors.length===0,r.errors);
}catch(e){r.error=e.stack;check('Readout review completes',false,e.message);}finally{await context.close();}
}}finally{await browser.close();}})().catch(e=>{reports.push({error:e.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,reports},null,2));if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});Morgan Location
A Python module in the tools folder of Testcode that reads morgan crown estate and provenance, using SHA-256.
storagetestcode / sandbox/tools/morgan-location.py · lines 1–36 of 36 · Not reached from any entry point (candidate for review)
- What it does
- It loads morgan crown estate and provenance. Defines read, write. Uses libraries pathlib, json, hashlib, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: GeoJSON file morgan-crown-estate.geojson; GeoJSON file 10919.geojson; JSON file 10919-provenance.json; JSON file 10.json; JSON file current.json. Coordinate systems named: WGS84 / EPSG:4326.
- What it achieves
- It is built from the read step (`read`) and the write step (`write`). Use a pinned, attributed Crown Estate lease area for indicative Morgan screening. It reads `current.json` and writes `data/project-areas/10919.geojson`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · Python module
- Uses
- pathlib, json, hashlib, datetime
- Used by
- none found
- Produces
- read, write
- Defines here
- read, write
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/morgan-location.py:1-36 · blob 88999d694927b94a231fc23530d6968267690db2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Use a pinned, attributed Crown Estate lease area for indicative Morgan screening."""
from pathlib import Path
import json, hashlib, datetime
R=Path(__file__).resolve().parents[1]; D=R/'202609051300'; A=D/'atlas'
def read(p): return p.read_text(encoding='utf-8-sig')
def write(p,s): p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
source=R/'tools/source-data/morgan-crown-estate.geojson'
geo=json.loads(read(source)); assert len(geo['features'])==1
f=geo['features'][0]; assert f['properties']['Name_Prop']=='R4 Project 6 (Morgan)'
ring=f['geometry']['coordinates'][0]; assert len(f['geometry']['coordinates'])==1
# Planar polygon centroid in lon/lat: an explicitly approximate representative
# point, not a turbine, substation, landfall or a surveyed project coordinate.
cross=[p[0]*q[1]-q[0]*p[1] for p,q in zip(ring,ring[1:])]; area2=sum(cross)
lon=sum((p[0]+q[0])*v for p,q,v in zip(ring,ring[1:],cross))/(3*area2)
lat=sum((p[1]+q[1])*v for p,q,v in zip(ring,ring[1:],cross))/(3*area2)
assert -4.3<lon<-3.7 and 53.8<lat<54.2
url='https://services2.arcgis.com/PZklK9Q45mfMFuZs/arcgis/rest/services/WindSite_EngWalNI_TheCrownEstate/FeatureServer/0/query?f=geojson&where=Name_Prop%20like%20%27%25Morgan%25%27&outFields=*&outSR=4326'
meta={'repd_ref':'10919','source':'The Crown Estate, Wind Site Agreements','source_url':url,'source_item':'https://www.arcgis.com/home/item.html?id=22a1be6fb0c5416e9369f97743f387b1','source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'retrieved_utc':datetime.datetime.fromtimestamp(source.stat().st_mtime,datetime.timezone.utc).isoformat(),'method':'Planar area-weighted polygon centroid … [line shortened here: 682 characters; full line on GitHub]
write(A/'data/project-areas/10919.geojson',json.dumps(geo,separators=(',',':'))+'\n')
write(A/'data/project-areas/10919-provenance.json',json.dumps(meta,indent=2)+'\n')
p=A/'data/repd-identities/10.json'; data=json.loads(read(p));row=data['10919'];assert row['longitude'] is None and row['latitude'] is None
row.update(longitude=lon,latitude=lat,geometry_status='approximate_lease_area_centre',coordinate_source=meta['source'],location_provenance=meta)
write(p,json.dumps(data,separators=(',',':'))+'\n')
# Keep the name/capacity identity source separate from the geometry provenance.
j=json.loads(read(A/'current.json'))
for c in j['cartridges']:
if c['id']!='uk-gazetteer-flyto': continue
p=A/c['path'];s=read(p);needle=" identity_source: exact.identity_source || 'OFFICIAL_ACTIVE_REGISTER',"
assert needle in s;s=s.replace(needle," location_provenance: exact.location_provenance || null,\n"+needle)
dest='cartridges/202609051300-uk-gazetteer-flyto.js';write(A/dest,s)
if p.resolve()!=(A/dest).resolve(): p.unlink()
c.update(path='./'+dest,sha256=hashlib.sha256(s.encode()).hexdigest(),generation='202609051300')
write(A/'current.json',json.dumps(j,indent=2)+'\n')
p=D/'pipeline/scripts/plugins/projects-v9-5-1.js';s=read(p);needle=' const located = atlasCentresOnRepdPointV9_7(project);';assert needle in s
s=s.replace(needle," if (String(project.repd_ref) === '10919') return `<a class=\"action-link atlaslink\" target=\"_blank\" rel=\"noopener\" href=\"${escapeHtml(href)}\">MAP ↗</a><div class=\"map-note\">Approximate Crown Estate lease-area centre; indicative grid distances.</div>`;\n"+needle);write(p,s)
print(json.dumps(meta,indent=2))PDF Export Browser
A JavaScript module in the tools folder of Testcode. It is built from the check step (`check`).
rendertestcode / sandbox/tools/pdf-export.browser.mjs · lines 1–186 of 186 · Entry point
- What it does
- It loads data. Defines check. Uses libraries node:module, node:fs, node:os, node:path, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: command-line arguments. Out: JSON file results.json.
- Downstream impact
- Used directly by 1 file: Map PDF Workflow (testcode).
- What it achieves
- DOES PRESSING "SAVE THIS VIEW AS A PDF" PUT A REAL PDF ON THE READER'S DISK? --------------------------------------------------------------------------- Not "does a function called `savePdf` exist", not "is /DCTDecode present in the source".
- Why it matters
- Run by Map PDF Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:module, node:fs, node:os, node:path, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- run by Map PDF Workflow (workflow run), mentioned in Standalone (comment link)
- Produces
- check
- Defines here
- check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/pdf-export.browser.mjs:1-186 · blob 000e5ab551b9b639cbaaa97fe337cc507b55e105 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unknown
/**
* DOES PRESSING "SAVE THIS VIEW AS A PDF" PUT A REAL PDF ON THE READER'S DISK?
* ---------------------------------------------------------------------------
* Not "does a function called savePdf exist", not "is /DCTDecode present in the
* source". This drives the actual control in a real browser, waits for the
* browser's own download event, saves the file, and reads the bytes back.
*
* WHY IT EXISTS. On 2026-09-05 the architect opened the print preview in
* FIREFOX, saw the sheet render correctly, pressed Print with a physical Dell
* printer selected -- and got no file at all. Every path to a PDF up to that
* point went through the browser's print pipeline: window.print(), a dialog, a
* destination, a driver. None of that is ours, and that is the part that
* failed. #gridatlas-export-pdf writes the bytes itself, so this proof must
* establish that the bytes are a valid PDF containing the map -- independently
* of any print dialog.
*
* WHAT IT ASSERTS, AND WHY EACH ONE CAN GO RED
* - a download event fires at all (fails if the control refuses)
* - the file begins %PDF-1.4 and ends %%EOF (fails on a truncated writer)
* - it carries an image XObject with
* /DCTDecode and non-zero dimensions (fails on a blank capture)
* - the embedded stream really is a JPEG,
* ffd8 .. ffd9 (fails if the base64 slice is wrong)
* - PAGE aspect equals IMAGE aspect (fails the moment the sheet
* letterboxes or crops -- this is
* the "no white space" assertion)
* - the xref offsets resolve (fails on a mis-assembled file)
*
* The aspect check is the one that matters for the brochure requirement: a page
* whose ratio differs from the raster's either leaves white bands or crops
* ground the reader was looking at. Equality to within 0.5% is the only shape
* that does neither.
*
* Three engines, because "it works in Chrome" is not the requirement:
* "it must be compatible to ALL browsers natively".
*
* node tools/proofs/202609051329-pdf-export-outcomes.browser.mjs <base-url>
*/
import {createRequire} from 'node:module';
const require=createRequire(import.meta.url);
let playwright;try{playwright=require(process.env.PLAYWRIGHT_MODULE||'playwright');}catch{playwright=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const {chromium,firefox,webkit}=playwright;
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const BASE = process.argv[2];
if (!BASE) {
console.error('usage: node 202609051329-pdf-export-outcomes.browser.mjs <base-url>');
process.exit(2);
}
const OUT = path.resolve(process.env.TEST_OUTPUT || 'pdf-export-artifacts');
fs.mkdirSync(OUT,{recursive:true});
const VIEWPORTS = [
{ name: '393x852 phone', width: 393, height: 852 },
{ name: '1400x900 desktop', width: 1400, height: 900 }
];
const ENGINES = [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]];
const results = [];
const check = (name, ok, detail) => {
results.push({ name, ok: Boolean(ok), detail });
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` [${detail}]` : ''}`);
};
for (const [engineName, engine] of ENGINES) {
const browser = await engine.launch({headless:!(engineName==='firefox'&&process.env.FIREFOX_HEADED==='1')});
try {
for (const viewport of VIEWPORTS) {
const label = `${engineName} ${viewport.name}`;
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
acceptDownloads: true
});
const page = await context.newPage();
const pageErrors = [];
const consoleErrors=[];
page.on('console',message=>{if(['error','warning'].includes(message.type())&&consoleErrors.length<30)consoleErrors.push(message.text());});
page.on('pageerror', (error) => pageErrors.push(String(error).slice(0, 160)));
try {
await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForFunction(() => Boolean(window.__GRIDATLAS_V9_MAP__), null, { timeout: 60000 });
/* The map must have drawn: a canvas without preserveDrawingBuffer is
transparent to any reader outside the frame that drew it, so a
capture taken too early is a legitimately blank one. */
await page.waitForTimeout(7000);
/* The owning menu is found by containment, never by the word "File",
and opened explicitly -- openMenu() is a toggle, so a blind click on
an already-open panel closes the very thing this needs open. */
const menu = page.locator('#gridatlas-menu-bar .gm-menu')
.filter({ has: page.locator('button[data-gm-export]') }).first();
const alreadyOpen = await menu.evaluate((node) => node.classList.contains('gm-open')).catch(() => false);
if (!alreadyOpen) await menu.locator('.gm-title').first().click({ timeout: 12000 });
const menuState = await menu.evaluate((node) => {
const title = node.querySelector('.gm-title');
const panel = node.querySelector('.gm-panel');
return { open: node.classList.contains('gm-open'), expanded: title && title.getAttribute('aria-expanded'), hidden: panel && panel.hidden };
});
check(`${label}: the export menu is open before the PDF control is clicked`,
menuState.open && menuState.expanded === 'true' && menuState.hidden === false,
`open=${menuState.open} aria-expanded=${menuState.expanded} panel.hidden=${menuState.hidden}`);
/* Resolved by id. savePdf() REWRITES the button's text on click, so a
selector that reads its words loses it the moment it is used. */
/* The download wait is armed BEFORE the click, and its rejection is
absorbed here rather than left floating. When this proof is run
against bytes that have no PDF control -- which is exactly how it
was made to fail first -- the click times out at 15 s and this
promise then rejects at 30 s with nobody awaiting it. An unhandled
rejection kills the process, so the file crashed instead of
reporting FAIL. A proof that cannot report its own failure is the
defect this whole suite exists to catch. */
const downloadPromise = page.waitForEvent('download', { timeout: 30000 })
.catch((error) => ({ failed: String(error).slice(0, 120) }));
await page.locator('#gridatlas-export-pdf').click({ timeout: 15000 });
const download = await downloadPromise;
if (!download || download.failed) throw new Error(download ? download.failed : 'no download event');
const file = path.join(OUT, `${engineName}-${viewport.width}.pdf`);
await download.saveAs(file);
const bytes = fs.readFileSync(file);
const latin = bytes.toString('latin1');
check(`${label}: the browser received a download`, bytes.length > 0,
`${download.suggestedFilename()} ${bytes.length} bytes`);
check(`${label}: the file is a PDF, opened and closed`,
latin.startsWith('%PDF-1.4') && latin.trimEnd().endsWith('%%EOF'),
`head=${JSON.stringify(latin.slice(0, 8))} tail=${JSON.stringify(latin.trimEnd().slice(-6))}`);
const mediaBox = /\/MediaBox \[0 0 (\d+) (\d+)\]/.exec(latin);
const image = /\/Subtype \/Image[\s\S]{0,320}?\/Width (\d+)[\s\S]{0,320}?\/Height (\d+)/.exec(latin);
check(`${label}: the PDF carries a rasterised map, not an empty page`,
Boolean(image) && latin.includes('/DCTDecode') && Number(image?.[1]) > 0 && Number(image?.[2]) > 0,
image ? `${image[1]}x${image[2]} /DCTDecode=${latin.includes('/DCTDecode')}` : 'no image XObject');
/* An image XObject entry could name any bytes. Decode the stream. */
const stream = /\/Filter \/DCTDecode \/Length (\d+) >>\s*stream\r?\n/.exec(latin);
let jpegOk = false;
let jpegDetail = 'no DCTDecode stream';
if (stream) {
const start = stream.index + stream[0].length;
const jpeg = bytes.subarray(start, start + Number(stream[1]));
jpegOk = jpeg[0] === 0xff && jpeg[1] === 0xd8 && jpeg[jpeg.length - 2] === 0xff && jpeg[jpeg.length - 1] === 0xd9;
jpegDetail = `${jpeg.length} bytes, ${jpeg.subarray(0, 2).toString('hex')}..${jpeg.subarray(-2).toString('hex')}`;
}
check(`${label}: that stream really is a JPEG, start of image to end of image`, jpegOk, jpegDetail);
/* THE NO-WHITE-SPACE ASSERTION. */
let aspectOk = false;
let aspectDetail = 'no MediaBox or no image';
if (mediaBox && image) {
const pageAspect = Number(mediaBox[1]) / Number(mediaBox[2]);
const imageAspect = Number(image[1]) / Number(image[2]);
aspectOk = Math.abs(pageAspect - imageAspect) / imageAspect < 0.005;
aspectDetail = `page ${mediaBox[1]}x${mediaBox[2]}pt aspect ${pageAspect.toFixed(4)}`
+ ` vs image ${image[1]}x${image[2]} aspect ${imageAspect.toFixed(4)}`;
}
check(`${label}: the page is the shape of the map, so the sheet has no white space and nothing is cropped`,
aspectOk, aspectDetail);
const xref = /startxref\s+(\d+)/.exec(latin);
check(`${label}: the cross-reference table resolves`,
Boolean(xref) && latin.slice(Number(xref[1]), Number(xref[1]) + 4) === 'xref',
xref ? `startxref ${xref[1]} -> ${JSON.stringify(latin.slice(Number(xref[1]), Number(xref[1]) + 4))}` : 'no startxref');
check(`${label}: no page errors while writing the PDF`, pageErrors.length === 0, pageErrors.join(' | '));
} catch (error) {
await page.screenshot({path:path.join(OUT,engineName+'-'+viewport.width+'-failure.png')}).catch(()=>{});
check(`${label}: the PDF export completed`, false, {error:String(error),pageErrors,consoleErrors});
} finally {
await context.close();
}
}
} finally {
await browser.close();
}
}
fs.writeFileSync(path.join(OUT,'results.json'),JSON.stringify({base:BASE,results},null,2)+'\n');
const failed = results.filter((entry) => !entry.ok);
console.log(`\n${results.length - failed.length}/${results.length} PDF export outcome checks passed`);
if (failed.length) {
console.log(`${failed.length} failed:`);
for (const entry of failed) console.log(` ${entry.name} [${entry.detail}]`);
}
process.exit(failed.length ? 1 : 0);PDF Render Check
A Python module in the tools folder of Testcode.
storagetestcode / sandbox/tools/pdf-render-check.py · lines 1–41 of 41 · Entry point
- What it does
- Uses libraries itertools, json, sys, pathlib, pymupdf. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: command-line arguments. Out: JSON file render-check.json.
- Downstream impact
- Used directly by 1 file: Map PDF Workflow (testcode).
- What it achieves
- Independently parse and render the actual browser downloads; never author PDFs.
- Why it matters
- Run by Map PDF Workflow.
- Application
- testcode · sandbox/tools · Python module
- Uses
- itertools, json, sys, pathlib, pymupdf
- Used by
- run by Map PDF Workflow (workflow run)
- 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
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/pdf-render-check.py:1-41 · blob 6a0e89acc70883b67408f41681f2e6de5b5597f5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Independently parse and render the actual browser downloads; never author PDFs."""
import itertools
import json
import sys
from pathlib import Path
import pymupdf
directory = Path(sys.argv[1])
generation = sys.argv[2]
results = []
files = sorted(directory.glob('*.pdf'))
assert len(files) == 6, f'Expected six browser/viewport downloads, found {len(files)}'
for file in files:
document = pymupdf.open(file)
assert len(document) == 1, file
page = document[0]
spans = [span for block in page.get_text('dict')['blocks'] if 'lines' in block
for line in block['lines'] for span in line['spans']]
text = page.get_text()
assert f'generation {generation}' in text, (file, text)
assert 'OpenStreetMap' in text and 'CARTO' in text and 'UTC' in text, (file, text)
rectangles = [pymupdf.Rect(span['bbox']) for span in spans]
for rectangle in rectangles:
assert page.rect.contains(rectangle), (file, 'clipped metadata', rectangle)
for left, right in itertools.combinations(rectangles, 2):
intersection = left & right
assert intersection.is_empty or intersection.get_area() < 0.01, (file, 'overlapping metadata', left, right)
images = page.get_images(full=True)
assert len(images) == 1, (file, images)
raster = pymupdf.Pixmap(document, images[0][0])
assert (raster.width, raster.height) == (page.rect.width, page.rect.height), file
# Probe decoded image pixels, independently of the JPEG header and PDF syntax.
samples = raster.samples
stride = max(raster.n, (len(samples) // 10000 // raster.n) * raster.n)
colours = {samples[i:i+raster.n] for i in range(0, len(samples), stride)}
assert len(colours) > 32, (file, 'blank or near-uniform map', len(colours))
page.get_pixmap().save(str(file.with_suffix('.png')))
results.append({'file': file.name, 'nativePixels': [raster.width, raster.height],
'metadataSpans': len(spans), 'sampledColours': len(colours), 'pass': True})
(directory / 'render-check.json').write_text(json.dumps(results, indent=2) + '\n', encoding='utf-8')
print(f'PASS {len(results)} actual PDFs: readable nonoverlapping metadata, exact generation, native raster and rendered PNGs')