// Chat math (serve/web/math.js + math-adapter.js + the vendored KaTeX), run in Node. // node serve/test_web_math.js (serve/test_web_math.py runs it too and skips when node is missing) // // 1. where a formula starts and ends (prices, code, links, half-written formulas); // 2. the Markdown step: the model's text is escaped, a formula's source only ever reaches the page escaped; // 3. drawing: a stub adapter and a stub DOM (order, cache, stale answers, errors, size limit); // 4. safety: the REAL vendored KaTeX with the adapter's options, fed hostile formulas. "use strict"; const assert = require("node:assert/strict"); const path = require("node:path"); const web = path.join(__dirname, "web"); const math = require(path.join(web, "math.js")); const {split} = math; const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); const unesc = (s) => s.replace(/&(amp|lt|gt|quot|#39);/g, (m, k) => ({amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'"}[k])); const sources = (text) => split(text).filter((p) => p.source !== undefined).map((p) => [p.source, p.display]); const cases = { split_delimiters() { assert.deepEqual(sources("a $x^2$ b"), [["x^2", false]]); assert.deepEqual(sources("a \\(x+1\\) b"), [["x+1", false]]); assert.deepEqual(sources("a $$\\int_0^1 f$$ b"), [["\\int_0^1 f", true]]); assert.deepEqual(sources("a \\[\\sum_i i\\] b"), [["\\sum_i i", true]]); assert.deepEqual(sources("$$\nx = 1\n$$"), [["\nx = 1\n", true]], "display math may span lines"); assert.deepEqual(sources("$a$ and $b$"), [["a", false], ["b", false]]); // the text around a formula is kept whole assert.equal(split("a $x$ b").map((p) => p.raw).join(""), "a $x$ b"); }, split_not_math() { for (const text of ["It costs $5.", "$5 and $10", "from $5 to $10 each", "$ 5 $", "a $ b", "price: $1,000", "cost $5 USD, $6 EUR", "no formula here", "\\$x\\$", "a \\( unfinished", "100$"]) { assert.deepEqual(sources(text), [], text); } assert.deepEqual(sources("`$x$` and ```\n$$y$$\n```"), [], "code is code"); assert.deepEqual(sources("```js\nlet a = '$x$'\n```\n$z$"), [["z", false]], "a closed fence ends"); assert.deepEqual(sources("~~~\n\\(a\\)\n~~~"), [], "tilde fences too"); assert.deepEqual(sources("[x](https://example.com/$a$/b) $c$"), [["c", false]], "a link target is not math"); }, split_streaming() { const parts = split("see $$x^2 + "); assert.equal(parts.length, 2); assert.equal(parts[1].incomplete, true, "a formula still being written is plain text"); assert.equal(parts[1].source, undefined); assert.equal(split("```\n$$never closed").filter((p) => p.source !== undefined).length, 0, "an open fence swallows the rest"); }, markdown_escapes_everything() { const fmt = (t) => `
${esc(t)}
`; const html = math.markdown("hi there $x