GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / globalgrid2050 / testcode/202609051419/teleprinter

Print Source Code and 2 more files

A JavaScript module in the teleprinter folder of GlobalGrid2050 that fetches verified source code (`fetchVerifiedSourceCode`), using SHA-256.

470 lines of JavaScript from globalgrid2050, in 3 files. Topic: AI agents and coordination. Section 1621 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Png Pixels ingest · globalgrid2050 / testcode/202609051419/teleprinter/png-pixels.mjs lines 1–141
  2. Print Source Code render · globalgrid2050 / testcode/202609051457/teleprinter/print-source-code.js lines 1–179
  3. Screen PDF transform · globalgrid2050 / testcode/202609051457/teleprinter/screen-pdf.mjs lines 1–150

Png Pixels

A JavaScript module in the teleprinter folder of GlobalGrid2050. It is built from the fail step (`fail`), the crc32 step (`crc32`) and the inflate step (`inflate`).

ingestglobalgrid2050 / testcode/202609051419/teleprinter/png-pixels.mjs · lines 1–141 of 141 · version 2026-09-05 14:19 · pattern inflate (shared by 4 files)

What it does
It lists and searches its content. Defines fail, crc32, inflate, paeth, decodePngPixels.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Print Screen (globalgrid2050); Codex Png Pixels Test (teleprinter). Reached from 3 other entry points, including Codex Demo (teleprinter); Sandbox — Pipeline Page (testcode); Teleprinter Bootstrap (testcode).
What it achieves
Decode PNG sample bytes without browser color conversion or alpha premultiplication.
Why it matters
Imported by Print Screen. Checked by Codex Png Pixels Test.
Application
globalgrid2050 · testcode/202609051419/teleprinter · JavaScript module
Uses
none found
Used by
imported by Print Screen (import), imported by Codex Png Pixels Test (import), mentioned in Standalone (comment link)
Produces
decodePngPixels
Defines here
fail, crc32, inflate, paeth, decodePngPixels
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051419/teleprinter/png-pixels.mjs:1-141 · blob 98150c4635fd713ceb4baf0b09033db8851facb6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
/** Decode PNG sample bytes without browser color conversion or alpha premultiplication.
 * PNG specification: https://www.w3.org/TR/png-3/ (chunks, filters, iCCP).
 */
const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
const MAX_PIXELS = 40000000;
const MAX_INPUT = 256 * 1024 * 1024;
const MAX_PROFILE = 4 * 1024 * 1024;
const crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
  let value = index;
  for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  return value >>> 0;
});
function fail(reason) { throw new Error(`PNG screenshot: ${reason}`); }
function crc32(bytes) {
  let crc = 0xffffffff;
  for (const value of bytes) crc = crcTable[(crc ^ value) & 255] ^ (crc >>> 8);
  return (crc ^ 0xffffffff) >>> 0;
}
async function inflate(parts, limit, exact = false) {
  const reader = new Blob(parts).stream().pipeThrough(new DecompressionStream('deflate')).getReader();
  const chunks = [];
  let size = 0;
  try {
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      if (value.length > limit - size) fail('decompressed data exceeds its permitted length');
      size += value.length;
      chunks.push(value);
    }
    if (exact && size !== limit) fail('decompressed pixel data has the wrong length');
  } catch (error) {
    await reader.cancel().catch(() => {});
    if (error.message?.startsWith('PNG screenshot:')) throw error;
    fail('compressed data is corrupt or incomplete');
  } finally { reader.releaseLock(); }
  const output = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.length; }
  return output;
}
function paeth(a, b, c) {
  const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
  return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}

