rapier-math 1.1.1 → 2.1.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.
Files changed (55) hide show
  1. package/README.md +15 -5
  2. package/dist/accessible.css +6 -0
  3. package/dist/accessible.d.ts +10 -0
  4. package/dist/accessible.mjs +18 -0
  5. package/dist/classic.d.ts +8 -2
  6. package/dist/combined.d.ts +4 -0
  7. package/dist/combined.mjs +2 -0
  8. package/dist/index.d.ts +11 -0
  9. package/dist/index.mjs +6 -2980
  10. package/dist/integration.d.ts +11 -2
  11. package/dist/integration.mjs +96 -13
  12. package/dist/markdown-it.d.ts +7 -0
  13. package/dist/markdown-it.mjs +33 -19
  14. package/dist/mathml.d.ts +5 -0
  15. package/dist/mathml.mjs +3 -0
  16. package/dist/rapier-math.js +595 -143
  17. package/dist/rehype.d.ts +7 -0
  18. package/dist/rehype.mjs +28 -7
  19. package/dist/reuse.mjs +110 -0
  20. package/dist/stream.d.ts +36 -3
  21. package/dist/stream.mjs +63 -38
  22. package/docs/api.md +155 -26
  23. package/docs/math-components.json +6 -5
  24. package/docs/math-resources.json +170 -68
  25. package/docs/semantics.md +228 -0
  26. package/examples/README.md +15 -2
  27. package/examples/accessible.html +27 -0
  28. package/examples/accessible.mjs +42 -0
  29. package/examples/markdown.mjs +21 -4
  30. package/examples/semantic.mjs +11 -0
  31. package/examples/stream.mjs +31 -11
  32. package/examples/unified.mjs +17 -3
  33. package/package.json +16 -2
  34. package/src/math/api.js +16 -55
  35. package/src/math/browser.js +4 -0
  36. package/src/math/classic.js +7 -0
  37. package/src/math/combined.js +13 -0
  38. package/src/math/fallbacks.js +5 -0
  39. package/src/math/font.js +3 -0
  40. package/src/math/layout.js +6 -37
  41. package/src/math/mathml.js +406 -0
  42. package/src/math/package-build.mjs +24 -11
  43. package/src/math/package-layout.mjs +3 -0
  44. package/src/math/package-readme.mjs +14 -4
  45. package/src/math/parser.js +14 -11
  46. package/src/math/responsive.js +4 -0
  47. package/src/math/semantic-api.js +12 -0
  48. package/src/math/source.js +67 -0
  49. package/src/math/symbols.js +3 -0
  50. package/src/math/variants.js +41 -0
  51. package/src/tools/build-math.mjs +20 -11
  52. package/tests/adoption.mjs +112 -9
  53. package/tests/check.mjs +20 -5
  54. package/tests/semantics.mjs +340 -0
  55. package/tests/verify.mjs +6 -3
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Source custody and bounded diagnostics shared by SVG and MathML.
3
+ function mathSourceUTF16(source) {
4
+ // Four ASCII hex digits retain each original UTF-16 code unit across XML/HTML hosts.
5
+ const encoded=[],parts=[];
6
+ for(let i=0;i<source.length;i++) {
7
+ parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
8
+ if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
9
+ }
10
+ encoded.push(parts.join(''));
11
+ return encoded.join('');
12
+ }
13
+
14
+ function mathSourceAlternative(source) {
15
+ const alternatives=[],parts=[];
16
+ let first=-1,kept=0,hasCR=false;
17
+ for(let i=0;i<source.length;i++) {
18
+ const code=source.charCodeAt(i);
19
+ if(code===13)hasCR=true;
20
+ if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
21
+ const next=source.charCodeAt(i+1);
22
+ if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
23
+ }
24
+ if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
25
+ if(first<0)first=i;
26
+ if(i>kept)parts.push(source.slice(kept,i));
27
+ parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
28
+ // Flatten small batches instead of retaining one rope node per bad code unit.
29
+ if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
30
+ }
31
+ if(first<0)return {alternative:source,...(hasCR?{utf16:mathSourceUTF16(source)}:{})};
32
+ parts.push(source.slice(kept));alternatives.push(parts.join(''));
33
+ return {alternative:alternatives.join(''),utf16:mathSourceUTF16(source),error:{code:'invalid-source-character',offset:first,
34
+ message:'A source character cannot be embedded in XML. The text alternative shows Unicode escapes; the UTF-16 carrier keeps the original source.'}};
35
+ }
36
+
37
+ function mathAdmitSource(text) {
38
+ // Reject before scanning, escaping, parsing or constructing a source carrier.
39
+ return text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
40
+ code:'resource-limit',offset:0,sourceOmitted:true,
41
+ message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
42
+ }}:mathSourceAlternative(text);
43
+ }
44
+
45
+ function mathDiagnostic(cause) {
46
+ const message=String(cause?.message ?? cause),code=cause?.code,rawCommand=cause?.command;
47
+ const error={code:typeof code==='string'?code:'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,
48
+ offset:Number.isFinite(cause?.offset)?cause.offset:0};
49
+ if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
50
+ if(cause?.sourceOmitted)error.sourceOmitted=true;
51
+ if(rawCommand!==undefined) {
52
+ const command=String(rawCommand);
53
+ error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
54
+ if(command.length>128 || cause.commandTruncated)error.commandTruncated=true;
55
+ }
56
+ return error;
57
+ }
58
+
59
+ function mathPrepare(source) {
60
+ const text = String(source ?? ''), safe = mathAdmitSource(text);
61
+ let tree, error = safe.error;
62
+ if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
63
+ return {text, safe, tree, error};
64
+ }
65
+
66
+ import {parseMathTex} from './parser.js';
67
+ export {mathDiagnostic, mathPrepare, mathSourceUTF16};
@@ -96,3 +96,6 @@ for (const [name, symbol] of Object.entries(MATH_SYMBOLS)) {
96
96
  }
