@threepenny/md2pdf 2.2.2 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,7 +127,7 @@ A style that [bundles fonts](#adding-a-style) loads them relative to its stylesh
127
127
  | `@threepenny/md2pdf/styles/<name>.css` | Each style's on-screen look, scoped to `.markdown-body`. For `github`, load `github-markdown-css/github-markdown-light.css` first |
128
128
  | `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers. Load it after the on-screen file, only in a page that holds nothing but the document |
129
129
 
130
- `createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css`. (Before 2.2 it also took markdown-it-texmath, as `math: { texmath, katex }`; that still works, and texmath is ignored.) A formula over 8,000 characters, or one that defines a macro (`\def`, `\newcommand`), shows as its source in red. So does a formula that would take the HTML of a document's formulas past 10,000,000 characters, and every formula after it, so that a short document can't make a page hundreds of megabytes; `math: { katex, maxHtml }` changes that budget, and `maxHtml: Infinity` removes it. Sizes such as `\rule` and `\raisebox` are capped at 30em, before a size command such as `\Huge` scales them. Raw HTML in the Markdown is passed through unless you pass `html: false`, which escapes it; page breaks (`<div class="page-break"></div>`) are raw HTML, so they then print as text. `idPrefix` starts the document's ids, as [Embedding in a web page](#embedding-in-a-web-page) describes. `highlightBudget` is how many milliseconds each render may spend highlighting code, after which the rest of the code shows without colour: 100 with `html: false`, unlimited otherwise. Under a budget, a block over 4 KB is highlighted in pieces split at line breaks where it can, so a comment or string that spans a split can be coloured wrongly.
130
+ `createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css`. (Before 2.2 it also took markdown-it-texmath, as `math: { texmath, katex }`; that still works, and texmath is ignored.) A formula over 8,000 characters, one with braces nested over 100 levels deep, or one that defines a macro (`\def`, `\newcommand`), shows as its source in red. So does a formula that would take the HTML of a document's formulas past 10,000,000 characters, and every formula after it, so that a short document can't make a page hundreds of megabytes; `math: { katex, maxHtml }` changes that budget, and `maxHtml: Infinity` removes it. Sizes such as `\rule` and `\raisebox` are capped at 30em, before a size command such as `\Huge` scales them. Raw HTML in the Markdown is passed through unless you pass `html: false`, which escapes it; page breaks (`<div class="page-break"></div>`) are raw HTML, so they then print as text. `idPrefix` starts the document's ids, as [Embedding in a web page](#embedding-in-a-web-page) describes. `highlightBudget` is how many milliseconds each render may spend highlighting code, after which the rest of the code shows without colour: 100 with `html: false`, unlimited otherwise. Under a budget, a block over 4 KB is highlighted in pieces split at line breaks where it can, so a comment or string that spans a split can be coloured wrongly.
131
131
 
132
132
  ### Variables
133
133
 
@@ -203,7 +203,7 @@ The document paints its own background, so on a page that isn't white, give it s
203
203
 
204
204
  For Markdown you didn't write, render with `html: false` and an `idPrefix`, as in the example above. `html: false` escapes raw HTML, so the output has no scripts, event handlers, forms or style elements of the author's, and markdown-it refuses `javascript:`, `vbscript:`, `file:` and non-image `data:` URLs in links and images. The prefix keeps the document's ids from shadowing your page's globals (`# config` would otherwise give `id="config"`, which a browser exposes as `window.config`) or its own ids. Documents built to be slow to parse, such as thousands of identical headings, unclosed `[[` or unclosed formulas, render in about the time markdown-it itself takes. Code built to be slow to highlight is cut off by `highlightBudget`, which `html: false` sets to 100 ms: a render spends about that long highlighting, plus the 4 KB piece in progress, and shows the rest of the code without colour. A sanitizer such as DOMPurify is still worth running as a second line of defence. What's left to your page:
205
205
 
206
- - Limit the size of documents you accept. Without math the HTML can be about 100 times the size of the Markdown, for a document of nothing but callouts ([#51](https://github.com/jbrecht/md2pdf/issues/51)). With math, the formulas' HTML stops at 10,000,000 characters (`maxHtml`), and the formulas after that show as their source.
206
+ - Limit the size of documents you accept. Without math the HTML can be about 23 times the size of the Markdown, for a document of nothing but callouts (only a document's first 200 callouts draw an icon, and only its first 1,000 inline footnotes `^[…]` become footnotes; the rest print as text). With math, the formulas' HTML stops at 10,000,000 characters (`maxHtml`), and the formulas after that show as their source.
207
207
  - Images load from any URL the author chooses. A Content Security Policy's `img-src` limits that.
208
208
  - With math, a formula can still draw outside the document: sizes are capped, but a negative space such as `\kern{-300em}` isn't. Clip the element you render into with `contain: paint`, which also clips absolutely positioned content that `overflow: hidden` can let through.
209
209
 
package/lib/callouts.js CHANGED
@@ -32,6 +32,10 @@ const ICONS = {
32
32
  const MARKER = /^\[!([\w-]+)\][+-]?(?:[ \t]+([^]*))?$/;
33
33
  const LINE_SEPARATOR = /\p{Zl}|\p{Zp}/u;
34
34
 
35
+ // Each icon is about 1 KB, so only the first callouts of a document draw one: after that the title keeps
36
+ // an empty svg, and its place, but no icon. Otherwise a few characters per callout become a kilobyte.
37
+ const MAX_ICONS = 200;
38
+
35
39
  export default function callouts(md) {
36
40
  // Runs before inline parsing, so the title can be given its own inline token and still get Markdown.
37
41
  md.core.ruler.before('inline', 'callouts', (state) => {
@@ -83,7 +87,15 @@ export default function callouts(md) {
83
87
  state.tokens = out;
84
88
  });
85
89
 
86
- md.renderer.rules.callout_title_open = (tokens, idx) =>
87
- `<p class="markdown-alert-title"><svg class="octicon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="${ICONS[tokens[idx].meta.family]}"></path></svg>`;
90
+ let icons;
91
+ const render = md.renderer.render;
92
+ md.renderer.render = function (...args) {
93
+ icons = 0;
94
+ return render.apply(this, args);
95
+ };
96
+ md.renderer.rules.callout_title_open = (tokens, idx) => {
97
+ const path = icons++ < MAX_ICONS ? `<path d="${ICONS[tokens[idx].meta.family]}"></path>` : '';
98
+ return `<p class="markdown-alert-title"><svg class="octicon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">${path}</svg>`;
99
+ };
88
100
  md.renderer.rules.callout_title_close = () => '</p>\n';
89
101
  }
package/lib/footnotes.js CHANGED
@@ -6,7 +6,19 @@
6
6
 
7
7
  import { first } from './scan.js';
8
8
 
9
+ // Each inline note ^[…] becomes a reference, a list item and a back-link, about 70 times the three
10
+ // characters of an empty one, so a document gets this many; the rest stay text.
11
+ const MAX_INLINE = 1000;
12
+
9
13
  export default function footnotes(md, { idPrefix = '' }) {
14
+ const inline = md.inline.ruler.__rules__.find((r) => r.name === 'footnote_inline')?.fn;
15
+ if (!inline) throw new Error('markdown-it-footnote has no footnote_inline rule to limit');
16
+ md.inline.ruler.at('footnote_inline', (state, silent) => {
17
+ if (state.env.md2pdfInlineNotes >= MAX_INLINE) return false;
18
+ if (!inline(state, silent)) return false;
19
+ if (!silent) state.env.md2pdfInlineNotes = (state.env.md2pdfInlineNotes ?? 0) + 1;
20
+ return true;
21
+ });
10
22
  md.core.ruler.at('footnote_tail', footnoteTail);
11
23
  md.inline.ruler.at('footnote_ref', footnoteRef);
12
24
  if (!idPrefix) return;
package/lib/math.js CHANGED
@@ -9,6 +9,9 @@
9
9
  import { first, nextWhere } from './scan.js';
10
10
 
11
11
  const MAX_LENGTH = 8000;
12
+ // How deep braces may nest. KaTeX recurses once per level and overflows its stack at a few hundred, which
13
+ // takes it milliseconds per formula; a document of formulas that all do so takes seconds.
14
+ const MAX_DEPTH = 100;
12
15
  // Macro definitions are refused: a few hundred bytes of nested definitions expand to minutes of work. So is
13
16
  // a line break before the word (\\def), since counting backslashes can't tell where KaTeX's tokens end:
14
17
  // \verb\a\ ends at its second backslash.
@@ -20,6 +23,19 @@ const MAX_SIZE = 30;
20
23
  // the HTML past the budget, and every one after it, shows as its source.
21
24
  const MAX_HTML = 10_000_000;
22
25
 
26
+ // How deeply {…} nest in `tex`, not counting a brace after a backslash.
27
+ function braceDepth(tex) {
28
+ let depth = 0;
29
+ let max = 0;
30
+ for (let i = 0; i < tex.length; i++) {
31
+ const c = tex[i];
32
+ if (c === '\\') i++;
33
+ else if (c === '{') max = Math.max(max, ++depth);
34
+ else if (c === '}' && depth > 0) depth--;
35
+ }
36
+ return max;
37
+ }
38
+
23
39
  const SPACE = /\s/;
24
40
  const isBreak = (c) => c === '\n' || c === '\r' || c === '\u2028' || c === '\u2029';
25
41
 
@@ -197,9 +213,15 @@ function block(state, startLine, endLine, silent) {
197
213
  const last = match ? match.end - 1 : -1;
198
214
  // Inside a blockquote, endLine is the quote's end, for the lists and other blocks inside it too.
199
215
  if (!match || last > state.eMarks[endLine - 1]) return false;
200
- if (silent) return true;
201
216
  let line = startLine;
202
217
  while (line < endLine && !(last >= state.bMarks[line] + state.tShift[line] && last <= state.eMarks[line])) line++;
218
+ // Text after the closing delimiter on its line was dropped with the rest of the line, by texmath too. On
219
+ // the formula's first line, declining leaves it to the inline rules, which keep the text beside the
220
+ // formula. A formula over several lines stays a block, and the text follows it as a paragraph, since the
221
+ // paragraph and list rules would otherwise get its lines.
222
+ const rest = line < endLine ? state.src.slice(match.end, state.eMarks[line]).trim() : '';
223
+ if (rest && line === startLine) return false;
224
+ if (silent) return true;
203
225
  const token = state.push(match.type, 'math', 0);
204
226
  token.block = true;
205
227
  token.tag = match.tag;
@@ -209,6 +231,15 @@ function block(state, startLine, endLine, silent) {
209
231
  token.info = match.info ?? token.content;
210
232
  token.map = [startLine, line + 1];
211
233
  state.line = line + 1;
234
+ if (rest) {
235
+ const open = state.push('paragraph_open', 'p', 1);
236
+ const inline = state.push('inline', '', 0);
237
+ inline.content = rest;
238
+ inline.children = [];
239
+ const close = state.push('paragraph_close', 'p', -1);
240
+ open.map = inline.map = [line, line + 1];
241
+ open.block = close.block = true;
242
+ }
212
243
  return true;
213
244
  }
214
245
 
@@ -220,6 +251,7 @@ export default function math(md, { katex, maxHtml = MAX_HTML }) {
220
251
  `<span class="katex-error" title="${escapeHtml(reason)}" style="color:#cc0000">${escapeHtml(tex)}</span>`;
221
252
  const render = (tex, displayMode) => {
222
253
  if (tex.length > MAX_LENGTH) return error(tex, `Formulas over ${MAX_LENGTH} characters aren't rendered`);
254
+ if (braceDepth(tex) > MAX_DEPTH) return error(tex, `Formulas nested over ${MAX_DEPTH} levels deep aren't rendered`);
223
255
  if (DEFINITION.test(tex)) return error(tex, 'Macro definitions aren\'t supported');
224
256
  try {
225
257
  return katex.renderToString(tex, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threepenny/md2pdf",
3
- "version": "2.2.2",
3
+ "version": "2.2.3",
4
4
  "description": "Markdown to beautifully styled PDF: the renderer and macOS CLI behind md2pdf.me",
5
5
  "type": "module",
6
6
  "license": "MIT",