/** Unsupported valid PNG sample formats return null; invalid/corrupt PNGs throw. */
export async function decodePngPixels(input) {
  if (input instanceof Blob) {
    if (input.size > MAX_INPUT) fail('file is too large');
    input = await input.arrayBuffer();
  }
  const bytes = input instanceof Uint8Array ? input : input instanceof ArrayBuffer ? new Uint8Array(input) : null;
  if (!bytes) fail('expected PNG bytes or a Blob');
  if (bytes.length > MAX_INPUT) fail('file is too large');
  if (bytes.length < 8 || SIGNATURE.some((value, index) => bytes[index] !== value)) fail('invalid or truncated PNG signature');
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  let offset = 8, width, height, depth, color, interlace, channels;
  let seenHeader = false, seenPalette = false, seenData = false, endedData = false, seenEnd = false;
  let unsupported = false, profileParts, transparentColor, seenTransparency = false;
  const dataParts = [];
  while (offset < bytes.length) {
    if (bytes.length - offset < 12) fail('truncated chunk header');
    const length = view.getUint32(offset);
    if (length > 0x7fffffff || length > bytes.length - offset - 12) fail('truncated or oversized chunk');
    const typeBytes = bytes.subarray(offset + 4, offset + 8);
    if ([...typeBytes].some(value => value < 65 || value > 122 || (value > 90 && value < 97)) || (typeBytes[2] & 32)) fail('invalid chunk type');
    const type = String.fromCharCode(...typeBytes);
    const body = bytes.subarray(offset + 8, offset + 8 + length);
    if (crc32(bytes.subarray(offset + 4, offset + 8 + length)) !== view.getUint32(offset + 8 + length)) fail(`CRC mismatch in ${type}`);
    if (!seenHeader && type !== 'IHDR') fail('IHDR must be the first chunk');
    if (seenData && type !== 'IDAT') endedData = true;
    if (type === 'IHDR') {
      if (seenHeader || length !== 13) fail('invalid or duplicate IHDR');
      seenHeader = true;
      const ihdr = new DataView(body.buffer, body.byteOffset, body.byteLength);
      width = ihdr.getUint32(0); height = ihdr.getUint32(4);
      depth = body[8]; color = body[9]; interlace = body[12];
      const depths = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
      if (!width || !height || width > 0x7fffffff || height > 0x7fffffff || width * height > MAX_PIXELS) fail('image dimensions exceed the supported limit');
      if (!depths[color]?.includes(depth) || body[10] !== 0 || body[11] !== 0 || interlace > 1) fail('invalid PNG image format');
      channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color];
      unsupported = depth !== 8 || ![2, 6].includes(color) || interlace !== 0;
    } else if (type === 'PLTE') {
      if (seenPalette || seenData || !length || length % 3 || length > 768 || color === 0 || color === 4 || (color === 3 && length / 3 > 2 ** depth)) fail('invalid palette');
      seenPalette = true;
    } else if (type === 'IDAT') {
      if (endedData || (color === 3 && !seenPalette)) fail('invalid IDAT order');
      seenData = true; dataParts.push(body);
    } else if (type === 'iCCP') {
      if (profileParts || seenPalette || seenData) fail('invalid ICC profile order');
      const separator = body.indexOf(0);
      const name = body.subarray(0, separator);
      if (separator < 1 || separator > 79 || body[separator + 1] !== 0 || length <= separator + 2 || name[0] === 32 || name[name.length - 1] === 32 || name.some((value, index) => !((value >= 32 && value <= 126) || value >= 161) || (value === 32 && name[index - 1] === 32))) fail('invalid ICC profile chunk');
      profileParts = [body.subarray(separator + 2)];
    } else if (type === 'tRNS') {
      if (seenTransparency || seenData || color === 4 || color === 6 || (color === 0 && length !== 2) || (color === 2 && length !== 6) || (color === 3 && (!seenPalette || !length || length > 256))) fail('invalid transparency chunk');
      seenTransparency = true;
      if (color === 2) {
        const trns = new DataView(body.buffer, body.byteOffset, body.byteLength);
        transparentColor = [trns.getUint16(0), trns.getUint16(2), trns.getUint16(4)];
      }
    } else if (type === 'IEND') {
      if (!seenData || length !== 0 || offset + 12 !== bytes.length) fail('invalid IEND or trailing data');
      seenEnd = true;
    } else if (!(typeBytes[0] & 32) || ['acTL', 'fcTL', 'fdAT'].includes(type)) unsupported = true;
    offset += length + 12;
  }
  if (!seenHeader || !seenData || !seenEnd) fail('PNG is incomplete');
  const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
  const layouts = passes.map(([x, y, dx, dy]) => ({ width: Math.max(0, Math.ceil((width - x) / dx)), height: Math.max(0, Math.ceil((height - y) / dy)) })).filter(pass => pass.width && pass.height).map(pass => ({ ...pass, stride: Math.ceil(pass.width * channels * depth / 8) }));
  const expectedLength = layouts.reduce((sum, pass) => sum + (pass.stride + 1) * pass.height, 0);
  const raw = await inflate(dataParts, expectedLength, true);
  let scan = 0;
  for (const pass of layouts) for (let row = 0; row < pass.height; row++) {
    if (raw[scan] > 4) fail('unknown scanline filter');
    scan += pass.stride + 1;
  }
  const iccProfile = profileParts ? await inflate(profileParts, MAX_PROFILE) : undefined;
  if (iccProfile && !iccProfile.length) fail('empty ICC profile');
  if (unsupported) return null;
  const stride = width * channels;
  const rgba = new Uint8Array(width * height * 4);
  let previous = new Uint8Array(stride), current = new Uint8Array(stride);
  scan = 0;
  for (let y = 0; y < height; y++) {
    const filter = raw[scan++];
    for (let x = 0; x < stride; x++) {
      const a = x >= channels ? current[x - channels] : 0, b = previous[x], c = x >= channels ? previous[x - channels] : 0;
      const predictor = filter === 0 ? 0 : filter === 1 ? a : filter === 2 ? b : filter === 3 ? Math.floor((a + b) / 2) : paeth(a, b, c);
      current[x] = (raw[scan++] + predictor) & 255;
    }
    for (let x = 0; x < width; x++) {
      const source = x * channels, target = (y * width + x) * 4;
      rgba[target] = current[source]; rgba[target + 1] = current[source + 1]; rgba[target + 2] = current[source + 2];
      rgba[target + 3] = channels === 4 ? current[source + 3] : transparentColor && transparentColor.every((value, channel) => value === current[source + channel]) ? 0 : 255;
    }
    [previous, current] = [current, previous];
  }
  return { width, height, rgba, ...(iccProfile ? { iccProfile } : {}) };
}

