commit
e092cb029c
252 files changed
+35037
No files matched your search
@@ -0,0 +1,58 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The structure a screen reader navigates by, on the pages that render outside a browser: one main landmark, a
|
||||
// labeled navigation, a footer, one h1, and headings that do not skip a level. (The workspaces are checked by axe in
|
||||
// a browser: their main, header and h1 come from src/ui/shell.ts.)
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { installDocument } from '../dist/quarto/dom.js';
|
||||
|
||||
installDocument();
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k), key: () => null, get length() { return store.size; } };
|
||||
const { homeView } = await import('../dist/ui/home.js');
|
||||
const { libraryView } = await import('../dist/ui/library.js');
|
||||
const { messagePage } = await import('../dist/ui/notice.js');
|
||||
const { highlighted } = await import('../dist/quarto/render.js');
|
||||
|
||||
function outline(root) {
|
||||
// every heading in document order (the small document's querySelectorAll returns one list per selector)
|
||||
const out = [];
|
||||
const walk = (n) => { for (const c of n.children ?? []) { if (/^h[1-6]$/.test(c.localName)) out.push(Number(c.localName[1])); walk(c); } };
|
||||
walk(root);
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const [name, view] of [['home', () => homeView()], ['library', () => libraryView()], ['a library routine', () => libraryView('md.LennardJones')]]) {
|
||||
test(`${name}: one main, a labeled nav, a footer, one h1, and no heading skips a level`, () => {
|
||||
const root = view();
|
||||
assert.equal(root.querySelectorAll('main').length, 1);
|
||||
const nav = root.querySelectorAll('nav').filter((n) => n.getAttribute('class')?.includes('home-nav'));
|
||||
assert.equal(nav.length, 1);
|
||||
assert.equal(nav[0].getAttribute('aria-label'), 'Site');
|
||||
assert.equal(root.querySelectorAll('footer').length, 1);
|
||||
const levels = outline(root);
|
||||
assert.equal(levels.filter((l) => l === 1).length, 1, `one h1 in ${levels.join(' ')}`);
|
||||
assert.equal(levels[0], 1);
|
||||
for (let i = 1; i < levels.length; i++) assert.ok(levels[i] <= levels[i - 1] + 1, `h${levels[i - 1]} then h${levels[i]} at heading ${i}`);
|
||||
});
|
||||
}
|
||||
|
||||
test('a message page is a main landmark with its h1', () => {
|
||||
const page = messagePage('No such problem', 'text');
|
||||
assert.equal(page.querySelectorAll('main').length, 1);
|
||||
assert.equal(page.querySelector('h1').textContent, 'No such problem');
|
||||
});
|
||||
|
||||
test('a listing that scrolls can be reached from the keyboard; so can an editor that is read-only', () => {
|
||||
assert.equal(highlighted('OUTPUT 1', 'pseudo').getAttribute('tabindex'), '0');
|
||||
assert.match(readFileSync(new URL('../src/ui/editor.ts', import.meta.url), 'utf8'), /contentAttributes\.of\(\{.*tabindex: '0' \}\)/);
|
||||
const shell = readFileSync(new URL('../src/ui/shell.ts', import.meta.url), 'utf8');
|
||||
assert.match(shell, /el\('header', \{ class: 'toolbar' \}\)/, 'the toolbar is the workspace\'s banner');
|
||||
assert.match(shell, /el\('main', \{ class: 'workspace'/, 'the workspace is its main landmark');
|
||||
assert.match(shell, /el\('h1', \{ class: 'sr-only' \}/, 'and it has an h1');
|
||||
const embed = readFileSync(new URL('../src/ui/embed.ts', import.meta.url), 'utf8');
|
||||
assert.match(embed, /const root = el\('main', \{ class: 'embed' \}\)/, 'an embedded view is a main landmark');
|
||||
assert.match(embed, /el\('h1', \{ class: 'sr-only' \}/, 'with an h1');
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 9: three areas, each with its own route, panes, views and layout. A problem is one state shared by all
|
||||
// three; the area comes from the route. Anything that is not a route in the plan is home.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { areasFor, AREAS, AREA_ORDER, defaultAreaFor, paneForArea, isAreaId, areaHasPane } from '../dist/core/areas.js';
|
||||
import { parseRoute, routeFor, normalize, emptyState, applyEmbedParams } from '../dist/core/state.js';
|
||||
import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { EXERCISES } from '../core/dist/exercises/index.js';
|
||||
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
|
||||
test('every route shape parses and prints back', () => {
|
||||
for (const area of AREA_ORDER) {
|
||||
assert.deepEqual(parseRoute(`#/${area}/p/count-base`), { kind: 'problem', area, id: 'count-base' });
|
||||
assert.equal(routeFor({ kind: 'problem', area, id: 'count-base' }), `#/${area}/p/count-base`);
|
||||
assert.deepEqual(parseRoute(`#/${area}/s/~abc`), { kind: 'shared', area, blob: '~abc' });
|
||||
assert.equal(routeFor({ kind: 'shared', area, blob: '~abc' }), `#/${area}/s/~abc`);
|
||||
}
|
||||
assert.deepEqual(parseRoute(''), { kind: 'home' });
|
||||
assert.deepEqual(parseRoute('#/'), { kind: 'home' });
|
||||
const e = parseRoute('#/embed/trace/p/match?t=12');
|
||||
assert.equal(e.kind, 'embed'); assert.equal(e.view, 'trace'); assert.equal(e.problem, 'match'); assert.equal(e.params.get('t'), '12');
|
||||
const b = parseRoute('#/embed/life/~blob?area=dev');
|
||||
assert.equal(b.kind, 'embed'); assert.equal(b.blob, '~blob'); assert.equal(b.params.get('area'), 'dev');
|
||||
assert.equal(routeFor(b), '#/embed/life/~blob?area=dev');
|
||||
assert.equal(routeFor(parseRoute('#/embed/playground/p/demo?panel=life')), '#/embed/playground/p/demo?panel=life');
|
||||
assert.deepEqual(parseRoute('#/bridge/p/a%20b'), { kind: 'problem', area: 'bridge', id: 'a b' });
|
||||
});
|
||||
|
||||
test('an unknown route is home: the old links and the retired names do not work', () => {
|
||||
for (const h of ['#/p/count-base', '#/s/~abc', '#/learn', '#/learn/loops', '#/playground/p/demo', '#/bridge', '#/bridge/p', '#/bridge/x/y', '#/dev/s', '#/nowhere', '#/#problems', '#/#reference'])
|
||||
assert.deepEqual(parseRoute(h), { kind: 'home' }, h);
|
||||
});
|
||||
|
||||
test('the area table: three areas with the panes, views and docks of the plan', () => {
|
||||
assert.deepEqual(AREA_ORDER, ['bridge', 'dev', 'hw']);
|
||||
assert.ok(AREA_ORDER.every(isAreaId) && !isAreaId('learn') && !isAreaId('playground'));
|
||||
for (const id of AREA_ORDER) { assert.equal(AREAS[id].id, id); assert.equal(AREAS[id].route, id); assert.ok(AREAS[id].name && AREAS[id].tagline); }
|
||||
assert.deepEqual(AREAS.bridge.panes, ['lingo', 'matho', 'pseudo', 'speco', 'mojo']);
|
||||
assert.deepEqual(AREAS.dev.panes, ['mojo']);
|
||||
assert.deepEqual(AREAS.hw.panes, ['mojo', 'asm']);
|
||||
assert.ok(AREAS.dev.inspect.includes('trace') && AREAS.bridge.inspect.includes('trace'), 'both have the Run view, which shows the variables and their lifetimes');
|
||||
assert.ok(!AREAS.dev.inspect.includes('table') && !AREAS.dev.inspect.includes('life') && !AREAS.bridge.inspect.includes('table'), 'the Run view replaces the table of values and the lifetimes');
|
||||
assert.ok(AREAS.bridge.inspect.includes('proof') && !AREAS.dev.inspect.includes('proof'));
|
||||
assert.equal(AREAS.hw.workspace, 'board', 'Hardware is two panes: the code, and the board');
|
||||
assert.ok(AREAS.bridge.workspace === 'ide' && AREAS.dev.workspace === 'ide');
|
||||
assert.deepEqual([AREAS.hw.inspect, AREAS.hw.dock], [[], []], 'its views are cards on the board, not tabs');
|
||||
assert.ok(!AREAS.bridge.dock.includes('asm') && !AREAS.dev.dock.includes('asm'));
|
||||
assert.ok(areaHasPane(AREAS.hw, 'asm') && !areaHasPane(AREAS.dev, 'pseudo'));
|
||||
});
|
||||
|
||||
test('each problem names its area: Hardware for asm-*, Developer for Mojo-only, Bridge otherwise', () => {
|
||||
for (const e of EXERCISES) {
|
||||
const p = PROBLEMS.find((x) => x.id === e.id);
|
||||
assert.ok(isAreaId(p.area), e.id);
|
||||
const raw = (l) => !!(e.sources[l] ?? '').trim();
|
||||
if (e.area) assert.equal(p.area, e.area, e.id);
|
||||
else if (e.id.startsWith('asm-')) assert.equal(p.area, 'hw', e.id);
|
||||
else if ((raw('mojo') || e.mojoProgram) && !raw('pseudo') && !raw('lingo') && !raw('matho')) assert.equal(p.area, 'dev', e.id);
|
||||
else assert.equal(p.area, 'bridge', e.id);
|
||||
}
|
||||
assert.ok(PROBLEMS.some((p) => p.area === 'bridge') && PROBLEMS.some((p) => p.area === 'hw'));
|
||||
assert.equal(defaultAreaFor({ id: 'x', sources: { pseudo: 'OUTPUT 1' }, area: 'hw' }), 'hw', 'an exercise that says so wins');
|
||||
});
|
||||
|
||||
test('the pane a state opens on follows the area', () => {
|
||||
const count = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base'));
|
||||
assert.equal(count.lang, 'mojo', 'the exercise\'s own default is its Mojo');
|
||||
assert.equal(paneForArea(AREAS.bridge, count, true), 'pseudo', 'a problem opening in the Bridge begins with the idea');
|
||||
assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'speco' }, true), 'speco', 'a linked pane the student left open is kept');
|
||||
assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'mojo' }), 'mojo', 'a shared link at the Mojo tab keeps it');
|
||||
assert.equal(paneForArea(AREAS.dev, { ...count, lang: 'pseudo' }), 'mojo');
|
||||
const asm = stateForProblem(PROBLEMS.find((p) => p.id.startsWith('asm-')));
|
||||
assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'pseudo' }), 'asm');
|
||||
assert.equal(paneForArea(AREAS.hw, { ...count, lang: 'pseudo', sources: { ...count.sources, asm: '' } }), 'mojo', 'no assembly: Mojo');
|
||||
assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'mojo' }), 'mojo', 'a pane of the area is kept');
|
||||
});
|
||||
|
||||
test('layout is kept per area, and a state normalizes it that way', () => {
|
||||
const s = normalize({ v: 3, layout: { bridge: { split: 0.4, dockTab: 'problems' }, dev: { split: 0.7, dockCollapsed: true }, hw: { dock: 0.5, right: 7 }, nowhere: { split: 0.1 }, split: 0.9 } });
|
||||
assert.deepEqual(Object.keys(s.layout).sort(), ['bridge', 'dev', 'hw']);
|
||||
assert.equal(s.layout.bridge.split, 0.4); assert.equal(s.layout.bridge.dockTab, 'problems');
|
||||
assert.equal(s.layout.dev.split, 0.7); assert.equal(s.layout.dev.dockCollapsed, true);
|
||||
assert.equal(s.layout.hw.dock, 0.5); assert.equal(s.layout.hw.right, undefined, 'a fraction outside 0..1 is dropped');
|
||||
assert.equal(normalize({ v: 3, layout: { split: 0.5, dockTab: 'output' } }).layout, undefined, 'a layout that is not per area is not read');
|
||||
assert.equal(emptyState().layout, undefined);
|
||||
});
|
||||
|
||||
test('a session lays out the area it is open in, and the other areas keep their own', () => {
|
||||
const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base'));
|
||||
const bridge = new Session(st, { area: 'bridge', storageId: null });
|
||||
bridge.setLayout({ split: 0.3 });
|
||||
assert.equal(bridge.layout().split, 0.3);
|
||||
const dev = new Session(st, { area: 'dev', storageId: null });
|
||||
assert.equal(dev.layout().split, undefined, 'the Developer area has not been arranged yet');
|
||||
dev.setLayout({ split: 0.7, dockTab: 'compiler' });
|
||||
assert.equal(bridge.layout().split, 0.3, 'the same state: the Bridge arrangement is still there');
|
||||
assert.equal(st.layout.dev.dockTab, 'compiler');
|
||||
assert.equal(new Session(st, { storageId: null }).area, null, 'a session with no area is not a workspace: every pane counts');
|
||||
});
|
||||
|
||||
test('an embed query arranges one area, chosen with area=', () => {
|
||||
const s = applyEmbedParams(emptyState(), new URLSearchParams('editor=0.6&dock=closed'), 'dev');
|
||||
assert.deepEqual(s.layout, { dev: { split: 0.6, dockCollapsed: true } });
|
||||
});
|
||||
|
||||
test('allDiagnostics reports only the panes of the area', () => {
|
||||
const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base'));
|
||||
st.sources.mojo = 'def main(:\n';
|
||||
st.sources.pseudo = 'FUNCTION BROKEN(\n';
|
||||
const dev = new Session(structuredClone(st), { area: 'dev', storageId: null });
|
||||
assert.ok(dev.allDiagnostics().every((d) => d.lang === 'mojo'), 'Developer: Mojo only');
|
||||
assert.ok(dev.allDiagnostics().length);
|
||||
const bridge = new Session(structuredClone(st), { area: 'bridge', storageId: null });
|
||||
assert.ok(bridge.allDiagnostics().some((d) => d.lang === 'pseudo'));
|
||||
const hw = new Session(structuredClone(st), { area: 'hw', storageId: null });
|
||||
assert.ok(hw.allDiagnostics().every((d) => d.lang === 'mojo' || d.lang === 'asm'));
|
||||
});
|
||||
|
||||
test('the toolbar offers only the areas that would show the open pane exactly as it is', async () => {
|
||||
const { safeSwitches } = await import('../dist/core/areas.js');
|
||||
const open = (id, area) => { const st = stateForProblem(PROBLEMS.find((p) => p.id === id)); return new Session(st, { area, storageId: null }); };
|
||||
const s = open('count-base', 'dev');
|
||||
const shown = (a, l) => s.shownIn(a, l);
|
||||
assert.deepEqual(safeSwitches('dev', 'mojo', shown), ['hw'], 'Developer and Hardware share the Mojo');
|
||||
assert.deepEqual(safeSwitches('hw', 'mojo', shown), ['dev']);
|
||||
assert.deepEqual(safeSwitches('hw', 'asm', shown), [], 'only Hardware has x86-64');
|
||||
assert.deepEqual(safeSwitches('hw', 'mojo', () => ''), [], 'an empty pane offers no switch: the move would show other work');
|
||||
for (const l of ['lingo', 'matho', 'pseudo', 'speco']) assert.deepEqual(safeSwitches('bridge', l, shown), [], `only the Bridge has ${l}`);
|
||||
assert.notEqual(s.shownIn('bridge', 'mojo'), s.shownIn('dev', 'mojo'), 'the exercise\'s own Mojo is not the translation of its pseudo');
|
||||
assert.deepEqual(safeSwitches('bridge', 'mojo', shown), [], 'so the Bridge\'s Mojo tab does not offer Developer');
|
||||
// once the generated Mojo is copied into the Developer area, the Bridge and the others show the same text
|
||||
const b = open('count-base', 'bridge');
|
||||
assert.ok(b.adoptGeneratedMojo());
|
||||
assert.deepEqual(safeSwitches('bridge', 'mojo', (a, l) => b.shownIn(a, l)), ['dev', 'hw']);
|
||||
assert.deepEqual(safeSwitches('dev', 'lingo', shown), [], 'a pane the area does not have offers nothing');
|
||||
});
|
||||
|
||||
test('each problem opens in its own area first, then every other area it has something to show in', () => {
|
||||
for (const p of PROBLEMS) {
|
||||
const a = areasFor(p);
|
||||
assert.equal(a[0], p.area, p.id);
|
||||
assert.equal(new Set(a).size, a.length, `${p.id}: each area once`);
|
||||
assert.equal(a.includes('hw'), p.area === 'hw' || !!(p.sources.asm ?? '').trim(), `${p.id}: Hardware when it has x86-64`);
|
||||
assert.equal(a.includes('bridge'), p.area === 'bridge' || ['pseudo', 'lingo', 'matho', 'speco'].some((l) => (p.sources[l] ?? '').trim()), `${p.id}: the Bridge when it has an idea to translate`);
|
||||
}
|
||||
assert.deepEqual(areasFor({ area: 'bridge', sources: { pseudo: 'OUTPUT 1', mojo: 'def main(): pass', asm: 'ret' } }), ['bridge', 'dev', 'hw']);
|
||||
assert.deepEqual(areasFor({ area: 'hw', sources: { asm: 'ret' } }), ['hw']);
|
||||
assert.deepEqual(areasFor({ area: 'dev', sources: {}, mojo: { source: 'def main(): pass' } }), ['dev']);
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 12: the Mojo badges. The generated label (where the Mojo came from) and the godbolt badge (whether the real
|
||||
// compiler was asked about exactly this source) are independent, both are data a view reads from the session, and
|
||||
// neither can come from a link or a file.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { stateForProblem, problemById, PROBLEMS } from '../dist/core/catalog.js';
|
||||
import { mojoProvenance } from '../dist/core/provenance.js';
|
||||
import { compiledStatus, compileHash, forgetCompiles } from '../dist/core/compiles.js';
|
||||
import { normalize } from '../dist/core/state.js';
|
||||
import { GENERATED_HEADER } from '../core/dist/sync/header.js';
|
||||
import { mojoFromPseudo } from '../core/dist/sync/hub.js';
|
||||
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
|
||||
const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null });
|
||||
const answer = (over = {}) => async () => ({ error: null, seconds: 1, answer: { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: '1\n', stderr: '', timedOut: false, asm: [], ...over } });
|
||||
|
||||
test('the Bridge\'s Mojo is always generated; elsewhere the state says', () => {
|
||||
const b = open('count-base', 'bridge');
|
||||
assert.equal(b.provenance(), 'generated');
|
||||
assert.equal(mojoProvenance(b, 'bridge'), 'generated');
|
||||
assert.equal(open('count-base', 'dev').provenance(), null, 'an exercise\'s own Mojo is nobody\'s translation');
|
||||
assert.equal(open('count-base', 'hw').provenance(), null);
|
||||
assert.equal(mojoProvenance({ area: 'dev', state: { mojoOrigin: 'generated-edited' } }), 'generated-edited');
|
||||
});
|
||||
|
||||
test('copying sets generated, editing sets generated-edited, and only the button clears it', async () => {
|
||||
const s = open('count-base');
|
||||
assert.ok(s.adoptGeneratedMojo());
|
||||
assert.equal(s.state.mojoOrigin, 'generated');
|
||||
const dev = new Session(s.state, { area: 'dev', storageId: null });
|
||||
assert.equal(dev.provenance(), 'generated');
|
||||
dev.setSource('mojo', dev.source('mojo') + '\n# my note');
|
||||
assert.equal(dev.provenance(), 'generated-edited');
|
||||
forgetCompiles();
|
||||
await dev.compile(answer());
|
||||
assert.equal(dev.provenance(), 'generated-edited', 'a successful compile does not clear it');
|
||||
assert.ok(dev.clearMojoOrigin());
|
||||
assert.equal(dev.provenance(), null);
|
||||
assert.equal(dev.state.mojoOrigin, undefined);
|
||||
assert.ok(!dev.source('mojo').includes(GENERATED_HEADER), 'the header comment goes with it');
|
||||
assert.ok(dev.source('mojo').includes('# my note'), 'the student\'s own lines stay');
|
||||
assert.equal(dev.clearMojoOrigin(), false, 'nothing left to clear');
|
||||
});
|
||||
|
||||
test('the Bridge cannot clear provenance, and a translation always starts with the header', () => {
|
||||
const s = open('count-base');
|
||||
assert.equal(s.clearMojoOrigin(), false);
|
||||
let n = 0;
|
||||
for (const p of PROBLEMS) {
|
||||
const pseudo = stateForProblem(p).sources.pseudo;
|
||||
if (!pseudo) continue;
|
||||
const m = mojoFromPseudo(pseudo, null).source;
|
||||
if (m) { n++; assert.ok(m.startsWith(GENERATED_HEADER), p.id); }
|
||||
}
|
||||
assert.ok(n > 5);
|
||||
});
|
||||
|
||||
test('the godbolt badge: shown for the compiled source, not for one more character, level or input', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'dev');
|
||||
assert.equal(s.compileBadge(), null, 'never compiled: no badge');
|
||||
await s.compile(answer());
|
||||
const b = s.compileBadge();
|
||||
assert.equal(b.kind, 'compiled');
|
||||
assert.equal(b.status.outcome, 'ran');
|
||||
assert.equal(b.status.exit, 0);
|
||||
const original = s.source('mojo');
|
||||
s.setSource('mojo', original + ' ');
|
||||
assert.equal(s.compileBadge().kind, 'edited', 'a one-character edit removes the badge');
|
||||
s.setSource('mojo', original);
|
||||
assert.equal(s.compileBadge().kind, 'compiled', 'the same text again is the same compile');
|
||||
const back = open('count-base', 'dev');
|
||||
assert.equal(back.compileBadge().kind, 'compiled', 'the same text again is the same compile');
|
||||
back.setBuildLevel('default');
|
||||
assert.equal(back.compileBadge(), null, 'another build level was never asked');
|
||||
back.setBuildLevel('O0');
|
||||
back.setInput('3\n');
|
||||
assert.equal(back.compileBadge(), null, 'another input was never asked');
|
||||
});
|
||||
|
||||
test('outcomes: did not compile, exit N, timed out', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'dev');
|
||||
await s.compile(answer({ compiled: false, executed: false, exitCode: null }));
|
||||
assert.equal(s.compileBadge().status.outcome, 'did-not-compile');
|
||||
forgetCompiles();
|
||||
await s.compile(answer({ exitCode: 3 }));
|
||||
assert.deepEqual([s.compileBadge().status.outcome, s.compileBadge().status.exit], ['ran', 3]);
|
||||
forgetCompiles();
|
||||
await s.compile(answer({ timedOut: true }));
|
||||
assert.equal(s.compileBadge().status.outcome, 'timed-out');
|
||||
});
|
||||
|
||||
test('a failed request (no answer) leaves no badge', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'dev');
|
||||
await s.compile(async () => ({ answer: null, error: 'offline', seconds: 1 }));
|
||||
assert.equal(s.compileBadge(), null);
|
||||
});
|
||||
|
||||
test('the badge survives a new Session and the full answers being dropped, but is not in the state, a link or a file', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'dev');
|
||||
await s.compile(answer());
|
||||
const src = s.source('mojo');
|
||||
assert.equal(compiledStatus(src, '', 'O0').outcome, 'ran');
|
||||
assert.equal(compiledStatus(src, '', 'O0').level, 'O0');
|
||||
assert.ok(store.has('pplus.compiled'));
|
||||
store.delete('pplus.compiles'); // the full answers are gone; the summary index stays
|
||||
assert.equal(open('count-base', 'dev').compileBadge().kind, 'compiled');
|
||||
const text = JSON.stringify(s.state);
|
||||
assert.ok(!/compiled|godbolt|pplus\./i.test(text.replace(/"compiler"/g, '')), 'nothing about a compile in the state');
|
||||
forgetCompiles(); // someone else's browser: the same link, no compile
|
||||
const theirs = new Session(normalize(JSON.parse(text)), { area: 'dev', storageId: null });
|
||||
assert.equal(theirs.compileBadge(), null);
|
||||
});
|
||||
|
||||
test('both badges can show together, and the hash covers source, input and level', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'bridge');
|
||||
await s.compile(answer());
|
||||
assert.equal(s.provenance(), 'generated');
|
||||
assert.equal(s.compileBadge().kind, 'compiled');
|
||||
assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', '', 'default'));
|
||||
assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', 'x', 'O0'));
|
||||
assert.notEqual(compileHash('a', '', 'O0'), compileHash('a ', '', 'O0'));
|
||||
});
|
||||
|
||||
test('Compile & run on unchanged work shows the kept answer and sends nothing; asking again is a choice', async () => {
|
||||
forgetCompiles();
|
||||
const s = open('count-base', 'dev');
|
||||
assert.equal(s.keptCompile(), null, 'nothing kept before the first answer');
|
||||
let sent = 0;
|
||||
const fake = async () => { sent++; return { error: null, seconds: 1, answer: { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: `${sent}\n`, stderr: '', timedOut: false, asm: [] } }; };
|
||||
const first = await s.compile(fake);
|
||||
assert.equal(sent, 1);
|
||||
assert.equal(s.keptCompile(), first, 'the same source, input and level: the kept answer');
|
||||
assert.equal(s.reusedCompile(), null);
|
||||
s.reuseCompile(s.keptCompile());
|
||||
assert.equal(sent, 1, 'nothing sent');
|
||||
assert.equal(s.reusedCompile(), first, 'the view can say the answer was kept, not asked');
|
||||
assert.equal(s.lastCompile().record, first);
|
||||
// another level, another input, one more character: nothing kept for them
|
||||
assert.equal(s.keptCompile('default'), null);
|
||||
s.setInput('7');
|
||||
assert.equal(s.keptCompile(), null);
|
||||
s.setInput('');
|
||||
assert.equal(s.keptCompile(), first);
|
||||
const src = s.source('mojo');
|
||||
s.setSource('mojo', src + ' ');
|
||||
assert.equal(s.keptCompile(), null);
|
||||
s.setSource('mojo', src);
|
||||
// asking again, on purpose, sends and is no longer "kept"
|
||||
const again = await s.compile(fake);
|
||||
assert.equal(sent, 2);
|
||||
assert.equal(s.reusedCompile(), null);
|
||||
assert.equal(s.keptCompile(), again);
|
||||
// a request that failed is not an answer to show again
|
||||
forgetCompiles();
|
||||
const t = open('match', 'dev');
|
||||
await t.compile(async () => ({ answer: null, error: 'offline', seconds: 0 }));
|
||||
assert.equal(t.keptCompile(), null);
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 10 (and the part of stage 11 it needs): the Bridge's session behavior, without a DOM. In the Bridge the
|
||||
// Mojo pane is the literal translation of the pseudo, computed and never stored; the views that read a program
|
||||
// (trace, checker, tests, proof) work on the hub's pseudo; a pane that is not in step is not stepped; "Edit in
|
||||
// Developer" copies the generated Mojo out and records that it was generated.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { PROBLEMS, stateForProblem, problemById } from '../dist/core/catalog.js';
|
||||
import { SyncHub } from '../core/dist/sync/hub.js';
|
||||
import { normalize } from '../dist/core/state.js';
|
||||
import { GENERATED_HEADER } from '../core/dist/sync/header.js';
|
||||
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null });
|
||||
|
||||
test('in the Bridge the Mojo pane is the generated Mojo, not the stored Mojo; elsewhere it is the state\'s own', () => {
|
||||
const own = stateForProblem(problemById('count-base')).sources.mojo;
|
||||
assert.ok(own && !own.startsWith('# Generated'), 'the exercise has its own Mojo');
|
||||
const bridge = open('count-base', 'bridge');
|
||||
assert.ok(bridge.source('mojo').startsWith(GENERATED_HEADER), 'the Bridge shows the literal translation, header first');
|
||||
assert.equal(bridge.source('mojo'), bridge.derivedMojo().source);
|
||||
assert.equal(bridge.state.sources.mojo, own, 'the stored Mojo is untouched');
|
||||
assert.equal(open('count-base', 'dev').source('mojo'), own);
|
||||
assert.equal(open('count-base', 'hw').source('mojo'), own);
|
||||
assert.equal(new Session(stateForProblem(problemById('count-base')), { storageId: null }).source('mojo'), own, 'a session with no area (an embed of one pane) shows the state\'s own Mojo');
|
||||
});
|
||||
|
||||
test('the Bridge\'s Mojo follows an edit in any linked pane, and every view of it reads the generated source', () => {
|
||||
const s = open('count-base');
|
||||
const before = s.source('mojo');
|
||||
s.setSource('pseudo', s.source('pseudo').replace('Total <- 0', 'Total <- 3'));
|
||||
assert.notEqual(s.source('mojo'), before);
|
||||
assert.match(s.source('mojo'), /total = 3/);
|
||||
// the checker, the stepper and the tests read it
|
||||
s.setLang('mojo');
|
||||
assert.equal(s.parsedMojo().program.source ?? s.source('mojo'), s.source('mojo'));
|
||||
assert.deepEqual(s.parsedMojo().diagnostics.filter((d) => d.severity === 'error'), []);
|
||||
const tr = s.trace();
|
||||
assert.ok(tr && !tr.error, 'the generated Mojo steps in the interpreter');
|
||||
assert.ok(tr.output.some((l) => /3|4|5|6|7|8|9/.test(l)), 'and prints a count that includes the changed start');
|
||||
assert.ok(s.tests().length >= 0);
|
||||
// an edit in lingo reaches it too
|
||||
const lingo = s.source('lingo');
|
||||
assert.match(lingo, /Start with Total at 3\./, 'the English was regenerated from the pseudo');
|
||||
s.setSource('lingo', lingo.replace('Start with Total at 3.', 'Start with Total at 10.'));
|
||||
assert.match(s.source('mojo'), /total = 10/);
|
||||
});
|
||||
|
||||
test('trace steps the pseudo, not a stale pane', () => {
|
||||
const s = open('count-base');
|
||||
s.setLang('lingo');
|
||||
assert.equal(s.traceLang(), 'lingo', 'an in-step lingo pane is stepped as English');
|
||||
s.setSource('pseudo', 'FUNCTION BROKEN(\nRETURN'); // pseudo has errors: lingo is now stale
|
||||
assert.equal(s.linkState('lingo').kind, 'stale');
|
||||
assert.equal(s.traceLang(), 'pseudo', 'lingo holds text the pseudo has moved on from');
|
||||
});
|
||||
|
||||
test('prove and tests work on the hub\'s pseudo, with the speco woven', () => {
|
||||
const s = open('count-base-proved');
|
||||
s.setLang('lingo');
|
||||
s.setSource('lingo', s.source('lingo').replace('Add 1 to Total.', 'Add 1 to Total.')); // no change: nothing to do
|
||||
const lingo = s.source('lingo');
|
||||
s.setSource('lingo', lingo + '\n'); // an edit in English
|
||||
assert.equal(s.state.sync.authority, 'lingo');
|
||||
assert.match(s.source('pseudo'), /ENSURE/, 'the contracts are in the pseudo the English lowered to');
|
||||
const proof = s.proof();
|
||||
assert.ok(proof && proof.report.counts.total > 0, 'there is something to prove');
|
||||
assert.equal(proof.report.counts.broken, 0);
|
||||
assert.ok(s.tests().length > 0, 'tests are generated from the pseudo');
|
||||
});
|
||||
|
||||
test('Edit in Developer copies the generated Mojo into the state and records that it was generated', () => {
|
||||
const s = open('count-base');
|
||||
const generated = s.derivedMojo().source;
|
||||
assert.ok(s.wouldReplaceMojo(), 'the exercise\'s own Mojo would be replaced: the shell asks first');
|
||||
assert.equal(s.state.mojoOrigin, undefined);
|
||||
assert.ok(s.adoptGeneratedMojo());
|
||||
assert.equal(s.state.sources.mojo, generated);
|
||||
assert.equal(s.state.mojoOrigin, 'generated');
|
||||
assert.equal(s.state.lang, 'mojo');
|
||||
assert.equal(s.wouldReplaceMojo(), false, 'it already holds this program');
|
||||
// the Developer area shows it, and the first edit makes it theirs
|
||||
const dev = new Session(s.state, { area: 'dev', storageId: null });
|
||||
assert.equal(dev.source('mojo'), generated);
|
||||
dev.setSource('mojo', generated + '\n# mine\n');
|
||||
assert.equal(dev.state.mojoOrigin, 'generated-edited');
|
||||
dev.setSource('mojo', generated + '\n# mine again\n');
|
||||
assert.equal(dev.state.mojoOrigin, 'generated-edited');
|
||||
// a state with no pseudo has nothing to adopt
|
||||
const empty = new Session(normalize({ v: 3 }), { area: 'bridge', storageId: null });
|
||||
assert.equal(empty.adoptGeneratedMojo(), false);
|
||||
assert.equal(empty.state.mojoOrigin, undefined);
|
||||
});
|
||||
|
||||
test('mojoOrigin is validated, and is only ever set on Mojo the student did not write', () => {
|
||||
assert.equal(normalize({ v: 3, mojoOrigin: 'generated' }).mojoOrigin, 'generated');
|
||||
assert.equal(normalize({ v: 3, mojoOrigin: 'generated-edited' }).mojoOrigin, 'generated-edited');
|
||||
assert.equal(normalize({ v: 3, mojoOrigin: 'hand-written' }).mojoOrigin, undefined);
|
||||
const s = open('count-base', 'dev');
|
||||
s.setSource('mojo', s.source('mojo') + '\n# note\n');
|
||||
assert.equal(s.state.mojoOrigin, undefined, 'editing the exercise\'s own Mojo does not make it generated');
|
||||
});
|
||||
|
||||
test('line maps reach the Mojo: a pseudo line finds its Mojo lines and back', () => {
|
||||
const s = open('count-base');
|
||||
const maps = s.lineMaps();
|
||||
const pseudo = s.source('pseudo').split('\n');
|
||||
const at = pseudo.findIndex((l) => /Total <- Total \+ 1/.test(l)) + 1;
|
||||
const mojoLines = SyncHub.relate(maps, 'pseudo', at, 'mojo');
|
||||
assert.ok(mojoLines.length, 'the line has a Mojo line');
|
||||
assert.match(s.source('mojo').split('\n')[mojoLines[0] - 1], /total = total \+ 1/);
|
||||
assert.ok(SyncHub.relate(maps, 'mojo', mojoLines[0], 'pseudo').includes(at));
|
||||
// lingo line -> pseudo line, for a problem whose lingo was authored
|
||||
const lingo = s.source('lingo').split('\n');
|
||||
const l = lingo.findIndex((t) => /add 1 to Count/.test(t)) + 1;
|
||||
const p = SyncHub.relate(maps, 'lingo', l, 'pseudo');
|
||||
assert.ok(Array.isArray(p));
|
||||
});
|
||||
|
||||
test('every Bridge problem opens with generated Mojo that names itself and checks clean', () => {
|
||||
let n = 0;
|
||||
for (const p of PROBLEMS) {
|
||||
if (p.area !== 'bridge') continue;
|
||||
const s = new Session(stateForProblem(p), { area: 'bridge', storageId: null });
|
||||
if (!s.source('pseudo').trim()) continue;
|
||||
const m = s.source('mojo');
|
||||
if (!m) continue; // pseudo that does not read (five-bugs, by design)
|
||||
assert.ok(m.startsWith(GENERATED_HEADER), p.id);
|
||||
n++;
|
||||
}
|
||||
assert.ok(n >= 12, `${n} problems`);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// pplus-web pins pplus-core (core/) and core pins pplus-library (core/library/), each by commit. A pointer that names
|
||||
// a commit the checkout does not have, or a checkout left behind its pointer, builds and tests the site from other
|
||||
// sources than the commits say: the chain sat broken that way on main for five weeks once, and nothing said so
|
||||
// (docs/deploy.md, "Moving the pointers"). These run the cheap half of `pixi run release-check` (scripts/release.mjs):
|
||||
// no network, no build.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { quickCheck } from '../scripts/release.mjs';
|
||||
|
||||
test('every pointer names a commit its checkout has, and no checkout is behind its pointer', (t) => {
|
||||
const found = quickCheck();
|
||||
for (const f of found.filter((x) => x.level === 'note')) t.diagnostic(f.text);
|
||||
// under CI there is always a checkout to read: a pointer nobody could read is a gap, not a pass
|
||||
if (process.env.CI) assert.ok(!found.some((x) => x.unread), found.map((x) => x.text).join('\n'));
|
||||
assert.deepEqual(found.filter((x) => x.level === 'problem').map((x) => x.text), []);
|
||||
});
|
||||
|
||||
const git = (dir, ...args) => {
|
||||
const r = spawnSync('git', ['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', '-C', dir, ...args], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
return r.stdout.trim();
|
||||
};
|
||||
|
||||
/** A parent repository whose submodule `child` (a repository of two commits) is pinned at `pin` and checked out at `at`. */
|
||||
function fakeChain(pin, at) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-chain-'));
|
||||
git(root, 'init', '-q');
|
||||
fs.writeFileSync(path.join(root, 'package.json'), '{"name":"parent"}\n');
|
||||
const child = path.join(root, 'child');
|
||||
fs.mkdirSync(child);
|
||||
git(child, 'init', '-q');
|
||||
const commits = [];
|
||||
for (const n of ['one', 'two']) { fs.writeFileSync(path.join(child, 'f'), n); git(child, 'add', 'f'); git(child, 'commit', '-q', '-m', n); commits.push(git(child, 'rev-parse', 'HEAD')); }
|
||||
fs.writeFileSync(path.join(root, '.gitmodules'), '[submodule "child"]\n\tpath = child\n\turl = https://example.invalid/child.git\n\tbranch = main\n');
|
||||
const sha = pin === 'missing' ? 'f'.repeat(40) : commits[pin];
|
||||
git(root, 'update-index', '--add', '--cacheinfo', `160000,${sha},child`);
|
||||
git(child, 'checkout', '-q', commits[at]);
|
||||
return { root, commits };
|
||||
}
|
||||
|
||||
test('a pointer to a commit the checkout lacks, or a checkout behind its pointer, is a problem that names the fix', () => {
|
||||
if (spawnSync('git', ['--version']).status !== 0) assert.fail('git is not on the PATH');
|
||||
const cases = [
|
||||
{ pin: 'missing', at: 1, want: /does not have that commit\. Fix: git submodule update --init --recursive/ },
|
||||
{ pin: 1, at: 0, want: /behind the pinned .* Fix: git submodule update --recursive/ },
|
||||
];
|
||||
for (const c of cases) {
|
||||
const { root } = fakeChain(c.pin, c.at);
|
||||
try {
|
||||
const problems = quickCheck(root).filter((x) => x.level === 'problem');
|
||||
assert.equal(problems.length, 1, JSON.stringify(problems));
|
||||
assert.match(problems[0].text, c.want);
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); }
|
||||
}
|
||||
// at the pointer: nothing to say; ahead of it (work in progress, not yet pinned): a note, not a problem
|
||||
for (const [pin, at, notes] of [[1, 1, 0], [0, 1, 1]]) {
|
||||
const { root } = fakeChain(pin, at);
|
||||
try {
|
||||
const found = quickCheck(root);
|
||||
assert.deepEqual(found.filter((x) => x.level === 'problem'), []);
|
||||
assert.equal(found.filter((x) => x.level === 'note').length, notes);
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); }
|
||||
}
|
||||
});
|
||||
|
||||
test('build-info names the three commits the site is built from, as git has them', async () => {
|
||||
const { buildInfo } = await import('../scripts/build-info.mjs');
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
if (!fs.existsSync(path.join(ROOT, '.git')) && !process.env.CI) return; // a package has no commits to name
|
||||
const info = buildInfo();
|
||||
const head = (dir) => spawnSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim();
|
||||
assert.equal(info.web.commit, head(ROOT));
|
||||
assert.equal(info.core.commit, head(path.join(ROOT, 'core')));
|
||||
assert.equal(info.library.commit, head(path.join(ROOT, 'core', 'library')));
|
||||
assert.equal(info.web.version, JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version);
|
||||
assert.equal(info.core.version, JSON.parse(fs.readFileSync(path.join(ROOT, 'core', 'package.json'), 'utf8')).version);
|
||||
assert.match(info.mojo, /^\d+\.\d+\.\d+$/);
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The site's own words (the home page, index.html, the README, docs/app.md, the library and the Quarto pages) say
|
||||
// what is held and no more: the claims ledger (pplus-core work/release/claims.md) found sentences that claimed more.
|
||||
// These tests hold the sentences that a test can hold, and keep the overstated ones from coming back.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { installDocument } from '../dist/quarto/dom.js';
|
||||
|
||||
installDocument();
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k), key: (i) => [...store.keys()][i] ?? null, get length() { return store.size; } };
|
||||
const { homeView } = await import('../dist/ui/home.js');
|
||||
const { libraryView } = await import('../dist/ui/library.js');
|
||||
const { DESCRIPTION } = await import('../dist/core/site.js');
|
||||
const { AREAS } = await import('../dist/core/areas.js');
|
||||
const { PROBLEMS, problemById, stateForProblem } = await import('../dist/core/catalog.js');
|
||||
const { Session } = await import('../dist/core/session.js');
|
||||
const { machineView } = await import('../dist/ui/views/panels.js');
|
||||
const { generatedLabel } = await import('../dist/ui/provenance.js');
|
||||
|
||||
const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8');
|
||||
const squash = (s) => s.replace(/\s+/g, ' ');
|
||||
const home = homeView();
|
||||
const homeText = squash(home.textContent);
|
||||
const html = read('index.html');
|
||||
const meta = /<meta name="description"\s+content="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||
|
||||
test('one sentence says what Programming+ is, in index.html, the home page, the README and docs/app.md', () => {
|
||||
assert.match(DESCRIPTION, /^Programming\+ takes a procedure from an idea to Mojo to the machine\.$/);
|
||||
assert.ok(meta.startsWith(DESCRIPTION), 'the meta description starts with it');
|
||||
assert.match(html, /<title>Programming\+: from an idea to Mojo to the machine<\/title>/);
|
||||
const hero = squash(home.querySelector('.hero').textContent);
|
||||
assert.ok(hero.includes(DESCRIPTION), 'the hero says it');
|
||||
const firstParagraph = (md) => md.split('\n\n').find((p) => !p.startsWith('#'));
|
||||
assert.ok(firstParagraph(read('README.md')).startsWith(DESCRIPTION), 'the README opens with it');
|
||||
assert.ok(firstParagraph(read('docs/app.md')).startsWith(DESCRIPTION), 'docs/app.md opens with it');
|
||||
});
|
||||
|
||||
test('each invented notation name is said what it is where the home page first uses it', () => {
|
||||
const gloss = { lingo: /plain[- ]English/i, matho: /equations/i, pseudo: /pseudocode/i, speco: /specification/i };
|
||||
for (const [name, what] of Object.entries(gloss)) {
|
||||
const at = homeText.search(new RegExp(`\\b${name}\\b`));
|
||||
assert.ok(at >= 0, `${name} is on the page`);
|
||||
const around = homeText.slice(Math.max(0, at - 80), at + 80);
|
||||
assert.match(around, what, `the first "${name}" is glossed: …${around}…`);
|
||||
}
|
||||
// the Bridge's tagline names them with what they are, and it is the first place on the page they appear
|
||||
assert.match(AREAS.bridge.tagline, /plain-English steps \(lingo\), equations \(matho\) or pseudocode \(pseudo\)/);
|
||||
});
|
||||
|
||||
test('the home page\'s samples are real runs: each card shows what the engines made as the page loaded', () => {
|
||||
const cards = home.querySelectorAll('.area-card');
|
||||
assert.equal(cards.length, 3);
|
||||
const bridge = home.querySelector('.area-card-bridge');
|
||||
assert.equal(bridge.querySelectorAll('.area-step').length, 4, 'matho, pseudo, lingo and Mojo');
|
||||
for (const pre of bridge.querySelectorAll('pre')) assert.ok(pre.textContent.trim().length > 5, 'each notation has text');
|
||||
const steps = home.querySelector('.area-card-dev').querySelectorAll('.feat-steps li');
|
||||
assert.ok(steps.length >= 5, 'the first steps of count_base');
|
||||
const regs = home.querySelector('.area-card-hw').querySelectorAll('.area-regs tr');
|
||||
assert.equal(regs.length, 5, 'five registers of the machine at the first load');
|
||||
assert.match(squash(home.querySelector('.proof-counts').textContent), /^[1-9]\d* proved ?0 broken ?0 open$/);
|
||||
});
|
||||
|
||||
test('every problem with Mojo has Mojo verified on the real compiler, as the problem list says', () => {
|
||||
assert.match(homeText, /each one with Mojo has a program verified on the real compiler/);
|
||||
const withMojo = PROBLEMS.filter((p) => p.mojo || p.sources.mojo);
|
||||
assert.ok(withMojo.length > 10);
|
||||
for (const p of withMojo) assert.ok(p.mojo?.verified, `${p.id}: verified on the pinned compiler`);
|
||||
});
|
||||
|
||||
test('where the Hardware area states a cost, it says it is the model machine\'s', () => {
|
||||
assert.match(homeText, /the cycles each instruction costs on the model machine/);
|
||||
assert.match(AREAS.hw.tagline, /model machine/);
|
||||
assert.match(meta, /Hardware steps its x86-64 on a model machine/);
|
||||
// the Counters card (the board, the machine embed, the Quarto pplus-machine view all draw it)
|
||||
const st = stateForProblem(problemById('asm-two-pointers')); st.lang = 'asm';
|
||||
const root = document.createElement('div');
|
||||
machineView(new Session(st), root)();
|
||||
const text = squash(root.textContent);
|
||||
assert.match(text, /cycles/);
|
||||
assert.match(text, /a model machine: every count here is the model's, not a measurement of a real processor/);
|
||||
});
|
||||
|
||||
test('the generated label promises nothing a compiler did not answer', () => {
|
||||
const tip = generatedLabel('generated').getAttribute('title');
|
||||
assert.doesNotMatch(tip, /\bIt runs\b/);
|
||||
assert.match(tip, /stops there with an error instead of guessing/);
|
||||
});
|
||||
|
||||
test('the overstatements the claims ledger found stay gone', () => {
|
||||
const surfaces = {
|
||||
'home page': homeText,
|
||||
'index.html': html,
|
||||
'README.md': read('README.md'),
|
||||
'AGENTS.md': read('AGENTS.md'),
|
||||
'docs/app.md': read('docs/app.md'),
|
||||
'docs/deploy.md': read('docs/deploy.md'),
|
||||
'quarto/README.md': read('quarto/README.md'),
|
||||
'library page': squash(libraryView().textContent),
|
||||
'src/ui/quarto.ts': read('src/ui/quarto.ts'),
|
||||
};
|
||||
const never = [
|
||||
[/Everything runs in the browser/i, 'H1: Compile & run goes to godbolt.org'],
|
||||
[/checked against the real compiler/i, 'H2: held to its answers on the corpus, asked about the rest'],
|
||||
[/every step and every value in one Run view|every step and value in view|Every step, every value/i, 'H3: the interpreter reads a subset'],
|
||||
[/it runs and it can be compiled/i, 'H4'],
|
||||
[/completely specify any procedure|the notation is for any procedure/i, 'H5'],
|
||||
[/registers, caches and pipeline it runs on/i, 'H7'],
|
||||
[/It is built for the sciences/i, 'H8: an opinion'],
|
||||
[/every short input|the smallest input/i, 'H9, A12: every DNA string up to three letters; a smaller input'],
|
||||
[/The first group is computational biology/i, 'H10: the groups are by technique'],
|
||||
[/no runtime dependenc/i, 'R4, R19: CodeMirror is vendored'],
|
||||
[/gives `nan` in Mojo/i, 'A1: inf, -inf or nan'],
|
||||
[/a program that stops printing what it should fails the render/i, 'Q1: only with pplus-strict'],
|
||||
[/The prover is sound/i, 'A5: meant to be sound'],
|
||||
[/checked at every level/i, 'library: open, skipped and unverified checks exist'],
|
||||
[/interpreter are still JavaScript|typed only by their tests/i, "core's pseudo parser, checker and interpreter are strict TypeScript (core/src/engines/pseudo/*.ts)"],
|
||||
[/interpreter declines `chr`, `ord`|a string doubled in a loop/i, "core's Mojo interpreter runs ord and chr, and its run limits stop a doubled String (core/docs/limits.md)"],
|
||||
[/restructure plan|The plan said/i, 'a plan that is not in the repository'],
|
||||
[/labelled|colour|behaviour|optimis/i, 'US English'],
|
||||
];
|
||||
for (const [where, text] of Object.entries(surfaces)) for (const [re, why] of never) assert.doesNotMatch(text, re, `${where}: ${why}`);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The course stylesheets in styles/course/ are copies of the course site's files.
|
||||
// Each must still have the hash its README records, so a change is made upstream and copied, not edited here.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const DIR = new URL('../styles/course/', import.meta.url);
|
||||
|
||||
test('the course stylesheets are the course site\'s files, unchanged', () => {
|
||||
const readme = fs.readFileSync(new URL('README.md', DIR), 'utf8');
|
||||
const rows = [...readme.matchAll(/^\| `([\w-]+\.css)` \| `static\/css\/[^`]+` \|[^|]*\| `([0-9a-f]{64})` \|$/gm)];
|
||||
assert.deepEqual(rows.map((r) => r[1]).sort(), ['asm86.css', 'kit.css', 'tokens.css']);
|
||||
for (const [, file, want] of rows) {
|
||||
const got = crypto.createHash('sha256').update(fs.readFileSync(new URL(file, DIR))).digest('hex');
|
||||
assert.equal(got, want, `styles/course/${file} differs from the copy the README records`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the bridge supplies every page variable the course stylesheets read', () => {
|
||||
const bridge = fs.readFileSync(new URL('bridge.css', DIR), 'utf8');
|
||||
const read = new Set();
|
||||
for (const f of ['tokens.css', 'kit.css', 'asm86.css']) {
|
||||
for (const m of fs.readFileSync(new URL(f, DIR), 'utf8').matchAll(/var\((--bs-[\w-]+)/g)) read.add(m[1]);
|
||||
}
|
||||
for (const v of read) assert.match(bridge, new RegExp(`${v}\\s*:`), `bridge.css does not set ${v}`);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The Content-Security-Policy in docs/Caddyfile is the one the site runs under: these tests hold it to index.html
|
||||
// (every inline script is allowed by its hash, nothing loads from another origin) and to what the app sends.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { GODBOLT_BASE } from '../core/dist/mojo/generated/pin.js';
|
||||
|
||||
const caddy = readFileSync(new URL('../docs/Caddyfile', import.meta.url), 'utf8');
|
||||
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||
const header = (name) => { const m = new RegExp(`^\\s*${name}\\s+"([^"]*)"`, 'm').exec(caddy); return m ? m[1] : null; };
|
||||
const csp = header('Content-Security-Policy');
|
||||
const directive = (name) => (csp ?? '').split(';').map((d) => d.trim().split(/\s+/)).find((d) => d[0] === name)?.slice(1) ?? null;
|
||||
|
||||
test('the Caddy block sets a CSP and the other security headers', () => {
|
||||
assert.ok(csp, 'Content-Security-Policy');
|
||||
assert.equal(header('Referrer-Policy'), 'no-referrer');
|
||||
assert.equal(header('X-Content-Type-Options'), 'nosniff');
|
||||
assert.match(header('Permissions-Policy') ?? '', /camera=\(\)/);
|
||||
assert.doesNotMatch(caddy, /^\s*X-Frame-Options\s/m, 'course pages embed the app: framing is decided by frame-ancestors alone');
|
||||
for (const d of ['default-src', 'script-src', 'style-src', 'font-src', 'connect-src', 'object-src', 'base-uri', 'frame-ancestors']) assert.ok(directive(d), d);
|
||||
assert.deepEqual(directive('object-src'), ["'none'"]);
|
||||
});
|
||||
|
||||
test('every inline script of index.html is allowed by its hash, and scripts allow nothing looser', () => {
|
||||
const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
|
||||
assert.ok(inline.length >= 2, 'the theme script and the import map');
|
||||
const allowed = directive('script-src');
|
||||
for (const body of inline) {
|
||||
const hash = `'sha256-${createHash('sha256').update(body, 'utf8').digest('base64')}'`;
|
||||
assert.ok(allowed.includes(hash), `index.html changed an inline script: put ${hash} in script-src (docs/Caddyfile)`);
|
||||
}
|
||||
for (const loose of ["'unsafe-inline'", "'unsafe-eval'", '*', 'data:', 'https:']) assert.ok(!allowed.includes(loose), `script-src ${loose}`);
|
||||
});
|
||||
|
||||
test('the page loads nothing from another origin (the fonts are the site\'s own)', () => {
|
||||
const refs = [...html.matchAll(/\b(?:href|src)="([^"]+)"/g)].map((m) => m[1]).filter((u) => !u.startsWith('data:'));
|
||||
assert.ok(refs.length > 3);
|
||||
for (const u of refs) assert.ok(!/^(https?:)?\/\//.test(u), `index.html loads ${u}`);
|
||||
assert.doesNotMatch(html, /fonts\.googleapis|fonts\.gstatic/);
|
||||
assert.deepEqual(directive('font-src'), ["'self'"]);
|
||||
});
|
||||
|
||||
test('connect-src allows the compile backend and nothing else outside the site', () => {
|
||||
const origin = new URL(GODBOLT_BASE).origin;
|
||||
const allowed = directive('connect-src');
|
||||
assert.ok(allowed.includes(origin), `Compile & run posts to ${origin}`);
|
||||
assert.deepEqual(allowed.filter((s) => s !== "'self'"), [origin]);
|
||||
});
|
||||
|
||||
test('the fonts the page names are in the repository, with their license', () => {
|
||||
const css = readFileSync(new URL('../fonts/plex.css', import.meta.url), 'utf8');
|
||||
const files = [...css.matchAll(/url\("\.\/([^"]+)"\)/g)].map((m) => m[1]);
|
||||
assert.equal(files.length, 7);
|
||||
for (const f of files) assert.ok(readFileSync(new URL(`../fonts/${f}`, import.meta.url)).length > 10000, f);
|
||||
assert.match(readFileSync(new URL('../fonts/LICENSE.txt', import.meta.url), 'utf8'), /SIL Open Font License, Version 1\.1/);
|
||||
assert.match(readFileSync(new URL('../scripts/assemble.sh', import.meta.url), 'utf8'), /\bfonts\b/, 'assemble.sh copies fonts/ into the site');
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Every code pane is the CodeMirror editor (src/ui/editor.ts), never a plain <textarea>.
|
||||
// A textarea loses highlighting, line numbers, the teaching gutter (diagnostics, breakpoints,
|
||||
// run counts, the current line), hover help, and search, so these checks fail loudly if a
|
||||
// refactor swaps one in or the vendored CodeMirror stops being built.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const src = (p) => fs.readFileSync(new URL(`../${p}`, import.meta.url), 'utf8');
|
||||
|
||||
test('the editor is CodeMirror 6, vendored and built into dist/', () => {
|
||||
assert.match(src('src/ui/editor.ts'), /from '\.\.\/vendor\/codemirror\.js'/);
|
||||
assert.ok(fs.existsSync(new URL('../dist/vendor/codemirror.js', import.meta.url)), 'dist/vendor/codemirror.js is missing: the build no longer ships the editor');
|
||||
assert.ok(fs.statSync(new URL('../dist/vendor/codemirror.js', import.meta.url)).size > 100_000, 'dist/vendor/codemirror.js is too small to be CodeMirror');
|
||||
});
|
||||
|
||||
test('the workspace and the embeds make their code panes with Editor', () => {
|
||||
for (const f of ['src/ui/shell.ts', 'src/ui/embed.ts']) {
|
||||
const text = src(f);
|
||||
assert.match(text, /import \{[^}]*\bEditor\b[^}]*\} from '\.\/editor\.js'/, `${f} no longer imports Editor`);
|
||||
assert.match(text, /new Editor\(/, `${f} no longer makes an Editor`);
|
||||
}
|
||||
});
|
||||
|
||||
test('textareas are only for the small setup and input boxes, never for code', () => {
|
||||
for (const f of ['src/ui/shell.ts', 'src/ui/embed.ts']) {
|
||||
for (const m of src(f).matchAll(/el\('textarea',\s*\{([^}]*)\}/g)) {
|
||||
assert.match(m[1], /setup-ta/, `${f} makes a textarea that is not a setup or input box: ${m[0].slice(0, 80)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// What anyone on the internet can hand the app: a link, a file, a saved state, a program. Each must end in a
|
||||
// message or a working page, never an exception, a hang, or someone else's work saved over the reader's.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { decodeState, encodeState, normalize, parseRoute, isUnknownRoute, readStateFile, StateError, LIMITS, emptyState } from '../dist/core/state.js';
|
||||
import { Session, sharedSession, engineStopMessage } from '../dist/core/session.js';
|
||||
import { markBusy, takeCrashed, settle, setAside, clearBusy } from '../dist/core/guard.js';
|
||||
import { listVersions } from '../dist/core/versions.js';
|
||||
|
||||
const b64url = (bytes) => Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
async function deflate(text) {
|
||||
const s = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw'));
|
||||
return new Uint8Array(await new Response(s).arrayBuffer());
|
||||
}
|
||||
const fakeStore = () => {
|
||||
const m = new Map();
|
||||
return { m, getItem: (k) => m.get(k) ?? null, setItem: (k, v) => void m.set(k, String(v)), removeItem: (k) => void m.delete(k), key: (i) => [...m.keys()][i] ?? null, get length() { return m.size; } };
|
||||
};
|
||||
async function rejectsWith(p, re) {
|
||||
await assert.rejects(p, (e) => { assert.ok(e instanceof StateError, `a StateError, not ${e?.name}: ${e?.message}`); assert.match(e.message, re); return true; });
|
||||
}
|
||||
|
||||
test('a link that inflates past the limit (a decompression bomb) is refused before it is read', async () => {
|
||||
const bomb = await deflate(JSON.stringify({ v: 3, sources: { pseudo: 'x'.repeat(LIMITS.stateBytes * 4) } }));
|
||||
assert.ok(bomb.length < 40_000, 'the blob itself is small');
|
||||
await rejectsWith(decodeState(b64url(bomb)), /more than Programming\+ opens/);
|
||||
// uncompressed, behind the plain-text marker, a link cannot hold that much at all
|
||||
await rejectsWith(decodeState('~' + b64url(Buffer.from('{"v":3,"sources":{"pseudo":"' + 'x'.repeat(LIMITS.stateBytes) + '"}}'))), /longer than any Programming\+ makes/);
|
||||
});
|
||||
|
||||
test('a link longer than any the app writes is refused without decoding it', async () => {
|
||||
await rejectsWith(decodeState('A'.repeat(LIMITS.linkChars + 1)), /longer than any Programming\+ makes/);
|
||||
});
|
||||
|
||||
test('a cut-short, changed or garbage link says it is damaged', async () => {
|
||||
const good = await encodeState({ ...emptyState(), sources: { pseudo: 'OUTPUT 1\n'.repeat(40) } });
|
||||
await rejectsWith(decodeState(good.slice(0, Math.floor(good.length / 2))), /damaged/);
|
||||
await rejectsWith(decodeState('not base64!'), /damaged/);
|
||||
await rejectsWith(decodeState('~' + b64url(Buffer.from('{"v":3,'))), /damaged/);
|
||||
await rejectsWith(decodeState('~' + b64url(Buffer.from([0xff, 0xfe, 0x00]))), /damaged/);
|
||||
await rejectsWith(decodeState('AAAA'), /damaged/);
|
||||
// a whole link still opens
|
||||
assert.equal((await decodeState(good)).sources.pseudo, 'OUTPUT 1\n'.repeat(40));
|
||||
// a state from another format is empty, as before (docs/app.md)
|
||||
assert.deepEqual(await decodeState('~' + b64url(Buffer.from('{"v":2}'))), emptyState());
|
||||
});
|
||||
|
||||
test('a malformed escape in an address does not throw; an unknown embed view is the problems view', () => {
|
||||
assert.doesNotThrow(() => parseRoute('#/library/%E0%A4'));
|
||||
assert.deepEqual(parseRoute('#/bridge/p/%E0%A4'), { kind: 'problem', area: 'bridge', id: '%E0%A4' });
|
||||
assert.deepEqual(parseRoute('#/library/%E0'), { kind: 'library', id: '%E0' });
|
||||
const r = parseRoute('#/embed/<img onerror=x>/p/count-base');
|
||||
assert.equal(r.kind, 'embed'); assert.equal(r.view, 'problems');
|
||||
assert.doesNotThrow(() => parseRoute('#/embed/trace/p/%'));
|
||||
});
|
||||
|
||||
test('an address that names no page is told apart from the home page and its anchors', () => {
|
||||
for (const h of ['#/s/abc', '#/bridge/x', '#/p/count-base', '#/nope', '#/bridge/p/', '#/embed']) assert.ok(isUnknownRoute(h), h);
|
||||
for (const h of ['', '#', '#/', '#/#problems', '#/#reference', '#ref-pseudo', '#/bridge/p/count-base', '#/library', '#/quarto', '#/quarto#setup', '#/dev/s/abc']) assert.ok(!isUnknownRoute(h), h);
|
||||
});
|
||||
|
||||
test('only an anchor on the page already shown scrolls in place; from the library, #/#problems opens the home page', async () => {
|
||||
const { anchorOnly } = await import('../dist/core/state.js');
|
||||
assert.equal(anchorOnly('#/#problems', ['home', 'home-page']), true);
|
||||
assert.equal(anchorOnly('#/#problems', ['home', 'lib']), false, 'the library page is not the home page');
|
||||
assert.equal(anchorOnly('#/#problems', ['home', 'message-page']), false);
|
||||
assert.equal(anchorOnly('#/#reference', null), false);
|
||||
assert.equal(anchorOnly('#/nope/x', ['home', 'home-page']), false, 'an unknown address is rebuilt, with its note');
|
||||
assert.equal(anchorOnly('#/quarto#setup', ['home', 'qg']), true);
|
||||
assert.equal(anchorOnly('#/quarto#setup', ['home', 'home-page']), false);
|
||||
assert.equal(anchorOnly('#/bridge/p/count-base', ['home', 'home-page']), false);
|
||||
});
|
||||
|
||||
test('a problem id from a link is only ever an id', () => {
|
||||
assert.equal(normalize({ v: 3, problem: 'count-base' }).problem, 'count-base');
|
||||
assert.equal(normalize({ v: 3, problem: 'lib:md.LennardJones' }).problem, 'lib:md.LennardJones');
|
||||
for (const bad of ['', '../x', 'a b', '<script>', 'x'.repeat(200), 'a/b']) assert.equal(normalize({ v: 3, problem: bad }).problem, undefined, bad);
|
||||
});
|
||||
|
||||
test('a shared link never saves over the reader\'s own work on the problem it names', () => {
|
||||
const store = fakeStore();
|
||||
globalThis.localStorage = store;
|
||||
try {
|
||||
store.setItem('pplus.count-base', JSON.stringify({ v: 3, problem: 'count-base', sources: { pseudo: 'MY WORK' } }));
|
||||
const s = sharedSession(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), 'bridge');
|
||||
s.setSource('pseudo', 'OUTPUT 2'); s.setView('proof'); s.setT(3);
|
||||
assert.match(store.getItem('pplus.count-base'), /MY WORK/);
|
||||
assert.deepEqual([...store.m.keys()], ['pplus.count-base']);
|
||||
} finally { delete globalThis.localStorage; settle(null); }
|
||||
});
|
||||
|
||||
test('a .pplus.json that is not one says so; a real one opens with its versions', () => {
|
||||
assert.throws(() => readStateFile('hello'), (e) => e instanceof StateError && /not JSON/.test(e.message));
|
||||
for (const t of ['[1,2]', '{}', 'null', '42', '{"name":"package","version":"1.0.0"}']) assert.throws(() => readStateFile(t), (e) => e instanceof StateError && /not a Programming\+ state/.test(e.message), t);
|
||||
assert.throws(() => readStateFile(' '.repeat(LIMITS.stateBytes + 1)), (e) => e instanceof StateError && /larger than Programming\+ opens/.test(e.message));
|
||||
const file = JSON.stringify({ pplus: 1, savedAt: 'x', state: { v: 3, sources: { pseudo: 'OUTPUT 1' }, lang: 'pseudo' }, versions: [{ id: 'v1', name: 'a', at: 1, area: 'bridge', edits: {} }] });
|
||||
const r = readStateFile(file);
|
||||
assert.equal(r.state.sources.pseudo, 'OUTPUT 1'); assert.equal(r.versions.length, 1);
|
||||
// a bare state (no wrapper) opens too, and one from an earlier format opens empty, as a link does
|
||||
assert.equal(readStateFile('{"v":3,"sources":{"mojo":"def main():\\n pass"}}').state.sources.mojo, 'def main():\n pass');
|
||||
assert.deepEqual(readStateFile('{"v":2,"sources":{"pseudo":"OUTPUT 1"}}').state, emptyState());
|
||||
});
|
||||
|
||||
test('a pane nested past what a reader can follow gets a located answer from the reader, and the page keeps working', () => {
|
||||
// core's readers have limits of their own now (core docs/limits.md), so each of these is the reader's answer; the
|
||||
// session's catch is the net under them, and engineStopMessage is what it would say
|
||||
const deep = (o, c, n, mid = '1') => o.repeat(n) + mid + c.repeat(n);
|
||||
const ids = (s, lang) => s.diagnostics(lang).filter((d) => d.severity !== 'note' || d.id === 'unread').map((d) => d.id);
|
||||
const mojo = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: `def main():\n print(${deep('(', ')', 30000)})\n` } }), { area: 'dev', storageId: null });
|
||||
const d = mojo.diagnostics('mojo');
|
||||
// Mojo: not an error (the compiler takes thousands of levels), one note that Programming+ does not read it
|
||||
assert.equal(d.length, 1); assert.equal(d[0].id, 'unread'); assert.equal(d[0].line, 2); assert.match(d[0].message, /nested more than 200 levels deep/);
|
||||
assert.equal(mojo.trace().error.kind, 'unsupported');
|
||||
assert.deepEqual(mojo.trace().steps, []);
|
||||
assert.deepEqual(mojo.fuzz(), []);
|
||||
// a linked pane: opening it and editing it carry no exception to the views
|
||||
const lingo = new Session(normalize({ v: 3, lang: 'lingo', sources: { lingo: 'To f with n:\n the answer is ' + deep('(', ')', 30000) } }), { area: 'bridge', storageId: null });
|
||||
assert.deepEqual(ids(lingo, 'lingo'), ['too-long', 'too-deep']);
|
||||
assert.doesNotThrow(() => { lingo.source('pseudo'); lingo.trace(); lingo.proof(); lingo.allDiagnostics(); });
|
||||
const nested = new Session(normalize({ v: 3, lang: 'lingo', sources: { lingo: 'To f with n:\n the answer is ' + deep('(', ')', 300, 'n') + '.' } }), { area: 'bridge', storageId: null });
|
||||
assert.deepEqual(ids(nested, 'lingo'), ['too-deep']);
|
||||
const typed = new Session(normalize({ v: 3, lang: 'lingo', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge', storageId: null });
|
||||
assert.doesNotThrow(() => typed.setSource('lingo', 'To f with n:\n the answer is ' + deep('(', ')', 30000)));
|
||||
assert.equal(typed.linkState('pseudo').kind, 'stale');
|
||||
assert.match(typed.linkState('pseudo').reason ?? '', /does not read yet \(This sentence has more than 1,000 words and symbols/);
|
||||
const matho = new Session(normalize({ v: 3, lang: 'matho', sources: { matho: 'f(x) = ' + deep('{', '}', 30000, 'x') } }), { area: 'bridge', storageId: null });
|
||||
assert.deepEqual(ids(matho, 'matho'), ['matho-too-long']);
|
||||
assert.doesNotThrow(() => { matho.allDiagnostics(); matho.trace(); });
|
||||
// the net: a reader that still overflowed the stack, or threw anything else, would be worded like this
|
||||
assert.match(engineStopMessage(new RangeError('Maximum call stack size exceeded')), /nested more deeply than Programming\+ can read/);
|
||||
assert.match(engineStopMessage(new Error('boom')), /stopped reading this pane: boom\. This is a fault in Programming\+/);
|
||||
});
|
||||
|
||||
test('work that was running when the page died is set aside as a version, and the problem opens as written', () => {
|
||||
const store = fakeStore();
|
||||
markBusy('count-base', store);
|
||||
assert.equal(store.getItem('pplus.busy'), 'count-base');
|
||||
// the page died: the mark is still there at the next load, read once
|
||||
assert.equal(takeCrashed(store), 'count-base');
|
||||
assert.equal(takeCrashed(store), null);
|
||||
const saved = normalize({ v: 3, problem: 'count-base', sources: { mojo: 'def main():\n var t = String("x")\n while True:\n t = t + t\n' } });
|
||||
store.setItem('pplus.count-base', JSON.stringify(saved));
|
||||
const name = setAside('count-base', saved, 'dev', 'stopped', store, Date.UTC(2026, 10, 12, 15, 42));
|
||||
assert.match(name, /^When the page stopped \(/);
|
||||
assert.equal(store.getItem('pplus.count-base'), null, 'the save is gone, so the problem opens as written');
|
||||
const v = listVersions('pplus.versions.count-base', store);
|
||||
assert.equal(v.length, 1); assert.equal(v[0].name, name); assert.equal(v[0].auto, undefined, 'a named version: never the first to make room');
|
||||
assert.match(v[0].edits.sources.mojo, /t = t \+ t/);
|
||||
// a store that refuses the version keeps the save where it is
|
||||
const full = { ...fakeStore(), setItem() { throw new Error('QuotaExceededError'); } };
|
||||
assert.equal(setAside('count-base', saved, 'dev', 'stopped', full), null);
|
||||
// a page that settled or closed normally leaves nothing
|
||||
markBusy('x', store); clearBusy('x', store); assert.equal(takeCrashed(store), null);
|
||||
markBusy('x', store); settle(store); assert.equal(takeCrashed(store), null);
|
||||
// no storage at all: nothing to mark, nothing to find
|
||||
assert.doesNotThrow(() => { markBusy('x', null); takeCrashed(null); settle(null); });
|
||||
settle(null);
|
||||
});
|
||||
|
||||
test('a session marks its save busy when it saves, so a run that kills the page is found at the next load', () => {
|
||||
const store = fakeStore(), tab = fakeStore();
|
||||
globalThis.localStorage = store; globalThis.sessionStorage = tab;
|
||||
try {
|
||||
const s = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge' });
|
||||
s.setSource('pseudo', 'OUTPUT 2');
|
||||
assert.equal(tab.getItem('pplus.busy'), 'count-base', 'in this tab\'s storage');
|
||||
assert.equal(store.getItem('pplus.busy'), null, 'not among the saved work');
|
||||
} finally { settle(null); delete globalThis.localStorage; delete globalThis.sessionStorage; }
|
||||
});
|
||||
|
||||
test('storage that throws on every call (disabled, or full) is survived by every save path', () => {
|
||||
const throwing = { getItem() { throw new Error('SecurityError'); }, setItem() { throw new Error('QuotaExceededError'); }, removeItem() { throw new Error('SecurityError'); }, key() { throw new Error('SecurityError'); }, get length() { throw new Error('SecurityError'); } };
|
||||
globalThis.localStorage = throwing; globalThis.sessionStorage = throwing;
|
||||
try {
|
||||
const s = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge' });
|
||||
assert.doesNotThrow(() => { s.setSource('pseudo', 'OUTPUT 2'); s.saveVersion('mine'); s.versions(); s.hasUnsavedEdits(); });
|
||||
assert.doesNotThrow(() => { markBusy('count-base'); takeCrashed(); settle(); });
|
||||
} finally { delete globalThis.localStorage; delete globalThis.sessionStorage; settle(null); }
|
||||
});
|
||||
|
||||
test('the first Compile & run asks before anything is sent, and the answer stays in this browser', async () => {
|
||||
const { sendAllowed, allowSend, forgetSend } = await import('../dist/core/prefs.js');
|
||||
const store = fakeStore();
|
||||
globalThis.localStorage = store;
|
||||
try {
|
||||
forgetSend();
|
||||
assert.equal(sendAllowed(), false, 'nothing is sent before the reader agrees');
|
||||
allowSend();
|
||||
assert.equal(sendAllowed(), true);
|
||||
assert.equal(store.getItem('pplus.send.godbolt'), '1');
|
||||
// never in a state, a link or a file
|
||||
assert.ok(!JSON.stringify(normalize({ v: 3, sendGodbolt: true, send: true })).includes('send'));
|
||||
forgetSend();
|
||||
assert.equal(sendAllowed(), false);
|
||||
} finally { delete globalThis.localStorage; }
|
||||
});
|
||||
|
||||
test('a title from a link cannot end the shortcode the Share dialog writes for a page author', async () => {
|
||||
const { shortcodeTitle } = await import('../dist/quarto/shortcodes.js');
|
||||
const evil = 'Mean" >}}\n<script>alert(1)</script>{{< pplus-embed';
|
||||
const t = shortcodeTitle(evil);
|
||||
assert.doesNotMatch(t, /[<>{}"\n]/);
|
||||
assert.equal(t, 'Mean" scriptalert(1)/script pplus-embed');
|
||||
assert.equal(shortcodeTitle('Find a pattern, stepped through'), 'Find a pattern, stepped through');
|
||||
assert.equal(shortcodeTitle('x'.repeat(300)).length, 120);
|
||||
});
|
||||
|
||||
test('the trace\'s CSV and the table\'s copied text cannot start a spreadsheet formula', async () => {
|
||||
const { csvCell, toCsv, toTsv, safeCell } = await import('../dist/core/csv.js');
|
||||
for (const bad of ['=HYPERLINK("http://x","y")', '+1+1', '-2+3', '@SUM(A1)', '\t=1', '\r=1']) assert.ok(safeCell(bad).startsWith("'"), JSON.stringify(bad));
|
||||
for (const ok of ['-3', '+2.5', '1e-9', '-0.5', 'count_base', 'x = 1', '']) assert.equal(safeCell(ok), ok, 'numbers and ordinary text stay as they are');
|
||||
assert.equal(csvCell('say "hi"'), '"say ""hi"""');
|
||||
assert.equal(csvCell(12), '"12"');
|
||||
assert.equal(toCsv([['step', 'what ran'], [1, '=cmd|\' /C calc\'!A0']]), '"step","what ran"\n"1","\'=cmd|\' /C calc\'!A0"');
|
||||
assert.equal(toTsv([['N', '=1+1', 'a\tb']]), "N\t'=1+1\ta b");
|
||||
const src = (p) => fs.readFileSync(new URL(`../src/ui/views/${p}`, import.meta.url), 'utf8');
|
||||
assert.match(src('trace.ts'), /new Blob\(\[toCsv\(rows\)\]/, 'the CSV button writes through toCsv');
|
||||
assert.match(src('viz.ts'), /writeText\(toTsv\(rows\)\)/, 'the table\'s copy goes through toTsv');
|
||||
});
|
||||
|
||||
test('a framed view can grow its frame on a Quarto page, to a cap, and only with a finite height', async () => {
|
||||
const { runInNewContext } = await import('node:vm');
|
||||
const window = { addEventListener() {} };
|
||||
const document = { body: null, documentElement: {}, addEventListener() {}, querySelectorAll: () => [] };
|
||||
runInNewContext(fs.readFileSync(new URL('../quarto/_extensions/pplus/pplus.js', import.meta.url), 'utf8'), { window, document, MutationObserver: class { observe() {} } });
|
||||
const h = window.PPlus.frameHeight;
|
||||
assert.equal(h(500), 502);
|
||||
assert.equal(h(10), 120, 'never smaller than 120px');
|
||||
assert.equal(h(1e9), 4000, 'never taller than 4000px');
|
||||
for (const bad of [Infinity, NaN, '900', null, undefined, {}]) assert.equal(h(bad), null, String(bad));
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 15: the Hardware area's machine board. The course's views draw it (src/engines/asm86/views.js and
|
||||
// hwviews.js) and need a DOM, so they are checked by hand; what they are given is decided DOM-free in
|
||||
// core/hardware.ts and is tested here, for every problem that has assembly: which views each preset mounts and with
|
||||
// what options, and the frame each one draws at every step.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { themeBodyClass } from '../dist/ui/theme.js';
|
||||
import { BOARD_PRESETS, BOARD_VIEWS, BOARD_GROUPS, MACHINE_PRESETS, boardPreset, boardView, boardFrame, subRegisterWidths, normalizeBoard, presetOf, moveItem, addItem, removeItem, toggleWide, isWide, courseViews, parseMachine, machineName, machineSpec, machineLabel, lineTouches, asmMojoLines, relateAsmMojo } from '../dist/core/hardware.js';
|
||||
import { stageOccupancy, STAGES } from '../core/dist/engines/asm86/pipeline.js';
|
||||
import { coreAt } from '../core/dist/engines/asm86/ooo.js';
|
||||
import { decompose } from '../core/dist/engines/asm86/uops.js';
|
||||
import fs from 'node:fs';
|
||||
import { stripHeader, buildListing } from '../core/scripts/mojo/listings.mjs';
|
||||
import { forSimulator, simulatorSetup } from '../core/dist/mojo/att.js';
|
||||
import { listingFunctions, mojoBuildArgs } from '../core/dist/services/godbolt.js';
|
||||
import { hardwareFor, resolveMachine } from '../core/dist/engines/asm86/machine.js';
|
||||
import { viewNames } from '../core/dist/engines/asm86/views.js';
|
||||
import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { normalize, emptyState } from '../dist/core/state.js';
|
||||
import { SERVICES } from '../core/dist/services/index.js';
|
||||
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
|
||||
/** Every catalog problem with an x86-64 pane, run as the Hardware area runs it. */
|
||||
const WITH_ASM = PROBLEMS.filter((p) => (p.sources?.asm ?? '').trim());
|
||||
const traceOf = (p, machine) => {
|
||||
const st = stateForProblem(p);
|
||||
if (machine) st.machine = machine;
|
||||
st.lang = 'asm';
|
||||
const s = new Session(st, { area: 'hw', storageId: null });
|
||||
const tr = s.trace();
|
||||
assert.ok(tr && tr.lang === 'asm', `${p.id}: the x86-64 pane runs`);
|
||||
return { session: s, tr, raw: tr.raw.trace };
|
||||
};
|
||||
|
||||
test('the body class follows what the page shows: the setting, the system, or a host page that forces one', () => {
|
||||
assert.equal(themeBodyClass('light', true), 'quarto-light', 'a light app on a dark system draws light widgets');
|
||||
assert.equal(themeBodyClass('dark', false), 'quarto-dark');
|
||||
assert.equal(themeBodyClass('system', true), 'quarto-dark');
|
||||
assert.equal(themeBodyClass('system', false), 'quarto-light');
|
||||
for (const setting of ['light', 'dark', 'system']) for (const sys of [true, false]) {
|
||||
assert.equal(themeBodyClass(setting, sys, 'dark'), 'quarto-dark', 'an embed\'s ?theme= (or the host\'s switch) wins');
|
||||
assert.equal(themeBodyClass(setting, sys, 'light'), 'quarto-light');
|
||||
}
|
||||
});
|
||||
|
||||
test('every card the board offers is a course view or one of the app\'s own, in a group, and every preset is made of them', () => {
|
||||
const known = new Set(viewNames());
|
||||
const APP = new Set(['setup', 'output', 'problems', 'compiler', 'run', 'counters', 'lines']);
|
||||
assert.ok(WITH_ASM.length >= 10, 'the problems with assembly are found');
|
||||
assert.equal(new Set(BOARD_VIEWS.map((v) => v.id)).size, BOARD_VIEWS.length, 'each card once');
|
||||
for (const v of BOARD_VIEWS) {
|
||||
assert.ok(BOARD_GROUPS.includes(v.group), `${v.id}: a group of the add menu`);
|
||||
assert.ok(v.label && v.blurb, `${v.id}: a label and a line saying what it shows`);
|
||||
if (v.course) assert.ok(known.has(v.course.name), `${v.id} mounts "${v.course.name}", which views.js does not have`);
|
||||
else assert.ok(APP.has(v.id), `${v.id}: drawn by the app`);
|
||||
}
|
||||
for (const preset of BOARD_PRESETS) {
|
||||
assert.ok(preset.items.length >= 3 && preset.items.every((it) => boardView(it.id)), `${preset.id}: cards that exist`);
|
||||
assert.equal(presetOf(preset.items), preset.id, 'a preset is recognized as itself');
|
||||
for (const p of WITH_ASM) {
|
||||
const { raw } = traceOf(p);
|
||||
for (const machine of ['teaching', 'teaching+paging']) for (const c of courseViews(preset.items, raw, parseMachine(machine))) {
|
||||
assert.ok(known.has(c.name));
|
||||
assert.equal(typeof c.options, 'object', `${preset.id}/${c.id}: options for ${p.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.equal(boardPreset(undefined).id, 'regs', 'the board opens on registers and memory');
|
||||
assert.equal(boardPreset('nonsense').id, 'regs');
|
||||
assert.ok(BOARD_PRESETS.some((p) => p.items.some((it) => it.id === 'run')), 'a preset for the Mojo side');
|
||||
});
|
||||
|
||||
test('the student\'s own arrangement: move, add, remove, widen, and what a saved one may hold', () => {
|
||||
const regs = boardPreset('regs').items;
|
||||
const moved = moveItem(regs, regs.length - 1, 0);
|
||||
assert.equal(moved[0].id, regs[regs.length - 1].id);
|
||||
assert.equal(moved.length, regs.length);
|
||||
assert.equal(presetOf(moved), null, 'a changed arrangement is the student\'s own');
|
||||
assert.deepEqual(moveItem(moved, 0, regs.length - 1).map((x) => x.id), regs.map((x) => x.id), 'and moves back');
|
||||
assert.deepEqual(moveItem(regs, 9, 0), regs, 'a move from nowhere changes nothing');
|
||||
const added = addItem(regs, 'pipeline', 0);
|
||||
assert.equal(added[0].id, 'pipeline');
|
||||
assert.deepEqual(addItem(added, 'pipeline'), added, 'a card is on the board once');
|
||||
assert.deepEqual(addItem(regs, 'warp-drive'), regs, 'an unknown card is not added');
|
||||
assert.ok(!removeItem(added, 'pipeline').some((x) => x.id === 'pipeline'));
|
||||
const flags = regs.find((x) => x.id === 'flags');
|
||||
assert.equal(isWide(toggleWide(regs, 'flags').find((x) => x.id === 'flags')), !isWide(flags));
|
||||
assert.deepEqual(normalizeBoard([{ id: 'flags', wide: true }, 'memory', { id: 'flags' }, { id: 'nope' }, 7, null]), [{ id: 'flags', wide: true }, { id: 'memory' }], 'known cards, each once, widths kept');
|
||||
assert.equal(normalizeBoard('regs'), undefined);
|
||||
assert.equal(normalizeBoard(Array.from({ length: 40 }, () => 'flags')).length, 1);
|
||||
assert.ok(normalizeBoard(BOARD_VIEWS.map((v) => v.id)).length <= 24, 'at most 24 cards');
|
||||
// virtual memory's card mounts only with virtual memory on
|
||||
const { raw } = traceOf(PROBLEMS.find((x) => x.id === 'asm-two-pointers'));
|
||||
assert.deepEqual(courseViews([{ id: 'paging' }], raw, parseMachine('teaching')), []);
|
||||
assert.equal(courseViews([{ id: 'paging' }], raw, parseMachine('teaching+paging')).length, 1);
|
||||
});
|
||||
|
||||
test('the frame at every step is the one the course views expect, for every problem with assembly', () => {
|
||||
for (const p of WITH_ASM) {
|
||||
const { raw } = traceOf(p);
|
||||
for (let t = -1; t <= raw.count + 1; t++) {
|
||||
const f = boardFrame(raw, t);
|
||||
const tt = Math.max(0, Math.min(t, raw.count));
|
||||
assert.equal(f.t, tt);
|
||||
assert.equal(f.state, raw.states[tt]);
|
||||
assert.equal(f.last, tt ? raw.steps[tt - 1] : null, `${p.id}: the step that just ran`);
|
||||
if (f.next) assert.equal(f.next, raw.program.instrs[f.state.pc]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the register cards show every width the program uses', () => {
|
||||
const asm = SERVICES.asm.parse(' mov eax, 7\n mov cl, byte ptr [rdi]\n add r8d, 1\n mov rbx, rsi\n ret');
|
||||
assert.ok(asm.ok);
|
||||
assert.deepEqual(new Set(subRegisterWidths(asm.program)), new Set(['rax', 'rcx', 'r8']), 'rbx and rsi are only used whole');
|
||||
const widths = PROBLEMS.find((p) => p.id === 'asm-register-widths');
|
||||
assert.ok(widths, 'the register-widths problem exists');
|
||||
const { raw } = traceOf(widths);
|
||||
assert.ok(subRegisterWidths(raw.program).length > 1, 'its registers show their narrower names');
|
||||
});
|
||||
|
||||
test('the arrangement is part of the area\'s layout and normalizes', () => {
|
||||
const st = emptyState();
|
||||
st.layout = { hw: { board: [{ id: 'cache', wide: false }, 'flags'], dock: 0.5 } };
|
||||
assert.deepEqual(normalize(JSON.parse(JSON.stringify(st))).layout.hw.board, [{ id: 'cache', wide: false }, { id: 'flags' }]);
|
||||
st.layout = { hw: { board: 'warp-drive' } };
|
||||
assert.equal(normalize(JSON.parse(JSON.stringify(st))).layout.hw.board, undefined);
|
||||
const s = new Session(emptyState(), { area: 'hw', storageId: null });
|
||||
s.setLayout({ board: [{ id: 'counters' }] });
|
||||
assert.deepEqual(s.layout().board, [{ id: 'counters' }]);
|
||||
});
|
||||
|
||||
|
||||
test('each load and store shows the line it touched and how much of the line the program uses', () => {
|
||||
let touched = 0, missed = 0, partial = 0;
|
||||
for (const p of WITH_ASM) for (const machine of ['teaching', 'realistic', 'teaching+paging']) {
|
||||
const { raw } = traceOf(p, machine);
|
||||
const hw = hardwareFor(raw);
|
||||
const L = hw.memory().hierarchy.line;
|
||||
assert.deepEqual(lineTouches(hw, 0), [], 'nothing has run at step 0');
|
||||
for (let t = 1; t <= raw.count; t++) {
|
||||
const step = raw.steps[t - 1];
|
||||
const xs = lineTouches(hw, t);
|
||||
if (!machine.includes('paging')) {
|
||||
// without virtual memory the caches see the program's own addresses: every access of the step is there
|
||||
const want = step.accesses.reduce((n, a) => n + (Math.floor((a.addr + Math.max(1, a.size) - 1) / L) - Math.floor(a.addr / L) + 1), 0);
|
||||
assert.equal(xs.length, want, `${p.id} step ${t}: one entry per line per access`);
|
||||
}
|
||||
for (const x of xs) {
|
||||
touched++;
|
||||
if (!x.hit) missed++;
|
||||
assert.equal(x.lineSize, L);
|
||||
assert.equal(x.lineAddr % L, 0);
|
||||
assert.ok(x.from >= 0 && x.from < x.to && x.to <= L, `${p.id} step ${t}: the bytes are inside the line`);
|
||||
assert.equal(x.hit, x.level === 'L1d', 'a hit is a line found in L1d');
|
||||
for (let b = x.from; b < x.to; b++) assert.ok(x.usedSoFar.includes(b), 'the bytes used now count as used');
|
||||
assert.ok(x.usedSoFar.every((b) => x.usedInRun.includes(b)), 'used so far is part of used in the run');
|
||||
assert.ok(x.usedInRun.length <= L);
|
||||
if (x.usedInRun.length < L) partial++;
|
||||
if (!machine.includes('paging')) assert.equal(x.vaddr, x.addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.ok(touched > 50, 'the problems load and store');
|
||||
assert.ok(missed > 0, 'the teaching machine misses on small data');
|
||||
assert.ok(partial > 0, 'some lines are only partly used, which is what the view is for');
|
||||
});
|
||||
|
||||
test('virtual memory: the line is the physical one, and the access keeps the address the program wrote', () => {
|
||||
const p = PROBLEMS.find((x) => x.id === 'asm-two-pointers');
|
||||
const { raw } = traceOf(p, 'teaching+paging');
|
||||
const hw = hardwareFor(raw);
|
||||
const all = [];
|
||||
for (let t = 1; t <= raw.count; t++) all.push(...lineTouches(hw, t).map((x) => ({ x, step: raw.steps[t - 1] })));
|
||||
assert.ok(all.length);
|
||||
for (const { x, step } of all) assert.ok(step.accesses.some((a) => x.vaddr >= a.addr && x.vaddr < a.addr + Math.max(1, a.size)), 'the virtual address is one the instruction used');
|
||||
assert.ok(all.some(({ x }) => x.vaddr !== x.addr), 'and at least one is translated to another physical address');
|
||||
});
|
||||
|
||||
|
||||
test('Mojo beside x86-64: the line table the compiler left in the pane links each instruction to its Mojo line', () => {
|
||||
const asm = 'add: ; add(Int, Int)\n mov rax, rdi ; mojo line 2\n add rax, rsi ; mojo line 2\n ret\n call add ; mojo line 6';
|
||||
assert.deepEqual([...asmMojoLines(asm)], [[2, 2], [3, 2], [5, 6]]);
|
||||
assert.deepEqual(relateAsmMojo(asm, 'asm', 3), [2]);
|
||||
assert.deepEqual(relateAsmMojo(asm, 'asm', 4), [], 'an instruction the compiler added belongs to no line');
|
||||
assert.deepEqual(relateAsmMojo(asm, 'mojo', 2), [2, 3]);
|
||||
assert.deepEqual(relateAsmMojo(asm, 'mojo', 9), []);
|
||||
assert.equal(asmMojoLines(' mov rax, 7 ; a constant\n ret').size, 0, 'hand-written x86-64 is not linked');
|
||||
// a real listing, as Open in Hardware makes it from godbolt's saved answer
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
let checked = 0;
|
||||
for (const f of fs.readdirSync(ROOT + 'core/library/mojo/probes').filter((x) => x.endsWith('.mojo'))) {
|
||||
const text = fs.readFileSync(ROOT + 'core/library/mojo/probes/' + f, 'utf8');
|
||||
if (!/^# mode: (asm|both)/m.test(text)) continue;
|
||||
const r = buildListing(text, ROOT + 'core/library/mojo/golden', { forSimulator, simulatorSetup, listingFunctions, mojoBuildArgs });
|
||||
if (r.why) continue;
|
||||
const table = asmMojoLines(r.asm);
|
||||
if (!table.size) continue;
|
||||
checked++;
|
||||
const mojoLines = stripHeader(text).source.split('\n');
|
||||
for (const [a, m] of table) {
|
||||
assert.ok(m >= 1 && m <= mojoLines.length, `${f}: x86-64 line ${a} points at Mojo line ${m}, inside the program`);
|
||||
assert.ok(relateAsmMojo(r.asm, 'mojo', m).includes(a), `${f}: and back`);
|
||||
}
|
||||
}
|
||||
assert.ok(checked >= 1, 'a committed listing carries a line table');
|
||||
});
|
||||
|
||||
test('Open in Hardware on a compiled function: the work it makes can be shared, whatever data the function brings', async () => {
|
||||
// a function sent to the x86-64 pane brings the read-only data its code addresses in the setup; with the compiler's
|
||||
// half-megabyte table of source locations that was 2.5 MB for three of demo's functions, and the link the app
|
||||
// wrote for such work was one it refused to open (core writes a long block as quoted text now)
|
||||
const { encodeState, decodeState, LIMITS } = await import('../dist/core/state.js');
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const status = JSON.parse(fs.readFileSync(ROOT + 'core/library/mojo/golden/status.json', 'utf8'));
|
||||
const golden = JSON.parse(fs.readFileSync(`${ROOT}core/library/mojo/golden/${status.items.find((x) => x.id === 'local/demo').key}.json`, 'utf8'));
|
||||
const fns = listingFunctions(golden.result.asm);
|
||||
for (const name of ['cell', 'Grid::__init__', 'align', 'main']) {
|
||||
const fn = fns.find((f) => f.kind === 'user' && f.name.startsWith(name));
|
||||
assert.ok(fn, `demo has no function ${name}`);
|
||||
const s = new Session(stateForProblem(PROBLEMS.find((p) => p.id === 'demo')), { area: 'hw', storageId: null });
|
||||
const { source, data } = forSimulator(fns, fn);
|
||||
s.setSource('asm', source); s.setSetup(simulatorSetup(fn, data)); s.setLang('asm');
|
||||
assert.ok(s.trace().count >= 1, `${name} does not step`);
|
||||
const size = JSON.stringify(s.state).length;
|
||||
assert.ok(size < LIMITS.stateBytes / 2, `${name}: a state of ${size} bytes, against the ${LIMITS.stateBytes} a link may unpack to`);
|
||||
const back = await decodeState(await encodeState(s.state));
|
||||
assert.equal(back.setup, s.state.setup, `${name}: the setup does not come back from its own link`);
|
||||
assert.equal(back.sources.asm, s.state.sources.asm);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Mojo 1.2.0's input() and a pipe (the plan's gate G5): the Compiler view says why the compiler's run may stop with
|
||||
// EOF where the Run view does not, exactly when a program that may call input() more than once was sent with input.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { inputReads, inputNote } from '../dist/core/inputnote.js';
|
||||
import { installDocument } from '../dist/quarto/dom.js';
|
||||
|
||||
const prog = (body) => `def main():\n${body.split('\n').map((l) => ' ' + l).join('\n')}\n`;
|
||||
|
||||
test('one input() call in main reads input once: no note', () => {
|
||||
assert.deepEqual(inputReads(prog('var s = input()\nprint(s)')), { lines: [2], why: null });
|
||||
assert.equal(inputNote(prog('var s = input()\nprint(s)'), '1\n2\n'), null);
|
||||
});
|
||||
|
||||
test('two call sites, a loop, a comprehension, or a helper function may read more than once', () => {
|
||||
assert.equal(inputReads(prog('var a = input()\nvar b = input()\nprint(a + b)')).why, 'several');
|
||||
assert.deepEqual(inputReads(prog('var a = input()\nvar b = input()')).lines, [2, 3]);
|
||||
assert.equal(inputReads(prog('for i in range(3):\n print(input())')).why, 'loop');
|
||||
assert.equal(inputReads(prog('var n = 0\nwhile n < 3:\n if True:\n var s = input()\n n += 1')).why, 'loop');
|
||||
assert.equal(inputReads(prog('for i in range(3): print(input())')).why, 'loop', 'a loop on one line');
|
||||
assert.equal(inputReads(prog('var xs = [input() for _ in range(3)]')).why, 'loop', 'a comprehension');
|
||||
assert.equal(inputReads('def ask() -> String:\n return input()\n\ndef main():\n print(ask())\n').why, 'function');
|
||||
});
|
||||
|
||||
test('strings, comments, methods and a def named input are not calls', () => {
|
||||
assert.equal(inputReads(prog('print("input() input()") # input()\nvar s = input()')).why, null);
|
||||
assert.equal(inputReads(prog('var s = String("x")\nprint(s.input())\nvar t = input()')).why, null);
|
||||
assert.equal(inputReads(prog('"""\ninput()\ninput()\n"""\nvar t = input()')).why, null);
|
||||
assert.deepEqual(inputReads(prog('print(1)')), { lines: [], why: null });
|
||||
// after the loop ends, a single call outside it is once
|
||||
assert.equal(inputReads('def main():\n for i in range(3):\n print(i)\n var s = input()\n').why, null);
|
||||
});
|
||||
|
||||
test('the note: only when input was sent, and it names the lines and the reason', () => {
|
||||
const two = prog('var a = input()\nvar b = input()');
|
||||
assert.equal(inputNote(two, ''), null, 'no input sent: nothing to explain');
|
||||
assert.equal(inputNote(two, '\n'), null);
|
||||
const note = inputNote(two, '3\n4\n');
|
||||
assert.match(note, /lines 2 and 3/);
|
||||
assert.match(note, /first call takes every line/);
|
||||
assert.match(note, /EOF/);
|
||||
assert.match(inputNote(prog('for i in range(3):\n print(input())'), '1\n'), /in a loop \(line 3\)/);
|
||||
assert.equal(inputNote('def main(:\n input(\n', '1\n') === null || typeof inputNote('def main(:\n input(\n', '1\n') === 'string', true, 'text that does not lex still answers');
|
||||
});
|
||||
|
||||
test('the Compiler view shows the note under the output of such a compile, and not for a single read', async () => {
|
||||
installDocument();
|
||||
const { Session } = await import('../dist/core/session.js');
|
||||
const { normalize } = await import('../dist/core/state.js');
|
||||
const { compilerView } = await import('../dist/ui/views/compiler.js');
|
||||
const answer = (stdout, stderr = '') => ({ answer: { compiled: true, buildStderr: '', executed: true, exitCode: stderr ? 1 : 0, stdout, stderr, timedOut: false, asm: [] }, error: null, seconds: 0.1 });
|
||||
const draw = async (mojo, input, outcome) => {
|
||||
const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo }, input }), { area: 'dev', storageId: null });
|
||||
await s.compile(async () => outcome);
|
||||
const root = document.createElement('div');
|
||||
const off = compilerView(s, root, { reveal() {}, fix() {}, sendToAsm() {}, compile() {} });
|
||||
off();
|
||||
return root;
|
||||
};
|
||||
const two = prog('var a = input()\nvar b = input()\nprint(a, b)');
|
||||
const shown = await draw(two, '3\n4', answer('', 'Unhandled exception caught during execution: EOF'));
|
||||
const note = shown.querySelector('.compile-input-note');
|
||||
assert.ok(note, 'the note is shown');
|
||||
assert.match(note.textContent, /lines 2 and 3/);
|
||||
const once = await draw(prog('var a = input()\nprint(a)'), '3', answer('3\n'));
|
||||
assert.equal(once.querySelector('.compile-input-note'), null);
|
||||
const noInput = await draw(two, '', answer('', 'EOF'));
|
||||
assert.equal(noInput.querySelector('.compile-input-note'), null);
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The library page (#/library, src/ui/library.ts) and a library routine opened in the Bridge (src/core/library.ts):
|
||||
// every routine of core's registry is listed with its checks, and opens as a problem that runs.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installDocument } from '../dist/quarto/dom.js';
|
||||
|
||||
installDocument();
|
||||
const { parseRoute, routeFor } = await import('../dist/core/state.js');
|
||||
const { libraryModules, libraryState, checksOf, tally, LIBRARY_PREFIX } = await import('../dist/core/library.js');
|
||||
const { Session } = await import('../dist/core/session.js');
|
||||
|
||||
test('routes: #/library and #/library/<id>, and a routine opens under the problem id lib:<id>', () => {
|
||||
assert.deepEqual(parseRoute('#/library'), { kind: 'library' });
|
||||
assert.deepEqual(parseRoute('#/library/md.LennardJones'), { kind: 'library', id: 'md.LennardJones' });
|
||||
assert.equal(routeFor({ kind: 'library', id: 'md.LennardJones' }), '#/library/md.LennardJones');
|
||||
assert.deepEqual(parseRoute('#/bridge/p/lib:md.LennardJones'), { kind: 'problem', area: 'bridge', id: 'lib:md.LennardJones' });
|
||||
assert.equal(libraryState('lib:md.NoSuch'), null);
|
||||
assert.equal(libraryState('count-base'), null);
|
||||
});
|
||||
|
||||
test('every routine opens in the Bridge with its pseudo and its first case, and runs to that case\'s result', () => {
|
||||
let n = 0;
|
||||
for (const m of libraryModules()) for (const r of m.routines) {
|
||||
n++;
|
||||
const st = libraryState(`${LIBRARY_PREFIX}${r.id}`);
|
||||
assert.equal(st.sources.pseudo, r.source);
|
||||
assert.equal(st.call, r.cases[0].call);
|
||||
const session = new Session(st, { area: 'bridge' });
|
||||
const tr = session.trace('pseudo');
|
||||
assert.equal(tr.error, null, `${r.id}: ${tr.error?.message}`);
|
||||
assert.equal(tr.output.at(-1), `${r.name} returned ${r.cases[0].result}`, r.id);
|
||||
// stepping into the routine is the point of opening it: its own lines are in the run
|
||||
assert.ok(tr.steps.some((s) => s.line > 1 && s.kind !== 'call'), `${r.id}: the run shows none of the routine's lines`);
|
||||
}
|
||||
assert.ok(n >= 16);
|
||||
});
|
||||
|
||||
test('the page lists every routine with its checks, and each routine\'s page shows its source, cases, references and checks', async () => {
|
||||
const { libraryView } = await import('../dist/ui/library.js');
|
||||
const index = libraryView();
|
||||
const text = index.textContent;
|
||||
for (const m of libraryModules()) {
|
||||
assert.ok(text.includes(m.title), m.title);
|
||||
for (const r of m.routines) assert.ok(text.includes(r.name), r.id);
|
||||
}
|
||||
const r = libraryModules().find((m) => m.name === 'md').routines.find((x) => x.name === 'LennardJones');
|
||||
const page = libraryView(r.id);
|
||||
const t = page.textContent;
|
||||
assert.ok(t.includes('Open in the Bridge'));
|
||||
assert.ok(t.includes(`USE ${r.id}`));
|
||||
for (const c of r.cases) assert.ok(t.includes(c.call) && t.includes(c.result), c.call);
|
||||
for (const ref of r.references) assert.ok(t.includes(`${ref.lang} · ${ref.level}`), `${ref.lang}/${ref.level}`);
|
||||
assert.equal(page.querySelectorAll('.lib-chip').length >= checksOf(r).length, true);
|
||||
assert.ok(libraryView('md.NoSuch').textContent.includes('No such routine'));
|
||||
const t2 = tally(r);
|
||||
assert.equal(t2.fail, 0);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// What a first visit asks for, and what a browser may keep (docs/deploy.md): the assembled page preloads every module
|
||||
// its imports reach and names its commit (scripts/assemble-page.mjs), and the Caddy block caches only what may be cached.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { modulePreloads, assemblePage } from '../scripts/assemble-page.mjs';
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8');
|
||||
const html = read('index.html');
|
||||
const inlineHashes = (h) => [...h.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => createHash('sha256').update(m[1]).digest('base64'));
|
||||
|
||||
test('the preload list is every module the page imports, each once, and only files that exist', () => {
|
||||
const list = modulePreloads(ROOT);
|
||||
assert.ok(list.length > 100, `${list.length} modules`);
|
||||
assert.equal(new Set(list).size, list.length);
|
||||
assert.ok(!list.includes('./dist/main.js'), 'the entry loads itself');
|
||||
for (const href of ['./dist/ui/shell.js', './dist/vendor/codemirror.js', './core/dist/mojo/interp.js', './dist/ui/footer.js']) assert.ok(list.includes(href), href);
|
||||
for (const href of list) assert.ok(fs.existsSync(path.join(ROOT, href)), href);
|
||||
// every import in every listed module is listed too (or is the entry)
|
||||
const listed = new Set(list.map((h) => path.join(ROOT, h)));
|
||||
listed.add(path.join(ROOT, 'dist/main.js'));
|
||||
for (const f of listed) for (const m of fs.readFileSync(f, 'utf8').matchAll(/\bfrom\s*['"](\.[^'"]+|#core\/[^'"]+)['"]/g)) {
|
||||
const t = m[1].startsWith('#core/') ? path.join(ROOT, 'core/dist', m[1].slice(6)) : path.resolve(path.dirname(f), m[1]);
|
||||
assert.ok(listed.has(t), `${path.relative(ROOT, f)} imports ${m[1]}, which the list misses`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the assembled page adds the version and the preloads after the import map, and changes no inline script', () => {
|
||||
const out = assemblePage(html, { version: '0123456789abcdef0123456789abcdef01234567', preloads: ['./dist/a.js', './core/dist/b.js'] });
|
||||
assert.match(out, /<meta name="pplus-version" content="0123456789abcdef0123456789abcdef01234567">\n<\/head>/);
|
||||
const map = out.indexOf('<script type="importmap">');
|
||||
const first = out.indexOf('rel="modulepreload"');
|
||||
assert.ok(map > 0 && first > map, 'a module preload before the import map would make the browser ignore the map');
|
||||
assert.ok(first < out.indexOf('<script type="module"'));
|
||||
assert.deepEqual(inlineHashes(out), inlineHashes(html), 'the CSP allows the inline scripts by their hashes');
|
||||
assert.doesNotMatch(assemblePage(html, { version: 'dev' }), /pplus-version/, 'a checkout without a commit names none');
|
||||
assert.match(read('scripts/assemble.sh'), /node scripts\/assemble-page\.mjs site/);
|
||||
});
|
||||
|
||||
test('the page asks for its two everyday faces with the stylesheet, and every face swaps in when it arrives', () => {
|
||||
const pre = [...html.matchAll(/<link rel="preload" href="\.\/fonts\/([^"]+)" as="font" type="font\/woff2" crossorigin>/g)].map((m) => m[1]);
|
||||
assert.deepEqual(pre, ['IBMPlexSans-Regular.woff2', 'IBMPlexMono-Regular.woff2']);
|
||||
const css = read('fonts/plex.css');
|
||||
const faces = css.match(/@font-face/g).length;
|
||||
assert.equal(css.match(/font-display: swap/g).length, faces);
|
||||
});
|
||||
|
||||
test('the Caddy block caches nothing as immutable, revalidates the page and the code, and keeps the fonts', () => {
|
||||
const caddy = read('docs/Caddyfile');
|
||||
assert.doesNotMatch(caddy, /Cache-Control "[^"]*immutable/, 'no file name here changes with its content');
|
||||
assert.match(caddy, /@page path \/ \/index\.html\n\s*header @page Cache-Control "no-cache"/);
|
||||
assert.match(caddy, /@code path \*\.js \*\.css\n\s*header @code Cache-Control "no-cache"/);
|
||||
assert.match(caddy, /@fonts path \/fonts\/\*\.woff2\n\s*header @fonts Cache-Control "public, max-age=\d+"/);
|
||||
assert.match(caddy, /header \/VERSION Cache-Control "no-store"/);
|
||||
assert.doesNotMatch(read('src/main.ts') + html, /serviceWorker/, 'no service worker (offline reload is a later decision)');
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { normalize } from '../dist/core/state.js';
|
||||
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { MOJO_VERSION, GODBOLT_COMPILER } from '../core/dist/mojo/generated/pin.js';
|
||||
|
||||
// godbolt's stored answers, in pplus-core
|
||||
const goldens = fs.readdirSync(new URL('../core/library/mojo/golden/', import.meta.url)).filter((f) => /^[0-9a-f]{64}\.json$/.test(f))
|
||||
.map((f) => JSON.parse(fs.readFileSync(new URL(`../core/library/mojo/golden/${f}`, import.meta.url), 'utf8')));
|
||||
|
||||
test('the session keeps each answer with the source it answered, and says when it is stale', async () => {
|
||||
const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'fn main():\n print(1)\n' } }));
|
||||
assert.equal(s.diagnostics('mojo')[0].id, 'removed-syntax');
|
||||
const stderr = goldens.find((g) => g.firstItem === 'probes/dialect-fn').result.buildStderr;
|
||||
let asked = null;
|
||||
const fake = async (source, opts) => { asked = { source, ...opts }; return { answer: { compiled: false, buildStderr: stderr.replace('<source>:3:', '<source>:1:'), executed: false, exitCode: null, stdout: '', stderr: '', timedOut: false, asm: [] }, error: null, seconds: 0.1 }; };
|
||||
const rec = await s.compile(fake);
|
||||
assert.equal(asked.level, 'O0');
|
||||
assert.equal(rec.diagnostics[0].origin, `the Mojo ${MOJO_VERSION} compiler`);
|
||||
assert.equal(s.diagnostics('mojo')[0].id, 'compiler', 'the compiler\'s answer replaces Programming+\'s own finding');
|
||||
assert.equal(s.lastCompile().fresh, true);
|
||||
s.setSource('mojo', 'def main():\n print(1)\n');
|
||||
assert.equal(s.lastCompile().fresh, false);
|
||||
assert.deepEqual(s.diagnostics('mojo'), [], 'an answer for older source is not shown on the new lines');
|
||||
const failed = await s.compile(async () => ({ answer: null, error: 'Could not reach godbolt.org (offline).', seconds: 0 }));
|
||||
assert.equal(failed.outcome.error, 'Could not reach godbolt.org (offline).');
|
||||
});
|
||||
|
||||
test('Compile & run goes through the compile backend, and the record names the service that answered', async () => {
|
||||
const { compileBackend, setCompileBackend, explorerBackend, GODBOLT } = await import('../core/dist/services/compile-backend.js');
|
||||
assert.equal(compileBackend(), GODBOLT);
|
||||
assert.equal(GODBOLT.host, 'godbolt.org');
|
||||
assert.equal(GODBOLT.compiler, GODBOLT_COMPILER);
|
||||
const asked = [];
|
||||
const fake = { id: 'fake', host: 'checker.example', compiler: GODBOLT_COMPILER, compile: async (source, opts) => { asked.push({ source, ...opts }); return { answer: null, error: 'checker.example did not answer in time.', seconds: 0 }; } };
|
||||
const prev = setCompileBackend(fake);
|
||||
try {
|
||||
const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'def main():\n print(7)\n' } }));
|
||||
const rec = await s.compile();
|
||||
assert.equal(asked.length, 1);
|
||||
assert.equal(asked[0].source, 'def main():\n print(7)\n');
|
||||
assert.equal(asked[0].level, 'O0');
|
||||
assert.equal(rec.host, 'checker.example');
|
||||
} finally {
|
||||
setCompileBackend(prev);
|
||||
}
|
||||
assert.equal(compileBackend(), GODBOLT);
|
||||
// a Compiler Explorer at another address speaks the same API and names itself in its messages
|
||||
const elsewhere = explorerBackend('local', { base: 'http://127.0.0.1:9', compiler: GODBOLT_COMPILER, host: 'the local checker' });
|
||||
const out = await elsewhere.compile('def main():\n pass\n', { timeoutMs: 2000 });
|
||||
assert.equal(out.answer, null);
|
||||
assert.match(out.error, /the local checker/);
|
||||
});
|
||||
|
||||
test('godbolt\'s answer outlives the session: a new one for the same source finds it without asking again', async () => {
|
||||
const { forgetCompiles } = await import('../dist/core/compiles.js');
|
||||
forgetCompiles();
|
||||
const src = 'def main():\n print(42)\n';
|
||||
const answer = { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: '42\n', stderr: '', timedOut: false, asm: [{ text: '"example::main()":' }, { text: ' retq' }] };
|
||||
let asks = 0;
|
||||
const first = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } }));
|
||||
await first.compile(async () => { asks++; return { answer, error: null, seconds: 0.1 }; });
|
||||
// a change of problem, a reload: a new session for the same program
|
||||
const again = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } }));
|
||||
const last = again.lastCompile();
|
||||
assert.ok(last, 'the answer is there before anyone presses Compile');
|
||||
assert.equal(last.fresh, true);
|
||||
assert.equal(last.record.outcome.answer.stdout, '42\n');
|
||||
assert.equal(last.record.functions.length, 1, 'the listing is split into functions again');
|
||||
assert.equal(asks, 1);
|
||||
// a different program does not see it, and comes back to it once the source is the same again
|
||||
const other = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'def main():\n print(7)\n' } }));
|
||||
assert.equal(other.lastCompile(), null);
|
||||
other.setSource('mojo', src);
|
||||
assert.equal(other.lastCompile()?.fresh, true, 'editing back to a compiled source brings its answer back');
|
||||
// a failure to reach godbolt is not kept
|
||||
forgetCompiles();
|
||||
const offline = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } }));
|
||||
await offline.compile(async () => ({ answer: null, error: 'offline', seconds: 0 }));
|
||||
assert.equal(new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } })).lastCompile(), null);
|
||||
forgetCompiles();
|
||||
});
|
||||
|
||||
test('Stage 6b: comparing builds does not replace the build the student chose', async () => {
|
||||
const { Session } = await import('../dist/core/session.js');
|
||||
const { normalize } = await import('../dist/core/state.js');
|
||||
const s = new Session(normalize({ v: 3, sources: { mojo: 'def main():\n print(1)\n' }, lang: 'mojo' }));
|
||||
const fake = (level) => async () => ({ ok: true, answer: { compiled: true, executed: true, exitCode: 0, stdout: level, stderr: '', buildStderr: '', asm: [] } });
|
||||
await s.compile(fake('O0'));
|
||||
await s.compile(fake('default'), 'default');
|
||||
assert.equal(s.lastCompile().record.level, 'O0', 'the view keeps the chosen level');
|
||||
assert.ok(s.compileAt(s.source('mojo'), 'default'), 'the other build is there to compare with');
|
||||
});
|
||||
|
||||
test('a compile says how it was built: the arguments the request sent, from core\'s pin', async () => {
|
||||
const { MOJO_BUILD_ARGS } = await import('../core/dist/mojo/generated/pin.js');
|
||||
const { BUILD_ARGS } = await import('../core/dist/services/godbolt.js');
|
||||
assert.match(MOJO_BUILD_ARGS, /--target-cpu \S+ --fp-mode contract=off/);
|
||||
for (const level of ['O0', 'default']) assert.ok(BUILD_ARGS[level].startsWith(MOJO_BUILD_ARGS), `${level} is asked for with the pin's arguments first`);
|
||||
// the summary line of a compile and the badge's tooltip show them, and neither names arguments of its own
|
||||
const fs = await import('node:fs');
|
||||
for (const f of ['src/ui/views/compiler.ts', 'src/ui/provenance.ts']) {
|
||||
const text = fs.readFileSync(f, 'utf8');
|
||||
assert.ok(text.includes('MOJO_BUILD_ARGS'), `${f} shows the pin's arguments`);
|
||||
assert.doesNotMatch(text, /--target-cpu|--fp-mode/, `${f} writes build arguments of its own`);
|
||||
}
|
||||
// the two places the site's own tools run a Mojo file (a Quarto page's run, and the page checker) build it the same way
|
||||
for (const f of ['quarto/_extensions/pplus/render.mjs', 'scripts/check-pages.mjs']) {
|
||||
const text = fs.readFileSync(f, 'utf8');
|
||||
assert.ok(text.includes('mojoBuildArgs('), `${f} takes the pin's arguments`);
|
||||
assert.doesNotMatch(text, /\['run', file\]/, `${f} runs mojo with no build arguments`);
|
||||
assert.doesNotMatch(text, /--target-cpu|--fp-mode/, `${f} writes build arguments of its own`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// A phone-width screen shows one part of a workspace at a time (styles.css, src/ui/shell.ts setNarrow); a wider one
|
||||
// must not see any of it: AGENTS.md rule 7 keeps the workspace's parts where they are on a normal screen.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const css = readFileSync(new URL('../styles.css', import.meta.url), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
|
||||
/** The top-level blocks of a stylesheet: [prelude, body] pairs. */
|
||||
function blocks(text) {
|
||||
const out = []; let depth = 0, start = 0, prelude = '';
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (text[i] === '{') { if (depth === 0) { prelude = text.slice(start, i).trim(); start = i + 1; } depth++; }
|
||||
else if (text[i] === '}') { depth--; if (depth === 0) { out.push([prelude, text.slice(start, i)]); start = i + 1; } }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
test('every narrow-screen rule is inside the 700px media query, and the bar is hidden outside it', () => {
|
||||
const top = blocks(css);
|
||||
const outside = top.filter(([p]) => !p.startsWith('@media')).map(([p, b]) => `${p}{${b}}`);
|
||||
assert.ok(outside.some((r) => /^\.narrow-bar\{\s*display: none;\s*\}$/.test(r.replace(/\s*\{\s*/, '{').trim())), '.narrow-bar is display: none on a normal screen');
|
||||
for (const r of outside) assert.doesNotMatch(r, /data-narrow/, `a rule outside the media query reads data-narrow: ${r.slice(0, 80)}`);
|
||||
for (const [p, b] of top.filter(([p]) => p.startsWith('@media') && !/max-width: 700px/.test(p))) assert.doesNotMatch(b, /data-narrow|narrow-bar/, `${p} reads the narrow layout`);
|
||||
const narrow = top.filter(([p]) => /^@media \(max-width: 700px\)$/.test(p)).map(([, b]) => b).join('\n');
|
||||
for (const part of ['code', 'side', 'dock']) assert.match(narrow, new RegExp(`data-narrow="${part}"`), part);
|
||||
});
|
||||
|
||||
test('the shell offers the parts, and Run, Compile & run and a diagnostic\'s line show the part they open', () => {
|
||||
const shell = readFileSync(new URL('../src/ui/shell.ts', import.meta.url), 'utf8');
|
||||
assert.match(shell, /\[\['code', 'Code'\], \['side', 'Board'\]\] : \[\['code', 'Code'\], \['side', 'Run and views'\], \['dock', 'Setup and output'\]\]/);
|
||||
assert.match(shell, /this\.stepper\?\.goto\(this\.session\.trace\(\)\?\.count \?\? 0\); this\.setNarrow\('side'\);/, 'Run shows the Run view');
|
||||
assert.match(shell, /if \(open\) this\.setNarrow\('dock'\);/, 'opening the dock (Compile & run) shows it');
|
||||
assert.match(shell, /reveal: \(lang, line\) => \{\n\s*this\.setNarrow\('code'\);/, 'a line in the code shows the code');
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 13b: the best-practices switch. Off by default, one per area, remembered in the browser and nowhere else;
|
||||
// while it is off the rules are never called (a spy proves it), and nothing about them reaches a diagnostic.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { stateForProblem, problemById } from '../dist/core/catalog.js';
|
||||
import { practicesOn, setPracticesOn, forgetPractices, onPracticesChange } from '../dist/core/prefs.js';
|
||||
import { findPractices, PRACTICES_ORIGIN } from '../core/dist/mojo/practices.js';
|
||||
import { encodeState } from '../dist/core/state.js';
|
||||
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
|
||||
const spy = () => { const f = (...a) => { f.calls++; return findPractices(...a); }; f.calls = 0; return f; };
|
||||
const open = (id, area, practices) => new Session(stateForProblem(problemById(id)), { area, storageId: null, practices });
|
||||
const noted = (s) => s.allDiagnostics().filter((d) => d.origin === PRACTICES_ORIGIN);
|
||||
|
||||
test('off by default in every area, and the rules are never called while off', () => {
|
||||
forgetPractices();
|
||||
for (const area of ['bridge', 'dev', 'hw', null]) assert.equal(practicesOn(area), false, String(area));
|
||||
for (const area of ['bridge', 'dev', 'hw']) {
|
||||
const f = spy();
|
||||
const s = open('count-base', area, f);
|
||||
s.setLang('mojo');
|
||||
s.allDiagnostics(); s.diagnostics('mojo'); s.practices(); s.trace();
|
||||
assert.equal(f.calls, 0, `${area}: no rule ran`);
|
||||
assert.deepEqual(s.practices(), []);
|
||||
assert.deepEqual(noted(s), []);
|
||||
}
|
||||
});
|
||||
|
||||
test('the switch is per area, remembered under its own key, and a fresh read finds it', () => {
|
||||
forgetPractices();
|
||||
setPracticesOn('dev', true);
|
||||
assert.equal(store.get('pplus.practices.dev'), '1');
|
||||
assert.equal(practicesOn('dev'), true);
|
||||
assert.equal(practicesOn('bridge'), false, 'the other area is unaffected');
|
||||
assert.equal(practicesOn('hw'), false, 'Hardware has no switch');
|
||||
setPracticesOn('hw', true);
|
||||
assert.equal(practicesOn('hw'), false);
|
||||
let told = 0; const off = onPracticesChange(() => told++);
|
||||
setPracticesOn('bridge', true); setPracticesOn('bridge', false);
|
||||
off(); setPracticesOn('bridge', true);
|
||||
assert.equal(told, 2);
|
||||
setPracticesOn('bridge', false); setPracticesOn('dev', false);
|
||||
assert.ok(!store.has('pplus.practices.dev') && !store.has('pplus.practices.bridge'), 'off is stored as absent');
|
||||
});
|
||||
|
||||
test('on in the Developer area: findings are notes on the student\'s own lines; the Bridge, still off, stays quiet', () => {
|
||||
forgetPractices();
|
||||
setPracticesOn('dev', true);
|
||||
const f = spy();
|
||||
const dev = open('count-base', 'dev', f);
|
||||
dev.setSource('mojo', 'def main():\n var n: Int\n n = 5\n n = n + 1\n print(n)\n');
|
||||
const notes = noted(dev);
|
||||
assert.ok(f.calls >= 1);
|
||||
assert.deepEqual(notes.map((d) => d.id).sort(), ['practice-augmented-assign', 'practice-declare-then-assign']);
|
||||
assert.ok(notes.every((d) => d.severity === 'note' && d.fix && d.lang === 'mojo'));
|
||||
const g = spy();
|
||||
const bridge = open('count-base', 'bridge', g);
|
||||
bridge.allDiagnostics(); bridge.practices();
|
||||
assert.equal(g.calls, 0);
|
||||
forgetPractices();
|
||||
});
|
||||
|
||||
test('on in the Bridge: the generated Mojo draws findings in the helper\'s list, not in Problems', () => {
|
||||
forgetPractices();
|
||||
setPracticesOn('bridge', true);
|
||||
const s = open('count-base', 'bridge');
|
||||
const rules = new Set(s.practices().map((x) => x.rule));
|
||||
for (const id of ['declare-then-assign', 'augmented-assign', 'codepoint-loop']) assert.ok(rules.has(id), id);
|
||||
assert.deepEqual(noted(s), [], 'Problems stays about the pseudo and the translation');
|
||||
assert.equal(s.source('mojo'), s.derivedMojo().source, 'the Mojo is still the literal translation');
|
||||
forgetPractices();
|
||||
});
|
||||
|
||||
test('the switch is a browser preference: it is not in the state, so a link cannot turn it on', async () => {
|
||||
forgetPractices();
|
||||
setPracticesOn('dev', true);
|
||||
const st = stateForProblem(problemById('count-base'));
|
||||
assert.ok(!/practices/i.test(JSON.stringify(st)));
|
||||
assert.ok(!/practices/i.test(await encodeState(st)));
|
||||
forgetPractices();
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The app's "With Quarto" page (#/quarto, src/ui/quarto.ts): its samples must show what a page gets from the
|
||||
// extension, and every program in it must run as its header says.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { installDocument } from '../dist/quarto/dom.js';
|
||||
import { langOfFile } from '../dist/quarto/program.js';
|
||||
|
||||
installDocument();
|
||||
const { renderStatic } = await import('../dist/quarto/render.js');
|
||||
const { parseRoute, routeFor } = await import('../dist/core/state.js');
|
||||
|
||||
test('the gallery\'s samples render as a page would get them, and every run in it prints what its file says', async () => {
|
||||
const { galleryFiles, SAMPLES } = await import('../dist/ui/quarto.js');
|
||||
const { SHORTCODES, requestFor, liveStateFor, shortcodeText } = await import('../dist/quarto/shortcodes.js');
|
||||
const files = galleryFiles();
|
||||
const named = new Set(SAMPLES.map((s) => s.name));
|
||||
// every shortcode has a card; the machine's one-view shortcodes share a card with a menu of them all
|
||||
for (const d of SHORTCODES) assert.ok(named.has(d.name) || (d.kind === 'machine' && d.hw && SAMPLES.some((x) => x.explore)), `the gallery shows ${d.name}`);
|
||||
for (const s of SAMPLES) {
|
||||
for (const [k, v] of Object.entries(s.attrs)) if (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm', 'setup'].includes(k)) assert.ok(files[v] !== undefined, `${s.name} names ${v}`);
|
||||
assert.match(shortcodeText(s.name, s.attrs), new RegExp(`^\\{\\{< ${s.name} .* >\\}\\}$`));
|
||||
const def = SHORTCODES.find((d) => d.name === s.name);
|
||||
if (def.kind === 'live') { assert.ok(Object.keys(liveStateFor(s.attrs, files).sources).length, s.name); continue; }
|
||||
if (def.kind !== 'rendered' && def.kind !== 'machine') continue;
|
||||
const view = def.view ?? (s.attrs.view === 'dataflow' ? 'data' : s.attrs.view);
|
||||
const req = requestFor(view, s.attrs, files);
|
||||
if (def.hw) req.hw = [def.hw];
|
||||
const r = renderStatic(req);
|
||||
assert.deepEqual(r.warnings, [], `${s.name} ${JSON.stringify(s.attrs)}`);
|
||||
if (r.expect) assert.ok(r.expect.ok, `${s.name}: ${JSON.stringify(r.expect)}`);
|
||||
}
|
||||
// the files' own headers hold: each run prints its EXPECT lines, each stop is the one it names
|
||||
for (const [name, text] of Object.entries(files)) {
|
||||
const lang = langOfFile(name);
|
||||
if (!lang || lang === 'speco' || lang === 'asm') continue;
|
||||
const r = renderStatic({ view: 'run', files: { [lang]: text } });
|
||||
if (r.expect) assert.ok(r.expect.ok, `${name}: ${JSON.stringify(r.expect)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('#/quarto is the gallery, and its sections are links', () => {
|
||||
assert.deepEqual(parseRoute('#/quarto'), { kind: 'quarto' });
|
||||
assert.deepEqual(parseRoute('#/quarto#pplus-steps'), { kind: 'quarto', anchor: 'pplus-steps' });
|
||||
assert.equal(routeFor({ kind: 'quarto', anchor: 'setup' }), '#/quarto#setup');
|
||||
assert.deepEqual(parseRoute('#/quarto/x'), { kind: 'home' });
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The rendered views of the Quarto extension (src/quarto/): a program from the files beside a page, run by the app's
|
||||
// engines and drawn by its views as HTML, under the small document of src/quarto/dom.ts; the CLI pplus.lua calls
|
||||
// (quarto/_extensions/pplus/render.mjs). The gallery that shows them in the app is tests/quarto-gallery.test.mjs.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import zlib from 'node:zlib';
|
||||
import { installDocument, SDocument } from '../dist/quarto/dom.js';
|
||||
import { programHeader, listingText, langOfFile } from '../dist/quarto/program.js';
|
||||
|
||||
installDocument();
|
||||
const { renderStatic, STATIC_VIEWS, stepsPanel } = await import('../dist/quarto/render.js');
|
||||
const { problemById } = await import('../dist/core/catalog.js');
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const CB = problemById('count-base');
|
||||
const head = (call, expect) => `// CALL: ${call}\n${expect ? `// EXPECT: ${expect}\n` : ''}`;
|
||||
const PSEUDO = head(CB.call, 'COUNT_BASE returned 3') + CB.sources.pseudo;
|
||||
|
||||
test('a program file: its pane, its header lines, and the text a page shows', () => {
|
||||
assert.equal(langOfFile('x/count.pseudo'), 'pseudo');
|
||||
assert.equal(langOfFile('mean.tex'), 'matho');
|
||||
assert.equal(langOfFile('demo.mojo'), 'mojo');
|
||||
assert.equal(langOfFile('notes.txt'), null);
|
||||
const h = programHeader('// CALL: F(1)\n// INPUT: 4\n// INPUT: 5\n// EXPECT: F returned 2\n// STOPS: index\nFUNCTION F...');
|
||||
assert.deepEqual(h, { call: 'F(1)', input: ['4', '5'], expect: ['F returned 2'], stops: 'index', questions: [] });
|
||||
assert.deepEqual(programHeader('% CALL: X(1)\n% EXPECT: X returned 1\n').expect, ['X returned 1']);
|
||||
assert.deepEqual(programHeader('# expect-stdout: 3\n# expect-stdout: 4\ndef main():\n pass\n').expect, ['3', '4'], 'a Mojo file\'s corpus header counts as EXPECT');
|
||||
assert.equal(listingText('// CALL: F(1)\n\nFUNCTION F()\n', 'pseudo'), 'FUNCTION F()');
|
||||
assert.equal(listingText('# origin: x\n# expect-stdout: 1\n\ndef main():\n # note: mine\n print(1)\n', 'mojo'), 'def main():\n # note: mine\n print(1)');
|
||||
});
|
||||
|
||||
test('the small document builds, finds and writes what the views make', () => {
|
||||
const doc = new SDocument();
|
||||
const div = doc.createElement('div');
|
||||
div.className = 'a b';
|
||||
div.classList.add('c'); div.classList.toggle('a');
|
||||
div.style.left = '10%'; div.style.setProperty('--x', '1');
|
||||
div.dataset.stepNo = '4';
|
||||
const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 1 1');
|
||||
svg.appendChild(doc.createElementNS('http://www.w3.org/2000/svg', 'path'));
|
||||
const p = doc.createElement('p'); p.textContent = 'x < y & "z"';
|
||||
const sel = doc.createElement('select');
|
||||
for (const v of ['one', 'two']) { const o = doc.createElement('option'); o.value = v; o.textContent = v; sel.appendChild(o); }
|
||||
sel.value = 'two';
|
||||
const details = doc.createElement('details'); details.open = true;
|
||||
div.append(svg, p, sel, details);
|
||||
assert.equal(div.outerHTML, '<div class="b c" style="left: 10%; --x: 1" data-step-no="4"><svg viewBox="0 0 1 1"><path/></svg><p>x < y & "z"</p><select><option value="one" selected="">one</option><option value="two" selected>two</option></select><details open></details></div>'.replace(' selected=""', ''));
|
||||
assert.equal(div.querySelectorAll('svg path').length, 1, 'the descendant combinator');
|
||||
assert.equal(div.querySelector('[data-step-no="4"]'), null, 'the root itself is not searched');
|
||||
assert.equal(div.querySelectorAll('.b, p').length, 1);
|
||||
assert.equal(p.closest('.c'), div);
|
||||
assert.throws(() => div.querySelector('div > p'), /only the descendant combinator/);
|
||||
p.replaceWith(doc.createTextNode('gone'));
|
||||
assert.equal(div.textContent.includes('gone'), true);
|
||||
});
|
||||
|
||||
test('run: what the program prints, checked against its EXPECT lines, for each notation', () => {
|
||||
const r = renderStatic({ view: 'run', files: { pseudo: PSEUDO } });
|
||||
assert.equal(r.lang, 'pseudo');
|
||||
assert.deepEqual(r.expect, { want: ['COUNT_BASE returned 3'], got: ['COUNT_BASE returned 3'], ok: true });
|
||||
assert.match(r.html, /prints the 1 line its EXPECT header says/);
|
||||
assert.match(r.markdown, /```\nCOUNT_BASE returned 3\n```/);
|
||||
const wrong = renderStatic({ view: 'run', files: { pseudo: PSEUDO.replace('returned 3', 'returned 9') } });
|
||||
assert.equal(wrong.expect.ok, false);
|
||||
assert.match(wrong.warnings.join('\n'), /its EXPECT lines say \["COUNT_BASE returned 9"\]/);
|
||||
const lingo = renderStatic({ view: 'run', files: { lingo: CB.sources.lingo }, call: 'COUNT_BASES(\'A\', "GATTACA")' });
|
||||
assert.deepEqual(lingo.expect, undefined);
|
||||
assert.match(lingo.html, /COUNT_BASES returned 3/);
|
||||
const mojo = renderStatic({ view: 'run', files: { mojo: '# EXPECT: 3\n' + CB.sources.mojo } });
|
||||
assert.equal(mojo.lang, 'mojo');
|
||||
assert.ok(mojo.expect.ok);
|
||||
assert.match(mojo.html, /not the compiler/, 'the interpreter says it is not the compiler');
|
||||
const compiled = renderStatic({ view: 'run', files: { mojo: CB.sources.mojo }, compiled: { stdout: '3\n', stderr: '', status: 0, version: 'Mojo 9.9.9' } });
|
||||
// whatever version the rendering machine's compiler reports is what the view says
|
||||
assert.match(compiled.html, /Mojo 9\.9\.9, on the machine that rendered this page/);
|
||||
const broken = renderStatic({ view: 'run', files: { pseudo: 'FUNCTION F() RETURNS INTEGER\n RETURN Nope\nENDFUNCTION\n' } });
|
||||
assert.match(broken.html, /pplus-err/);
|
||||
assert.ok(broken.warnings.length);
|
||||
});
|
||||
|
||||
test('steps: one row per step of the run, the values after it, and the page drawn at the step asked for', () => {
|
||||
const r = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, t: 5 });
|
||||
const json = /<script type="application\/json" class="pplus-steps-data">([^<]*)<\/script>/.exec(r.html)[1];
|
||||
const data = JSON.parse(json);
|
||||
assert.equal(data.lang, 'pseudo');
|
||||
assert.equal(data.rows.length, data.count);
|
||||
assert.equal(data.t, 5);
|
||||
assert.deepEqual(data.cols.map((c) => c.label), ['B', 'T', 'N', 'Total', 'I']);
|
||||
const at = stepsPanel(data, 5);
|
||||
assert.match(r.html, new RegExp(`class="pplus-ln is-next" data-line="${at.next}"`));
|
||||
assert.equal(stepsPanel(data, data.count).out.join('\n'), 'COUNT_BASE returned 3');
|
||||
assert.equal(stepsPanel(data, 0).now, 'Before the first step.');
|
||||
const asm = renderStatic({ view: 'steps', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup, max: 20 });
|
||||
const ad = JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(asm.html)[1]);
|
||||
assert.equal(ad.lang, 'asm');
|
||||
assert.equal(ad.count, 20);
|
||||
assert.ok(ad.truncated);
|
||||
assert.ok(ad.cols.length && ad.cols.every((c) => /^r[a-z0-9]+$/.test(c.label)), 'a column per register the run writes');
|
||||
const follow = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, follow: ['total'] });
|
||||
assert.deepEqual(JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(follow.html)[1]).cols.map((c) => c.label), ['Total']);
|
||||
});
|
||||
|
||||
test('every rendered view draws for a program that has what it needs, with the app\'s controls taken out', () => {
|
||||
const files = { pseudo: PSEUDO, speco: problemById('count-base-proved').sources.speco };
|
||||
for (const view of ['table', 'flow', 'data', 'proof', 'tests', 'check']) {
|
||||
const r = renderStatic({ view, files });
|
||||
assert.match(r.html, new RegExp(`^<div class="[^"]*pplus-static pplus-v-${view}`), view);
|
||||
assert.doesNotMatch(r.html, /<button|<input|<select/, `${view} keeps no control the page cannot use`);
|
||||
assert.ok(r.markdown.length > 10, `${view} has a Markdown form`);
|
||||
}
|
||||
assert.match(renderStatic({ view: 'flow', files }).html, /<svg[^>]*class="flow-svg"/);
|
||||
assert.match(renderStatic({ view: 'proof', files }).html, /4 proved/);
|
||||
const check = renderStatic({ view: 'check', files: { pseudo: problemById('five-bugs').sources.pseudo } });
|
||||
assert.match(check.html, /problem-error/);
|
||||
assert.match(check.markdown, /\*\*error\*\*, pseudo line \d+: /);
|
||||
const tests = renderStatic({ view: 'tests', files: { pseudo: problemById('match-off-by-one').sources.pseudo } });
|
||||
assert.match(tests.html, /way of failing/);
|
||||
const machine = renderStatic({ view: 'machine', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup });
|
||||
assert.match(machine.markdown, /\| instructions \| \d+ \|/);
|
||||
const life = renderStatic({ view: 'life', files: { mojo: fs.readFileSync(ROOT + 'core/library/mojo/stress/lifecycle-moves.mojo', 'utf8') } });
|
||||
assert.ok((life.html.match(/life-row/g) ?? []).length >= 3);
|
||||
assert.doesNotMatch(life.html, /Click a mark/, 'a page has no stepper to move');
|
||||
assert.equal(STATIC_VIEWS.length, 12);
|
||||
});
|
||||
|
||||
test('translate: one file in, every notation out, Mojo labeled as generated', () => {
|
||||
const r = renderStatic({ view: 'translate', files: { matho: '% CALL: X_BAR(3, [1.0, 2.0, 6.0])\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n' } });
|
||||
assert.deepEqual(r.panes.map((p) => [p.lang, p.authored, p.generated]), [['matho', true, false], ['lingo', false, true], ['pseudo', false, true], ['mojo', false, true]]);
|
||||
assert.equal(r.panes.find((p) => p.lang === 'lingo').from, 'matho');
|
||||
assert.match(r.panes.find((p) => p.lang === 'mojo').text, /def x_bar/);
|
||||
const only = renderStatic({ view: 'translate', files: { lingo: CB.sources.lingo }, to: ['pseudo', 'mojo'] });
|
||||
assert.deepEqual(only.panes.map((p) => p.lang), ['pseudo', 'mojo']);
|
||||
const cannot = renderStatic({ view: 'translate', files: { pseudo: PSEUDO }, to: ['matho'] });
|
||||
assert.equal(cannot.panes[0].text, '');
|
||||
assert.ok(cannot.panes[0].note, 'a notation that cannot say it says why');
|
||||
});
|
||||
|
||||
test('render.mjs answers a request from pplus.lua, and keeps the answer in its cache', () => {
|
||||
const cache = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-cache-'));
|
||||
const ask = (req) => {
|
||||
const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify(req), encoding: 'utf8', env: { ...process.env, PATH: '/nonexistent' } });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
return JSON.parse(r.stdout);
|
||||
};
|
||||
const a = ask({ view: 'run', files: { pseudo: PSEUDO }, cache });
|
||||
assert.equal(a.expect.ok, true);
|
||||
assert.equal(a.node, undefined, 'the element stays behind; its HTML goes');
|
||||
assert.equal(fs.readdirSync(cache).length, 1);
|
||||
const b = ask({ view: 'run', files: { pseudo: PSEUDO }, cache });
|
||||
assert.deepEqual(b, a, 'the same answer, from the cache');
|
||||
assert.match(ask({ view: 'nonsense', files: { pseudo: PSEUDO } }).error, /unknown view "nonsense"/);
|
||||
const big = ask({ view: 'tests', files: { pseudo: PSEUDO } });
|
||||
assert.ok(big.html.length > 65536 && big.html.endsWith('</div>'), `a large answer (${big.html.length} characters) arrives whole through the pipe`);
|
||||
const none = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', os.tmpdir()], { input: '{}', encoding: 'utf8' });
|
||||
assert.match(JSON.parse(none.stdout).error, /no built Programming\+/);
|
||||
// a Mojo run asks for the compiler only when one is on the PATH; compiler="on" insists on it
|
||||
const mojo = ask({ view: 'run', files: { mojo: CB.sources.mojo }, compiler: 'on' });
|
||||
assert.match(mojo.error, /no `mojo` on the PATH/);
|
||||
});
|
||||
|
||||
test('the machine board: every card of the Hardware area, drawn at each step, the drawings shared between steps', async () => {
|
||||
const { HW_NAMES, HW_PRESETS, hwView } = await import('../dist/quarto/machine.js');
|
||||
const p = problemById('asm-two-pointers');
|
||||
const files = { asm: p.sources.asm };
|
||||
const board = renderStatic({ view: 'hw', files, setup: p.setup, t: 9 });
|
||||
assert.deepEqual(board.warnings, []);
|
||||
const data = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(board.html)[1]);
|
||||
assert.equal(data.count, 97);
|
||||
assert.equal(data.shown.length, 98, 'every step of a short run');
|
||||
assert.deepEqual(data.cards.map((c) => c.id), HW_PRESETS[0].views);
|
||||
for (const c of data.cards) {
|
||||
assert.equal(c.at.length, data.shown.length);
|
||||
assert.ok(c.frames.length <= data.shown.length && c.at.every((i) => i < c.frames.length));
|
||||
}
|
||||
assert.ok(data.cards.find((c) => c.id === 'stack').frames.length < 5, 'a card that does not change is drawn once');
|
||||
assert.equal(data.steps[9].x, 'mov r11, qword ptr [rdx + r9*8]');
|
||||
// every view of the machine draws on this run without failing, paging with virtual memory switched on
|
||||
for (const name of Object.keys(HW_NAMES)) {
|
||||
const r = renderStatic({ view: 'hw', files, setup: p.setup, hw: [name], max: 12 });
|
||||
assert.deepEqual(r.warnings, [], name);
|
||||
assert.doesNotMatch(r.html, /has-failed|could not be built/, name);
|
||||
const frames = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(r.html)[1]).cards.flatMap((c) => c.frames).join('');
|
||||
assert.doesNotMatch(frames, /<button|<input|<select/, `${name}: its drawings keep no control`);
|
||||
}
|
||||
assert.match(renderStatic({ view: 'hw', files, setup: p.setup, hw: ['paging'], max: 12 }).html, /with virtual memory/);
|
||||
const sampled = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['registers'], max: 20 });
|
||||
const sd = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(sampled.html)[1]);
|
||||
assert.ok(sd.shown.length <= 21 && sd.shown.at(-1) === 97, 'a long run is sampled, and the last step is always there');
|
||||
assert.match(sampled.html, /every 5th is drawn/);
|
||||
const one = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['encoding'], t: 9, stepper: false, listing: false });
|
||||
assert.doesNotMatch(one.html, /pplus-steps-bar|pplus-hw-data|pplus-hw-listing/, 'stepper="0": one step, nothing to step');
|
||||
assert.match(one.markdown, /The machine at step 9 of 97, after `mov r11/);
|
||||
assert.equal(hwView('alu'), 'bits');
|
||||
assert.equal(hwView('chip'), 'machine');
|
||||
assert.equal(hwView('run'), null, 'not a machine view');
|
||||
const none = renderStatic({ view: 'hw', files: { pseudo: PSEUDO } });
|
||||
assert.match(none.warnings.join(), /no x86-64 file/);
|
||||
});
|
||||
|
||||
test('render.mjs compresses the machine\'s steps, and they come back whole', () => {
|
||||
const p = problemById('asm-two-pointers');
|
||||
const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify({ view: 'hw', files: { asm: p.sources.asm }, setup: p.setup, hw: ['pipeline'] }), encoding: 'utf8' });
|
||||
const res = JSON.parse(r.stdout);
|
||||
const b64 = /type="application\/x-pplus-deflate" class="pplus-hw-data">([^<]+)</.exec(res.html)[1];
|
||||
const data = JSON.parse(zlib.inflateRawSync(Buffer.from(b64, 'base64')).toString('utf8'));
|
||||
assert.equal(data.cards[0].id, 'pipeline');
|
||||
assert.ok(b64.length < 60000, `the pipeline over 97 steps is ${b64.length} characters`);
|
||||
});
|
||||
|
||||
test('a run that cannot start reports its EXPECT lines as not printed', () => {
|
||||
const r = renderStatic({ view: 'run', files: { pseudo: '// EXPECT: 3\nPROCEDURE F(\n' } });
|
||||
assert.deepEqual(r.expect, { want: ['3'], got: [], ok: false });
|
||||
assert.match(r.warnings.join('\n'), /It does not run yet/);
|
||||
assert.equal(renderStatic({ view: 'run', files: { pseudo: 'PROCEDURE F(\n' } }).expect, undefined, 'no EXPECT lines, nothing to hold it to');
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The Quarto extension embeds what the playground shows: the whole playground or one view, arranged by the
|
||||
// shortcode's options; the app reads those options from the embed's query (applyEmbedParams).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { applyEmbedParams, emptyState, EMBED_VIEWS, parseRoute } from '../dist/core/state.js';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const EXT = ROOT + 'quarto/_extensions/pplus';
|
||||
|
||||
test('an embed query arranges the example the way the playground controls do', () => {
|
||||
const base = { ...emptyState(), sources: { mojo: 'def main():\n pass', asm: 'ret' }, lang: 'pseudo' };
|
||||
const s = applyEmbedParams(base, new URLSearchParams('lang=mojo&panel=compiler&build=default&machine=Zen%204&dock=closed&docktab=output&editor=0.6&side=0.4&dockheight=0.75&t=3'), 'hw');
|
||||
assert.equal(s.lang, 'mojo');
|
||||
assert.equal(s.view, 'compiler');
|
||||
assert.equal(s.build, 'default');
|
||||
assert.equal(s.machine, 'Zen 4');
|
||||
assert.deepEqual(s.layout, { hw: { dockCollapsed: true, dockTab: 'output', split: 0.6, right: 0.4, dock: 0.75 } }, 'the arrangement is the area\'s');
|
||||
assert.equal(s.t, 3);
|
||||
assert.equal(base.layout, undefined, 'the state it was given is not changed');
|
||||
});
|
||||
|
||||
test('a malformed embed query changes nothing', () => {
|
||||
const base = emptyState();
|
||||
const s = applyEmbedParams(base, new URLSearchParams('panes=klingon&area=nowhere&panel=nope&build=O3&editor=2&t=-1&lang=cobol&dock=maybe'));
|
||||
assert.equal(s.view, base.view);
|
||||
assert.equal(s.lang, base.lang);
|
||||
assert.equal(s.build, undefined);
|
||||
assert.equal(s.t, undefined);
|
||||
assert.deepEqual(s.layout, {});
|
||||
});
|
||||
|
||||
test('the playground and the Mojo views are embeddable routes', () => {
|
||||
for (const v of ['playground', 'life', 'compiler']) assert.ok(EMBED_VIEWS.includes(v));
|
||||
const r = parseRoute('#/embed/playground/p/demo?panel=life');
|
||||
assert.equal(r.kind, 'embed');
|
||||
assert.equal(r.view, 'playground');
|
||||
assert.equal(r.problem, 'demo');
|
||||
assert.equal(r.params.get('panel'), 'life');
|
||||
});
|
||||
|
||||
test('check-pages knows every view the app embeds', () => {
|
||||
const text = fs.readFileSync(ROOT + 'scripts/check-pages.mjs', 'utf8');
|
||||
const listed = new Set([...(/const EMBED_VIEWS = new Set\(\[([^\]]+)\]\)/.exec(text)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]));
|
||||
assert.deepEqual([...listed].sort(), [...EMBED_VIEWS].sort());
|
||||
});
|
||||
|
||||
// the shortcode itself, run by pandoc's Lua with Quarto's few functions stubbed. Without pandoc 3 on the PATH these
|
||||
// are skipped on a developer's machine. Under CI (the CI variable set, as Gitea and GitHub Actions set it) they are
|
||||
// not skipped: they run and fail, because a skip in CI is how a gap hides (eleven of these were skipped in CI for
|
||||
// weeks, until pixi brought pandoc to the runner). pixi run test brings pandoc.
|
||||
const pandoc = spawnSync('pandoc', ['--version'], { encoding: 'utf8' });
|
||||
const lua = pandoc.status === 0 && /pandoc 3/.test(pandoc.stdout);
|
||||
const NO_PANDOC = !lua && !process.env.CI && 'pandoc 3 is not on the PATH';
|
||||
const needPandoc = () => assert.ok(lua, 'pandoc 3 is not on the PATH, and CI must run the Quarto tests: run them as pixi run test, which brings the pinned pandoc');
|
||||
|
||||
function shortcode(calls, files) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-'));
|
||||
for (const [f, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, f), text);
|
||||
fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify(calls));
|
||||
needPandoc();
|
||||
const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
return { out: r.stdout.trim().split('\n').map((l) => JSON.parse(l)), warnings: r.stderr };
|
||||
}
|
||||
const stateOf = (src) => JSON.parse(Buffer.from(/\/~([\w-]+)/.exec(src)[1], 'base64url').toString('utf8'));
|
||||
|
||||
const MOJO = '# origin: Programming+ demo\n# probe: a recursive function\n# mode: both\n# args: -O0 --debug-level=line-tables\n# expect: pass\n\ndef main():\n # note: this comment is the program\'s\n print(1)\n';
|
||||
|
||||
test('the shortcode embeds the whole playground from files, arranged as asked', { skip: NO_PANDOC }, () => {
|
||||
const { out } = shortcode([{ mojo: 'demo.mojo', asm: 'demo.asm', setup: 'demo.setup', view: 'playground', area: 'hw', panel: 'compiler', build: 'default', dock: 'open', editor: '0.6', title: 'Demo' }],
|
||||
{ 'demo.mojo': MOJO, 'demo.asm': 'main:\n ret', 'demo.setup': '# main() takes no arguments' });
|
||||
const [o] = out;
|
||||
assert.match(o.src, /^https:\/\/pplus\.scient\.ing\/#\/embed\/playground\/~/);
|
||||
assert.equal(o.height, '720', 'the playground gets a taller frame by default');
|
||||
const st = stateOf(o.src);
|
||||
assert.equal(st.sources.mojo, 'def main():\n # note: this comment is the program\'s\n print(1)', 'the corpus header is left out; a comment in the program is kept');
|
||||
assert.equal(st.sources.asm, 'main:\n ret');
|
||||
assert.equal(st.setup, '# main() takes no arguments');
|
||||
assert.equal(st.view, 'compiler');
|
||||
assert.equal(st.build, 'default');
|
||||
assert.deepEqual(st.layout, { hw: { dockCollapsed: false, split: 0.6 } });
|
||||
assert.equal(st.title, 'Demo');
|
||||
assert.match(o.src, /\?area=hw&panel=compiler&build=default&dock=open&editor=0\.6$/);
|
||||
});
|
||||
|
||||
test('the shortcode writes a state the app reads back whole, and lists matho as LaTeX', { skip: NO_PANDOC }, async () => {
|
||||
const { normalize } = await import('../dist/core/state.js');
|
||||
const { out } = shortcode([{ pseudo: 'x.pseudo' }, { matho: 'm.tex', show: 'listing', math: '0' }], { 'x.pseudo': 'OUTPUT 1\n', 'm.tex': 'y = x^2\n' });
|
||||
const st = stateOf(out[0].src);
|
||||
assert.equal(st.v, normalize(st).v, 'the shortcode writes the current state format');
|
||||
assert.equal(normalize(st).sources.pseudo, 'OUTPUT 1');
|
||||
assert.deepEqual(out[1].codes, [{ lang: 'latex', text: 'y = x^2' }], 'pandoc highlights the listing as LaTeX');
|
||||
});
|
||||
|
||||
test('the shortcode arranges a catalog problem and a state from Share, and refuses an unknown view', { skip: NO_PANDOC }, () => {
|
||||
const { out, warnings } = shortcode([
|
||||
{ problem: 'demo', view: 'playground', panel: 'life', machine: 'Zen 4', theme: 'dark' },
|
||||
{ state: 'https://pplus.scient.ing/#/bridge/s/~eyJ2IjoyfQ', view: 'life' },
|
||||
{ mojo: 'demo.mojo', show: 'listing' },
|
||||
{ mojo: 'demo.mojo', view: 'nonsense' },
|
||||
{ mojo: 'demo.mojo', view: 'playground', height: 'auto' },
|
||||
], { 'demo.mojo': MOJO });
|
||||
assert.equal(out[0].src, 'https://pplus.scient.ing/#/embed/playground/p/demo?panel=life&machine=Zen%204&theme=dark');
|
||||
assert.equal(out[1].src, 'https://pplus.scient.ing/#/embed/life/~eyJ2IjoyfQ', 'a whole share link is cut down to its state');
|
||||
assert.deepEqual(out[2].codes, [{ lang: 'mojo', text: 'def main():\n # note: this comment is the program\'s\n print(1)' }]);
|
||||
assert.match(out[3].src, /#\/embed\/trace\//);
|
||||
assert.match(warnings, /unknown view="nonsense"/);
|
||||
assert.equal(out[4].height, '720');
|
||||
assert.match(warnings, /height="auto" does not apply/);
|
||||
});
|
||||
|
||||
/* ---------- the family of shortcodes (quarto/_extensions/pplus/pplus.lua) ---------- */
|
||||
|
||||
const PSEUDO = '// CALL: COUNT_BASE(\'A\', "GATTACA")\n// EXPECT: COUNT_BASE returned 3\nFUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER\n DECLARE Total : INTEGER\n Total <- 0\n FOR I <- 0 TO LENGTH(T)\n IF T[I] == B THEN\n Total <- Total + 1\n ENDIF\n NEXT I\n RETURN Total\nENDFUNCTION\n';
|
||||
const sc = (name, kw, meta = { 'pplus-cache': 'false' }) => ({ sc: name, kw, meta });
|
||||
|
||||
test('pplus.lua offers every shortcode the gallery and check-pages know, and no other', { skip: NO_PANDOC }, async () => {
|
||||
const { SHORTCODE_NAMES } = await import('../dist/quarto/shortcodes.js');
|
||||
needPandoc();
|
||||
const r = spawnSync('pandoc', ['lua', '-e', `quarto = { doc = { input_file = '' } }; local t = dofile('${EXT}/pplus.lua'); local n = {} for k in pairs(t) do n[#n + 1] = k end table.sort(n) print(table.concat(n, ' '))`], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.deepEqual(r.stdout.trim().split(' '), [...SHORTCODE_NAMES].sort());
|
||||
const check = fs.readFileSync(ROOT + 'scripts/check-pages.mjs', 'utf8');
|
||||
const hwViews = [...(/const HW_VIEWS = \[([^\]]+)\]/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]);
|
||||
const listed = [...(/const SHORTCODES = new Set\(\[([^\]]+)\]\)/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]).filter((n) => n.startsWith('pplus'));
|
||||
assert.deepEqual([...listed, ...hwViews.map((v) => `pplus-hw-${v}`)].sort(), [...SHORTCODE_NAMES].sort(), 'scripts/check-pages.mjs knows every shortcode');
|
||||
const { HW_NAMES } = await import('../dist/quarto/machine.js');
|
||||
assert.deepEqual(hwViews, Object.keys(HW_NAMES), 'and every machine view, in the same order as pplus.lua');
|
||||
const luaHw = [...(/local HW_VIEWS = \{([^}]+)\}/.exec(fs.readFileSync(EXT + '/pplus.lua', 'utf8'))?.[1] ?? '').matchAll(/"([^"]+)"/g)].map((m) => m[1]);
|
||||
assert.deepEqual(luaHw, Object.keys(HW_NAMES));
|
||||
const { STATIC_VIEWS } = await import('../dist/quarto/render.js');
|
||||
const views = new Set([...(/const STATIC_VIEWS = new Set\(\[([^\]]+)\]\)/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]));
|
||||
for (const v of STATIC_VIEWS) assert.ok(views.has(v), `check-pages knows pplus-view's view="${v}"`);
|
||||
});
|
||||
|
||||
test('a rendered shortcode runs the file while the page renders: no iframe, the view in the page', { skip: NO_PANDOC }, () => {
|
||||
const { out, warnings } = shortcode([
|
||||
sc('pplus-run', { pseudo: 'count.pseudo', code: '1', title: 'Count' }),
|
||||
sc('pplus-steps', { pseudo: 'count.pseudo', t: '3' }),
|
||||
sc('pplus-flow', { pseudo: 'count.pseudo', live: 'click' }),
|
||||
sc('pplus-view', { view: 'dataflow', pseudo: 'count.pseudo' }),
|
||||
], { 'count.pseudo': PSEUDO });
|
||||
const [run, steps, flow, data] = out;
|
||||
assert.equal(run.src, undefined, 'no iframe');
|
||||
assert.ok(run.divs.includes('pplus-figure pplus-figure-run'));
|
||||
assert.match(run.raw.join(''), /class="[^"]*pplus-static pplus-v-run[^"]*"/);
|
||||
assert.match(run.raw.join(''), /COUNT_BASE returned 3/);
|
||||
assert.match(run.raw.join(''), /pplus-figtitle">Count</);
|
||||
assert.deepEqual(run.codes.map((c) => c.lang), ['pseudo'], 'code="1" puts the listing in the figure');
|
||||
assert.doesNotMatch(run.codes[0].text, /CALL:|EXPECT:/, 'without its header lines');
|
||||
assert.match(steps.raw.join(''), /<script type="application\/json" class="pplus-steps-data">/);
|
||||
assert.match(steps.raw.join(''), /data-t="3"/);
|
||||
assert.match(flow.raw.join(''), /<svg[^>]*class="flow-svg"/);
|
||||
assert.match(flow.raw.join(''), /class="pplus-golive" data-src="https:\/\/pplus\.scient\.ing\/#\/embed\/flow\/~/, 'live="click" carries the live view to put in its place');
|
||||
assert.match(data.raw.join(''), /pplus-v-data/);
|
||||
assert.doesNotMatch(warnings, /pplus-run|pplus-steps|pplus-flow/);
|
||||
});
|
||||
|
||||
test('a rendered run that does not print its EXPECT lines is reported, and stops the render with pplus-strict', { skip: NO_PANDOC }, () => {
|
||||
const wrong = PSEUDO.replace('returned 3', 'returned 4');
|
||||
const { warnings } = shortcode([sc('pplus-run', { pseudo: 'w.pseudo' })], { 'w.pseudo': wrong });
|
||||
assert.match(warnings, /pplus-run in index\.qmd: run: printed \["COUNT_BASE returned 3"\], its EXPECT lines say \["COUNT_BASE returned 4"\]/);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-'));
|
||||
fs.writeFileSync(path.join(dir, 'w.pseudo'), wrong);
|
||||
fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify([sc('pplus-run', { pseudo: 'w.pseudo' }, { 'pplus-strict': 'true', 'pplus-cache': 'false' })]));
|
||||
needPandoc();
|
||||
const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' });
|
||||
assert.notEqual(r.status, 0, 'the render stops');
|
||||
assert.match(r.stderr, /does not print its EXPECT lines \(pplus-strict is on\)/);
|
||||
});
|
||||
|
||||
test('check-pages reads a machine shortcode too: pplus-hw-<view> with a missing file, and a view that does not exist', () => {
|
||||
// the name pattern once stopped at the first hyphenated part, so every pplus-hw-<view> shortcode was skipped
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-pages-'));
|
||||
fs.writeFileSync(path.join(dir, 'two.asm'), 'main:\n ret\n');
|
||||
const run = (text) => {
|
||||
fs.writeFileSync(path.join(dir, 'index.qmd'), text);
|
||||
return spawnSync(process.execPath, [ROOT + 'scripts/check-pages.mjs', dir], { encoding: 'utf8', cwd: ROOT, env: { ...process.env, CHECK_FILES_ONLY: '1' } });
|
||||
};
|
||||
const ok = run('{{< pplus-hw-pipeline asm="two.asm" >}}\n');
|
||||
assert.equal(ok.status, 0, ok.stdout + ok.stderr);
|
||||
const missing = run('{{< pplus-hw-pipeline asm="missing.asm" >}}\n');
|
||||
assert.equal(missing.status, 1);
|
||||
assert.match(missing.stdout, /pplus-hw-pipeline >}} names missing\.asm, which does not exist/);
|
||||
const unknown = run('{{< pplus-hw-nosuch asm="two.asm" >}}\n');
|
||||
assert.equal(unknown.status, 1);
|
||||
assert.match(unknown.stdout, /pplus-hw-nosuch >}} is not a shortcode of the extension/);
|
||||
});
|
||||
|
||||
test('a program with EXPECT lines that does not run stops the render with pplus-strict', { skip: NO_PANDOC }, () => {
|
||||
const broken = '// EXPECT: 3\nPROCEDURE F(\n';
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-'));
|
||||
fs.writeFileSync(path.join(dir, 'b.pseudo'), broken);
|
||||
fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify([sc('pplus-run', { pseudo: 'b.pseudo' }, { 'pplus-strict': 'true', 'pplus-cache': 'false' })]));
|
||||
needPandoc();
|
||||
const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' });
|
||||
assert.notEqual(r.status, 0, 'the render stops');
|
||||
assert.match(r.stderr, /does not print its EXPECT lines \(pplus-strict is on\)/);
|
||||
});
|
||||
|
||||
test('without an engine a rendered view falls back to the listing and the live view', { skip: NO_PANDOC }, () => {
|
||||
const { out, warnings } = shortcode([sc('pplus-table', { pseudo: 'count.pseudo' }, { 'pplus-engine': 'none' })], { 'count.pseudo': PSEUDO });
|
||||
assert.deepEqual(out[0].codes.map((c) => c.lang), ['pseudo']);
|
||||
assert.match(out[0].src, /#\/embed\/table\/~/);
|
||||
assert.match(warnings, /showing the live view instead/);
|
||||
});
|
||||
|
||||
test('translate writes a tabset of code blocks; listing, tabs and link need no engine', { skip: NO_PANDOC }, () => {
|
||||
const { out } = shortcode([
|
||||
sc('pplus-translate', { matho: 'mean.tex' }),
|
||||
sc('pplus-listing', { pseudo: 'count.pseudo', numbers: '1' }),
|
||||
sc('pplus-tabs', { pseudo: 'count.pseudo', matho: 'mean.tex' }),
|
||||
sc('pplus-link', { pseudo: 'count.pseudo', text: 'Open it' }),
|
||||
sc('pplus-playground', { pseudo: 'count.pseudo', panel: 'flow' }),
|
||||
sc('pplus-embed', { pseudo: 'count.pseudo', view: 'life' }),
|
||||
], { 'count.pseudo': PSEUDO, 'mean.tex': '% CALL: X_BAR(3, [1.0, 2.0, 6.0])\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n' });
|
||||
const [tr, listing, tabs, link, playground, embed] = out;
|
||||
assert.ok(tr.divs.some((d) => d.includes('panel-tabset')), 'a tabset (Quarto turns it into tabs)');
|
||||
assert.deepEqual(tr.codes.map((c) => c.lang), ['latex', 'lingo', 'pseudo', 'mojo'], 'the file the page gave first, then what was made from it');
|
||||
assert.match(tr.codes.find((c) => c.lang === 'pseudo').text, /FUNCTION X_BAR/);
|
||||
assert.equal(tr.maths.length, 1, 'the equation typeset too');
|
||||
assert.match(tr.raw.join(''), /pplus-tag-generated/);
|
||||
assert.deepEqual(listing.codes, [{ lang: 'pseudo', text: PSEUDO.split('\n').slice(2).join('\n').trim() }]);
|
||||
assert.ok(tabs.divs.some((d) => d.includes('panel-tabset')));
|
||||
assert.match(link.links[0], /^https:\/\/pplus\.scient\.ing\/#\/bridge\/s\/~/);
|
||||
assert.match(playground.src, /#\/embed\/playground\/~.*\?panel=flow$/);
|
||||
assert.equal(playground.height, '720');
|
||||
assert.match(embed.src, /#\/embed\/life\/~/);
|
||||
});
|
||||
|
||||
test('in a format other than HTML a rendered view is Markdown', { skip: NO_PANDOC }, () => {
|
||||
process.env.PPLUS_FORMAT = 'latex';
|
||||
try {
|
||||
const { out } = shortcode([sc('pplus-run', { pseudo: 'count.pseudo' }), sc('pplus-flow', { pseudo: 'count.pseudo' })], { 'count.pseudo': PSEUDO });
|
||||
assert.equal(Object.keys(out[0].raw).length, 0, 'no HTML'); // (an empty Lua table is {} in JSON)
|
||||
assert.deepEqual(out[0].codes.map((c) => c.text), ['COUNT_BASE returned 3']);
|
||||
assert.ok(out[0].links.length, 'and a link to the app');
|
||||
assert.equal(Object.keys(out[1].raw).length, 0);
|
||||
} finally { delete process.env.PPLUS_FORMAT; }
|
||||
});
|
||||
|
||||
test('the Lua listing and the renderer\'s leave out the same header lines', { skip: NO_PANDOC }, async () => {
|
||||
const { listingText } = await import('../dist/quarto/program.js');
|
||||
const files = { 'a.pseudo': PSEUDO, 'b.mojo': MOJO, 'c.tex': '% CALL: F(1)\n% EXPECT: F returned 1\ny = x\n', 'd.lingo': '// CALL: F(1)\nTo f x:\n The answer is x.\n' };
|
||||
const { out } = shortcode([sc('pplus-listing', { pseudo: 'a.pseudo', mojo: 'b.mojo', matho: 'c.tex', lingo: 'd.lingo', math: '0' })], files);
|
||||
const byLang = Object.fromEntries(out[0].codes.map((c) => [c.lang, c.text]));
|
||||
assert.equal(byLang.pseudo, listingText(PSEUDO, 'pseudo'));
|
||||
assert.equal(byLang.mojo, listingText(MOJO, 'mojo'));
|
||||
assert.equal(byLang.latex, listingText(files['c.tex'], 'matho'));
|
||||
assert.equal(byLang.lingo, listingText(files['d.lingo'], 'lingo'));
|
||||
});
|
||||
|
||||
test('pplus-views.css is what `pixi run quarto-css` writes from styles.css', () => {
|
||||
const r = spawnSync(process.execPath, [ROOT + 'scripts/quarto-css.mjs', '--check'], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
});
|
||||
|
||||
test('the example site\'s programs run as their headers say, and its shortcodes name files that exist', () => {
|
||||
const r = spawnSync(process.execPath, [ROOT + 'scripts/check-pages.mjs', ROOT + 'quarto/example'], { encoding: 'utf8', cwd: ROOT });
|
||||
assert.equal(r.status, 0, r.stdout + r.stderr);
|
||||
assert.match(r.stdout, /0 problems/);
|
||||
const page = fs.readFileSync(ROOT + 'quarto/example/index.qmd', 'utf8') + fs.readFileSync(ROOT + 'quarto/example/live.qmd', 'utf8');
|
||||
const used = new Set([...page.matchAll(/(?<!\{)\{\{<\s*(pplus(?:-[a-z]+)?)/g)].map((m) => m[1]));
|
||||
const page2 = page + fs.readFileSync(ROOT + 'quarto/example/machine.qmd', 'utf8');
|
||||
for (const m of page2.matchAll(/(?<!\{)\{\{<\s*(pplus(?:-[a-z]+)*)/g)) used.add(m[1]);
|
||||
for (const name of ['pplus-run', 'pplus-steps', 'pplus-table', 'pplus-flow', 'pplus-dataflow', 'pplus-lifetimes', 'pplus-proof', 'pplus-tests', 'pplus-check', 'pplus-translate', 'pplus-machine', 'pplus-view', 'pplus-hw', 'pplus-hw-pipeline', 'pplus-hw-chip', 'pplus-hw-paging', 'pplus-hw-encoding', 'pplus-hw-counters', 'pplus-playground', 'pplus-embed', 'pplus-listing', 'pplus-tabs', 'pplus-link'])
|
||||
assert.ok(used.has(name), `the example site uses ${name}`);
|
||||
});
|
||||
|
||||
test('the machine: pplus-hw draws the board over an x86-64 run, and pplus-hw-<view> one card', { skip: NO_PANDOC }, async () => {
|
||||
const { problemById } = await import('../dist/core/catalog.js');
|
||||
const p = problemById('asm-two-pointers');
|
||||
const files = { 'two.asm': p.sources.asm, 'two.setup': p.setup };
|
||||
const { out, warnings } = shortcode([
|
||||
sc('pplus-hw', { asm: 'two.asm', setup: 'two.setup', t: '9' }),
|
||||
sc('pplus-hw-cache', { asm: 'two.asm', setup: 'two.setup', listing: '0' }),
|
||||
sc('pplus-hw', { asm: 'two.asm', setup: 'two.setup', views: 'registers,nonsense', column: 'body' }),
|
||||
sc('pplus-hw-registers', { pseudo: 'count.pseudo' }),
|
||||
], { ...files, 'count.pseudo': PSEUDO });
|
||||
const [board, cache, named, noAsm] = out;
|
||||
const html = board.raw.join('');
|
||||
assert.ok(board.divs.includes('pplus-figure pplus-figure-hw column-page'), 'the board is page-wide');
|
||||
for (const card of ['registers', 'flags', 'address', 'memory', 'stack']) assert.match(html, new RegExp(`data-hw="${card}"`), `the first preset has ${card}`);
|
||||
assert.match(html, /pplus-hw-now">Step 9: mov r11, qword ptr/);
|
||||
assert.match(html, /<div class="a86 board-a86" data-hw-frame="">\s*<section class="a86-panel/, 'the opening step\'s drawing is in the markup');
|
||||
assert.match(html, /<script type="application\/x-pplus-deflate" class="pplus-hw-data">[A-Za-z0-9+/=]+<\/script>/, 'every step, compressed');
|
||||
assert.match(html, /href="https:\/\/pplus\.scient\.ing\/#\/hw\/s\/~/, 'open in the playground goes to Hardware');
|
||||
const cacheHtml = cache.raw.join('');
|
||||
assert.ok(cache.divs.includes('pplus-figure pplus-figure-hw'), 'one card is as wide as the text');
|
||||
assert.match(cacheHtml, /data-hw="cache"/);
|
||||
assert.doesNotMatch(cacheHtml, /pplus-hw-listing/);
|
||||
assert.ok(!named.divs.some((d) => d.includes('column-')));
|
||||
assert.match(warnings, /pplus-hw in index\.qmd: hw: no machine view "nonsense"/);
|
||||
assert.match(noAsm.raw.join(''), /run an x86-64 file/);
|
||||
assert.match(warnings, /pplus-hw-registers in index\.qmd: hw: no x86-64 file/);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Runs the extension's shortcodes outside Quarto, with the few `quarto` functions they use stubbed, and prints one
|
||||
-- JSON line per call for tests/quarto.test.mjs. Usage: pandoc lua harness.lua <ext> <page dir> <calls.json>
|
||||
--
|
||||
-- A call is either the options of {{< pplus >}} ({ pseudo = "x.pseudo", ... }), or { sc = "pplus-run", kw = {...},
|
||||
-- meta = {...} } for any shortcode. The line holds what the blocks came to: the iframe's src and height, the code
|
||||
-- blocks (language and text), the links, the raw HTML, the classes of every Div, and the tab titles.
|
||||
local ext, dir, calls_file = arg[1], arg[2], arg[3]
|
||||
local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||||
local function b64(data)
|
||||
return ((data:gsub('.', function(x) local r, b = '', x:byte() for i = 8, 1, -1 do r = r .. (b % 2 ^ i - b % 2 ^ (i - 1) > 0 and '1' or '0') end return r end) .. '0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
|
||||
if #x < 6 then return '' end local c = 0 for i = 1, 6 do c = c + (x:sub(i, i) == '1' and 2 ^ (6 - i) or 0) end return b64chars:sub(c + 1, c + 1) end) .. ({ '', '==', '=' })[#data % 3 + 1])
|
||||
end
|
||||
local format = os.getenv('PPLUS_FORMAT') or 'html'
|
||||
quarto = { doc = { input_file = dir .. '/index.qmd', is_format = function(f) return f == format end, add_html_dependency = function() end },
|
||||
base64 = { encode = b64 }, json = { encode = pandoc.json.encode } }
|
||||
local shortcodes = dofile(ext .. '/pplus.lua')
|
||||
local f = io.open(calls_file); local calls = pandoc.json.decode(f:read('a'), false); f:close()
|
||||
local function str_table(t) local out = {} for k, v in pairs(t or {}) do out[k] = pandoc.Str(tostring(v)) end return out end
|
||||
for _, call in ipairs(calls) do
|
||||
local name, kw, meta = 'pplus', call, {}
|
||||
if call.sc then name, kw, meta = call.sc, call.kw or {}, call.meta or {} end
|
||||
local out = { codes = {}, links = {}, raw = {}, divs = {}, maths = {} }
|
||||
local blocks = shortcodes[name]({}, kw, str_table(meta))
|
||||
pandoc.Div(blocks):walk({
|
||||
RawBlock = function(blk)
|
||||
out.raw[#out.raw + 1] = blk.text
|
||||
local src = blk.text:match('<iframe[^>]-src="([^"]+)"')
|
||||
if src then out.src = src:gsub('&', '&'); out.height = blk.text:match('<iframe[^>]-height="(%d+)"') end
|
||||
end,
|
||||
CodeBlock = function(blk) out.codes[#out.codes + 1] = { lang = blk.classes[1], text = blk.text } end,
|
||||
Link = function(l) out.links[#out.links + 1] = l.target end,
|
||||
Div = function(d) if #d.classes > 0 then out.divs[#out.divs + 1] = table.concat(d.classes, ' ') end end,
|
||||
Math = function(m) out.maths[#out.maths + 1] = m.text end,
|
||||
})
|
||||
print(pandoc.json.encode(out))
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Runs against the compiled output: `npm test` builds first.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { encodeState, decodeState, parseRoute, routeFor } from '../dist/core/state.js';
|
||||
import { toAscii, toMath, parseSpec, weave, extractSpec } from '../core/dist/services/speco.js';
|
||||
import { studyOf, runPseudo, provePseudo } from '../core/dist/services/pseudo.js';
|
||||
import { readLingo, runLingo } from '../core/dist/services/lingo.js';
|
||||
import { parseAsm, runAsmProgram, parseSetup } from '../core/dist/services/asm.js';
|
||||
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
|
||||
test('state survives a URL round trip and routes parse', async () => {
|
||||
const st = stateForProblem(PROBLEMS[0]); st.t = 7; st.call = 'COUNT_BASE(\'G\', "GGG")';
|
||||
const back = await decodeState(await encodeState(st));
|
||||
assert.deepEqual(back.sources, st.sources);
|
||||
assert.equal(back.t, 7); assert.equal(back.call, st.call); assert.equal(back.problem, st.problem);
|
||||
assert.deepEqual(parseRoute('#/bridge/p/count-base'), { kind: 'problem', area: 'bridge', id: 'count-base' });
|
||||
const r = parseRoute('#/embed/trace/p/match?t=12');
|
||||
assert.equal(r.kind, 'embed'); assert.equal(r.view, 'trace'); assert.equal(r.problem, 'match'); assert.equal(r.params.get('t'), '12');
|
||||
assert.equal(routeFor({ kind: 'problem', area: 'dev', id: 'match' }), '#/dev/p/match');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// "What this site stores and sends" (SITE_DATA in src/core/site.ts, in the footer) is held to the code here: what the
|
||||
// shipped files ask for, which other sites they name, what they keep in the browser, and the footer's legal lines.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { GODBOLT_BASE } from '../core/dist/mojo/generated/pin.js';
|
||||
import { SITE_DATA, SOURCE_URL, LICENSE_FILES, DISCLAIMER, DESCRIPTION, siteVersion } from '../dist/core/site.js';
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8');
|
||||
const walk = (dir, keep) => fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true }).flatMap((e) => {
|
||||
const p = path.join(dir, e.name);
|
||||
return e.isDirectory() ? walk(p, keep) : keep(p) ? [p] : [];
|
||||
});
|
||||
|
||||
/** What scripts/assemble.sh ships: the page, the styles and fonts, dist/, core's dist/ (without the lesson corpus), and the Quarto extension. */
|
||||
const shipped = () => {
|
||||
const code = (p) => /\.(m?js|css|html|lua)$/.test(p) && !p.endsWith('.d.ts') && !p.endsWith('.map');
|
||||
return [
|
||||
'index.html', 'styles.css',
|
||||
...walk('styles', code), ...walk('fonts', code), ...walk('dist', code),
|
||||
...walk('core/dist', code).filter((p) => !p.startsWith('core/dist/curriculum/')),
|
||||
...walk('quarto/_extensions/pplus', code).filter((p) => !p.includes('/engine/')),
|
||||
];
|
||||
};
|
||||
|
||||
test('the only request the shipped code makes to another site is Compile & run\'s, to godbolt.org', () => {
|
||||
const files = shipped();
|
||||
assert.ok(files.length > 100, `${files.length} files`);
|
||||
const api = /\bfetch\s*\(|XMLHttpRequest|sendBeacon|new\s+WebSocket|new\s+EventSource|\.importScripts\s*\(/;
|
||||
const callers = files.filter((f) => api.test(read(f)));
|
||||
assert.deepEqual(callers, ['core/dist/services/godbolt.js'], 'a new network call must be added to the note on what the site sends');
|
||||
assert.equal(new URL(GODBOLT_BASE).hostname, 'godbolt.org');
|
||||
});
|
||||
|
||||
test('every other site the shipped files name is a link a reader follows, or not a place at all', () => {
|
||||
// a new origin fails here until it is listed with what it is; none of them is asked for anything (the CSP's
|
||||
// connect-src, font-src and script-src allow this site and godbolt.org only: tests/csp.test.mjs)
|
||||
const allowed = new Map([
|
||||
['https://godbolt.org', 'Compile & run (the one request, after asking)'],
|
||||
['https://mojolang.org', 'links to the Mojo manual and release notes'],
|
||||
['https://quest.mojolang.org', 'a link to Mojo Quest'],
|
||||
['https://doi.org', 'links to where a library routine\'s method comes from'],
|
||||
['https://dlmf.nist.gov', 'the same: the NIST Digital Library of Mathematical Functions'],
|
||||
['https://www.itl.nist.gov', 'the same: the NIST/SEMATECH e-Handbook of Statistical Methods'],
|
||||
['https://archive.org', 'the same: a scanned handbook'],
|
||||
['https://biopython.org', 'the same: the documentation of the function a routine is held against'],
|
||||
['https://biosc1540.scient.ing', 'the "guide" link beside a diagnostic'],
|
||||
['https://pplus.scient.ing', 'the Quarto extension\'s default address of the app, for its live views'],
|
||||
['http://www.w3.org', 'the SVG namespace, not a request'],
|
||||
['https://pplus.invalid', 'the address the small document of src/quarto/dom.ts pretends to have'],
|
||||
]);
|
||||
if (SOURCE_URL) allowed.set(new URL(SOURCE_URL).origin, 'the footer\'s link to the source');
|
||||
const seen = new Map();
|
||||
for (const f of shipped()) for (const m of read(f).matchAll(/\bhttps?:\/\/[a-z0-9.-]+\.[a-z]{2,}(?::\d+)?/gi)) {
|
||||
const o = new URL(m[0]).origin;
|
||||
if (!seen.has(o)) seen.set(o, f);
|
||||
}
|
||||
const unknown = [...seen].filter(([o]) => !allowed.has(o)).map(([o, f]) => `${o} (${f})`);
|
||||
assert.deepEqual(unknown, [], 'say what each is in this test, and in SITE_DATA if the site asks it for anything');
|
||||
assert.ok(seen.has(new URL(GODBOLT_BASE).origin));
|
||||
});
|
||||
|
||||
test('the site keeps nothing but localStorage and one sessionStorage mark, under names that start with pplus', () => {
|
||||
const src = walk('src', (p) => p.endsWith('.ts') && !p.includes('/vendor/')).map(read).join('\n');
|
||||
for (const api of ['document.cookie', 'indexedDB', 'caches.open', 'serviceWorker', 'openDatabase']) assert.ok(!src.includes(api), `src uses ${api}`);
|
||||
const shippedCode = shipped().filter((f) => f.endsWith('.js')).map(read).join('\n');
|
||||
assert.ok(!/document\.cookie|indexedDB\.open|navigator\.serviceWorker/.test(shippedCode), 'nor do the shipped modules');
|
||||
// every key a storage call names starts with pplus. (keys built by a function are checked where they are built)
|
||||
const literal = [...src.matchAll(/(?:local|session)Storage\.(?:getItem|setItem|removeItem)\(\s*(['"`])([^'"`$]*)/g)].map((m) => m[2]);
|
||||
assert.ok(literal.length > 3);
|
||||
for (const k of literal) assert.ok(/^pplus[.:]/.test(k) || k.startsWith('progo.'), `storage key ${k}`);
|
||||
// the keys built from an id (a problem's save, its versions, a preference per area) are template strings
|
||||
const built = [...src.matchAll(/`(pplus[.:][^`$]*)\$\{/g)].map((m) => m[1]);
|
||||
assert.ok(built.length >= 4, built.join(' '));
|
||||
for (const k of built) assert.ok(/^pplus[.:]/.test(k), `storage key ${k}…`);
|
||||
assert.match(read('src/core/guard.ts'), /sessionStorage/, 'the one sessionStorage mark (SITE_DATA says so)');
|
||||
assert.match(SITE_DATA.join(' '), /localStorage/);
|
||||
assert.match(SITE_DATA.join(' '), /sessionStorage/);
|
||||
assert.match(SITE_DATA.join(' '), /under names that start with "pplus"/);
|
||||
});
|
||||
|
||||
test('the note says what Compile & run sends, that it asks first, and that a shared link never saves over your work', () => {
|
||||
const text = SITE_DATA.join(' ');
|
||||
assert.match(text, /No accounts, no cookies, no analytics/);
|
||||
assert.match(text, /Compile & run sends the Mojo pane's text, the input box's lines and the build flags to godbolt\.org/);
|
||||
assert.match(text, /The first time, it says so and asks; nothing is sent until you agree/);
|
||||
assert.match(text, /never saves over your own work/);
|
||||
// what the request carries is mojoRequestBody's: the source, the input and the flags (core's src/services/godbolt.ts)
|
||||
const body = read('core/src/services/godbolt.ts');
|
||||
assert.match(body, /export function mojoRequestBody\(source: string, stdin = '', args = ''\)/);
|
||||
// held elsewhere: tests/hardening.test.mjs "the first Compile & run asks before anything is sent" and
|
||||
// "a shared link never saves over the reader's own work on the problem it names"
|
||||
const hardening = read('tests/hardening.test.mjs');
|
||||
assert.match(hardening, /the first Compile & run asks before anything is sent/);
|
||||
assert.match(hardening, /a shared link never saves over the reader\\'s own work/);
|
||||
});
|
||||
|
||||
test('the footer links the license and notices the site ships, and repeats NOTICE.md\'s disclaimer', () => {
|
||||
const assemble = read('scripts/assemble.sh');
|
||||
for (const f of LICENSE_FILES) {
|
||||
const file = f.href.replace('./', '');
|
||||
assert.ok(fs.existsSync(path.join(ROOT, file)), file);
|
||||
assert.match(assemble, new RegExp(`\\b${file.replace('.', '\\.')}\\b`), `assemble.sh copies ${file}`);
|
||||
}
|
||||
assert.match(read('LICENSE.md'), /Apache License/);
|
||||
const notice = read('NOTICE.md').replace(/\s+/g, ' ');
|
||||
assert.ok(notice.includes('Programming+ is not affiliated with, sponsored by, or endorsed by Modular Inc.'));
|
||||
assert.match(DISCLAIMER, /^Programming\+ is not affiliated with, sponsored by, or endorsed by Modular Inc\./);
|
||||
assert.equal(typeof SOURCE_URL, 'string', 'the source address: one constant, empty until the owner sets it');
|
||||
assert.ok(DESCRIPTION.length < 120);
|
||||
});
|
||||
|
||||
test('the build\'s version is shown only when the assembled page names a commit', () => {
|
||||
assert.equal(siteVersion('0123456789abcdef0123456789abcdef01234567'), '0123456789ab');
|
||||
assert.equal(siteVersion('dev'), null);
|
||||
assert.equal(siteVersion(''), null);
|
||||
assert.equal(siteVersion(null), null);
|
||||
assert.equal(siteVersion('<script>'), null);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Every source file written here says who holds its copyright and under which license, in two SPDX lines at its
|
||||
// top, so a file copied out of the repository still says where it came from. Left without them, on purpose:
|
||||
// the vendored editor's type declarations (src/vendor/), which are other people's files with their own
|
||||
// notices (THIRD_PARTY.md). A new file fails here until
|
||||
// it has the lines; this test goes with them if the owner drops the headers.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const LEFT_OUT = [/^src\/vendor\//];
|
||||
const HOLDER = 'SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC';
|
||||
const LICENSE = 'SPDX-License-Identifier: Apache-2.0';
|
||||
|
||||
test('every hand-written source, script and test starts with its SPDX lines', () => {
|
||||
const files = [];
|
||||
const walk = (dir) => {
|
||||
for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
|
||||
const f = `${dir}/${e.name}`;
|
||||
if (e.isDirectory()) { if (!['node_modules', '__pycache__'].includes(e.name)) walk(f); }
|
||||
else if (/\.(ts|js|mjs|py|sh)$/.test(e.name) && !LEFT_OUT.some((r) => r.test(f))) files.push(f);
|
||||
}
|
||||
};
|
||||
for (const d of ['src', 'scripts', 'tests']) walk(d);
|
||||
assert.ok(files.length > 85, `${files.length} files read`);
|
||||
const missing = [];
|
||||
for (const f of files) {
|
||||
const lines = fs.readFileSync(path.join(ROOT, f), 'utf8').split('\n');
|
||||
const at = lines[0].startsWith('#!') ? 1 : 0;
|
||||
const mark = /\.(py|sh)$/.test(f) ? '# ' : '// ';
|
||||
if (lines[at] !== mark + HOLDER || lines[at + 1] !== mark + LICENSE) missing.push(f);
|
||||
}
|
||||
assert.deepEqual(missing, []);
|
||||
assert.match(fs.readFileSync(path.join(ROOT, 'LICENSE.md'), 'utf8'), /Apache License/);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Programming+ is a new product: a state from any other version normalizes to empty, not migrated.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalize, emptyState, DEFAULT_PANES } from '../dist/core/state.js';
|
||||
|
||||
test('the state format is 3: no code pane, and mojo is the pane of Mojo the student writes', () => {
|
||||
assert.equal(emptyState().v, 3);
|
||||
assert.ok(!DEFAULT_PANES.includes('code'));
|
||||
assert.ok(DEFAULT_PANES.includes('mojo'));
|
||||
});
|
||||
|
||||
test('format-3 Mojo state round-trips, with its build level', () => {
|
||||
const s = normalize({ v: 3, lang: 'mojo', panes: ['pseudo', 'mojo'], sources: { mojo: 'def main():\n print(1)' }, view: 'compiler', build: 'default' });
|
||||
assert.equal(s.lang, 'mojo'); assert.equal(s.view, 'compiler'); assert.equal(s.build, 'default');
|
||||
assert.equal(s.sources.mojo, 'def main():\n print(1)');
|
||||
assert.equal(normalize({ v: 3, build: 'O3' }).build, undefined);
|
||||
});
|
||||
|
||||
test('a state from any other version normalizes to empty, not migrated', () => {
|
||||
assert.deepEqual(normalize({ v: 2, lang: 'mojo', panes: ['pseudo', 'mojo'], sources: { pseudo: 'OUTPUT 1' } }), emptyState());
|
||||
assert.deepEqual(normalize({ v: 1, lang: 'code', panes: ['pseudo', 'code', 'asm'], sources: { pseudo: 'OUTPUT 1', code: 'print(1)' }, target: 'rust', codeView: 'manual' }), emptyState());
|
||||
// the oldest links, with no v at all, and whose generated pane was called mojo: also empty, not migrated
|
||||
assert.deepEqual(normalize({ lang: 'mojo', panes: ['lingo', 'mojo'] }), emptyState());
|
||||
});
|
||||
|
||||
test('format-3 state round-trips', () => {
|
||||
const s = normalize({ v: 3, lang: 'asm', sources: { asm: 'ret' }, view: 'asm' });
|
||||
assert.equal(s.lang, 'asm'); assert.equal(s.panes, undefined, 'the area, not the state, decides which panes show'); assert.equal(s.sources.asm, 'ret');
|
||||
});
|
||||
|
||||
test('an embed keeps its own save, never the app\'s save for the problem', async () => {
|
||||
const { embedStorageId } = await import('../dist/core/state.js');
|
||||
const { Session } = await import('../dist/core/session.js');
|
||||
assert.equal(embedStorageId('mojo', 'count-base'), 'embed.mojo.p.count-base');
|
||||
assert.equal(embedStorageId('trace', undefined, 'abc'), embedStorageId('trace', undefined, 'abc'));
|
||||
assert.notEqual(embedStorageId('trace', undefined, 'abc'), embedStorageId('trace', undefined, 'abd'));
|
||||
assert.match(embedStorageId('trace', undefined, 'x'.repeat(5000)), /^embed\.trace\.b\.[0-9a-f]{8}$/);
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
|
||||
try {
|
||||
const embed = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { storageId: 'embed.pseudo.p.count-base' });
|
||||
embed.setSource('pseudo', 'OUTPUT 2');
|
||||
assert.deepEqual([...store.keys()], ['pplus.embed.pseudo.p.count-base']);
|
||||
const app = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }));
|
||||
app.setSource('pseudo', 'OUTPUT 3');
|
||||
assert.ok(store.has('pplus.count-base'));
|
||||
assert.match(store.get('pplus.embed.pseudo.p.count-base'), /OUTPUT 2/);
|
||||
// an embed keeps a save only while it holds edits: editing back to the original removes it
|
||||
const { editedFrom } = await import('../dist/core/state.js');
|
||||
const original = normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } });
|
||||
const kept = new Session(structuredClone(original), { storageId: 'embed.x', keep: (st) => editedFrom(st, original) });
|
||||
kept.setSource('pseudo', 'OUTPUT 9'); assert.ok(store.has('pplus.embed.x'));
|
||||
kept.setSource('pseudo', 'OUTPUT 1'); assert.ok(!store.has('pplus.embed.x'), 'back to the original: no save');
|
||||
kept.setView('proof'); assert.ok(!store.has('pplus.embed.x'), 'where the reader looks is not an edit');
|
||||
const readOnly = new Session(normalize({ v: 3, problem: 'count-base' }), { storageId: null });
|
||||
store.clear(); readOnly.setSource('pseudo', 'OUTPUT 4');
|
||||
assert.equal(store.size, 0, 'a read-only embed saves nothing');
|
||||
} finally { delete globalThis.localStorage; }
|
||||
});
|
||||
|
||||
test('a save made against an older version of a problem is dropped unless it holds edits', async () => {
|
||||
const { normalize, editsFingerprint, resolveSaved } = await import('../dist/core/state.js');
|
||||
const original = normalize({ v: 3, problem: 'p', sources: { pseudo: 'OUTPUT 2' } });
|
||||
const older = normalize({ v: 3, problem: 'p', sources: { pseudo: 'OUTPUT 1' } });
|
||||
assert.deepEqual(resolveSaved(original, null), { state: original, stale: false });
|
||||
// made against the current version: kept as is
|
||||
const current = { ...structuredClone(original), base: editsFingerprint(original), edited: false, t: 3 };
|
||||
assert.equal(resolveSaved(original, current).state.t, 3);
|
||||
// made against an older version, no edits: the author's current version wins
|
||||
const untouched = { ...structuredClone(older), base: editsFingerprint(older), edited: false };
|
||||
assert.deepEqual(resolveSaved(original, untouched), { state: original, stale: false });
|
||||
// made against an older version, with edits: kept, and marked stale
|
||||
const edited = { ...structuredClone(older), sources: { pseudo: 'OUTPUT 9' }, base: editsFingerprint(older), edited: true };
|
||||
const r = resolveSaved(original, edited);
|
||||
assert.equal(r.stale, true); assert.equal(r.state.sources.pseudo, 'OUTPUT 9');
|
||||
// a save from before fingerprints existed is kept
|
||||
assert.equal(resolveSaved(original, normalize({ v: 3, sources: { pseudo: 'OUTPUT 7' } })).state.sources.pseudo, 'OUTPUT 7');
|
||||
// fingerprints ignore where the reader is looking
|
||||
assert.equal(editsFingerprint(original), editsFingerprint({ ...original, t: 9, view: 'proof' }));
|
||||
});
|
||||
|
||||
test('a save from another state format is discarded, so the problem opens as written', async () => {
|
||||
const { loadLocal, resolveSaved } = await import('../dist/core/state.js');
|
||||
const { problemById, stateForProblem } = await import('../dist/core/catalog.js');
|
||||
const store = new Map([['pplus.count-base', JSON.stringify({ v: 2, problem: 'count-base', sources: { pseudo: 'OUTPUT 9' } })]]);
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
|
||||
try {
|
||||
assert.equal(loadLocal('count-base'), null);
|
||||
assert.ok(!store.has('pplus.count-base'), 'the old save is removed');
|
||||
const original = stateForProblem(problemById('count-base'));
|
||||
assert.deepEqual(resolveSaved(original, loadLocal('count-base')).state, original);
|
||||
} finally { delete globalThis.localStorage; }
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 8: the sync hub (restructure plan, section 2.3), without any UI. Pseudo is the hub; the pane that is
|
||||
// edited is the authority and is never rewritten; an authority with errors changes nothing; a language that
|
||||
// cannot say the program goes stale rather than blank; contracts ride along; opening rewrites nothing; and the
|
||||
// whole cascade is fast enough that typing stays instant.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { SyncHub, LINKED, namesFromMatho } from '../core/dist/sync/hub.js';
|
||||
import { pseudoToLingo } from '../core/dist/sync/pseudo-to-lingo.js';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { PROBLEMS, stateForProblem, problemById } from '../dist/core/catalog.js';
|
||||
import { encodeState, decodeState, emptyState } from '../dist/core/state.js';
|
||||
import { checkMojo } from '../core/dist/mojo/check.js';
|
||||
import { studyOf } from '../core/dist/services/pseudo.js';
|
||||
import { EQUATIONS, FIXTURES } from '../core/tests/helpers/sync-programs.mjs';
|
||||
|
||||
globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } };
|
||||
|
||||
const sync = (r) => ({ authority: r.authority, stale: r.stale, names: r.names });
|
||||
const next = (r, lang, text) => new SyncHub(r.sources, sync(r)).edit(lang, text);
|
||||
|
||||
const COUNT = `FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER
|
||||
DECLARE Total : INTEGER
|
||||
Total <- 0
|
||||
FOR EACH C IN T
|
||||
IF C == B THEN
|
||||
Total <- Total + 1
|
||||
ENDIF
|
||||
NEXT C
|
||||
RETURN Total
|
||||
ENDFUNCTION`;
|
||||
const SIMPLE = `FUNCTION SUMMED(N : INTEGER, X : LIST OF FLOAT) RETURNS FLOAT
|
||||
DECLARE S : FLOAT
|
||||
S <- 0.0
|
||||
FOR I <- 0 TO N
|
||||
S <- S + X[I]
|
||||
NEXT I
|
||||
RETURN S
|
||||
ENDFUNCTION`;
|
||||
const WHILE_PSEUDO = FIXTURES['fixture:div-mod'][0];
|
||||
|
||||
test('the first edit makes the pane the authority and writes the shown panes into the state', () => {
|
||||
const p = problemById('count-base');
|
||||
const s = new Session(stateForProblem(p));
|
||||
let events = 0; s.onChange(() => events++);
|
||||
const lingo = s.source('lingo').replace('Start with Count at 0.', 'Start with Count at 5.');
|
||||
assert.notEqual(lingo, s.source('lingo'));
|
||||
s.setSource('lingo', lingo);
|
||||
assert.equal(events, 1, 'one change event for the whole cascade');
|
||||
assert.equal(s.state.sync.authority, 'lingo');
|
||||
assert.equal(s.state.sources.lingo, lingo);
|
||||
assert.match(s.source('pseudo'), /Count <- 5/);
|
||||
assert.match(s.derivedMojo().source, /count = 5/);
|
||||
assert.equal(s.linkState('lingo').kind, 'authority');
|
||||
assert.equal(s.linkState('pseudo').kind, 'sync');
|
||||
// an unchanged text is not an edit
|
||||
s.setSource('lingo', lingo);
|
||||
assert.equal(events, 1);
|
||||
// Mojo and x86-64 are not linked
|
||||
s.setSource('mojo', 'def main():\n pass\n');
|
||||
assert.equal(s.state.sync.authority, 'lingo');
|
||||
});
|
||||
|
||||
test('a share link round-trips sync, and a stale pane stays stale', async () => {
|
||||
const p = problemById('count-base');
|
||||
const s = new Session(stateForProblem(p));
|
||||
s.setSource('pseudo', 'FUNCTION BROKEN(\nRETURN');
|
||||
assert.equal(s.linkState('lingo').kind, 'stale');
|
||||
const blob = await encodeState(s.state);
|
||||
const back = await decodeState(blob);
|
||||
assert.deepEqual(back.sync, s.state.sync);
|
||||
const s2 = new Session(back);
|
||||
assert.match(s2.linkState('lingo').reason, /pseudo line/);
|
||||
assert.equal(s2.source('pseudo'), 'FUNCTION BROKEN(\nRETURN', 'a state that has been edited is not filled again');
|
||||
// a malformed sync field is dropped, not trusted
|
||||
const { normalize } = await import('../dist/core/state.js');
|
||||
assert.equal(normalize({ v: 3, sync: { authority: 'mojo' } }).sync, undefined);
|
||||
});
|
||||
|
||||
test('derivedMojo is the literal translation, is memoized by the pseudo and the call, and passes the checker', () => {
|
||||
const s = new Session(stateForProblem(problemById('count-base')));
|
||||
const a = s.derivedMojo();
|
||||
assert.match(a.source, /^# Generated by Programming\+ from pseudo\./);
|
||||
assert.equal(s.derivedMojo(), a, 'the same object while the pseudo and the call are unchanged');
|
||||
const diags = checkMojo(a.source).diagnostics.filter((d) => d.severity === 'error');
|
||||
assert.deepEqual(diags, []);
|
||||
s.setSource('pseudo', s.source('pseudo').replace('Total <- 0', 'Total <- 1'));
|
||||
assert.notEqual(s.derivedMojo(), a);
|
||||
assert.match(s.derivedMojo().source, /total = 1/);
|
||||
s.setCall('COUNT_BASE("C", "CCC")');
|
||||
assert.match(s.derivedMojo().source, /count_base\("C", "CCC"\)/);
|
||||
// no pseudo, no Mojo
|
||||
assert.equal(new Session(emptyState()).derivedMojo().source, '');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// The commands people run live in pixi.toml; the README's table lists them. core/ is pplus-core, a project of its
|
||||
// own with its own pixi.toml and this same test. These tests keep the
|
||||
// two in step, and keep every `pixi run <task>` mentioned anywhere pointing at a task that exists.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8');
|
||||
|
||||
/** Task names in pixi.toml's [tasks] table: `name = {` at the start of a line, until the next table. */
|
||||
function pixiTasks() {
|
||||
const text = read('pixi.toml');
|
||||
const body = text.slice(text.indexOf('\n[tasks]') + 1).split(/\n\[(?!tasks\])/)[0];
|
||||
return [...body.matchAll(/^([a-z][a-z0-9-]*)\s*=\s*\{/gm)].map((m) => m[1]);
|
||||
}
|
||||
|
||||
/** Task names in the README's Commands table: the first cell, a backticked name with optional arguments. */
|
||||
function readmeTasks() {
|
||||
const readme = read('README.md');
|
||||
const section = readme.slice(readme.indexOf('## Commands'), readme.indexOf('\n## ', readme.indexOf('## Commands') + 1));
|
||||
return [...section.matchAll(/^\| `([a-z][a-z0-9-]*)(?: [^`]*)?` \|/gm)].map((m) => m[1]);
|
||||
}
|
||||
|
||||
test('the README lists every pixi task, once, and nothing else', () => {
|
||||
const tasks = pixiTasks();
|
||||
assert.ok(tasks.length > 15, `only ${tasks.length} tasks read from pixi.toml`);
|
||||
const listed = readmeTasks();
|
||||
assert.deepEqual([...listed].sort(), [...tasks].sort());
|
||||
assert.equal(new Set(listed).size, listed.length, 'a task is listed twice');
|
||||
});
|
||||
|
||||
test('every pixi task has a description', () => {
|
||||
const text = read('pixi.toml');
|
||||
for (const t of pixiTasks()) {
|
||||
const line = text.split('\n').find((l) => l.startsWith(`${t} = {`));
|
||||
assert.match(line, /description = "[^"]+"/, `${t} has no description`);
|
||||
}
|
||||
});
|
||||
|
||||
test('every `pixi run <task>` in the docs, scripts and sources names a real task', () => {
|
||||
const tasks = new Set(pixiTasks());
|
||||
const files = [];
|
||||
const walk = (dir) => {
|
||||
for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) { if (!['node_modules', 'dist', 'site', '.git', '.pixi', 'corpus', 'golden', 'vendor', 'scratch', '_site', '.quarto'].includes(e.name) && p !== 'core') walk(p); }
|
||||
else if (/\.(md|mjs|ts|py|lua|yml|toml)$/.test(e.name)) files.push(p);
|
||||
}
|
||||
};
|
||||
walk('.');
|
||||
const unknown = [];
|
||||
for (const f of files) {
|
||||
for (const m of read(f).matchAll(/pixi run ([a-z][a-z0-9-]*)/g)) if (!tasks.has(m[1])) unknown.push(`${f}: pixi run ${m[1]}`);
|
||||
}
|
||||
assert.deepEqual(unknown, []);
|
||||
});
|
||||
|
||||
test('package.json keeps only what CI and a machine without pixi need', () => {
|
||||
const pkg = JSON.parse(read('package.json'));
|
||||
assert.deepEqual(Object.keys(pkg.scripts).sort(), ['build', 'check', 'dev', 'test', 'watch']);
|
||||
// the README and AGENTS.md say TypeScript is the only npm dependency and the site has no npm runtime dependency
|
||||
assert.equal(pkg.dependencies, undefined, 'no npm runtime dependency (CodeMirror is vendored in src/vendor/)');
|
||||
assert.deepEqual(Object.keys(pkg.devDependencies ?? {}), ['typescript']);
|
||||
});
|
||||
|
||||
test('every document the README points to exists', () => {
|
||||
const readme = read('README.md');
|
||||
for (const m of readme.matchAll(/\]\(((?:docs|quarto|styles)\/[^)#]+)\)/g)) assert.ok(fs.existsSync(path.join(ROOT, m[1])), `${m[1]} is linked from the README but missing`);
|
||||
for (const m of read('docs/app.md').matchAll(/`(docs\/[\w.-]+\.md)`/g)) assert.ok(fs.existsSync(path.join(ROOT, m[1])), `${m[1]} is named in docs/app.md but missing`);
|
||||
});
|
||||
|
||||
test('the site names the Mojo version core is pinned to, in its documents and in pixi.toml', async () => {
|
||||
// core decides the pin (core/library/mojo/pin.json); these are the site's sentences that have to move with it
|
||||
const { MOJO_VERSION, GODBOLT_COMPILER } = await import('../core/dist/mojo/generated/pin.js');
|
||||
const wrong = [];
|
||||
for (const d of ['README.md', 'AGENTS.md', 'docs/app.md', 'docs/deploy.md', 'quarto/README.md']) {
|
||||
fs.readFileSync(path.join(ROOT, d), 'utf8').split('\n').forEach((line, i) => {
|
||||
for (const m of line.matchAll(/(?:pinned to (?:\*\*)?(?:Mojo )?|verified on Mojo )(\d+\.\d+\.\d+)/g)) if (m[1] !== MOJO_VERSION) wrong.push(`${d}:${i + 1} says ${m[1]}`);
|
||||
for (const m of line.matchAll(/\bmojo_\d+_\d+_\d+\b/g)) if (m[0] !== GODBOLT_COMPILER) wrong.push(`${d}:${i + 1} says ${m[0]}`);
|
||||
});
|
||||
}
|
||||
assert.deepEqual(wrong, [], `core is pinned to Mojo ${MOJO_VERSION}`);
|
||||
assert.match(fs.readFileSync(path.join(ROOT, 'pixi.toml'), 'utf8'), new RegExp(`^mojo = "==${MOJO_VERSION.replace(/\./g, '\\.')}"`, 'm'), 'pixi.toml installs the compiler core is pinned to');
|
||||
});
|
||||
|
||||
test('package.json and pixi.toml agree, and the site pins the same Node and Python as core', () => {
|
||||
// package.json is what a machine without pixi reads; core/pixi.toml is the pin core is tested with
|
||||
const pkg = JSON.parse(read('package.json'));
|
||||
const toml = read('pixi.toml');
|
||||
const core = read('core/pixi.toml');
|
||||
assert.equal(/^version = "([^"]+)"/m.exec(toml)?.[1], pkg.version, 'the version in pixi.toml [workspace] and in package.json');
|
||||
for (const dep of ['nodejs', 'python']) {
|
||||
const pin = (text) => new RegExp(`^${dep} = "([^"]+)"`, 'm').exec(text)?.[1];
|
||||
assert.equal(pin(toml), pin(core), `${dep}: the site pins ${pin(toml)}, core ${pin(core)}`);
|
||||
}
|
||||
const parts = (s) => s.split('.').map(Number).concat([0, 0]).slice(0, 3);
|
||||
const atLeast = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return true; };
|
||||
const floor = /^>=\s*(\d+(?:\.\d+){0,2})$/.exec(pkg.engines?.node ?? '');
|
||||
assert.ok(floor, `engines.node is "${pkg.engines?.node}"; this test reads ">=X.Y.Z"`);
|
||||
const pinned = /^nodejs = ">=(\d+\.\d+\.\d+)/m.exec(toml);
|
||||
assert.ok(pinned && atLeast(parts(pinned[1]), parts(floor[1])), `pixi installs Node ${pinned?.[1]}, below engines.node ${pkg.engines.node}`);
|
||||
assert.equal(pkg.engines.node, JSON.parse(read('core/package.json')).engines?.node, 'the site and core name the same oldest Node');
|
||||
assert.ok(atLeast(parts(process.versions.node), parts(floor[1])), `this Node is ${process.versions.node}, below engines.node ${pkg.engines.node}`);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// THIRD_PARTY.md is written by hand; these tests hold it to the files that say what is bundled, copied, loaded
|
||||
// and installed, so a rebuilt CodeMirror, a new copied stylesheet, a self-hosted font or a moved tool fails here
|
||||
// until the inventory says so. They read files only: no build and no core/ needed.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname;
|
||||
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8');
|
||||
const doc = read('THIRD_PARTY.md');
|
||||
const row = (name) => doc.split('\n').find((l) => l.startsWith(`| ${name} `)) ?? '';
|
||||
|
||||
test('every package bundled into codemirror.js has a row with its version and a copyright notice', () => {
|
||||
const banner = read('src/vendor/codemirror.js').split('\n').slice(0, 3).join('\n');
|
||||
const pkgs = [...banner.matchAll(/(@?[a-z0-9-]+(?:\/[a-z0-9-]+)?)@(\d+\.\d+\.\d+)/g)].map((m) => [m[1], m[2]]);
|
||||
assert.ok(pkgs.length >= 10, `only ${pkgs.length} packages read from the banner`);
|
||||
for (const [name, version] of pkgs) {
|
||||
const r = row(name);
|
||||
assert.ok(r.includes(`| ${version} |`), `${name}@${version} has no row with that version`);
|
||||
assert.match(r, /\| Copyright \(C\) \d{4}(-\d{4})? by .+ \|$/, `${name} has no copyright notice`);
|
||||
}
|
||||
const rows = doc.split('\n').filter((l) => /^\| (@[a-z0-9-]+\/)?[a-z0-9-]+ \| \d+\.\d+\.\d+ \| /.test(l));
|
||||
assert.equal(rows.length, pkgs.length, 'a row for a package the bundle does not hold');
|
||||
// the permission notice is the one the vendored license file carries
|
||||
const permission = read('src/vendor/CODEMIRROR-LICENSE').split('\n').slice(4).join('\n').trim();
|
||||
assert.ok(doc.includes(permission), 'the MIT permission notice differs from src/vendor/CODEMIRROR-LICENSE');
|
||||
});
|
||||
|
||||
test('every copied course stylesheet and syntax definition is named', () => {
|
||||
for (const dir of ['styles/course', 'quarto/_extensions/pplus/course', 'quarto/_extensions/pplus/syntax']) {
|
||||
for (const f of fs.readdirSync(path.join(ROOT, dir))) if (/\.(css|xml)$/.test(f)) assert.ok(doc.includes(`\`${f}\``), `${dir}/${f} is not named`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the fonts the page loads are named, and a font file in the repository has its license beside it', () => {
|
||||
const html = read('index.html');
|
||||
for (const m of html.matchAll(/family=([A-Za-z+]+)/g)) assert.ok(doc.includes(m[1].replace(/\+/g, ' ')), `${m[1]} is not named`);
|
||||
const fonts = [];
|
||||
const walk = (d) => {
|
||||
for (const e of fs.readdirSync(path.join(ROOT, d), { withFileTypes: true })) {
|
||||
const p = path.join(d, e.name);
|
||||
if (e.isDirectory()) { if (!['node_modules', 'dist', 'core', '.git', '.pixi', 'site', 'scratch', '_site', '.quarto'].includes(e.name)) walk(p); } // _site and .quarto: what `pixi run quarto-example` leaves, with Quarto's own fonts
|
||||
else if (/\.(woff2?|ttf|otf)$/i.test(e.name)) fonts.push(p);
|
||||
}
|
||||
};
|
||||
walk('.');
|
||||
for (const f of fonts) {
|
||||
const dir = path.dirname(f);
|
||||
assert.ok(fs.readdirSync(path.join(ROOT, dir)).some((n) => /^(OFL|LICENSE)/i.test(n)), `${f} has no OFL or LICENSE file beside it`);
|
||||
}
|
||||
if (fonts.length) assert.ok(/IBM Plex/.test(doc), 'font files are served but THIRD_PARTY.md names no font');
|
||||
});
|
||||
|
||||
test('the tools in pixi.lock and package-lock.json have their versions and licenses', () => {
|
||||
const lock = read('pixi.lock');
|
||||
const conda = (pkg) => {
|
||||
const m = lock.match(new RegExp(`\\n- conda: \\S*/${pkg}-(\\d[^-/]*)-[^/\\s]*\\.conda\\n(?: .*\\n)*? license: (.+)`));
|
||||
assert.ok(m, `${pkg} is not in pixi.lock`);
|
||||
return { version: m[1], license: m[2].trim() };
|
||||
};
|
||||
for (const [name, pkg] of [['Mojo', 'mojo'], ['Node.js', 'nodejs'], ['Python', 'python'], ['pandoc', 'pandoc']]) {
|
||||
const c = conda(pkg);
|
||||
assert.ok(row(name).includes(`| ${c.version} |`) && row(name).includes(c.license), `${name} ${c.version}, ${c.license}`);
|
||||
}
|
||||
const pkgs = JSON.parse(read('package-lock.json')).packages;
|
||||
assert.deepEqual(Object.keys(pkgs).filter((k) => k), ['node_modules/typescript'], 'a new npm package needs a row here (and AGENTS.md allows none)');
|
||||
const ts = pkgs['node_modules/typescript'];
|
||||
assert.ok(row('TypeScript').includes(`| ${ts.version} |`) && row('TypeScript').includes(`| ${ts.license} |`), `TypeScript ${ts.version}, ${ts.license}`);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Every badge and chip the site shows makes a claim, and core's docs/trust.md is where each claim says what earned
|
||||
// it, what it means and what it does not mean. This test holds the two together: the words a badge can show are
|
||||
// listed here with the row of trust.md that covers them, the words must still be in the source that draws them, the
|
||||
// row must still be in trust.md, and a badge drawn in a new place fails the count until it is listed.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const trust = fs.readFileSync('core/docs/trust.md', 'utf8');
|
||||
/** The first cell ("Shown") of every row of every table in trust.md. */
|
||||
const shown = trust.split('\n').filter((l) => l.startsWith('| ') && !/^\| (Shown|---)/.test(l)).map((l) => l.slice(2).split(' | ')[0]);
|
||||
const read = (f) => fs.readFileSync(f, 'utf8');
|
||||
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.ts') ? [path.join(dir, e.name)] : []));
|
||||
|
||||
/** [the words on the badge, the file that draws it, the words of trust.md's "Shown" cell that cover it] */
|
||||
const BADGES = [
|
||||
['Generated from pseudo', 'src/ui/provenance.ts', '**Generated from pseudo**'],
|
||||
['best-practice rewrite', 'src/ui/provenance.ts', '**Generated from pseudo, with N best-practice rewrites**'],
|
||||
['Started from generated Mojo', 'src/ui/provenance.ts', '**Started from generated Mojo**'],
|
||||
['Compiled on godbolt', 'src/ui/provenance.ts', '**Compiled on godbolt**'],
|
||||
['Edited since compile', 'src/ui/provenance.ts', '**Edited since compile**'],
|
||||
...['compiling', 'ran, exit 0', 'exited with', 'compiled, did not run', 'did not compile', 'timed out', 'no answer']
|
||||
.map((w) => [w, 'src/ui/views/compiler.ts', `**${w}`]),
|
||||
['verified on Mojo', 'src/ui/shell.ts', '**verified on Mojo'],
|
||||
['not verified', 'src/ui/shell.ts', '**not verified**'],
|
||||
['your edits', 'src/ui/shell.ts', '**your edits**'],
|
||||
['`Mojo ${MOJO_VERSION}`', 'src/ui/shell.ts', '(no other word)'],
|
||||
["'verified'", 'src/ui/home.ts', 'The home page\'s **verified** chip'],
|
||||
['your edits saved', 'src/ui/home.ts', '**your edits saved** chip'],
|
||||
['proved', 'src/ui/views/panels.ts', '**Proved**'],
|
||||
['broken by a run', 'src/ui/views/panels.ts', '**Broken**'],
|
||||
['open', 'src/ui/views/panels.ts', '**Open**'],
|
||||
['partial: not every path was examined', 'src/ui/views/panels.ts', '**partial: not every path was examined**'],
|
||||
['no failures', 'src/ui/views/tests.ts', '**no failures**'],
|
||||
['of failing', 'src/ui/views/tests.ts', '**N ways of failing**'],
|
||||
['not tested', 'src/ui/views/tests.ts', '**not tested**'],
|
||||
// the home page's sample cards show the same three kinds of answer on a fixed example
|
||||
['no failures', 'src/ui/home.ts', '**no failures**'],
|
||||
['to fail', 'src/ui/home.ts', '**N ways of failing**'],
|
||||
['proved', 'src/ui/home.ts', '**Proved**'],
|
||||
['ran, exit 0', 'src/ui/home.ts', '**ran, exit 0**'],
|
||||
];
|
||||
/** The library page's chips are a check's name and one of five words; trust.md has a row for each kind of check. */
|
||||
const LIBRARY_ROWS = ['**Cases pass**', '**Prover: pass**', '**Prover: open**', '**A reference agrees**', '**Mojo: unverified**', '**Proof: pass**'];
|
||||
|
||||
test('every badge the site can show is drawn where this test says, and has a row in core\'s docs/trust.md', () => {
|
||||
assert.ok(shown.length >= 30, `${shown.length} rows read from core/docs/trust.md`);
|
||||
for (const [words, file, row] of BADGES) {
|
||||
assert.ok(read(file).includes(words), `${file} no longer shows "${words}": take it off this list, or say what replaced it`);
|
||||
assert.ok(shown.some((c) => c.includes(row)), `core/docs/trust.md has no row for ${row} (shown by ${file} as "${words}")`);
|
||||
}
|
||||
for (const row of LIBRARY_ROWS) assert.ok(shown.some((c) => c.includes(row)), `core/docs/trust.md has no row for ${row}`);
|
||||
});
|
||||
|
||||
test('a badge drawn in a new place is listed here, with its row in trust.md, before it ships', () => {
|
||||
const sites = new Map();
|
||||
for (const f of walk('src')) {
|
||||
const n = (read(f).match(/class: [`'](?:badge[ `'$]|chip chip-verified|chip chip-saved|lib-chip[ `'$])/g) || []).length;
|
||||
if (n) sites.set(f, n);
|
||||
}
|
||||
assert.deepEqual(Object.fromEntries(sites), {
|
||||
'src/ui/home.ts': 9,
|
||||
'src/ui/library.ts': 2,
|
||||
'src/ui/provenance.ts': 3,
|
||||
'src/ui/shell.ts': 3,
|
||||
'src/ui/views/compiler.ts': 2,
|
||||
'src/ui/views/panels.ts': 5,
|
||||
'src/ui/views/tests.ts': 3,
|
||||
}, 'a badge was added or removed: update BADGES above and core\'s docs/trust.md, then this count');
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Stage 14: saved versions. A version holds what the student edits (sources, link bookkeeping, where the Mojo came
|
||||
// from, call, input, setup, machine, build) and not where they are looking (layout, step, open tab). Switching and
|
||||
// Reset save unsaved work first, so neither loses anything; the cap holds; a link carries no versions, a file may.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Session } from '../dist/core/session.js';
|
||||
import { stateForProblem, problemById } from '../dist/core/catalog.js';
|
||||
import { resolveSaved, editsFingerprint, normalize, encodeState, decodeState, saveLocal } from '../dist/core/state.js';
|
||||
import {
|
||||
listVersions, saveVersion, renameVersion, deleteVersion, restoreVersion, editsOf, hasUnsavedEdits, versionKey, currentVersion,
|
||||
exportVersions, importVersions, cleanVersion, storagePressure, MAX_VERSIONS, PRESSURE_CHARS, newWorkspaceId,
|
||||
} from '../dist/core/versions.js';
|
||||
|
||||
function fakeStorage() {
|
||||
const m = new Map();
|
||||
return {
|
||||
getItem: (k) => m.get(k) ?? null, setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k),
|
||||
key: (i) => [...m.keys()][i] ?? null, get length() { return m.size; }, _m: m,
|
||||
};
|
||||
}
|
||||
let store;
|
||||
test.beforeEach(() => { store = fakeStorage(); globalThis.localStorage = store; });
|
||||
|
||||
const problem = (id = 'count-base') => stateForProblem(problemById(id));
|
||||
const open = (state, area = 'bridge', opts = {}) => new Session(state, { area, storageId: null, original: opts.original, stale: opts.stale });
|
||||
const withLingo = (st, text) => { const s = structuredClone(st); s.sources.lingo = text; return s; };
|
||||
|
||||
test('save, list, rename, delete and restore round-trip', () => {
|
||||
const st = problem();
|
||||
const key = versionKey(st);
|
||||
assert.equal(key, 'pplus.versions.count-base');
|
||||
assert.deepEqual(listVersions(key), []);
|
||||
const a = saveVersion(key, 'first', st, 'bridge', { now: 1000 });
|
||||
const edited = withLingo(st, 'Start with Total at 0.');
|
||||
const b = saveVersion(key, 'second', edited, 'dev', { now: 2000 });
|
||||
assert.ok(a.ok && b.ok);
|
||||
assert.deepEqual(listVersions(key).map((v) => [v.name, v.area]), [['second', 'dev'], ['first', 'bridge']], 'newest first, with the area it was saved in');
|
||||
assert.equal(renameVersion(key, a.version.id, 'original'), true);
|
||||
assert.equal(listVersions(key)[1].name, 'original');
|
||||
const back = restoreVersion(key, b.version.id, st);
|
||||
assert.equal(back.sources.lingo, 'Start with Total at 0.');
|
||||
assert.equal(restoreVersion(key, 'nope', st), null);
|
||||
assert.equal(deleteVersion(key, b.version.id), true);
|
||||
assert.equal(listVersions(key).length, 1);
|
||||
assert.equal(deleteVersion(key, 'nope'), false);
|
||||
deleteVersion(key, a.version.id);
|
||||
assert.equal(store.getItem(key), null, 'an empty list leaves nothing behind');
|
||||
});
|
||||
|
||||
test('a version holds the edited fields, sync, mojoOrigin and machine, and not the layout, step or tab', () => {
|
||||
const st = problem();
|
||||
Object.assign(st, { input: '3\n', call: 'COUNT_BASE("A", "AA")', setup: 'x', machine: 'm', build: 'default', mojoOrigin: 'generated', sync: { authority: 'lingo', stale: {}, names: {} }, layout: { bridge: { split: 0.3 } }, t: 7, lang: 'matho', view: 'flow', title: 'T' });
|
||||
const e = editsOf(st);
|
||||
assert.deepEqual(Object.keys(e).sort(), ['build', 'call', 'input', 'machine', 'mojoOrigin', 'setup', 'sources', 'sync']);
|
||||
for (const k of ['layout', 't', 'lang', 'view', 'title', 'problem', 'base', 'edited']) assert.ok(!(k in e), k);
|
||||
});
|
||||
|
||||
test('restoring changes the edits but not the layout, the step or the open tab; a field the version lacks does not linger', () => {
|
||||
const key = 'pplus.versions.count-base';
|
||||
const plain = problem();
|
||||
const v = saveVersion(key, 'plain', plain, 'bridge').version;
|
||||
const now = withLingo(plain, 'something else');
|
||||
Object.assign(now, { call: 'X()', mojoOrigin: 'generated-edited', sync: { authority: 'lingo', stale: {}, names: {} }, layout: { bridge: { split: 0.7 } }, t: 9, lang: 'lingo', view: 'flow' });
|
||||
const r = restoreVersion(key, v.id, now);
|
||||
assert.equal(r.sources.lingo, plain.sources.lingo);
|
||||
assert.equal(r.call, plain.call);
|
||||
assert.ok(!('mojoOrigin' in r) && !('sync' in r));
|
||||
assert.deepEqual([r.layout, r.t, r.lang, r.view], [now.layout, 9, 'lingo', 'flow']);
|
||||
});
|
||||
|
||||
test('switching with unsaved edits saves "Before switching" first; switching without edits does not', () => {
|
||||
const st = problem();
|
||||
const s = open(structuredClone(st), 'bridge', { original: st });
|
||||
const keep = s.saveVersion('plain'); assert.ok(keep.ok);
|
||||
assert.equal(s.hasUnsavedEdits(), false, 'the problem as written has nothing to lose');
|
||||
s.setSource('lingo', 'Start with Total at 5.');
|
||||
assert.equal(s.hasUnsavedEdits(), true);
|
||||
const was = s.state.sources.lingo;
|
||||
assert.ok(s.restoreVersion(keep.version.id));
|
||||
const names = s.versions().map((v) => v.name);
|
||||
assert.equal(names.length, 2);
|
||||
assert.ok(names.some((n) => /^Before switching \(/.test(n)), names.join('|'));
|
||||
assert.ok(s.versions().find((v) => v.auto).edits.sources.lingo === was, 'the automatic version holds the work that was replaced');
|
||||
assert.equal(s.state.sources.lingo, st.sources.lingo);
|
||||
// now the work is exactly a saved version: switching again adds nothing
|
||||
assert.equal(s.hasUnsavedEdits(), false);
|
||||
const before = s.versions().length;
|
||||
const other = s.versions().find((v) => v.auto);
|
||||
assert.ok(s.restoreVersion(other.id));
|
||||
assert.equal(s.versions().length, before);
|
||||
});
|
||||
|
||||
test('Reset saves the work first as "Before reset", and does nothing extra when there is nothing to lose', () => {
|
||||
const st = problem();
|
||||
const s = open(structuredClone(st), 'dev', { original: st });
|
||||
assert.ok(s.reset(problem()));
|
||||
assert.deepEqual(s.versions(), []);
|
||||
s.setSource('mojo', s.source('mojo') + '\n# mine');
|
||||
assert.ok(s.reset(problem()));
|
||||
const [v] = s.versions();
|
||||
assert.match(v.name, /^Before reset \(/);
|
||||
assert.ok(v.auto && v.edits.sources.mojo.endsWith('# mine'));
|
||||
assert.ok(!s.source('mojo').includes('# mine'));
|
||||
});
|
||||
|
||||
test('the cap holds: automatic versions make room, and named ones are never dropped to do it', () => {
|
||||
const key = 'pplus.versions.count-base', st = problem();
|
||||
for (let i = 0; i < MAX_VERSIONS; i++) assert.ok(saveVersion(key, `v${i}`, st, 'bridge', { now: 1000 + i, auto: i < 3 }).ok);
|
||||
assert.equal(listVersions(key).length, MAX_VERSIONS);
|
||||
const r = saveVersion(key, 'more', st, 'bridge', { now: 9999 });
|
||||
assert.ok(r.ok);
|
||||
assert.equal(r.dropped.length, 1);
|
||||
assert.equal(r.dropped[0].name, 'v0', 'the oldest automatic one went');
|
||||
assert.equal(listVersions(key).length, MAX_VERSIONS);
|
||||
for (let i = 0; i < 2; i++) saveVersion(key, `x${i}`, st, 'bridge', { now: 10000 + i });
|
||||
assert.equal(listVersions(key).length, MAX_VERSIONS);
|
||||
const full = saveVersion(key, 'no room', st, 'bridge', { now: 20000 });
|
||||
assert.deepEqual(full, { ok: false, reason: 'cap' });
|
||||
assert.equal(listVersions(key).length, MAX_VERSIONS);
|
||||
});
|
||||
|
||||
test('a refused save stops the switch: nothing changes and nothing is lost', () => {
|
||||
const st = problem();
|
||||
const s = open(structuredClone(st), 'bridge', { original: st });
|
||||
const keep = s.saveVersion('plain');
|
||||
for (let i = 0; i < MAX_VERSIONS - 1; i++) saveVersion(s.versionKey(), `n${i}`, st, 'bridge', { now: 5 + i });
|
||||
s.setSource('lingo', 'Start with Total at 6.');
|
||||
assert.equal(s.restoreVersion(keep.version.id), false);
|
||||
assert.equal(s.state.sources.lingo, 'Start with Total at 6.');
|
||||
});
|
||||
|
||||
test('a stale problem: "See the new version" keeps the edits as a version and opens the problem as it is now', () => {
|
||||
const original = problem();
|
||||
const saved = withLingo(original, 'My own start.');
|
||||
saved.base = 'deadbeef'; saved.edited = true; // made against another version of the problem
|
||||
const { state, stale } = resolveSaved(original, saved);
|
||||
assert.equal(stale, true);
|
||||
const s = open(state, 'bridge', { original, stale });
|
||||
assert.equal(s.stale, true);
|
||||
assert.ok(s.seeNewVersion());
|
||||
assert.equal(s.stale, false);
|
||||
assert.equal(s.state.sources.lingo, original.sources.lingo, 'the problem as it is now');
|
||||
const [v] = s.versions();
|
||||
assert.equal(v.name, 'My edits, before the problem changed');
|
||||
assert.ok(!v.auto);
|
||||
assert.equal(v.edits.sources.lingo, 'My own start.');
|
||||
assert.equal(editsFingerprint(s.state), editsFingerprint(original));
|
||||
});
|
||||
|
||||
test('work from a share link has no problem: it gets a workspace id when first saved, and the list is found again by it', async () => {
|
||||
const shared = normalize({ ...problem(), v: 3 }); shared.problem = undefined; shared.title = 'From a link';
|
||||
const blob = await encodeState(shared);
|
||||
const s = open(await decodeState(blob), 'bridge');
|
||||
assert.equal(s.versionKey(), null);
|
||||
assert.deepEqual(s.versions(), []);
|
||||
assert.equal(s.hasUnsavedEdits(), true, 'work with no original has something to save once it has text');
|
||||
const r = s.saveVersion('mine');
|
||||
assert.ok(r.ok);
|
||||
assert.match(s.state.workspace, /^w[0-9a-f]{16}$/);
|
||||
assert.equal(s.versionKey(), `pplus.versions.ws.${s.state.workspace}`);
|
||||
const again = open(await decodeState(await encodeState(s.state)), 'dev');
|
||||
assert.deepEqual(again.versions().map((v) => v.name), ['mine'], 'the same work in another area finds the same versions');
|
||||
});
|
||||
|
||||
test('the same work in each area shares one list', () => {
|
||||
const st = problem();
|
||||
const a = open(structuredClone(st), 'bridge', { original: st }), b = open(structuredClone(st), 'dev', { original: st }), c = open(structuredClone(st), 'hw', { original: st });
|
||||
a.saveVersion('from the Bridge');
|
||||
assert.deepEqual(b.versions().map((v) => [v.name, v.area]), [['from the Bridge', 'bridge']]);
|
||||
assert.equal(c.versions().length, 1);
|
||||
});
|
||||
|
||||
test('a file with versions restores them in a fresh storage, never over a version with the same id', () => {
|
||||
const key = 'pplus.versions.ws.wabc12345678', st = problem();
|
||||
saveVersion(key, 'one', st, 'bridge', { now: 1 }); saveVersion(key, 'two', withLingo(st, 'x'), 'dev', { now: 2 });
|
||||
const file = JSON.parse(JSON.stringify(exportVersions(key)));
|
||||
const fresh = fakeStorage();
|
||||
assert.deepEqual(importVersions(key, file, fresh), { added: 2, skipped: 0 });
|
||||
assert.deepEqual(listVersions(key, fresh).map((v) => v.name), ['two', 'one']);
|
||||
// renamed in the fresh browser; importing the file again must not undo that
|
||||
renameVersion(key, file[0].id, 'renamed here', fresh);
|
||||
assert.deepEqual(importVersions(key, file, fresh), { added: 0, skipped: 2 });
|
||||
assert.equal(listVersions(key, fresh).find((v) => v.id === file[0].id).name, 'renamed here');
|
||||
});
|
||||
|
||||
test('a damaged or hostile version in a file is dropped or cleaned, never trusted', () => {
|
||||
assert.equal(cleanVersion(null), null);
|
||||
assert.equal(cleanVersion({ id: '../x', name: 'n', at: 1, area: 'bridge', edits: {} }), null);
|
||||
assert.equal(cleanVersion({ id: 'ok', name: 'n', at: 1, area: 'nowhere', edits: {} }), null);
|
||||
const v = cleanVersion({ id: 'ok', name: 'n'.repeat(500), at: 1, area: 'bridge', edits: { sources: { pseudo: 'x', evil: 'y' }, layout: { bridge: { split: 0.1 } }, t: 4, mojoOrigin: 'hand-written' } });
|
||||
assert.equal(v.name.length, 120);
|
||||
assert.deepEqual(Object.keys(v.edits), ['sources']);
|
||||
assert.deepEqual(v.edits.sources, { pseudo: 'x' });
|
||||
const key = 'pplus.versions.count-base';
|
||||
assert.deepEqual(importVersions(key, 'nonsense'), { added: 0, skipped: 0 });
|
||||
assert.deepEqual(importVersions(key, [{ id: 1 }]), { added: 0, skipped: 1 });
|
||||
});
|
||||
|
||||
test('the drop-down warns when storage is nearly full', () => {
|
||||
assert.equal(storagePressure(store).nearlyFull, false);
|
||||
store.setItem('big', 'x'.repeat(PRESSURE_CHARS));
|
||||
assert.equal(storagePressure(store).nearlyFull, true);
|
||||
});
|
||||
|
||||
test('a browser that refuses storage still keeps versions for the tab, and a full one says so instead of losing them', () => {
|
||||
const key = 'pplus.versions.count-base', st = problem();
|
||||
assert.ok(saveVersion(key, 'tab only', st, 'bridge', { store: null }).ok);
|
||||
assert.deepEqual(listVersions(key, null).map((v) => v.name), ['tab only']);
|
||||
const full = { getItem: () => null, setItem() { throw new Error('quota'); }, removeItem() { } };
|
||||
assert.deepEqual(saveVersion(key, 'x', st, 'bridge', { store: full }), { ok: false, reason: 'storage' });
|
||||
});
|
||||
|
||||
test('a version is not in the state, a link or the problem\'s own save', async () => {
|
||||
const s = open(problem(), 'bridge');
|
||||
s.saveVersion('v');
|
||||
assert.ok(!/versions?/i.test(JSON.stringify(s.state).replace(/"version"/g, '')));
|
||||
assert.ok(!/"edits"/.test(await encodeState(s.state)));
|
||||
assert.equal(newWorkspaceId().length, 17);
|
||||
assert.equal(currentVersion(s.versionKey(), s.state)?.name, 'v', 'the work is exactly the version just saved');
|
||||
});
|
||||
|
||||
test('a session keeps its own copy of the problem: editing the work never edits "the problem as written"', () => {
|
||||
const st = problem();
|
||||
const s = open(st, 'bridge', { original: st }); // the very same object, as when a problem opens with no save
|
||||
s.setSource('lingo', 'Start with Total at 5.');
|
||||
assert.notEqual(st.sources.lingo, 'Start with Total at 5.' === st.sources.lingo ? '' : 'x');
|
||||
assert.equal(s.hasUnsavedEdits(), true, 'the edit shows against the problem as written');
|
||||
assert.equal(s.state.sources.lingo, 'Start with Total at 5.');
|
||||
});
|
||||
Reference in new issue
Block a user