rapier-math 2.4.1 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +10 -3
- package/README.md +4 -5
- package/dist/index.mjs +1 -1
- package/dist/markdown-rules.mjs +47 -0
- package/dist/rapier-math.js +875 -321
- package/docs/api.md +6 -2
- package/docs/font-source.md +54 -35
- package/docs/math-components.json +51 -7
- package/docs/math-resources.json +59 -64
- package/package.json +3 -3
- package/src/math/FONT-LICENSE.txt +9 -2
- package/src/math/build-font.py +88 -80
- package/src/math/classic.js +1 -1
- package/src/math/font.js +24 -488
- package/src/math/layout.js +356 -182
- package/src/math/mathml.js +79 -14
- package/src/math/package-layout.mjs +1 -0
- package/src/math/package-readme.mjs +3 -4
- package/src/math/parser.js +398 -82
- package/src/tools/build-math.mjs +22 -7
- package/tests/adoption.mjs +0 -252
- package/tests/check.mjs +0 -134
- package/tests/semantics.mjs +0 -340
- package/tests/typeset.mjs +0 -172
- package/tests/verify.mjs +0 -49
package/src/tools/build-math.mjs
CHANGED
|
@@ -12,10 +12,10 @@ import {mathModules, mathClassicSource} from '../math/package-build.mjs';
|
|
|
12
12
|
import {mathReadme} from '../math/package-readme.mjs';
|
|
13
13
|
|
|
14
14
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
15
|
-
export const MATH_VERSION = '2.
|
|
15
|
+
export const MATH_VERSION = '2.7.0';
|
|
16
16
|
export const MATH_BUNDLE = 'rapier-math-' + MATH_VERSION + '.js';
|
|
17
17
|
export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'source.js', 'variants.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'api.js', 'browser.js', 'mathml.js', 'semantic-api.js', 'combined.js', 'classic.js'].map(name => 'math/' + name);
|
|
18
|
-
export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs', 'math/typeset-verify.mjs'];
|
|
18
|
+
export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/CHANGELOG.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs', 'math/typeset-verify.mjs'];
|
|
19
19
|
export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'reuse.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
|
|
20
20
|
'accessible.mjs', 'accessible.css', 'mathml.d.ts', 'combined.d.ts', 'accessible.d.ts',
|
|
21
21
|
'index.d.ts', 'classic.d.ts', 'delimiters.d.ts', 'integration.d.ts', 'markdown-it.d.ts', 'rehype.d.ts', 'stream.d.ts',
|
|
@@ -30,13 +30,27 @@ const FONT = {
|
|
|
30
30
|
copyright: 'Copyright 2012--2014 for Latin Modern Math OTF by B. Jackowski, P. Strzelczyk and P. Pianowski (on behalf of TeX users groups). This work is released under the GUST Font License -- see http://tug.org/fonts/licenses/GUST-FONT-LICENSE.txt for details.',
|
|
31
31
|
licenseSource: 'https://mirror.apps.cam.ac.uk/pub/tex-archive/fonts/lm-math/doc/GUST-FONT-LICENSE.txt',
|
|
32
32
|
licenseFile: 'math/FONT-LICENSE.txt',
|
|
33
|
-
licenseSha256: '
|
|
33
|
+
licenseSha256: 'fb1f153e363d003180781b4a043f34ab76d17f1c338de9229c40149b52cfdf2f',
|
|
34
|
+
};
|
|
35
|
+
const MONO = {
|
|
36
|
+
name: 'Latin Modern Mono', version: '2.004', license: FONT.license,
|
|
37
|
+
source: 'https://ftp.riken.jp/CTAN/fonts/lm/fonts/opentype/public/lm/lmmono10-regular.otf',
|
|
38
|
+
sha256: '22deb6d3be3ffcb40b33f0e010afb256c677d97c2a2bdee1f5740cdc97751558',
|
|
39
|
+
copyright: 'Copyright 2003, 2009 B. Jackowski and J. M. Nowacki (on behalf of TeX users groups). This work is released under the GUST Font License -- see http://tug.org/fonts/licenses/GUST-FONT-LICENSE.txt for details.',
|
|
40
|
+
note: 'Monospace text outlines and advances; complete license in math-font-LICENSE.txt',
|
|
41
|
+
};
|
|
42
|
+
const HOOK = {
|
|
43
|
+
name: 'Latin Modern Math Italic10 Regular', version: '2.003', license: FONT.license,
|
|
44
|
+
source: 'https://ftp.riken.jp/CTAN/fonts/lm/fonts/type1/public/lm/lmmi10.pfb',
|
|
45
|
+
sha256: 'c24662506b402f3e0033cc75eb746eb490a1b7477e6b3ef52053f5025ec0fc57',
|
|
46
|
+
copyright: 'Copyright 2003--2009 by B. Jackowski and J.M. Nowacki (on behalf of TeX USERS GROUPS).',
|
|
47
|
+
note: 'Small arrow hook outline; the composer supplies its advance; complete license in math-font-LICENSE.txt',
|
|
34
48
|
};
|
|
35
49
|
const digest = (bytes, algorithm = 'sha256', encoding = 'hex') => createHash(algorithm).update(bytes).digest(encoding);
|
|
36
50
|
|
|
37
51
|
async function fontLicense(root, packageLayout = false) {
|
|
38
52
|
const bytes = await readFile(resolve(root, packageLayout ? mathPackagePath(FONT.licenseFile) : FONT.licenseFile));
|
|
39
|
-
if (digest(bytes) !== FONT.licenseSha256 || !bytes.includes(FONT.copyright))
|
|
53
|
+
if (digest(bytes) !== FONT.licenseSha256 || !bytes.includes(FONT.copyright) || !bytes.includes(MONO.copyright) || !bytes.includes(HOOK.copyright))
|
|
40
54
|
throw new Error('The math font license differs from its source pin');
|
|
41
55
|
return bytes;
|
|
42
56
|
}
|
|
@@ -56,9 +70,10 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
|
|
|
56
70
|
inputs.push({file, bytes, text: bytes.toString('utf8')});
|
|
57
71
|
}
|
|
58
72
|
const license = await fontLicense(root, packageLayout);
|
|
59
|
-
if (!inputs[0].text.includes(
|
|
73
|
+
if (!inputs[0].text.includes(FONT.copyright) || !inputs[0].text.includes('Complete license: FONT-LICENSE.txt')) throw new Error('The embedded math font is missing its notice');
|
|
74
|
+
// The single-file bundle travels alone, so it carries both complete licenses itself.
|
|
60
75
|
const ownLicense = (await read('math/LICENSE-MIT')).toString('utf8');
|
|
61
|
-
const bytes = Buffer.from('/*!\n' + ownLicense.trim() + '\n*/\n(function(){\n\'use strict\';\n' + inputs.map(input => mathClassicSource(input.text)).join('\n\n') + '\n})();\n');
|
|
76
|
+
const bytes = Buffer.from('/*!\n' + ownLicense.trim() + '\n*/\n/*!\n' + license.toString('utf8').trim() + '\n*/\n(function(){\n\'use strict\';\n' + inputs.map(input => mathClassicSource(input.text)).join('\n\n') + '\n})();\n');
|
|
62
77
|
new Script(bytes.toString('utf8'), {filename: MATH_BUNDLE});
|
|
63
78
|
const gzipBytes = gzipSync(bytes, {level: 9}).length;
|
|
64
79
|
if (gzipBytes >= 500_000) throw new Error('The math plugin exceeds its 500 KB gzip budget: ' + gzipBytes);
|
|
@@ -73,7 +88,7 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
|
|
|
73
88
|
bytes: bytes.length, gzipBytes, sha256, sha384,
|
|
74
89
|
sources: inputs.map(input => ({file: input.file, packageFile: mathPackagePath(input.file), bytes: input.bytes.length, sha256: digest(input.bytes)})),
|
|
75
90
|
recipe,
|
|
76
|
-
components: [{name: FONT.name, version: FONT.version, license: FONT.license, source: FONT.source, sha256: FONT.sourceSha256}],
|
|
91
|
+
components: [{name: FONT.name, version: FONT.version, license: FONT.license, source: FONT.source, sha256: FONT.sourceSha256, copyright: FONT.copyright}, MONO, HOOK],
|
|
77
92
|
font: {...FONT, licenseBytes: license.length},
|
|
78
93
|
};
|
|
79
94
|
resources.adoption = [];
|
package/tests/adoption.mjs
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Optional host checks: run from the installed package with the example peers.
|
|
3
|
-
// One source-custody table; no appearance or timing assertions.
|
|
4
|
-
import assert from 'node:assert/strict';
|
|
5
|
-
import MarkdownIt from 'markdown-it';
|
|
6
|
-
import {render} from 'rapier-math';
|
|
7
|
-
import rapierMath from 'rapier-math/markdown-it';
|
|
8
|
-
import rehypeMath from 'rapier-math/rehype';
|
|
9
|
-
import {createMathMatcher} from 'rapier-math/delimiters';
|
|
10
|
-
import {createMarkdownStream, createMathSession} from 'rapier-math/stream';
|
|
11
|
-
import {processor} from '../examples/unified.mjs';
|
|
12
|
-
|
|
13
|
-
const md = new MarkdownIt({html: false}).use(rapierMath);
|
|
14
|
-
const dollar = new MarkdownIt({html: false}).use(rapierMath, {singleDollar: true});
|
|
15
|
-
const mathNodes = (host, source) => host.parse(source, {}).flatMap(token => token.children || [token])
|
|
16
|
-
.filter(token => token.type === 'math_inline' || token.type === 'math_block');
|
|
17
|
-
const rows = [
|
|
18
|
-
['escaped pair incomplete', String.raw`$$x\$$`, 0],
|
|
19
|
-
['escaped pair then closer', String.raw`$$x\$$y$$`, 1],
|
|
20
|
-
['even escape run', String.raw`$$x\\$$`, 1],
|
|
21
|
-
['brackets', String.raw`A \(x+1\) B \[y\]`, 2],
|
|
22
|
-
['escaped bracket opener', String.raw`A \\(x\\)`, 0],
|
|
23
|
-
['currency', 'It costs $5 and $10.', 0],
|
|
24
|
-
['code and fence', '`$$x$$`\n\n```tex\n$$y$$\n```\n\n $$z$$\n', 0],
|
|
25
|
-
['links', String.raw`[\(x\)](https://example.com/$$x$$)`, 0],
|
|
26
|
-
['literal backslashes', String.raw`Path C:\\temp. \(\text{a\ b}\)`, 1],
|
|
27
|
-
['CRLF BOM Unicode', '\ufeffπ 🐈\r\n\r\n$$\r\nx+1\r\n$$\r\n', 1],
|
|
28
|
-
['incomplete', 'Before \\(x+1 and after', 0],
|
|
29
|
-
['malformed UTF-16', '\ud800 and \\(x\\) and \udfff', 1],
|
|
30
|
-
];
|
|
31
|
-
for (const [name, source, count] of rows) {
|
|
32
|
-
assert.equal(mathNodes(md, source).length, count, name);
|
|
33
|
-
const batch = md.render(source, {});
|
|
34
|
-
// Every two-piece boundary, including CRLF, escape runs and surrogate pairs.
|
|
35
|
-
for (let split = 0; split <= source.length; split++) {
|
|
36
|
-
const stream = createMarkdownStream((text, mathSession) => md.render(text, {rapierMathSession: mathSession}), {previewEvery: 8});
|
|
37
|
-
stream.write(source.slice(0, split)); stream.write(source.slice(split));
|
|
38
|
-
const final = stream.finish();
|
|
39
|
-
assert.equal(final.source, source, name + ': exact transport source');
|
|
40
|
-
assert.equal(final.html, batch, name + ': final batch agreement');
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
for (const [source, count] of [[String.raw`$x\$y$`, 1], ['$x$5', 0], ['$ x$', 0], ['$x $', 0], ['$$$x$$$', 0]])
|
|
44
|
-
assert.equal(mathNodes(dollar, source).length, count);
|
|
45
|
-
// Image descriptions are text-only host output: unknown math token types must
|
|
46
|
-
// not disappear from alt text or spend a formula-render budget.
|
|
47
|
-
for (const [source, alt] of [
|
|
48
|
-
[String.raw``, 'before $$x$$ after'],
|
|
49
|
-
[String.raw``, String.raw`before \(x\) after`],
|
|
50
|
-
[String.raw` c](outer.png)`, 'a b $$x$$ c'],
|
|
51
|
-
[String.raw``, 'a $$\\text{<>&"}$$ b'],
|
|
52
|
-
]) {
|
|
53
|
-
const host = new MarkdownIt({html: false}).use(rapierMath, {maxFormulas: 1});
|
|
54
|
-
const tokens = host.parse(source + String.raw` \(y\)`, {});
|
|
55
|
-
for (let pass = 0; pass < 2; pass++) {
|
|
56
|
-
const env = {}, html = host.renderer.render(tokens, host.options, env);
|
|
57
|
-
assert(html.includes('alt="' + alt + '"'), 'image math remains literal source');
|
|
58
|
-
assert.equal((html.match(/<svg /g) || []).length, 1, 'alt text does not spend the formula budget');
|
|
59
|
-
assert.equal(env.rapierMathErrors, undefined);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
const exact = '\ufeff$$\r\n α+\\text{a\\ b} 🐈\r\n$$';
|
|
63
|
-
const span = createMathMatcher(exact)(1);
|
|
64
|
-
assert.equal(exact.slice(span.bodyStart, span.bodyEnd), '\r\n α+\\text{a\\ b} 🐈\r\n');
|
|
65
|
-
assert.equal(createMathMatcher(String.raw`$$x\$$`)(0), null);
|
|
66
|
-
|
|
67
|
-
let first = createMarkdownStream(text => text, {maxSourceLength: 8, previewEvery: 2});
|
|
68
|
-
const second = createMarkdownStream(text => text);
|
|
69
|
-
first.write('ab'); second.write('other'); first.abort(); first.abort();
|
|
70
|
-
assert.throws(() => first.write('c'));
|
|
71
|
-
const replaced = first;
|
|
72
|
-
first = first.reset(); first.write('new');
|
|
73
|
-
assert.throws(() => replaced.write('stale'), 'a replaced producer cannot write into the new message');
|
|
74
|
-
assert.throws(() => first.write('123456'), {code: 'resource-limit'});
|
|
75
|
-
assert.equal(first.finish().source, 'new');
|
|
76
|
-
assert.equal(second.finish().source, 'other');
|
|
77
|
-
assert.throws(() => second.finish());
|
|
78
|
-
let failingHost = true, supplied = 0;
|
|
79
|
-
const failing = createMarkdownStream(text => {
|
|
80
|
-
supplied += text.length;
|
|
81
|
-
if (failingHost) throw new Error('host failed');
|
|
82
|
-
return text;
|
|
83
|
-
}, {previewEvery: 2});
|
|
84
|
-
const failedSource = 'x'.repeat(32);
|
|
85
|
-
for (const chunk of failedSource) {
|
|
86
|
-
try { failing.write(chunk); } catch (error) { assert.equal(error.message, 'host failed'); }
|
|
87
|
-
}
|
|
88
|
-
failingHost = false;
|
|
89
|
-
assert.equal(failing.finish().source, failedSource, 'failed previews retain every accepted chunk');
|
|
90
|
-
assert(supplied < 3 * failedSource.length, 'failed previews keep the repeated-work bound');
|
|
91
|
-
failing.abort(); failing.reset().abort();
|
|
92
|
-
|
|
93
|
-
const hostile = String.raw`Before \(\text{</title><script>alert(1)</script>}\). <img src=x onerror=alert(1)>`;
|
|
94
|
-
assert(!/<script|<img/i.test(md.render(hostile, {})));
|
|
95
|
-
// Cached syntax can serve multiple outputs. Budgets belong to each render, not
|
|
96
|
-
// to parsing or to an env object; every paragraph still shares one document cap.
|
|
97
|
-
const formulaSource = String.raw`\(x\)`, svgCount = html => (html.match(/<svg /g) || []).length;
|
|
98
|
-
for (const budgets of [{maxFormulas: 1}, {maxOutputLength: render('x').svg.length}]) {
|
|
99
|
-
const host = new MarkdownIt({html: false}).use(rapierMath, budgets);
|
|
100
|
-
const mathSession = createMathSession(), env = {rapierMathSession: mathSession};
|
|
101
|
-
for (const inline of [false, true]) {
|
|
102
|
-
const source = formulaSource + (inline ? ' ' : '\n\n') + formulaSource;
|
|
103
|
-
const tree = host.parse(source, {});
|
|
104
|
-
const tokens = inline ? tree[1].children : tree;
|
|
105
|
-
const renderer = inline ? host.renderer.renderInline : host.renderer.render;
|
|
106
|
-
for (let pass = 0; pass < 2; pass++) {
|
|
107
|
-
delete env.rapierMathErrors;
|
|
108
|
-
const out = renderer.call(host.renderer, tokens, host.options, env);
|
|
109
|
-
assert.equal(svgCount(out), 1);
|
|
110
|
-
assert.equal(env.rapierMathErrors.length, 1);
|
|
111
|
-
assert.equal(env.rapierMathErrors[0].errors[0].code, 'resource-limit');
|
|
112
|
-
assert(out.includes(formulaSource));
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
assert.equal(mathSession.stats.evaluations, 1, 'admitted cache hits still spend the fresh document budget');
|
|
116
|
-
mathSession.dispose();
|
|
117
|
-
}
|
|
118
|
-
const nestedHost = new MarkdownIt({html: false}).use(rapierMath, {maxFormulas: 1});
|
|
119
|
-
const nestedTree = nestedHost.parse(formulaSource + ' fail', {});
|
|
120
|
-
const textRule = nestedHost.renderer.rules.text;
|
|
121
|
-
nestedHost.renderer.rules.text = (tokens, index, opts, env, self) => {
|
|
122
|
-
if (tokens[index].content === ' fail') throw new Error('host render failed');
|
|
123
|
-
if (tokens[index].content.includes('nested')) {
|
|
124
|
-
for (const inline of [false, true]) {
|
|
125
|
-
const nestedEnv = {rapierMathSession: env.rapierMathSession};
|
|
126
|
-
assert.throws(() => inline
|
|
127
|
-
? self.renderInline(nestedTree[1].children, opts, nestedEnv)
|
|
128
|
-
: self.render(nestedTree, opts, nestedEnv), /host render failed/);
|
|
129
|
-
assert.equal(nestedEnv.rapierMathErrors, undefined, 'nested render has its own budget');
|
|
130
|
-
assert.equal(env.rapierMathSession.stats.entries, 0, 'a failed nested render clears retained artifacts');
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return textRule(tokens, index, opts, env, self);
|
|
134
|
-
};
|
|
135
|
-
const outerTree = nestedHost.parse(formulaSource + ' nested ' + formulaSource, {});
|
|
136
|
-
const nestedSession = createMathSession();
|
|
137
|
-
// A custom host can run the same renderer twice; a failed nested render must
|
|
138
|
-
// restore the outer cap and leave subsequent root renders fresh.
|
|
139
|
-
for (let pass = 0; pass < 2; pass++) {
|
|
140
|
-
const env = {rapierMathSession: nestedSession}, out = nestedHost.renderer.render(outerTree, nestedHost.options, env);
|
|
141
|
-
assert.equal(svgCount(out), 1);
|
|
142
|
-
assert.equal(env.rapierMathErrors.length, 1);
|
|
143
|
-
assert.equal(env.rapierMathErrors[0].errors[0].code, 'resource-limit');
|
|
144
|
-
}
|
|
145
|
-
nestedSession.dispose();
|
|
146
|
-
// Reentering an already parsed inline tree is still an independent render, even
|
|
147
|
-
// when its array is already known to the active outer document.
|
|
148
|
-
const reentrant = new MarkdownIt({html: false}).use(rapierMath, {maxFormulas: 1});
|
|
149
|
-
const reentrantTree = reentrant.parse(formulaSource + ' nested ' + formulaSource + '\n\n' + formulaSource, {});
|
|
150
|
-
const reentrantText = reentrant.renderer.rules.text, reentrantSession = createMathSession();
|
|
151
|
-
reentrant.renderer.rules.text = (tokens, index, opts, env, self) => {
|
|
152
|
-
if (!env.nested && tokens[index].content.includes('nested')) {
|
|
153
|
-
for (const children of [tokens, reentrantTree[4].children]) {
|
|
154
|
-
const nestedEnv = {nested: true, rapierMathSession: reentrantSession};
|
|
155
|
-
assert.equal(svgCount(self.renderInline(children, opts, nestedEnv)), 1, 'reentrant same/sibling tree gets a fresh cap');
|
|
156
|
-
}
|
|
157
|
-
assert.equal(svgCount(reentrant.renderInline(formulaSource, {nested: true, rapierMathSession: reentrantSession})), 1);
|
|
158
|
-
}
|
|
159
|
-
return reentrantText(tokens, index, opts, env, self);
|
|
160
|
-
};
|
|
161
|
-
const reentrantEnv = {rapierMathSession: reentrantSession};
|
|
162
|
-
assert.equal(svgCount(reentrant.renderer.render(reentrantTree, reentrant.options, reentrantEnv)), 1);
|
|
163
|
-
assert.equal(reentrantEnv.rapierMathErrors.length, 2, 'the outer document still spends one shared cap');
|
|
164
|
-
reentrantSession.dispose();
|
|
165
|
-
const tiny = new MarkdownIt({html: false}).use(rapierMath, {maxOutputLength: 1});
|
|
166
|
-
assert(!tiny.render(String.raw`\(x\)`).includes('<svg'));
|
|
167
|
-
const bad = {}, fallback = md.render(String.raw`Good \(x\). Bad \(\unknown{x}\).`, bad);
|
|
168
|
-
assert.equal(bad.rapierMathErrors[0].errors[0].code, 'unsupported-command');
|
|
169
|
-
assert(fallback.includes('\\unknown{x}'));
|
|
170
|
-
|
|
171
|
-
const unified = await processor.process('Code `$$x$$`. Math $$x+1$$.\n\n<script>alert(1)</script>\n\n$$\\unknown{x}$$');
|
|
172
|
-
assert.equal((String(unified).match(/<svg /g) || []).length, 1);
|
|
173
|
-
assert(!String(unified).includes('<script'));
|
|
174
|
-
assert.equal(unified.messages[0].ruleId, 'unsupported-command');
|
|
175
|
-
assert(String(unified).includes('\\unknown{x}'));
|
|
176
|
-
const unifiedSession = createMathSession();
|
|
177
|
-
for (let pass = 0; pass < 2; pass++) {
|
|
178
|
-
const file = processor.processSync({value: 'Formula $$x$$. Repeated $$x$$.', data: {rapierMathSession: unifiedSession}});
|
|
179
|
-
assert.equal(svgCount(String(file)), 2);
|
|
180
|
-
assert.equal(file.messages.length, 0);
|
|
181
|
-
}
|
|
182
|
-
assert.equal(unifiedSession.stats.evaluations, 1, 'rehype explicitly reuses formula work across fresh trees');
|
|
183
|
-
unifiedSession.dispose();
|
|
184
|
-
// Setup is part of the same failure lifetime as rendering. Invalid budgets may
|
|
185
|
-
// arrive between previews; neither adapter may leave the old message artifacts.
|
|
186
|
-
const setupOptions = {maxFormulas: 1}, setupHost = new MarkdownIt().use(rapierMath, setupOptions);
|
|
187
|
-
const setupTransform = rehypeMath(setupOptions);
|
|
188
|
-
for (const adapter of ['markdown-it', 'rehype']) {
|
|
189
|
-
const session = createMathSession();
|
|
190
|
-
setupHost.render(formulaSource, {rapierMathSession: session});
|
|
191
|
-
assert.equal(session.stats.entries, 1);
|
|
192
|
-
setupOptions.maxFormulas = -1;
|
|
193
|
-
assert.throws(() => adapter === 'markdown-it'
|
|
194
|
-
? setupHost.render(formulaSource, {rapierMathSession: session})
|
|
195
|
-
: setupTransform({type: 'root', children: []}, {data: {rapierMathSession: session}}), RangeError);
|
|
196
|
-
assert.equal(session.stats.entries, 0, adapter + ': failed setup clears retained artifacts');
|
|
197
|
-
assert.equal(session.stats.retainedBytes, 0);
|
|
198
|
-
setupOptions.maxFormulas = 1;
|
|
199
|
-
session.dispose();
|
|
200
|
-
}
|
|
201
|
-
// Without a reuse session, ordinary options retain per-occurrence observation.
|
|
202
|
-
// An explicit session intentionally snapshots stable options at the root.
|
|
203
|
-
const changingOptions = {renderOptions: {maxWidth: 1}}, changingHost = new MarkdownIt().use(rapierMath, changingOptions);
|
|
204
|
-
const changingText = changingHost.renderer.rules.text;
|
|
205
|
-
changingHost.renderer.rules.text = (tokens, index, opts, env, self) => {
|
|
206
|
-
changingOptions.renderOptions.maxWidth = 5;
|
|
207
|
-
return changingText(tokens, index, opts, env, self);
|
|
208
|
-
};
|
|
209
|
-
const changingFormula = 'x+x+x+x+x+x', changingSource = '\\(' + changingFormula + '\\) then \\(' + changingFormula + '\\)';
|
|
210
|
-
const narrow = render(changingFormula, {maxWidth: 1}).svg, wide = render(changingFormula, {maxWidth: 5}).svg;
|
|
211
|
-
assert.equal(changingHost.render(changingSource), '<p>' + narrow + ' then ' + wide + '</p>\n');
|
|
212
|
-
changingOptions.renderOptions.maxWidth = 1;
|
|
213
|
-
const changingSession = createMathSession();
|
|
214
|
-
assert.equal(changingHost.render(changingSource, {rapierMathSession: changingSession}), '<p>' + narrow + ' then ' + narrow + '</p>\n');
|
|
215
|
-
changingSession.dispose();
|
|
216
|
-
// A host may throw a non-Error value while options are read. Normalize it before
|
|
217
|
-
// adapter serialization, including falsy message/command values and non-string codes.
|
|
218
|
-
for (const accessible of [false, true]) for (const cached of [false, true]) {
|
|
219
|
-
const mathSession = cached ? createMathSession() : undefined;
|
|
220
|
-
const host = new MarkdownIt().use(rapierMath, {accessible,
|
|
221
|
-
renderOptions: {get maxWidth() { throw {code: 7, message: '', command: 0}; }}});
|
|
222
|
-
const env = {rapierMathSession: mathSession};
|
|
223
|
-
const html = host.render(String.raw`\(x\)`, env);
|
|
224
|
-
assert(html.includes('data-math-error="invalid-tex"'));
|
|
225
|
-
assert.deepEqual(env.rapierMathErrors[0].errors, [{code: 'invalid-tex', message: '', offset: 0, command: '0'}]);
|
|
226
|
-
mathSession?.dispose();
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
// MathML can leave a containing link unnamed even though its nested structure
|
|
231
|
-
// remains accessible. Give only the new composed route a destination fallback;
|
|
232
|
-
// retain authored names and leave ordinary SVG and rejected insertions unchanged.
|
|
233
|
-
const linkedCode = source => ({type: 'element', tagName: 'code', properties: {className: ['language-math', 'math-inline']}, children: [{type: 'text', value: source}]});
|
|
234
|
-
for (const accessible of [false, true]) for (const authored of [{}, {title: 'Open the derivation'}, {ariaLabel: 'Read proof'}, {ariaLabelledBy: ['purpose']}]) {
|
|
235
|
-
const properties = {href: 'https://example.test/proof?a=1&b=2', ...authored};
|
|
236
|
-
const link = {type: 'element', tagName: 'a', properties, children: [{type: 'element', tagName: 'strong', properties: {}, children: [linkedCode(String.raw`\frac{x}{y}`)]}]};
|
|
237
|
-
rehypeMath({accessible})({type: 'root', children: [link]});
|
|
238
|
-
const expected = accessible && Object.keys(authored).length === 0 ? {...properties, title: properties.href} : {href: properties.href, ...authored};
|
|
239
|
-
assert.deepEqual(link.properties, expected, 'host-owned accessible names remain authoritative');
|
|
240
|
-
const tags = [], walk = node => { if (node.tagName) tags.push(node.tagName); for (const child of node.children || []) walk(child); }; walk(link);
|
|
241
|
-
assert.equal(tags.filter(tag => tag === 'svg').length, 1, 'destination fallback preserves visual SVG');
|
|
242
|
-
assert.equal(tags.filter(tag => tag === 'math').length, accessible ? 1 : 0, 'destination fallback preserves native MathML');
|
|
243
|
-
}
|
|
244
|
-
for (const source of [String.raw`\unsupported{x}`, String.raw`\href{https://example.test/inner}{x}`]) {
|
|
245
|
-
const link = {type: 'element', tagName: 'a', properties: {href: 'https://example.test/outer'}, children: [linkedCode(source)]};
|
|
246
|
-
rehypeMath({accessible: true})({type: 'root', children: [link]});
|
|
247
|
-
assert.equal(link.properties.title, undefined, 'rejected insertion does not mutate the host link');
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
console.log(JSON.stringify({sourceCustodyRows: rows.length, splitAgreement: 'all two-piece boundaries',
|
|
251
|
-
lifetimes: 'abort, replacement handles, rejection, interleaved messages, explicit bounded reuse', adapters: 'markdown-it and sanitized unified',
|
|
252
|
-
security: 'hostile source stays inert; document math budgets fall back'}));
|
package/tests/check.mjs
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Package entry, exact authored text and hostile-content boundaries; no appearance assertions.
|
|
3
|
-
import assert from 'node:assert/strict';
|
|
4
|
-
import {readFile} from 'node:fs/promises';
|
|
5
|
-
import {Script, createContext} from 'node:vm';
|
|
6
|
-
import {assembleMath} from '../src/tools/build-math.mjs';
|
|
7
|
-
import {fileURLToPath} from 'node:url';
|
|
8
|
-
|
|
9
|
-
const read = path => readFile(new URL('../' + path, import.meta.url), 'utf8');
|
|
10
|
-
const pkg = JSON.parse(await read('./package.json'));
|
|
11
|
-
const resources = JSON.parse(await read('./docs/math-resources.json'));
|
|
12
|
-
const classicSource = await read('./' + resources.packageBundle);
|
|
13
|
-
assert.equal(pkg.name, 'rapier-math');
|
|
14
|
-
assert.equal(pkg.version, resources.version);
|
|
15
|
-
assert.equal(pkg.type, 'module');
|
|
16
|
-
assert.equal(pkg.license, 'SEE LICENSE IN LICENSE');
|
|
17
|
-
assert.equal(Object.keys(pkg.dependencies || {}).length, 0);
|
|
18
|
-
assert.equal(Object.keys(pkg.scripts || {}).length, 0);
|
|
19
|
-
const rebuilt = await assembleMath({root: fileURLToPath(new URL('..', import.meta.url)), packageLayout: true});
|
|
20
|
-
for (const [file, content] of rebuilt.modules) assert.equal(await read(file), content, 'exact native module: ' + file);
|
|
21
|
-
const rendererLicense = await read('./src/math/LICENSE-MIT'), fontLicense = await read('./src/math/FONT-LICENSE.txt');
|
|
22
|
-
for (const name of ['./LICENSE', './src/math/font.js', './' + resources.packageBundle]) {
|
|
23
|
-
const text = await read(name);
|
|
24
|
-
if (!name.endsWith('font.js')) assert(text.includes(rendererLicense.trim()), name + ': renderer license');
|
|
25
|
-
assert(text.includes(fontLicense.trim()), name + ': complete font license');
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Initialize Node's lazy Web API globals before observing module purity. This
|
|
29
|
-
// allocates a local Response only; no network request or renderer evaluation.
|
|
30
|
-
new Response();
|
|
31
|
-
const globals = Object.getOwnPropertyDescriptors(globalThis);
|
|
32
|
-
const stream = await import('rapier-math/stream');
|
|
33
|
-
assert.deepEqual(Object.keys(stream).sort(), ['createMarkdownStream', 'createMathSession']);
|
|
34
|
-
assert.equal(Object.hasOwn(pkg.exports, './reuse'), false, 'reuse is an internal package helper');
|
|
35
|
-
const session = stream.createMathSession();
|
|
36
|
-
assert(Object.isFrozen(session), 'message session handle is immutable');
|
|
37
|
-
session.clear(); session.dispose();
|
|
38
|
-
assert.equal(typeof (await import('../dist/integration.mjs')).createFormulaRenderer, 'function', 'internal adapter import closure');
|
|
39
|
-
const module = await import('../dist/index.mjs');
|
|
40
|
-
const semantic = await import('rapier-math/mathml'), combined = await import('rapier-math/combined');
|
|
41
|
-
assert.deepEqual(Object.keys(semantic).sort(), ['parse', 'toMathML']);
|
|
42
|
-
assert.deepEqual(Object.keys(combined), ['renderWithMathML']);
|
|
43
|
-
assert.equal(typeof (await import('rapier-math/accessible')).renderAccessible, 'function');
|
|
44
|
-
assert.equal(pkg.exports['./accessible.css'], './dist/accessible.css');
|
|
45
|
-
assert(pkg.sideEffects.includes('./dist/accessible.css'));
|
|
46
|
-
const afterImport = Object.getOwnPropertyDescriptors(globalThis);
|
|
47
|
-
assert.deepEqual(Reflect.ownKeys(afterImport), Reflect.ownKeys(globals), 'module adds no globals');
|
|
48
|
-
for (const key of Reflect.ownKeys(globals)) for (const field of Object.keys(globals[key]))
|
|
49
|
-
assert(Object.is(afterImport[key][field], globals[key][field]), 'module preserves global ' + String(key));
|
|
50
|
-
assert.deepEqual(Object.keys(module).sort(), ['default', 'fit', 'observe', 'parse', 'render', 'renderToString', 'version']);
|
|
51
|
-
for (const name of Object.keys(module.default)) assert.equal(module[name], module.default[name], 'named/default export ' + name);
|
|
52
|
-
assert.equal(module.version, resources.version);
|
|
53
|
-
assert(Object.isFrozen(module.default));
|
|
54
|
-
|
|
55
|
-
const context = createContext({atob, URL});
|
|
56
|
-
new Script(classicSource, {filename: resources.bundle}).runInContext(context);
|
|
57
|
-
const classic = context.RapierMath;
|
|
58
|
-
assert.equal(classic.version, pkg.version, 'classic/package release identity');
|
|
59
|
-
const plain = value => JSON.parse(JSON.stringify(value));
|
|
60
|
-
const unescape = text => text.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (_, entity) =>
|
|
61
|
-
entity[0] === '#' ? String.fromCodePoint(entity[1] === 'x' ? parseInt(entity.slice(2), 16) : Number(entity.slice(1))) :
|
|
62
|
-
({amp: '&', lt: '<', gt: '>', quot: '"', apos: "'"})[entity]);
|
|
63
|
-
function sourceAlternative(result, source) {
|
|
64
|
-
const label = /\baria-label="([^"]*)"/.exec(result.svg)?.[1];
|
|
65
|
-
const title = /<title>([^<]*)<\/title>/.exec(result.svg)?.[1];
|
|
66
|
-
const utf16 = /\bdata-tex-utf16="([0-9a-f]+)"/.exec(result.svg)?.[1];
|
|
67
|
-
if (utf16) assert.equal(utf16.match(/.{4}/g).map(part => String.fromCharCode(parseInt(part, 16))).join(''), source, 'exact UTF-16 alternative');
|
|
68
|
-
else { assert.equal(unescape(label), source, 'exact aria alternative'); assert.equal(unescape(title), source, 'exact title alternative'); }
|
|
69
|
-
}
|
|
70
|
-
function inert(svg) {
|
|
71
|
-
assert(!/<\s*(?:script|foreignObject|iframe|object|embed|image|style|animate|set)\b/i.test(svg), 'no executable or remote SVG element');
|
|
72
|
-
for (const tag of svg.match(/<[^>]+>/g) || []) {
|
|
73
|
-
const attributes = [...tag.matchAll(/\s([^\s=]+)="([^"]*)"/g)];
|
|
74
|
-
for (const [, name, value] of attributes) {
|
|
75
|
-
assert(!/^on/i.test(name), 'no event attribute');
|
|
76
|
-
if (/^(?:href|xlink:href)$/i.test(name)) assert(/^https?:\/\//i.test(unescape(value)), 'only HTTP(S) links');
|
|
77
|
-
if (!/^(?:aria-label|data-tex-utf16)$/.test(name)) assert(!/url\s*\(|javascript:|vbscript:/i.test(unescape(value)), 'no executable attribute');
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const examples = [
|
|
83
|
-
[String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`, {displayMode: true}],
|
|
84
|
-
[String.raw`\begin{aligned}a&=b+c\\d&=e+f\end{aligned}`, {displayMode: true, maxWidth: 4}],
|
|
85
|
-
[String.raw`\newcommand{\squareof}[1]{#1^2}\squareof{x}`, {screen: {fontSize: 16, pixelRatio: 2, dark: false}}],
|
|
86
|
-
[String.raw`\text{A < B & "C" 'D'} + α`, {}],
|
|
87
|
-
[String.raw`\href{https://example.com/?a=1&b=2}{x}`, {}],
|
|
88
|
-
[String.raw`\unsupported{content}`, {}],
|
|
89
|
-
['x\u0000y\ud800z\udfff', {}],
|
|
90
|
-
];
|
|
91
|
-
for (const [source, options] of examples) {
|
|
92
|
-
const result = module.render(source, options);
|
|
93
|
-
assert.deepEqual(plain(result), plain(classic.render(source, options)), 'module/classic result');
|
|
94
|
-
assert.equal(module.renderToString(source, options), result.svg, 'string export agrees with render');
|
|
95
|
-
sourceAlternative(result, source); inert(result.svg);
|
|
96
|
-
}
|
|
97
|
-
assert.deepEqual(plain(module.parse(examples[0][0])), plain(classic.parse(examples[0][0])), 'module/classic parse');
|
|
98
|
-
assert.equal(module.render(examples.at(-1)[0]).errors[0].code, 'invalid-source-character');
|
|
99
|
-
assert.equal(module.render(examples.at(-2)[0]).errors[0].code, 'unsupported-command');
|
|
100
|
-
|
|
101
|
-
const hostile = [
|
|
102
|
-
String.raw`\text{</title><script>alert(1)</script>}`,
|
|
103
|
-
String.raw`\href{javascript:alert(1)}{x}`,
|
|
104
|
-
String.raw`\href{data:text/html,test}{x}`,
|
|
105
|
-
String.raw`\href{https://example.com/" onload="alert(1)}{x}`,
|
|
106
|
-
String.raw`\color{url(https://example.com/payload)}x`,
|
|
107
|
-
String.raw`\def\again{\again}\again`,
|
|
108
|
-
];
|
|
109
|
-
for (const source of hostile) {
|
|
110
|
-
const result = module.render(source);
|
|
111
|
-
sourceAlternative(result, source); inert(result.svg);
|
|
112
|
-
assert.deepEqual(plain(result), plain(classic.render(source)), 'module/classic hostile result');
|
|
113
|
-
}
|
|
114
|
-
for (const source of hostile.slice(1)) assert(module.render(source).errors.length, 'unsafe or exhausted input produces a diagnostic');
|
|
115
|
-
for (const source of ['x'.repeat(1_000_001), '\ud800'.repeat(1_000_001), '&'.repeat(8_000_000)]) {
|
|
116
|
-
const result = module.render(source);
|
|
117
|
-
assert.equal(result.errors[0].code, 'resource-limit');
|
|
118
|
-
assert.equal(result.errors[0].sourceOmitted, true);
|
|
119
|
-
assert(result.svg.includes('data-math-source-omitted="true"'));
|
|
120
|
-
assert(!result.svg.includes('data-tex-utf16'), 'refused source never creates a carrier');
|
|
121
|
-
assert(result.svg.length < 100_000, 'refusal diagnostic is fixed-size');
|
|
122
|
-
assert.equal(module.renderToString(source), result.svg);
|
|
123
|
-
assert.deepEqual(plain(result), plain(classic.render(source)), 'module/classic refusal result');
|
|
124
|
-
inert(result.svg);
|
|
125
|
-
}
|
|
126
|
-
const longCommand = '\\' + 'a'.repeat(10_000), diagnostic = module.render(longCommand);
|
|
127
|
-
assert(diagnostic.errors[0].messageTruncated && diagnostic.errors[0].commandTruncated);
|
|
128
|
-
sourceAlternative(diagnostic, longCommand);
|
|
129
|
-
assert(diagnostic.errors[0].message.length <= 1025 && diagnostic.errors[0].command.length <= 128);
|
|
130
|
-
const unicodeFailure = module.render('\\begin{' + '😀'.repeat(600) + '}x');
|
|
131
|
-
assert(unicodeFailure.errors[0].message.isWellFormed(), 'diagnostic admission cannot split a source surrogate pair');
|
|
132
|
-
assert.equal(module.render('x+1').errors.length, 0, 'refused input cannot poison later rendering');
|
|
133
|
-
console.log(JSON.stringify({name: pkg.name, version: module.version, module: 'native ESM; no global changes',
|
|
134
|
-
rebuild: 'exact static native graph', classicAgreement: examples.length + hostile.length, sourceAlternatives: 'exact', hostileContent: 'inert', licenses: 'complete'}));
|