Print Source Code

A JavaScript module in the teleprinter folder of GlobalGrid2050 that fetches verified source code (`fetchVerifiedSourceCode`), using SHA-256.

renderglobalgrid2050 / testcode/202609051457/teleprinter/print-source-code.js · lines 1–179 of 179 · version 2026-09-05 14:57 · Entry point · pattern sameOrigin (shared by 2 files)

What it does
It draws its content. Defines 9 functions or classes, including sha256, sameOrigin, get, fetchVerifiedSourceCode, attachPrintSourceCode. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 4 files: Controls (globalgrid2050); Codex Demo (teleprinter); Codex Source Code Test (teleprinter); Controls (testcode). Reached from 2 other entry points, including Sandbox — Pipeline Page (testcode); Teleprinter Bootstrap (testcode).
What it achieves
It fetches verified source code (`fetchVerifiedSourceCode`) and is built from the sha256 step (`sha256`) and the same origin helper (`sameOrigin`). Browser driver: attach to a button; fetch, verify, and download committed source as UTF-8 text. It responds to click events.
Why it matters
Loaded by the Codex Demo page in Teleprinter. Also imported by Controls, from Testcode. Checked by Codex Source Code Test.
Application
globalgrid2050 · testcode/202609051457/teleprinter · JavaScript module
Uses
none found
Used by
imported by Controls (import), imported by Codex Demo (import), referenced by Codex Source Code Test (new URL import.meta.url), imported by Controls (import)
Produces
fetchVerifiedSourceCode, attachPrintSourceCode, attachSourceCodeControls
Defines here
sha256, sameOrigin, get, fetchVerifiedSourceCode, attachPrintSourceCode, manualCopy, bind, click, detach
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051457/teleprinter/print-source-code.js:1-179 · blob 1827a78fd6951776093ebb1c186f3e8155dbadbc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
/** Browser driver: attach to a button; fetch, verify, and download committed source as UTF-8 text. */
async function sha256(bytes) {
  return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), byte => byte.toString(16).padStart(2, '0')).join('');
}
function sameOrigin(url) {
  const resolved = new URL(url, location.href);
  if (resolved.origin !== location.origin || !/^https?:$/.test(resolved.protocol)) throw new Error('Print source code requires same-origin HTTP(S) files.');
  return resolved.href;
}
async function get(url) {
  const response = await fetch(sameOrigin(url), { cache: 'no-store', credentials: 'same-origin', redirect: 'error' });
  if (!response.ok) throw new Error(`Print source code fetch failed: HTTP ${response.status}`);
  return response;
}

