rapier-math 2.0.0 → 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 (47) 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 +3 -1
  11. package/dist/integration.mjs +13 -19
  12. package/dist/markdown-it.mjs +7 -4
  13. package/dist/mathml.d.ts +5 -0
  14. package/dist/mathml.mjs +3 -0
  15. package/dist/rapier-math.js +595 -143
  16. package/dist/rehype.mjs +13 -3
  17. package/docs/api.md +38 -2
  18. package/docs/math-components.json +6 -5
  19. package/docs/math-resources.json +150 -54
  20. package/docs/semantics.md +228 -0
  21. package/examples/README.md +10 -0
  22. package/examples/accessible.html +27 -0
  23. package/examples/accessible.mjs +42 -0
  24. package/examples/semantic.mjs +11 -0
  25. package/package.json +16 -2
  26. package/src/math/api.js +16 -55
  27. package/src/math/browser.js +4 -0
  28. package/src/math/classic.js +7 -0
  29. package/src/math/combined.js +13 -0
  30. package/src/math/fallbacks.js +5 -0
  31. package/src/math/font.js +3 -0
  32. package/src/math/layout.js +6 -37
  33. package/src/math/mathml.js +406 -0
  34. package/src/math/package-build.mjs +24 -11
  35. package/src/math/package-layout.mjs +3 -0
  36. package/src/math/package-readme.mjs +14 -4
  37. package/src/math/parser.js +14 -11
  38. package/src/math/responsive.js +4 -0
  39. package/src/math/semantic-api.js +12 -0
  40. package/src/math/source.js +67 -0
  41. package/src/math/symbols.js +3 -0
  42. package/src/math/variants.js +41 -0
  43. package/src/tools/build-math.mjs +19 -10
  44. package/tests/adoption.mjs +34 -0
  45. package/tests/check.mjs +13 -5
  46. package/tests/semantics.mjs +340 -0
  47. package/tests/verify.mjs +3 -3
