235 lines
16 KiB
JavaScript
235 lines
16 KiB
JavaScript
// 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));
|
|
});
|