97
97
  const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc mod').split(' '));
98
98
  const MATH_LIMIT_OPERATORS = new Set(('lim limsup liminf sup inf max min injlim projlim varlimsup varliminf varinjlim varprojlim').split(' '));
99
+
100
+
101
+ export {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS};
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
3
+ const MATH_STYLED_RANGES = {
4
+ italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
5
+ 'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
6
+ 'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
7
+ 'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
8
+ 'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
9
+ 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
10
+ monospace: [0x1d670, 0x1d68a, 0x1d7f6],
11
+ };
12
+ const MATH_STYLED_LEGACY = {
13
+ italic: {104: 0x210e},
14
+ script: {66:0x212c,69:0x2130,70:0x2131,72:0x210b,73:0x2110,76:0x2112,77:0x2133,82:0x211b,101:0x212f,103:0x210a,111:0x2134},
15
+ fraktur: {67:0x212d,72:0x210c,73:0x2111,82:0x211c,90:0x2128},
16
+ 'double-struck': {67:0x2102,72:0x210d,78:0x2115,80:0x2119,81:0x211a,82:0x211d,90:0x2124},
17
+ };
18
+ const MATH_STYLED_GREEK = {bold:0x1d6a8, italic:0x1d6e2, 'bold-italic':0x1d71c, 'sans-serif-bold':0x1d756, 'sans-serif-bold-italic':0x1d790};
19
+ const MATH_STYLED_GREEK_SPECIAL = [0x2207,0x2202,0x3f5,0x3d1,0x3f0,0x3d5,0x3f1,0x3d6];
20
+ function mathStyledCodePoint(cp, variant) {
21
+ if (variant === 'normal') variant = 'italic';
22
+ if (MATH_STYLED_LEGACY[variant]?.[cp] !== undefined) return MATH_STYLED_LEGACY[variant][cp];
23
+ const r = MATH_STYLED_RANGES[variant];
24
+ if (r) {
25
+ if (cp >= 65 && cp <= 90) return r[0] + cp - 65;
26
+ if (cp >= 97 && cp <= 122) return r[1] + cp - 97;
27
+ if (r[2] && cp >= 48 && cp <= 57) return r[2] + cp - 48;
28
+ }
29
+ const greek = MATH_STYLED_GREEK[variant];
30
+ if (greek !== undefined) {
31
+ if (cp >= 0x391 && cp <= 0x3a9 && cp !== 0x3a2) return greek + cp - 0x391;
32
+ if (cp >= 0x3b1 && cp <= 0x3c9) return greek + 26 + cp - 0x3b1;
33
+ const special = MATH_STYLED_GREEK_SPECIAL.indexOf(cp);
34
+ if (special === 0) return greek + 25;
35
+ if (special > 0) return greek + 50 + special;
36
+ }
37
+ return cp;
38
+ }
39
+
40
+
41
+ export {mathStyledCodePoint};
@@ -8,17 +8,18 @@ import {createHash} from 'node:crypto';
8
8
  import {gzipSync} from 'node:zlib';
