@threepenny/md2pdf 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -13
- package/bin/md2pdf.js +165 -28
- package/lib/css.js +35 -8
- package/lib/fit.js +266 -0
- package/lib/math.js +28 -16
- package/lib/page-size.js +20 -0
- package/lib/render.js +141 -15
- package/lib/typography.js +32 -0
- package/package.json +3 -2
- package/styles/academic.css +18 -1
- package/styles/classic.css +18 -1
- package/styles/cyberpunk.css +16 -0
- package/styles/elvish.css +16 -0
- package/styles/github.css +41 -1
- package/styles/gothic.css +34 -5
- package/styles/modern.css +18 -1
- package/styles/print/academic.css +33 -0
- package/styles/print/classic.css +33 -0
- package/styles/print/cyberpunk.css +33 -0
- package/styles/print/elvish.css +33 -0
- package/styles/print/github.css +29 -0
- package/styles/print/gothic.css +33 -0
- package/styles/print/modern.css +33 -0
- package/styles/print/report.css +33 -0
- package/styles/print/resume.css +33 -0
- package/styles/print/sandwake.css +33 -0
- package/styles/print/worksheet.css +33 -0
- package/styles/report.css +18 -1
- package/styles/resume.css +18 -1
- package/styles/sandwake.css +18 -2
- package/styles/worksheet.css +18 -1
package/README.md
CHANGED
|
@@ -6,11 +6,11 @@ Convert Markdown to beautifully styled PDFs. This is the rendering engine and ma
|
|
|
6
6
|
- **On a Mac and comfortable with a terminal?** Install the command-line tool below. It adds a Finder right-click action and a keyboard shortcut.
|
|
7
7
|
- **Building something?** Use the renderer and styles as a dependency, to make PDFs ([Using the renderer](#using-the-renderer)) or to show Markdown in your own pages ([Embedding in a web page](#embedding-in-a-web-page)).
|
|
8
8
|
|
|
9
|
-
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no
|
|
9
|
+
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no level-one heading, `#` or `<h1>`. A leading `---` block of ordinary Markdown prints as Markdown after a divider), and page breaks (`<div class="page-break"></div>`). Collapsed `<details>` sections print open. Typed `--`, `---`, `...` and `+-` print as –, —, … and ±, and straight quotes as curly ones; `(c)`, `(r)` and `(tm)` print as typed (before 2.5 they became ©, ® and ™, so type the symbol or `©`, `®`, `™` where you want one). Eleven print styles are included: `github`, `classic`, `academic`, `modern`, `report`, `resume`, `worksheet`, `gothic`, `sandwake`, `elvish` and `cyberpunk`.
|
|
10
10
|
|
|
11
11
|
# Command-line tool (macOS)
|
|
12
12
|
|
|
13
|
-
Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome.
|
|
13
|
+
Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome. Formulas (`$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and environments such as `\begin{aligned}…\end{aligned}` or `\begin{align*}…\end{align*}` that start a block) are drawn with [KaTeX](https://katex.org), as on md2pdf.me; the HTML that `--html` writes also carries MathML for screen readers, which the PDF doesn't. Prices such as $5 and $10 stay text, even beside a formula. A displayed formula wider than the page shrinks until it fits, so a very long one prints small; split it over lines with `aligned` to keep it full size. A table wider than the page fits by breaking the long words in its widest columns, mid-word and without a hyphen, then its headers if that isn't enough, and every cell as a last resort. A formula in one of its cells first shrinks to as little as half size, before any word breaks, and smaller only if the table still doesn't fit. A table that fits prints as written.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -26,7 +26,7 @@ This installs:
|
|
|
26
26
|
- **Convert to PDF** Quick Action — right-click any `.md` file in Finder → **Quick Actions → Convert to PDF**
|
|
27
27
|
- **⌃⌥⌘P** keyboard shortcut — select `.md` files in Finder and press it
|
|
28
28
|
|
|
29
|
-
Re-run `install.sh` if you move this folder
|
|
29
|
+
Re-run `install.sh` if you move this folder, remove the Node version it was installed with, or pull a version that adds a dependency (md2pdf says so when KaTeX, which draws formulas, is missing). `./uninstall.sh` removes all of it, and your saved default style (below).
|
|
30
30
|
|
|
31
31
|
To use a different shortcut, pass it when installing (`@` ⌘, `~` ⌥, `^` ⌃, `$` ⇧), or set it to empty to skip:
|
|
32
32
|
|
|
@@ -50,6 +50,8 @@ md2pdf notes.md --css my.css # layer extra CSS on top of the style (its url()
|
|
|
50
50
|
md2pdf notes.md --html # also write the intermediate HTML (for tweaking CSS)
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
+
A `--css` file's `@import`s resolve against it too. The rules they import come before the style, so where they and the style set the same thing equally specifically, the style wins; rules written in the file itself win.
|
|
54
|
+
|
|
53
55
|
From Finder, a single file opens in Preview when done; multiple files show a notification.
|
|
54
56
|
|
|
55
57
|
## Styles
|
|
@@ -63,7 +65,7 @@ From Finder, a single file opens in Preview when done; multiple files show a not
|
|
|
63
65
|
| `report` | Business or technical report: title block from the first heading, running header with the title, "Page N of M" footers, gridded tables |
|
|
64
66
|
| `resume` | Compact and one-page friendly: the first heading is your name, the paragraph after it your contact line, `##` headings are ruled section dividers |
|
|
65
67
|
| `worksheet` | For worksheets, stories and class handouts: Andika body text and rounded Fredoka headings (both bundled), larger type, bright headings that change color each section, outlined rounded boxes and big tick boxes for task lists |
|
|
66
|
-
| `gothic` | An old book of dread: blackletter Grenze Gotisch headings and IM Fell English body text (both bundled), oxblood red titles, main headings and table rules, a drop cap after the title, leaf ornaments for rules, page numbers between dashes |
|
|
68
|
+
| `gothic` | An old book of dread: blackletter Grenze Gotisch headings and IM Fell English body text (both bundled), oxblood red titles, main headings, bold text and table rules, a drop cap after the title, leaf ornaments for rules, page numbers between dashes |
|
|
67
69
|
| `sandwake` | A space-opera codex: wide Michroma capitals for titles and sections, Spectral text and Space Mono labels (all bundled), rust section numbers and drop cap, later titles numbered as books ("Liber II"), a setting-sun rule, outlined code and callouts, a running title and folio numbers |
|
|
68
70
|
| `elvish` | A quiet manuscript from under the trees: Cormorant Unicase titles and sections and Cormorant Garamond text (both bundled) at a larger size, a gold star between leafed sprigs above the title, leaves for bullets and beside `##` headings, a drop cap after each `#` heading, verse-like quotes between stars, double-ruled callouts, italic Roman numerals for lists and page numbers |
|
|
69
71
|
| `cyberpunk` | A job file leaked off somebody's terminal: squared Chakra Petch text and JetBrains Mono labels (both bundled), teal and hot magenta on white, the title in a gridded panel with corner brackets and a cyan and magenta offset, numbered sections ("01 //"), `###` headings as terminal prompts, intercept boxes for quotes, pale terminal panels for code, boxed two-digit list numbers, a running title and page numbers out of the total |
|
|
@@ -75,17 +77,19 @@ Switch the default style — used by the Finder Quick Action, the keyboard short
|
|
|
75
77
|
./set-style.sh classic # make classic the default
|
|
76
78
|
```
|
|
77
79
|
|
|
78
|
-
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion.
|
|
80
|
+
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion. If you set `XDG_CONFIG_HOME` in your shell, the `md2pdf` command and `set-style.sh` use `$XDG_CONFIG_HOME/md2pdf/config.json` instead, but the Quick Action and the shortcut still read `~/.config`, since Finder doesn't load your shell profile; `MD2PDF_CONFIG` names a config file of your own. `./uninstall.sh` deletes `config.json` from both of those `md2pdf` folders, and nothing else in them, and keeps a file elsewhere that `MD2PDF_CONFIG` names.
|
|
79
81
|
|
|
80
82
|
### Adding a style
|
|
81
83
|
|
|
82
84
|
Styles are registered in the `STYLES` map in `bin/md2pdf.js`; each is a list of CSS files inlined into the page in order. A style has two files:
|
|
83
85
|
|
|
84
86
|
- `styles/<name>.css`, the on-screen look. The content is wrapped in `<article class="markdown-body">`, and every rule must be scoped to it: no `:root`, `html`, `body` or `@page` rules, so the style can be embedded in other pages.
|
|
85
|
-
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers,
|
|
87
|
+
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers, `html, body` margins, collapsed `<details>` sections printed open, and `margin-trim: block-end` on `.markdown-body` in Safari, so it doesn't print a blank last page.
|
|
86
88
|
|
|
87
89
|
Register it in `STYLES` and add its page margin to `pageMargins` in `lib/styles.js`, and it's available to `-s` and `set-style.sh`. Use `md2pdf --html` to get the intermediate HTML for tweaking in a browser. For one-off tweaks, `--css` is enough.
|
|
88
90
|
|
|
91
|
+
`test/fixtures/sample.md` has the elements a style needs to handle: headings, lists, tables, code, block quotes, footnotes, images, math and a diagram; `test/fixtures/callouts.md` has the callouts. Check a style against them with `bin/md2pdf.js -s <name> test/fixtures/sample.md` (each PDF lands beside its Markdown; `*.pdf` is ignored). Its `mermaid` block prints as code here; md2pdf.me draws it as a diagram, so check diagrams there.
|
|
92
|
+
|
|
89
93
|
A style can bundle fonts, so it looks the same on every computer:
|
|
90
94
|
|
|
91
95
|
- Put each family in `styles/fonts/<family>/`: its `.woff2` files (the smallest format, and every current browser reads it) and its `OFL.txt`, and nothing else. Only fonts under the SIL Open Font License, which allows bundling. Fonts are the only files a style bundles.
|
|
@@ -95,7 +99,9 @@ A style can bundle fonts, so it looks the same on every computer:
|
|
|
95
99
|
|
|
96
100
|
The CLI resolves a stylesheet's relative `url()`s against the stylesheet, and loads every declared font before printing, including one used only in a page header. `npm test` checks the file layout, the licence, the family names, `local()` and `font-display`.
|
|
97
101
|
|
|
98
|
-
|
|
102
|
+
End the on-screen file with the rule the other styles end with, which turns off ligatures when Safari prints: Safari's PDFs copy a ligature as the wrong characters ("The" pastes as "!e"), while Chrome's, the CLI's and on-screen text are unaffected. It belongs in the on-screen file, not the print file, because a page that embeds a style prints without the print file. On a Mac with `swiftc`, `npm test` prints every style through WebKit and checks the copied text.
|
|
103
|
+
|
|
104
|
+
The text of the document's first level-one heading, written as `#` or as an HTML `<h1>`, read as a browser shows it (empty if there is none, and a formula in it as its TeX, `$e^{i\pi}$`), is available to page margin boxes as `var(--document-title)`, e.g. `@top-left { content: var(--document-title); }`, as the `report` style does.
|
|
99
105
|
|
|
100
106
|
A style declares the [shared variables](#variables) in its first rule, `:where(.markdown-body) { … }`, with a comment saying what each one does there, and uses them for every size, gap, color and font they name. Spacing follows two patterns: `line-height: calc(1 + 0.55 * var(--md2pdf-leading))` and `margin: calc(1.8em * var(--md2pdf-space)) 0 …`. `npm test` checks that each variable is declared and changes the document. Page margins aren't included: they stay in the style's `@page` rule, in `styles/print/<name>.css`.
|
|
101
107
|
|
|
@@ -122,16 +128,18 @@ const html = buildDocument({
|
|
|
122
128
|
});
|
|
123
129
|
```
|
|
124
130
|
|
|
131
|
+
`pageSize` is the page size the CLI's `--page-size` takes, Letter by default: `auto`; `portrait` or `landscape`; a paper name (`a5`, `a4`, `a3`, `b5`, `b4`, `jis-b5`, `jis-b4`, `letter`, `legal`, `ledger`) alone or with `portrait` or `landscape`; or one or two lengths in `in`, `cm`, `mm`, `q`, `pt`, `pc`, `px`, `em`, `rem`, `ex`, `ch`, `vw`, `vh`, `vmin` or `vmax`, such as `5in 8in` (no `calc()` or newer units). Case doesn't matter. Anything else, including a value that isn't a string, throws a `TypeError`, so check a value you didn't choose with `isPageSize(size)` first. `head` (HTML added to the page's `<head>`) and `bodyHtml` are written into the page as given, and so is `css`, except that a `</style` in it can't end the page's `<style>` element. `css` and `head` must come from you, not from a visitor: CSS can still restyle the whole page and load URLs, which can send the page's content to another server. For Markdown you didn't write, render `bodyHtml` with `html: false`, as [below](#embedding-in-a-web-page) describes.
|
|
132
|
+
|
|
125
133
|
A style that [bundles fonts](#adding-a-style) loads them relative to its stylesheet, so a page that inlines the CSS must rewrite those `url()`s, as the CLI does, or let a bundler do it (in Vite, `?inline`, not `?raw`). Before printing, start every font loading and wait: a font used only in a page header may otherwise not be requested until printing starts, and the PDF falls back, as it does in headless Chrome. `await Promise.allSettled([...document.fonts].map((f) => f.load()))`.
|
|
126
134
|
|
|
127
135
|
| Export | What it is |
|
|
128
136
|
| ------ | ---------- |
|
|
129
|
-
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument(
|
|
137
|
+
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument({ bodyHtml, title, css, pageSize?, head? })`, `isPageSize(size)` (whether `buildDocument` takes `size` as its `pageSize`), `titleOf(markdown, fallback)` (the first level-one heading's text, a `#` heading or a raw-HTML `<h1>`, without Markdown syntax: the h1 `headingText` finds in a render with raw HTML on. Else the front matter's `title:`, else the fallback. The text is decoded, so escape it before writing it into HTML; `buildDocument` escapes its `title`), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` (the text of the first `<h1>` in rendered HTML, as a browser shows it, formulas as their TeX) |
|
|
130
138
|
| `@threepenny/md2pdf/styles` | `pageMargins`: each style's `@page` margin at default spacing, e.g. `pageMargins.classic` is `'1in 1.1in 0.9in'` |
|
|
131
139
|
| `@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 |
|
|
132
|
-
| `@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 |
|
|
140
|
+
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers, collapsed `<details>` sections printed open, and, in Safari, no space below the document's last block. Load it after the on-screen file, only in a page that holds nothing but the document. A section without a `<summary>` still shows the browser's closed arrow; to turn the arrow, remove each section's `name` and set `open` on it before printing, as the CLI does |
|
|
133
141
|
|
|
134
|
-
`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
|
|
142
|
+
`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`, which hides the MathML each formula carries for screen readers; without it, that MathML shows beside the formula and can draw far outside it. (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, their MathML included, 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.
|
|
135
143
|
|
|
136
144
|
### Variables
|
|
137
145
|
|
|
@@ -145,7 +153,7 @@ Every style takes the same variables, set on the `.markdown-body` element. A `--
|
|
|
145
153
|
| `--md2pdf-background` | The document's background, white |
|
|
146
154
|
| `--md2pdf-text` | Body text |
|
|
147
155
|
| `--md2pdf-muted` | Secondary text, such as footnotes and captions |
|
|
148
|
-
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style. `gothic`'s leaf ornaments stay oxblood, `sandwake`'s horizon ornament stays rust, `elvish`'s title, `#`, `##`, `####` and `#####` headings, links, quotes, note callouts, table rules and ornaments keep their own greens and gold, and `cyberpunk`'s `##` and `####` headings, links, nested bullets, list numbers, tick boxes, table headings, the title's frame, most of each rule, the quote label, note callouts and function names in code stay teal |
|
|
156
|
+
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style, and `github`'s focus rings. `gothic`'s leaf ornaments stay oxblood, `sandwake`'s horizon ornament stays rust, `elvish`'s title, `#`, `##`, `####` and `#####` headings, links, quotes, note callouts, table rules and ornaments keep their own greens and gold, and `cyberpunk`'s `##` and `####` headings, links, nested bullets, list numbers, tick boxes, table headings, the title's frame, most of each rule, the quote label, note callouts and function names in code stay teal |
|
|
149
157
|
| `--md2pdf-rule` | Rules, borders and table lines (every style but `github`) |
|
|
150
158
|
| `--md2pdf-surface` | A tinted background: inline code and code blocks in `classic`, `modern`, `worksheet`, `gothic` and `elvish`, and callouts too in `classic` and `gothic`; inline code, quotes and table headings in `report`; the inside of code blocks, callouts and inline code in `sandwake`, white as designed; the title panel, inline code, code blocks, table headings and shaded table rows in `cyberpunk`. The other styles don't use it |
|
|
151
159
|
| `--md2pdf-font` | The body font |
|
|
@@ -203,9 +211,9 @@ A style that bundles fonts loads them from `fonts/` beside its stylesheet, so se
|
|
|
203
211
|
|
|
204
212
|
Set the [variables](#variables) on the `.markdown-body` element itself, with any selector or inline (`<article class="markdown-body" style="--md2pdf-font-size: 10pt">`). The style declares its defaults with no specificity, so your rule wins wherever it appears. A value set on `:root` or another element around the document doesn't reach it. One page can hold several documents in the same style, each with its own overrides, but not two different styles.
|
|
205
213
|
|
|
206
|
-
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `
|
|
214
|
+
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `em { color: #c00 }` reddens italic text in the document too. A highlight.js theme on your page is the exception: the styles keep it out of the document's code blocks. Headings get ids from their text (`# Notes` becomes `id="notes"`) so `[[#Notes]]` links work. Pass `idPrefix`, letters, digits, `_` and `-` starting with a letter and ending in `-`, to start every heading and footnote id with it, and every link to a `#` in the document: with `idPrefix: 'notes-'`, `# Notes` becomes `id="notes-notes"` and `[see](#notes)` links to it. Then no heading takes an id your page uses, as long as none of your page's ids start with the prefix, and two documents on one page don't share ids, as long as neither's prefix starts the other's (`a-` and `a-b-` would). Without it, give your own elements ids that a heading won't produce. Links in raw HTML, which only `html: true` lets through, aren't rewritten.
|
|
207
215
|
|
|
208
|
-
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:
|
|
216
|
+
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; with math, pass DOMPurify `ADD_TAGS: ['semantics', 'annotation']`, or it unwraps the MathML's annotation and screen readers read each formula's TeX after it. What's left to your page:
|
|
209
217
|
|
|
210
218
|
- 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.
|
|
211
219
|
- Images load from any URL the author chooses. A Content Security Policy's `img-src` limits that.
|
package/bin/md2pdf.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// md2pdf: convert Markdown files to PDF using headless Chrome.
|
|
3
3
|
|
|
4
4
|
import { spawn } from 'node:child_process';
|
|
5
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { homedir, tmpdir } from 'node:os';
|
|
7
7
|
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
@@ -11,7 +11,9 @@ import { createRequire } from 'node:module';
|
|
|
11
11
|
|
|
12
12
|
import hljs from 'highlight.js';
|
|
13
13
|
import { buildDocument, createRenderer, titleOf } from '../lib/render.js';
|
|
14
|
-
import {
|
|
14
|
+
import { fitFormulas, fitTables } from '../lib/fit.js';
|
|
15
|
+
import { rewriteUrls, splitImports } from '../lib/css.js';
|
|
16
|
+
import { PAPER, isPageSize } from '../lib/page-size.js';
|
|
15
17
|
|
|
16
18
|
const require = createRequire(import.meta.url);
|
|
17
19
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -34,6 +36,25 @@ const STYLES = {
|
|
|
34
36
|
cyberpunk: styleFiles('cyberpunk'),
|
|
35
37
|
};
|
|
36
38
|
const FALLBACK_STYLE = 'github';
|
|
39
|
+
// Not STYLES[name], which is truthy for names every object inherits, such as toString.
|
|
40
|
+
const isStyle = (name) => typeof name === 'string' && Object.hasOwn(STYLES, name);
|
|
41
|
+
// A checkout installed before KaTeX was a dependency has none until install.sh runs again; it still converts.
|
|
42
|
+
const katex = await import('katex').then(
|
|
43
|
+
(m) => m.default,
|
|
44
|
+
(err) => {
|
|
45
|
+
if (err.code === 'ERR_MODULE_NOT_FOUND') return null;
|
|
46
|
+
throw err;
|
|
47
|
+
},
|
|
48
|
+
);
|
|
49
|
+
// Added after the style only when the document has a formula, so a document without math prints as before.
|
|
50
|
+
// The rules after KaTeX's keep a displayed formula on one page and put a $$ … $$ (1) equation number at the
|
|
51
|
+
// right margin, as md2pdf.me does.
|
|
52
|
+
const MATH_CSS = katex && require.resolve('katex/dist/katex.min.css');
|
|
53
|
+
const EQUATION_NUMBERS = `
|
|
54
|
+
.markdown-body eqn { display: block; break-inside: avoid; }
|
|
55
|
+
.markdown-body section.eqno { display: flex; align-items: center; }
|
|
56
|
+
.markdown-body section.eqno > eqn { flex: 1; margin-left: 3em; }
|
|
57
|
+
.markdown-body section.eqno > span { width: 3em; text-align: right; }`;
|
|
37
58
|
|
|
38
59
|
// Settings shared by the CLI, Finder Quick Action and keyboard shortcut.
|
|
39
60
|
const CONFIG_PATH =
|
|
@@ -58,7 +79,7 @@ Options:
|
|
|
58
79
|
-o, --output <file> Output path (only with a single input file)
|
|
59
80
|
-s, --style <name> Style to use (${Object.keys(STYLES).join(', ')}; default: ${defaultStyle})
|
|
60
81
|
--css <file> Extra CSS file applied after the style
|
|
61
|
-
-p, --page-size <size> Letter, A4, Legal, ... (default: Letter)
|
|
82
|
+
-p, --page-size <size> Letter, A4, Legal, "A4 landscape", "5in 8in", ... (default: Letter)
|
|
62
83
|
--open Open the PDF when done
|
|
63
84
|
--html Also write the intermediate .html (for debugging styles)
|
|
64
85
|
--set-style <name> Make <name> the default style (also used by the Finder Quick Action)
|
|
@@ -72,7 +93,9 @@ Environment:
|
|
|
72
93
|
function readConfig() {
|
|
73
94
|
if (!existsSync(CONFIG_PATH)) return {};
|
|
74
95
|
try {
|
|
75
|
-
|
|
96
|
+
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
97
|
+
if (config === null || typeof config !== 'object' || Array.isArray(config)) throw new Error('not a JSON object');
|
|
98
|
+
return config;
|
|
76
99
|
} catch (err) {
|
|
77
100
|
console.error(`md2pdf: ignoring unreadable config ${CONFIG_PATH}: ${err.message}`);
|
|
78
101
|
return {};
|
|
@@ -96,9 +119,9 @@ function findChrome() {
|
|
|
96
119
|
return found;
|
|
97
120
|
}
|
|
98
121
|
|
|
99
|
-
// A stylesheet's text, with its relative url()s (a style's bundled fonts, say) made absolute:
|
|
100
|
-
// into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
101
|
-
// file they name that doesn't exist.
|
|
122
|
+
// A stylesheet's text, with its relative url()s and @imports (a style's bundled fonts, say) made absolute:
|
|
123
|
+
// inlined into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
124
|
+
// each file they name that doesn't exist.
|
|
102
125
|
const warned = new Set();
|
|
103
126
|
function readCss(file) {
|
|
104
127
|
return rewriteUrls(readFileSync(file, 'utf8'), (ref) => {
|
|
@@ -119,23 +142,90 @@ function readCss(file) {
|
|
|
119
142
|
}
|
|
120
143
|
|
|
121
144
|
function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
122
|
-
const
|
|
145
|
+
const bodyHtml = createRenderer({ hljs, ...(katex && { math: { katex } }) }).render(markdown);
|
|
146
|
+
const math = /<eqn?>/.test(bodyHtml) ? [readCss(MATH_CSS) + EQUATION_NUMBERS] : [];
|
|
147
|
+
// An @import counts only before every other rule, so the --css file's @imports lead the page's CSS: the
|
|
148
|
+
// style then wins ties with the rules they import, while the file's own rules still follow the style.
|
|
149
|
+
const extra = extraCss ? splitImports(readCss(extraCss)) : null;
|
|
150
|
+
const css = [...(extra ? extra.head : []), ...STYLES[style].map(readCss), ...math, ...(extra ? [extra.rest] : [])].join('\n');
|
|
151
|
+
const loadFonts = `() => document.fonts.forEach((f) => f.load().catch(() => {}))`;
|
|
152
|
+
// Once its fonts have loaded, a displayed formula wider than the column shrinks to fit. It fits whatever
|
|
153
|
+
// column it ends up in, so the printed page needs no second run. Then a table wider than the printed page
|
|
154
|
+
// fits it, measured at that page's width; it goes second, since fitFormulas resets a formula in a cell.
|
|
155
|
+
const fits = [...(/<eqn>/.test(bodyHtml) ? [fitFormulas] : []), ...(/<table[\s>]/i.test(bodyHtml) ? [fitTables] : [])];
|
|
123
156
|
return buildDocument({
|
|
124
|
-
bodyHtml
|
|
157
|
+
bodyHtml,
|
|
125
158
|
title,
|
|
126
159
|
css,
|
|
127
160
|
pageSize,
|
|
128
161
|
// <base> makes relative image/link paths resolve against the Markdown file's folder.
|
|
129
162
|
// Chrome loads a font used only in a page header or footer too late for the PDF, so start every
|
|
130
|
-
// declared font loading now; the PDF waits for those loads with the rest of the page.
|
|
163
|
+
// declared font loading now; the PDF waits for those loads with the rest of the page. An imported
|
|
164
|
+
// stylesheet's fonts may not be declared until the page has loaded, so they start then.
|
|
131
165
|
head: `<base href="${pathToFileURL(baseDir + '/').href}">
|
|
132
|
-
<script>document.addEventListener('DOMContentLoaded',
|
|
166
|
+
<script>document.addEventListener('DOMContentLoaded', ${loadFonts});</script>${extra?.head.length ? `
|
|
167
|
+
<script>addEventListener('load', ${loadFonts});</script>` : ''}${
|
|
168
|
+
// The print stylesheet shows a collapsed section's content, but can't reach the closed arrow the
|
|
169
|
+
// browser draws for one without a <summary>. Opening each section turns that arrow too. Opening one
|
|
170
|
+
// section of a named group closes the rest, so each leaves its group first.
|
|
171
|
+
/<details[\s/>]/i.test(bodyHtml)
|
|
172
|
+
? `
|
|
173
|
+
<script>document.addEventListener('DOMContentLoaded', () => {
|
|
174
|
+
for (const section of document.querySelectorAll('details')) {
|
|
175
|
+
section.removeAttribute('name');
|
|
176
|
+
section.open = true;
|
|
177
|
+
}
|
|
178
|
+
});</script>`
|
|
179
|
+
: ''
|
|
180
|
+
}${fits.length
|
|
181
|
+
? `
|
|
182
|
+
<script>${fits.join('\n')}
|
|
183
|
+
addEventListener('load', () => document.fonts.ready.then(() => { ${fits.map((fit) => `${fit.name}();`).join(' ')} }));</script>`
|
|
184
|
+
: ''
|
|
185
|
+
}`,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// The temp folders that exist right now, and the Chrome printing, so an interrupt can clean up.
|
|
190
|
+
const tempDirs = new Set();
|
|
191
|
+
let chromeProc = null;
|
|
192
|
+
|
|
193
|
+
function makeTempDir(prefix) {
|
|
194
|
+
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
195
|
+
tempDirs.add(dir);
|
|
196
|
+
return dir;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function removeTempDir(dir) {
|
|
200
|
+
rmSync(dir, { recursive: true, force: true });
|
|
201
|
+
tempDirs.delete(dir);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// On an interrupt, stop Chrome, wait for it to let go of its profile, remove the temp folders, then
|
|
205
|
+
// die of the same signal so the shell sees it. Chrome gets SIGKILL: a Control + C reaches it too, and
|
|
206
|
+
// headless Chrome that has had a SIGINT hangs and ignores SIGTERM, outliving md2pdf.
|
|
207
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
|
208
|
+
process.once(signal, () => {
|
|
209
|
+
const die = () => {
|
|
210
|
+
for (const dir of tempDirs) {
|
|
211
|
+
try {
|
|
212
|
+
removeTempDir(dir);
|
|
213
|
+
} catch {
|
|
214
|
+
// Leave a folder that can't be removed rather than miss the others or the signal.
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
process.kill(process.pid, signal);
|
|
218
|
+
};
|
|
219
|
+
if (!chromeProc) return die();
|
|
220
|
+
chromeProc.once('close', die);
|
|
221
|
+
chromeProc.kill('SIGKILL');
|
|
222
|
+
setTimeout(die, 5000).unref();
|
|
133
223
|
});
|
|
134
224
|
}
|
|
135
225
|
|
|
136
226
|
function runChrome(chrome, htmlPath, pdfPath) {
|
|
137
227
|
// A throwaway profile keeps headless Chrome separate from any Chrome you have open.
|
|
138
|
-
const profile =
|
|
228
|
+
const profile = makeTempDir('md2pdf-chrome-');
|
|
139
229
|
const args = [
|
|
140
230
|
'--headless',
|
|
141
231
|
'--disable-gpu',
|
|
@@ -149,24 +239,52 @@ function runChrome(chrome, htmlPath, pdfPath) {
|
|
|
149
239
|
pathToFileURL(htmlPath).href,
|
|
150
240
|
];
|
|
151
241
|
return new Promise((resolvePromise, reject) => {
|
|
152
|
-
const proc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
242
|
+
const proc = (chromeProc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] }));
|
|
153
243
|
let stderr = '';
|
|
154
244
|
proc.stderr.on('data', (d) => (stderr += d));
|
|
155
|
-
|
|
245
|
+
// A Chrome that fails to start emits 'error' first, and main() may exit before its 'close' arrives.
|
|
246
|
+
proc.on('error', (err) => {
|
|
247
|
+
if (chromeProc === proc) chromeProc = null;
|
|
248
|
+
removeTempDir(profile);
|
|
249
|
+
reject(err);
|
|
250
|
+
});
|
|
156
251
|
proc.on('close', (code) => {
|
|
157
|
-
|
|
252
|
+
if (chromeProc === proc) chromeProc = null;
|
|
253
|
+
removeTempDir(profile);
|
|
158
254
|
if (code === 0 && existsSync(pdfPath)) resolvePromise();
|
|
159
255
|
else reject(new Error(`Chrome failed (exit ${code}):\n${stderr.trim()}`));
|
|
160
256
|
});
|
|
161
257
|
});
|
|
162
258
|
}
|
|
163
259
|
|
|
164
|
-
|
|
260
|
+
// A file's identity, whatever name reaches it: names can differ by case, a symlink or a hard link.
|
|
261
|
+
const fileId = (stat) => `${stat.dev}:${stat.ino}`;
|
|
262
|
+
|
|
263
|
+
// `written` maps each PDF this run has written, by fileId, to the input it came from;
|
|
264
|
+
// `inputs` maps each of this run's inputs, by fileId, to its name.
|
|
265
|
+
async function convert(input, opts, chrome, written, inputs) {
|
|
165
266
|
const inputPath = resolve(input);
|
|
166
267
|
if (!existsSync(inputPath)) throw new Error(`No such file: ${input}`);
|
|
167
|
-
const
|
|
268
|
+
const source = fileId(statSync(inputPath));
|
|
168
269
|
const stem = basename(inputPath, extname(inputPath));
|
|
169
270
|
const pdfPath = resolve(opts.output ?? join(dirname(inputPath), `${stem}.pdf`));
|
|
271
|
+
const target = statSync(pdfPath, { throwIfNoEntry: false });
|
|
272
|
+
if (target && fileId(target) === source) {
|
|
273
|
+
throw new Error('The PDF would replace the file it is made from; give another path with --output');
|
|
274
|
+
}
|
|
275
|
+
const htmlPath = opts.html && pdfPath.replace(/\.pdf$/i, '') + '.html';
|
|
276
|
+
const htmlTarget = htmlPath && statSync(htmlPath, { throwIfNoEntry: false });
|
|
277
|
+
if (htmlTarget && fileId(htmlTarget) === source) {
|
|
278
|
+
throw new Error('The HTML would replace the file it is made from; give another path with --output');
|
|
279
|
+
}
|
|
280
|
+
if (htmlTarget && inputs.has(fileId(htmlTarget))) {
|
|
281
|
+
throw new Error(`The HTML would replace ${inputs.get(fileId(htmlTarget))}, another input; convert it alone with --output`);
|
|
282
|
+
}
|
|
283
|
+
if (target && written.has(fileId(target))) {
|
|
284
|
+
throw new Error(`${pdfPath} was already written from ${written.get(fileId(target))}; convert it alone with --output`);
|
|
285
|
+
}
|
|
286
|
+
if (!existsSync(dirname(pdfPath))) throw new Error(`No such folder: ${dirname(pdfPath)}`);
|
|
287
|
+
const markdown = readFileSync(inputPath, 'utf8');
|
|
170
288
|
const title = titleOf(markdown, stem);
|
|
171
289
|
|
|
172
290
|
const html = buildHtml({
|
|
@@ -178,15 +296,23 @@ async function convert(input, opts, chrome) {
|
|
|
178
296
|
pageSize: opts['page-size'],
|
|
179
297
|
});
|
|
180
298
|
|
|
181
|
-
const workDir =
|
|
299
|
+
const workDir = makeTempDir('md2pdf-');
|
|
182
300
|
try {
|
|
183
|
-
const
|
|
184
|
-
writeFileSync(
|
|
185
|
-
if (
|
|
186
|
-
|
|
301
|
+
const page = join(workDir, `${stem}.html`);
|
|
302
|
+
writeFileSync(page, html);
|
|
303
|
+
if (htmlPath) writeFileSync(htmlPath, html);
|
|
304
|
+
// Chrome prints into the temp folder: printing over a PDF it can't replace, it reports success.
|
|
305
|
+
const printed = join(workDir, 'print.pdf');
|
|
306
|
+
await runChrome(chrome, page, printed);
|
|
307
|
+
try {
|
|
308
|
+
writeFileSync(pdfPath, readFileSync(printed));
|
|
309
|
+
} catch (err) {
|
|
310
|
+
throw new Error(`Could not write ${pdfPath}: ${err.message.split(',')[0]}`);
|
|
311
|
+
}
|
|
187
312
|
} finally {
|
|
188
|
-
|
|
313
|
+
removeTempDir(workDir);
|
|
189
314
|
}
|
|
315
|
+
written.set(fileId(statSync(pdfPath)), input);
|
|
190
316
|
return pdfPath;
|
|
191
317
|
}
|
|
192
318
|
|
|
@@ -213,10 +339,10 @@ async function main() {
|
|
|
213
339
|
}
|
|
214
340
|
const { values: opts, positionals: files } = parsed;
|
|
215
341
|
const config = readConfig();
|
|
216
|
-
const defaultStyle =
|
|
342
|
+
const defaultStyle = isStyle(config.style) ? config.style : FALLBACK_STYLE;
|
|
217
343
|
|
|
218
344
|
if (opts['set-style'] !== undefined) {
|
|
219
|
-
if (!
|
|
345
|
+
if (!isStyle(opts['set-style'])) unknownStyle(opts['set-style']);
|
|
220
346
|
writeConfig({ ...config, style: opts['set-style'] });
|
|
221
347
|
console.log(`Default style is now "${opts['set-style']}".`);
|
|
222
348
|
process.exit(0);
|
|
@@ -229,21 +355,32 @@ async function main() {
|
|
|
229
355
|
console.log(usage(defaultStyle));
|
|
230
356
|
process.exit(opts.help ? 0 : 2);
|
|
231
357
|
}
|
|
232
|
-
if (config.style && !
|
|
358
|
+
if (config.style && !isStyle(config.style)) {
|
|
233
359
|
console.error(`md2pdf: config style "${config.style}" no longer exists; using ${FALLBACK_STYLE}`);
|
|
234
360
|
}
|
|
235
361
|
opts.style ??= defaultStyle;
|
|
236
|
-
if (!
|
|
362
|
+
if (!isStyle(opts.style)) unknownStyle(opts.style);
|
|
363
|
+
if (!isPageSize(opts['page-size'])) {
|
|
364
|
+
console.error(`md2pdf: unknown page size "${opts['page-size']}". Use one of ${PAPER.join(', ')}, alone or with "landscape", or a width and height such as "5in 8in"`);
|
|
365
|
+
process.exit(2);
|
|
366
|
+
}
|
|
237
367
|
if (opts.output && files.length > 1) {
|
|
238
368
|
console.error('md2pdf: --output can only be used with a single input file');
|
|
239
369
|
process.exit(2);
|
|
240
370
|
}
|
|
241
371
|
|
|
242
372
|
const chrome = findChrome();
|
|
373
|
+
if (!katex) console.error(`md2pdf: KaTeX isn't installed, so formulas print as their source; run ${join(ROOT, 'install.sh')} again`);
|
|
243
374
|
let failed = 0;
|
|
375
|
+
const written = new Map();
|
|
376
|
+
const inputs = new Map();
|
|
377
|
+
for (const file of files) {
|
|
378
|
+
const stat = statSync(resolve(file), { throwIfNoEntry: false });
|
|
379
|
+
if (stat) inputs.set(fileId(stat), file);
|
|
380
|
+
}
|
|
244
381
|
for (const file of files) {
|
|
245
382
|
try {
|
|
246
|
-
const pdf = await convert(file, opts, chrome);
|
|
383
|
+
const pdf = await convert(file, opts, chrome, written, inputs);
|
|
247
384
|
console.log(pdf);
|
|
248
385
|
if (opts.open) spawn('open', [pdf], { stdio: 'ignore', detached: true }).unref();
|
|
249
386
|
} catch (err) {
|
package/lib/css.js
CHANGED
|
@@ -2,26 +2,53 @@
|
|
|
2
2
|
|
|
3
3
|
import { cssString } from './render.js';
|
|
4
4
|
|
|
5
|
-
// A comment, a string, or a url()
|
|
5
|
+
// A comment, a string, an @import of a string, or a url(); the groups hold the @import's double- or
|
|
6
|
+
// single-quoted reference, then the url()'s double-quoted, single-quoted or bare one.
|
|
6
7
|
const STRING = (q) => `${q}(?:\\\\[^]|[^${q}\\\\\\n])*${q}`;
|
|
7
8
|
const TOKENS = new RegExp(
|
|
8
|
-
String.raw`\/\*[^]
|
|
9
|
+
String.raw`\/\*[^]*?\*\/|@import\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)')|${STRING('"')}|${STRING("'")}|url\(\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)'|([^)\s'"\\]*))\s*\)`,
|
|
9
10
|
'gi',
|
|
10
11
|
);
|
|
11
12
|
|
|
12
|
-
// Replaces each relative url() in a stylesheet with url(<resolve(ref)>)
|
|
13
|
-
// and references that are absolute, root-relative,
|
|
13
|
+
// Replaces each relative url() and @import "…" in a stylesheet with url(<resolve(ref)>) or
|
|
14
|
+
// @import "<resolve(ref)>", leaving comments, strings, and references that are absolute, root-relative,
|
|
15
|
+
// fragments or contain CSS escapes as they are.
|
|
14
16
|
export function rewriteUrls(css, resolve) {
|
|
15
|
-
return css.replace(TOKENS, (whole, dq, sq, bare) => {
|
|
16
|
-
const ref = dq ?? sq ?? bare;
|
|
17
|
+
return css.replace(TOKENS, (whole, idq, isq, dq, sq, bare) => {
|
|
18
|
+
const ref = idq ?? isq ?? dq ?? sq ?? bare;
|
|
17
19
|
if (!ref || ref.includes('\\') || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(ref)) return whole;
|
|
18
|
-
return `url(${cssString(resolve(ref))})`;
|
|
20
|
+
return (idq ?? isq) !== undefined ? `@import ${cssString(resolve(ref))}` : `url(${cssString(resolve(ref))})`;
|
|
19
21
|
});
|
|
20
22
|
}
|
|
21
23
|
|
|
22
|
-
// The relative references a stylesheet's url()s make, as rewriteUrls sees them.
|
|
24
|
+
// The relative references a stylesheet's url()s and @imports make, as rewriteUrls sees them.
|
|
23
25
|
export function relativeUrls(css) {
|
|
24
26
|
const refs = [];
|
|
25
27
|
rewriteUrls(css, (ref) => (refs.push(ref), ref));
|
|
26
28
|
return refs;
|
|
27
29
|
}
|
|
30
|
+
|
|
31
|
+
// What may open a stylesheet: white space, a comment, or an @charset, @layer or @import statement.
|
|
32
|
+
// Each character of a statement can match only one way, and a comment ends at its first */, so a long
|
|
33
|
+
// statement that never ends can't make the match backtrack; an unclosed comment ends the opening.
|
|
34
|
+
const COMMENT = String.raw`\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/`;
|
|
35
|
+
const QUOTED = `${STRING('"')}|${STRING("'")}`;
|
|
36
|
+
const group = (inner) => String.raw`\((?:${COMMENT}|${QUOTED}|${inner}|\/(?!\*)|[^()"'/])*\)`;
|
|
37
|
+
const PRELUDE = String.raw`\s+|${COMMENT}|@(charset|layer|import)(?![\w-])(?:${COMMENT}|${QUOTED}|${group(group(group('(?!)')))}|\/(?!\*)|[^;{}()"'/])*(?:;|$)`;
|
|
38
|
+
|
|
39
|
+
// A stylesheet's leading @import rules, which count only before every other rule, with the @layer
|
|
40
|
+
// statements among them so its layers keep their order; and the rest of its text. A stylesheet with no
|
|
41
|
+
// @import comes back whole.
|
|
42
|
+
export function splitImports(css) {
|
|
43
|
+
const prelude = new RegExp(PRELUDE, 'iy');
|
|
44
|
+
const head = [];
|
|
45
|
+
let rest = '';
|
|
46
|
+
let end = 0;
|
|
47
|
+
for (let m; (m = prelude.exec(css)); end = prelude.lastIndex) {
|
|
48
|
+
// One at the very end may have no semicolon; moved ahead of other rules, it needs one.
|
|
49
|
+
if (/^(?:import|layer)$/i.test(m[1] ?? '')) head.push(m[0].endsWith(';') ? m[0] : `${m[0]};`);
|
|
50
|
+
else rest += m[0];
|
|
51
|
+
}
|
|
52
|
+
if (!head.some((rule) => /^@import/i.test(rule))) return { head: [], rest: css };
|
|
53
|
+
return { head, rest: rest + css.slice(end) };
|
|
54
|
+
}
|