rapier-math 1.0.2 → 1.1.1

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 +23 -93
  2. package/dist/classic.d.ts +4 -0
  3. package/dist/delimiters.d.ts +8 -0
  4. package/dist/delimiters.mjs +39 -0
  5. package/dist/index.d.ts +43 -0
  6. package/{index.mjs → dist/index.mjs} +43 -15
  7. package/dist/integration.d.ts +9 -0
  8. package/dist/integration.mjs +28 -0
  9. package/dist/markdown-it.d.ts +6 -0
  10. package/dist/markdown-it.mjs +45 -0
  11. package/dist/markdown-rules.mjs +65 -0
  12. package/{rapier-math-1.0.2.js → dist/rapier-math.js} +43 -15
  13. package/dist/rehype.d.ts +6 -0
  14. package/dist/rehype.mjs +37 -0
  15. package/dist/stream.d.ts +14 -0
  16. package/dist/stream.mjs +46 -0
  17. package/docs/api.md +210 -0
  18. package/{math-components.json → docs/math-components.json} +7 -7
  19. package/docs/math-resources.json +290 -0
  20. package/examples/README.md +25 -0
  21. package/examples/browser.html +10 -0
  22. package/examples/browser.mjs +24 -0
  23. package/examples/formula.mjs +12 -0
  24. package/examples/markdown.mjs +9 -0
  25. package/examples/react.tsx +19 -0
  26. package/examples/stream.mjs +19 -0
  27. package/examples/unified.mjs +26 -0
  28. package/examples/worker.mjs +7 -0
  29. package/package.json +68 -19
  30. package/src/math/api.js +35 -13
  31. package/src/math/browser.js +7 -1
  32. package/src/math/layout.js +1 -1
  33. package/src/math/package-build.mjs +0 -13
  34. package/src/math/package-layout.mjs +17 -0
  35. package/src/math/package-readme.mjs +45 -0
  36. package/src/tools/build-math.mjs +48 -13
  37. package/tests/adoption.mjs +149 -0
  38. package/{check.mjs → tests/check.mjs} +29 -8
  39. package/tests/verify.mjs +46 -0
  40. package/LICENSE-MIT +0 -21
  41. package/math-LICENSE.txt +0 -21
  42. package/math-font-LICENSE.txt +0 -457
  43. package/src/math/package-verify.mjs +0 -40
  44. package/src/package.json +0 -9
  45. package/src/shell/math-resources.json +0 -105
  46. package/verify.mjs +0 -40
  47. /package/{src/math/FONT-SOURCE.md → docs/font-source.md} +0 -0
@@ -2311,7 +2311,7 @@ function mathLayout(n,c) {
2311
2311
  case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0};}
2312
2312
  case 'raise': {const b=mathLayout(n.body,c),s=mathScale(c);return mathCompose([[b,0,-n.amount*s]],b.w,{class:b.class,...(n.height===undefined?{}:{h:n.height*s}),...(n.depth===undefined?{}:{d:n.depth*s})});}
2313
2313
  case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
2314
- case 'link': {const b=mathLayout(n.body,c);const url=new URL(n.href);if(!['http:','https:'].includes(url.protocol))throw Object.assign(new Error('Unsupported equation link'),{code:'unsafe-url'});b.svg='<a href="'+mathEscape(n.href)+'" target="_blank" rel="noopener noreferrer">'+b.svg+'</a>';return b;}
2314
+ case 'link': {const b=mathLayout(n.body,c);const url=new URL(n.href);if(!['http:','https:'].includes(url.protocol))throw Object.assign(new Error('Unsupported equation link'),{code:'unsafe-url'});b.svg='<a href="'+mathEscape(n.href)+'" aria-label="'+mathEscape(n.href)+'" tabindex="0" target="_blank" rel="noopener noreferrer">'+b.svg+'</a>';return b;}
2315
2315
  default: throw Object.assign(new Error('Unsupported maths construct: '+n.type),{code:'unsupported-construct'});
2316
2316
  }
2317
2317
  }
