@memberjunction/ng-markdown 6.2.0-edge.3 → 6.2.0-edge.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/markdown.service.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,cAAc,EAEd,sBAAsB,EACtB,WAAW,EAEZ,MAAM,+BAA+B,CAAC;AAMvC,OAAO,qCAAqC,CAAC;AAC7C,OAAO,qCAAqC,CAAC;AAC7C,OAAO,8BAA8B,CAAC;AACtC,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC;AACvC,OAAO,8BAA8B,CAAC;AACtC,OAAO,iCAAiC,CAAC;AACzC,OAAO,iCAAiC,CAAC;AACzC,OAAO,+BAA+B,CAAC;AACvC,OAAO,iCAAiC,CAAC;AACzC,OAAO,+BAA+B,CAAC;AACvC,OAAO,mCAAmC,CAAC;AAC3C,OAAO,kCAAkC,CAAC;;AAuE1C,qBAGa,eAAe;IAC1B,OAAO,CAAC,MAAM,CAAwB;IACtC,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,aAAa,CAA0D;IAC/E,qGAAqG;IACrG,OAAO,CAAC,aAAa,CAAwB;IAC7C,2EAA2E;IAC3E,OAAO,CAAC,WAAW,CAAiC;IAEpD;;;OAGG;IACH,OAAO,CAAC,cAAc,CAUpB;;IAMF;;OAEG;IACI,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI;IAKpD,+CAA+C;IACxC,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI;IAIpD;;;;;OAKG;IACI,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,MAAM;IA2BxE,qCAAqC;IA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kBAAkB;IAoE1B;;;;OAIG;IACH,OAAO,CAAC,uBAAuB;yCAxlBpB,eAAe;6CAAf,eAAe;CAgnB3B"}
@@ -1,4 +1,5 @@
1
1
  import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
2
+ import katex from 'katex';
2
3
  import { MarkdownService } from './markdown.service';
3
4
  describe('MarkdownService (DOM)', () => {
4
5
  let service;
@@ -126,6 +127,154 @@ describe('MarkdownService (DOM)', () => {
126
127
  expect(loads).toBe(0);
127
128
  });
128
129
  });