9
9
  import {Script} from 'node:vm';
10
10
  import {mathPackagePath, MATH_CLASSIC} from '../math/package-layout.mjs';
11
- import {mathModule} from '../math/package-build.mjs';
11
+ 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 = '1.1.1';
15
+ export const MATH_VERSION = '2.1.0';
16
16
  export const MATH_BUNDLE = 'rapier-math-' + MATH_VERSION + '.js';
17
- export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'browser.js', 'api.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'];
19
- export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
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'];
19
+ export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'reuse.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
20
+ 'accessible.mjs', 'accessible.css', 'mathml.d.ts', 'combined.d.ts', 'accessible.d.ts',
20
21
  'index.d.ts', 'classic.d.ts', 'delimiters.d.ts', 'integration.d.ts', 'markdown-it.d.ts', 'rehype.d.ts', 'stream.d.ts',
21
- 'examples/formula.mjs', 'examples/markdown.mjs', 'examples/stream.mjs', 'examples/unified.mjs',
22
+ 'examples/semantic.mjs', 'examples/accessible.html', 'examples/accessible.mjs', 'examples/formula.mjs', 'examples/markdown.mjs', 'examples/stream.mjs', 'examples/unified.mjs',
22
23
  'examples/browser.html', 'examples/browser.mjs', 'examples/react.tsx', 'examples/worker.mjs', 'examples/README.md']
23
24
  .map(file => ({file: 'math/' + file, packageFile: mathPackagePath('math/' + file)}));
24
25
  const FONT = {
@@ -57,7 +58,7 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
57
58
  const license = await fontLicense(root, packageLayout);
58
59
  if (!inputs[0].text.includes(license.toString('utf8').trim())) throw new Error('The embedded math font is missing its complete license');
59
60
  const ownLicense = (await read('math/LICENSE-MIT')).toString('utf8');
60
- const bytes = Buffer.from('/*!\n' + ownLicense.trim() + '\n*/\n(function(){\n\'use strict\';\n' + inputs.map(input => input.text.trimEnd()).join('\n\n') + '\n})();\n');
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');
61
62
  new Script(bytes.toString('utf8'), {filename: MATH_BUNDLE});
62
63
  const gzipBytes = gzipSync(bytes, {level: 9}).length;
63
64
  if (gzipBytes >= 500_000) throw new Error('The math plugin exceeds its 500 KB gzip budget: ' + gzipBytes);
@@ -80,15 +81,18 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
80
81
  const content = await read(file);
81
82
  resources.adoption.push({file, packageFile, bytes: content.length, sha256: digest(content)});
82
83
  }
83
- return {resources, bytes};
84
+ return {resources, bytes, modules: mathModules(MATH_VERSION)};
84
85
  }
85
86
 
