92 lines
5.5 KiB
JavaScript
92 lines
5.5 KiB
JavaScript
#!/usr/bin/env node
|
|
// render.mjs: runs one static view for the Programming+ shortcodes (pplus.lua calls it while Quarto renders).
|
|
//
|
|
// node render.mjs <engine> a request as JSON on stdin; the result as JSON on stdout
|
|
//
|
|
// <engine> is a built Programming+ (a folder holding dist/, or dist/ itself): the extension finds it as
|
|
// quarto/README.md describes. The views run the app's own engines, from dist/quarto/render.js, under a small
|
|
// document (dist/quarto/dom.js): nothing here knows how a program runs.
|
|
//
|
|
// A Mojo file asked to run is also given to a real compiler when one is on the PATH (`mojo`; inside pixi, the
|
|
// pinned one), and the page shows that compiler's output; without one, Programming+'s interpreter runs it and
|
|
// the page says so. `"compiler": "off"` in the request skips the compiler.
|
|
//
|
|
// Results are cached by the request and the engine's build, in the folder the request names (`cache`).
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { pathToFileURL } from 'node:url';
|
|
|
|
// written synchronously: process.exit() would cut an asynchronous write to a pipe short
|
|
const write = (text) => { const b = Buffer.from(text); let o = 0; while (o < b.length) o += fs.writeSync(1, b, o); };
|
|
const out = (obj) => write(JSON.stringify(obj));
|
|
function fail(message) { out({ error: message }); process.exit(0); }
|
|
|
|
const arg = process.argv[2];
|
|
if (!arg) fail('usage: node render.mjs <Programming+ folder or its dist/>');
|
|
const dist = fs.existsSync(path.join(arg, 'quarto', 'render.js')) ? arg : path.join(arg, 'dist');
|
|
const entry = path.join(dist, 'quarto', 'render.js');
|
|
if (!fs.existsSync(entry)) fail(`no built Programming+ at ${arg} (looked for ${entry}); build it with \`pixi run build\``);
|
|
|
|
let req;
|
|
try { req = JSON.parse(fs.readFileSync(0, 'utf8')); } catch (e) { fail(`the request is not JSON: ${e.message}`); }
|
|
|
|
// the cache key: the request, and the build of every file the views read (a rebuilt engine renders again)
|
|
let key = null;
|
|
if (req.cache) {
|
|
const h = crypto.createHash('sha256').update(JSON.stringify({ ...req, cache: undefined }));
|
|
// the app's files in dist/, pplus-core's beside it in ../core/dist/ (a checkout, or the engine folder quarto-engine writes)
|
|
for (const f of ['quarto/render.js', 'quarto/machine.js', 'quarto/dom.js', 'core/session.js', 'ui/views/viz.js']) {
|
|
try { h.update(f + fs.statSync(path.join(dist, f)).mtimeMs); } catch { /* absent: not part of the key */ }
|
|
}
|
|
for (const f of ['common/workspace.js', 'engines/asm86/hwviews.js', 'engines/asm86/views.js', 'mojo/generated/pin.js']) {
|
|
try { h.update('core/' + f + fs.statSync(path.join(dist, '..', 'core', 'dist', f)).mtimeMs); } catch { /* absent: not part of the key */ }
|
|
}
|
|
key = h.digest('hex').slice(0, 24);
|
|
try { write(fs.readFileSync(path.join(req.cache, key + '.json'), 'utf8')); process.exit(0); } catch { /* not cached yet */ }
|
|
}
|
|
|
|
// a real Mojo compiler, for a run of a Mojo file
|
|
let compiled = null;
|
|
if (req.view === 'run' && typeof req.files?.mojo === 'string' && req.compiler !== 'off') {
|
|
const v = spawnSync('mojo', ['--version'], { encoding: 'utf8' });
|
|
if (v.status === 0) {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-mojo-'));
|
|
const file = path.join(dir, 'main.mojo');
|
|
fs.writeFileSync(file, req.files.mojo);
|
|
const input = (req.input ?? []).map((l) => l + '\n').join('');
|
|
// built as Programming+ builds everywhere (pplus-core's pin: a stated target CPU, and a multiply never fused
|
|
// with an add), so the page shows what the app's Compile & run would, on whatever machine renders it
|
|
const { mojoBuildArgs } = await import(pathToFileURL(path.join(dist, '..', 'core', 'dist', 'services', 'godbolt.js')).href);
|
|
const args = mojoBuildArgs('', { x86_64: process.arch === 'x64' }).split(/\s+/).filter(Boolean);
|
|
const r = spawnSync('mojo', ['run', ...args, file], { input, encoding: 'utf8', timeout: 180000 });
|
|
compiled = { stdout: r.stdout ?? '', stderr: r.stderr ?? '', status: r.status, version: v.stdout.trim(), args: args.join(' ') };
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
} else if (req.compiler === 'on') fail('compiler="on", and there is no `mojo` on the PATH');
|
|
}
|
|
|
|
const { installDocument } = await import(pathToFileURL(path.join(dist, 'quarto', 'dom.js')).href);
|
|
installDocument();
|
|
const { renderStatic } = await import(pathToFileURL(entry).href);
|
|
let res;
|
|
try {
|
|
res = renderStatic({ ...req, compiled });
|
|
} catch (e) {
|
|
fail(`the ${req.view} view failed: ${e?.stack || e}`);
|
|
}
|
|
const { node, ...rest } = res;
|
|
// a machine board keeps every step's drawing of every card: they repeat from step to step, so deflate (which
|
|
// pplus.js undoes with the browser's DecompressionStream) makes them a few kilobytes a card
|
|
if (rest.html) {
|
|
const zlib = await import('node:zlib');
|
|
rest.html = rest.html.replace(/<script type="application\/json" class="pplus-hw-data">([^<]*)<\/script>/g, (_, json) =>
|
|
`<script type="application/x-pplus-deflate" class="pplus-hw-data">${zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 }).toString('base64')}</script>`);
|
|
}
|
|
const text = JSON.stringify(rest);
|
|
if (key) { try { fs.mkdirSync(req.cache, { recursive: true }); fs.writeFileSync(path.join(req.cache, key + '.json'), text); } catch { /* a cache that cannot be written is no cache */ } }
|
|
write(text);
|
|
// the views leave timers behind (a deferred scroll, a tooltip); the answer is written, so do not wait for them
|
|
process.exit(0);
|