export async function fetchVerifiedSourceCode({ manifestUrl, textUrl, expectedRepository, expectedCommit }) {
  if (!manifestUrl || !textUrl) throw new Error('The source code file has not been set up for this page.');
  const [manifestResponse, textResponse] = await Promise.all([get(manifestUrl), get(textUrl)]);
  const manifest = await manifestResponse.json();
  const bytes = new Uint8Array(await textResponse.arrayBuffer());
  if (manifest.format !== 'codex-print-source-code-v1' || !/^[a-f0-9]{40,64}$/.test(manifest.commit)) throw new Error('Invalid source code manifest.');
  if (expectedRepository && manifest.repository !== expectedRepository) throw new Error('Source code repository mismatch.');
  if (expectedCommit && manifest.commit !== expectedCommit) throw new Error('Source code commit mismatch.');
  if (bytes.length !== manifest.byteCount || await sha256(bytes) !== manifest.sha256) throw new Error('Source code bundle integrity check failed.');
  const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
  const sourceText = decoder.decode(bytes);
  if (!Array.isArray(manifest.files)) throw new Error('Missing source code inventory.');
  const framing = [`PRINT SOURCE CODE\nFormat: ${manifest.format}\nRepository: ${manifest.repository}\nCommit: ${manifest.commit}\nTree: ${manifest.tree}\nScopes: ${JSON.stringify(manifest.scopes)}\nPolicy: ${JSON.stringify(manifest.policy)}\nInventory: ${JSON.stringify(manifest.files.map(({ startByte, ...entry }) => entry))}\n\n`];
  let included = 0, omitted = 0, previousEnd = 0;
  const seen = new Set();
  for (const file of manifest.files) {
    if (typeof file.path !== 'string' || seen.has(file.path)) throw new Error('Invalid source code inventory path.');
    seen.add(file.path);
    if (file.status === 'omitted' && file.reason) { omitted++; continue; }
    if (file.status !== 'included' || !Number.isSafeInteger(file.startByte) || !Number.isSafeInteger(file.byteCount) || file.byteCount < 0 || file.startByte < previousEnd || file.startByte + file.byteCount > bytes.length) throw new Error('Invalid source code file boundary.');
    if (await sha256(bytes.subarray(file.startByte, file.startByte + file.byteCount)) !== file.sha256) throw new Error(`Source code file integrity check failed: ${file.path}`);
    framing.push(`===== BEGIN FILE ${JSON.stringify(file.path)} | bytes=${file.byteCount} | sha256=${file.sha256} =====\n`, decoder.decode(bytes.subarray(file.startByte, file.startByte + file.byteCount)), `\n===== END FILE ${JSON.stringify(file.path)} =====\n\n`);
    previousEnd = file.startByte + file.byteCount;
    included++;
  }
  if (!included || included !== manifest.includedCount || omitted !== manifest.omittedCount) throw new Error('Source code coverage check failed.');
  framing.push('===== END PRINT SOURCE CODE =====\n');
  if (framing.join('') !== sourceText) throw new Error('Source code inventory or file boundaries do not match the text.');
  return { bytes, manifest };
}

