// 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/
/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', '{{< 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));
});