86
87
  export async function buildMath({root = ROOT, updatePins = true, packageLayout = false} = {}) {
87
- const {resources, bytes} = await assembleMath({root, packageLayout});
88
+ const {resources, bytes, modules} = await assembleMath({root, packageLayout});
88
89
  if (packageLayout) {
89
90
  await mkdir(resolve(root, 'dist'), {recursive: true});
90
91
  await writeFile(resolve(root, MATH_CLASSIC), bytes);
91
- await writeFile(resolve(root, 'dist/index.mjs'), mathModule(bytes));
92
+ for (const [file, content] of modules) {
93
+ await mkdir(dirname(resolve(root, file)), {recursive: true});
94
+ await writeFile(resolve(root, file), content);
95
+ }
92
96
  await writeFile(resolve(root, 'docs/math-resources.json'), JSON.stringify(resources, null, 2) + '\n');
93
97
  await writeFile(resolve(root, 'README.md'), mathReadme(resources));
94
98
  const sbomPath = resolve(root, 'docs/math-components.json');
@@ -117,8 +121,13 @@ export async function buildMath({root = ROOT, updatePins = true, packageLayout =
117
121
  if (!block.test(loader)) throw new Error('The math loader pin could not be located');
118
122
  const version = /var MATH_VERSION = '[^']+';/;
119
123
  if (!version.test(loader)) throw new Error('The math loader version could not be located');
124
+ const cdn = /(key: 'math',[\s\S]*?cdn: ')[^']+(')/;
125
+ if (!cdn.test(loader)) throw new Error('The math loader CDN pin could not be located');
126
+ // The old unversioned URL is shipped with a hash pin. Never replace its bytes.
127
+ const immutableUrl = 'https://cdn.jsdelivr.net/gh/jackskip22/rapier-plugins@main/math/' + MATH_BUNDLE;
120
128
  await writeFile(loaderPath, loader.replace(version, "var MATH_VERSION = '" + MATH_VERSION + "';")
121
- .replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after));
129
+ .replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after)
130
+ .replace(cdn, (_, before, after) => before + immutableUrl + after));
122
131
  }
123
132
  return {bundle: MATH_BUNDLE, bytes: bytes.length, gzipBytes, sha256, sha384};
124
133
  }
@@ -5,8 +5,9 @@ import assert from 'node:assert/strict';
5
5
  import MarkdownIt from 'markdown-it';
6
6
  import {render} from 'rapier-math';
7
7
  import rapierMath from 'rapier-math/markdown-it';
8
+ import rehypeMath from 'rapier-math/rehype';
8
9
  import {createMathMatcher} from 'rapier-math/delimiters';
9
- import {createMarkdownStream} from 'rapier-math/stream';
10
+ import {createMarkdownStream, createMathSession} from 'rapier-math/stream';
10
11
  import {processor} from '../examples/unified.mjs';
11
12
 
12
13
  const md = new MarkdownIt({html: false}).use(rapierMath);
