In this section
- GridAtlas CI automation · teleprinter / drivers/gridatlas/ci.mjs lines 1–236
- GridAtlas Wiring render · teleprinter / drivers/gridatlas/gridatlas-wiring.js lines 1–177
- GridAtlas Print PDF render · teleprinter / drivers/gridatlas/print-pdf.js lines 1–191
GridAtlas CI
A JavaScript module in the drivers folder of Teleprinter that uses SHA-256 using data from the npm repository.
automationteleprinter / drivers/gridatlas/ci.mjs · lines 1–236 of 236 · Not reached from any entry point (candidate for review) · pattern record (shared by 46 files)
- What it does
- It loads data. Defines record, parses, git. Uses libraries node:fs/promises, node:child_process, node:crypto, node:os, node:path. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: npm data; JSON file current.json; command-line arguments.
- What it achieves
- It is built from the record step (`record`), the parses step (`parses`) and the git step (`git`). One command, a JSON verdict, and an exit code — so the same check runs on this laptop, in a hook, or in a workflow, and gives the same answer.
- Why it matters
- No other file in the estate was found to import it.
- Application
- teleprinter · drivers/gridatlas · JavaScript module
- Uses
- node:fs/promises, node:child_process, node:crypto, node:os, node:path, node:url
- Used by
- none found
- Produces
- record, parses, git
- Defines here
- record, parses, git
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/ci.mjs:1-236 · blob 1b9f573bfa044326be8e84cf1c2877416cfe2f09 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* OFFLINE CI FOR THE GRIDATLAS TELEPRINTER LANE.
* ---------------------------------------------------------------------------
* No network. No browser. No model. One command, a JSON verdict, and an exit
* code — so the same check runs on this laptop, in a hook, or in a workflow,
* and gives the same answer.
*
* WHY IT EXISTS, AND WHAT IT WOULD HAVE CAUGHT.
* On 2026-09-05 this lane put a cartridge live that did not parse: a
* single-quoted string carrying a raw line break. `node --check` had passed on
* the ES module the cartridge part was flattened from — a DIFFERENT FILE — so
* nothing caught it. window.initVentusMap never ran and the live Atlas had no
* map, no menu bar and no layer controls, in every browser. The architect found
* it, not the tooling.
*
* Every check below is therefore about the ARTEFACT THAT SHIPS rather than the
* source it came from, and each one can fail:
*
* drivers-parse every driver file parses
* part-parses the GENERATED cartridge part parses
* part-matches the vendored part still matches the drivers it claims
* to be built from (SHA-256 in its own header)
* cartridges-parse every cartridge named in atlas/current.json parses —
* the served bytes, not the parts
* gate-refuses a NEGATIVE CONTROL: a deliberately corrupted driver must
* make the build refuse. A gate that has never been seen
* to fail is not known to work.
* no-invented-urls the source collector must not resolve root-relative
* names against the page, which manufactured
* https://ventusltd.github.io/npm/... and reported three
* dependencies missing that were never missing
* tree-declared the git state is reported, so a green run on a dirty
* tree is visible as one rather than mistaken for a clean
* one
*
* WHAT IT DELIBERATELY DOES NOT DO. It does not open a browser, so it says
* nothing about whether the page WORKS — only that what ships can be parsed and
* is what it claims to be. Behaviour is the browser proofs' job
* (tools/proofs/*.browser.mjs) and it is a separate question. Nothing here
* touches a physical phone either.
*
* node drivers/gridatlas/ci.mjs <gridatlas-repo> [--json <path>]
*/
import { readFile, writeFile, mkdtemp, mkdir, rm, copyFile } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DRIVERS = ['screen-frame.js', 'print-pdf.js', 'print-source-code.js',
'gridatlas-wiring.js', 'build-part.mjs', 'ci.mjs'];
const repo = process.argv[2];
if (!repo) {
console.error('usage: node drivers/gridatlas/ci.mjs <gridatlas-repo> [--json <path>]');
process.exit(2);
}
const jsonAt = process.argv.includes('--json')
? process.argv[process.argv.indexOf('--json') + 1] : null;
const checks = [];
function record(name, ok, detail) {
checks.push({ name, ok, detail });
console.log(`${ok ? 'PASS' : 'FAIL'} ${name} ${detail}`);
}
function parses(file) {
const out = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
return { ok: out.status === 0, error: (out.stderr || '').split('\n')[0] };
}
function git(args) {
const out = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8' });
return (out.stdout || '').trim();
}
/* 1. Every driver parses. */
{
const bad = [];
for (const name of DRIVERS) {
const result = parses(path.join(HERE, name));
if (!result.ok) bad.push(`${name}: ${result.error}`);
}
record('drivers-parse', bad.length === 0,
bad.length ? bad.join(' | ') : `${DRIVERS.length} files`);
}
/* 2 and 3. The vendored part parses AND still matches its declared sources.
build-part.mjs --verify answers both: it rebuilds from the drivers and
compares, and the build refuses to emit anything that does not parse. */
{
const out = spawnSync(process.execPath,
[path.join(HERE, 'build-part.mjs'), repo, '--verify'], { encoding: 'utf8' });
const text = ((out.stdout || '') + (out.stderr || '')).trim();
record('part-matches', out.status === 0, text.split('\n').slice(0, 3).join(' | '));
}
{
/* The SERVED part must parse. Superseded parts are immutable history and are
counted, not judged: three of them do not parse, and that is the permanent
record of the 2026-09-05 incident rather than a fault to fix. Deleting them
would be editing a published generation. */
const current = JSON.parse(await readFile(path.join(repo, 'atlas', 'current.json'), 'utf8'));
const manifests = current.cartridges.map(c => c.assembled_from).filter(Boolean);
let servedPart = null;
for (const manifest of manifests) {
const text = await readFile(
path.join(repo, 'atlas', String(manifest).replace(/^\.\//, '')), 'utf8');
const hit = text.match(/(\d{12}-teleprint-controls\.js)/);
if (hit) { servedPart = hit[1]; break; }
}
if (servedPart) {
const result = parses(path.join(repo, 'atlas', 'modules', servedPart));
record('part-parses', result.ok,
result.ok ? `${servedPart} (served)` : `${servedPart}: ${result.error}`);
} else {
record('part-parses', false, 'current.json names no parts manifest carrying the part');
}
const all = git(['ls-files', 'atlas/modules'])
.split('\n').filter(name => /teleprint-controls\.js$/.test(name));
const broken = all.filter(name => path.basename(name) !== servedPart
&& !parses(path.join(repo, name)).ok).map(name => path.basename(name));
record('history-declared', true,
`${all.length} vendored part(s) in history; ${broken.length} do not parse`
+ (broken.length ? ` (${broken.join(', ')}) — superseded, immutable` : ''));
}
/* 4. THE SERVED BYTES. Every cartridge the composition actually names. */
{
const current = JSON.parse(await readFile(path.join(repo, 'atlas', 'current.json'), 'utf8'));
const bad = [];
for (const cartridge of current.cartridges) {
const file = path.join(repo, 'atlas', cartridge.path.replace(/^\.\//, ''));
const result = parses(file);
if (!result.ok) bad.push(`${cartridge.id}: ${result.error}`);
}
record('cartridges-parse', bad.length === 0,
bad.length ? bad.join(' | ')
: `generation ${current.generation}, ${current.cartridges.length} cartridges`);
}
/* 5. NEGATIVE CONTROL. Corrupt a copy of a driver and require a refusal.
Done in a temp directory: the real drivers are never touched. */
{
const scratch = await mkdtemp(path.join(tmpdir(), 'teleprint-ci-'));
try {
for (const name of ['screen-frame.js', 'print-pdf.js', 'print-source-code.js',
'gridatlas-wiring.js', 'build-part.mjs']) {
await copyFile(path.join(HERE, name), path.join(scratch, name));
}
/* The exact 2026-09-05 defect: a single-quoted string broken across two
lines. It is invisible to a reader and fatal to a parser. */
const victim = path.join(scratch, 'print-source-code.js');
const text = await readFile(victim, 'utf8');
await writeFile(victim, text + "\nconst broken = 'a\nb';\n", 'utf8');
/* The build reads the target's modules directory before it writes, so the
control needs a real one — otherwise it fails on a missing path and the
check passes for the wrong reason, which is the failure mode this whole
runner exists to prevent. */
const fakeRepo = path.join(scratch, 'repo');
await mkdir(path.join(fakeRepo, 'atlas', 'modules'), { recursive: true });
const out = spawnSync(process.execPath,
[path.join(scratch, 'build-part.mjs'), fakeRepo],
{ encoding: 'utf8' });
const said = ((out.stdout || '') + (out.stderr || ''));
/* It must refuse, and it must refuse FOR THE RIGHT REASON. A build that
happens to fail because the target directory is missing would satisfy a
naive "did it exit non-zero" check while proving nothing. */
const refusedForParse = /does not parse/.test(said);
record('gate-refuses', out.status !== 0 && refusedForParse,
refusedForParse ? 'refused a part that does not parse'
: `exit ${out.status} but not for a parse failure: ${said.split('\n')[0]}`);
void fakeRepo;
} finally {
await rm(scratch, { recursive: true, force: true });
}
}
/* 5b. CALL THE FUNCTIONS.
`node --check` parses; it does not resolve names. It passed for hours on a
print-source-code.js that referenced three identifiers which were never
defined, so every call threw a ReferenceError and the live button was dead.
Demonstrated: with the defect reinstated, `node --check` still passes and
this test fails with "ReferenceError: headerLines is not defined". */
{
const out = spawnSync(process.execPath,
['--test', path.join(HERE, 'smoke.test.mjs')], { encoding: 'utf8' });
const text = (out.stdout || '') + (out.stderr || '');
const pass = (text.match(/^# pass (\d+)$/m) || [])[1] || (text.match(/pass (\d+)/) || [])[1];
const fail = (text.match(/^# fail (\d+)$/m) || [])[1] || (text.match(/fail (\d+)/) || [])[1];
const firstError = (text.match(/(ReferenceError|TypeError|AssertionError)[^\n]*/) || [])[0];
record('drivers-run', out.status === 0,
out.status === 0 ? `${pass || '?'} runtime tests passed`
: `${fail || '?'} failed — ${firstError || 'see node --test output'}`);
}
/* 6. The invented-dependency guard, asserted against the source that ships. */
{
const text = await readFile(path.join(HERE, 'print-source-code.js'), 'utf8');
const guarded = /startsWith\('\/'\)[\s\S]{0,80}return;/.test(text);
record('no-invented-urls', guarded,
guarded ? 'root-relative names are dropped, not resolved against the page'
: 'a root-relative name would be resolved against location.href again');
}
/* 7. State the git tree rather than assume it. */
{
const dirty = git(['status', '--porcelain']).split('\n').filter(Boolean);
const head = git(['rev-parse', '--short', 'HEAD']);
record('tree-declared', true,
`${repo.split(/[\\/]/).pop()} at ${head}, ${dirty.length} uncommitted path(s)`);
}
const failed = checks.filter(check => !check.ok);
const verdict = {
schema: 'gridatlas-teleprint-ci-v1',
ranAt: new Date().toISOString(),
repo,
network: false,
browser: false,
checks,
passed: checks.length - failed.length,
failed: failed.length,
ok: failed.length === 0,
doesNotEstablish: [
'that the page works — no browser is opened here',
'anything about a physical iPhone or Android device',
'that dependency discovery is complete; a browser cannot prove that'
]
};
if (jsonAt) await writeFile(jsonAt, JSON.stringify(verdict, null, 2) + '\n', 'utf8');
console.log(`\n${verdict.passed} passed, ${verdict.failed} failed, ${checks.length} checks`);
console.log(`sha256(this runner) ${createHash('sha256')
.update(await readFile(path.join(HERE, 'ci.mjs'))).digest('hex').slice(0, 16)}`);
process.exit(verdict.ok ? 0 : 1);GridAtlas Wiring
A JavaScript file in the drivers folder of Teleprinter that works with status line (`statusLine`) and begin preparing (`beginPreparing`).
renderteleprinter / drivers/gridatlas/gridatlas-wiring.js · lines 1–177 of 177 · Not reached from any entry point (candidate for review) · pattern beginPreparing (shared by 6 files)
- What it does
- It draws its content. Defines statusLine, say, beginPreparing, button, install. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- What it achieves
- It is built from the status line helper (`statusLine`), the say step (`say`) and the begin preparing helper (`beginPreparing`). WIRING: put the two functions in the File menu, and nowhere else. -------------------------------------------------------------------------- The reader already knows where printing lives -- they found it once and printed a sheet from it. It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- teleprinter · drivers/gridatlas · script
- Uses
- none found
- Used by
- none found
- Produces
- statusLine, say, beginPreparing, button, install
- Defines here
- statusLine, say, beginPreparing, button, install
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/gridatlas-wiring.js:1-177 · blob 8cf1e83fc72427abb2cae3c9a7ea8736f74727a5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* WIRING: put the two functions in the File menu, and nowhere else.
--------------------------------------------------------------------------
The reader already knows where printing lives -- they found it once and
printed a sheet from it. A floating button somewhere else would be a second
place to learn, so both controls go into the same EXPORT THIS VIEW group,
next to the print command that is already there.
The two are SEPARATE COMMANDS and are never merged into one "export":
Print PDF a picture of the screen, for a person to look at
Print source code the whole source and its dependencies, for a machine
to read
NOTHING EXISTING IS REPLACED. The older map-only PDF control stays exactly
as it is. Two implementations of the same idea sitting side by side is the
point -- where they disagree, the disagreement is the finding. */
var PANEL_ANCHOR = '#gridatlas-export-print';
var STATUS_ID = 'gridatlas-teleprint-status';
var MAX_TRIES = 80;
function statusLine(anchor) {
var node = document.getElementById(STATUS_ID);
if (node) return node;
node = document.createElement('div');
node.id = STATUS_ID;
node.setAttribute('role', 'status');
node.setAttribute('aria-live', 'polite');
node.style.cssText = 'padding:6px 11px;font:10px/1.4 ui-monospace,'
+ 'SFMono-Regular,Menlo,monospace;color:#9fd6e4;opacity:.9;'
+ 'white-space:normal;max-width:34ch';
if (anchor && anchor.parentNode) anchor.parentNode.appendChild(node);
return node;
}
function say(text) {
var node = document.getElementById(STATUS_ID);
if (node) node.textContent = text;
}
/* The teleprint of the source is prepared when the FILE MENU OPENS, not when
the button is pressed.
Collecting it means reading every resource the browser loaded, which takes
seconds and ends the user gesture. A share sheet or a clipboard write
requested after that gesture has ended is refused, and the reader is told
nothing happened for no reason they can see. Preparing early costs one
speculative pass and makes the press instant. */
var prepared = null;
var preparing = null;
function beginPreparing() {
if (prepared || preparing) return preparing;
preparing = collectSourceCode({ appName: 'GridAtlas' })
.then(function (result) {
prepared = result;
preparing = null;
say('Source ready · ' + result.included + ' files'
+ (result.missing.length ? ' · ' + result.missing.length + ' not readable' : ''));
return result;
})
.catch(function (error) {
preparing = null;
say('Source could not be prepared: ' + (error && error.message));
throw error;
});
return preparing;
}
function button(label, id, onClick) {
var node = document.createElement('button');
node.id = id;
node.setAttribute('type', 'button');
node.setAttribute('data-gm-export', id.replace('gridatlas-', ''));
node.setAttribute('data-teleprint', '1');
node.textContent = label;
node.addEventListener('click', function () { onClick(node); });
return node;
}
function install() {
var anchor = document.querySelector(PANEL_ANCHOR);
if (!anchor || !anchor.parentNode) return false;
if (document.getElementById('gridatlas-teleprint-source')) return true;
var pdf = button('⎙ Print PDF · exactly this screen',
'gridatlas-teleprint-pdf', function (node) {
var was = node.textContent;
say('Capturing the screen…');
printPdf({
note: {
brand: 'VENTUS · GLOBALGRID2050 · GRID ATLAS',
title: document.title,
url: location.href,
stamp: new Date().toISOString().replace('T', ' ').slice(0, 16) + ' UTC',
credit: Array.prototype.map.call(
document.querySelectorAll('.maplibregl-ctrl-attrib-inner'),
function (n) { return n.textContent.trim(); }
).filter(Boolean).join(' | ')
}
}).then(function (receipt) {
/* REPORT THE MEASUREMENT, DO NOT GRADE IT.
------------------------------------------------------------------
This read `scale >= 0.999 ? 'every screen pixel'`. An ultrawide
capture measured 2326 of 2327 columns -- 0.99957 -- so the sheet
announced "every screen pixel" for a record that was one pixel
column short. A threshold dressed as a fact is exactly the habit
this estate has a rule against, and I wrote the rule.
It also read width only, so a frame that was full width and short in
height reported as complete. The claim is now an integer equality on
BOTH axes, decided in screen-frame.js where the numbers are, and
anything less prints the pixel counts rather than a verdict. */
var fidelity = '';
if (receipt.everyScreenPixel) {
fidelity = ' · every screen pixel';
} else if (receipt.screenWidth) {
fidelity = ' · ' + receipt.width + '×' + receipt.height + ' of '
+ receipt.screenWidth + '×' + receipt.screenHeight + ' screen pixels';
}
say('PDF · ' + receipt.width + '×' + receipt.height + ' px, page '
+ receipt.pageWidth + '×' + receipt.pageHeight + fidelity
+ ' · via ' + receipt.method);
node.textContent = was;
}, function (error) {
/* The reader cancelling the screen-share chooser is a decision, not a
fault, and must not be reported as one. */
say(error && /denied|Permission|abort/i.test(String(error.message || error))
? 'Screen capture was not allowed, so nothing was printed.'
: 'Could not print: ' + (error && error.message));
node.textContent = was;
});
});
var source = button('⎙ Print source code · for AI review',
'gridatlas-teleprint-source', function () {
say('Preparing the source…');
Promise.resolve(prepared || beginPreparing()).then(function (collected) {
return deliverSourceCode(collected, { panel: true });
}).then(function (receipt) {
say('Source code · ' + receipt.included + ' files, '
+ receipt.bytes + ' bytes'
+ (receipt.volumesAvailable > 1
? ' · whole file; ' + receipt.volumesAvailable
+ ' volumes available if your chat refuses it'
: '')
+ ' · ' + receipt.via.join(' + ')
+ (receipt.missing ? ' · ' + receipt.missing + ' not readable' : ''));
}, function (error) {
say('Could not print the source: ' + (error && error.message));
});
});
anchor.parentNode.insertBefore(pdf, anchor.nextSibling);
pdf.parentNode.insertBefore(source, pdf.nextSibling);
statusLine(source);
say('Print PDF saves this screen. Print source code saves the code behind it.');
/* Opening File is the signal to start work. Delegated from the document so
it survives the menu being rebuilt. */
document.addEventListener('click', function (event) {
var title = event.target && event.target.closest
? event.target.closest('.gm-title') : null;
if (title && /file/i.test(title.textContent || '')) beginPreparing();
}, true);
return true;
}
/* The export group is built by the menu bar, which itself installs only once
63 layer controls exist. Polling rather than assuming: a fixed delay is a
guess that is wrong on a slow phone and wasteful on a fast desktop. */
if (!install()) {
var tries = 0;
var timer = setInterval(function () {
tries += 1;
if (install() || tries >= MAX_TRIES) clearInterval(timer);
}, 250);
}GridAtlas Print PDF
A JavaScript module in the drivers folder of Teleprinter that works with screen PDF (`screenPdf`).
renderteleprinter / drivers/gridatlas/print-pdf.js · lines 1–191 of 191 · Not reached from any entry point (candidate for review) · pattern printPdf (shared by 6 files)
- What it does
- It draws its content. Defines 6 functions or classes, including bytes, join, pdfString, deflate, screenPdf. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
- Inputs & outputs
- Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: GridAtlas Smoke Test (teleprinter).
- What it achieves
- It is built from the bytes step (`bytes`), the join step (`join`) and the PDF string helper (`pdfString`). PRINT PDF -- one PDF unit per captured pixel, and a strip that says where it came from. --------------------------------------------------------------------------- This is the FIRST of the two Teleprinter functions and it is entirely separate from the second. Its code works with 400 kV.
- Why it matters
- Checked by GridAtlas Smoke Test.
- Application
- teleprinter · drivers/gridatlas · JavaScript module
- Uses
- GridAtlas Screen Frame (import)
- Used by
- imported by GridAtlas Smoke Test (dynamic import)
- Produces
- screenPdf, printPdf
- Defines here
- bytes, join, pdfString, deflate, screenPdf, printPdf
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/print-pdf.js:1-191 · blob e2a7762131d638e37fb14ac82367e9665235b2b6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* PRINT PDF -- one PDF unit per captured pixel, and a strip that says where it
* came from.
* ---------------------------------------------------------------------------
* This is the FIRST of the two Teleprinter functions and it is entirely
* separate from the second. It answers "give me what is on my screen as a
* file". It knows nothing about source code.
*
* NO PAPER. The page box is exactly the captured raster's width, and its
* height is the raster plus one provenance strip. Not A4, not A3, not "the
* long edge scaled to 1190pt" -- that last one was real, it shipped, and on a
* 1390x518 desktop capture it emitted a 1190x443 page: a 14% REDUCTION of the
* record presented as the record. "THE PRINT MUST BE HIGH RES OF WHAT THE USER
* SEES NOT A REDUCED CRAP VERSION". "WE ARE NOT USING PAPER".
*
* WHY FLATE AND RAW RGB RATHER THAN JPEG. JPEG is lossy, and a lossy record is
* an edited one: text in the layer panel and the thin 400 kV lines are exactly
* the content its ringing artefacts damage most. /FlateDecode over raw RGB
* samples is bit-exact, so the bytes in the file ARE the bytes that were on
* the screen, and a reviewer can say so rather than hope so.
*
* WHY THE STRIP IS OUTSIDE THE IMAGE. The furniture used to be painted over
* the map. It covered the menu bar at the top and the legend at the bottom,
* and on a real sheet it truncated the generation stamp to "generation
* 202609051211 - 2026-09-". The record must not be written on. So the page is
* made taller than the capture and the strip lives in the space that adds:
* every pixel of the reader's screen survives untouched, and the provenance is
* still on the sheet. "I like the headers and footers thats nice ... KEEP
* THAT".
*/
import { screenFrame } from './screen-frame.js';
const encoder = new TextEncoder();
const bytes = (text) => encoder.encode(text);
function join(parts) {
let length = 0;
for (const part of parts) length += part.length;
const out = new Uint8Array(length);
let at = 0;
for (const part of parts) { out.set(part, at); at += part.length; }
return out;
}
/* PDF strings are parenthesised, so a literal parenthesis or backslash in a
project name would end the string early and corrupt every object offset
after it. Non-ASCII is dropped rather than guessed at: WinAnsi is not UTF-8
and a mojibake stamp is worse than a plain one. */
function pdfString(text) {
return String(text == null ? '' : text)
.replace(/[\\()]/g, '\\$&')
.replace(/[^\x20-\x7e]/g, '');
}
async function deflate(data) {
if (typeof CompressionStream !== 'function') {
throw new Error('This browser cannot compress the page.');
}
const stream = new Blob([data]).stream().pipeThrough(new CompressionStream('deflate'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
/**
* Build a one-page PDF whose page is the capture plus a provenance strip.
*
* @param {{width:number,height:number,rgba:Uint8ClampedArray}} frame
* @param {{brand?:string,title?:string,url?:string,stamp?:string,credit?:string,method?:string}} [note]
*/
export async function screenPdf(frame, note = {}) {
const { width, height, rgba } = frame || {};
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height)
|| width < 1 || height < 1) {
throw new Error('The captured frame has invalid dimensions.');
}
if (!rgba || rgba.length !== width * height * 4) {
throw new Error('The captured frame has the wrong number of samples.');
}
/* The strip scales with the record, not with an assumed sheet: a 2514px-tall
phone capture and a 518px-tall desktop one both need a legible credit, and
a fixed 9pt is illegible on one and enormous on the other. */
const unit = Math.max(1, Math.min(width, height) / 900);
const headSize = Math.max(9, Math.round(13 * unit));
const footSize = Math.max(7, Math.round(9 * unit));
const pad = Math.max(10, Math.round(14 * unit));
const strip = headSize + footSize + pad * 2 + Math.round(pad * 0.6);
const pageH = height + strip;
const rgb = new Uint8Array(width * height * 3);
for (let i = 0, o = 0; i < rgba.length; i += 4, o += 3) {
rgb[o] = rgba[i]; rgb[o + 1] = rgba[i + 1]; rgb[o + 2] = rgba[i + 2];
}
const image = await deflate(rgb);
const heading = pdfString(note.title || 'GlobalGrid2050 · Grid Atlas');
const brand = pdfString(note.brand || 'VENTUS · GLOBALGRID2050 · GRID ATLAS');
const left = pdfString(note.credit || '');
const right = pdfString([note.stamp, note.method && ('capture: ' + note.method)]
.filter(Boolean).join(' · '));
const link = pdfString(note.url || '');
/* The image is placed at y=strip so the strip occupies the BOTTOM of the
page, below the record, in PDF's origin-at-bottom-left space. */
const content = [
'q', `${width} 0 0 ${height} 0 ${strip} cm`, '/Screen Do', 'Q',
'q', '0.016 0.039 0.047 rg', `0 0 ${width} ${strip} re f`, 'Q',
`BT /F1 ${headSize} Tf 1 1 1 rg ${pad} ${strip - pad - headSize + Math.round(headSize * 0.25)} Td (${brand}) Tj ET`,
`BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${pad} ${Math.round(pad * 0.9) + footSize} Td (${heading}) Tj ET`,
`BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55)} Td (${link}) Tj ET`,
`BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55) + footSize + 2} Td (${left}) Tj ET`,
`BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${Math.max(pad, width - pad - right.length * footSize * 0.52)} ${Math.round(pad * 0.9) + footSize} Td (${right}) Tj ET`
].join('\n');
const contentBytes = await deflate(bytes(content));
const objects = [
bytes('<< /Type /Catalog /Pages 2 0 R >>'),
bytes('<< /Type /Pages /Kids [3 0 R] /Count 1 >>'),
bytes(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${width} ${pageH}] `
+ '/Resources << /XObject << /Screen 5 0 R >> /Font << /F1 6 0 R >> >> '
+ '/Contents 4 0 R >>'),
join([bytes(`<< /Length ${contentBytes.length} /Filter /FlateDecode >>\nstream\n`),
contentBytes, bytes('\nendstream')]),
join([bytes('<< /Type /XObject /Subtype /Image '
+ `/Width ${width} /Height ${height} /ColorSpace /DeviceRGB `
+ '/BitsPerComponent 8 /Interpolate false /Filter /FlateDecode '
+ `/Length ${image.length} >>\nstream\n`), image, bytes('\nendstream')]),
bytes('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>')
];
const chunks = [bytes('%PDF-1.4\n')];
const offsets = [];
let at = chunks[0].length;
objects.forEach((body, index) => {
offsets.push(at);
const piece = join([bytes(`${index + 1} 0 obj\n`), body, bytes('\nendobj\n')]);
chunks.push(piece);
at += piece.length;
});
let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets) xref += String(offset).padStart(10, '0') + ' 00000 n \n';
chunks.push(bytes(xref + `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\n`
+ `startxref\n${at}\n%%EOF\n`));
return { bytes: join(chunks), pageWidth: width, pageHeight: pageH, strip };
}
/**
* Capture the screen and put a PDF of it on the reader's disk.
*
* Separate from printSourceCode() on purpose: one produces a picture of the
* screen, the other produces text for a machine to read, and conflating them
* gives a reader a file that is bad at both.
*/
export async function printPdf({ capture, note = {}, filename } = {}) {
const frame = await screenFrame({ capture });
const built = await screenPdf(frame, { ...note, method: frame.method });
const blob = new Blob([built.bytes], { type: 'application/pdf' });
const name = filename
|| `gridatlas-screen-${new Date().toISOString().replace(/[:.]/g, '-')}.pdf`;
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = name;
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
/* Revoking immediately races the browser's own fetch of the blob on some
builds; 30 s is long enough for any of them and short enough that a reader
printing repeatedly does not accumulate them. */
setTimeout(() => {
URL.revokeObjectURL(url);
if (link.parentNode) link.parentNode.removeChild(link);
}, 30000);
return {
method: frame.method,
width: frame.width,
height: frame.height,
/* Carried out so the caller can tell the reader the truth about what the
file holds rather than repeating a "1:1" that describes only the
relationship between the page and the image inside it. */
screenWidth: frame.screenWidth || null,
screenHeight: frame.screenHeight || null,
captureScale: typeof frame.captureScale === 'number' ? frame.captureScale : null,
captureScaleHeight: typeof frame.captureScaleHeight === 'number' ? frame.captureScaleHeight : null,
everyScreenPixel: frame.everyScreenPixel === true,
pageWidth: built.pageWidth,
pageHeight: built.pageHeight,
bytes: built.bytes.length,
filename: name
};
}