@@ -2770,12 +2770,18 @@ function mathFitElement(svg, printing = false) {
2770
2770
  if(screenKey!==state.screen || (target===null)!==(state.width===null) || target!==null && Math.abs(target-state.width)>.005) {
2771
2771
  const rendered=renderMath(source,{displayMode:display,maxWidth:(screenKey!==state.screen?width:target) || undefined,screen});
2772
2772
  if(!rendered.errors.length) {
2773
+ const active=doc.activeElement,links=active && svg.contains(active)?[...svg.querySelectorAll('a')]:[];
2774
+ const focusIndex=links.indexOf(active),focusHref=focusIndex<0?null:active.getAttribute('href');
2773
2775
  const replacement=new view.DOMParser().parseFromString(rendered.svg,'image/svg+xml').documentElement;
2774
- for(const name of ['width','height','viewBox','data-math-natural-width','data-math-max-width','data-math-lines','data-math-screen']) {
2776
+ for(const name of ['role','width','height','viewBox','data-math-natural-width','data-math-max-width','data-math-lines','data-math-screen']) {
2775
2777
  if(replacement.hasAttribute(name))svg.setAttribute(name,replacement.getAttribute(name));else svg.removeAttribute(name);
2776
2778
  }
2777
2779
  svg.style.verticalAlign=replacement.style.verticalAlign;
2778
2780
  svg.replaceChildren(...Array.from(replacement.childNodes,node=>doc.importNode(node,true)));
2781
+ if(focusIndex>=0 && (!doc.activeElement || doc.activeElement===doc.body)) {
2782
+ const link=svg.querySelectorAll('a')[focusIndex];
2783
+ if(link?.getAttribute('href')===focusHref)link.focus({preventScroll:true});
2784
+ }
2779
2785
  state.natural=Number(svg.getAttribute('data-math-natural-width'));state.screen=screenKey;
2780
2786
  state.width=state.natural>width?width:null;
2781
2787
  if(state.width===null)svg.removeAttribute('data-math-max-width');
@@ -2871,23 +2877,27 @@ function mathSvg(box,source,error,utf16,options={}) {
2871
2877
  const opacity=options.screen?.dark ? .94 : 1;
2872
2878
  if (![width,height,depth,left,...viewBox].every(Number.isFinite)) throw new Error('Mathematical dimensions are not finite');
2873
2879
  const escapedSource=mathEscape(source);
2874
- const svg='<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="'+escapedSource+'"'+
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+'"'+
2875
2882
  ' data-rapier-math="'+(options.displayMode?'display':'inline')+'" data-math-lines="'+(box.lines || 1)+'"'+
2876
2883
  ' data-math-natural-width="'+mathNumber(options.naturalWidth ?? width)+'"'+
2877
2884
  (options.screen?' data-math-screen="'+mathNumber(options.screen.fontSize)+'|'+mathNumber(options.screen.pixelRatio)+'|'+options.screen.dark+'"':'')+
2878
2885
  (options.maxWidth?' data-math-max-width="'+mathNumber(options.maxWidth)+'"':'')+
2879
2886
  (utf16?' data-tex-utf16="'+utf16+'"':'')+
2887
+ (error?.sourceOmitted?' data-math-source-omitted="true"':'')+
2880
2888
  (error?' data-math-error="'+mathEscape(error.code)+'"':'')+' width="'+mathNumber(width)+'em" height="'+mathNumber(height+depth)+'em"'+
2881
2889
  ' viewBox="'+viewBox.map(mathNumber).join(' ')+'"'+
2882
2890
  ' style="font-size:'+mathNumber(mathFontRatio)+'em;max-width:100%;height:auto;vertical-align:-'+mathNumber(depth)+'em;'+
2883
2891
  'fill-opacity:'+opacity+';stroke-opacity:'+opacity+'" fill="currentColor">'+
2884
2892
  '<title>'+escapedSource+'</title>'+(error?'<desc>'+mathEscape(error.message)+'</desc>':'')+
2885
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'});
2886
2895
  return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
2887
2896
  }
2888
2897
 
2889
2898
  function mathSourceAlternative(source) {
2890
- let alternative='',first=-1,kept=0;
2899
+ const alternatives=[],parts=[];
2900
+ let first=-1,kept=0;
2891
2901
  for(let i=0;i<source.length;i++) {
2892
2902
  const code=source.charCodeAt(i);
2893
2903
  if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
@@ -2896,19 +2906,32 @@ function mathSourceAlternative(source) {
2896
2906
  }
2897
2907
  if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
2898
2908
  if(first<0)first=i;
2899
- alternative+=source.slice(kept,i)+'\\u'+code.toString(16).toUpperCase().padStart(4,'0');kept=i+1;
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;}
2900
2913
  }
2901
2914
  if(first<0)return {alternative:source};
2902
- alternative+=source.slice(kept);
2915
+ parts.push(source.slice(kept));alternatives.push(parts.join(''));
2903
2916
  // Only malformed XML text needs a separate carrier; each four hex digits keep one original code unit.
2904
- let utf16='';
2905
- for(let i=0;i<source.length;i++)utf16+=source.charCodeAt(i).toString(16).padStart(4,'0');
2906
- return {alternative,utf16,error:{code:'invalid-source-character',offset:first,
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,
2907
2924
  message:'A source character cannot be embedded in SVG. The text alternative shows Unicode escapes; data-tex-utf16 keeps the original source.'}};
2908
2925
  }
2909
2926
 
2910
2927
  function renderMath(source,options={}) {
2911
- const text=String(source ?? ''),safe=mathSourceAlternative(text),context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
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}};
2912
2935
  try {
2913
2936
  if(safe.error)throw safe.error;
2914
2937
  if(options?.screen!==undefined) {
@@ -2925,11 +2948,16 @@ function renderMath(source,options={}) {
2925
2948
  return mathSvg(box,safe.alternative,undefined,undefined,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
2926
2949
  }
2927
2950
  catch (cause) {
2928
- const error={code:cause.code || 'invalid-tex',message:String(cause.message || cause),offset:Number.isFinite(cause.offset)?cause.offset:0};
2929
- if(cause.command)error.command=cause.command;
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
+ }
2930
2959
  // A diagnostic is visible, but remains distinct from a successfully typeset formula.
2931
- // A hostile command can have a very long name. Keep its full diagnostic in desc/errors,
2932
- // while the visible notice stays finite and can render after the formula exhausted its budget.
2960
+ // Diagnostics have an explicit bound. Exact input stays in the source alternative.
2933
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,'?');
2934
2962
  const diagnostic={...context,variant:'roman',size:0.8,budget:{nodes:0,outlineBytes:0}};
2935
2963
  try {
@@ -2942,7 +2970,7 @@ function renderMath(source,options={}) {
2942
2970
  }
2943
2971
 
2944
2972
  globalThis.RapierMath=Object.freeze({
2945
- version:'1.0.2',
2973
+ version:'1.1.1',
2946
2974
  parse:parseMathTex,
2947
2975
  render:renderMath,
2948
2976
  fit:mathFit,
@@ -0,0 +1,6 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import type {Root} from 'hast';
3
+ import type {VFile} from 'vfile';
4
+ import type {IntegrationOptions} from './integration.js';
5
+ /** Install after sanitization. Recognizes remark-rehype math code nodes. */
6
+ export default function rehypeRapierMath(options?: IntegrationOptions): (tree: Root, file: VFile) => void;
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import {fromHtml} from 'hast-util-from-html';
3
+ import {createFormulaRenderer} from './integration.mjs';
4
+
5
+ // Run AFTER the host sanitizer. Only known math code nodes are replaced, using
6
+ // fresh renderer output parsed into HAST. Authored raw nodes never become HTML here.
7
+ export default function rehypeRapierMath(options = {}) {
8
+ return (tree, file) => {
9
+ const render = createFormulaRenderer(options);
10
+ function math(node) {
11
+ const names = node?.properties?.className;
12
+ if (node?.type !== 'element' || node.tagName !== 'code' || !Array.isArray(names) ||
13
+ !names.includes('language-math') || !names.some(name => name === 'math-inline' || name === 'math-display') ||
14
+ !Array.isArray(node.children) || !node.children.every(child => child.type === 'text' && typeof child.value === 'string')) return null;
15
+ return {source: node.children.map(child => child.value).join(''), display: names.includes('math-display')};
16
+ }
17
+ function visit(parent) {
18
+ for (let index = 0; index < (parent.children?.length || 0); index++) {
19
+ const node = parent.children[index];
20
+ const code = node.type === 'element' && node.tagName === 'pre' && node.children?.length === 1 ? node.children[0] : node;
21
+ const input = math(code);
22
+ if (!input) { visit(node); continue; }
23
+ const result = render(input.source, input.display);
24
+ if (result.errors.length) {
25
+ for (const error of result.errors) {
26
+ const message = file?.message(error.message, {place: code.position, source: 'rapier-math', ruleId: error.code});
27
+ if (message) { message.mathSource = input.source; message.mathOffset = error.offset; }
28
+ }
29
+ continue;
30
+ }
31
+ const svg = fromHtml(result.svg, {fragment: true}).children[0];
32
+ parent.children[index] = input.display ? {type: 'element', tagName: 'div', properties: {className: ['math-display']}, children: [svg]} : svg;
33
+ }
34
+ }
35
+ visit(tree);
36
+ };
37
+ }
@@ -0,0 +1,14 @@
1
+ // SPDX-License-Identifier: MIT
2
+ export interface MarkdownSnapshot {source: string; html: string; revision: number; final: boolean}
3
+ export interface MarkdownStream {
4
+ /** null means keep the previous preview; the chunk was still accepted. */
5
+ write(chunk: string): MarkdownSnapshot | null;
6
+ finish(): MarkdownSnapshot;
7
+ abort(): void;
8
+ /** Replace a message by resetting, then writing the replacement source. */
9
+ reset(): number;
10
+ readonly revision: number;
11
+ }
12
+ export function createMarkdownStream(renderMarkdown: (source: string) => string, options?: {
13
+ maxSourceLength?: number; previewEvery?: number;
14
+ }): MarkdownStream;
@@ -0,0 +1,46 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Full Markdown previews have no append-only promise. Geometric admission bounds
3
+ // the total source passed to a synchronous host, including the final batch pass.
4
+ export function createMarkdownStream(renderMarkdown, {maxSourceLength = 1_000_000, previewEvery = 256} = {}) {
5
+ if (typeof renderMarkdown !== 'function') throw new TypeError('Supply a synchronous Markdown renderer.');
6
+ for (const value of [maxSourceLength, previewEvery])
7
+ if (!Number.isSafeInteger(value) || value < 1) throw new RangeError('Stream limits must be positive finite integers.');
8
+ let chunks = [], length = 0, threshold = previewEvery, closed = false, revision = 0, rendering = false;
9
+ function open() {
10
+ if (closed || rendering) throw new Error(closed ? 'This stream is closed; reset it before writing.' : 'A stream renderer cannot reenter its stream.');
11
+ }
12
+ function snapshot(final) {
13
+ const source = chunks.join('');
14
+ chunks = source ? [source] : [];
15
+ // Failed previews consumed work too. Further chunks must still wait for the
16
+ // next geometric threshold; only an explicit finish retries immediately.
17
+ threshold = Math.max(previewEvery, length * 2);
18
+ rendering = true;
19
+ let html;
20
+ try {
21
+ html = renderMarkdown(source);
22
+ if (typeof html !== 'string') throw new TypeError('The Markdown renderer must return a string synchronously.');
23
+ } finally { rendering = false; }
24
+ if (final) { closed = true; chunks = []; length = 0; }
25
+ return {source, html, revision, final};
26
+ }
27
+ return {
28
+ write(chunk) {
29
+ open();
30
+ if (typeof chunk !== 'string') throw new TypeError('Decode transport bytes to strings before writing.');
31
+ if (chunk.length > maxSourceLength - length)
32
+ throw Object.assign(new RangeError('The message exceeds its source budget; this chunk was not accepted.'), {code: 'resource-limit'});
33
+ if (!chunk.length) return null;
34
+ chunks.push(chunk); length += chunk.length; revision++;
35
+ return length >= threshold ? snapshot(false) : null;
36
+ },
37
+ finish() { open(); revision++; return snapshot(true); },
38
+ abort() {
39
+ if (rendering) throw new Error('A stream renderer cannot abort its stream.');
40
+ if (closed) return;
41
+ chunks = []; length = 0; closed = true; revision++;
42
+ },
43
+ reset() { if (rendering) throw new Error('A stream renderer cannot reset its stream.'); chunks = []; length = 0; threshold = previewEvery; closed = false; return ++revision; },
44
+ get revision() { return revision; },
45
+ };
46
+ }
package/docs/api.md ADDED
@@ -0,0 +1,210 @@
1
+ # Rapier Math
2
+
3
+ Self-contained TeX-to-SVG maths with embedded Latin Modern outlines. Rendering is synchronous and offline,
4
+ with no core runtime dependencies, DOM, global installation or remote font request. Optional integrations
5
+ keep the host's Markdown parser in charge.
6
+
7
+ ## Start with a formula
8
+
9
+ ```sh
10
+ npm install rapier-math
11
+ ```
12
+
13
+ ```js
14
+ import {render} from 'rapier-math';
15
+ const source = String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`;
16
+ const result = render(source, {displayMode: true});
17
+ if (result.errors.length) console.error(result.errors);
18
+ else console.log(result.svg);
19
+ ```
20
+
21
+ Keep `source` for editing and copying. A formula API accepts TeX without Markdown delimiters.
22
+ `String.raw` helps with JavaScript literals; JSON and transport decoding are separate layers. Never unescape
23
+ the TeX a second time. Native ESM works in Node 22+, current browsers and module workers; no CommonJS wrapper
24
+ is provided. Server output needs no client renderer unless fitting or further rendering is wanted.
25
+
26
+ ## Markdown
27
+
28
+ ```sh
29
+ npm install markdown-it
30
+ ```
31
+
32
+ ```js
33
+ import MarkdownIt from 'markdown-it';
34
+ import rapierMath from 'rapier-math/markdown-it';
35
+ const md = new MarkdownIt({html: false}).use(rapierMath);
36
+ const env = {};
37
+ const html = md.render('Price $5. Code: `$$x$$`. Formula: \\(x^2\\).', env);
38
+ console.log(env.rapierMathErrors || []);
39
+ ```
40
+
41
+ Default delimiters are `\(...\)` (inline), `\[...\]` and `$$...$$` (display). Single `$...$` is opt-in:
42
+ `.use(rapierMath, {singleDollar: true})`. It cannot distinguish all currency from mathematics.
43
+
44
+ | Boundary rule | Contract |
45
+ | --- | --- |
46
+ | Escapes | An odd run of preceding backslashes escapes a delimiter; an even run does not. The body is never unescaped. |
47
+ | Dollar runs | Only complete runs of one or two dollars are delimiters. Three or more are literal. `\$$` is an escaped pair. |
48
+ | Single dollars | Nonempty body, no leading/trailing whitespace or CR/LF; a closer followed by an ASCII digit is rejected. |
49
+ | Other pairs | Whitespace and newlines are allowed. The first unescaped matching closer wins. No delimiter nesting. |
50
+ | Blocks | A display opener at the host's block start and a closer followed only by line whitespace makes a block. Otherwise it is inline content. |
51
+ | Incomplete input | No math node is emitted until a matching closer exists. Surrounding text stays under host control. |
52
+ | Protected source | Code spans, fences, indented code, link destinations, autolinks and HTML tags remain host syntax. Math in link labels is disabled. Math in image descriptions is retained as literal source in alt text. |
53
+
54
+ Use `html: false` for untrusted Markdown. If your application enables raw HTML, retain its sanitizer and
55
+ HTML policy. Inline HTML element contents follow the host grammar; the math adapter is not an HTML parser.
56
+ The `rapier-math/delimiters` export offers `createMathMatcher(source, options)(start, limit?)` for authors of
57
+ other host adapters. It indexes boundaries in a raw text region, returns exact UTF-16 offsets, and knows
58
+ nothing about Markdown structure. Do not scan rendered HTML with it.
59
+
60
+ The Rapier app explicitly keeps its established dollar-only dialect, including math in link labels.
61
+ The shared owner corrects escaped display closers and retains outer formula whitespace. No public
62
+ adapter or renderer imports the app's AGPL Markdown implementation.
63
+
64
+ ## unified / remark / rehype
65
+
66
+ Use `remark-math`, `remark-rehype`, then `rehype-sanitize`, then `rapier-math/rehype`, then `rehype-stringify`.
67
+ The complete [unified example](../examples/unified.mjs) grants only the math classes on sanitized code nodes.
68
+ The adapter replaces supported `language-math` + `math-inline`/`math-display` nodes with HAST parsed from
69
+ fresh renderer SVG. It does not turn authored raw HTML into trusted markup or loosen the global SVG sanitizer.
70
+ The optional `hast-util-from-html` peer is used only by this entrypoint.
71
+
72
+ Choose `remarkMath({singleDollarTextMath: false})` to avoid single-dollar ambiguity. Remark owns delimiter,
73
+ whitespace and code rules in this pipeline; its grammar is different from the markdown-it adapter and does
74
+ not enable backslash delimiters. Unsupported formulas remain copyable code and produce VFile messages
75
+ with `ruleId`, `mathOffset` and `mathSource`.
76
+
77
+ Both rendering adapters accept `renderOptions`, `maxFormulas` (default 1024) and `maxOutputLength` (default
78
+ 16 Mi UTF-16 code units of successful SVG per document render). Rendering a cached markdown-it token tree
79
+ again starts a fresh budget; inline children share their enclosing document's budget. Exhaustion leaves subsequent source literal with
80
+ diagnostics. The host owns its own source, tree, prose and final HTML budgets. These are synchronous adapters.
81
+
82
+ ## Streaming
83
+
84
+ ```js
85
+ import {createMarkdownStream} from 'rapier-math/stream';
86
+ const stream = createMarkdownStream(source => md.render(source, {}));
87
+ const preview = stream.write('The answer is \\(x'); // may return null
88
+ stream.write('^2\\).');
89
+ const completed = stream.finish(); // {source, html, revision, final: true}
90
+ ```
91
+
92
+ Use one stream per message. `write` accepts decoded strings and returns either a whole preview or `null`;
93
+ `finish` always runs the same batch renderer on the complete exact source. `abort` releases pending text.
94
+ `reset` starts a replacement and advances the revision. Cancel the old producer before reset, or reject its
95
+ chunks using your conversation generation. No callbacks, timers, DOM mutations or shared conversation state
96
+ are installed. See the [stream example](../examples/stream.mjs).
97
+
98
+ Markdown references, setext headings and fences can change earlier interpretation, so previews are
99
+ replaceable, not committed prefixes. An open formula remains literal. Defaults: at most 1,000,000 retained
100
+ source code units; first preview at 256 units, then only after the source has at least doubled. Including
101
+ one `finish`, the total source sent to the host is less than three times final length, even if previews fail.
102
+ Explicit retries of `finish` are additional host calls. There is no full-prefix
103
+ render on every token. Late previews are consequently less frequent; show incoming chunks as text for
104
+ immediate progress. `previewEvery` sets the first threshold, not a fixed per-chunk interval.
105
+
106
+ Retained state is O(message length), not a claimed constant-memory Markdown parser. Stream chunks can split
107
+ delimiters, CRLF, escapes or surrogate pairs. Final interpretation is batch-equivalent; interim previews
108
+ may show an incomplete code unit. A rejected oversized chunk is not accepted or silently truncated; the
109
+ caller still owns it. A failed renderer leaves accumulated source available for retry or reset.
110
+
111
+ ## Formula API and browser lifetime
112
+
113
+ | Export | Result |
114
+ | --- | --- |
115
+ | `render(tex, options?)` | `{svg, width, height, depth, lines, fitted, errors}`; dimensions in mathematical ems. |
116
+ | `renderToString(tex, options?)` | SVG, including diagnostic SVG for admitted malformed or unsupported syntax. |
117
+ | `parse(tex)` | Inspectable AST; throws structured errors. Internal node vocabulary can grow. |
118
+ | `fit(container)` | One synchronous DOM fitting pass, returning selected formula count. |
119
+ | `observe(container)` | Observe current formulas; returns idempotent cleanup. |
120
+ | `version` | The package version. Default export provides the same API. |
121
+
122
+ `displayMode`, `maxWidth` in mathematical ems, and optional `screen: {fontSize, pixelRatio, dark}` configure
123
+ rendering. Screen numbers must be positive finite values; `dark` must be boolean. Omit screen options for
124
+ SSR and the initial hydration render. Long rows break at available relations/operators; indivisible
125
+ oversized groups scale to fit. Fit after hydration, stop observation before replacement, then observe the
126
+ new formulas. Stop on unmount. [Browser](../examples/browser.html), [worker](../examples/worker.mjs) and
127
+ [React/SSR](../examples/react.tsx) examples demonstrate these boundaries. React is not a package dependency.
128
+
129
+ ## Errors, source and accessibility
130
+
131
+ Check `errors` before treating a formula as successful. Errors include `code`, `message`, UTF-16 `offset`
132
+ and sometimes `command`. Render-result messages are limited to 1024 code units plus an ellipsis and command
133
+ names to 128, with explicit `messageTruncated`/`commandTruncated` flags. Exact admitted source is retained
134
+ independently. `parse` throws the parser's details, bounded by its source admission limit. Do not use a
135
+ diagnostic message as a source archive.
136
+
137
+ Valid XML source is kept exactly in SVG `aria-label` and `title`, including BOM, tabs and CRLF (escaped as
138
+ character references). Invalid XML characters have visible Unicode escapes and a `data-tex-utf16` carrier:
139
+ each four hex digits represents one original UTF-16 code unit. This includes isolated surrogates. The
140
+ Markdown host may normalize its syntax-node content; retain the original Markdown separately. Streams
141
+ return the exact concatenated source, including malformed UTF-16, without normalization.
142
+
143
+ Source longer than 1,000,000 code units returns a bounded `resource-limit` diagnostic before source
144
+ scanning, escaping or parsing. Its error has `sourceOmitted: true` and its SVG has
145
+ `data-math-source-omitted="true"`; neither embeds or truncates the refused source. `renderToString` returns
146
+ the same diagnostic SVG. Keep the original input for editing or copying. Admitted source alternatives
147
+ remain exact. Other limits include 100,000 tokens, 50,000 parser nodes, depth 192, 4096 macro expansions, 100,000 layout
148
+ visits, 4 Mi outline characters and 8 Mi composed SVG characters. Complete returned SVG, including source
149
+ alternatives and diagnostics, is capped at 24 Mi UTF-16 code units. These are output/work bounds, not peak
150
+ heap or device-memory claims. A later good render has a fresh budget.
151
+
152
+ SVG labels contain raw TeX, not semantic MathML or mathematical speech. Ordinary equations are images in
153
+ the accessibility tree. Equations containing authored HTTP(S) links use a group so the links remain exposed;
154
+ each link is keyboard-focusable and labelled with its destination. Keep the editable source or a separate
155
+ copy-source affordance in your host. Full semantic navigation, speech and screen-reader parity are not
156
+ provided. A future semantic serializer needs an explicit AST-to-MathML mapping and assistive-technology
157
+ evaluation; adding a raw TeX label does not satisfy that requirement.
158
+
159
+ ## Security and deployment
160
+
161
+ The renderer emits local SVG outlines, never executable HTML, remote font/image fetches or loaded TeX
162
+ extensions. Authored links permit only HTTP(S) and use `noopener noreferrer`. Insert only the returned
163
+ SVG, never concatenate TeX or arbitrary HTML into the sink. On failure, use a text node or the framework's
164
+ escaped text rendering. Formula safety does not sanitize surrounding Markdown.
165
+
166
+ The native ESM path needs no `eval` or `unsafe-eval`. Generated SVG does contain style attributes:
167
+ `script-src 'self'; style-src-attr 'unsafe-inline'; style-src-elem 'none'` permits same-origin external
168
+ modules and those attributes in browsers implementing CSP3. It does **not** work under a policy forbidding
169
+ all inline styles. `examples/browser.html` carries that policy; older browsers need their own reviewed
170
+ style policy. No network access is needed after local module loading; use `connect-src 'none'` if suitable.
171
+
172
+ With `require-trusted-types-for 'script'`, string HTML sinks and the DOMParser used by `fit`/`observe`
173
+ require TrustedHTML. The core does not create a policy, return TrustedHTML or claim fitting support under
174
+ that policy. Prefer server-rendered output or the structured rehype path in such applications. If the host
175
+ uses a policy for initial insertion, narrowly scope it to freshly generated renderer output; never use a
176
+ blanket identity policy for arbitrary strings. The browser/React examples assume string sinks are permitted.
177
+
178
+ ## Syntax and limits
179
+
180
+ Supported: fractions, roots, scripts, limits, matrices/arrays/alignment, delimiters, accents, operators,
181
+ Greek and mathematical alphabets, text/color/size/spacing, local macros, and selected chemistry/physics.
182
+ Existing supported package names select built-in syntax; there is no external package/file loader.
183
+ This is not a complete TeX document engine. No automatic numbering or cross-formula reference guarantee.
184
+ Unsupported commands give diagnostics. Lowercase script/bold-script requests use ordinary-letter fallbacks
185
+ where Latin Modern lacks those alphabets. All embedded licensed outlines remain present.
186
+
187
+ ## Package and proof
188
+
189
+ Declarations accompany every public entry. Formula imports do not pull in Markdown, unified or React.
190
+ For TypeScript, markdown-it 15 provides its own types; markdown-it 14 projects also install
191
+ `@types/markdown-it@14`. Use the declarations for your host version.
192
+ For a classic script, use `dist/rapier-math.js` and `globalThis.RapierMath`.
193
+ The payload includes the font: it is not a few-kilobyte renderer. Payload counts below describe this
194
+ build, not npm tarball size or a comparison against another library.
195
+
196
+ Run `node tests/verify.mjs` and `node tests/check.mjs` from this checkout. The carried source rebuilds the exact
197
+ classic payload and ESM module; receipts also cover the adapters, declarations and examples. Follow
198
+ `docs/font-source.md` to regenerate font data. License and font provenance are carried with every build.
199
+
200
+ Verified-claim scope: synchronous self-contained formula rendering; opt-in Markdown integrations; bounded
201
+ replaceable previews with exact final source; structured diagnostics and explicit source fallback. This
202
+ does not establish all-device behavior, full TeX compatibility, semantic accessibility or universal
203
+ size/speed superiority. Test your host's sanitizer, CSP, browser lifetime and supported formula corpus.
204
+
205
+ ## Licenses
206
+
207
+ The renderer and neutral adapters are MIT. Latin Modern Math 1.959 outlines/metrics retain the GUST Font
208
+ License, an instance of LPPL. `LICENSE` contains both complete grants. `src/math/LICENSE-MIT`,
209
+ `src/math/FONT-LICENSE.txt` and the SPDX 2.3 `docs/math-components.json` retain renderer and font notices. Both payloads
210
+ retain complete licenses. App-specific AGPL source is not included in this package.
@@ -2,10 +2,10 @@
2
2
  "spdxVersion": "SPDX-2.3",
3
3
  "dataLicense": "CC0-1.0",
4
4
  "SPDXID": "SPDXRef-DOCUMENT",
5
- "name": "rapier-math-1.0.2",
6
- "documentNamespace": "https://rapier.website/spdx/rapier-math-1.0.2-55c326429ed51564670c67fb4e35eddbe4115fb077440146e4fbb5f81a247f9a",
5
+ "name": "rapier-math-1.1.1",
6
+ "documentNamespace": "https://rapier.website/spdx/rapier-math-1.1.1-050f4ebfb7c78beaefb01c9d6aa62192fd03757fc677134850bdb1f090033b81",
7
7
  "creationInfo": {
8
- "created": "2026-10-12T10:57:51.103Z",
8
+ "created": "2026-10-12T17:29:00Z",
9
9
  "creators": [
10
10
  "Tool: rapier-math-components",
11
11
  "Organization: rapier.website"
@@ -15,8 +15,8 @@
15
15
  {
16
16
  "name": "rapier-math",
17
17
  "SPDXID": "SPDXRef-rapier-math",
18
- "versionInfo": "1.0.2",
19
- "downloadLocation": "https://cdn.jsdelivr.net/gh/jackskip22/rapier-plugins@main/math/rapier-math-1.0.2.js",
18
+ "versionInfo": "1.1.1",
19
+ "downloadLocation": "NOASSERTION",
20
20
  "filesAnalyzed": false,
21
21
  "licenseConcluded": "MIT AND LicenseRef-GUST-Font-License",
22
22
  "licenseDeclared": "MIT AND LicenseRef-GUST-Font-License",
@@ -24,7 +24,7 @@
24
24
  "checksums": [
25
25
  {
26
26
  "algorithm": "SHA256",
27
- "checksumValue": "55c326429ed51564670c67fb4e35eddbe4115fb077440146e4fbb5f81a247f9a"
27
+ "checksumValue": "050f4ebfb7c78beaefb01c9d6aa62192fd03757fc677134850bdb1f090033b81"
28
28
  }
29
29
  ]
30
30
  },
@@ -43,7 +43,7 @@
43
43
  "checksumValue": "6075562b771f8b82f0c179e363389684f2dd09de30038269e2628e504bd7be0f"
44
44
  }
45
45
  ],
46
- "comment": "SVG outlines and OpenType MATH metrics; complete license in math-font-LICENSE.txt"
46
+ "comment": "SVG outlines and OpenType MATH metrics; complete license in src/math/FONT-LICENSE.txt"
47
47
  }
48
48
  ],
49
49
  "hasExtractedLicensingInfos": [