@@ -32,7 +33,7 @@ for (const [name, source, count] of rows) {
32
33
  const batch = md.render(source, {});
33
34
  // Every two-piece boundary, including CRLF, escape runs and surrogate pairs.
34
35
  for (let split = 0; split <= source.length; split++) {
35
- const stream = createMarkdownStream(text => md.render(text, {}), {previewEvery: 8});
36
+ const stream = createMarkdownStream((text, mathSession) => md.render(text, {rapierMathSession: mathSession}), {previewEvery: 8});
36
37
  stream.write(source.slice(0, split)); stream.write(source.slice(split));
37
38
  const final = stream.finish();
38
39
  assert.equal(final.source, source, name + ': exact transport source');
@@ -63,11 +64,13 @@ const span = createMathMatcher(exact)(1);
63
64
  assert.equal(exact.slice(span.bodyStart, span.bodyEnd), '\r\n α+\\text{a\\ b} 🐈\r\n');
64
65
  assert.equal(createMathMatcher(String.raw`$$x\$$`)(0), null);
65
66
 
66
- const first = createMarkdownStream(text => text, {maxSourceLength: 8, previewEvery: 2});
67
+ let first = createMarkdownStream(text => text, {maxSourceLength: 8, previewEvery: 2});
67
68
  const second = createMarkdownStream(text => text);
68
69
  first.write('ab'); second.write('other'); first.abort(); first.abort();
69
70
  assert.throws(() => first.write('c'));
70
- first.reset(); first.write('new');
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');
71
74
  assert.throws(() => first.write('123456'), {code: 'resource-limit'});
72
75
  assert.equal(first.finish().source, 'new');
73
76
  assert.equal(second.finish().source, 'other');
@@ -85,7 +88,7 @@ for (const chunk of failedSource) {
85
88
  failingHost = false;
86
89
  assert.equal(failing.finish().source, failedSource, 'failed previews retain every accepted chunk');
87
90
  assert(supplied < 3 * failedSource.length, 'failed previews keep the repeated-work bound');
88
- failing.abort(); failing.reset();
91
+ failing.abort(); failing.reset().abort();
89
92
 
90
93
  const hostile = String.raw`Before \(\text{</title><script>alert(1)</script>}\). <img src=x onerror=alert(1)>`;
91
94
  assert(!/<script|<img/i.test(md.render(hostile, {})));
@@ -94,19 +97,23 @@ assert(!/<script|<img/i.test(md.render(hostile, {})));
94
97
  const formulaSource = String.raw`\(x\)`, svgCount = html => (html.match(/<svg /g) || []).length;
95
98
  for (const budgets of [{maxFormulas: 1}, {maxOutputLength: render('x').svg.length}]) {
96
99
  const host = new MarkdownIt({html: false}).use(rapierMath, budgets);
100
+ const mathSession = createMathSession(), env = {rapierMathSession: mathSession};
97
101
  for (const inline of [false, true]) {
98
102
  const source = formulaSource + (inline ? ' ' : '\n\n') + formulaSource;
99
103
  const tree = host.parse(source, {});
100
104
  const tokens = inline ? tree[1].children : tree;
101
105
  const renderer = inline ? host.renderer.renderInline : host.renderer.render;
102
106
  for (let pass = 0; pass < 2; pass++) {
103
- const env = {}, out = renderer.call(host.renderer, tokens, host.options, env);
107
+ delete env.rapierMathErrors;
108
+ const out = renderer.call(host.renderer, tokens, host.options, env);
104
109
  assert.equal(svgCount(out), 1);
105
110
  assert.equal(env.rapierMathErrors.length, 1);
106
111
  assert.equal(env.rapierMathErrors[0].errors[0].code, 'resource-limit');
107
112
  assert(out.includes(formulaSource));
108
113
  }
109
114
  }
115
+ assert.equal(mathSession.stats.evaluations, 1, 'admitted cache hits still spend the fresh document budget');
116
+ mathSession.dispose();
110
117
  }
111
118
  const nestedHost = new MarkdownIt({html: false}).use(rapierMath, {maxFormulas: 1});
112
119
  const nestedTree = nestedHost.parse(formulaSource + ' fail', {});
@@ -115,24 +122,46 @@ nestedHost.renderer.rules.text = (tokens, index, opts, env, self) => {
115
122
  if (tokens[index].content === ' fail') throw new Error('host render failed');
116
123
  if (tokens[index].content.includes('nested')) {
117
124
  for (const inline of [false, true]) {
118
- const nestedEnv = {};
125
+ const nestedEnv = {rapierMathSession: env.rapierMathSession};
119
126
  assert.throws(() => inline
120
127
  ? self.renderInline(nestedTree[1].children, opts, nestedEnv)
121
128
  : self.render(nestedTree, opts, nestedEnv), /host render failed/);
122
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');
123
131
  }
124
132
  }
125
133
  return textRule(tokens, index, opts, env, self);
126
134
  };
127
135
  const outerTree = nestedHost.parse(formulaSource + ' nested ' + formulaSource, {});
136
+ const nestedSession = createMathSession();
128
137
  // A custom host can run the same renderer twice; a failed nested render must
129
138
  // restore the outer cap and leave subsequent root renders fresh.
130
139
  for (let pass = 0; pass < 2; pass++) {
131
- const env = {}, out = nestedHost.renderer.render(outerTree, nestedHost.options, env);
140
+ const env = {rapierMathSession: nestedSession}, out = nestedHost.renderer.render(outerTree, nestedHost.options, env);
132
141
  assert.equal(svgCount(out), 1);
133
142
  assert.equal(env.rapierMathErrors.length, 1);
134
143
  assert.equal(env.rapierMathErrors[0].errors[0].code, 'resource-limit');
135
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();
136
165
  const tiny = new MarkdownIt({html: false}).use(rapierMath, {maxOutputLength: 1});
137
166
  assert(!tiny.render(String.raw`\(x\)`).includes('<svg'));
138
167
  const bad = {}, fallback = md.render(String.raw`Good \(x\). Bad \(\unknown{x}\).`, bad);
@@ -144,6 +173,80 @@ assert.equal((String(unified).match(/<svg /g) || []).length, 1);
144
173
  assert(!String(unified).includes('<script'));
145
174
  assert.equal(unified.messages[0].ruleId, 'unsupported-command');
146
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
+
147
250
  console.log(JSON.stringify({sourceCustodyRows: rows.length, splitAgreement: 'all two-piece boundaries',
148
- lifetimes: 'abort, reset, replacement, rejection, interleaved messages', adapters: 'markdown-it and sanitized unified',
251
+ lifetimes: 'abort, replacement handles, rejection, interleaved messages, explicit bounded reuse', adapters: 'markdown-it and sanitized unified',
149
252
  security: 'hostile source stays inert; document math budgets fall back'}));
package/tests/check.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  import assert from 'node:assert/strict';
4
4
  import {readFile} from 'node:fs/promises';
5
5
  import {Script, createContext} from 'node:vm';
6
- import {mathModule} from '../src/math/package-build.mjs';
6
+ import {assembleMath} from '../src/tools/build-math.mjs';
7
+ import {fileURLToPath} from 'node:url';
7
8
 
8
9
  const read = path => readFile(new URL('../' + path, import.meta.url), 'utf8');
9
10
  const pkg = JSON.parse(await read('./package.json'));
@@ -15,11 +16,12 @@ assert.equal(pkg.type, 'module');
15
16
  assert.equal(pkg.license, 'SEE LICENSE IN LICENSE');
16
17
  assert.equal(Object.keys(pkg.dependencies || {}).length, 0);
17
18
  assert.equal(Object.keys(pkg.scripts || {}).length, 0);
18
- assert.equal(await read('./dist/index.mjs'), mathModule(classicSource), 'exact generated module');
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);
19
21
  const rendererLicense = await read('./src/math/LICENSE-MIT'), fontLicense = await read('./src/math/FONT-LICENSE.txt');
20
- for (const name of ['./LICENSE', './dist/index.mjs', './' + resources.packageBundle]) {
22
+ for (const name of ['./LICENSE', './src/math/font.js', './' + resources.packageBundle]) {
21
23
  const text = await read(name);
22
- assert(text.includes(rendererLicense.trim()), name + ': renderer license');
24
+ if (!name.endsWith('font.js')) assert(text.includes(rendererLicense.trim()), name + ': renderer license');
23
25
  assert(text.includes(fontLicense.trim()), name + ': complete font license');
24
26
  }
25
27
 
@@ -27,7 +29,20 @@ for (const name of ['./LICENSE', './dist/index.mjs', './' + resources.packageBun
27
29
  // allocates a local Response only; no network request or renderer evaluation.
28
30
  new Response();
29
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');
30
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'));
31
46
  const afterImport = Object.getOwnPropertyDescriptors(globalThis);
32
47
  assert.deepEqual(Reflect.ownKeys(afterImport), Reflect.ownKeys(globals), 'module adds no globals');
33
48
  for (const key of Reflect.ownKeys(globals)) for (const field of Object.keys(globals[key]))
@@ -115,4 +130,4 @@ const unicodeFailure = module.render('\\begin{' + '😀'.repeat(600) + '}x');
115
130
  assert(unicodeFailure.errors[0].message.isWellFormed(), 'diagnostic admission cannot split a source surrogate pair');
116
131
  assert.equal(module.render('x+1').errors.length, 0, 'refused input cannot poison later rendering');
117
132
  console.log(JSON.stringify({name: pkg.name, version: module.version, module: 'native ESM; no global changes',
118
- rebuild: 'exact module', classicAgreement: examples.length + hostile.length, sourceAlternatives: 'exact', hostileContent: 'inert', licenses: 'complete'}));
133
+ rebuild: 'exact static native graph', classicAgreement: examples.length + hostile.length, sourceAlternatives: 'exact', hostileContent: 'inert', licenses: 'complete'}));