/** Verified download/copy/share controls. Returned cleanup removes listeners and generated fallback. */
export function attachPrintSourceCode({ button, copyButton, shareButton, status, fallbackContainer, manifestUrl, textUrl, expectedRepository, expectedCommit, filename = 'source-code.txt', prepareSource, onError } = {}) {
  if (!button || typeof button.addEventListener !== 'function') throw new Error('Print source code requires a button element.');
  const instructions = 'Attach this text file in ChatGPT, or copy and paste its contents.';
  const ownedStatus = !status;
  if (!status) { status = document.createElement('p'); button.insertAdjacentElement('afterend', status); }
  status.setAttribute('role', 'status');
  status.setAttribute('aria-live', 'polite');
  status.textContent = instructions;
  const controls = [button, copyButton, shareButton].filter(Boolean);
  const initialDisabled = controls.map(item => item.disabled);
  const listeners = [];
  let fallback;
  let busy = false;
  let prepared;
  let detached = false;
  const safeFilename = `${filename.replace(/\.txt$/i, '').replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')}.txt`;
  const manualCopy = text => {
    if (!fallback) {
      fallback = document.createElement('div');
      const label = document.createElement('p');
      label.textContent = 'Select all the source code below, then copy it and paste it into ChatGPT.';
      const area = document.createElement('textarea');
      area.readOnly = true;
      area.rows = 14;
      area.style.width = '100%';
      area.setAttribute('aria-label', 'Complete source code. Select all and copy.');
      fallback.append(label, area);
      (fallbackContainer || button.parentElement || document.body).append(fallback);
    }
    const area = fallback.querySelector('textarea');
    area.value = text;
    area.focus();
    area.select();
    status.textContent = 'Automatic copy is unavailable. The complete source code is ready below for you to select and copy.';
  };
  const bind = (control, label, action) => {
    if (!control) return;
    control.textContent = label;
    control.setAttribute('aria-label', label);
    const click = async () => {
    if (busy || control.disabled || !prepared) return;
    busy = true;
    const wasDisabled = controls.map(item => item.disabled);
    for (const item of controls) { item.disabled = true; item.setAttribute('aria-busy', 'true'); }
    try {
      // Preparation finished before the click: clipboard/share runs in this user gesture.
      const { bytes } = prepared;
      if (action === 'copy') {
        const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
        try {
          if (!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable');
          await navigator.clipboard.writeText(text);
          status.textContent = 'Source code copied. Paste it into ChatGPT.';
        } catch { manualCopy(text); }
      } else if (action === 'share') {
        const file = new File([bytes], safeFilename, { type: 'text/plain;charset=utf-8' });
        if (!navigator.canShare?.({ files: [file] })) {
          status.textContent = `File sharing is unavailable here. Use Print source code or Copy source code. ${instructions}`;
        } else {
          await navigator.share({ files: [file], title: 'Source code' });
          status.textContent = `Share action completed. ${instructions}`;
        }
      } else {
        const url = URL.createObjectURL(new Blob([bytes], { type: 'text/plain;charset=utf-8' }));
        const link = document.createElement('a');
        link.href = url;
        link.download = safeFilename;
        document.body.append(link);
        link.click();
        link.remove();
        setTimeout(() => URL.revokeObjectURL(url), 60000);
        status.textContent = `Text file download requested. ${instructions}`;
      }
    } catch (error) {
      if (error.name === 'AbortError') status.textContent = `Sharing cancelled. ${instructions}`;
      else {
        status.textContent = `Could not prepare source code: ${error.message}`;
        control.dispatchEvent(new CustomEvent('sourcecodeerror', { detail: error }));
        if (onError) onError(error);
        else console.error('Print source code:', error);
      }
    } finally {
      controls.forEach((item, index) => { item.disabled = wasDisabled[index]; item.removeAttribute('aria-busy'); });
      busy = false;
    }
    };
    control.addEventListener('click', click);
    listeners.push([control, click]);
  };
  bind(button, 'Print source code', 'download');
  bind(copyButton, 'Copy source code', 'copy');
  if (shareButton) {
    shareButton.hidden = !(typeof navigator.share === 'function' && typeof navigator.canShare === 'function');
    bind(shareButton, 'Share source code', 'share');
  }
  for (const item of controls) { item.disabled = true; item.setAttribute('aria-busy', 'true'); }
  status.textContent = 'Preparing the complete source code…';
  const ready = fetchVerifiedSourceCode({ manifestUrl, textUrl, expectedRepository, expectedCommit }).then(async result => {
    if (prepareSource) {
      status.textContent = 'Collecting the current screen state and its dependencies…';
      result = await prepareSource(result);
      if (!(result?.bytes instanceof Uint8Array) || !result.manifest) throw new Error('The current screen source could not be prepared.');
    }
    if (detached) return null;
    prepared = result;
    controls.forEach((item, index) => { item.disabled = initialDisabled[index]; item.removeAttribute('aria-busy'); });
    status.textContent = result.manifest.format === 'codex-runtime-source-v1'
      ? `Source code ready with the current screen state and ${result.manifest.counts.included} dependency responses. ${result.manifest.failures.length} resources could not be read; any gaps are listed in the file. ${instructions}`
      : `Source code ready: ${result.manifest.includedCount} files, ${result.bytes.length} bytes. ${instructions}`;
    return result;
  }).catch(error => {
    if (!detached) {
      for (const item of controls) item.removeAttribute('aria-busy');
      status.textContent = 'The complete source code could not be prepared. Reload the page to try again.';
      button.dispatchEvent(new CustomEvent('sourcecodeerror', { detail: error }));
      if (onError) onError(error);
      else console.error('Print source code:', error);
    }
    return null;
  });
  const detach = () => {
    detached = true;
    for (const [control, listener] of listeners) control.removeEventListener('click', listener);
    controls.forEach((item, index) => { item.disabled = initialDisabled[index]; item.removeAttribute('aria-busy'); });
    fallback?.remove();
    if (ownedStatus) status.remove();
  };
  detach.ready = ready;
  return detach;
}

export const attachSourceCodeControls = attachPrintSourceCode;

Screen PDF

A JavaScript module in the teleprinter folder of GlobalGrid2050. It gets screen PDF layout (`getScreenPdfLayout`) and is built from the bytes step (`bytes`) and the join step (`join`).

transformglobalgrid2050 / testcode/202609051457/teleprinter/screen-pdf.mjs · lines 1–150 of 150 · version 2026-09-05 14:57 · pattern stream (shared by 2 files)

What it does
It calculates its inputs. Defines 10 functions or classes, including bytes, join, deflate, printable, textWidth.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Print Screen (globalgrid2050); Codex Screen PDF Test (teleprinter). Reached from 3 other entry points, including Codex Demo (teleprinter); Sandbox — Pipeline Page (testcode); Teleprinter Bootstrap (testcode).
What it achieves
Codex Teleprinter: lossless pixels with optional vector furniture outside the image.
Why it matters
Imported by Print Screen. Checked by Codex Screen PDF Test.
Application
globalgrid2050 · testcode/202609051457/teleprinter · JavaScript module
Uses
none found
Used by
imported by Print Screen (import), imported by Codex Screen PDF Test (import), mentioned in Standalone (comment link)
Produces
getScreenPdfLayout, screenPdf
Defines here
bytes, join, deflate, printable, textWidth, wrap, pdfString, getScreenPdfLayout, screenPdf, stream
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051457/teleprinter/screen-pdf.mjs:1-150 · blob fdb1ca4c25e0c3bea47122ac32c801165d95ffcc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
/** Codex Teleprinter: lossless pixels with optional vector furniture outside the image. */
const enc = new TextEncoder();
const bytes = s => enc.encode(s);
const join = parts => {
  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
  let at = 0;
  for (const p of parts) { out.set(p, at); at += p.length; }
  return out;
};
async function deflate(data) {
  return new Uint8Array(await new Response(new Blob([data]).stream()
    .pipeThrough(new CompressionStream('deflate'))).arrayBuffer());
}
// Standard Helvetica advance widths in 1/1000 em, ASCII 32..126.
const advances = {
  regular: [278,278,355,556,556,889,667,191,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,278,278,584,584,584,556,1015,667,667,722,722,667,611,778,722,278,500,667,556,833,722,778,667,778,722,667,611,722,667,944,667,667,611,278,278,278,469,556,333,556,556,500,556,556,278,556,556,222,222,500,222,833,556,556,556,556,333,500,278,556,500,722,500,500,500,334,260,334,584],
  bold: [278,333,474,556,556,889,722,238,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,333,333,584,584,584,611,975,722,722,722,722,667,611,778,722,278,556,722,611,833,722,778,667,778,722,667,611,722,667,944,667,667,611,333,278,333,584,556,333,556,611,556,611,556,333,611,611,278,278,556,278,889,611,611,611,611,389,556,333,611,556,778,556,556,500,389,280,389,584],
};
const windows1252 = new Map([[0x20ac,128],[0x201a,130],[0x0192,131],[0x201e,132],[0x2026,133],[0x2020,134],[0x2021,135],[0x02c6,136],[0x2030,137],[0x0160,138],[0x2039,139],[0x0152,140],[0x017d,142],[0x2018,145],[0x2019,146],[0x201c,147],[0x201d,148],[0x2022,149],[0x2013,150],[0x2014,151],[0x02dc,152],[0x2122,153],[0x0161,154],[0x203a,155],[0x0153,156],[0x017e,158],[0x0178,159]]);
function printable(value) {
  return [...String(value ?? '').replace(/\r\n?/g, '\n').replace(/\t/g, '    ')].map(char => {
    const point = char.codePointAt(0);
    return char === '\n' || point >= 32 && point <= 126 || point >= 160 && point <= 255 || windows1252.has(point) ? char : `[U+${point.toString(16).toUpperCase()}]`;
  }).join('');
}
function textWidth(text, font, size) {
  return [...text].reduce((sum, char) => {
    const code = char.codePointAt(0);
    // A full em is a conservative bound for non-ASCII WinAnsi glyphs.
    return sum + (code >= 32 && code <= 126 ? advances[font][code - 32] : code === 183 ? 278 : code === 169 ? 737 : 1100);
  }, 0) * size / 1000;
}
function wrap(text, font, size, available) {
  const result = [];
  for (const paragraph of printable(text).split('\n')) {
    let remaining = paragraph;
    if (!remaining) { result.push(''); continue; }
    while (remaining) {
      let count = 0, used = 0, lastSpace = -1;
      for (const char of remaining) {
        const next = textWidth(char, font, size);
        if (used + next > available) break;
        used += next; count += char.length;
        if (char === ' ') lastSpace = count;
      }
      if (!count) throw new Error('The screen is too narrow for the header and footer text.');
      if (count < remaining.length && lastSpace > 0) count = lastSpace;
      result.push(remaining.slice(0, count));
      remaining = remaining.slice(count);
    }
  }
  return result;
}
function pdfString(text) {
  return '(' + [...text].map(char => {
    const point = char.codePointAt(0), code = windows1252.get(point) ?? point;
    return code >= 127 ? '\\' + code.toString(8).padStart(3, '0') : char === '(' || char === ')' || char === '\\' ? '\\' + char : char;
  }).join('') + ')';
}

/** Image coordinates use PDF's bottom-left origin; page width stays exactly width. */
export function getScreenPdfLayout(width, height, furniture) {
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 14400 || height > 14400 || width * height > 40000000) throw new Error('The screen image has invalid dimensions.');
  if (!furniture) return { width, height, image: { x: 0, y: 0, width, height }, headerHeight: 0, footerHeight: 0, lines: [] };
  if (typeof furniture !== 'object') throw new Error('Header and footer settings must be an object.');
  const requestedScale = furniture.scale ?? 1;
  if (!Number.isFinite(requestedScale) || requestedScale <= 0) throw new Error('Header and footer scale must be positive.');
  const scale = Math.max(1, Math.min(2, requestedScale));
  const padding = 12 * scale;
  const available = width - padding * 2;
  if (available < 14 * scale) throw new Error('The screen is too narrow for the header and footer text.');
  const sections = [
    { band: 'header', font: 'bold', size: 12 * scale, text: furniture.brand ?? 'VENTUS  GLOBALGRID2050 · GRID ATLAS' },
    { band: 'header', font: 'regular', size: 14 * scale, text: furniture.title ?? 'Screen record' },
    { band: 'footer', font: 'regular', size: 10 * scale, text: furniture.credit ?? 'Data © OpenStreetMap contributors | © CARTO | EV data © Open Charge Map' },
    { band: 'footer', font: 'regular', size: 10 * scale, text: [furniture.generation ? `generation ${furniture.generation}` : '', furniture.capturedAt ?? new Date().toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC')].filter(Boolean).join(' · ') },
    { band: 'footer', font: 'regular', size: 10 * scale, text: furniture.url ?? '' },
  ];
  const bands = { header: [], footer: [] };
  for (const section of sections) if (String(section.text).length) {
    for (const text of wrap(section.text, section.font, section.size, available)) bands[section.band].push({ text, font: section.font, size: section.size, leading: section.size * 1.35, band: section.band });
  }
  const headerHeight = Math.ceil(padding * 2 + bands.header.reduce((sum, line) => sum + line.leading, 0));
  const footerHeight = Math.ceil(padding * 2 + bands.footer.reduce((sum, line) => sum + line.leading, 0));
  const pageHeight = headerHeight + height + footerHeight;
  if (pageHeight > 14400) throw new Error('The image plus header and footer exceeds the PDF height limit.');
  const lines = [];
  for (const [band, top] of [['header', pageHeight], ['footer', footerHeight]]) {
    let cursor = top - padding;
    for (const line of bands[band]) {
      lines.push({ ...line, x: padding, y: cursor - line.size, width: textWidth(line.text, line.font, line.size) });
      cursor -= line.leading;
    }
  }
  return { width, height: pageHeight, image: { x: 0, y: footerHeight, width, height }, headerHeight, footerHeight, lines };
}

export async function screenPdf({ width, height, rgba, iccProfile, furniture }) {
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1
      || width > 14400 || height > 14400 || width * height > 40000000
      || !(rgba instanceof Uint8Array || rgba instanceof Uint8ClampedArray)
      || rgba.length !== width * height * 4) throw new Error('The screen image has invalid dimensions or pixels.');
  if (iccProfile && (!(iccProfile instanceof Uint8Array) || iccProfile.length < 128 || iccProfile.length > 4000000
      || new TextDecoder().decode(iccProfile.subarray(16,20)) !== 'RGB '
      || new TextDecoder().decode(iccProfile.subarray(36,40)) !== 'acsp')) throw new Error('The screenshot colour profile is invalid.');
  const rgb = new Uint8Array(width * height * 3);
  const alpha = new Uint8Array(width * height);
  let transparent = false;
  for (let p = 0; p < alpha.length; p++) {
    rgb.set(rgba.subarray(p * 4, p * 4 + 3), p * 3);
    alpha[p] = rgba[p * 4 + 3];
    if (alpha[p] !== 255) transparent = true;
  }
  const stream = (dict, data) => join([bytes(`<< ${dict} /Length ${data.length} >>\nstream\n`), data, bytes('\nendstream')]);
  const colourSpace = iccProfile ? '[/ICCBased 6 0 R]' : '/DeviceRGB';
  const maskId = iccProfile ? 7 : 6;
  const layout = getScreenPdfLayout(width, height, furniture);
  const regularFontId = 6 + Number(Boolean(iccProfile)) + Number(transparent);
  const boldFontId = regularFontId + 1;
  const fontResources = furniture ? ` /Font << /F1 ${regularFontId} 0 R /F2 ${boldFontId} 0 R >>` : '';
  let content = `q\n${width} 0 0 ${height} 0 ${layout.image.y} cm\n/Screen Do\nQ\n`;
  if (furniture) {
    content += `q\n1 1 1 rg\n0 0 ${width} ${layout.footerHeight} re f\n0 ${layout.footerHeight + height} ${width} ${layout.headerHeight} re f\n0.08 0.12 0.16 rg\n`;
    for (const line of layout.lines) content += `BT /${line.font === 'bold' ? 'F2' : 'F1'} ${line.size} Tf 1 0 0 1 ${line.x} ${line.y} Tm ${pdfString(line.text)} Tj ET\n`;
    content += 'Q\n';
  }
  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} ${layout.height}] /Resources << /XObject << /Screen 4 0 R >>${fontResources} >> /Contents 5 0 R >>`),
    stream(`/Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace ${colourSpace} /BitsPerComponent 8 /Interpolate false /Filter /FlateDecode${transparent ? ` /SMask ${maskId} 0 R` : ''}`, await deflate(rgb)),
    stream('', bytes(content))
  ];
  if (iccProfile) objects.push(stream('/N 3 /Alternate /DeviceRGB /Filter /FlateDecode', await deflate(iccProfile)));
  if (transparent) objects.push(stream(`/Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode`, await deflate(alpha)));
  if (furniture) {
    objects.push(bytes('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'));
    objects.push(bytes('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>'));
  }
  const chunks = [bytes('%PDF-1.4\n%Teleprinter\n')];
  const offsets = [0];
  let length = chunks[0].length;
  objects.forEach((object, i) => {
    offsets.push(length);
    const chunk = join([bytes(`${i + 1} 0 obj\n`), object, bytes('\nendobj\n')]);
    chunks.push(chunk); length += chunk.length;
  });
  chunks.push(bytes(`xref\n0 ${offsets.length}\n0000000000 65535 f \n${offsets.slice(1).map(n => `${String(n).padStart(10, '0')} 00000 n \n`).join('')}trailer\n<< /Size ${offsets.length} /Root 1 0 R >>\nstartxref\n${length}\n%%EOF\n`));
  return join(chunks);
}