rapier-math 2.0.0 → 2.2.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/README.md +15 -5
- package/dist/accessible.css +6 -0
- package/dist/accessible.d.ts +10 -0
- package/dist/accessible.mjs +18 -0
- package/dist/classic.d.ts +8 -2
- package/dist/combined.d.ts +4 -0
- package/dist/combined.mjs +2 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.mjs +6 -2980
- package/dist/integration.d.ts +3 -1
- package/dist/integration.mjs +13 -19
- package/dist/markdown-it.mjs +7 -4
- package/dist/mathml.d.ts +5 -0
- package/dist/mathml.mjs +3 -0
- package/dist/rapier-math.js +674 -173
- package/dist/rehype.mjs +13 -3
- package/docs/api.md +42 -4
- package/docs/math-components.json +6 -5
- package/docs/math-resources.json +150 -54
- package/docs/semantics.md +228 -0
- package/examples/README.md +10 -0
- package/examples/accessible.html +27 -0
- package/examples/accessible.mjs +42 -0
- package/examples/semantic.mjs +11 -0
- package/package.json +16 -2
- package/src/math/api.js +16 -55
- package/src/math/browser.js +4 -0
- package/src/math/classic.js +7 -0
- package/src/math/combined.js +13 -0
- package/src/math/fallbacks.js +5 -0
- package/src/math/font.js +3 -0
- package/src/math/layout.js +56 -53
- package/src/math/mathml.js +408 -0
- package/src/math/package-build.mjs +24 -11
- package/src/math/package-layout.mjs +3 -0
- package/src/math/package-readme.mjs +14 -4
- package/src/math/parser.js +36 -20
- package/src/math/responsive.js +4 -0
- package/src/math/semantic-api.js +12 -0
- package/src/math/source.js +67 -0
- package/src/math/symbols.js +6 -3
- package/src/math/variants.js +41 -0
- package/src/tools/build-math.mjs +18 -10
- package/tests/adoption.mjs +34 -0
- package/tests/check.mjs +13 -5
- package/tests/semantics.mjs +340 -0
- package/tests/verify.mjs +3 -3
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Structural MathML, exact-source custody and hostile-content checks against a staged package.
|
|
3
|
+
// Replay: node semantic-check.mjs [package-root]. Requires Python 3 with lxml for strict XML parsing.
|
|
4
|
+
// This exercises generated native ESM/classic entries. It makes no appearance or AT speech claims.
|
|
5
|
+
import assert from 'node:assert/strict';
|
|
6
|
+
import {readFile} from 'node:fs/promises';
|
|
7
|
+
import {dirname, resolve} from 'node:path';
|
|
8
|
+
import {fileURLToPath, pathToFileURL} from 'node:url';
|
|
9
|
+
import {spawnSync} from 'node:child_process';
|
|
10
|
+
import {Script, createContext} from 'node:vm';
|
|
11
|
+
|
|
12
|
+
const root = resolve(process.argv[2] || resolve(dirname(fileURLToPath(import.meta.url)), '..'));
|
|
13
|
+
const read = path => readFile(resolve(root, path), 'utf8');
|
|
14
|
+
const pkg = JSON.parse(await read('package.json'));
|
|
15
|
+
const resources = JSON.parse(await read('docs/math-resources.json'));
|
|
16
|
+
const entry = key => pathToFileURL(resolve(root, pkg.exports[key].default)).href;
|
|
17
|
+
const module = {...await import(entry('.')), ...await import(entry('./mathml'))};
|
|
18
|
+
const {renderWithMathML} = await import(entry('./combined'));
|
|
19
|
+
const standalone = await import(entry('./mathml'));
|
|
20
|
+
const {renderAccessible} = await import(entry('./accessible'));
|
|
21
|
+
const classicSource = await read(resources.packageBundle);
|
|
22
|
+
const context = createContext({atob, URL});
|
|
23
|
+
new Script(classicSource, {filename: resources.bundle}).runInContext(context);
|
|
24
|
+
const classic = context.RapierMath;
|
|
25
|
+
const plain = value => JSON.parse(JSON.stringify(value));
|
|
26
|
+
|
|
27
|
+
const corpus = [
|
|
28
|
+
{id: 'fraction-roots', source: String.raw`\frac{12.5}{\sqrt[3]{1+\sqrt{x_2^4}}}`, status: 'complete'},
|
|
29
|
+
{id: 'numbers-signs', source: '-12.34+56-7', status: 'complete'},
|
|
30
|
+
{id: 'number-boundaries', source: String.raw`1{2}3+4\,5+6.7.8+2e3+9\text{ten}0`, status: 'complete'},
|
|
31
|
+
{id: 'number-scripts', source: String.raw`12.3^4+1{2}^3+4\,5^6`, status: 'complete'},
|
|
32
|
+
{id: 'scripts-inline', source: String.raw`x_{12}^{34}+\sum_{i=1}^{20}i`, status: 'complete'},
|
|
33
|
+
{id: 'scripts-display', source: String.raw`x_{12}^{34}+\sum_{i=1}^{20}i`, options: {displayMode: true}, status: 'complete'},
|
|
34
|
+
{id: 'explicit-limits', source: String.raw`\int\limits_0^1 f(x)\,dx+\sum\nolimits_i^n a_i`, options: {displayMode: true}, status: 'complete'},
|
|
35
|
+
{id: 'operators', source: String.raw`\sin x+\operatorname{arg max}_{x}f(x)`, status: 'complete'},
|
|
36
|
+
{id: 'atom-class-limits', source: String.raw`\mathrel{x}+\mathop{xy}+\sum_0^1\limits`, status: 'presentation-fallback'},
|
|
37
|
+
{id: 'fences-accents', source: String.raw`\left(\hat{x}+\underline{y}\middle|z\right)+\overunderset{u}{v}{=}`, status: 'complete'},
|
|
38
|
+
{id: 'matrix', source: String.raw`\begin{pmatrix}1&2\\3&4\end{pmatrix}`, status: 'complete'},
|
|
39
|
+
{id: 'cases', source: String.raw`\begin{cases}x&x\ge0\\-x&\text{otherwise}\end{cases}`, status: 'complete'},
|
|
40
|
+
{id: 'aligned', source: String.raw`\begin{aligned}a&=b+c\\d&=e\end{aligned}`, status: 'complete'},
|
|
41
|
+
{id: 'array-insertion', source: String.raw`\begin{array}{r@{=}l}x&1\\y&2\end{array}`, status: 'presentation-fallback'},
|
|
42
|
+
{id: 'style-text', source: String.raw`\mathbf{x}+\mathbb{R}+\text{speed 12.5}`, status: 'complete'},
|
|
43
|
+
{id: 'macro', source: String.raw`\newcommand{\ratio}[2]{\frac{#1}{#2}}\ratio{12}{34}`, status: 'complete'},
|
|
44
|
+
{id: 'explicit-tokens', source: String.raw`\mmlToken{mi}{speed}+\mmlToken{mn}{12.34}+\mmlToken{mo}{lim}+\mmlToken{mtext}{word}`, status: 'complete'},
|
|
45
|
+
{id: 'links', source: String.raw`\href{https://example.com/?a=1&b=2}{\frac{x}{2}}`, status: 'presentation-fallback'},
|
|
46
|
+
{id: 'nested-link', source: String.raw`\href{https://example.com/outer}{\href{https://example.com/inner}{x}}`, status: 'refused', code: 'semantic-nested-link'},
|
|
47
|
+
{id: 'hidden-link', source: String.raw`\phantom{\href{https://example.com/}{x}}`, status: 'refused', code: 'semantic-hidden-link'},
|
|
48
|
+
{id: 'chemistry', source: String.raw`\ce{2 H2 + O2 -> 2 H2O}`, status: 'presentation-fallback'},
|
|
49
|
+
{id: 'physics-units', source: String.raw`\dv[2]{x}{t}+\pu{1.2e-3 m s-1}`, status: 'presentation-fallback'},
|
|
50
|
+
{id: 'tags-labels', source: String.raw`x=1\label{eq:sample}\tag{A}`, status: 'presentation-fallback'},
|
|
51
|
+
{id: 'presentation', source: String.raw`\cancel{x}+\phantom{a}+\smash{b}+\raisebox{1em}{c}`, status: 'presentation-fallback'},
|
|
52
|
+
{id: 'xml-text', source: String.raw`\text{A < B \& "C" 'D' </mtext><script>run</script>}`, status: 'complete'},
|
|
53
|
+
{id: 'source-lines', source: '\ufeffx% authored 😀 comment\r\n+\t1\r', status: 'complete'},
|
|
54
|
+
{id: 'source-invalid', source: 'x\u0000y\ud800z\udfff\ufffe', status: 'refused', code: 'invalid-source-character'},
|
|
55
|
+
{id: 'generated-invalid', source: String.raw`\unicode{0xffff}`, status: 'refused', code: 'invalid-semantic-character'},
|
|
56
|
+
{id: 'unsupported', source: String.raw`\unsupported{x}`, status: 'refused', code: 'unsupported-command'},
|
|
57
|
+
{id: 'bounded-diagnostic', source: '\\' + 'q'.repeat(5000), status: 'refused', code: 'unsupported-command'},
|
|
58
|
+
{id: 'url-script', source: String.raw`\href{javascript:alert(1)}{x}`, status: 'refused'},
|
|
59
|
+
{id: 'url-data', source: String.raw`\href{data:text/html,payload}{x}`, status: 'refused'},
|
|
60
|
+
{id: 'url-attribute', source: String.raw`\href{https://example.com/" onclick="alert(1)}{x}`, status: 'refused'},
|
|
61
|
+
{id: 'token-attribute', source: String.raw`\mmlToken{mi}[onclick="alert(1)"]{x}`, status: 'refused'},
|
|
62
|
+
{id: 'color-url', source: String.raw`\textcolor{url(https://example.com/payload)}{x}`, status: 'refused'},
|
|
63
|
+
{id: 'macro-exhaustion', source: String.raw`\def\again{\again}\again`, status: 'refused', code: 'resource-limit'},
|
|
64
|
+
{id: 'depth-exhaustion', source: '\\sqrt{'.repeat(200) + 'x' + '}'.repeat(200), status: 'refused', code: 'resource-limit'},
|
|
65
|
+
{id: 'parts-exhaustion', source: 'x'.repeat(50_001), status: 'refused', code: 'resource-limit'},
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
// Array insertions amplify shared AST content without a large authored source.
|
|
69
|
+
// These reach serializer work/output admission, independently of the parser's own limits.
|
|
70
|
+
for (const [id, insertion, rows] of [['table-work', 'x', 500], ['table-output', '\\text{' + 'A'.repeat(1000) + '}', 40]])
|
|
71
|
+
corpus.push({id, source: '\\begin{array}{*{256}{@{' + insertion + '}c}}' + Array(rows).fill('a').join('\\\\') + '\\end{array}', status: 'refused', code: 'resource-limit', semanticOnly: true});
|
|
72
|
+
// Neither source admission nor presentation alone reaches its own bound. Their
|
|
73
|
+
// aggregate must refuse without throwing or discarding the exact CR-sensitive source.
|
|
74
|
+
corpus.push({id: 'complete-output', source: '%' + '&'.repeat(995000) + '\r\n' +
|
|
75
|
+
'\\begin{array}{*{256}{@{\\text{' + 'A'.repeat(900) + '}}c}}' + Array(32).fill('a').join('\\\\') + '\\end{array}',
|
|
76
|
+
status: 'refused', code: 'resource-limit', semanticOnly: true});
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
// Counterexamples at admission and normalization boundaries. These check source
|
|
80
|
+
// authority, truthful semantic status and focus safety rather than appearance.
|
|
81
|
+
for (const name of ['constructor', 'toString', 'hasOwnProperty'])
|
|
82
|
+
corpus.push({id: 'inherited-' + name, source: '\\' + name + '{x}', status: 'refused', code: 'unsupported-command'});
|
|
83
|
+
corpus.push({id: 'inherited-text', source: String.raw`\text{\toString}`, status: 'refused', code: 'unsupported-command'});
|
|
84
|
+
corpus.push({id: 'own-macro-name', source: String.raw`\newcommand{\constructor}{x}\constructor`, status: 'complete'});
|
|
85
|
+
corpus.push({id: 'invalid-color-link', source: String.raw`\href{https://example.com}{\textcolor{transparent}{\textcolor{notacolor}{x}}}`, status: 'refused', code: 'semantic-empty-link'});
|
|
86
|
+
corpus.push({id: 'known-color-link', source: String.raw`\href{https://example.com}{\textcolor{transparent}{\textcolor{RebeccaPurple}{x}}}`, status: 'presentation-fallback'});
|
|
87
|
+
corpus.push({id: 'operator-domain', source: String.raw`\operatorname{\Tr}+\mathop{\grad}`, status: 'presentation-fallback', code: 'semantic-physics-presentation'});
|
|
88
|
+
corpus.push({id: 'unicode-numbers', source: '𝟙𝟚.𝟛^4+١٢', status: 'complete'});
|
|
89
|
+
corpus.push({id: 'authored-invisible-operator', source: String.raw`f\unicode{0x2061}(x)`, status: 'complete'});
|
|
90
|
+
|
|
91
|
+
const records = corpus.map(item => {
|
|
92
|
+
const result = module.toMathML(item.source, item.options);
|
|
93
|
+
assert.equal(result.status, item.status, item.id + ': explicit semantic status');
|
|
94
|
+
if (item.code) assert(result.errors.some(error => error.code === item.code), item.id + ': refusal reason');
|
|
95
|
+
assert.equal(result.status === 'complete', result.errors.length === 0, item.id + ': incomplete mapping is disclosed');
|
|
96
|
+
assert.deepEqual(plain(classic.toMathML(item.source, item.options)), result, item.id + ': classic/ESM semantic agreement');
|
|
97
|
+
assert.deepEqual(standalone.toMathML(item.source, item.options), result, item.id + ': font-free/full semantic agreement');
|
|
98
|
+
if (!item.semanticOnly) {
|
|
99
|
+
const combined = renderWithMathML(item.source, item.options);
|
|
100
|
+
assert.deepEqual(combined.semantics, result, item.id + ': combined path preserves semantic result');
|
|
101
|
+
}
|
|
102
|
+
for (const value of Object.values(result.metrics)) assert(Number.isSafeInteger(value) && value >= 0, item.id + ': finite bounded work');
|
|
103
|
+
assert.equal(result.metrics.outputCodeUnits, result.mathml.length, item.id + ': complete returned-output accounting');
|
|
104
|
+
assert(result.mathml.length <= 16 * 1024 * 1024, item.id + ': complete output bound');
|
|
105
|
+
return {...item, result};
|
|
106
|
+
});
|
|
107
|
+
const diagnostic = records.find(record => record.id === 'bounded-diagnostic').result.errors[0];
|
|
108
|
+
assert.equal(diagnostic.messageTruncated, true, 'semantic diagnostic retains its truncation marker');
|
|
109
|
+
assert.equal(diagnostic.commandTruncated, true, 'semantic command retains its truncation marker');
|
|
110
|
+
assert(diagnostic.message.length <= 1025 && diagnostic.command.length <= 128, 'bounded diagnostic fields');
|
|
111
|
+
assert.equal(records.find(record => record.id === 'source-lines').result.source.encoding, 'application/x-rapier-tex-utf16', 'CR source declares its HTML-stable exact carrier');
|
|
112
|
+
|
|
113
|
+
// Oversized text never enters source escaping or becomes an apparent truncated source archive.
|
|
114
|
+
for (const [id, source] of [['source-omitted', 'x'.repeat(1_000_001)], ['invalid-omitted', '\ud800'.repeat(1_000_001)]]) {
|
|
115
|
+
const result = standalone.toMathML(source);
|
|
116
|
+
assert.equal(result.status, 'refused');
|
|
117
|
+
assert.equal(result.source.omitted, true);
|
|
118
|
+
assert(result.errors.some(error => error.code === 'resource-limit' && error.sourceOmitted));
|
|
119
|
+
assert(result.mathml.length < 100_000, id + ': bounded refusal');
|
|
120
|
+
records.push({id, source, result});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// A returned inspectable tree is caller-owned data; mutations cannot alter another parse or render.
|
|
124
|
+
const detached = module.parse('x+1');
|
|
125
|
+
detached.children[0].value = '</mi><script>run</script>';
|
|
126
|
+
detached.children.push(detached);
|
|
127
|
+
assert.equal(module.parse('x+1').children[0].value, 'x', 'parse has no shared mutable tree');
|
|
128
|
+
assert.deepEqual(module.toMathML('x+1'), standalone.toMathML('x+1'), 'detached mutation cannot poison rendering');
|
|
129
|
+
assert.equal(module.toMathML(String.raw`\ratio{1}{2}`).status, 'refused', 'local macro scope cannot leak');
|
|
130
|
+
const good = module.toMathML('x+1');
|
|
131
|
+
good.errors.push({code: 'caller-change'});
|
|
132
|
+
assert.equal(module.toMathML('x+1').status, 'complete', 'returned diagnostic arrays are not shared');
|
|
133
|
+
|
|
134
|
+
const hosts = ['fraction-roots', 'links', 'unsupported'].map(id => {
|
|
135
|
+
const item = records.find(record => record.id === id);
|
|
136
|
+
const result = renderAccessible(item.source, item.options);
|
|
137
|
+
assert.deepEqual(result.semantics, item.result, id + ': composition preserves semantic payload');
|
|
138
|
+
if (id === 'unsupported') {
|
|
139
|
+
assert.equal(result.presentation, 'refused');
|
|
140
|
+
assert.equal(result.html, '');
|
|
141
|
+
assert(result.errors.length > 0);
|
|
142
|
+
} else assert.equal(result.presentation, id === 'links' ? 'mathml' : 'svg-mathml');
|
|
143
|
+
return {id, html: result.html};
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// A real XML parser catches unescaped text, wrong namespaces, injected children and attribute splitting.
|
|
147
|
+
const xmlReader = String.raw`
|
|
148
|
+
import json, re, sys
|
|
149
|
+
from lxml import etree
|
|
150
|
+
MATH = 'http://www.w3.org/1998/Math/MathML'
|
|
151
|
+
HTML = 'http://www.w3.org/1999/xhtml'
|
|
152
|
+
SVG = 'http://www.w3.org/2000/svg'
|
|
153
|
+
admitted = set('math semantics annotation mrow mi mn mo mtext mfrac msqrt mroot msub msup msubsup mover munder munderover mtable mtr mtd mstyle mspace mphantom mpadded menclose merror'.split())
|
|
154
|
+
def read_node(node, semantic):
|
|
155
|
+
q = etree.QName(node)
|
|
156
|
+
if semantic:
|
|
157
|
+
assert q.namespace == MATH or (q.namespace == HTML and q.localname == 'a'), 'unexpected semantic namespace'
|
|
158
|
+
assert q.localname in admitted or (q.namespace == HTML and q.localname == 'a'), 'unadmitted semantic element'
|
|
159
|
+
if q.namespace == HTML:
|
|
160
|
+
assert etree.QName(node.getparent()).namespace == MATH and etree.QName(node.getparent()).localname == 'mtext', 'HTML link only within MathML mtext'
|
|
161
|
+
assert q.localname.lower() not in ('script', 'iframe', 'object', 'embed', 'image', 'foreignobject', 'style', 'animate', 'set'), 'active or remote element'
|
|
162
|
+
attrs = dict(node.attrib)
|
|
163
|
+
for name, value in attrs.items():
|
|
164
|
+
local = etree.QName(name).localname
|
|
165
|
+
assert not local.lower().startswith('on'), 'event attribute'
|
|
166
|
+
assert local not in ('src', 'srcdoc', 'action', 'formaction'), 'active attribute'
|
|
167
|
+
if local == 'href':
|
|
168
|
+
assert re.match(r'^https?://[^\s<>"\x27\\]+$', value, re.I), 'link must remain a single HTTP(S) URL'
|
|
169
|
+
if local not in ('href', 'aria-label', 'data-tex-utf16'):
|
|
170
|
+
assert not re.search(r'url\s*\(|javascript:|vbscript:|expression\s*\(', value, re.I), 'executable attribute value'
|
|
171
|
+
if semantic:
|
|
172
|
+
assert local != 'id', 'semantic output must not invent occurrence identity'
|
|
173
|
+
assert not re.search(r'(?<![A-Za-z])(?:NaN|Infinity)(?![A-Za-z])', value), 'nonfinite semantic attribute'
|
|
174
|
+
return {'tag': q.localname, 'ns': q.namespace, 'attrs': attrs, 'text': node.text or '', 'children': [read_node(child, semantic) for child in node], 'tail': node.tail or ''}
|
|
175
|
+
def parse(text, semantic):
|
|
176
|
+
assert '<!DOCTYPE' not in text and '<!ENTITY' not in text, 'DTD/entity injection'
|
|
177
|
+
parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True, recover=False)
|
|
178
|
+
node = etree.fromstring(text.encode('utf-8'), parser)
|
|
179
|
+
return read_node(node, semantic)
|
|
180
|
+
data = json.load(sys.stdin)
|
|
181
|
+
result = {'xml': '.'.join(map(str, etree.LXML_VERSION)), 'libxml': '.'.join(map(str, etree.LIBXML_VERSION)), 'python': sys.version.split()[0], 'records': [], 'hosts': []}
|
|
182
|
+
for item in data['records']:
|
|
183
|
+
tree = parse(item['mathml'], True)
|
|
184
|
+
assert tree['tag'] == 'math' and tree['ns'] == MATH, item['id'] + ': namespace-correct root'
|
|
185
|
+
result['records'].append({'id': item['id'], 'tree': tree})
|
|
186
|
+
for item in data['hosts']:
|
|
187
|
+
tree = parse('<div xmlns="' + HTML + '">' + item['html'] + '</div>', False)
|
|
188
|
+
result['hosts'].append({'id': item['id'], 'tree': tree})
|
|
189
|
+
print(json.dumps(result, ensure_ascii=True))
|
|
190
|
+
`;
|
|
191
|
+
const xml = spawnSync(process.env.RAPIER_MATH_PYTHON || 'python3', ['-c', xmlReader], {
|
|
192
|
+
input: JSON.stringify({records: records.map(({id, result}) => ({id, mathml: result.mathml})), hosts}),
|
|
193
|
+
encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
|
|
194
|
+
});
|
|
195
|
+
assert.equal(xml.status, 0, 'strict XML reader: ' + (xml.error?.message || xml.stderr));
|
|
196
|
+
const parsed = JSON.parse(xml.stdout);
|
|
197
|
+
const trees = new Map(parsed.records.map(({id, tree}) => [id, tree]));
|
|
198
|
+
const walk = function*(node) {yield node; for (const child of node.children) yield* walk(child);};
|
|
199
|
+
const find = (tree, tag) => [...walk(tree)].filter(node => node.tag === tag);
|
|
200
|
+
const one = (tree, tag) => {const nodes = find(tree, tag); assert.equal(nodes.length, 1, 'one ' + tag); return nodes[0];};
|
|
201
|
+
// Compare relationships by Unicode base characters while allowing standard mathematical alphabets.
|
|
202
|
+
// Exact authored text is checked separately from the raw parsed annotation, without normalization.
|
|
203
|
+
const textOf = node => node.tag === 'annotation' ? '' : (node.text + node.children.map(child => textOf(child) + child.tail).join('')).normalize('NFKC');
|
|
204
|
+
const tokens = tree => [...walk(tree)].filter(node => ['mi', 'mn', 'mo', 'mtext'].includes(node.tag) && !node.children.length).map(node => [node.tag, node.text.normalize('NFKC')]);
|
|
205
|
+
const rowTexts = tree => one(tree, 'mtable').children.filter(node => node.tag === 'mtr').map(row => row.children.filter(node => node.tag === 'mtd').map(textOf));
|
|
206
|
+
|
|
207
|
+
for (const {id, source, result} of records) {
|
|
208
|
+
const annotations = find(trees.get(id), 'annotation');
|
|
209
|
+
if (result.source.omitted) assert(!annotations.some(node => /(?:tex|utf16)/.test(node.attrs.encoding || '')), id + ': omitted source has no source carrier');
|
|
210
|
+
else {
|
|
211
|
+
const carriers = annotations.filter(node => node.attrs.encoding === result.source.encoding);
|
|
212
|
+
assert.equal(carriers.length, 1, id + ': one declared exact-source carrier');
|
|
213
|
+
if (result.source.encoding === 'application/x-tex') assert.equal(carriers[0].text, source, id + ': exact XML-decoded TeX including CRLF/BOM');
|
|
214
|
+
else {
|
|
215
|
+
assert.equal(result.source.encoding, 'application/x-rapier-tex-utf16');
|
|
216
|
+
assert.match(carriers[0].text, /^(?:[\da-f]{4})*$/i);
|
|
217
|
+
const original = (carriers[0].text.match(/.{4}/g) || []).map(value => String.fromCharCode(parseInt(value, 16))).join('');
|
|
218
|
+
assert.equal(original, source, id + ': exact UTF-16 custody across invalid XML or CR-sensitive hosts');
|
|
219
|
+
assert(!annotations.some(node => node.attrs.encoding === 'application/x-tex'), id + ': escaped substitute is never labelled original TeX');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
assert.deepEqual(tokens(trees.get('unicode-numbers')).filter(([tag]) => tag === 'mn').map(([,value]) => value),
|
|
225
|
+
['12.3', '4', '١٢'], 'authored Unicode decimal digits retain numerical roles and grouping');
|
|
226
|
+
assert(tokens(trees.get('authored-invisible-operator')).some(([tag, value]) => tag === 'mo' && value === '\u2061'),
|
|
227
|
+
'explicit invisible function application stays an operator');
|
|
228
|
+
const fraction = one(trees.get('fraction-roots'), 'mfrac');
|
|
229
|
+
assert.equal(fraction.children.length, 2);
|
|
230
|
+
assert.equal(textOf(fraction.children[0]), '12.5', 'numerator owns decimal token');
|
|
231
|
+
const rootNode = one(fraction.children[1], 'mroot');
|
|
232
|
+
assert.equal(rootNode.children.length, 2);
|
|
233
|
+
assert.equal(textOf(rootNode.children[1]), '3', 'root index is second child');
|
|
234
|
+
const nestedRoot = one(rootNode.children[0], 'msqrt');
|
|
235
|
+
const rootScripts = one(nestedRoot, 'msubsup');
|
|
236
|
+
assert.deepEqual(rootScripts.children.map(textOf), ['x', '2', '4'], 'script order is base/sub/sup');
|
|
237
|
+
assert.deepEqual(tokens(trees.get('numbers-signs')), [['mo', '−'], ['mn', '12.34'], ['mo', '+'], ['mn', '56'], ['mo', '−'], ['mn', '7']], 'signs stay operators and decimal digits stay one number');
|
|
238
|
+
const boundedNumbers = tokens(trees.get('number-boundaries'));
|
|
239
|
+
for (const forbidden of ['123', '45', '6.7.8', '2e3', '90']) assert(!boundedNumbers.some(([tag, text]) => tag === 'mn' && text === forbidden), 'no false number across explicit boundary: ' + forbidden);
|
|
240
|
+
assert(!boundedNumbers.some(([tag, text]) => tag === 'mn' && text.includes('.')), 'malformed multi-dot run never invents a decimal suffix');
|
|
241
|
+
assert(boundedNumbers.some(([tag, text]) => tag === 'mi' && text === 'e'), 'ordinary e is not guessed as scientific notation');
|
|
242
|
+
assert.deepEqual(find(trees.get('number-scripts'), 'msup').map(node => node.children.map(textOf)), [['12.3', '4'], ['2', '3'], ['5', '6']], 'numerical script bases coalesce only within their group/space boundary');
|
|
243
|
+
assert.equal(find(trees.get('scripts-inline'), 'munderover').length, 0, 'display-only limits are side scripts inline');
|
|
244
|
+
const sumLimits = one(trees.get('scripts-display'), 'munderover');
|
|
245
|
+
assert.deepEqual(sumLimits.children.map(textOf), ['∑', 'i=1', '20'], 'operator limits retain base/lower/upper order');
|
|
246
|
+
const explicitLimits = trees.get('explicit-limits');
|
|
247
|
+
assert.deepEqual(one(explicitLimits, 'munderover').children.map(textOf), ['∫', '0', '1'], 'explicit integral limits survive');
|
|
248
|
+
assert(find(explicitLimits, 'msubsup').some(node => textOf(node.children[0]) === '∑'), 'nolimits keeps side scripts');
|
|
249
|
+
const operatorTokens = tokens(trees.get('operators'));
|
|
250
|
+
for (const name of ['sin', 'arg max']) assert(operatorTokens.some(([tag, text]) => tag === 'mo' && text === name), 'one named-operator token: ' + name);
|
|
251
|
+
const overridden = trees.get('atom-class-limits');
|
|
252
|
+
assert(tokens(overridden).some(([tag, text]) => tag === 'mo' && text === 'x'), 'explicit simple relation class is retained');
|
|
253
|
+
assert(tokens(overridden).some(([tag, text]) => tag === 'mi' && text === 'y'), 'compound operator class preserves inner mathematical structure');
|
|
254
|
+
const fixedLimits = one(overridden, 'munderover');
|
|
255
|
+
assert.deepEqual(fixedLimits.children.map(textOf), ['∑', '0', '1']);
|
|
256
|
+
assert.equal(one(fixedLimits.children[0], 'mo').attrs.movablelimits, 'false', 'Core cannot undo explicit limits applied after scripts');
|
|
257
|
+
const decorations = trees.get('fences-accents');
|
|
258
|
+
assert.equal(textOf(one(decorations, 'mover').children[0]), 'x', 'accent owns its base');
|
|
259
|
+
assert.equal(textOf(one(decorations, 'munder').children[0]), 'y', 'under-accent owns its base');
|
|
260
|
+
assert.deepEqual(one(decorations, 'munderover').children.map(textOf), ['=', 'v', 'u'], 'under/over follows base/under/over order');
|
|
261
|
+
assert.deepEqual(rowTexts(trees.get('matrix')), [['1', '2'], ['3', '4']], 'matrix row/cell order');
|
|
262
|
+
assert.deepEqual(rowTexts(trees.get('cases')), [['x', 'x≥0'], ['−x', 'otherwise']], 'cases retain expression/condition pairing');
|
|
263
|
+
assert.deepEqual(rowTexts(trees.get('aligned')), [['a', '=b+c'], ['d', '=e']], 'alignment retains equation cells');
|
|
264
|
+
assert.deepEqual(rowTexts(trees.get('array-insertion')).map(row => row.join('')), ['x=1', 'y=2'], 'array insertions remain mathematical content');
|
|
265
|
+
assert(tokens(trees.get('style-text')).some(([tag, text]) => tag === 'mtext' && text === 'speed 12.5'), 'text is not retokenized as a product');
|
|
266
|
+
assert.deepEqual(one(trees.get('macro'), 'mfrac').children.map(textOf), ['12', '34'], 'macro-expanded mathematical relationships survive');
|
|
267
|
+
const explicit = tokens(trees.get('explicit-tokens'));
|
|
268
|
+
for (const expected of [['mi', 'speed'], ['mn', '12.34'], ['mo', 'lim'], ['mtext', 'word']]) assert(explicit.some(token => token[0] === expected[0] && token[1] === expected[1]), 'explicit token identity: ' + expected.join(':'));
|
|
269
|
+
const link = one(trees.get('links'), 'a');
|
|
270
|
+
assert.equal(link.attrs.href, 'https://example.com/?a=1&b=2');
|
|
271
|
+
assert.deepEqual(one(link, 'mfrac').children.map(textOf), ['x', '2'], 'link retains nested mathematical structure');
|
|
272
|
+
assert(find(trees.get('chemistry'), 'msub').some(node => textOf(node.children[1]) === '2'), 'chemistry retains lowered subscript structure');
|
|
273
|
+
assert(tokens(trees.get('chemistry')).some(([tag, text]) => tag === 'mo' && text === '→'), 'chemistry retains reaction-arrow presentation');
|
|
274
|
+
assert.equal(find(trees.get('physics-units'), 'mfrac').length, 1, 'derivative fraction is structured');
|
|
275
|
+
assert(find(trees.get('physics-units'), 'msup').some(node => textOf(node.children[0]) === '10' && textOf(node.children[1]) === '−3'), 'unit scientific notation retains lowered power structure');
|
|
276
|
+
assert(textOf(trees.get('tags-labels')).includes('A'), 'authored tag is retained');
|
|
277
|
+
assert(![...walk(trees.get('tags-labels'))].some(node => node.attrs.id || node.attrs.href), 'label does not invent equation identity or references');
|
|
278
|
+
assert.equal(textOf(one(trees.get('presentation'), 'mphantom')), 'a', 'intentional phantom content is not discarded');
|
|
279
|
+
|
|
280
|
+
for (const {id, tree} of parsed.hosts) {
|
|
281
|
+
if (id === 'unsupported') continue;
|
|
282
|
+
const descend = (node, hidden = false) => {
|
|
283
|
+
const isHidden = hidden || node.attrs['aria-hidden'] === 'true';
|
|
284
|
+
assert(!(isHidden && (node.attrs.href || (node.attrs.tabindex !== undefined && Number(node.attrs.tabindex) >= 0))), id + ': no focus target in hidden output');
|
|
285
|
+
if (node.tag === 'svg') assert(isHidden, id + ': visual SVG excluded from duplicate announcements');
|
|
286
|
+
if (node.tag === 'math') assert(!isHidden, id + ': semantic math remains exposed');
|
|
287
|
+
for (const child of node.children) descend(child, isHidden);
|
|
288
|
+
};
|
|
289
|
+
descend(tree);
|
|
290
|
+
if (id === 'links') {
|
|
291
|
+
assert.equal(find(tree, 'svg').length, 0, 'linked composition exposes one native MathML presentation');
|
|
292
|
+
assert.equal(find(tree, 'a').length, 1, 'one authored link produces one focus target');
|
|
293
|
+
} else {
|
|
294
|
+
assert.equal(find(tree, 'svg').length, 1);
|
|
295
|
+
assert.equal(find(tree, 'math').length, 1);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Observe work in the exact classic body; counters delegate every real operation unchanged.
|
|
300
|
+
const work = {parses: 0, layoutVisits: 0, fontDecodes: 0};
|
|
301
|
+
let instrumented = classicSource;
|
|
302
|
+
for (const [signature, counter] of [['function parseMathTex(source) {', 'parses'], ['function mathLayout(n,c) {', 'layoutVisits']]) {
|
|
303
|
+
assert.equal(instrumented.split(signature).length, 2, 'one known observation seam');
|
|
304
|
+
instrumented = instrumented.replace(signature, signature + '\nglobalThis.__semanticWork.' + counter + '++;');
|
|
305
|
+
}
|
|
306
|
+
const observed = createContext({URL, __semanticWork: work, atob(value) {work.fontDecodes++; return atob(value);}});
|
|
307
|
+
new Script(instrumented, {filename: resources.bundle}).runInContext(observed);
|
|
308
|
+
const importFontDecodes = work.fontDecodes;
|
|
309
|
+
const formula = corpus[0].source;
|
|
310
|
+
Object.assign(work, {parses: 0, layoutVisits: 0, fontDecodes: 0});
|
|
311
|
+
assert.equal(observed.RapierMath.toMathML(formula).status, 'complete');
|
|
312
|
+
assert.deepEqual(work, {parses: 1, layoutVisits: 0, fontDecodes: 0}, 'semantic call parses once and performs no layout or lazy font decoding');
|
|
313
|
+
Object.assign(work, {parses: 0, layoutVisits: 0, fontDecodes: 0});
|
|
314
|
+
const combined = observed.RapierMath.renderWithMathML(formula);
|
|
315
|
+
assert.equal(combined.errors.length, 0);
|
|
316
|
+
assert.equal(work.parses, 1, 'combined SVG and MathML share one parse');
|
|
317
|
+
assert(work.layoutVisits > 0, 'combined probe exercises actual layout');
|
|
318
|
+
const combinedWork = {...work};
|
|
319
|
+
|
|
320
|
+
// Cold native semantic entry executes with font/network/DOM access guards, without a mocked renderer.
|
|
321
|
+
const cold = spawnSync(process.execPath, ['--input-type=module', '-e', `
|
|
322
|
+
import assert from 'node:assert/strict';
|
|
323
|
+
for (const name of ['atob', 'fetch', 'document', 'window'])
|
|
324
|
+
Object.defineProperty(globalThis, name, {configurable: true, get() {throw new Error('Unexpected semantic dependency: ' + name);}});
|
|
325
|
+
const math = await import(process.argv[1]);
|
|
326
|
+
const result = math.toMathML(process.argv[2]);
|
|
327
|
+
assert.equal(result.status, 'complete');
|
|
328
|
+
assert.equal(math.parse(process.argv[2]).type, 'row');
|
|
329
|
+
process.stdout.write(JSON.stringify(result));
|
|
330
|
+
`, entry('./mathml'), formula], {encoding: 'utf8', maxBuffer: 2 * 1024 * 1024});
|
|
331
|
+
assert.equal(cold.status, 0, 'cold font-free native entry: ' + (cold.error?.message || cold.stderr));
|
|
332
|
+
assert.deepEqual(JSON.parse(cold.stdout), module.toMathML(formula), 'cold entry preserves real semantic output');
|
|
333
|
+
|
|
334
|
+
console.log(JSON.stringify({name: pkg.name, version: module.version, runtime: process.version,
|
|
335
|
+
xml: {python: parsed.python, lxml: parsed.xml, libxml: parsed.libxml}, corpus: corpus.length,
|
|
336
|
+
sourceOmissions: 2, sourceCustody: 'exact after XML parsing; reversible UTF-16 carrier for invalid XML',
|
|
337
|
+
entryAgreement: 'native ESM, classic, font-free ESM, combined render',
|
|
338
|
+
composition: 'one exposed semantic presentation; no hidden or duplicate authored link focus targets',
|
|
339
|
+
work: {fullImportFontDecodes: importFontDecodes, standaloneCall: {parses: 1, layoutVisits: 0, fontDecodes: 0}, combined: combinedWork},
|
|
340
|
+
coldSemanticEntry: 'no font, network or DOM access', assistiveTechnology: 'not exercised'}));
|
package/tests/verify.mjs
CHANGED
|
@@ -6,7 +6,6 @@ import {createHash} from 'node:crypto';
|
|
|
6
6
|
import {dirname, resolve} from 'node:path';
|
|
7
7
|
import {fileURLToPath} from 'node:url';
|
|
8
8
|
import {assembleMath} from '../src/tools/build-math.mjs';
|
|
9
|
-
import {mathModule} from '../src/math/package-build.mjs';
|
|
10
9
|
import {mathReadme} from '../src/math/package-readme.mjs';
|
|
11
10
|
|
|
12
11
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -31,7 +30,7 @@ for (const input of [...resources.sources, ...resources.recipe, ...resources.ado
|
|
|
31
30
|
const rendererLicense = await read('src/math/LICENSE-MIT');
|
|
32
31
|
const fontLicense = await read('src/math/FONT-LICENSE.txt');
|
|
33
32
|
assert.equal(hash(fontLicense), resources.font.licenseSha256, 'font license SHA-256');
|
|
34
|
-
for (const text of [payload, await read('LICENSE')
|
|
33
|
+
for (const text of [payload, await read('LICENSE')]) {
|
|
35
34
|
assert(text.includes(rendererLicense.toString('utf8').trim()), 'complete renderer license');
|
|
36
35
|
assert(text.includes(fontLicense.toString('utf8').trim()), 'complete font license');
|
|
37
36
|
}
|
|
@@ -44,6 +43,7 @@ assert.equal(sbom.hasExtractedLicensingInfos.find(item => item.licenseId === res
|
|
|
44
43
|
assert.equal((await read('README.md')).toString('utf8'), mathReadme(resources), 'generated README');
|
|
45
44
|
const rebuilt = await assembleMath({root, packageLayout: true});
|
|
46
45
|
assert.deepEqual(rebuilt.bytes, payload, 'rebuilt classic payload');
|
|
47
|
-
|
|
46
|
+
for (const [file, content] of rebuilt.modules)
|
|
47
|
+
assert.equal((await read(file)).toString('utf8'), content, 'rebuilt native module: ' + file);
|
|
48
48
|
console.log(JSON.stringify({file: resources.packageBundle, bytes: payload.length, sha256: resources.sha256,
|
|
49
49
|
sourceFiles: paths.size, rebuild: 'exact', licenses: 'complete'}));
|