@@ -847,7 +847,7 @@ class MathTexParser {
847
847
  for (;;) {
848
848
  const token = this.peek();
849
849
  if (token.kind === 'eof' || stop(token)) break;
850
- if (token.kind === 'command' && (MATH_TEX_DECLARATIONS[token.value] || token.value === 'color')) {
850
+ if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
851
851
  this.take();
852
852
  const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
853
853
  children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
@@ -998,7 +998,7 @@ class MathTexParser {
998
998
  if (token.kind === 'command') {
999
999
  if (token.value === '{' || token.value === '}') return token.value;
1000
1000
  if (token.value === '|') return '‖';
1001
- const symbol = MATH_SYMBOLS[token.value];
1001
+ const symbol = Object.hasOwn(MATH_SYMBOLS, token.value) ? MATH_SYMBOLS[token.value] : null;
1002
1002
  if (symbol && (['open', 'close'].includes(symbol.class) || /^(vert|Vert|backslash|slash|[uUdD].*arrow)$/.test(token.value))) return symbol.value;
1003
1003
  }
1004
1004
  if (token.kind === 'char' && '.()[]{}|/<>‖⌈⌉⌊⌋⟨⟩↑↓↕⇑⇓⇕'.includes(token.value))
@@ -1012,7 +1012,7 @@ class MathTexParser {
1012
1012
  if (Object.hasOwn(MATH_TEX_LONG_ARROWS, name)) return this.node('style', {class: 'rel', body: this.row([this.node('space', {width: 5 / 18}), this.node('glyph', MATH_SYMBOLS[MATH_TEX_LONG_ARROWS[name]]), this.node('space', {width: 5 / 18})])});
1013
1013
  // amsmath \dots: centred dots before a binary operator, a relation or an integral, low dots otherwise.
1014
1014
  if (name === 'dots') {
1015
- const next = this.rawPeek(), after = next.kind === 'command' ? MATH_SYMBOLS[next.value] : null;
1015
+ const next = this.rawPeek(), after = next.kind === 'command' && Object.hasOwn(MATH_SYMBOLS, next.value) ? MATH_SYMBOLS[next.value] : null;
1016
1016
  const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
1017
1017
  if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
1018
1018
  }
@@ -1078,7 +1078,7 @@ class MathTexParser {
1078
1078
  if (name === 'operatorname') {
1079
1079
  const starred = this.is('*'); if (starred) this.take();
1080
1080
  const body = this.subparse(this.rawArgument(), true, 'roman');
1081
- return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never'});
1081
+ return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
1082
1082
  }
1083
1083
  if (/^math(ord|op|bin|rel|open|close|punct|inner)$/.test(name)) return this.node('style', {body: this.argument(), class: name.slice(4), ...(name === 'mathop' ? {limits: 'display'} : {})});
1084
1084
  if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
@@ -1151,14 +1151,14 @@ class MathTexParser {
1151
1151
  if (name === 'tag') {
1152
1152
  const starred = this.is('*'); if (starred) this.take();
1153
1153
  const body = this.subparse(this.rawArgument(), true);
1154
- return this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]);
1154
+ return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
1155
1155
  }
1156
1156
  if (name === 'mod' || name === 'bmod') return this.row([this.node('space', {width: name === 'bmod' ? 5 / 18 : 1}), this.node('text', {value: 'mod', variant: 'roman', class: name === 'bmod' ? 'bin' : 'op'}), this.node('space', {width: name === 'bmod' ? 5 / 18 : 1 / 3})]);
1157
1157
  if (name === 'pmod' || name === 'pod') return this.row([this.node('space', {width: 1}), this.node('fence', {left: '(', right: ')', body: this.row([...(name === 'pmod' ? [this.node('text', {value: 'mod', variant: 'roman'}), this.node('space', {width: 1 / 3})] : []), this.argument()])})]);
1158
1158
  if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
1159
- if (name === 'ce') return this.chemistry(this.rawArgument());
1160
- if (name === 'pu') return this.units(this.rawArgument());
1161
- if (this.physicsCommand(name)) return this.physics(name, token);
1159
+ if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
1160
+ if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
1161
+ if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
1162
1162
  if (name === 'mmlToken') return this.mathmlToken(token);
1163
1163
  if (name === 'unicode' || name === 'char') return this.character(name, token);
1164
1164
  if (name === 'TeX' || name === 'LaTeX') return this.node('text', {value: name, variant: 'roman'});
@@ -1383,7 +1383,7 @@ class MathTexParser {
1383
1383
  if (!next || next.kind !== 'char' || !(next.value === '#' || (/^[1-9]$/.test(next.value) && Number(next.value) <= params.length)))
1384
1384
  this.error('invalid-macro', 'A replacement refers to a missing macro parameter.', body[i - 1]);
1385
1385
  }
1386
- const existing = this.macro(macroName) || MATH_SYMBOLS[macroName] || MATH_TEX_VARIANTS[macroName] || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
1386
+ const existing = this.macro(macroName) || Object.hasOwn(MATH_SYMBOLS, macroName) || Object.hasOwn(MATH_TEX_VARIANTS, macroName) || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
1387
1387
  if (name === 'providecommand' && existing) return;
1388
1388
  if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
1389
1389
  this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
@@ -1516,7 +1516,7 @@ class MathTexParser {
1516
1516
  if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
1517
1517
  value += (letters + marks[name]).normalize('NFC'); continue;
1518
1518
  }
1519
- if (MATH_SYMBOLS[name] && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
1519
+ if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
1520
1520
  flush();
1521
1521
  const body = this.command(token);
1522
1522
  if (body) children.push(body);
@@ -1707,7 +1707,7 @@ class MathTexParser {
1707
1707
  if (!match || !variants.has(match[1])) this.error('unsupported-attribute', 'Only a mathematical font variant is supported on a token.', token);
1708
1708
  variant = match[1] === 'normal' ? 'roman' : match[1] === 'bold-sans-serif' ? 'sans-serif-bold' : match[1];
1709
1709
  }
1710
- return this.node('style', {variant, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
1710
+ return this.node('style', {variant, tokenKind: kind, tokenText: text, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
1711
1711
  }
1712
1712
  character(name, token) {
1713
1713
  let raw;
@@ -1736,48 +1736,72 @@ function parseMathTex(source) {
1736
1736
  }
1737
1737
 
1738
1738
  // SPDX-License-Identifier: MIT
1739
- // Boxes use ems, a baseline at y=0 and a downward SVG axis. Font outlines stay in font units.
1740
- const mathNumber = n => {
1741
- if (!Number.isFinite(n)) throw new Error('Math geometry is not finite');
1742
- const scaled = n * 1e6;
1743
- return String((Number.isFinite(scaled) ? Math.round(scaled) / 1e6 : n) || 0);
1744
- };
1745
- const mathEscape = s => String(s).replace(/[&<>"'\t\n\r]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','\t':'&#9;','\n':'&#10;','\r':'&#13;'}[c]));
1746
- const mathFontRatio = (MATH_FONT.textXHeight / MATH_FONT.textUnits) / (MATH_FONT.xHeight / MATH_FONT.units);
1747
- function mathScale(c) {
1748
- if (!c.level) return c.size;
1749
- const scale = MATH_FONT.constants[c.level === 1 ? 'ScriptPercentScaleDown' : 'ScriptScriptPercentScaleDown'] / 100;
1750
- return c.size * (c.screen ? Math.max(scale, Math.min(1, (c.level === 1 ? 12 : 10) / c.screen.fontSize)) : scale);
1739
+ // Source custody and bounded diagnostics shared by SVG and MathML.
1740
+ function mathSourceUTF16(source) {
1741
+ // Four ASCII hex digits retain each original UTF-16 code unit across XML/HTML hosts.
1742
+ const encoded=[],parts=[];
1743
+ for(let i=0;i<source.length;i++) {
1744
+ parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
1745
+ if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
1746
+ }
1747
+ encoded.push(parts.join(''));
1748
+ return encoded.join('');
1751
1749
  }
1752
1750
 
1753
- function mathScreenStroke(c, scale) {
1754
- if (!c.screen) return 0;
1755
- const {fontSize, pixelRatio, dark} = c.screen, size = fontSize * (scale ?? mathScale(c));
1756
- if (!(size > 0)) return 0;
1757
- const small = Math.max(0, Math.min(1, (32 - size) / 16));
1758
- const hairline = MATH_FONT.constants.FractionRuleThickness / MATH_FONT.units * size;
1759
- return small * ((dark ? .18 : .09) / Math.sqrt(pixelRatio) + Math.max(0, (dark ? 1 : .85) / pixelRatio - hairline) * .35) / fontSize;
1751
+ function mathSourceAlternative(source) {
1752
+ const alternatives=[],parts=[];
1753
+ let first=-1,kept=0,hasCR=false;
1754
+ for(let i=0;i<source.length;i++) {
1755
+ const code=source.charCodeAt(i);
1756
+ if(code===13)hasCR=true;
1757
+ if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
1758
+ const next=source.charCodeAt(i+1);
1759
+ if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
1760
+ }
1761
+ if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
1762
+ if(first<0)first=i;
1763
+ if(i>kept)parts.push(source.slice(kept,i));
1764
+ parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
1765
+ // Flatten small batches instead of retaining one rope node per bad code unit.
1766
+ if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
1767
+ }
1768
+ if(first<0)return {alternative:source,...(hasCR?{utf16:mathSourceUTF16(source)}:{})};
1769
+ parts.push(source.slice(kept));alternatives.push(parts.join(''));
1770
+ return {alternative:alternatives.join(''),utf16:mathSourceUTF16(source),error:{code:'invalid-source-character',offset:first,
1771
+ message:'A source character cannot be embedded in XML. The text alternative shows Unicode escapes; the UTF-16 carrier keeps the original source.'}};
1760
1772
  }
1761
- const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallback * MATH_FONT.units) / MATH_FONT.units * mathScale(c);
1762
- const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
1763
- const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
1764
- const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
1765
- const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>' : '';
1766
1773
 
1767
- function mathCompose(items, width, extra = {}) {
1768
- let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
1769
- for (const [b, x, y] of items) {
1770
- if(svg.length+b.svg.length+128>8*1024*1024)throw Object.assign(new Error('Mathematical composition exceeds the SVG budget'),{code:'resource-limit'});
1771
- h = Math.max(h, b.h - y); d = Math.max(d, b.d + y);
1772
- left = Math.min(left, x + b.left); right = Math.max(right, x + b.right);
1773
- if(b.svg) {inkTop=Math.min(inkTop,b.inkTop+y);inkBottom=Math.max(inkBottom,b.inkBottom+y);}
1774
- svg += mathMove(b, x, y);
1775
- }
1776
- const single=items.length===1?items[0]:null,b=single?.[0];
1777
- const glyph=b?.glyph===undefined?{}:{glyph:b.glyph,unitScale:b.unitScale,glyphX:(b.glyphX || 0)+single[1],glyphY:(b.glyphY || 0)+single[2],extended:b.extended,scriptBase:b.scriptBase,stroke:b.stroke};
1778
- return mathBox(width, h, d, svg, {left, right, inkTop:Number.isFinite(inkTop)?inkTop:-h, inkBottom:Number.isFinite(inkBottom)?inkBottom:d,...glyph,...extra});
1774
+ function mathAdmitSource(text) {
1775
+ // Reject before scanning, escaping, parsing or constructing a source carrier.
1776
+ return text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
1777
+ code:'resource-limit',offset:0,sourceOmitted:true,
1778
+ message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
1779
+ }}:mathSourceAlternative(text);
1780
+ }
1781
+
1782
+ function mathDiagnostic(cause) {
1783
+ const message=String(cause?.message ?? cause),code=cause?.code,rawCommand=cause?.command;
1784
+ const error={code:typeof code==='string'?code:'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,
1785
+ offset:Number.isFinite(cause?.offset)?cause.offset:0};
1786
+ if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
1787
+ if(cause?.sourceOmitted)error.sourceOmitted=true;
1788
+ if(rawCommand!==undefined) {
1789
+ const command=String(rawCommand);
1790
+ error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
1791
+ if(command.length>128 || cause.commandTruncated)error.commandTruncated=true;
1792
+ }
1793
+ return error;
1779
1794
  }
1780
1795
 
1796
+ function mathPrepare(source) {
1797
+ const text = String(source ?? ''), safe = mathAdmitSource(text);
1798
+ let tree, error = safe.error;
1799
+ if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
1800
+ return {text, safe, tree, error};
1801
+ }
1802
+
1803
+ // SPDX-License-Identifier: MIT
1804
+ // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
1781
1805
  const MATH_STYLED_RANGES = {
1782
1806
  italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
1783
1807
  'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
@@ -1815,6 +1839,49 @@ function mathStyledCodePoint(cp, variant) {
1815
1839
  return cp;
1816
1840
  }
1817
1841
 
1842
+ // SPDX-License-Identifier: MIT
1843
+ // Boxes use ems, a baseline at y=0 and a downward SVG axis. Font outlines stay in font units.
1844
+ const mathNumber = n => {
1845
+ if (!Number.isFinite(n)) throw new Error('Math geometry is not finite');
1846
+ const scaled = n * 1e6;
1847
+ return String((Number.isFinite(scaled) ? Math.round(scaled) / 1e6 : n) || 0);
1848
+ };
1849
+ const mathEscape = s => String(s).replace(/[&<>"'\t\n\r]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','\t':'&#9;','\n':'&#10;','\r':'&#13;'}[c]));
1850
+ const mathFontRatio = (MATH_FONT.textXHeight / MATH_FONT.textUnits) / (MATH_FONT.xHeight / MATH_FONT.units);
1851
+ function mathScale(c) {
1852
+ if (!c.level) return c.size;
1853
+ const scale = MATH_FONT.constants[c.level === 1 ? 'ScriptPercentScaleDown' : 'ScriptScriptPercentScaleDown'] / 100;
1854
+ return c.size * (c.screen ? Math.max(scale, Math.min(1, (c.level === 1 ? 12 : 10) / c.screen.fontSize)) : scale);
1855
+ }
1856
+
1857
+ function mathScreenStroke(c, scale) {
1858
+ if (!c.screen) return 0;
1859
+ const {fontSize, pixelRatio, dark} = c.screen, size = fontSize * (scale ?? mathScale(c));
1860
+ if (!(size > 0)) return 0;
1861
+ const small = Math.max(0, Math.min(1, (32 - size) / 16));
1862
+ const hairline = MATH_FONT.constants.FractionRuleThickness / MATH_FONT.units * size;
1863
+ return small * ((dark ? .18 : .09) / Math.sqrt(pixelRatio) + Math.max(0, (dark ? 1 : .85) / pixelRatio - hairline) * .35) / fontSize;
1864
+ }
1865
+ const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallback * MATH_FONT.units) / MATH_FONT.units * mathScale(c);
1866
+ const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
1867
+ const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
1868
+ const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
1869
+ const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>' : '';
1870
+
1871
+ function mathCompose(items, width, extra = {}) {
1872
+ let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
1873
+ for (const [b, x, y] of items) {
1874
+ if(svg.length+b.svg.length+128>8*1024*1024)throw Object.assign(new Error('Mathematical composition exceeds the SVG budget'),{code:'resource-limit'});
1875
+ h = Math.max(h, b.h - y); d = Math.max(d, b.d + y);
1876
+ left = Math.min(left, x + b.left); right = Math.max(right, x + b.right);
1877
+ if(b.svg) {inkTop=Math.min(inkTop,b.inkTop+y);inkBottom=Math.max(inkBottom,b.inkBottom+y);}
1878
+ svg += mathMove(b, x, y);
1879
+ }
1880
+ const single=items.length===1?items[0]:null,b=single?.[0];
1881
+ const glyph=b?.glyph===undefined?{}:{glyph:b.glyph,unitScale:b.unitScale,glyphX:(b.glyphX || 0)+single[1],glyphY:(b.glyphY || 0)+single[2],extended:b.extended,scriptBase:b.scriptBase,stroke:b.stroke};
1882
+ return mathBox(width, h, d, svg, {left, right, inkTop:Number.isFinite(inkTop)?inkTop:-h, inkBottom:Number.isFinite(inkBottom)?inkBottom:d,...glyph,...extra});
1883
+ }
1884
+
1818
1885
  function mathGlyphIndex(id, c, extra = {}) {
1819
1886
  if(c.dotless)id=MATH_FONT.dotless?.[id] ?? id;
1820
1887
  const alternates=MATH_FONT.scriptAlternates[id],scale=mathScale(c);
@@ -2680,6 +2747,72 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
2680
2747
  return mathFitBox(natural,width,c);
2681
2748
  }
2682
2749
 
2750
+ // SPDX-License-Identifier: MIT
2751
+ function mathSvg(box,source,error,utf16,options={}) {
2752
+ if(box.svg.length>8*1024*1024)throw Object.assign(new Error('This formula produces too much SVG to render safely.'),{code:'resource-limit'});
2753
+ const pad=0.025,left=Math.min(0,box.left)-pad,right=Math.max(box.w,box.right)+pad;
2754
+ const width=Math.max(0.05,right-left),height=Math.max(0.025,box.h+pad,-box.inkTop+pad),depth=Math.max(0.025,box.d+pad,box.inkBottom+pad);
2755
+ const viewBox=[left*1000,-height*1000,width*1000,(height+depth)*1000];
2756
+ const opacity=options.screen?.dark ? .94 : 1;
2757
+ if (![width,height,depth,left,...viewBox].every(Number.isFinite)) throw new Error('Mathematical dimensions are not finite');
2758
+ const escapedSource=mathEscape(source);
2759
+ // A group exposes authored links to accessibility APIs; an image would hide them.
2760
+ const svg='<svg xmlns="http://www.w3.org/2000/svg" role="'+(box.svg.includes('<a ')?'group':'img')+'" aria-label="'+escapedSource+'"'+
2761
+ ' data-rapier-math="'+(options.displayMode?'display':'inline')+'" data-math-lines="'+(box.lines || 1)+'"'+
2762
+ ' data-math-natural-width="'+mathNumber(options.naturalWidth ?? width)+'"'+
2763
+ (options.screen?' data-math-screen="'+mathNumber(options.screen.fontSize)+'|'+mathNumber(options.screen.pixelRatio)+'|'+options.screen.dark+'"':'')+
2764
+ (options.maxWidth?' data-math-max-width="'+mathNumber(options.maxWidth)+'"':'')+
2765
+ (utf16?' data-tex-utf16="'+utf16+'"':'')+
2766
+ (error?.sourceOmitted?' data-math-source-omitted="true"':'')+
2767
+ (error?' data-math-error="'+mathEscape(error.code)+'"':'')+' width="'+mathNumber(width)+'em" height="'+mathNumber(height+depth)+'em"'+
2768
+ ' viewBox="'+viewBox.map(mathNumber).join(' ')+'"'+
2769
+ ' style="font-size:'+mathNumber(mathFontRatio)+'em;max-width:100%;height:auto;vertical-align:-'+mathNumber(depth)+'em;'+
2770
+ 'fill-opacity:'+opacity+';stroke-opacity:'+opacity+'" fill="currentColor">'+
2771
+ '<title>'+escapedSource+'</title>'+(error?'<desc>'+mathEscape(error.message)+'</desc>':'')+
2772
+ '<g transform="scale(1000)">'+box.svg+'</g></svg>';
2773
+ if(svg.length>24*1024*1024)throw Object.assign(new Error('The complete formula markup exceeds its output budget.'),{code:'resource-limit'});
2774
+ return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
2775
+ }
2776
+
2777
+ function mathRenderPrepared(prepared,options={}) {
2778
+ const {text,safe,tree,error:parseError}=prepared;
2779
+ const context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
2780
+ try {
2781
+ if(safe.error)throw safe.error;
2782
+ if(options?.screen!==undefined) {
2783
+ const {fontSize,pixelRatio,dark}=options.screen || {},scaled=Number.isFinite(fontSize)?fontSize*mathFontRatio:NaN;
2784
+ if(!Number.isFinite(fontSize) || fontSize<=0 || !Number.isFinite(pixelRatio) || pixelRatio<=0 ||
2785
+ typeof dark!=='boolean' || !Number.isFinite(scaled) || scaled<=0 || !Number.isFinite(scaled*pixelRatio) || scaled*pixelRatio<=0 ||
2786
+ !Number.isFinite(1/scaled) || !Number.isFinite(1/pixelRatio) || !Number.isFinite(1/(scaled*pixelRatio)))
2787
+ throw Object.assign(new Error('Screen font size, pixel ratio and device scale must be positive and finite; dark must be a boolean.'),{code:'invalid-screen'});
2788
+ context.screen={fontSize:scaled,pixelRatio,dark};
2789
+ }
2790
+ if(parseError)throw parseError;
2791
+ const natural=mathLayout(tree,context),limit=Number(options?.maxWidth);
2792
+ const maxWidth=Number.isFinite(limit) && limit>.1?limit:undefined;
2793
+ const box=maxWidth && mathInkWidth(natural)>maxWidth-.05?mathResponsiveLayout(tree,context,maxWidth-.05,natural):natural;
2794
+ return mathSvg(box,safe.alternative,undefined,safe.utf16,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
2795
+ }
2796
+ catch (cause) {
2797
+ const error=mathDiagnostic(cause);
2798
+ // A diagnostic is visible, but remains distinct from a successfully typeset formula.
2799
+ // Diagnostics have an explicit bound. Exact input stays in the source alternative.
2800
+ const label=error.message.length>240?'This formula could not be rendered. The complete diagnostic is in its text description.':error.message.replace(/[^\x20-\x7e]/g,'?');
2801
+ const diagnostic={...context,variant:'roman',size:0.8,budget:{nodes:0,outlineBytes:0}};
2802
+ try {
2803
+ return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display,screen:context.screen});
2804
+ } catch {
2805
+ diagnostic.screen=undefined;
2806
+ return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display});
2807
+ }
2808
+ }
2809
+ }
2810
+
2811
+ function renderMath(source,options={}) {
2812
+ return mathRenderPrepared(mathPrepare(source),options);
2813
+ }
2814
+ function mathRenderToString(source,options) { return renderMath(source,options).svg; }
2815
+
2683
2816
  // SPDX-License-Identifier: MIT
2684
2817
  // The browser supplies the column and physical pixel grid; rendering remains synchronous and pure.
2685
2818
  const mathBrowserStates=new WeakMap(),mathBrowserDocuments=new WeakMap(),mathRuleOriginals=new WeakMap();
@@ -2869,112 +3002,431 @@ function mathObserve(root) {
2869
3002
  }
2870
3003
 
2871
3004
  // SPDX-License-Identifier: MIT
2872
- function mathSvg(box,source,error,utf16,options={}) {
2873
- if(box.svg.length>8*1024*1024)throw Object.assign(new Error('This formula produces too much SVG to render safely.'),{code:'resource-limit'});
2874
- const pad=0.025,left=Math.min(0,box.left)-pad,right=Math.max(box.w,box.right)+pad;
2875
- const width=Math.max(0.05,right-left),height=Math.max(0.025,box.h+pad,-box.inkTop+pad),depth=Math.max(0.025,box.d+pad,box.inkBottom+pad);
2876
- const viewBox=[left*1000,-height*1000,width*1000,(height+depth)*1000];
2877
- const opacity=options.screen?.dark ? .94 : 1;
2878
- if (![width,height,depth,left,...viewBox].every(Number.isFinite)) throw new Error('Mathematical dimensions are not finite');
2879
- const escapedSource=mathEscape(source);
2880
- // A group exposes authored links to accessibility APIs; an image would hide them.
2881
- const svg='<svg xmlns="http://www.w3.org/2000/svg" role="'+(box.svg.includes('<a ')?'group':'img')+'" aria-label="'+escapedSource+'"'+
2882
- ' data-rapier-math="'+(options.displayMode?'display':'inline')+'" data-math-lines="'+(box.lines || 1)+'"'+
2883
- ' data-math-natural-width="'+mathNumber(options.naturalWidth ?? width)+'"'+
2884
- (options.screen?' data-math-screen="'+mathNumber(options.screen.fontSize)+'|'+mathNumber(options.screen.pixelRatio)+'|'+options.screen.dark+'"':'')+
2885
- (options.maxWidth?' data-math-max-width="'+mathNumber(options.maxWidth)+'"':'')+
2886
- (utf16?' data-tex-utf16="'+utf16+'"':'')+
2887
- (error?.sourceOmitted?' data-math-source-omitted="true"':'')+
2888
- (error?' data-math-error="'+mathEscape(error.code)+'"':'')+' width="'+mathNumber(width)+'em" height="'+mathNumber(height+depth)+'em"'+
2889
- ' viewBox="'+viewBox.map(mathNumber).join(' ')+'"'+
2890
- ' style="font-size:'+mathNumber(mathFontRatio)+'em;max-width:100%;height:auto;vertical-align:-'+mathNumber(depth)+'em;'+
2891
- 'fill-opacity:'+opacity+';stroke-opacity:'+opacity+'" fill="currentColor">'+
2892
- '<title>'+escapedSource+'</title>'+(error?'<desc>'+mathEscape(error.message)+'</desc>':'')+
2893
- '<g transform="scale(1000)">'+box.svg+'</g></svg>';
2894
- if(svg.length>24*1024*1024)throw Object.assign(new Error('The complete formula markup exceeds its output budget.'),{code:'resource-limit'});
2895
- return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
3005
+ // One bounded walk of the admitted TeX tree. This is Presentation MathML, not a
3006
+ // second grammar, a content-math inference engine or a public AST input API.
3007
+ const MATH_ML_OPAQUE_COLOR = /^(?:aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)$/i;
3008
+ const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3009
+ const MATH_ML_INVALID_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/u;
3010
+ function mathMLXML(value) {
3011
+ const text = String(value);
3012
+ if (MATH_ML_INVALID_XML.test(text))
3013
+ throw {code: 'invalid-semantic-character', offset: 0, message: 'A generated mathematical character is not valid XML.'};
3014
+ return text.replace(/[&<>"'\t\n\r]/g, character => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '\t': '&#9;', '\n': '&#10;', '\r': '&#13;'}[character]));
2896
3015
  }
2897
3016
 
2898
- function mathSourceAlternative(source) {
2899
- const alternatives=[],parts=[];
2900
- let first=-1,kept=0;
2901
- for(let i=0;i<source.length;i++) {
2902
- const code=source.charCodeAt(i);
2903
- if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
2904
- const next=source.charCodeAt(i+1);
2905
- if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
3017
+ function mathML(tree, source, safeSource, options = {}) {
3018
+ const metrics = {nodes: 0, depth: 0, outputCodeUnits: 0, links: 0};
3019
+ const diagnostics = [], codes = new Set(), active = new WeakSet();
3020
+ const sourceOmitted = source.length > 1000000 || !!safeSource?.error?.sourceOmitted;
3021
+ // HAST stringifiers can emit decoded CR literally; a subsequent HTML parse
3022
+ // normalizes it. ASCII custody survives that real host pipeline unchanged.
3023
+ const utf16 = sourceOmitted ? null : (safeSource?.utf16 ?? null);
3024
+ const encoding = sourceOmitted ? null : utf16 === null ? 'application/x-tex' : 'application/x-rapier-tex-utf16';
3025
+ const sourceInfo = {encoding, ...(sourceOmitted ? {omitted: true} : {})};
3026
+ let parts = [], length = 0, content = 0;
3027
+ const fail = (code, message) => { throw {code, message, offset: 0}; };
3028
+ const write = value => {
3029
+ length += value.length;
3030
+ if (length > 8 * 1024 * 1024) fail('resource-limit', 'MathML presentation exceeds its output budget.');
3031
+ parts.push(value);
3032
+ };
3033
+ const open = (name, attributes = {}) => {
3034
+ let value = '<' + name;
3035
+ for (const [key, item] of Object.entries(attributes)) if (item !== undefined)
3036
+ value += ' ' + key + '="' + mathMLXML(item) + '"';
3037
+ write(value + '>');
3038
+ };
3039
+ const close = name => write('</' + name + '>');
3040
+ const token = (name, value, attributes, context) => {
3041
+ open(name, attributes); write(mathMLXML(value)); close(name);
3042
+ if (!context?.phantom && !context?.transparent && /[^\p{White_Space}\p{Default_Ignorable_Code_Point}]/u.test(value)) content++;
3043
+ };
3044
+ const decimal = value => {
3045
+ if (!Number.isFinite(value)) fail('invalid-semantic-value', 'A mathematical dimension is not finite.');
3046
+ return String(Math.round(value * 1e6) / 1e6 || 0);
3047
+ };
3048
+ const em = value => decimal(value) + 'em';
3049
+ const warn = (code, message) => {
3050
+ if (!codes.has(code)) { codes.add(code); diagnostics.push({code, message, offset: 0}); }
3051
+ };
3052
+ const visit = (node, depth) => {
3053
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML traversal exceeds its work budget.');
3054
+ metrics.depth = Math.max(metrics.depth, depth);
3055
+ if (depth > 512) fail('resource-limit', 'MathML is nested too deeply.');
3056
+ if (!node || typeof node !== 'object') fail('unsupported-semantic-node', 'A mathematical part is missing.');
3057
+ };
3058
+ const family = node => {
3059
+ const role = node.semanticRole;
3060
+ if (role === 'chemistry') warn('semantic-chemistry-presentation', 'Chemical notation retains presentation structure; chemical element, bond, charge and reaction meanings are not inferred.');
3061
+ else if (role === 'physics') warn('semantic-physics-presentation', 'Physics notation retains its parsed mathematical relationships; physical and specialized operator meanings are not inferred.');
3062
+ else if (role === 'units') warn('semantic-units-presentation', 'Unit notation retains the parser-expanded mathematical structure; quantities and unit identities are not inferred.');
3063
+ else if (role === 'tag') warn('semantic-tag-presentation', 'An authored tag remains following content; no equation identity, numbering or cross-reference semantics are assigned.');
3064
+ };
3065
+ const scriptContext = context => ({...context, display: false, level: Math.min(2, context.level + 1)});
3066
+ const styledContext = (context, node) => {
3067
+ const next = {...context};
3068
+ if (node.variant) next.variant = node.variant;
3069
+ // Invalid names inherit the current color; they cannot prove visibility.
3070
+ if (/^(?:transparent|#[\da-f]{3}0|#[\da-f]{6}00)$/i.test(node.color || '')) next.transparent = true;
3071
+ else if (node.color && (/^#/.test(node.color) || MATH_ML_OPAQUE_COLOR.test(node.color))) next.transparent = false;
3072
+ if (node.absoluteSize !== undefined) next.size = node.absoluteSize;
3073
+ if (node.size !== undefined) next.size *= node.size;
3074
+ if (node.mathStyle) { next.display = node.mathStyle === 'display'; next.level = {display: 0, text: 0, script: 1, scriptscript: 2}[node.mathStyle]; }
3075
+ return next;
3076
+ };
3077
+ const variant = (node, context) => node.variant || (context.variant === 'normal' ? node.defaultVariant || (node.type === 'text' ? 'roman' : 'normal') : context.variant);
3078
+ const styledText = (value, face) => {
3079
+ // Native Core supports only mi mathvariant=normal. The shared pure Unicode
3080
+ // mapping keeps mathematical alphabets meaningful without loading the font.
3081
+ if (face === 'roman') return value;
3082
+ let result = '';
3083
+ for (const character of value) result += String.fromCodePoint(mathStyledCodePoint(character.codePointAt(0), face));
3084
+ return result;
3085
+ };
3086
+ const atom = (node, value, kind, context, attributes = {}) => {
3087
+ const face = variant(node, context);
3088
+ if (kind === 'mtext') {
3089
+ let css = '';
3090
+ if (face.includes('bold')) css += 'font-weight:700;';
3091
+ if (face.includes('italic')) css += 'font-style:italic;';
3092
+ if (face.includes('sans-serif')) css += 'font-family:sans-serif;';
3093
+ else if (face === 'monospace') css += 'font-family:monospace;';
3094
+ if (/script|fraktur|double-struck/.test(face)) {
3095
+ attributes.mathvariant = face;
3096
+ warn('semantic-text-variant', 'This text alphabet uses the MathML 3 mathvariant extension; a Core host may show ordinary text while preserving the text content.');
3097
+ }
3098
+ if (css) attributes.style = css;
3099
+ token(kind, value, attributes, context); return;
2906
3100
  }
2907
- if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
2908
- if(first<0)first=i;
2909
- if(i>kept)parts.push(source.slice(kept,i));
2910
- parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
2911
- // Flatten small batches instead of retaining one rope node per bad code unit.
2912
- if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
2913
- }
2914
- if(first<0)return {alternative:source};
2915
- parts.push(source.slice(kept));alternatives.push(parts.join(''));
2916
- // Only malformed XML text needs a separate carrier; each four hex digits keep one original code unit.
2917
- const encoded=[];parts.length=0;
2918
- for(let i=0;i<source.length;i++) {
2919
- parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
2920
- if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
2921
- }
2922
- encoded.push(parts.join(''));
2923
- return {alternative:alternatives.join(''),utf16:encoded.join(''),error:{code:'invalid-source-character',offset:first,
2924
- message:'A source character cannot be embedded in SVG. The text alternative shows Unicode escapes; data-tex-utf16 keeps the original source.'}};
2925
- }
3101
+ const styled = styledText(value, face);
3102
+ if (kind === 'mo' && context.movableLimits !== undefined) attributes.movablelimits = String(context.movableLimits);
3103
+ if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
3104
+ token(kind, styled, attributes, context);
3105
+ };
3106
+ const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ]$/.test(node.value) ? 'mi' :
3107
+ ['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
3108
+ /^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
3109
+ const classOf = node => {
3110
+ if (!node) return undefined;
3111
+ if (node.class) return node.class;
3112
+ if (node.type === 'scripts' || node.type === 'accent') return classOf(node.base);
3113
+ if (node.type === 'style' || node.type === 'link') return classOf(node.body);
3114
+ if (node.type === 'row' && node.children.length === 1) return classOf(node.children[0]);
3115
+ return 'ord';
3116
+ };
3117
+ const limitsOf = node => {
3118
+ if (!node) return undefined;
3119
+ if (node.limits) return node.limits;
3120
+ if (node.type === 'style' || node.type === 'link') return limitsOf(node.body);
3121
+ if (node.type === 'row' && node.children.length === 1) return limitsOf(node.children[0]);
3122
+ if (node.type === 'accent') return limitsOf(node.base);
3123
+ return undefined;
3124
+ };
3125
+ const plain = (node, depth, strict = false) => {
3126
+ visit(node, depth); family(node);
3127
+ if (strict && node.variant && node.variant !== 'roman') return null;
3128
+ if (node.type === 'text' || !strict && node.type === 'glyph') return node.value;
3129
+ if (node.type !== 'row') return null;
3130
+ const values = [];
3131
+ for (const child of node.children) {
3132
+ const value = plain(child, depth + 1, strict);
3133
+ if (value === null) return null;
3134
+ values.push(value);
3135
+ }
3136
+ return values.join('');
3137
+ };
3138
+ const fence = (value, form, context, size) => {
3139
+ if (value) token('mo', value, {fence: 'true', form, stretchy: 'true', symmetric: 'true', ...(size ? {minsize: em(size), maxsize: em(size)} : {})}, context);
3140
+ };
3141
+ const numberPart = node => node?.type === 'glyph' && !node.semanticRole && !node.tokenKind && !node.large && !node.delimiter &&
3142
+ !node.delimiterSize && (!node.class || node.class === 'ord') && /^[\p{Decimal_Number}.]$/u.test(node.value);
3143
+ const sameNumberStyle = (left, right) => left.variant === right.variant && left.defaultVariant === right.defaultVariant;
3144
+ const singleToken = node => {
3145
+ while (node?.type === 'row' && !node.semanticRole && node.children.length === 1) node = node.children[0];
3146
+ return node?.type === 'glyph' || node?.type === 'text' ? node : null;
3147
+ };
2926
3148
 
2927
- function renderMath(source,options={}) {
2928
- const text=String(source ?? '');
2929
- // Reject before scanning, escaping or parsing. Keep the diagnostic-return
2930
- // contract, but explicitly omit refused source instead of expanding it.
2931
- const safe=text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
2932
- code:'resource-limit',offset:0,sourceOmitted:true,
2933
- message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
2934
- }}:mathSourceAlternative(text),context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
2935
- try {
2936
- if(safe.error)throw safe.error;
2937
- if(options?.screen!==undefined) {
2938
- const {fontSize,pixelRatio,dark}=options.screen || {},scaled=Number.isFinite(fontSize)?fontSize*mathFontRatio:NaN;
2939
- if(!Number.isFinite(fontSize) || fontSize<=0 || !Number.isFinite(pixelRatio) || pixelRatio<=0 ||
2940
- typeof dark!=='boolean' || !Number.isFinite(scaled) || scaled<=0 || !Number.isFinite(scaled*pixelRatio) || scaled*pixelRatio<=0 ||
2941
- !Number.isFinite(1/scaled) || !Number.isFinite(1/pixelRatio) || !Number.isFinite(1/(scaled*pixelRatio)))
2942
- throw Object.assign(new Error('Screen font size, pixel ratio and device scale must be positive and finite; dark must be a boolean.'),{code:'invalid-screen'});
2943
- context.screen={fontSize:scaled,pixelRatio,dark};
3149
+ function scripts(node, context, depth, base) {
3150
+ const limits = node.limits || limitsOf(node.base), stacked = limits === 'always' || limits === 'display' && context.display && context.level === 0;
3151
+ const name = stacked ? node.sub && node.sup ? 'munderover' : node.sub ? 'munder' : 'mover' : node.sub && node.sup ? 'msubsup' : node.sub ? 'msub' : 'msup';
3152
+ open(name, stacked ? {accent: node.sup ? 'false' : undefined, accentunder: node.sub ? 'false' : undefined} : {});
3153
+ if (base) base(); else emit(node.base, {...context, form: undefined, movableLimits: stacked ? false : undefined}, depth + 1);
3154
+ if (node.sub) emit(node.sub, scriptContext(context), depth + 1);
3155
+ if (node.sup) emit(node.sup, scriptContext(context), depth + 1);
3156
+ close(name);
3157
+ }
3158
+
3159
+ function row(children, context, depth) {
3160
+ open('mrow');
3161
+ let previous;
3162
+ for (let index = 0; index < children.length; index++) {
3163
+ const node = children[index];
3164
+ if (numberPart(node)) {
3165
+ let end = index + 1;
3166
+ while (end < children.length && numberPart(children[end]) && sameNumberStyle(node, children[end])) end++;
3167
+ const scripted = children[end]?.type === 'scripts' && !children[end].semanticRole && numberPart(children[end].base) && sameNumberStyle(node, children[end].base) ? children[end] : null;
3168
+ const values = children.slice(index, end).map(child => child.value).join('') + (scripted ? scripted.base.value : '');
3169
+ // A malformed multi-dot run is not silently split into apparent decimal
3170
+ // numbers. Groups, explicit spaces, styles and scripts are hard borders.
3171
+ if (/^(?:\p{Decimal_Number}+(?:\.\p{Decimal_Number}*)?|\.\p{Decimal_Number}+)$/u.test(values)) {
3172
+ for (let at = index; at < end; at++) visit(children[at], depth + 1);
3173
+ if (scripted) {
3174
+ visit(scripted, depth + 1); visit(scripted.base, depth + 2);
3175
+ scripts(scripted, context, depth + 1, () => atom(node, values, 'mn', context)); end++;
3176
+ } else atom(node, values, 'mn', context);
3177
+ previous = 'ord'; index = end - 1; continue;
3178
+ }
3179
+ // Consume an invalid run in one pass. Reconsidering each suffix both
3180
+ // invents decimals (6.7.8 -> 6 . 7.8) and makes dot-only input quadratic.
3181
+ for (let at = index; at < end; at++) emit(children[at], context, depth + 1);
3182
+ if (scripted) { emit(scripted, context, depth + 1); end++; }
3183
+ previous = 'ord'; index = end - 1; continue;
3184
+ }
3185
+ let form;
3186
+ if (node.type === 'glyph' && node.class === 'bin')
3187
+ form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : 'infix';
3188
+ emit(node, {...context, form}, depth + 1);
3189
+ if (node.type !== 'space') previous = classOf(node);
3190
+ }
3191
+ close('mrow');
3192
+ }
3193
+
3194
+ function table(node, context, depth) {
3195
+ const rows = node.rows, columns = Math.max(node.align?.length || 0, node.pairs ? node.pairs * 2 : 0, ...rows.map(cells => cells.length));
3196
+ const insertions = node.columnInsertions || [], rules = (node.columnRules?.length || 0) + (node.rowRules?.length || 0);
3197
+ if (columns > 256 || rows.length > 2048 || rows.length * (columns + insertions.length) + rules > 100000)
3198
+ fail('resource-limit', 'MathML table composition exceeds its work budget.');
3199
+ for (const boundary of node.columnRules || []) if (!Number.isInteger(boundary) || boundary < 0 || boundary > columns)
3200
+ fail('invalid-rule', 'An array rule exceeds its columns.');
3201
+ for (const rule of node.rowRules || []) {
3202
+ const from = rule.from ?? 0, to = rule.to ?? columns;
3203
+ if (!Number.isInteger(rule.before) || rule.before < 0 || rule.before > rows.length || !Number.isInteger(from) ||
3204
+ !Number.isInteger(to) || from < 0 || from > to || to > columns)
3205
+ fail('invalid-rule', 'An array rule exceeds its cells.');
3206
+ }
3207
+ if (insertions.length || rules) warn('semantic-array-presentation', 'Array insertion content is preserved in adjacent cells; decorative row and column rules have no additional mathematical meaning and are omitted.');
3208
+ const before = Array.from({length: columns + 1}, () => []);
3209
+ for (const insertion of insertions) {
3210
+ if (!Number.isInteger(insertion.before) || insertion.before < 0 || insertion.before > columns)
3211
+ fail('invalid-alignment', 'A MathML array insertion exceeds its columns.');
3212
+ before[insertion.before].push(insertion.body);
3213
+ }
3214
+ const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
3215
+ const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(node.env);
3216
+ const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
3217
+ const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
3218
+ psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
3219
+ cases: ['{', ''], dcases: ['{', ''], rcases: ['', '}'], drcases: ['', '}']}[node.env];
3220
+ if (delimiters) { open('mrow'); fence(delimiters[0], 'prefix', context); }
3221
+ open('mtable', {displaystyle: String(cellContext.display), scriptlevel: String(cellContext.level), 'data-math-environment': node.env});
3222
+ for (let at = 0; at < rows.length; at++) {
3223
+ open('mtr');
3224
+ for (let column = 0; column < columns; column++) {
3225
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
3226
+ let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
3227
+ if (node.env === 'multline' && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
3228
+ open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
3229
+ open('mrow');
3230
+ for (const body of before[column]) emit(body, cellContext, depth + 1);
3231
+ if (rows[at][column]) emit(rows[at][column], cellContext, depth + 1);
3232
+ if (column === columns - 1) for (const body of before[columns]) emit(body, cellContext, depth + 1);
3233
+ close('mrow'); close('mtd');
3234
+ }
3235
+ close('mtr');
2944
3236
  }
2945
- const tree=parseMathTex(text),natural=mathLayout(tree,context),limit=Number(options?.maxWidth);
2946
- const maxWidth=Number.isFinite(limit) && limit>.1?limit:undefined;
2947
- const box=maxWidth && mathInkWidth(natural)>maxWidth-.05?mathResponsiveLayout(tree,context,maxWidth-.05,natural):natural;
2948
- return mathSvg(box,safe.alternative,undefined,undefined,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
3237
+ close('mtable');
3238
+ if (delimiters) { fence(delimiters[1], 'postfix', context); close('mrow'); }
3239
+ if (node.position || node.rowGaps?.some(value => value))
3240
+ warn('semantic-table-spacing', 'Table row and cell relationships are preserved; custom baseline placement and row gaps are not reproduced.');
2949
3241
  }
2950
- catch (cause) {
2951
- const message=String(cause.message || cause);
2952
- const error={code:cause.code || 'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,offset:Number.isFinite(cause.offset)?cause.offset:0};
2953
- if(message.length>1024)error.messageTruncated=true;
2954
- if(cause.sourceOmitted)error.sourceOmitted=true;
2955
- if(cause.command) {
2956
- error.command=String(cause.command).slice(0,128);
2957
- if(cause.command.length>128)error.commandTruncated=true;
2958
- }
2959
- // A diagnostic is visible, but remains distinct from a successfully typeset formula.
2960
- // Diagnostics have an explicit bound. Exact input stays in the source alternative.
2961
- const label=error.message.length>240?'This formula could not be rendered. The complete diagnostic is in its text description.':error.message.replace(/[^\x20-\x7e]/g,'?');
2962
- const diagnostic={...context,variant:'roman',size:0.8,budget:{nodes:0,outlineBytes:0}};
3242
+
3243
+ function emit(node, context, depth = 0) {
3244
+ visit(node, depth); family(node);
3245
+ if (active.has(node)) fail('unsupported-semantic-node', 'A mathematical tree contains a cycle.');
3246
+ active.add(node);
2963
3247
  try {
2964
- return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display,screen:context.screen});
2965
- } catch {
2966
- diagnostic.screen=undefined;
2967
- return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display});
2968
- }
3248
+ switch (node.type) {
3249
+ case 'row': row(node.children, context, depth); break;
3250
+ case 'glyph': {
3251
+ const name = kind(node), attributes = {};
3252
+ if (name === 'mo') {
3253
+ if (node.class === 'open' || node.class === 'close') { attributes.fence = 'true'; attributes.form = node.class === 'open' ? 'prefix' : 'postfix'; }
3254
+ else if (node.class === 'punct') attributes.separator = 'true';
3255
+ else if (context.form) attributes.form = context.form;
3256
+ if (node.large !== undefined) attributes.largeop = String(!!node.large);
3257
+ if (node.limits) attributes.movablelimits = String(node.limits === 'display');
3258
+ if (node.delimiter || node.delimiterSize || node.stretch) attributes.stretchy = 'true';
3259
+ else attributes.stretchy = 'false';
3260
+ if (node.delimiterSize) attributes.minsize = attributes.maxsize = em(node.delimiterSize);
3261
+ }
3262
+ atom(node, node.value, name, context, attributes); break;
3263
+ }
3264
+ case 'text': atom(node, node.value, ['op', 'bin', 'rel'].includes(node.class) ? 'mo' : 'mtext', context,
3265
+ node.class === 'op' ? {form: 'prefix', movablelimits: String(node.limits === 'display')} : {}); break;
3266
+ case 'space': open('mspace', {width: em(Math.max(0, node.width)), style: node.width < 0 ? 'margin-left:' + em(node.width) : undefined}); close('mspace'); break;
3267
+ case 'scripts': scripts(node, context, depth); break;
3268
+ case 'frac': {
3269
+ const local = node.style ? styledContext(context, {mathStyle: node.style}) : context;
3270
+ if (node.style) open('mstyle', {displaystyle: String(local.display), scriptlevel: String(local.level)});
3271
+ if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
3272
+ open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
3273
+ const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
3274
+ emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
3275
+ if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
3276
+ if (node.style) close('mstyle');
3277
+ if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
3278
+ break;
3279
+ }
3280
+ case 'root':
3281
+ open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
3282
+ if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
3283
+ close(node.index ? 'mroot' : 'msqrt'); break;
3284
+ case 'fence':
3285
+ open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, context, depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
3286
+ case 'accent': {
3287
+ if (node.overlay) {
3288
+ warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
3289
+ const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : 'updiagonalstrike';
3290
+ open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
3291
+ }
3292
+ const under = node.position === 'under', name = under ? 'munder' : 'mover';
3293
+ open(name, {[under ? 'accentunder' : 'accent']: 'true'}); emit(node.base, {...context, movableLimits: false}, depth + 1);
3294
+ token('mo', node.value, {stretchy: String(!!node.stretch)}, context); close(name); break;
3295
+ }
3296
+ case 'overunder': {
3297
+ const name = node.over && node.under ? 'munderover' : node.under ? 'munder' : 'mover';
3298
+ open(name, {accent: node.over ? 'false' : undefined, accentunder: node.under ? 'false' : undefined}); emit(node.base, {...context, movableLimits: false}, depth + 1);
3299
+ if (node.under) emit(node.under, scriptContext(context), depth + 1);
3300
+ if (node.over) emit(node.over, scriptContext(context), depth + 1);
3301
+ close(name); break;
3302
+ }
3303
+ case 'table': table(node, context, depth); break;
3304
+ case 'style': {
3305
+ const local = styledContext(context, node), attributes = {'data-math-class': node.class};
3306
+ if (node.mathStyle) { attributes.displaystyle = String(local.display); attributes.scriptlevel = String(local.level); }
3307
+ let css = '';
3308
+ if (node.absoluteSize !== undefined || node.size !== undefined) css += 'font-size:' + decimal(local.size / context.size) + 'em;';
3309
+ if (node.color) css += 'color:' + node.color + ';';
3310
+ if (node.background) css += 'background-color:' + node.background + ';';
3311
+ if (node.border) css += 'border:0.04em solid ' + node.border + ';padding:' + em(node.padding ?? .2) + ';';
3312
+ if (css) attributes.style = css;
3313
+ open('mstyle', attributes);
3314
+ if (node.tokenKind) {
3315
+ atom({variant: local.variant}, node.tokenText, node.tokenKind, local);
3316
+ } else if (node.operatorName) {
3317
+ const value = plain(node.body, depth + 1, true);
3318
+ if (value === null) {
3319
+ warn('semantic-rich-operator', 'A styled or mixed-math operator name retains its nested structure instead of becoming one plain operator token.');
3320
+ emit(node.body, local, depth + 1);
3321
+ } else atom({variant: 'roman'}, value, 'mo', local, {form: 'prefix', movablelimits: String(node.limits === 'display')});
3322
+ } else if (node.width !== undefined) {
3323
+ warn('semantic-layout-adjustment', 'A TeX layout adjustment retains its mathematical content with a bounded presentation approximation.');
3324
+ open('mpadded', {width: em(node.width)}); emit(node.body, local, depth + 1); close('mpadded');
3325
+ } else if (node.class) {
3326
+ const leaf = singleToken(node.body);
3327
+ if (leaf) emit({...leaf, class: node.class}, local, depth + 1);
3328
+ else {
3329
+ warn('semantic-atom-class', 'A compound expression retains its mathematical children; its TeX atom class does not create a single MathML operator.');
3330
+ emit(node.body, local, depth + 1);
3331
+ }
3332
+ } else emit(node.body, local, depth + 1);
3333
+ close('mstyle'); break;
3334
+ }
3335
+ case 'phantom': {
3336
+ const before = content;
3337
+ if (node.mode === 'h' || node.mode === 'v') open('mpadded', node.mode === 'h' ? {height: '0', depth: '0'} : {width: '0'});
3338
+ open('mphantom'); emit(node.body, {...context, phantom: true}, depth + 1); close('mphantom');
3339
+ if (node.mode === 'h' || node.mode === 'v') close('mpadded');
3340
+ content = before; break;
3341
+ }
3342
+ case 'smash':
3343
+ open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
3344
+ emit(node.body, context, depth + 1); close('mpadded'); break;
3345
+ case 'raise':
3346
+ open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
3347
+ emit(node.body, context, depth + 1); close('mpadded'); break;
3348
+ case 'rule':
3349
+ warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
3350
+ open('mspace', {width: em(node.width), height: em(node.height), depth: em(node.depth), style: 'background-color:currentColor'}); close('mspace');
3351
+ if (!context.phantom && !context.transparent && node.width > 0 && node.height + node.depth > 0) content++; break;
3352
+ case 'link': {
3353
+ if (context.inLink) fail('semantic-nested-link', 'Nested authored mathematical links cannot be represented as valid native HTML links.');
3354
+ if (context.phantom) fail('semantic-hidden-link', 'An authored link inside phantom content cannot become an invisible native focus target.');
3355
+ let url;
3356
+ try { url = new URL(node.href); } catch { fail('unsafe-link', 'A mathematical link has an invalid address.'); }
3357
+ if (!['http:', 'https:'].includes(url.protocol) || !/^https?:\/\/[^\s<>"'\\]+$/i.test(node.href))
3358
+ fail('unsafe-link', 'A mathematical link must use an HTTP or HTTPS address.');
3359
+ warn('semantic-link-embedding', 'The authored link uses native HTML inside MathML text, with a nested MathML expression; assistive-technology interaction depends on the host.');
3360
+ metrics.links++;
3361
+ open('mtext'); open('a', {xmlns: 'http://www.w3.org/1999/xhtml', href: node.href, title: node.href, target: '_blank', rel: 'noopener noreferrer'});
3362
+ const before = content;
3363
+ open('math', {xmlns: MATH_ML_NAMESPACE, display: 'inline'}); emit(node.body, {...context, inLink: true, display: false}, depth + 1);
3364
+ if (content === before) fail('semantic-empty-link', 'An authored mathematical link has no visible content for native focus.');
3365
+ close('math'); close('a'); close('mtext'); break;
3366
+ }
3367
+ default: fail('unsupported-semantic-node', 'Unsupported mathematical node for MathML.');
3368
+ }
3369
+ } finally { active.delete(node); }
2969
3370
  }
3371
+
3372
+ let status;
3373
+ try {
3374
+ if (sourceOmitted) fail('resource-limit', 'This formula is too long for MathML. Its source was not embedded; retain the original input.');
3375
+ if (options.error || safeSource?.error) throw options.error || safeSource.error;
3376
+ if (!tree) fail('unsupported-semantic-node', 'A parsed mathematical expression is required.');
3377
+ emit(tree, {display: !!options.displayMode, level: 0, size: 1, variant: 'normal', inLink: false});
3378
+ status = diagnostics.length ? 'presentation-fallback' : 'complete';
3379
+ } catch (cause) {
3380
+ const error = mathDiagnostic(cause);
3381
+ if (sourceOmitted) error.sourceOmitted = true;
3382
+ diagnostics.length = 0; diagnostics.push(error);
3383
+ status = 'refused'; metrics.links = 0;
3384
+ parts = ['<merror><mtext>Formula could not be represented as MathML.</mtext></merror>'];
3385
+ }
3386
+ const presentation = parts.join('');
3387
+ const annotation = sourceOmitted ? '' : encoding === 'application/x-tex' ?
3388
+ '<annotation encoding="application/x-tex">' + mathMLXML(source) + '</annotation>' :
3389
+ '<annotation encoding="text/plain">' + mathMLXML(safeSource.alternative) + '</annotation>' +
3390
+ '<annotation encoding="application/x-rapier-tex-utf16">' + utf16 + '</annotation>';
3391
+ const wrap = body => '<math xmlns="' + MATH_ML_NAMESPACE + '" display="' + (options.displayMode ? 'block' : 'inline') +
3392
+ '" data-rapier-mathml-status="' + status + '"' + (sourceOmitted ? ' data-math-source-omitted="true"' : '') +
3393
+ '><semantics>' + body + annotation + '</semantics></math>';
3394
+ // Source admission bounds escaping independently of the presentation budget:
3395
+ // at most 6M XML-escaped source, or 6M alternative plus 4M UTF-16 carrier.
3396
+ let mathml = wrap(presentation);
3397
+ if (mathml.length > 16 * 1024 * 1024) {
3398
+ status = 'refused'; metrics.links = 0;
3399
+ diagnostics.length = 0;
3400
+ diagnostics.push({code: 'resource-limit', offset: 0, message: 'Complete MathML exceeds its output budget.'});
3401
+ mathml = wrap('<merror><mtext>Formula could not be represented as MathML.</mtext></merror>');
3402
+ }
3403
+ metrics.outputCodeUnits = mathml.length;
3404
+ return {mathml, status, errors: diagnostics, metrics, source: sourceInfo};
2970
3405
  }
2971
3406
 
3407
+ // SPDX-License-Identifier: MIT
3408
+ function mathSemanticPrepared(prepared, options = {}) {
3409
+ const {text, safe, tree, error} = prepared;
3410
+ return mathML(tree, text, safe, {displayMode: !!options?.displayMode, error});
3411
+ }
3412
+ function mathToMathML(source, options = {}) {
3413
+ return mathSemanticPrepared(mathPrepare(source), options);
3414
+ }
3415
+
3416
+ // SPDX-License-Identifier: MIT
3417
+ // The prepared tree never crosses the public boundary. Both outputs consume it
3418
+ // within this call, before any result or caller-mutable parse tree is exposed.
3419
+ function mathRenderWithMathML(source, options = {}) {
3420
+ const prepared = mathPrepare(source), displayMode = !!options?.displayMode;
3421
+ const semantics = mathSemanticPrepared(prepared, {displayMode});
3422
+ return {...mathRenderPrepared(prepared, {...options, displayMode}), semantics};
3423
+ }
3424
+
3425
+ // SPDX-License-Identifier: MIT
2972
3426
  globalThis.RapierMath=Object.freeze({
2973
- version:'2.0.0',
2974
- parse:parseMathTex,
2975
- render:renderMath,
2976
- fit:mathFit,
2977
- observe:mathObserve,
2978
- renderToString(source,options) {return renderMath(source,options).svg;},
3427
+ version:'2.1.0', parse:parseMathTex,
3428
+ render:renderMath, renderToString:mathRenderToString,
3429
+ fit:mathFit, observe:mathObserve,
3430
+ toMathML:mathToMathML, renderWithMathML:mathRenderWithMathML,
2979
3431
  });
2980
3432
  })();