130
+ describe('RenderMath', () => {
131
+ /** Parse through the real pipeline (sanitizer included) and mount it, as the component does. */
132
+ const mount = (markdown) => {
133
+ const container = document.createElement('div');
134
+ container.innerHTML = service.Parse(markdown);
135
+ return container;
136
+ };
137
+ const stubLoader = (impl) => {
138
+ service.loadKatex = impl;
139
+ };
140
+ it('typesets inline and display math as MathML with the real engine', async () => {
141
+ const container = mount('Energy $E = mc^2$ where\n\n$$\n\\frac{a}{b}\n$$');
142
+ expect(await service.RenderMath(container)).toBe(true);
143
+ const formulas = container.querySelectorAll('math');
144
+ expect(formulas.length).toBe(2);
145
+ expect(formulas[0].getAttribute('display')).toBeNull();
146
+ expect(formulas[1].getAttribute('display')).toBe('block');
147
+ expect(container.querySelector('mfrac')).not.toBeNull();
148
+ expect(container.querySelector('annotation')?.textContent).toBe('E = mc^2');
149
+ expect(container.querySelector('code.mj-math')).toBeNull();
150
+ });
151
+ it('spells styled letters with Unicode math characters, which Chrome renders (it ignores mathvariant)', async () => {
152
+ const container = mount('$\\mathbf{E} \\in \\mathbb{R}^3, \\mathcal{L}, \\mathfrak{H}, \\mathbf{0}, \\boldsymbol{\\alpha}$');
153
+ await service.RenderMath(container);
154
+ const identifiers = Array.from(container.querySelectorAll('mi, mn')).map((n) => n.textContent);
155
+ expect(identifiers).toEqual(expect.arrayContaining(['𝐄', 'ℝ', 'ℒ', 'ℌ', '𝟎']));
156
+ expect(container.querySelector('mi[mathvariant="bold"], mi[mathvariant="double-struck"]')).toBeNull();
157
+ // Greek has no Unicode form here: it keeps the attribute for the CSS bold fallback.
158
+ expect(container.querySelector('mi[mathvariant="bold-italic"]')?.textContent).toBe('α');
159
+ // The TeX source in the annotation is untouched.
160
+ expect(container.querySelector('annotation')?.textContent).toContain('\\mathbf{E}');
161
+ });
162
+ it('leaves TeX it cannot parse visible as source, and still typesets the rest', async () => {
163
+ const container = mount('Broken $\\frac{a$ but fine $x^2$');
164
+ expect(await service.RenderMath(container)).toBe(true);
165
+ const broken = container.querySelector('code.mj-math.mj-math-error');
166
+ expect(broken?.textContent).toBe('\\frac{a');
167
+ expect(broken?.getAttribute('title')).toBeTruthy();
168
+ expect(container.querySelectorAll('math').length).toBe(1);
169
+ });
170
+ it('leaves a formula that defines macros as source (expansion bombs)', async () => {
171
+ const container = mount('$\\def\\a{x x x}\\a\\a$ and $y$');
172
+ await service.RenderMath(container);
173
+ const kept = container.querySelector('code.mj-math.mj-math-error');
174
+ expect(kept?.textContent).toBe('\\def\\a{x x x}\\a\\a');
175
+ expect(kept?.getAttribute('title')).toContain('macros');
176
+ expect(container.querySelectorAll('math').length).toBe(1);
177
+ });
178
+ it('caps user sizes', async () => {
179
+ const container = mount('$\\rule{100000em}{100000em}$');
180
+ await service.RenderMath(container);
181
+ const rule = container.querySelector('mspace');
182
+ expect(parseFloat(rule?.getAttribute('width') ?? '0')).toBeLessThanOrEqual(20);
183
+ expect(parseFloat(rule?.getAttribute('height') ?? '0')).toBeLessThanOrEqual(20);
184
+ });
185
+ it('skips placeholders a newer render replaced while KaTeX was loading', async () => {
186
+ let release = () => undefined;
187
+ stubLoader(() => new Promise((resolve) => (release = resolve)));
188
+ const container = mount('$x^2$');
189
+ const pending = service.RenderMath(container);
190
+ container.innerHTML = service.Parse('$y^2$'); // the next streamed chunk
191
+ release(katex);
192
+ expect(await pending).toBe(false);
193
+ expect(container.querySelector('math')).toBeNull();
194
+ expect(container.querySelector('code.mj-math')?.textContent).toBe('y^2');
195
+ });
196
+ it('keeps \\href inert (trust is off)', async () => {
197
+ const container = mount('$\\href{javascript:alert(1)}{x}$');
198
+ await service.RenderMath(container);
199
+ // No link anywhere: the command shows as an unrendered "\href". The URL survives only
200
+ // as text inside <annotation>, which is the TeX source and never a link.
201
+ expect(container.querySelector('a, [href]')).toBeNull();
202
+ expect(container.querySelector('mtext')?.textContent).toBe('\\href');
203
+ });
204
+ it('never loads the engine when the document has no math', async () => {
205
+ let loads = 0;
206
+ stubLoader(async () => {
207
+ loads++;
208
+ throw new Error('the engine must not be fetched for a math-free document');
209
+ });
210
+ expect(await service.RenderMath(mount('It costs $5 and $10.'))).toBe(false);
211
+ expect(loads).toBe(0);
212
+ });
213
+ it('leaves the source showing when the lazy chunk cannot be loaded', async () => {
214
+ stubLoader(() => Promise.reject(new Error('chunk fetch failed')));
215
+ const container = mount('$x^2$');
216
+ expect(await service.RenderMath(container)).toBe(false);
217
+ expect(container.querySelector('code.mj-math')?.textContent).toBe('x^2');
218
+ });
219
+ it('does nothing at all when math is disabled by config', async () => {
220
+ let loads = 0;
221
+ stubLoader(async () => {
222
+ loads++;
223
+ throw new Error('the engine must not be fetched when math is disabled');
224
+ });
225
+ service.ConfigureMarked({ enableMath: false });
226
+ const container = mount('$x^2$');
227
+ expect(await service.RenderMath(container)).toBe(false);
228
+ expect(loads).toBe(0);
229
+ expect(container.textContent?.trim()).toBe('$x^2$');
230
+ });
231
+ });
232
+ describe('MathML markup', () => {
233
+ const MATHML_NS = 'http://www.w3.org/1998/Math/MathML';
234
+ const mount = (markdown) => {
235
+ const container = document.createElement('div');
236
+ container.innerHTML = service.Parse(markdown);
237
+ return container;
238
+ };
239
+ it('keeps a JATS formula as real MathML elements, prefixes removed', () => {
240
+ const c = mount('Loss <mml:math display="inline"><mml:mn>7</mml:mn><mml:mo>×</mml:mo><mml:msup><mml:mn>10</mml:mn><mml:mn>13</mml:mn></mml:msup></mml:math> per pulse.');
241
+ const msup = c.querySelector('msup');
242
+ expect(msup?.namespaceURI).toBe(MATHML_NS);
243
+ expect(msup?.textContent).toBe('1013');
244
+ expect(c.textContent).toContain('per pulse.');
245
+ });
246
+ it('keeps a table\'s column alignment and spacing (DOMPurify misspells one, lacks the other)', () => {
247
+ const c = mount('<math display="block"><mtable columnalign="right left" columnspacing="0em 2em"><mtr><mtd><mi>a</mi></mtd><mtd><mo>=</mo><mi>b</mi></mtd></mtr></mtable></math>');
248
+ const table = c.querySelector('mtable');
249
+ expect(table?.getAttribute('columnalign')).toBe('right left');
250
+ expect(table?.getAttribute('columnspacing')).toBe('0em 2em');
251
+ });
252
+ it('shows the formula once when MathML carries its TeX in an annotation (MathJax, Pandoc, Word)', () => {
253
+ const c = mount('<math><semantics><mrow><msup><mi>x</mi><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">x^2</annotation></semantics></math>');
254
+ expect(c.querySelector('msup')).not.toBeNull();
255
+ expect(c.textContent?.trim()).toBe('x2');
256
+ });
257
+ it('spells styled letters with Unicode math characters, as for typeset TeX', async () => {
258
+ const c = mount('<math><mi mathvariant="bold">E</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mn>3</mn></msup></math>');
259
+ await service.RenderMath(c);
260
+ expect(Array.from(c.querySelectorAll('mi')).map((n) => n.textContent)).toEqual(['𝐄', 'ℝ']);
261
+ });
262
+ // Known DOMPurify bypass shapes through MathML, plus the plain attribute and handler routes.
263
+ it.each([
264
+ ['javascript: href on a MathML element', '<math href="javascript:alert(1)"><mi xlink:href="javascript:alert(1)">x</mi></math>'],
265
+ ['maction with a script link', '<math><maction actiontype="statusline" xlink:href="javascript:alert(1)"><mi>x</mi></maction></math>'],
266
+ ['HTML inside annotation-xml', '<math><annotation-xml encoding="text/html"><img src="x" onerror="alert(1)"></annotation-xml></math>'],
267
+ ['mglyph/style namespace confusion', '<math><mtext><table><mglyph><style><img src="x" onerror="alert(1)">'],
268
+ ['form/math nesting confusion', '<form><math><mtext></form><form><mglyph><style></math><img src="x" onerror="alert(1)">'],
269
+ ['handlers on MathML elements', '<math onclick="alert(1)"><mi onmouseover="alert(1)">x</mi></math>'],
270
+ ])('strips %s', (_name, payload) => {
271
+ const c = mount(payload);
272
+ const attributes = Array.from(c.querySelectorAll('*')).flatMap((el) => Array.from(el.attributes));
273
+ expect(attributes.filter((a) => a.name.startsWith('on'))).toEqual([]);
274
+ expect(attributes.filter((a) => /javascript:/i.test(a.value))).toEqual([]);
275
+ expect(c.querySelector('script')).toBeNull();
276
+ });
277
+ });
129
278
  describe('parse sanitizes unless scripts are explicitly enabled', () => {
130
279
  it('strips handlers and script from passthrough HTML', () => {
131
280
  const out = service.parse('<div><img src="x" onerror="alert(1)"><script>alert(2)</script></div>', { enableHtml: true });
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.service.dom.test.js","sourceRoot":"","sources":["../../../src/lib/services/markdown.service.dom.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEzE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAmBrD,QAAQ,CAAC,uBAAuB,EAAE,GAAG,EAAE;IACrC,IAAI,OAAwB,CAAC;IAC7B,IAAI,MAAgC,CAAC;IAErC,UAAU,CAAC,GAAG,EAAE;QACd,OAAO,GAAG,IAAI,eAAe,EAAE,CAAC;QAChC,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE,CAAE,OAAqC,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAC7F,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE;QACrB,EAAE,CAAC,sCAAsC,EAAE,GAAG,EAAE;YAC9C,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,oCAAoC,EAAE,GAAG,EAAE;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E,GAAG,EAAE;YACzE,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';\nimport type { Mermaid } from 'mermaid';\nimport { MarkdownService } from './markdown.service';\n\n/**\n * jsdom specs for the web shell around @memberjunction/markdown-core.\n *\n * These focus on the browser-only concerns that stay in the Angular service:\n * the `parse()` entry points and the DOM-based `unwrapMiscodedHtml()` fixup.\n * The framework-agnostic parsing itself is covered in @memberjunction/markdown-core.\n *\n * `unwrapMiscodedHtml` is private, so we reach it through a typed cast — the same\n * pattern the markdown-core engine spec uses to poke the internal marked instance.\n * This keeps the assertions deterministic (exact HTML in, exact behavior out)\n * rather than depending on which fixtures marked happens to miscode.\n */\ntype UnwrapAccessor = { unwrapMiscodedHtml(html: string): string };\n\n/** Same private-member reach-in, for the lazily-loaded mermaid engine (see `loadMermaid`). */\ntype MermaidLoaderAccessor = { loadMermaid(): Promise<Mermaid> };\n\ndescribe('MarkdownService (DOM)', () => {\n let service: MarkdownService;\n let unwrap: (html: string) => string;\n\n beforeEach(() => {\n service = new MarkdownService();\n unwrap = (html: string) => (service as unknown as UnwrapAccessor).unwrapMiscodedHtml(html);\n });\n\n describe('parse', () => {\n it('returns empty string for empty input', () => {\n expect(service.parse('')).toBe('');\n });\n\n it('renders basic prose to a paragraph', () => {\n expect(service.parse('hello world')).toContain('<p>');\n });\n\n it('accepts per-call config overrides without throwing', () => {\n expect(() => service.parse('# Title', { enableHtml: true })).not.toThrow();\n });\n\n it('parseAsync resolves to the same output as parse', async () => {\n const md = '**bold**';\n expect(await service.parseAsync(md)).toBe(service.parse(md));\n });\n });\n\n describe('unwrapMiscodedHtml', () => {\n it('is a no-op when there are no <pre> blocks', () => {\n const html = '<p>just a paragraph</p>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('returns empty input unchanged', () => {\n expect(unwrap('')).toBe('');\n });\n\n it('skips content containing <svg (DOMParser would mangle SVG namespaces)', () => {\n const html = '<pre><code>&lt;svg&gt;&lt;rect/&gt;&lt;/svg&gt;</code></pre>';\n // Left untouched precisely because it contains \"<svg\".\n expect(unwrap(html)).toBe(html);\n });\n\n it('preserves an intentional code block that carries a language class', () => {\n const html = '<pre><code class=\"language-html\">&lt;div&gt;&lt;span&gt;x&lt;/span&gt;&lt;/div&gt;</code></pre>';\n const out = unwrap(html);\n // Language-classed code is an intentional example → NOT unwrapped.\n expect(out).toContain('language-html');\n expect(out).toContain('<pre>');\n });\n\n it('unwraps structural HTML that marked miscoded into a <pre><code> block', () => {\n // textContent decodes to <div><span>x</span></div> — multi-tag structural HTML.\n const html = '<pre><code>&lt;div&gt;&lt;span&gt;x&lt;/span&gt;&lt;/div&gt;</code></pre>';\n const out = unwrap(html);\n expect(out).toContain('<div>');\n expect(out).toContain('<span>x</span>');\n // The escaped code-block form must be gone.\n expect(out).not.toContain('&lt;div&gt;');\n expect(out).not.toContain('<pre>');\n });\n\n it('does not unwrap a single self-closing tag (needs 2+ tags to qualify)', () => {\n const html = '<pre><code>&lt;br&gt;</code></pre>';\n // tagCount < 2 → looksLikeStructuralHtml returns false → left as-is.\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not unwrap an empty code block', () => {\n const html = '<pre><code></code></pre>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not unwrap plain non-HTML code content', () => {\n const html = '<pre><code>const x = 1; // not html</code></pre>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not throw on malformed markup', () => {\n expect(() => unwrap('<pre><code>&lt;div&gt;&lt;span&gt;unclosed')).not.toThrow();\n });\n });\n\n describe('config accessors', () => {\n it('resetConfig restores enableHtml to the default (false)', () => {\n service.configureMarked({ enableHtml: true });\n expect(service.getConfig().enableHtml).toBe(true);\n service.resetConfig();\n expect(service.getConfig().enableHtml).toBe(false);\n });\n\n it('isLanguageSupported reflects Prism registration', () => {\n // typescript is imported by the service; a made-up language is not.\n expect(service.isLanguageSupported('typescript')).toBe(true);\n expect(service.isLanguageSupported('definitely-not-a-language')).toBe(false);\n });\n });\n\n describe('renderMermaid', () => {\n /** Stub the private lazy loader — the point of these specs is WHEN it is called, not what it returns. */\n const stubLoader = (impl: () => Promise<Mermaid>): void => {\n (service as unknown as MermaidLoaderAccessor).loadMermaid = impl;\n };\n\n const containerWith = (html: string): HTMLElement => {\n const container = document.createElement('div');\n container.innerHTML = html;\n return container;\n };\n\n it('never loads the diagram engine when the document has no diagram', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched for a diagram-free document');\n });\n\n const result = await service.renderMermaid(containerWith('<p>no diagrams here</p>'));\n\n expect(result).toBe(false);\n expect(loads).toBe(0);\n });\n\n it('shows a visible failure on every block when the lazy chunk cannot be loaded', async () => {\n stubLoader(() => Promise.reject(new Error('chunk fetch failed')));\n const container = containerWith(\n '<pre><code class=\"language-mermaid\">graph TD; A-->B;</code></pre>' +\n '<div class=\"mermaid\">graph TD; C-->D;</div>',\n );\n\n const result = await service.renderMermaid(container);\n\n expect(result).toBe(false);\n const failed = container.querySelectorAll('.mermaid-error');\n expect(failed.length).toBe(2);\n for (const element of Array.from(failed)) {\n expect(element.getAttribute('data-mermaid-error')).toBe('Diagram engine failed to load');\n }\n });\n\n it('does nothing at all when mermaid is disabled by config', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched when mermaid is disabled');\n });\n service.configureMarked({ enableMermaid: false });\n\n const result = await service.renderMermaid(\n containerWith('<pre><code class=\"language-mermaid\">graph TD; A-->B;</code></pre>'),\n );\n\n expect(result).toBe(false);\n expect(loads).toBe(0);\n });\n });\n\n describe('parse sanitizes unless scripts are explicitly enabled', () => {\n it('strips handlers and script from passthrough HTML', () => {\n const out = service.parse('<div><img src=\"x\" onerror=\"alert(1)\"><script>alert(2)</script></div>', { enableHtml: true });\n expect(out).not.toContain('onerror');\n expect(out).not.toContain('<script');\n expect(out).toContain('<img');\n });\n\n it('leaves script in place when enableJavaScript is true (the opt-out)', () => {\n const out = service.parse('<div>x</div><script>alert(1)</script>', { enableHtml: true, enableJavaScript: true });\n expect(out).toContain('<script>');\n });\n\n it('sanitizeHtml is exposed for consumers that bind parse() output themselves', () => {\n expect(service.sanitizeHtml('<a href=\"javascript:alert(1)\" onclick=\"x()\">x</a>')).toBe('<a>x</a>');\n });\n });\n\n describe('unwrapMiscodedHtml is inert and keeps leading style', () => {\n afterEach(() => vi.restoreAllMocks());\n const miscoded = '<pre><code>&lt;style&gt;.card{color:red}&lt;/style&gt;&lt;div class=\"card\"&gt;&lt;img src=\"x\" onerror=\"alert(1)\"&gt;&lt;p&gt;hi&lt;/p&gt;&lt;/div&gt;</code></pre>';\n\n it('never creates elements on the live document while unwrapping', () => {\n // Building the replacement on the live document would run image error handlers at\n // parse time, before parse() sanitizes the returned string.\n const createElement = vi.spyOn(document, 'createElement');\n unwrap(miscoded);\n expect(createElement).not.toHaveBeenCalled();\n });\n\n it('unwraps the structural HTML and keeps a leading <style>', () => {\n const out = unwrap(miscoded);\n expect(out).not.toContain('<pre>');\n expect(out).toContain('<style>.card{color:red}</style>');\n expect(out).toContain('<div class=\"card\">');\n });\n\n it('returns markup for parse() to sanitize rather than executing it', () => {\n expect(unwrap(miscoded)).toContain('onerror=\"alert(1)\"');\n });\n });\n});\n"]}
1
+ {"version":3,"file":"markdown.service.dom.test.js","sourceRoot":"","sources":["../../../src/lib/services/markdown.service.dom.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEzE,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAsBrD,QAAQ,CAAC,uBAAu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SAAS,CAAC,iCAAiC,CAAC,CAAC;YACzD,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,iEAAiE,EAAE,GAAG,EAAE;YACzE,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';\nimport type { Mermaid } from 'mermaid';\nimport katex from 'katex';\nimport { MarkdownService } from './markdown.service';\n\n/**\n * jsdom specs for the web shell around @memberjunction/markdown-core.\n *\n * These focus on the browser-only concerns that stay in the Angular service:\n * the `parse()` entry points and the DOM-based `unwrapMiscodedHtml()` fixup.\n * The framework-agnostic parsing itself is covered in @memberjunction/markdown-core.\n *\n * `unwrapMiscodedHtml` is private, so we reach it through a typed cast — the same\n * pattern the markdown-core engine spec uses to poke the internal marked instance.\n * This keeps the assertions deterministic (exact HTML in, exact behavior out)\n * rather than depending on which fixtures marked happens to miscode.\n */\ntype UnwrapAccessor = { unwrapMiscodedHtml(html: string): string };\n\n/** Same private-member reach-in, for the lazily-loaded mermaid engine (see `loadMermaid`). */\ntype MermaidLoaderAccessor = { loadMermaid(): Promise<Mermaid> };\n\n/** And for the lazily-loaded KaTeX engine (see `loadKatex`). */\ntype KatexLoaderAccessor = { loadKatex(): Promise<unknown> };\n\ndescribe('MarkdownService (DOM)', () => {\n let service: MarkdownService;\n let unwrap: (html: string) => string;\n\n beforeEach(() => {\n service = new MarkdownService();\n unwrap = (html: string) => (service as unknown as UnwrapAccessor).unwrapMiscodedHtml(html);\n });\n\n describe('parse', () => {\n it('returns empty string for empty input', () => {\n expect(service.parse('')).toBe('');\n });\n\n it('renders basic prose to a paragraph', () => {\n expect(service.parse('hello world')).toContain('<p>');\n });\n\n it('accepts per-call config overrides without throwing', () => {\n expect(() => service.parse('# Title', { enableHtml: true })).not.toThrow();\n });\n\n it('parseAsync resolves to the same output as parse', async () => {\n const md = '**bold**';\n expect(await service.parseAsync(md)).toBe(service.parse(md));\n });\n });\n\n describe('unwrapMiscodedHtml', () => {\n it('is a no-op when there are no <pre> blocks', () => {\n const html = '<p>just a paragraph</p>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('returns empty input unchanged', () => {\n expect(unwrap('')).toBe('');\n });\n\n it('skips content containing <svg (DOMParser would mangle SVG namespaces)', () => {\n const html = '<pre><code>&lt;svg&gt;&lt;rect/&gt;&lt;/svg&gt;</code></pre>';\n // Left untouched precisely because it contains \"<svg\".\n expect(unwrap(html)).toBe(html);\n });\n\n it('preserves an intentional code block that carries a language class', () => {\n const html = '<pre><code class=\"language-html\">&lt;div&gt;&lt;span&gt;x&lt;/span&gt;&lt;/div&gt;</code></pre>';\n const out = unwrap(html);\n // Language-classed code is an intentional example → NOT unwrapped.\n expect(out).toContain('language-html');\n expect(out).toContain('<pre>');\n });\n\n it('unwraps structural HTML that marked miscoded into a <pre><code> block', () => {\n // textContent decodes to <div><span>x</span></div> — multi-tag structural HTML.\n const html = '<pre><code>&lt;div&gt;&lt;span&gt;x&lt;/span&gt;&lt;/div&gt;</code></pre>';\n const out = unwrap(html);\n expect(out).toContain('<div>');\n expect(out).toContain('<span>x</span>');\n // The escaped code-block form must be gone.\n expect(out).not.toContain('&lt;div&gt;');\n expect(out).not.toContain('<pre>');\n });\n\n it('does not unwrap a single self-closing tag (needs 2+ tags to qualify)', () => {\n const html = '<pre><code>&lt;br&gt;</code></pre>';\n // tagCount < 2 → looksLikeStructuralHtml returns false → left as-is.\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not unwrap an empty code block', () => {\n const html = '<pre><code></code></pre>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not unwrap plain non-HTML code content', () => {\n const html = '<pre><code>const x = 1; // not html</code></pre>';\n expect(unwrap(html)).toBe(html);\n });\n\n it('does not throw on malformed markup', () => {\n expect(() => unwrap('<pre><code>&lt;div&gt;&lt;span&gt;unclosed')).not.toThrow();\n });\n });\n\n describe('config accessors', () => {\n it('resetConfig restores enableHtml to the default (false)', () => {\n service.configureMarked({ enableHtml: true });\n expect(service.getConfig().enableHtml).toBe(true);\n service.resetConfig();\n expect(service.getConfig().enableHtml).toBe(false);\n });\n\n it('isLanguageSupported reflects Prism registration', () => {\n // typescript is imported by the service; a made-up language is not.\n expect(service.isLanguageSupported('typescript')).toBe(true);\n expect(service.isLanguageSupported('definitely-not-a-language')).toBe(false);\n });\n });\n\n describe('renderMermaid', () => {\n /** Stub the private lazy loader — the point of these specs is WHEN it is called, not what it returns. */\n const stubLoader = (impl: () => Promise<Mermaid>): void => {\n (service as unknown as MermaidLoaderAccessor).loadMermaid = impl;\n };\n\n const containerWith = (html: string): HTMLElement => {\n const container = document.createElement('div');\n container.innerHTML = html;\n return container;\n };\n\n it('never loads the diagram engine when the document has no diagram', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched for a diagram-free document');\n });\n\n const result = await service.renderMermaid(containerWith('<p>no diagrams here</p>'));\n\n expect(result).toBe(false);\n expect(loads).toBe(0);\n });\n\n it('shows a visible failure on every block when the lazy chunk cannot be loaded', async () => {\n stubLoader(() => Promise.reject(new Error('chunk fetch failed')));\n const container = containerWith(\n '<pre><code class=\"language-mermaid\">graph TD; A-->B;</code></pre>' +\n '<div class=\"mermaid\">graph TD; C-->D;</div>',\n );\n\n const result = await service.renderMermaid(container);\n\n expect(result).toBe(false);\n const failed = container.querySelectorAll('.mermaid-error');\n expect(failed.length).toBe(2);\n for (const element of Array.from(failed)) {\n expect(element.getAttribute('data-mermaid-error')).toBe('Diagram engine failed to load');\n }\n });\n\n it('does nothing at all when mermaid is disabled by config', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched when mermaid is disabled');\n });\n service.configureMarked({ enableMermaid: false });\n\n const result = await service.renderMermaid(\n containerWith('<pre><code class=\"language-mermaid\">graph TD; A-->B;</code></pre>'),\n );\n\n expect(result).toBe(false);\n expect(loads).toBe(0);\n });\n });\n\n describe('RenderMath', () => {\n /** Parse through the real pipeline (sanitizer included) and mount it, as the component does. */\n const mount = (markdown: string): HTMLElement => {\n const container = document.createElement('div');\n container.innerHTML = service.Parse(markdown);\n return container;\n };\n\n const stubLoader = (impl: () => Promise<unknown>): void => {\n (service as unknown as KatexLoaderAccessor).loadKatex = impl;\n };\n\n it('typesets inline and display math as MathML with the real engine', async () => {\n const container = mount('Energy $E = mc^2$ where\\n\\n$$\\n\\\\frac{a}{b}\\n$$');\n\n expect(await service.RenderMath(container)).toBe(true);\n\n const formulas = container.querySelectorAll('math');\n expect(formulas.length).toBe(2);\n expect(formulas[0].getAttribute('display')).toBeNull();\n expect(formulas[1].getAttribute('display')).toBe('block');\n expect(container.querySelector('mfrac')).not.toBeNull();\n expect(container.querySelector('annotation')?.textContent).toBe('E = mc^2');\n expect(container.querySelector('code.mj-math')).toBeNull();\n });\n\n it('spells styled letters with Unicode math characters, which Chrome renders (it ignores mathvariant)', async () => {\n const container = mount('$\\\\mathbf{E} \\\\in \\\\mathbb{R}^3, \\\\mathcal{L}, \\\\mathfrak{H}, \\\\mathbf{0}, \\\\boldsymbol{\\\\alpha}$');\n\n await service.RenderMath(container);\n\n const identifiers = Array.from(container.querySelectorAll('mi, mn')).map((n) => n.textContent);\n expect(identifiers).toEqual(expect.arrayContaining(['𝐄', 'ℝ', 'ℒ', 'ℌ', '𝟎']));\n expect(container.querySelector('mi[mathvariant=\"bold\"], mi[mathvariant=\"double-struck\"]')).toBeNull();\n // Greek has no Unicode form here: it keeps the attribute for the CSS bold fallback.\n expect(container.querySelector('mi[mathvariant=\"bold-italic\"]')?.textContent).toBe('α');\n // The TeX source in the annotation is untouched.\n expect(container.querySelector('annotation')?.textContent).toContain('\\\\mathbf{E}');\n });\n\n it('leaves TeX it cannot parse visible as source, and still typesets the rest', async () => {\n const container = mount('Broken $\\\\frac{a$ but fine $x^2$');\n\n expect(await service.RenderMath(container)).toBe(true);\n\n const broken = container.querySelector('code.mj-math.mj-math-error');\n expect(broken?.textContent).toBe('\\\\frac{a');\n expect(broken?.getAttribute('title')).toBeTruthy();\n expect(container.querySelectorAll('math').length).toBe(1);\n });\n\n it('leaves a formula that defines macros as source (expansion bombs)', async () => {\n const container = mount('$\\\\def\\\\a{x x x}\\\\a\\\\a$ and $y$');\n\n await service.RenderMath(container);\n\n const kept = container.querySelector('code.mj-math.mj-math-error');\n expect(kept?.textContent).toBe('\\\\def\\\\a{x x x}\\\\a\\\\a');\n expect(kept?.getAttribute('title')).toContain('macros');\n expect(container.querySelectorAll('math').length).toBe(1);\n });\n\n it('caps user sizes', async () => {\n const container = mount('$\\\\rule{100000em}{100000em}$');\n\n await service.RenderMath(container);\n\n const rule = container.querySelector('mspace');\n expect(parseFloat(rule?.getAttribute('width') ?? '0')).toBeLessThanOrEqual(20);\n expect(parseFloat(rule?.getAttribute('height') ?? '0')).toBeLessThanOrEqual(20);\n });\n\n it('skips placeholders a newer render replaced while KaTeX was loading', async () => {\n let release: (engine: unknown) => void = () => undefined;\n stubLoader(() => new Promise((resolve) => (release = resolve)));\n const container = mount('$x^2$');\n\n const pending = service.RenderMath(container);\n container.innerHTML = service.Parse('$y^2$'); // the next streamed chunk\n release(katex);\n\n expect(await pending).toBe(false);\n expect(container.querySelector('math')).toBeNull();\n expect(container.querySelector('code.mj-math')?.textContent).toBe('y^2');\n });\n\n it('keeps \\\\href inert (trust is off)', async () => {\n const container = mount('$\\\\href{javascript:alert(1)}{x}$');\n\n await service.RenderMath(container);\n\n // No link anywhere: the command shows as an unrendered \"\\href\". The URL survives only\n // as text inside <annotation>, which is the TeX source and never a link.\n expect(container.querySelector('a, [href]')).toBeNull();\n expect(container.querySelector('mtext')?.textContent).toBe('\\\\href');\n });\n\n it('never loads the engine when the document has no math', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched for a math-free document');\n });\n\n expect(await service.RenderMath(mount('It costs $5 and $10.'))).toBe(false);\n expect(loads).toBe(0);\n });\n\n it('leaves the source showing when the lazy chunk cannot be loaded', async () => {\n stubLoader(() => Promise.reject(new Error('chunk fetch failed')));\n const container = mount('$x^2$');\n\n expect(await service.RenderMath(container)).toBe(false);\n expect(container.querySelector('code.mj-math')?.textContent).toBe('x^2');\n });\n\n it('does nothing at all when math is disabled by config', async () => {\n let loads = 0;\n stubLoader(async () => {\n loads++;\n throw new Error('the engine must not be fetched when math is disabled');\n });\n service.ConfigureMarked({ enableMath: false });\n\n const container = mount('$x^2$');\n\n expect(await service.RenderMath(container)).toBe(false);\n expect(loads).toBe(0);\n expect(container.textContent?.trim()).toBe('$x^2$');\n });\n });\n\n describe('MathML markup', () => {\n const MATHML_NS = 'http://www.w3.org/1998/Math/MathML';\n const mount = (markdown: string): HTMLElement => {\n const container = document.createElement('div');\n container.innerHTML = service.Parse(markdown);\n return container;\n };\n\n it('keeps a JATS formula as real MathML elements, prefixes removed', () => {\n const c = mount('Loss <mml:math display=\"inline\"><mml:mn>7</mml:mn><mml:mo>×</mml:mo><mml:msup><mml:mn>10</mml:mn><mml:mn>13</mml:mn></mml:msup></mml:math> per pulse.');\n const msup = c.querySelector('msup');\n expect(msup?.namespaceURI).toBe(MATHML_NS);\n expect(msup?.textContent).toBe('1013');\n expect(c.textContent).toContain('per pulse.');\n });\n\n it('keeps a table\\'s column alignment and spacing (DOMPurify misspells one, lacks the other)', () => {\n const c = mount('<math display=\"block\"><mtable columnalign=\"right left\" columnspacing=\"0em 2em\"><mtr><mtd><mi>a</mi></mtd><mtd><mo>=</mo><mi>b</mi></mtd></mtr></mtable></math>');\n const table = c.querySelector('mtable');\n expect(table?.getAttribute('columnalign')).toBe('right left');\n expect(table?.getAttribute('columnspacing')).toBe('0em 2em');\n });\n\n it('shows the formula once when MathML carries its TeX in an annotation (MathJax, Pandoc, Word)', () => {\n const c = mount('<math><semantics><mrow><msup><mi>x</mi><mn>2</mn></msup></mrow><annotation encoding=\"application/x-tex\">x^2</annotation></semantics></math>');\n expect(c.querySelector('msup')).not.toBeNull();\n expect(c.textContent?.trim()).toBe('x2');\n });\n\n it('spells styled letters with Unicode math characters, as for typeset TeX', async () => {\n const c = mount('<math><mi mathvariant=\"bold\">E</mi><mo>∈</mo><msup><mi mathvariant=\"double-struck\">R</mi><mn>3</mn></msup></math>');\n await service.RenderMath(c);\n expect(Array.from(c.querySelectorAll('mi')).map((n) => n.textContent)).toEqual(['𝐄', 'ℝ']);\n });\n\n // Known DOMPurify bypass shapes through MathML, plus the plain attribute and handler routes.\n it.each([\n ['javascript: href on a MathML element', '<math href=\"javascript:alert(1)\"><mi xlink:href=\"javascript:alert(1)\">x</mi></math>'],\n ['maction with a script link', '<math><maction actiontype=\"statusline\" xlink:href=\"javascript:alert(1)\"><mi>x</mi></maction></math>'],\n ['HTML inside annotation-xml', '<math><annotation-xml encoding=\"text/html\"><img src=\"x\" onerror=\"alert(1)\"></annotation-xml></math>'],\n ['mglyph/style namespace confusion', '<math><mtext><table><mglyph><style><img src=\"x\" onerror=\"alert(1)\">'],\n ['form/math nesting confusion', '<form><math><mtext></form><form><mglyph><style></math><img src=\"x\" onerror=\"alert(1)\">'],\n ['handlers on MathML elements', '<math onclick=\"alert(1)\"><mi onmouseover=\"alert(1)\">x</mi></math>'],\n ])('strips %s', (_name, payload) => {\n const c = mount(payload);\n const attributes = Array.from(c.querySelectorAll('*')).flatMap((el) => Array.from(el.attributes));\n expect(attributes.filter((a) => a.name.startsWith('on'))).toEqual([]);\n expect(attributes.filter((a) => /javascript:/i.test(a.value))).toEqual([]);\n expect(c.querySelector('script')).toBeNull();\n });\n });\n\n describe('parse sanitizes unless scripts are explicitly enabled', () => {\n it('strips handlers and script from passthrough HTML', () => {\n const out = service.parse('<div><img src=\"x\" onerror=\"alert(1)\"><script>alert(2)</script></div>', { enableHtml: true });\n expect(out).not.toContain('onerror');\n expect(out).not.toContain('<script');\n expect(out).toContain('<img');\n });\n\n it('leaves script in place when enableJavaScript is true (the opt-out)', () => {\n const out = service.parse('<div>x</div><script>alert(1)</script>', { enableHtml: true, enableJavaScript: true });\n expect(out).toContain('<script>');\n });\n\n it('sanitizeHtml is exposed for consumers that bind parse() output themselves', () => {\n expect(service.sanitizeHtml('<a href=\"javascript:alert(1)\" onclick=\"x()\">x</a>')).toBe('<a>x</a>');\n });\n });\n\n describe('unwrapMiscodedHtml is inert and keeps leading style', () => {\n afterEach(() => vi.restoreAllMocks());\n const miscoded = '<pre><code>&lt;style&gt;.card{color:red}&lt;/style&gt;&lt;div class=\"card\"&gt;&lt;img src=\"x\" onerror=\"alert(1)\"&gt;&lt;p&gt;hi&lt;/p&gt;&lt;/div&gt;</code></pre>';\n\n it('never creates elements on the live document while unwrapping', () => {\n // Building the replacement on the live document would run image error handlers at\n // parse time, before parse() sanitizes the returned string.\n const createElement = vi.spyOn(document, 'createElement');\n unwrap(miscoded);\n expect(createElement).not.toHaveBeenCalled();\n });\n\n it('unwraps the structural HTML and keeps a leading <style>', () => {\n const out = unwrap(miscoded);\n expect(out).not.toContain('<pre>');\n expect(out).toContain('<style>.card{color:red}</style>');\n expect(out).toContain('<div class=\"card\">');\n });\n\n it('returns markup for parse() to sanitize rather than executing it', () => {\n expect(unwrap(miscoded)).toContain('onerror=\"alert(1)\"');\n });\n });\n});\n"]}
@@ -36,8 +36,10 @@ import * as i0 from "@angular/core";
36
36
  * into other packages' DOMPurify usage, and so the configuration is parsed once instead
37
37
  * of on every render.
38
38
  *
39
- * Profile: HTML + SVG + SVG filters, which keeps structural markup, inline styles, data
40
- * attributes and inline vector graphics and removes the script vectors. Deviations from
39
+ * Profile: HTML + SVG + SVG filters + MathML, which keeps structural markup, inline styles, data
40
+ * attributes, inline vector graphics and formulas written as MathML, and removes the script vectors.
41
+ * MathML is DOMPurify's own profile, with its namespace checks (the mXSS class of bypasses through
42
+ * `<math>` is what those checks exist for). Deviations from
41
43
  * DOMPurify's defaults, each deliberate:
42
44
  * - FORCE_BODY: a document that starts with `<style>` keeps it (otherwise the parser hoists
43
45
  * a leading style element into <head> and it is dropped); agent-authored mockups start
@@ -47,6 +49,13 @@ import * as i0 from "@angular/core";
47
49
  * heading ids produce. This app does not read globals off `window` by element id, so
48
50
  * DOM clobbering has no effect here, and heading anchors matter.
49
51
  * - `target` on links is kept, with `rel="noopener noreferrer"` enforced when it is set.
52
+ * - `columnalign` and `columnspacing` are added: DOMPurify's MathML list spells the first
53
+ * `columnsalign` and lacks the second, so MathML tables lost their layout in Firefox and Safari
54
+ * (Chrome ignores both; the component stylesheet aligns columns there). Both are presentational. (`form` on `<mo>` stays out: on HTML it associates an element with a form, and
55
+ * MathML infers an operator's form without it.)
56
+ * - `annotation` / `annotation-xml` content is dropped with the element. DOMPurify removes both but
57
+ * would keep their text, and MathJax, Pandoc and Word MathML carry the TeX source there, so a
58
+ * formula would read "x2x^2".
50
59
  * - `<use>` is allowed only with a same-document reference (`#id`); external references
51
60
  * are removed. SMIL `<animate>`/`<set>` stay disallowed: they can rewrite `href`.
52
61
  */
@@ -60,9 +69,10 @@ function getPurifier() {
60
69
  if (!instance.isSupported)
61
70
  return null;
62
71
  instance.setConfig({
63
- USE_PROFILES: { html: true, svg: true, svgFilters: true },
72
+ USE_PROFILES: { html: true, svg: true, svgFilters: true, mathMl: true },
64
73
  ADD_TAGS: ['use'],
65
- ADD_ATTR: ['target'],
74
+ ADD_ATTR: ['target', 'columnalign', 'columnspacing'],
75
+ ADD_FORBID_CONTENTS: ['annotation', 'annotation-xml'],
66
76
  FORCE_BODY: true,
67
77
  SANITIZE_DOM: false,
68
78
  });
@@ -90,6 +100,75 @@ function getPurifier() {
90
100
  purifier = instance;
91
101
  return purifier;
92
102
  }
103
+ /**
104
+ * Unicode's Mathematical Alphanumeric Symbols by MathML `mathvariant`: the code points of capital
105
+ * A, small a and digit 0 (0 where Unicode has no digits in that style).
106
+ */
107
+ const MATH_LETTER_BASES = {
108
+ bold: [0x1d400, 0x1d41a, 0x1d7ce],
109
+ italic: [0x1d434, 0x1d44e, 0],
110
+ 'bold-italic': [0x1d468, 0x1d482, 0],
111
+ script: [0x1d49c, 0x1d4b6, 0],
112
+ 'bold-script': [0x1d4d0, 0x1d4ea, 0],
113
+ fraktur: [0x1d504, 0x1d51e, 0],
114
+ 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
115
+ 'bold-fraktur': [0x1d56c, 0x1d586, 0],
116
+ 'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2],
117
+ 'bold-sans-serif': [0x1d5d4, 0x1d5ee, 0x1d7ec],
118
+ 'sans-serif-italic': [0x1d608, 0x1d622, 0],
119
+ 'sans-serif-bold-italic': [0x1d63c, 0x1d656, 0],
120
+ monospace: [0x1d670, 0x1d68a, 0x1d7f6],
121
+ };
122
+ /** Letters Unicode encoded (in Letterlike Symbols) before that block existed; it has holes where they would go. */
123
+ const MATH_LETTER_HOLES = {
124
+ 'italic h': 'ℎ',
125
+ 'script B': 'ℬ', 'script E': 'ℰ', 'script F': 'ℱ', 'script H': 'ℋ', 'script I': 'ℐ', 'script L': 'ℒ',
126
+ 'script M': 'ℳ', 'script R': 'ℛ', 'script e': 'ℯ', 'script g': 'ℊ', 'script o': 'ℴ',
127
+ 'fraktur C': 'ℭ', 'fraktur H': 'ℌ', 'fraktur I': 'ℑ', 'fraktur R': 'ℜ', 'fraktur Z': 'ℨ',
128
+ 'double-struck C': 'ℂ', 'double-struck H': 'ℍ', 'double-struck N': 'ℕ', 'double-struck P': 'ℙ',
129
+ 'double-struck Q': 'ℚ', 'double-struck R': 'ℝ', 'double-struck Z': 'ℤ',
130
+ };
131
+ function toMathLetter(char, variant) {
132
+ const hole = MATH_LETTER_HOLES[`${variant} ${char}`];
133
+ if (hole)
134
+ return hole;
135
+ const bases = MATH_LETTER_BASES[variant];
136
+ if (!bases)
137
+ return null;
138
+ const code = char.charCodeAt(0);
139
+ if (code >= 65 && code <= 90)
140
+ return String.fromCodePoint(bases[0] + code - 65);
141
+ if (code >= 97 && code <= 122)
142
+ return String.fromCodePoint(bases[1] + code - 97);
143
+ if (code >= 48 && code <= 57 && bases[2])
144
+ return String.fromCodePoint(bases[2] + code - 48);
145
+ return null;
146
+ }
147
+ /**
148
+ * Chrome lays out MathML Core, which honors `mathvariant` only as "normal". KaTeX writes
149
+ * \mathbf{E} as `<mi mathvariant="bold">E</mi>` and \mathbb{R} as `mathvariant="double-struck"`,
150
+ * so Chrome would show plain letters, losing the difference between a vector and a scalar. MathML
151
+ * Core's own answer is to spell such letters with their Unicode math characters (𝐄, ℝ), which every
152
+ * browser renders. Identifiers and numbers only; anything without a Unicode form (Greek, text runs)
153
+ * keeps its attribute and gets the CSS fallback in the component stylesheet.
154
+ */
155
+ function useUnicodeMathLetters(root) {
156
+ root.querySelectorAll('mi[mathvariant], mn[mathvariant]').forEach((node) => {
157
+ const variant = node.getAttribute('mathvariant') ?? '';
158
+ const text = node.textContent ?? '';
159
+ const letters = Array.from(text, (char) => toMathLetter(char, variant));
160
+ if (text && letters.every((letter) => letter !== null)) {
161
+ node.textContent = letters.join('');
162
+ node.removeAttribute('mathvariant');
163
+ }
164
+ });
165
+ }
166
+ /**
167
+ * TeX that defines macros. KaTeX's `maxExpand` counts expansions, not output, so three kilobytes of
168
+ * `\def` can expand to half a million MathML nodes and freeze the tab, again on every streamed
169
+ * chunk. A rendered answer has no use for its own macros, so such formulas stay source.
170
+ */
171
+ const TEX_MACRO_DEFINITION = /\\(?:[gex]?def|let|futurelet|newcommand|renewcommand|providecommand)(?![a-zA-Z])/;
93
172
  export class MarkdownService {
94
173
  constructor() {
95
174
  this.engine = new MarkdownEngine();
@@ -100,6 +179,10 @@ export class MarkdownService {
100
179
  this.mermaidEngine = null;
101
180
  /** In-flight load, so N diagrams in one document share ONE chunk fetch. */
102
181
  this.mermaidLoad = null;
182
+ /** The KaTeX engine, once its lazy chunk has landed. Null until a formula is actually typeset. */
183
+ this.katexEngine = null;
184
+ /** In-flight load, so N formulas in one document share ONE chunk fetch. */
185
+ this.katexLoad = null;
103
186
  /**
104
187
  * Prism-backed highlight function injected into the core engine. The engine
105
188
  * itself has no Prism dependency — it calls this for the HTML output path.
@@ -306,6 +389,99 @@ export class MarkdownService {
306
389
  async renderMermaid(container) {
307
390
  return this.RenderMermaid(container);
308
391
  }
392
+ /**
393
+ * Fetch the KaTeX engine, on first use only. A dynamic `import()` under the "genuine bundle-size
394
+ * deferral" allowance (typescript-style rules, category 3), like {@link loadMermaid}: KaTeX is
395
+ * 277 KB minified (76 KB gzipped), and documents with no math never download it. A failed load
396
+ * clears the cached promise so a later render can retry.
397
+ */
398
+ async loadKatex() {
399
+ if (this.katexEngine) {
400
+ return this.katexEngine;
401
+ }
402
+ this.katexLoad ??= import('katex').then((module) => module.default);
403
+ try {
404
+ this.katexEngine = await this.katexLoad;
405
+ return this.katexEngine;
406
+ }
407
+ catch (error) {
408
+ this.katexLoad = null;
409
+ throw error;
410
+ }
411
+ }
412
+ /**
413
+ * Spell MathML's styled letters (`mathvariant="bold"`, `"double-struck"`, ...) with their Unicode
414
+ * math characters, which Chrome renders. `RenderMath` already does this; call it on its own when
415
+ * math is off, because MathML that arrived as markup still renders then.
416
+ *
417
+ * @param container The DOM element containing the MathML
418
+ */
419
+ UseUnicodeMathLetters(container) {
420
+ useUnicodeMathLetters(container);
421
+ }
422
+ /**
423
+ * Typeset TeX math in a container: every `code.mj-math` placeholder that markdown-core's
424
+ * math extension emitted. Call this after the HTML has been inserted into the DOM. MathML that
425
+ * arrived as markup is already rendered by the browser; it only gets the letter fix below.
426
+ *
427
+ * The output is MathML, which current browsers lay out natively, so hosts need no KaTeX
428
+ * stylesheet or fonts. KaTeX builds the nodes itself from the TeX text (no HTML string is
429
+ * parsed) and runs with `trust` off, so `\href`, `\url` and `\includegraphics` stay inert.
430
+ * A formula KaTeX cannot parse, one that defines macros, or an engine that fails to load leaves
431
+ * the TeX source showing as code. User sizes are capped at 20em.
432
+ *
433
+ * Whether math is on is the caller's decision (`<mj-markdown>` checks its `EnableMath` input):
434
+ * this service is a root singleton whose config the last-rendered component set, so it is no
435
+ * guide to the container in hand. Without math enabled at parse time there are no placeholders.
436
+ *
437
+ * @param container The DOM element containing the math placeholders
438
+ * @returns true if at least one TeX formula was typeset
439
+ */
440
+ async RenderMath(container) {
441
+ // MathML that arrived as markup (a formula from a JATS article) needs the same Chrome fix as
442
+ // KaTeX's output, and no engine.
443
+ useUnicodeMathLetters(container);
444
+ // Find the placeholders BEFORE touching the engine: no math, no chunk fetch.
445
+ const placeholders = container.querySelectorAll('code.mj-math');
446
+ if (placeholders.length === 0)
447
+ return false;
448
+ let engine;
449
+ try {
450
+ engine = await this.loadKatex();
451
+ }
452
+ catch (error) {
453
+ console.error('Failed to load the KaTeX math engine:', error);
454
+ return false;
455
+ }
456
+ let typeset = false;
457
+ placeholders.forEach((placeholder) => {
458
+ // A newer render (the next streamed chunk) replaced it while KaTeX was loading.
459
+ if (!container.contains(placeholder))
460
+ return;
461
+ const tex = placeholder.textContent ?? '';
462
+ const target = document.createElement('span');
463
+ try {
464
+ if (TEX_MACRO_DEFINITION.test(tex)) {
465
+ throw new Error('Formulas that define macros are not typeset');
466
+ }
467
+ engine.render(tex, target, {
468
+ displayMode: placeholder.classList.contains('mj-math-display'),
469
+ output: 'mathml',
470
+ throwOnError: true,
471
+ strict: 'ignore',
472
+ maxSize: 20
473
+ });
474
+ useUnicodeMathLetters(target);
475
+ placeholder.replaceWith(...Array.from(target.childNodes));
476
+ typeset = true;
477
+ }
478
+ catch (error) {
479
+ placeholder.classList.add('mj-math-error');
480
+ placeholder.title = error instanceof Error ? error.message : 'This formula could not be typeset';
481
+ }
482
+ });
483
+ return typeset;
484
+ }
309
485
  /**
310
486
  * Mark mermaid blocks as un-renderable, so the failure is VISIBLE rather than a block of
311
487
  * raw diagram source the reader can't explain. The `.mermaid-error` class carries the