mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce1b5d4d89 | ||
|
|
e02d690957 | ||
|
|
5d94a93a03 | ||
|
|
9a4beb1747 | ||
|
|
c03c643a7c | ||
|
|
74d06afca0 | ||
|
|
f285e12ff9 | ||
|
|
6729a1e7bb | ||
|
|
37a61cfc08 | ||
|
|
45ed91c90c | ||
|
|
9909b508e7 | ||
|
|
bd3ac11469 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
A plugin that depends on a plugin of another pipeline stage (an emitter or component on a transformer) no longer fails the build because of their `order`: order is checked only between plugins of the same stage.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Plugin updates with the fixes from a test audit:
|
||||
|
||||
- note-properties: an empty `tags:` or `aliases:` no longer fails the build.
|
||||
- bases-page: sorting, filters, formulas and group headings work as in Obsidian.
|
||||
- encrypted-pages: a numeric `password` encrypts the page, and a custom `outputPath` works.
|
||||
- darkmode, reader-mode, syntax-highlighting and comments: no double handlers after a page is unlocked.
|
||||
- stacked-pages: links work under a base path.
|
||||
- breadcrumbs: `resolveFrontmatterTitle` is honoured.
|
||||
- canvas-page: a `#View` link selects that view.
|
||||
- search: fields left out of `fieldPriority` are searched, and excerpts keep their last word.
|
||||
- explorer: a note next to a folder of the same name stays listed, and folder options apply.
|
||||
- folder-page, og-image, description, table-of-contents, graph, obsidian-flavored-markdown and utils: smaller fixes.
|
||||
- latex: `customMacros` work with MathJax. ox-hugo: figure parameters in backticks.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Relative links and embeds keep their query string after SPA navigation and in popovers (`./viewer.html?file=a.pdf` no longer loses `?file=a.pdf`).
|
||||
Generated
+90
-90
@@ -16,40 +16,40 @@
|
||||
"@quartz-community/alias-redirects": "^1.0.3",
|
||||
"@quartz-community/article-title": "^1.0.2",
|
||||
"@quartz-community/backlinks": "^1.0.4",
|
||||
"@quartz-community/bases-page": "^1.5.5",
|
||||
"@quartz-community/breadcrumbs": "^1.0.5",
|
||||
"@quartz-community/canvas-page": "^1.1.4",
|
||||
"@quartz-community/bases-page": "^1.5.6",
|
||||
"@quartz-community/breadcrumbs": "^1.0.6",
|
||||
"@quartz-community/canvas-page": "^1.1.6",
|
||||
"@quartz-community/citations": "^1.0.1",
|
||||
"@quartz-community/cname": "^1.0.1",
|
||||
"@quartz-community/comments": "^1.0.2",
|
||||
"@quartz-community/comments": "^1.0.3",
|
||||
"@quartz-community/content-meta": "^1.0.2",
|
||||
"@quartz-community/content-page": "^1.0.3",
|
||||
"@quartz-community/created-modified-date": "^1.0.5",
|
||||
"@quartz-community/darkmode": "^1.0.2",
|
||||
"@quartz-community/description": "^1.0.2",
|
||||
"@quartz-community/encrypted-pages": "^1.2.0",
|
||||
"@quartz-community/darkmode": "^1.0.3",
|
||||
"@quartz-community/description": "^1.0.3",
|
||||
"@quartz-community/encrypted-pages": "^1.3.1",
|
||||
"@quartz-community/explicit-publish": "^1.2.0",
|
||||
"@quartz-community/explorer": "^1.2.2",
|
||||
"@quartz-community/explorer": "^1.2.5",
|
||||
"@quartz-community/favicon": "^1.0.1",
|
||||
"@quartz-community/folder-page": "^1.1.3",
|
||||
"@quartz-community/folder-page": "^1.1.4",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.8",
|
||||
"@quartz-community/graph": "^1.0.9",
|
||||
"@quartz-community/hard-line-breaks": "^1.1.0",
|
||||
"@quartz-community/latex": "^1.1.2",
|
||||
"@quartz-community/note-properties": "^1.2.3",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
|
||||
"@quartz-community/og-image": "^1.1.3",
|
||||
"@quartz-community/ox-hugo": "^1.0.3",
|
||||
"@quartz-community/latex": "^1.1.3",
|
||||
"@quartz-community/note-properties": "^1.2.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
|
||||
"@quartz-community/og-image": "^1.1.4",
|
||||
"@quartz-community/ox-hugo": "^1.0.4",
|
||||
"@quartz-community/page-title": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.3",
|
||||
"@quartz-community/recent-notes": "^1.0.3",
|
||||
"@quartz-community/roam": "^1.1.0",
|
||||
"@quartz-community/search": "^1.1.2",
|
||||
"@quartz-community/search": "^1.1.4",
|
||||
"@quartz-community/spacer": "^1.0.2",
|
||||
"@quartz-community/stacked-pages": "^1.0.3",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.4",
|
||||
"@quartz-community/table-of-contents": "^1.0.5",
|
||||
"@quartz-community/stacked-pages": "^1.0.4",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.5",
|
||||
"@quartz-community/table-of-contents": "^1.0.6",
|
||||
"@quartz-community/tag-list": "^1.0.3",
|
||||
"@quartz-community/tag-page": "^1.0.7",
|
||||
"@quartz-community/unlisted-pages": "^1.2.0",
|
||||
@@ -97,7 +97,7 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.2",
|
||||
"@quartz-community/utils": "^1.3.3",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
@@ -2330,9 +2330,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/bases-page": {
|
||||
"version": "1.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.5.tgz",
|
||||
"integrity": "sha512-aUJgKt3KjP2UOT4sfeHugkwMyptqXpkRBrHiOthyEND2NI43kZUTNQ2FicTZQLDMLOSnuUu4PXgHv0NF4Ntyrw==",
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.6.tgz",
|
||||
"integrity": "sha512-ohlqctMKbxneePgYKMOImCHhmo798OCyD3WuNw7QyXyIY6t3HhodvTVrtpxinlWmI6ug/kELsTyEbgrgtzAZVA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lucide/icons": "^1.70.0",
|
||||
@@ -2361,9 +2361,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/breadcrumbs": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/breadcrumbs/-/breadcrumbs-1.0.5.tgz",
|
||||
"integrity": "sha512-xnEyZ1N7s3Q5KFu4V5K5f+bQ4H1XmJMMNfCCDUVHJj1Y9ZAHpgg3ICmAas2WBLcVOjw6SkBlIFTNpLAbaRsZLw==",
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/breadcrumbs/-/breadcrumbs-1.0.6.tgz",
|
||||
"integrity": "sha512-YkEdGAtoeO4NupgwbTLBh2ownp4ALjGCMAlDkPocY3v8k2E+VDRXKRlnuqALv/wvR++nAz64U3zBGoD686sW5g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2383,9 +2383,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/canvas-page": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.4.tgz",
|
||||
"integrity": "sha512-HNvwpnIbv887epOKTKcr1fMV9cSN6JjQw7mxNSiBJSSe9dtYUu4F7FPIFE33JFSWOpilDgV6f+ApnYVQ1c9yaA==",
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.6.tgz",
|
||||
"integrity": "sha512-Cuu3xxC1PCKM5+ixO58cnNmK0So9RHnE1bxVLPW619b0tCL2ZyuN4QQK4yCN7ia8N6uiLyI+jqAALMS1+tl9fA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2443,9 +2443,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/comments": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/comments/-/comments-1.0.2.tgz",
|
||||
"integrity": "sha512-cHFjN7yn7rxgDzEOboM5viYOk1ex4Y/gIfDqN/BLNlqhPaZIkl2dq7RcYmkeVAz9kAJqNSj+WPQdVpB/2PGIGw==",
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/comments/-/comments-1.0.3.tgz",
|
||||
"integrity": "sha512-p4NMrXIBXuFXRd7OIVTkIE8Q8Zta7fjdESR4ozrAtWISiYp3JIIQGOZXxfaKho7PpkE6/9PFkeTA9ze6HSvuOA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2538,9 +2538,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/darkmode": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/darkmode/-/darkmode-1.0.2.tgz",
|
||||
"integrity": "sha512-FCfR8bdg248Y1NJhN6TWVBENwFiJak3gwqmpof/GMeTXr6e76FPe2ggTTz66a+s9UQ/ZC3JKU9xpHQi0zcGhyQ==",
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/darkmode/-/darkmode-1.0.3.tgz",
|
||||
"integrity": "sha512-KbhU+TInNMAr+eV8x/yR56piDWQbRjhX6YhWxx0BgFBcvS84LGLsgz+5EHpB34ybsTJvUjjoj9rPTGVlFIR/ww==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2560,9 +2560,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/description": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/description/-/description-1.0.2.tgz",
|
||||
"integrity": "sha512-Mb0VqNOqiY9UQLK0y7p2/LVJAUqH8ra3Pek0Gz8q35FxJXkv2RDyjNb49qMUM0dpIaLVUkv9GBuKxeoxbwt4Yg==",
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/description/-/description-1.0.3.tgz",
|
||||
"integrity": "sha512-xfVkexOUFnGVMOyXZYins32KEAkKKn1Qt6ywUwRwXiibE1xz0sXU3Z4EE0vKfeR6RxGnLiM+EfgX6DTWLmKEpA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2582,9 +2582,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/encrypted-pages": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.3.0.tgz",
|
||||
"integrity": "sha512-V04420LqG90y+LsZ7e9cOhRdHg/uVKKq0trWxjACnBQaHD9pAw/ODBh2FuXvjvj8ZuzzelRD6sIVeS9vq2isLg==",
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.3.1.tgz",
|
||||
"integrity": "sha512-BWgChS+Ni+VdGAENhTu7EDWoDRrj3/k/hMynEdIf5YpCE0cB0RvkNtYskys73BxMfO+TwmT9vpMBbpHenXa4iw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2621,9 +2621,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/explorer": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/explorer/-/explorer-1.2.2.tgz",
|
||||
"integrity": "sha512-pbkcUxmY0xwolEetcSqw3tH4quHdT2robkjCLTRT75OoQVG0jlSTPGnVJAAYErsXMyBKU8Eek7EQD0dZfBVyyg==",
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/explorer/-/explorer-1.2.5.tgz",
|
||||
"integrity": "sha512-VXKEx1IcOmdiLThHBkL8kOr6K+ofzweedGd6GVQXi8FmCemo7OUzBAkdUVkhqSEBogS3pT/znGM0K7sEF+mHyg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2664,9 +2664,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/folder-page": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.3.tgz",
|
||||
"integrity": "sha512-eklsnqXUTgRKGKhoaIC/8A2Tlrs5MCQyn4XSptR6FNaFGbUPBVM+Tg71qfCAB1klBZ/1wIIm+Ouw66AJXXN4IQ==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.4.tgz",
|
||||
"integrity": "sha512-aEaXi5qJdWPMMvtBakaVw/wDU/iVf5ujW1hMnBxDJyCDXF9FRdk1njeFi+Op299y5SWnF7+ruLjhraqeaYLnCA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2734,9 +2734,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/graph": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.8.tgz",
|
||||
"integrity": "sha512-7BCIGU3r8qYFFKu0YkGduo4DS0sIGZZNmDOc9TYP5gqMQIs6cXRuLoBkJmRjXnYSfDPBZ0dJQlAHmij61+THpA==",
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.9.tgz",
|
||||
"integrity": "sha512-7t6v0i9dPr8JIWRQEalszHk25pmhapns/mD18zyt0P1EwbZrU8Kbc5l6nXFM7jSq/pfigDvo9GmcNFFtTMYK1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2777,9 +2777,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/latex": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/latex/-/latex-1.1.2.tgz",
|
||||
"integrity": "sha512-NdF9tLelQ7CclJLZy8RiHSJHJGy5udfG2js7eXD0BTbwVhouTij/eX1TqDrnrZqPOU271A9m7aZUUmnIE/aebg==",
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/latex/-/latex-1.1.3.tgz",
|
||||
"integrity": "sha512-7692k+HBHmWwYhONTA5BMZOOCsVxubuirsBTk9ySh+0SgTcUxpYX9lXaaX32wO6Kxs0NX4XBsHdVLPdYjHt2Mw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
@@ -2802,9 +2802,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/note-properties": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.3.tgz",
|
||||
"integrity": "sha512-udQ8hWrkX9V1tcrxyxRniE8QkFXHAp1AFYjhZ9ZcRFNdSxgyu7Q18vHRl65jrW7MKoApN6VB3dOjUwiM1hn88A==",
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.4.tgz",
|
||||
"integrity": "sha512-ZFShM1V+zwoHI6q3OHkgwfTLtoQGRiWkCLYjQZQFyxKMMKZJt/YAacwA+fSk75Uc0jnn0oQTJjWNeewvez4fHw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2828,9 +2828,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/obsidian-flavored-markdown": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.3.tgz",
|
||||
"integrity": "sha512-nevXFettUGuQemzqcXkDiUjKLeUKQ36RkITQx36G56gAB1TkrHv03gP4iX9EVXHi/9ZCSlgDdyHIkDRgP0lL4Q==",
|
||||
"version": "2.5.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.4.tgz",
|
||||
"integrity": "sha512-TxSDvn3FTGa0FvEEoIA+CVQmqCrLhAWxQmhkBevjUEaAYPaW8xUU8lLm36Cb14Baoze6JnbDJ9csMHr6k/D5Vw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/rehype-obsidian": "^1.6.0",
|
||||
@@ -2853,9 +2853,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/og-image": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.1.3.tgz",
|
||||
"integrity": "sha512-Dljt4OhrdupDZiIDf1Om5Bi/7LBlZATo+pWdufpKwskEIHoDadEpHbf/TzFlPzdRTJ2EjH2d/v2vD2L+YwX6tw==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.1.4.tgz",
|
||||
"integrity": "sha512-aJyXYMjIPrj3M3jFoYyqW/YODKmSoJP+bbQ5LyH0FnpuWGIGDBPVRqYmx5qUuiVjc5SMiVMMf8AyWuH63nCbUQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2883,9 +2883,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/ox-hugo": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/ox-hugo/-/ox-hugo-1.0.3.tgz",
|
||||
"integrity": "sha512-emizGp+iuZfG5C+mbb1fQ84vCZ9fqTJJuDXKaJzf5J+tMS+sEffcR5/7jC50+v4dQZY7ZSPXBLIwFgmcwvChLw==",
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/ox-hugo/-/ox-hugo-1.0.4.tgz",
|
||||
"integrity": "sha512-ptVP2qxdW4/BdVl20S+kfsRT1SyjcYGfICNqNJ4GLbVkE9gXWhS2QR8KZ7vXmwQ60XV5B23oYEnqH0zkz5ViFg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
@@ -2926,9 +2926,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/reader-mode": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/reader-mode/-/reader-mode-1.0.2.tgz",
|
||||
"integrity": "sha512-Mm7llTF6erRk9ASrkcfYIKApfFf/yrBiYsPs+P8vx8qXaVziem/4e2G6wnT2EQQFUuYSSKklZ328V7rfN6fRRg==",
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/reader-mode/-/reader-mode-1.0.3.tgz",
|
||||
"integrity": "sha512-rlLFcmyIp6iYLIMajQtO11OpkRj7RofrQD3DBLRn2rNzl3ySe8pfU0WpvoyRRK/clD2/lGtwrTNJa76WG6K0Vg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2970,18 +2970,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/rehype-obsidian": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.6.0.tgz",
|
||||
"integrity": "sha512-7NyJNKr515xtCBBhzLr4UdoENutGPgAJhh3GA0S3j6Qj2r7v+hFNSq4yd3gtFP0GK7b4PPfOtTTyAWCC8BYiig==",
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.6.1.tgz",
|
||||
"integrity": "sha512-+YlDMPBjCUbuIvbxrDvipXXTuRjrFaL9QYrwkxRgong7HsAzTqu0XSl43ih3/GgxR8xKNECThVxJiMlmdvUXUw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/remark-obsidian": {
|
||||
"version": "2.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.4.tgz",
|
||||
"integrity": "sha512-VD5gkPCAygxLAhlFE3afaLhyWkPO8F7H89fHzLPd9uzpTR+NrcVbYrIMU8VTd3eXwxpdOGWxeX7K2y5lMw6kQQ==",
|
||||
"version": "2.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.5.tgz",
|
||||
"integrity": "sha512-xlJX+6XIWEBCPnJ4Mg8Xnrxeh2+pq0XAKUWXGOEY0kHNf2uDsiM5VRTd15/4jR1J2FN2KmOAB7jV+8J0xSlnqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -3019,9 +3019,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/search": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.2.tgz",
|
||||
"integrity": "sha512-pgAdTLGU9yVMXtlD9YGi9/wDV4ktMBwnGwLAOJmQcDkOBLVIS0T2SAIksiaCr5OrV9L+8yiAZ1BmasSxqThn4g==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.4.tgz",
|
||||
"integrity": "sha512-s02rNbjLkg4rVNdA0Pr2LHlGK1zn0PcS2+mBoyWqhZ4vZraGKgLpbAUiDgXD740GU630vcpEwmtT0FNWbgzl9g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -3062,9 +3062,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/stacked-pages": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.3.tgz",
|
||||
"integrity": "sha512-wdILZkQpYL9k490iXzNRkWtrDyRBxCfs+rqz3JUWPyMAq3ztlyH0UtDoyB+zDUN9XryPqmTf0b3rtiKlQLiJFg==",
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.4.tgz",
|
||||
"integrity": "sha512-XQsi9CwReWxr7c6e1uWHpYYegQfpaL+sPPASkM+RVX0pw21V9aYpMy0HRFWpbyJnpIM847rVPfZ6W3IH3Db/mw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -3088,9 +3088,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/syntax-highlighting": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/syntax-highlighting/-/syntax-highlighting-1.0.4.tgz",
|
||||
"integrity": "sha512-4qCnsPGyEImFPPgyH9J4w5Y8NCG9gV8ra1UV6/mQJHXLN6m0i1KewwpV9hyEqNlgPJ0TyDJh04XVGcY1t3Ts6A==",
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/syntax-highlighting/-/syntax-highlighting-1.0.5.tgz",
|
||||
"integrity": "sha512-u9yzkNK5NefFaFMp+tOOEaVs/NxmfR2HLXbmkXt4HHwztfGPue1gi8ZUixeY6NSjGWBFx/i+RofpCcrhDycFjg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
@@ -3113,9 +3113,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/table-of-contents": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/table-of-contents/-/table-of-contents-1.0.5.tgz",
|
||||
"integrity": "sha512-sz7SqYgn+bCAp6evvPSXLNGmC93XZZB+Dt7TUZEHN6Kgnct0QCo32NFsjm7B3Bah0JuMyJ/oCrX47zvO6q99wg==",
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/table-of-contents/-/table-of-contents-1.0.6.tgz",
|
||||
"integrity": "sha512-8pc8lpOY4Awqiso16cSqqIrXy9kXy+n56uajFbtm7IHzZvXNsdh5JnXsowVUaJBONMnAu20ASFDGwVub5PUQGQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -3230,9 +3230,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/utils": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.2.tgz",
|
||||
"integrity": "sha512-50SiiB1HY2zdpjO7SUJklITcFqH/sJNq6PE1a8dtc8HIvQfPW4kXALoiPUqvaYzcBVscnkZ9rfmlSgn/vaA4eA==",
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.3.tgz",
|
||||
"integrity": "sha512-g33lwWCBL1SpcWP/NgClXUMG8BILrGbkT6/7xR/Dtnf0X8DP+1em+emRJElckzxGUXsLnDY+jvhn4zu8xaXXFQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
|
||||
+21
-21
@@ -46,40 +46,40 @@
|
||||
"@quartz-community/alias-redirects": "^1.0.3",
|
||||
"@quartz-community/article-title": "^1.0.2",
|
||||
"@quartz-community/backlinks": "^1.0.4",
|
||||
"@quartz-community/bases-page": "^1.5.5",
|
||||
"@quartz-community/breadcrumbs": "^1.0.5",
|
||||
"@quartz-community/canvas-page": "^1.1.4",
|
||||
"@quartz-community/bases-page": "^1.5.6",
|
||||
"@quartz-community/breadcrumbs": "^1.0.6",
|
||||
"@quartz-community/canvas-page": "^1.1.6",
|
||||
"@quartz-community/citations": "^1.0.1",
|
||||
"@quartz-community/cname": "^1.0.1",
|
||||
"@quartz-community/comments": "^1.0.2",
|
||||
"@quartz-community/comments": "^1.0.3",
|
||||
"@quartz-community/content-meta": "^1.0.2",
|
||||
"@quartz-community/content-page": "^1.0.3",
|
||||
"@quartz-community/created-modified-date": "^1.0.5",
|
||||
"@quartz-community/darkmode": "^1.0.2",
|
||||
"@quartz-community/description": "^1.0.2",
|
||||
"@quartz-community/encrypted-pages": "^1.2.0",
|
||||
"@quartz-community/darkmode": "^1.0.3",
|
||||
"@quartz-community/description": "^1.0.3",
|
||||
"@quartz-community/encrypted-pages": "^1.3.1",
|
||||
"@quartz-community/explicit-publish": "^1.2.0",
|
||||
"@quartz-community/explorer": "^1.2.2",
|
||||
"@quartz-community/explorer": "^1.2.5",
|
||||
"@quartz-community/favicon": "^1.0.1",
|
||||
"@quartz-community/folder-page": "^1.1.3",
|
||||
"@quartz-community/folder-page": "^1.1.4",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.8",
|
||||
"@quartz-community/graph": "^1.0.9",
|
||||
"@quartz-community/hard-line-breaks": "^1.1.0",
|
||||
"@quartz-community/latex": "^1.1.2",
|
||||
"@quartz-community/note-properties": "^1.2.3",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.3",
|
||||
"@quartz-community/og-image": "^1.1.3",
|
||||
"@quartz-community/ox-hugo": "^1.0.3",
|
||||
"@quartz-community/latex": "^1.1.3",
|
||||
"@quartz-community/note-properties": "^1.2.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
|
||||
"@quartz-community/og-image": "^1.1.4",
|
||||
"@quartz-community/ox-hugo": "^1.0.4",
|
||||
"@quartz-community/page-title": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.3",
|
||||
"@quartz-community/recent-notes": "^1.0.3",
|
||||
"@quartz-community/roam": "^1.1.0",
|
||||
"@quartz-community/search": "^1.1.2",
|
||||
"@quartz-community/search": "^1.1.4",
|
||||
"@quartz-community/spacer": "^1.0.2",
|
||||
"@quartz-community/stacked-pages": "^1.0.3",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.4",
|
||||
"@quartz-community/table-of-contents": "^1.0.5",
|
||||
"@quartz-community/stacked-pages": "^1.0.4",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.5",
|
||||
"@quartz-community/table-of-contents": "^1.0.6",
|
||||
"@quartz-community/tag-list": "^1.0.3",
|
||||
"@quartz-community/tag-page": "^1.0.7",
|
||||
"@quartz-community/unlisted-pages": "^1.2.0",
|
||||
@@ -124,7 +124,7 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.2",
|
||||
"@quartz-community/utils": "^1.3.3",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
|
||||
@@ -1169,3 +1169,253 @@ describe("links to pages removed by filters (crawl-links#7)", () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("links built-in: options, other elements and edge cases", () => {
|
||||
const el = (tagName: string, properties: Element["properties"], text?: string): Element => ({
|
||||
type: "element",
|
||||
tagName,
|
||||
properties,
|
||||
children: text === undefined ? [] : [{ type: "text", value: text }],
|
||||
})
|
||||
const a = (href: string, text = href) => el("a", { href }, text)
|
||||
function run(
|
||||
nodes: Element[],
|
||||
{
|
||||
slug = "folder/page",
|
||||
opts = {},
|
||||
allSlugs = ["folder/page"],
|
||||
data = {},
|
||||
permalinks,
|
||||
}: {
|
||||
slug?: string
|
||||
opts?: Record<string, unknown>
|
||||
allSlugs?: string[]
|
||||
data?: Record<string, unknown>
|
||||
permalinks?: Record<string, string>
|
||||
} = {},
|
||||
) {
|
||||
const tree: Root = { type: "root", children: nodes }
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
|
||||
const ctx = { allSlugs, permalinks } as unknown as BuildCtx
|
||||
const [factory] = Links(opts).htmlPlugins!(ctx) as [() => (t: Root, f: VFile) => void]
|
||||
factory()(tree, file)
|
||||
return { nodes, file }
|
||||
}
|
||||
const classes = (e: Element) => e.properties.className as string[] | undefined
|
||||
const text = (e: Element) => (e.children[0] as Text).value
|
||||
|
||||
test("defaults: pretty links, external links open in place with an icon, no lazy loading", () => {
|
||||
const { nodes } = run([
|
||||
a("https://example.com/a/b"),
|
||||
a("other/note"),
|
||||
el("img", { src: "pic.png", alt: "x" }),
|
||||
])
|
||||
const [external, internal, img] = nodes
|
||||
assert.strictEqual(external.properties.target, undefined)
|
||||
assert.strictEqual(text(external), "https://example.com/a/b")
|
||||
assert.deepStrictEqual(external.children[1], {
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
"aria-hidden": "true",
|
||||
class: "external-icon",
|
||||
style: "max-width:0.8em;max-height:0.8em",
|
||||
viewBox: "0 0 512 512",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
d: "M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
assert.strictEqual(text(internal), "note")
|
||||
assert.strictEqual(img.properties.loading, undefined)
|
||||
})
|
||||
|
||||
test("openLinksInNewTab and externalLinkIcon: false apply to external links only", () => {
|
||||
const { nodes } = run([a("https://example.com"), a("other")], {
|
||||
opts: { openLinksInNewTab: true, externalLinkIcon: false },
|
||||
})
|
||||
const [external, internal] = nodes
|
||||
assert.strictEqual(external.properties.target, "_blank")
|
||||
assert.strictEqual(external.children.length, 1)
|
||||
assert.strictEqual(internal.properties.target, undefined)
|
||||
})
|
||||
|
||||
test("prettyLinks: false keeps the link text; text that isn't a single text node is left alone", () => {
|
||||
const off = run([a("folder/note")], { opts: { prettyLinks: false } }).nodes
|
||||
assert.strictEqual(text(off[0]), "folder/note")
|
||||
const formatted: Element = {
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: "folder/note" },
|
||||
children: [el("em", {}, "folder/note"), { type: "text", value: " more" }],
|
||||
}
|
||||
run([formatted])
|
||||
assert.strictEqual(text(formatted.children[0] as Element), "folder/note")
|
||||
assert.strictEqual((formatted.children[1] as Text).value, " more")
|
||||
assert.ok(!classes(formatted)!.includes("alias"))
|
||||
})
|
||||
|
||||
test("lazyLoad and src resolution for img, video, audio and iframe; external sources are kept", () => {
|
||||
const { nodes } = run(
|
||||
[
|
||||
el("img", { src: "a.png", alt: "a" }),
|
||||
el("video", { src: "v.mp4" }),
|
||||
el("audio", { src: "s.mp3" }),
|
||||
el("iframe", { src: "doc.pdf" }),
|
||||
el("img", { src: "https://cdn.example.com/x.png", alt: "x" }),
|
||||
el("script", { src: "x.js" }),
|
||||
],
|
||||
{ opts: { lazyLoad: true, markdownLinkResolution: "absolute" } },
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => [n.properties.src, n.properties.loading]),
|
||||
[
|
||||
["../a.png", "lazy"],
|
||||
["../v.mp4", "lazy"],
|
||||
["../s.mp3", "lazy"],
|
||||
["../doc.pdf", "lazy"],
|
||||
["https://cdn.example.com/x.png", "lazy"],
|
||||
["x.js", undefined],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("only an image of a missing file gets its path as alt text", () => {
|
||||
const { nodes } = run([el("video", { src: "missing.mp4" }), el("img", { src: "#x" })])
|
||||
assert.strictEqual(nodes[0].properties.alt, undefined)
|
||||
assert.strictEqual(nodes[1].properties.alt, undefined)
|
||||
})
|
||||
|
||||
test("object[data] / source[src] that are empty, fragments or external are not rewritten", () => {
|
||||
const values = ["", "#frag", "https://example.com/x.svg"]
|
||||
const { nodes } = run([
|
||||
...values.map((data) => el("object", { data })),
|
||||
...values.map((src) => el("source", { src })),
|
||||
])
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => n.properties.data ?? n.properties.src),
|
||||
[...values, ...values],
|
||||
)
|
||||
})
|
||||
|
||||
test("anchors without an href are not links", () => {
|
||||
const named = el("a", { id: "here" }, "folder/x")
|
||||
run([named])
|
||||
assert.deepStrictEqual(named.properties, { id: "here" })
|
||||
assert.strictEqual(text(named), "folder/x")
|
||||
})
|
||||
|
||||
test("the home page and folder pages: index always exists; a folder needs a page under it", () => {
|
||||
const { nodes } = run([a("/"), a("/fold/"), a("/folder/"), a("/a/")], {
|
||||
slug: "page",
|
||||
allSlugs: ["page", "folder/note", "a/b"],
|
||||
})
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => classes(n)!.includes("broken")),
|
||||
[false, true, false, false],
|
||||
)
|
||||
})
|
||||
|
||||
test("a missing vault file's type is its last extension", () => {
|
||||
const { nodes } = run([a("/missing.txt.png"), a("/missing.png.txt")], { slug: "page" })
|
||||
assert.deepStrictEqual(
|
||||
nodes.map((n) => classes(n)!.includes("broken")),
|
||||
[true, false],
|
||||
)
|
||||
})
|
||||
|
||||
test("permalinks: a link's heading anchor is kept when it is rebased onto the permalink", () => {
|
||||
const { nodes, file } = run([a("target#Some Heading", "Target"), a("#local")], {
|
||||
slug: "home",
|
||||
data: { relativePath: "folder/page.md" },
|
||||
allSlugs: ["home", "t", "folder/page", "folder/target"],
|
||||
permalinks: { "folder/page.md": "home", "folder/target.md": "t" },
|
||||
})
|
||||
assert.strictEqual(nodes[0].properties.href, "./t#some-heading")
|
||||
assert.strictEqual(nodes[1].properties.href, "#local")
|
||||
assert.deepStrictEqual(file.data.links, ["t"])
|
||||
})
|
||||
|
||||
test("frontmatter links: a bare #heading adds no outgoing link, note#heading links the note", () => {
|
||||
const { file } = run([], {
|
||||
data: { frontmatterLinks: ["#intro", "other#part", "https://example.com"] },
|
||||
opts: { markdownLinkResolution: "absolute" },
|
||||
})
|
||||
assert.deepStrictEqual(file.data.links, ["other"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("links to removed pages: marks that change", () => {
|
||||
const link = (slug: string): Element => ({
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
|
||||
children: [{ type: "text", value: slug }],
|
||||
})
|
||||
const page = (slug: string, children: Element[], data: Record<string, unknown> = {}) => {
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
|
||||
return [{ type: "root", children } as Root, file] as ProcessedContent
|
||||
}
|
||||
|
||||
test("a filter that changes re-marks the link once and re-emits the page", () => {
|
||||
const home = page("index", [link("draft")])
|
||||
const changed = new Set<FullSlug>()
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
|
||||
const a = (home[0] as Root).children[0] as Element
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
|
||||
changed.clear()
|
||||
markUnpublishedLinks([home], new Map([["draft", "ExplicitPublish"]]), undefined, changed)
|
||||
assert.deepStrictEqual([...changed], ["index"])
|
||||
assert.strictEqual(a.properties["data-filtered"], "ExplicitPublish")
|
||||
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
|
||||
})
|
||||
|
||||
test("removedPages names the filter, 'filter' when unknown, and the first removed page wins", () => {
|
||||
const home = page("index", [])
|
||||
const a = page("a", [], { aliases: ["shared"] })
|
||||
const b = page("b", [], { aliases: ["shared"] })
|
||||
const noSlug = page("", [])
|
||||
noSlug[1].data.slug = undefined
|
||||
assert.deepStrictEqual(
|
||||
[...removedPages([home, a, b, noSlug], [home])],
|
||||
[
|
||||
["a", "filter"],
|
||||
["shared", "filter"],
|
||||
["b", "filter"],
|
||||
],
|
||||
)
|
||||
const reasons = removedPages([home, a, b], [home], (s) => (s === "a" ? "Drafts" : undefined))
|
||||
assert.deepStrictEqual(
|
||||
[...reasons],
|
||||
[
|
||||
["a", "Drafts"],
|
||||
["shared", "Drafts"],
|
||||
["b", "filter"],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("only <a> elements are marked; the tags index is a generated target", () => {
|
||||
const div: Element = {
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { "data-slug": "draft" },
|
||||
children: [],
|
||||
}
|
||||
const home = page("index", [div, link("tags")])
|
||||
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), new Set())
|
||||
assert.deepStrictEqual(div.properties, { "data-slug": "draft" })
|
||||
const tags = (home[0] as Root).children[1] as Element
|
||||
assert.strictEqual(tags.properties["data-missing"], "")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,430 @@
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { registerHooks } from "node:module"
|
||||
import test, { after, describe } from "node:test"
|
||||
import { createContext, runInContext } from "node:vm"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent } from "../../components/types"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { GlobalConfiguration } from "../../cfg"
|
||||
|
||||
// The emitter imports SCSS and inline browser scripts that esbuild bundles in a real build. Under
|
||||
// tsx each one is replaced by a marker: `.stub-<name>{--stub:<name>}` for SCSS, `window.__stub_<name>`
|
||||
// for scripts, so the tests can tell where each one ends up.
|
||||
registerHooks({
|
||||
load(url, context, next) {
|
||||
const name = path.basename(new URL(url).pathname).replace(/\.(inline\.ts|scss)$/, "")
|
||||
if (url.endsWith(".scss")) {
|
||||
const css = `.stub-${name.replace(/\W/g, "_")}{--stub:${name.replace(/\W/g, "_")}}`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(css)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
if (/\.inline\.ts$/.test(url)) {
|
||||
const js = `window.__stub_${name} = 1`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(js)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
return next(url, context)
|
||||
},
|
||||
})
|
||||
const { ComponentResources } = await import("./componentResources")
|
||||
|
||||
const theme = {
|
||||
fontOrigin: "local",
|
||||
cdnCaching: true,
|
||||
typography: { header: "Header Font", body: "Body Font", code: "Code Font" },
|
||||
colors: {
|
||||
lightMode: {
|
||||
light: "#fff",
|
||||
lightgray: "#eee",
|
||||
gray: "#999",
|
||||
darkgray: "#444",
|
||||
dark: "#222",
|
||||
secondary: "#00f",
|
||||
tertiary: "#0f0",
|
||||
highlight: "#ff0",
|
||||
textHighlight: "#ff08",
|
||||
},
|
||||
darkMode: {
|
||||
light: "#000",
|
||||
lightgray: "#111",
|
||||
gray: "#666",
|
||||
darkgray: "#bbb",
|
||||
dark: "#ddd",
|
||||
secondary: "#88f",
|
||||
tertiary: "#8f8",
|
||||
highlight: "#880",
|
||||
textHighlight: "#8808",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const Widget: QuartzComponent = Object.assign(() => null, {
|
||||
css: ".widget{color:blue}",
|
||||
beforeDOMLoaded: "window.__widgetBefore = 1",
|
||||
afterDOMLoaded: "window.__widgetAfter = 1",
|
||||
})
|
||||
const Other: QuartzComponent = Object.assign(() => null, {
|
||||
css: [".other{color:green}"],
|
||||
afterDOMLoaded: ["window.__otherAfter = 1"],
|
||||
})
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function emit(
|
||||
configuration: Partial<GlobalConfiguration>,
|
||||
{
|
||||
serve = false,
|
||||
resources = { css: [], js: [], additionalHead: [] } as StaticResources,
|
||||
// the same component from two emitters is collected once; an emitter may have none
|
||||
emitters = [
|
||||
{ getQuartzComponents: () => [Widget, Other] },
|
||||
{ getQuartzComponents: () => [Widget] },
|
||||
{},
|
||||
] as unknown[],
|
||||
} = {},
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-component-resources-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve },
|
||||
cfg: {
|
||||
configuration: { enableSPA: true, enablePopovers: true, theme, ...configuration },
|
||||
plugins: { emitters },
|
||||
},
|
||||
} as unknown as BuildCtx
|
||||
const written: string[] = []
|
||||
for await (const fp of ComponentResources().emit(ctx, [], resources) as AsyncIterable<string>) {
|
||||
written.push(path.relative(output, fp).split(path.sep).join("/"))
|
||||
}
|
||||
const read = (name: string) => fs.readFileSync(path.join(output, name), "utf8")
|
||||
return { ctx, written, read }
|
||||
}
|
||||
|
||||
/** The script files postscript.js imports, in its order, with whether each is awaited alone. */
|
||||
function importedScripts(postscript: string) {
|
||||
return [...postscript.matchAll(/import\("\.\/([^"]+)"\)/g)].map((m) => m[1])
|
||||
}
|
||||
|
||||
describe("ComponentResources emitter", () => {
|
||||
test("production: content-hashed index.css / prescript / postscript, named in ctx.hashedResourceNames", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const names = ctx.hashedResourceNames!
|
||||
assert.match(names["index.css"], /^index-[0-9a-f]{8}\.css$/)
|
||||
assert.match(names["prescript.js"], /^prescript-[0-9a-f]{8}\.js$/)
|
||||
assert.match(names["postscript.js"], /^postscript-[0-9a-f]{8}\.js$/)
|
||||
for (const file of Object.values(names)) assert.ok(written.includes(file), file)
|
||||
|
||||
// components' beforeDOMLoaded scripts go in the prescript (once, though listed twice)
|
||||
const prescript = read(names["prescript.js"])
|
||||
assert.equal(prescript.split("__widgetBefore").length, 2)
|
||||
})
|
||||
|
||||
test("production: postscript loads component scripts in parallel and the SPA router last", async () => {
|
||||
const { ctx, written, read } = await emit({ prefetch: "hover" })
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const scripts = importedScripts(postscript)
|
||||
for (const s of scripts) {
|
||||
assert.match(s, /^static\/scripts\/script-\d+-[0-9a-f]{8}\.js$/)
|
||||
assert.ok(written.includes(s), s)
|
||||
}
|
||||
const contents = scripts.map(read)
|
||||
// component scripts, then the global ones: popover, prefetch (with its settings), router
|
||||
assert.deepEqual(
|
||||
contents.map((c) =>
|
||||
c.includes("__widgetAfter")
|
||||
? "widget"
|
||||
: c.includes("__otherAfter")
|
||||
? "other"
|
||||
: c.includes("__stub_popover")
|
||||
? "popover"
|
||||
: c.includes("__stub_prefetch")
|
||||
? "prefetch"
|
||||
: c.includes("__stub_spa")
|
||||
? "spa"
|
||||
: c,
|
||||
),
|
||||
["widget", "other", "popover", "prefetch", "spa"],
|
||||
)
|
||||
assert.match(
|
||||
contents[3],
|
||||
/window\.__quartzPrefetchMode = "hover";\nwindow\.__quartzSpa = true;/,
|
||||
)
|
||||
// all but the router are imported together; the router (which dispatches the first `nav`)
|
||||
// only after they all registered their listeners
|
||||
const last = scripts[scripts.length - 1]
|
||||
const [parallel, rest] = postscript.split(`await import("./${last}")`)
|
||||
assert.ok(parallel.startsWith("await Promise.all(["), postscript)
|
||||
assert.ok(!parallel.includes("__stub_spa") && !parallel.includes(last), postscript)
|
||||
for (const s of scripts.slice(0, -1)) assert.ok(parallel.includes(`import("./${s}")`), s)
|
||||
assert.equal(rest.trim(), ";")
|
||||
})
|
||||
|
||||
test("prefetching defaults to viewport mode", async () => {
|
||||
const { ctx, read } = await emit({ prefetch: undefined })
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
const prefetch = scripts.find((s) => s.includes("__stub_prefetch"))!
|
||||
assert.match(prefetch, /^window\.__quartzPrefetchMode = "viewport";/)
|
||||
})
|
||||
|
||||
test("without SPA routing the last script dispatches the first nav itself; prefetch: false loads no prefetcher", async () => {
|
||||
const { ctx, read } = await emit({
|
||||
enableSPA: false,
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
})
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_spa")))
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_prefetch") || s.includes("__stub_popover")))
|
||||
assert.match(scripts[scripts.length - 1], /new CustomEvent\("nav"/)
|
||||
assert.ok(!read(ctx.hashedResourceNames!["index.css"]).includes("stub-popover"))
|
||||
})
|
||||
|
||||
test("component CSS goes into one component stylesheet; index.css has theme, global and base styles", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const componentFile = written.find((f) => /^component-[0-9a-f]{8}\.css$/.test(f))
|
||||
assert.ok(componentFile, written.join(", "))
|
||||
const componentCss = read(componentFile)
|
||||
assert.match(componentCss, /\.widget\{color:#00f\}/)
|
||||
assert.match(componentCss, /\.other\{color:green\}/)
|
||||
assert.equal(ctx.componentCssMap!.get(".widget{color:blue}"), componentFile)
|
||||
assert.equal(ctx.componentCssMap!.get(".other{color:green}"), componentFile)
|
||||
|
||||
const index = read(ctx.hashedResourceNames!["index.css"])
|
||||
assert.ok(!index.includes(".widget"), "component CSS is not duplicated into index.css")
|
||||
// the popover's CSS (added globally) and base styles in the quartz-base layer, then custom.scss
|
||||
assert.match(
|
||||
index,
|
||||
/^@layer quartz-base\{.*\.stub-popover\{.*\.stub-base\{.*\}\.stub-custom\{/s,
|
||||
)
|
||||
assert.match(index, /--secondary:#00f/)
|
||||
assert.match(index, /--titleFont:"Header Font"/)
|
||||
})
|
||||
|
||||
test("inline plugin CSS/JS resources are moved to files named in ctx.extractedInlineResources", async () => {
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: ".plugin-inline { color: red; }", inline: true },
|
||||
{ content: "https://example.com/external.css" },
|
||||
],
|
||||
js: [
|
||||
{ script: "window.__early = 1", loadTime: "beforeDOMReady", contentType: "inline" },
|
||||
{ script: "window.__late = 1", loadTime: "afterDOMReady", contentType: "inline" },
|
||||
{ src: "https://example.com/x.js", loadTime: "afterDOMReady", contentType: "external" },
|
||||
],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, written, read } = await emit({}, { resources })
|
||||
const map = ctx.extractedInlineResources!
|
||||
assert.equal(map.size, 3)
|
||||
const css = map.get(".plugin-inline { color: red; }")!
|
||||
assert.match(css, /^static\/resource-style-[0-9a-f]{8}\.css$/)
|
||||
assert.equal(read(css), ".plugin-inline{color:red}")
|
||||
const early = map.get("window.__early = 1")!
|
||||
const late = map.get("window.__late = 1")!
|
||||
assert.match(early, /^static\/resource-before-[0-9a-f]{8}\.js$/)
|
||||
assert.match(late, /^static\/resource-after-[0-9a-f]{8}\.js$/)
|
||||
assert.match(read(late), /window\.__late=1/)
|
||||
for (const f of [css, early, late]) assert.ok(written.includes(f), f)
|
||||
// the resources themselves are left as they are (partial rebuilds reuse them)
|
||||
assert.equal(resources.css.length, 2)
|
||||
})
|
||||
|
||||
test("CSS a plugin marks inline that lightningcss can't parse is written as it is", async () => {
|
||||
const broken = ".a { color: red"
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: "@media (", inline: true },
|
||||
{ content: broken, inline: true },
|
||||
],
|
||||
js: [],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, read } = await emit({}, { resources })
|
||||
assert.equal(read(ctx.extractedInlineResources!.get("@media (")!), "@media (")
|
||||
})
|
||||
|
||||
test("serve mode: unhashed names and one minified postscript bundle in order", async () => {
|
||||
const { ctx, written, read } = await emit({}, { serve: true })
|
||||
assert.deepEqual(ctx.hashedResourceNames, {
|
||||
"index.css": "index.css",
|
||||
"prescript.js": "prescript.js",
|
||||
"postscript.js": "postscript.js",
|
||||
})
|
||||
assert.ok(!written.some((f) => f.startsWith("static/scripts/")))
|
||||
const postscript = read("postscript.js")
|
||||
const order = [
|
||||
"__widgetAfter",
|
||||
"__otherAfter",
|
||||
"__stub_popover",
|
||||
"__stub_prefetch",
|
||||
"__stub_spa",
|
||||
].map((marker) => postscript.indexOf(marker))
|
||||
assert.ok(order.every((at) => at >= 0))
|
||||
assert.deepEqual(
|
||||
[...order].sort((a, b) => a - b),
|
||||
order,
|
||||
)
|
||||
// minified by esbuild
|
||||
assert.ok(!postscript.includes("window.__widgetAfter = 1"), postscript)
|
||||
})
|
||||
|
||||
test("postscript.js is a valid module: the parallel imports are comma-separated", async () => {
|
||||
const { ctx, read } = await emit({})
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const AsyncFunction = (async () => {}).constructor as new (code: string) => unknown
|
||||
assert.doesNotThrow(() => new AsyncFunction(postscript), postscript)
|
||||
assert.equal(importedScripts(postscript).length, 5)
|
||||
})
|
||||
|
||||
test("without component CSS no component stylesheet is emitted", async () => {
|
||||
const { ctx, written } = await emit({}, { emitters: [] })
|
||||
assert.ok(!written.some((f) => f.startsWith("component-")), written.join(", "))
|
||||
assert.equal(ctx.componentCssMap!.size, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("analytics scripts", () => {
|
||||
/** Run the site's analytics script in a fake page; returns the URLs of the scripts it loads. */
|
||||
async function loadedScripts(analytics: Record<string, unknown>) {
|
||||
const { ctx, read } = await emit(
|
||||
{
|
||||
analytics: analytics as GlobalConfiguration["analytics"],
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
},
|
||||
{ emitters: [] },
|
||||
)
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
// the analytics script(s), before the router
|
||||
const ours = scripts.slice(0, -1)
|
||||
const loaded: { src: string; attributes: Record<string, string> }[] = []
|
||||
const element = () => ({
|
||||
attributes: {} as Record<string, string>,
|
||||
setAttribute(name: string, value: string) {
|
||||
this.attributes[name] = value
|
||||
},
|
||||
})
|
||||
const firstScript = { parentNode: { insertBefore: (s: never) => loaded.push(s) } }
|
||||
const document = Object.assign(new EventTarget(), {
|
||||
title: "Page",
|
||||
createElement: element,
|
||||
head: { appendChild: (s: never) => loaded.push(s) },
|
||||
getElementsByTagName: () => [firstScript],
|
||||
})
|
||||
const context = createContext({
|
||||
document,
|
||||
location: { hostname: "garden.example", pathname: "/", href: "https://garden.example/" },
|
||||
})
|
||||
context.window = context
|
||||
for (const script of ours) runInContext(script, context)
|
||||
return { loaded: loaded.map((s) => ({ src: s.src, attributes: s.attributes })), context, ours }
|
||||
}
|
||||
|
||||
const cases: [Record<string, unknown>, string, Record<string, string>?][] = [
|
||||
[{ provider: "google", tagId: "G-1" }, "https://www.googletagmanager.com/gtag/js?id=G-1"],
|
||||
[
|
||||
{ provider: "plausible" },
|
||||
"https://plausible.io/js/script.manual.js",
|
||||
{ "data-domain": "garden.example" },
|
||||
],
|
||||
[{ provider: "plausible", host: "https://p.example" }, "https://p.example/js/script.manual.js"],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1" },
|
||||
"https://analytics.umami.is/script.js",
|
||||
{ "data-website-id": "w1" },
|
||||
],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1", host: "https://u.example", script: "u.js" },
|
||||
"https://u.example/u.js",
|
||||
],
|
||||
[{ provider: "goatcounter", websiteId: "g1" }, "https://gc.zgo.at/count.js"],
|
||||
[{ provider: "posthog", apiKey: "k" }, "https://app.posthog.com/static/array.js"],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://ph.example" },
|
||||
"https://ph.example/static/array.js",
|
||||
],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://h", apiHost: "https://api.h" },
|
||||
"https://api.h/static/array.js",
|
||||
],
|
||||
[{ provider: "tinylytics", siteId: "t 1" }, "https://tinylytics.app/embed/t%201.js?spa"],
|
||||
[{ provider: "cabin" }, "https://scripts.withcabin.com/hello.js"],
|
||||
[{ provider: "cabin", host: "https://c.example" }, "https://c.example/hello.js"],
|
||||
[{ provider: "clarity", projectId: "c1" }, "https://www.clarity.ms/tag/c1"],
|
||||
[{ provider: "matomo", host: "m.example", siteId: "3" }, "//m.example/matomo.js"],
|
||||
[{ provider: "vercel" }, "/_vercel/insights/script.js"],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1" },
|
||||
"https://app.rybbit.io/api/script.js",
|
||||
{ "data-site-id": "r1" },
|
||||
],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1", host: "https://r.example" },
|
||||
"https://r.example/api/script.js",
|
||||
],
|
||||
]
|
||||
for (const [analytics, src, attributes] of cases) {
|
||||
test(`${JSON.stringify(analytics)} loads ${src}`, async () => {
|
||||
const { loaded } = await loadedScripts(analytics)
|
||||
assert.deepEqual(
|
||||
loaded.map((s) => s.src),
|
||||
[src],
|
||||
)
|
||||
for (const [name, value] of Object.entries(attributes ?? {})) {
|
||||
assert.equal(loaded[0].attributes[name], value, name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("goatcounter counts at the site's endpoint; posthog gets its options", async () => {
|
||||
const gc = await loadedScripts({ provider: "goatcounter", websiteId: "g1", host: "gc.example" })
|
||||
assert.ok(gc.ours.join("\n").includes('"https://" + "g1" + "." + "gc.example" + "/count"'))
|
||||
const ph = await loadedScripts({
|
||||
provider: "posthog",
|
||||
apiKey: "k",
|
||||
uiHost: "https://ui.example",
|
||||
personProfiles: "identified_only",
|
||||
})
|
||||
const init = (ph.context.posthog as { _i: [string, Record<string, unknown>][] })._i[0]
|
||||
assert.deepEqual(init[0], "k")
|
||||
assert.deepEqual(
|
||||
{ ...init[1] },
|
||||
{
|
||||
api_host: "https://app.posthog.com",
|
||||
ui_host: "https://ui.example",
|
||||
person_profiles: "identified_only",
|
||||
capture_pageview: false,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("vercel's queue stub is defined in the prescript, before any script runs", async () => {
|
||||
const { ctx, read } = await emit({ analytics: { provider: "vercel" } }, { emitters: [] })
|
||||
const context = createContext({})
|
||||
context.window = context
|
||||
runInContext(read(ctx.hashedResourceNames!["prescript.js"]), context)
|
||||
assert.equal(typeof context.va, "function")
|
||||
context.va("event", "x")
|
||||
assert.deepEqual(
|
||||
[...(context.vaq as unknown[][])].map((args) => [...args]),
|
||||
[["event", "x"]],
|
||||
)
|
||||
})
|
||||
|
||||
test("no analytics, no analytics script", async () => {
|
||||
const { ours } = await loadedScripts({})
|
||||
assert.deepEqual(ours, [])
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { registerHooks } from "node:module"
|
||||
import { getSlugOptions, setSlugOptions } from "../../util/path"
|
||||
import { getDiagnostics, resetDiagnostics } from "../../util/diagnostics"
|
||||
import type { QuartzComponent } from "../../components/types"
|
||||
|
||||
// loadQuartzConfig imports the built-in emitters, whose SCSS and inline browser scripts esbuild
|
||||
@@ -157,3 +158,271 @@ plugins:
|
||||
assert.ok(transformers.includes("Description"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("loadQuartzConfig: configuration, options and loading", () => {
|
||||
let dir: string
|
||||
before(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-config-"))
|
||||
process.env.QUARTZ_CONFIG_QUIET = "1"
|
||||
})
|
||||
afterEach(() => {
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
setSlugOptions(undefined)
|
||||
})
|
||||
after(() => {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
const useConfig = (content: string) => {
|
||||
const file = path.join(dir, "quartz.config.yaml")
|
||||
fs.writeFileSync(file, content)
|
||||
process.env.QUARTZ_CONFIG_PATH = file
|
||||
}
|
||||
const instance = (cfg: Awaited<ReturnType<typeof loadQuartzConfig>>, name: string) =>
|
||||
cfg.plugins.transformers.find((p) => p.name === name)
|
||||
|
||||
test("CLI overrides win over the YAML configuration; built-ins are exposed with their settings", async () => {
|
||||
useConfig(`configuration:
|
||||
pageTitle: From YAML
|
||||
baseUrl: yaml.example.com
|
||||
links:
|
||||
prettyLinks: false
|
||||
plugins: []
|
||||
`)
|
||||
const cfg = await loadQuartzConfig({ baseUrl: "cli.example.com" })
|
||||
assert.equal(cfg.configuration.baseUrl, "cli.example.com")
|
||||
assert.equal(cfg.configuration.pageTitle, "From YAML")
|
||||
// configuration.links: the configured options over the built-in's defaults, enabled and order
|
||||
assert.deepEqual(cfg.configuration.links, {
|
||||
markdownLinkResolution: "shortest",
|
||||
prettyLinks: false,
|
||||
openLinksInNewTab: false,
|
||||
lazyLoad: false,
|
||||
externalLinkIcon: true,
|
||||
disableBrokenWikilinks: true,
|
||||
enabled: true,
|
||||
order: 60,
|
||||
})
|
||||
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
|
||||
// the built-in emitters, then the page renderer last; the 404 page type is always there
|
||||
assert.deepEqual(names(cfg.plugins.emitters), [
|
||||
"ComponentResources",
|
||||
"Assets",
|
||||
"Static",
|
||||
"SlugRedirects",
|
||||
"ContentIndex",
|
||||
"Fonts",
|
||||
"PageTypeDispatcher",
|
||||
])
|
||||
assert.deepEqual(names(cfg.plugins.pageTypes ?? []), ["404"])
|
||||
})
|
||||
|
||||
test("a former crawl-links entry configures the built-in with crawl-links' defaults and isn't loaded", async () => {
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/crawl-links"
|
||||
enabled: true
|
||||
options:
|
||||
openLinksInNewTab: true
|
||||
`)
|
||||
resetDiagnostics()
|
||||
const cfg = await loadQuartzConfig()
|
||||
// not installed, and not tried: no load error
|
||||
assert.deepEqual(
|
||||
getDiagnostics().filter((d) => d.severity === "error"),
|
||||
[],
|
||||
)
|
||||
const links = cfg.configuration.links as unknown as Record<string, unknown>
|
||||
assert.equal(links.markdownLinkResolution, "absolute")
|
||||
assert.equal(links.openLinksInNewTab, true)
|
||||
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
|
||||
})
|
||||
|
||||
test("an entry's options override the manifest's defaultOptions", async () => {
|
||||
// Latex' defaultOptions say renderEngine: katex, whose stylesheet it adds as a resource;
|
||||
// with mathjax it adds none
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
`)
|
||||
const katex = instance(await loadQuartzConfig(), "Latex")
|
||||
assert.ok(katex?.externalResources?.({} as never), "katex resources")
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
options:
|
||||
renderEngine: mathjax
|
||||
`)
|
||||
const mathjax = instance(await loadQuartzConfig(), "Latex")
|
||||
assert.ok(mathjax, "Latex is loaded")
|
||||
assert.equal(mathjax.externalResources?.({} as never), undefined)
|
||||
})
|
||||
|
||||
test("plugins run by entry order, then defaultOrder; disabled entries aren't loaded", async () => {
|
||||
// defaultOrder: description 70, latex 80, table-of-contents 50
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/latex"
|
||||
enabled: true
|
||||
order: 5
|
||||
- source: "@quartz-community/description"
|
||||
enabled: true
|
||||
- source: "@quartz-community/table-of-contents"
|
||||
enabled: true
|
||||
- source: "@quartz-community/hard-line-breaks"
|
||||
enabled: false
|
||||
`)
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.deepEqual(names(cfg.plugins.transformers), [
|
||||
"Frontmatter",
|
||||
"Latex",
|
||||
"TableOfContents",
|
||||
"Links",
|
||||
"Description",
|
||||
])
|
||||
})
|
||||
|
||||
test("a plugin that can't be loaded is skipped locally and fails the build in CI", async () => {
|
||||
useConfig(`plugins:
|
||||
- source: "@quartz-community/does-not-exist"
|
||||
enabled: true
|
||||
- source: "@quartz-community/description"
|
||||
enabled: true
|
||||
`)
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.ok(names(cfg.plugins.transformers).includes("Description"))
|
||||
|
||||
const saved = { ...process.env }
|
||||
try {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
delete process.env.QUARTZ_ALLOW_BROKEN_PLUGINS
|
||||
process.env.CI = "true"
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message:
|
||||
/^1 enabled plugin could not be loaded: @quartz-community\/does-not-exist \(see above\)/,
|
||||
})
|
||||
process.env.QUARTZ_ALLOW_BROKEN_PLUGINS = "1"
|
||||
await loadQuartzConfig()
|
||||
} finally {
|
||||
for (const key of ["CI", "QUARTZ_ALLOW_BROKEN_PLUGINS", "QUARTZ_CONFIG_QUIET"]) {
|
||||
if (saved[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = saved[key]
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("loadQuartzConfig: a local plugin's manifest (package.json → quartz)", () => {
|
||||
let dir: string
|
||||
const linked: string[] = []
|
||||
// .quartz/plugins and .quartz, where this test creates them
|
||||
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const created = [pluginsDir, path.dirname(pluginsDir)].filter((d) => !fs.existsSync(d))
|
||||
before(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-local-plugin-"))
|
||||
process.env.QUARTZ_CONFIG_QUIET = "1"
|
||||
})
|
||||
afterEach(() => {
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
})
|
||||
after(() => {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
// the symlinks installPlugin made in .quartz/plugins
|
||||
for (const link of linked)
|
||||
if (fs.lstatSync(link, { throwIfNoEntry: false })) fs.unlinkSync(link)
|
||||
for (const d of created) if (fs.readdirSync(d).length === 0) fs.rmdirSync(d)
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
|
||||
/** A transformer plugin in `dir/<name>` whose instance records the options it got. */
|
||||
function localPlugin(name: string, quartz: Record<string, unknown>) {
|
||||
const root = path.join(dir, name)
|
||||
fs.mkdirSync(root)
|
||||
fs.writeFileSync(
|
||||
path.join(root, "package.json"),
|
||||
JSON.stringify({ name, version: "2.3.4", type: "module", main: "index.js", quartz }),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(root, "index.js"),
|
||||
`export default (opts) => ({ name: ${JSON.stringify(name)}, opts, textTransform: (_c, s) => s })\n`,
|
||||
)
|
||||
linked.push(path.join(process.cwd(), ".quartz", "plugins", name))
|
||||
return root
|
||||
}
|
||||
const useConfig = (plugins: { source: string; options?: object }[]) => {
|
||||
const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.yaml`)
|
||||
fs.writeFileSync(
|
||||
file,
|
||||
`plugins:\n${plugins.map((p) => ` - source: ${JSON.stringify(p.source)}\n enabled: true\n options: ${JSON.stringify(p.options ?? {})}\n`).join("")}`,
|
||||
)
|
||||
process.env.QUARTZ_CONFIG_PATH = file
|
||||
}
|
||||
const withEnv = async (env: Record<string, string | undefined>, fn: () => Promise<void>) => {
|
||||
const saved = Object.fromEntries(Object.keys(env).map((k) => [k, process.env[k]]))
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k]
|
||||
else process.env[k] = v
|
||||
}
|
||||
try {
|
||||
await fn()
|
||||
} finally {
|
||||
for (const [k, v] of Object.entries(saved)) {
|
||||
if (v === undefined) delete process.env[k]
|
||||
else process.env[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("its defaultOptions are the base of the entry's options", async () => {
|
||||
const root = localPlugin("audit-options", {
|
||||
name: "audit-options",
|
||||
category: "transformer",
|
||||
defaultOptions: { greeting: "hello", size: 1 },
|
||||
})
|
||||
useConfig([{ source: root, options: { size: 2 } }])
|
||||
const cfg = await loadQuartzConfig()
|
||||
const plugin = cfg.plugins.transformers.find((p) => p.name === "audit-options") as unknown as {
|
||||
opts: unknown
|
||||
}
|
||||
assert.deepEqual(plugin.opts, { greeting: "hello", size: 2 })
|
||||
})
|
||||
|
||||
test("a plugin that needs a newer Quartz warns locally and fails the build in CI", async () => {
|
||||
const root = localPlugin("audit-future", {
|
||||
name: "audit-future",
|
||||
category: "transformer",
|
||||
quartzVersion: ">=99.0.0",
|
||||
})
|
||||
useConfig([{ source: root }])
|
||||
await withEnv({ CI: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined }, async () => {
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.ok(names(cfg.plugins.transformers).includes("audit-future"))
|
||||
})
|
||||
await withEnv(
|
||||
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined },
|
||||
async () => {
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message: /^1 enabled plugin does not support Quartz [^:]+: audit-future \(see above\)/,
|
||||
})
|
||||
},
|
||||
)
|
||||
await withEnv(
|
||||
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" },
|
||||
async () => {
|
||||
await loadQuartzConfig()
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("a missing dependency fails the build", async () => {
|
||||
const root = localPlugin("audit-deps", {
|
||||
name: "audit-deps",
|
||||
category: "transformer",
|
||||
dependencies: ["github:someone/not-configured"],
|
||||
})
|
||||
useConfig([{ source: root }])
|
||||
await withEnv({ QUARTZ_CONFIG_QUIET: undefined }, async () => {
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
message: "Plugin dependency validation failed with 1 error(s). See above for details.",
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,9 @@ import type { PluginManifest } from "./types"
|
||||
import { componentRegistry } from "../../components/registry"
|
||||
import type { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
|
||||
import { PluginJsonEntry, LayoutPosition } from "./types"
|
||||
import { LayoutDiagnostics } from "./layoutReport"
|
||||
import { h } from "preact"
|
||||
import { render } from "preact-render-to-string"
|
||||
|
||||
describe("resolveConfigPath", () => {
|
||||
afterEach(() => {
|
||||
@@ -432,3 +435,302 @@ describe("async plugin factories", () => {
|
||||
assert.strictEqual(detectCategoryFromModule({ default: factory }), "transformer")
|
||||
})
|
||||
})
|
||||
|
||||
describe("dependency order between plugins", () => {
|
||||
const validate = (
|
||||
plugin: Partial<PluginManifest>,
|
||||
dep: Partial<PluginManifest>,
|
||||
order?: { plugin?: number; dep?: number },
|
||||
) => {
|
||||
const entries: PluginJsonEntry[] = [
|
||||
{ source: "github:someone/x", enabled: true, options: {}, order: order?.plugin },
|
||||
{ source: "github:someone/y", enabled: true, options: {}, order: order?.dep },
|
||||
]
|
||||
const manifests = new Map<string, PluginManifest>([
|
||||
[
|
||||
"github:someone/x",
|
||||
{ name: "x", dependencies: ["github:someone/y"], ...plugin } as PluginManifest,
|
||||
],
|
||||
["github:someone/y", { name: "y", ...dep } as PluginManifest],
|
||||
])
|
||||
return validateDependencies(entries, manifests, [])
|
||||
}
|
||||
|
||||
test("a dependency of the same stage must run first: entry order, else defaultOrder, else 50", () => {
|
||||
const transformer = { category: "transformer" } as const
|
||||
assert.deepStrictEqual(validate(transformer, { ...transformer, defaultOrder: 40 }).errors, [])
|
||||
assert.match(
|
||||
validate(transformer, { ...transformer, defaultOrder: 60 }).errors[0],
|
||||
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
|
||||
)
|
||||
// the entry's order wins over the manifest's defaultOrder, on both sides
|
||||
assert.deepStrictEqual(
|
||||
validate(
|
||||
{ ...transformer, defaultOrder: 10 },
|
||||
{ ...transformer, defaultOrder: 60 },
|
||||
{
|
||||
plugin: 70,
|
||||
},
|
||||
).errors,
|
||||
[],
|
||||
)
|
||||
assert.match(
|
||||
validate(transformer, { ...transformer, defaultOrder: 10 }, { dep: 55 }).errors[0],
|
||||
/\(order: 50\) depends on "y" \(order: 55\)/,
|
||||
)
|
||||
// equal order: stable, the dependency is not after the plugin
|
||||
assert.deepStrictEqual(validate(transformer, transformer).errors, [])
|
||||
})
|
||||
|
||||
test("a dependency cycle fails the build", () => {
|
||||
const entries: PluginJsonEntry[] = [
|
||||
{ source: "github:someone/x", enabled: true, options: {} },
|
||||
{ source: "github:someone/y", enabled: true, options: {} },
|
||||
]
|
||||
const manifests = new Map<string, PluginManifest>([
|
||||
["github:someone/x", { name: "x", dependencies: ["github:someone/y"] } as PluginManifest],
|
||||
["github:someone/y", { name: "y", dependencies: ["github:someone/x"] } as PluginManifest],
|
||||
])
|
||||
assert.deepStrictEqual(validateDependencies(entries, manifests, []).errors, [
|
||||
"Circular dependency detected: x → y → x",
|
||||
])
|
||||
})
|
||||
|
||||
// Order only decides between plugins of the same stage: all transformers run before any filter or
|
||||
// emitter, and a component-only plugin has no place in the pipeline. An emitter (or a component)
|
||||
// depending on a transformer with a higher order used to fail the build with "is configured to
|
||||
// run first", although the transformer always runs first.
|
||||
test("a dependency of another stage is not ordered against the plugin", () => {
|
||||
const transformer = { category: "transformer", defaultOrder: 60 } as const
|
||||
assert.deepStrictEqual(validate({ category: "emitter" }, transformer).errors, [])
|
||||
assert.deepStrictEqual(validate({ category: "component" }, transformer).errors, [])
|
||||
assert.deepStrictEqual(
|
||||
validate({ category: "component" }, { category: "component", defaultOrder: 60 }).errors,
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test("a plugin of several stages is ordered against a dependency in a stage they share", () => {
|
||||
const transformer = { category: "transformer", defaultOrder: 60 } as const
|
||||
assert.match(
|
||||
validate({ category: ["transformer", "emitter"] }, transformer).errors[0],
|
||||
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
|
||||
)
|
||||
// without a category the stage is unknown: still compared
|
||||
assert.match(validate({}, { defaultOrder: 60 }).errors[0], /depends on "y" \(order: 60\)/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin names of each source form", () => {
|
||||
test("github:, git+…, https:// URLs, local paths and { repo, name } objects", () => {
|
||||
const cases: [Parameters<typeof isExcluded>[0], string][] = [
|
||||
["github:someone/my-plugin#v2", "my-plugin"],
|
||||
["git+https://github.com/someone/my-plugin.git", "my-plugin"],
|
||||
["https://gitlab.com/group/my-plugin.git#main", "my-plugin"],
|
||||
["https://github.com/someone/my-plugin", "my-plugin"],
|
||||
["./plugins/my-plugin/", "my-plugin"],
|
||||
[{ repo: "github:someone/repo", name: "my-plugin" }, "my-plugin"],
|
||||
[{ repo: "github:someone/my-plugin" }, "my-plugin"],
|
||||
]
|
||||
for (const [source, name] of cases) {
|
||||
assert.ok(isExcluded(source, [name]), JSON.stringify(source))
|
||||
assert.ok(!isExcluded(source, ["someone"]), JSON.stringify(source))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("validateDependencies: which plugins are checked", () => {
|
||||
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
|
||||
source,
|
||||
enabled: true,
|
||||
options: {},
|
||||
...extra,
|
||||
})
|
||||
const m = (extra: Partial<PluginManifest>) => ({ name: "n", ...extra }) as PluginManifest
|
||||
|
||||
test("a disabled plugin's dependencies are not required", () => {
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x", { enabled: false })],
|
||||
new Map([["github:a/x", m({ dependencies: ["github:a/missing"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
})
|
||||
|
||||
test("messages name the plugin by its displayName", () => {
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x")],
|
||||
new Map([["github:a/x", m({ displayName: "Fancy X", dependencies: ["github:a/missing"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [
|
||||
'Plugin "Fancy X" requires "missing". Run: npx quartz plugin add github:a/missing',
|
||||
])
|
||||
})
|
||||
|
||||
test("a disabled dependency with a higher order is only a warning", () => {
|
||||
const { errors, warnings } = validateDependencies(
|
||||
[entry("github:a/x"), entry("github:a/y", { enabled: false, order: 90 })],
|
||||
new Map([["github:a/x", m({ dependencies: ["github:a/y"] })]]),
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
assert.strictEqual(warnings.length, 1)
|
||||
})
|
||||
|
||||
test("a plugin at the same order as the built-in it depends on runs after it", () => {
|
||||
const plan = planBuiltins({
|
||||
configuration: {},
|
||||
entries: [],
|
||||
nameOf: () => "",
|
||||
providesOf: () => undefined,
|
||||
})
|
||||
const { errors } = validateDependencies(
|
||||
[entry("github:a/x", { order: 60 })],
|
||||
new Map([
|
||||
[
|
||||
"github:a/x",
|
||||
m({ category: "transformer", dependencies: ["@quartz-community/crawl-links"] }),
|
||||
],
|
||||
]),
|
||||
plan.builtins,
|
||||
)
|
||||
assert.deepStrictEqual(errors, [])
|
||||
})
|
||||
|
||||
test("cycles of any length are found once; shared dependencies are no cycle", () => {
|
||||
const deps = (map: Record<string, string[]>) =>
|
||||
new Map(Object.entries(map).map(([k, d]) => [k, m({ dependencies: d })]))
|
||||
const sources = ["github:a/w", "github:a/x", "github:a/y", "github:a/z"]
|
||||
const entries = sources.map((s) => entry(s))
|
||||
// w → x → y → z, and w → y: a diamond, no cycle
|
||||
assert.deepStrictEqual(
|
||||
validateDependencies(
|
||||
entries,
|
||||
deps({
|
||||
"github:a/w": ["github:a/x", "github:a/y"],
|
||||
"github:a/x": ["github:a/y"],
|
||||
"github:a/y": ["github:a/z"],
|
||||
}),
|
||||
).errors,
|
||||
[],
|
||||
)
|
||||
// w → x → y → z → x
|
||||
assert.deepStrictEqual(
|
||||
validateDependencies(
|
||||
entries,
|
||||
deps({
|
||||
"github:a/w": ["github:a/x"],
|
||||
"github:a/x": ["github:a/y"],
|
||||
"github:a/y": ["github:a/z"],
|
||||
"github:a/z": ["github:a/x"],
|
||||
}),
|
||||
).errors,
|
||||
["Circular dependency detected: x → y → z → x"],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildLayoutForEntries: components and options", () => {
|
||||
const place = (layout: Record<string, unknown>, manifest?: Record<string, unknown>) => {
|
||||
componentRegistry.register("p", makeComponent("P"), "test-source", manifest as never)
|
||||
return buildLayoutForEntries(
|
||||
[{ source: "p", enabled: true, options: {}, layout: layout as never }],
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
test("mobile-only and desktop-only wrap the component in their class", () => {
|
||||
const html = (layout: Record<string, unknown>) => {
|
||||
const [C] = place({ position: "left", ...layout }).left!
|
||||
return render(h(C as never, {} as never))
|
||||
}
|
||||
assert.strictEqual(html({ display: "mobile-only" }), '<div class="mobile-only"></div>')
|
||||
assert.strictEqual(html({ display: "desktop-only" }), '<div class="desktop-only"></div>')
|
||||
assert.strictEqual(html({ display: "all" }), "")
|
||||
assert.strictEqual(html({ display: null }), "")
|
||||
})
|
||||
|
||||
test("display all / null raise no warning; a non-numeric priority is 50 with a warning", () => {
|
||||
const diag = new LayoutDiagnostics()
|
||||
componentRegistry.register("q", makeComponent("Q"), "test-source")
|
||||
componentRegistry.register("r", makeComponent("R"), "test-source")
|
||||
componentRegistry.register("s", makeComponent("S"), "test-source")
|
||||
const result = buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "q",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: "high", display: "all" } as never,
|
||||
},
|
||||
{
|
||||
source: "r",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 60, display: null } as never,
|
||||
},
|
||||
{
|
||||
source: "s",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 40 } as never,
|
||||
},
|
||||
],
|
||||
{},
|
||||
diag,
|
||||
)
|
||||
assert.deepStrictEqual(diag.warnings, [
|
||||
'plugin "q": layout priority "high" is not a number — using 50.',
|
||||
])
|
||||
assert.deepStrictEqual(
|
||||
result.left!.map((c) => c.displayName),
|
||||
["S", "Q", "R"],
|
||||
)
|
||||
})
|
||||
|
||||
test("layout.position: null falls back to the manifest's defaultPosition", () => {
|
||||
const result = place({ position: null, priority: 1 }, { defaultPosition: "right" })
|
||||
assert.strictEqual(result.right!.length, 1)
|
||||
})
|
||||
|
||||
test("a component registered under the PascalCase name of a kebab-case plugin is found", () => {
|
||||
componentRegistry.register("TagList", makeComponent("TagListC"), "test-source")
|
||||
const result = buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "tag-list",
|
||||
enabled: true,
|
||||
options: {},
|
||||
layout: { position: "left", priority: 1 },
|
||||
},
|
||||
],
|
||||
{},
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
result.left!.map((c) => c.displayName),
|
||||
["TagListC"],
|
||||
)
|
||||
})
|
||||
|
||||
test("a constructor gets the entry's options with quartz.ts overrides on top, or none", () => {
|
||||
const received: unknown[] = []
|
||||
const ctor = ((opts?: unknown) => {
|
||||
received.push(opts)
|
||||
return makeComponent(`C${received.length}`)
|
||||
}) as QuartzComponentConstructor
|
||||
componentRegistry.register("ctor-a", ctor, "test-source")
|
||||
componentRegistry.register("ctor-b", ctor, "test-source")
|
||||
componentRegistry.setOptionOverrides("ctor-a", { extra: true, base: 2 })
|
||||
buildLayoutForEntries(
|
||||
[
|
||||
{
|
||||
source: "ctor-a",
|
||||
enabled: true,
|
||||
options: { base: 1, own: "x" },
|
||||
layout: { position: "left", priority: 1 },
|
||||
},
|
||||
{ source: "ctor-b", enabled: true, options: {}, layout: { position: "left", priority: 2 } },
|
||||
],
|
||||
{},
|
||||
)
|
||||
assert.deepStrictEqual(received, [{ base: 2, own: "x", extra: true }, undefined])
|
||||
})
|
||||
})
|
||||
@@ -159,6 +159,22 @@ interface DependencyValidationResult {
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
/** The pipeline stages a plugin's `order` decides its place in (a component has none). */
|
||||
const ORDERED_STAGES = ["transformer", "filter", "emitter", "pageType"] as const
|
||||
|
||||
/**
|
||||
* Whether `order` decides between the two plugins: they run in a stage they share (all
|
||||
* transformers run before any filter or emitter, whatever their order). Without a category on
|
||||
* either side the stage is unknown, and they are compared.
|
||||
*/
|
||||
function sameStage(a: PluginManifest, b: PluginManifest | undefined): boolean {
|
||||
if (!a.category || !b?.category) return true
|
||||
const stagesOfB = [b.category].flat()
|
||||
return [a.category]
|
||||
.flat()
|
||||
.some((c) => stagesOfB.includes(c) && (ORDERED_STAGES as readonly string[]).includes(c))
|
||||
}
|
||||
|
||||
export function validateDependencies(
|
||||
entries: PluginJsonEntry[],
|
||||
manifests: Map<string, PluginManifest>,
|
||||
@@ -229,7 +245,7 @@ export function validateDependencies(
|
||||
const depManifest = manifests.get(dep)
|
||||
const depOrder = depEntry.order ?? depManifest?.defaultOrder ?? 50
|
||||
|
||||
if (pluginOrder < depOrder) {
|
||||
if (pluginOrder < depOrder && sameStage(manifest, depManifest)) {
|
||||
errors.push(
|
||||
`Plugin "${pluginName}" (order: ${pluginOrder}) depends on "${depName}" (order: ${depOrder}), ` +
|
||||
`but "${pluginName}" is configured to run first. Either increase "${pluginName}"'s order above ${depOrder} ` +
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { registerHooks } from "node:module"
|
||||
import test, { after, describe } from "node:test"
|
||||
import { h } from "preact"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent, QuartzComponentProps } from "../../components/types"
|
||||
import type { QuartzPageTypePluginInstance } from "../types"
|
||||
import type { FilePath, FullSlug } from "../../util/path"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { ChangeEvent } from "../types"
|
||||
import type { Element, Root } from "hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
|
||||
// Rendering a page imports components with SCSS and inline browser scripts, which esbuild bundles
|
||||
// in a real build; under tsx they are stubbed out.
|
||||
registerHooks({
|
||||
load(url, context, next) {
|
||||
if (url.endsWith(".scss") || /\.inline\.ts$/.test(url)) {
|
||||
return { format: "module", source: "export default ''", shortCircuit: true }
|
||||
}
|
||||
return next(url, context)
|
||||
},
|
||||
})
|
||||
const { PageTypeDispatcher } = await import("./dispatcher")
|
||||
const { defaultProcessedContent } = await import("../vfile")
|
||||
|
||||
const Head: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("head", null, h("title", null, String(fileData.frontmatter?.title ?? "")))
|
||||
|
||||
/** A page type whose body names it, so the emitted HTML tells which page type rendered a page. */
|
||||
function pageType(
|
||||
name: string,
|
||||
overrides: Partial<QuartzPageTypePluginInstance> = {},
|
||||
): QuartzPageTypePluginInstance {
|
||||
const Body: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("article", { "data-type": name }, `${name}:${fileData.slug}`)
|
||||
return {
|
||||
name,
|
||||
layout: name,
|
||||
match: () => true,
|
||||
body: () => Body,
|
||||
...overrides,
|
||||
} as QuartzPageTypePluginInstance
|
||||
}
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function setup(
|
||||
pageTypes: QuartzPageTypePluginInstance[],
|
||||
removedPages?: Map<string, string>,
|
||||
transformers: unknown[] = [],
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-dispatcher-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve: false, directory: "content" },
|
||||
cfg: {
|
||||
configuration: { baseUrl: "example.com/sub", locale: "en-US" },
|
||||
plugins: { pageTypes, transformers },
|
||||
},
|
||||
allSlugs: [],
|
||||
virtualPages: [],
|
||||
removedPages,
|
||||
} as unknown as BuildCtx
|
||||
const read = (slug: string) => fs.readFileSync(path.join(output, `${slug}.html`), "utf8")
|
||||
return { ctx, output, read }
|
||||
}
|
||||
|
||||
const resources: StaticResources = { css: [], js: [], additionalHead: [] }
|
||||
const dispatcher = () => PageTypeDispatcher({ defaults: { head: Head } })
|
||||
|
||||
function page(slug: string, html = "", links: string[] = []) {
|
||||
return defaultProcessedContent({
|
||||
slug: slug as FullSlug,
|
||||
relativePath: `${slug}.md` as FilePath,
|
||||
filePath: `content/${slug}.md` as FilePath,
|
||||
frontmatter: { title: slug, tags: [] },
|
||||
links: links as never,
|
||||
htmlAst: { type: "root", children: [] },
|
||||
}).map((x, i) =>
|
||||
i === 0 && html
|
||||
? {
|
||||
type: "root",
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${html}`, "data-slug": html, className: ["internal"] },
|
||||
children: [{ type: "text", value: html }],
|
||||
},
|
||||
],
|
||||
}
|
||||
: x,
|
||||
) as ReturnType<typeof defaultProcessedContent>
|
||||
}
|
||||
|
||||
const linkOf = ([tree]: ReturnType<typeof page>) => (tree as Root).children[0] as Element
|
||||
|
||||
async function collect(gen: AsyncGenerator<FilePath> | AsyncIterable<FilePath>, output: string) {
|
||||
const out: string[] = []
|
||||
for await (const fp of gen) out.push(path.relative(output, fp).split(path.sep).join("/"))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
describe("PageTypeDispatcher.emit", () => {
|
||||
test("each page is rendered by the first matching page type in priority order", async () => {
|
||||
const types = [
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug.startsWith("special/") }),
|
||||
pageType("none", { match: () => false, priority: 100 }),
|
||||
]
|
||||
const { ctx, output, read } = setup(types)
|
||||
const content = [page("index"), page("special/a")]
|
||||
const files = await collect(dispatcher().emit(ctx, content, resources) as never, output)
|
||||
assert.deepEqual(files, ["index.html", "special/a.html"])
|
||||
assert.match(read("index"), /<article data-type="low">low:index<\/article>/)
|
||||
assert.match(read("special/a"), /<article data-type="high">high:special\/a<\/article>/)
|
||||
assert.match(read("special/a"), /<title>special\/a<\/title>/)
|
||||
})
|
||||
|
||||
test("virtual pages are emitted with their page type's body; the 404 page uses the site's base path", async () => {
|
||||
const generated = pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [
|
||||
{ slug: "tags/x" as FullSlug, title: "Tag x", data: {} },
|
||||
{ slug: "404" as FullSlug, title: "Not found", data: {} },
|
||||
],
|
||||
})
|
||||
const { ctx, output, read } = setup([pageType("content"), generated])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("a/b")], resources) as never, output)
|
||||
assert.deepEqual(files, ["404.html", "a/b.html", "tags/x.html"])
|
||||
assert.match(read("tags/x"), /tags:tags\/x/)
|
||||
assert.match(read("tags/x"), /<title>Tag x<\/title>/)
|
||||
// the 404 page is served from any depth: its assets are under the absolute base path
|
||||
assert.match(read("404"), /<script src="\/sub\/postscript\.js"/)
|
||||
assert.match(read("a/b"), /<script src="\.\.\/postscript\.js"/)
|
||||
assert.deepEqual(
|
||||
ctx.virtualPages.map(([, f]) => f.data.slug),
|
||||
["tags/x"],
|
||||
)
|
||||
})
|
||||
|
||||
test("links to a draft are marked broken in the emitted page", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const a = page("a", "draft")
|
||||
await collect(dispatcher().emit(ctx, [a], resources) as never, output)
|
||||
assert.deepEqual(linkOf(a).properties, {
|
||||
href: "./draft",
|
||||
"data-slug": "draft",
|
||||
className: ["internal", "broken"],
|
||||
"data-filtered": "Drafts",
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: pages that stand for files", () => {
|
||||
test("virtualPageHtmlPlugins' result is what the page shows; a page whose body fails isn't emitted", async () => {
|
||||
const Board: QuartzComponent = ({ fileData }: QuartzComponentProps) => {
|
||||
if (fileData.slug === "broken.canvas") throw new Error("cannot render")
|
||||
return h("p", null, `board ${fileData.slug}`)
|
||||
}
|
||||
const canvas = pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
body: () => Board,
|
||||
generate: () =>
|
||||
["a.canvas", "secret.canvas", "broken.canvas"].map((slug) => ({
|
||||
slug: slug as FullSlug,
|
||||
title: slug,
|
||||
data: {},
|
||||
})),
|
||||
})
|
||||
const encrypt = {
|
||||
name: "Encrypt",
|
||||
virtualPageHtmlPlugins: () => [
|
||||
() => (tree: Root, file: { data: { slug?: string } }) => {
|
||||
if (file.data.slug === "secret.canvas") {
|
||||
tree.children = [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: {},
|
||||
children: [{ type: "text", value: "ciphertext" }],
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
],
|
||||
}
|
||||
// transformers without virtualPageHtmlPlugins are skipped
|
||||
const { ctx, output, read } = setup([pageType("content"), canvas], undefined, [
|
||||
{ name: "Plain" },
|
||||
encrypt,
|
||||
])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("index")], resources) as never, output)
|
||||
assert.deepEqual(files, ["a.canvas.html", "index.html", "secret.canvas.html"])
|
||||
assert.match(read("a.canvas"), /<p>board a\.canvas<\/p>/)
|
||||
assert.match(read("secret.canvas"), /<div>ciphertext<\/div>/)
|
||||
assert.doesNotMatch(read("secret.canvas"), /board/)
|
||||
// later emitters read the processed tree from ctx.virtualPages; the failed page is gone
|
||||
const trees = Object.fromEntries(
|
||||
ctx.virtualPages.map(([tree, f]) => [f.data.slug, toHtml(tree as Root)]),
|
||||
)
|
||||
assert.deepEqual(Object.keys(trees), ["a.canvas", "secret.canvas"])
|
||||
assert.equal(trees["secret.canvas"], "<div>ciphertext</div>")
|
||||
assert.equal(trees["a.canvas"], "")
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: what page bodies see", () => {
|
||||
// a body listing the pages it can embed (allFiles) and the files of folder "f" (ctx.trie)
|
||||
const Lister: QuartzComponent = ({ allFiles, ctx }: QuartzComponentProps) =>
|
||||
h(
|
||||
"article",
|
||||
null,
|
||||
`files:${allFiles.map((f) => f.slug).join(",")};` +
|
||||
`f:${(ctx.trie?.findNode(["f"])?.children ?? []).map((c) => c.slug).join(",")}`,
|
||||
)
|
||||
const types = () => [
|
||||
pageType("content", { body: () => Lister }),
|
||||
pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
generate: () => [{ slug: "f/board.canvas" as FullSlug, title: "Board", data: {} }],
|
||||
}),
|
||||
pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "tags/t" as FullSlug, title: "t", data: {} }],
|
||||
}),
|
||||
]
|
||||
const expected = "files:f/note,f/board.canvas,tags/t;f:f/note,f/board.canvas"
|
||||
|
||||
test("emit: virtual pages are in allFiles; the folder trie holds the pages that stand for files", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
await collect(dispatcher().emit(ctx, [page("f/note")], resources) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit: the same, for the pages it re-emits", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
const note = page("f/note")
|
||||
const events = [
|
||||
{ type: "change", path: "f/note.md", file: note[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [note], resources, events) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit renders a changed page with the first matching page type by priority", async () => {
|
||||
const { ctx, output, read } = setup([
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug === "special" }),
|
||||
])
|
||||
const [a, b] = [page("special"), page("plain")]
|
||||
const events = [
|
||||
{ type: "change", path: "special.md", file: a[1] },
|
||||
{ type: "change", path: "plain.md", file: b[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [a, b], resources, events) as never, output)
|
||||
assert.match(read("special"), /data-type="high"/)
|
||||
assert.match(read("plain"), /data-type="low"/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher.partialEmit", () => {
|
||||
test("re-emits changed Markdown pages and all virtual pages, removes deleted pages' output", async () => {
|
||||
const generated = pageType("folder", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "f/index" as FullSlug, title: "F", data: {} }],
|
||||
})
|
||||
const { ctx, output } = setup([pageType("content"), generated])
|
||||
const [a, b] = [page("a"), page("b")]
|
||||
await collect(dispatcher().emit(ctx, [a, b], resources) as never, output)
|
||||
fs.writeFileSync(path.join(output, "gone.html"), "stale")
|
||||
|
||||
const events = [
|
||||
{ type: "change", path: "a.md", file: a[1] },
|
||||
{ type: "delete", path: "gone.md" },
|
||||
// not Markdown: no page of its own
|
||||
{ type: "change", path: "image.png" },
|
||||
] as unknown as ChangeEvent[]
|
||||
ctx.virtualPages = []
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [a, b], resources, events) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["a.html", "f/index.html"])
|
||||
assert.ok(!fs.existsSync(path.join(output, "gone.html")))
|
||||
})
|
||||
|
||||
test("a page whose link to a removed page changed is re-emitted although its source didn't", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const linking = page("linking", "draft")
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [linking, page("other")], resources, []) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["linking.html"])
|
||||
assert.equal(linkOf(linking).properties["data-filtered"], "Drafts")
|
||||
})
|
||||
})
|
||||
@@ -635,3 +635,38 @@ describe("links to unpublished pages, after the page types ran (crawl-links#7)",
|
||||
assert.ok(marks(home).every((m) => m === "ok"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveLayout: every slot", () => {
|
||||
test("a page type's override replaces each default slot; the page type's body is the page body", () => {
|
||||
const Body = (() => null) as unknown as QuartzComponent
|
||||
const pt = makePageType({ body: () => Body })
|
||||
const slots = ["header", "beforeBody", "afterBody", "left", "right", "footer"] as const
|
||||
const defaults = Object.fromEntries(slots.map((s) => [s, [StubA]]))
|
||||
const overrides = Object.fromEntries(slots.map((s) => [s, [StubB]]))
|
||||
const OtherHead = (() => null) as unknown as QuartzComponent
|
||||
const layout = resolveLayout(
|
||||
pt,
|
||||
{ head: StubHead, ...defaults },
|
||||
{ [pt.layout]: { head: OtherHead, ...overrides } },
|
||||
)
|
||||
for (const slot of slots) assert.deepStrictEqual(layout[slot], [StubB], slot)
|
||||
assert.strictEqual(layout.head, OtherHead)
|
||||
assert.strictEqual(layout.pageBody, Body)
|
||||
// without an override, the defaults
|
||||
const plain = resolveLayout(pt, { head: StubHead, ...defaults }, {})
|
||||
for (const slot of slots) assert.deepStrictEqual(plain[slot], [StubA], slot)
|
||||
})
|
||||
|
||||
test("collectComponents leaves out a missing head", () => {
|
||||
const components = collectComponents([makePageType()], { left: [StubA] }, {})
|
||||
assert.ok(!components.includes(undefined as never))
|
||||
assert.strictEqual(components.length, 2)
|
||||
})
|
||||
|
||||
test("collectTreeTransforms: page types without treeTransforms add none", () => {
|
||||
const t = (() => {}) as never
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const result = collectTreeTransforms(ctx, [{}, { treeTransforms: () => [t] }])
|
||||
assert.deepStrictEqual(result, { before: [], treeTransforms: [t], after: [] })
|
||||
})
|
||||
})
|
||||
@@ -295,9 +295,10 @@ const RenderedBody: QuartzComponent = ({ fileData, tree }: QuartzComponentProps)
|
||||
*
|
||||
* Run the transformers' `virtualPageHtmlPlugins` on the rendered body (`file.data.htmlAst`) of a
|
||||
* page that stands for a file — e.g. encrypted-pages encrypting a canvas. When they change the
|
||||
* tree, the page shows the changed tree instead of rendering its body again. A page whose body
|
||||
* failed to render, or that a plugin throws on, is left unpublished: emitting it unprocessed could
|
||||
* publish what the plugin protects.
|
||||
* tree, the page shows the changed tree instead of rendering its body again. Both failures fail
|
||||
* closed, as emitting the page unprocessed could publish what the plugin protects: a page whose
|
||||
* body failed to render is left unpublished (returns false), and a plugin that throws fails the
|
||||
* whole build (`trace` reports the error and exits the process, or throws in a worker).
|
||||
*/
|
||||
export function processVirtualPageHtml(
|
||||
ve: VirtualEntry,
|
||||
@@ -340,7 +341,8 @@ export function processVirtualPageHtml(
|
||||
* Render each virtual page's Body component to HTML and parse it to a hast tree,
|
||||
* populating vfile.data.htmlAst so that transclusion (e.g. ![[file.canvas]]) can inline the
|
||||
* virtual page's content, then run `virtualPageHtmlPlugins` on it (pages that stand for files).
|
||||
* Returns the entries to emit: those whose processing failed are removed from `ctx.virtualPages`.
|
||||
* Returns the entries to emit: those whose body failed to render (so they can't be processed) are
|
||||
* removed from `ctx.virtualPages`. A plugin throwing while processing fails the build.
|
||||
*/
|
||||
function populateVirtualPageHtmlAst(
|
||||
virtualEntries: VirtualEntry[],
|
||||
|
||||
@@ -3,7 +3,12 @@ import assert from "node:assert"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { readContentFile } from "./parse"
|
||||
import { createHtmlProcessor, createMdProcessor, parseMarkdown, readContentFile } from "./parse"
|
||||
import type { Root as MdRoot } from "mdast"
|
||||
import type { Root as HtmlRoot } from "hast"
|
||||
import type { VFile } from "vfile"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
import { isContentError } from "../util/pluginErrors"
|
||||
import type { FilePath } from "../util/path"
|
||||
|
||||
@@ -39,3 +44,93 @@ describe("readContentFile", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("parseMarkdown (one thread)", () => {
|
||||
// a transformer that records which of its hooks ran, in which order
|
||||
const recorder = (name: string, log: string[]) => ({
|
||||
name,
|
||||
textTransform: (_ctx: unknown, src: string) => {
|
||||
log.push(`${name}:text`)
|
||||
return `${src}\n\n${name}`
|
||||
},
|
||||
markdownPlugins: () => [
|
||||
() => (tree: MdRoot) => {
|
||||
log.push(`${name}:md`)
|
||||
tree.children.push({ type: "paragraph", children: [{ type: "text", value: `md-${name}` }] })
|
||||
},
|
||||
],
|
||||
htmlPlugins: () => [
|
||||
() => (tree: HtmlRoot, file: VFile) => {
|
||||
log.push(`${name}:html`)
|
||||
file.data[`html-${name}` as "slug"] = toHtml(tree) as never
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
test("runs text, Markdown and HTML transforms in plugin order and sets the file's paths", async () => {
|
||||
// Quartz passes POSIX-style paths (its glob yields them on Windows too)
|
||||
const posix = (p: string) => p.split(path.sep).join("/")
|
||||
const dir = posix(await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-")))
|
||||
try {
|
||||
await fs.promises.mkdir(`${dir}/Sub Folder`)
|
||||
const a = `${dir}/Sub Folder/My Note.md`
|
||||
const b = `${dir}/other.md`
|
||||
await fs.promises.writeFile(a, "\n\n # Title \n\n")
|
||||
await fs.promises.writeFile(b, "text")
|
||||
const log: string[] = []
|
||||
const ctx = {
|
||||
argv: { directory: dir, verbose: false, concurrency: 1 },
|
||||
// a transformer may implement any subset of the hooks
|
||||
cfg: {
|
||||
plugins: { transformers: [recorder("one", log), { name: "bare" }, recorder("two", log)] },
|
||||
},
|
||||
// a frontmatter permalink is the page's address
|
||||
permalinks: { "other.md": "elsewhere/page" },
|
||||
} as unknown as BuildCtx
|
||||
const res = await parseMarkdown(ctx, [a, b] as FilePath[])
|
||||
|
||||
assert.deepStrictEqual(
|
||||
res.map(([, file]) => [file.data.relativePath, file.data.slug, file.data.filePath]),
|
||||
[
|
||||
["Sub Folder/My Note.md", "sub-folder/my-note", a],
|
||||
["other.md", "elsewhere/page", b],
|
||||
],
|
||||
)
|
||||
// the text is trimmed before the first textTransform, which sees what the one before returned
|
||||
assert.strictEqual(String(res[0][1].value), "# Title\n\none\n\ntwo")
|
||||
// per file: all text transforms, then Markdown plugins, then (after all files) HTML plugins
|
||||
assert.deepStrictEqual(log, [
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:html",
|
||||
"two:html",
|
||||
"one:html",
|
||||
"two:html",
|
||||
])
|
||||
const data = res[0][1].data as Record<string, string>
|
||||
// Markdown plugins ran in order, and remark-rehype turned the Markdown AST into HTML
|
||||
assert.strictEqual(
|
||||
data["html-one"],
|
||||
"<h1>Title</h1>\n<p>one</p>\n<p>two</p>\n<p>md-one</p>\n<p>md-two</p>",
|
||||
)
|
||||
assert.strictEqual(res[0][0].type, "root")
|
||||
assert.strictEqual(toHtml(res[0][0] as HtmlRoot), data["html-two"])
|
||||
} finally {
|
||||
await fs.promises.rm(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("raw HTML in Markdown is kept (allowDangerousHtml)", async () => {
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const md = createMdProcessor(ctx)
|
||||
const ast = md.parse('<div class="x">hi</div>')
|
||||
const html = await createHtmlProcessor(ctx).run(await md.run(ast))
|
||||
assert.strictEqual(toHtml(html, { allowDangerousHtml: true }), '<div class="x">hi</div>')
|
||||
})
|
||||
})
|
||||
@@ -440,3 +440,70 @@ describe("slugs.stripDiacritics (#2410)", () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("normalizeRelativeURLs (SPA navigation and popovers)", () => {
|
||||
// A minimal stand-in for a parsed page: querySelectorAll understands the attribute selectors
|
||||
// `[a=""]` and `[a^="v"]`, comma-separated, as a browser does.
|
||||
function fakePage(attrs: Record<string, string>[]) {
|
||||
const els = attrs.map((a) => ({
|
||||
attrs: { ...a },
|
||||
getAttribute(name: string) {
|
||||
return this.attrs[name] ?? null
|
||||
},
|
||||
setAttribute(name: string, value: string) {
|
||||
this.attrs[name] = value
|
||||
},
|
||||
}))
|
||||
const matches = (el: (typeof els)[number], selector: string) =>
|
||||
selector.split(",").some((part) => {
|
||||
const m = part.trim().match(/^\[(\w+)(\^?)="([^"]*)"\]$/)
|
||||
if (!m) throw new SyntaxError(`unsupported selector ${part}`)
|
||||
const value = el.getAttribute(m[1])
|
||||
if (value === null) return false
|
||||
return m[2] ? value.startsWith(m[3]) : value === m[3]
|
||||
})
|
||||
const page = {
|
||||
querySelectorAll: (selector: string) => els.filter((el) => matches(el, selector)),
|
||||
}
|
||||
return { page: page as unknown as Element, els }
|
||||
}
|
||||
|
||||
test("rebases relative href and src onto the page's URL, keeping fragments; others are left", () => {
|
||||
const { page, els } = fakePage([
|
||||
{ href: "./sibling" },
|
||||
{ href: "../up/page#part" },
|
||||
{ href: "" },
|
||||
{ src: "./img.png" },
|
||||
{ src: "../media/v.mp4" },
|
||||
{ href: "https://example.com/x" },
|
||||
{ href: "/absolute" },
|
||||
{ href: "#local" },
|
||||
{ src: "plain.png" },
|
||||
])
|
||||
path.normalizeRelativeURLs(page, "https://garden.example/notes/deep/page?q=1#h")
|
||||
assert.deepStrictEqual(
|
||||
els.map((e) => e.attrs),
|
||||
[
|
||||
{ href: "/notes/deep/sibling" },
|
||||
{ href: "/notes/up/page#part" },
|
||||
// an empty href is the page itself, its query string included (as in the browser)
|
||||
{ href: "/notes/deep/page?q=1" },
|
||||
{ src: "/notes/deep/img.png" },
|
||||
{ src: "/notes/media/v.mp4" },
|
||||
{ href: "https://example.com/x" },
|
||||
{ href: "/absolute" },
|
||||
{ href: "#local" },
|
||||
{ src: "plain.png" },
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
// _rebaseHtmlElement used to keep only `pathname + hash` of the resolved URL, so a relative
|
||||
// link or embed with a query string lost it after SPA navigation or in a popover
|
||||
// (`./static/viewer.html?file=a.pdf` → `/notes/static/viewer.html`).
|
||||
test("keeps the query string of a relative URL", () => {
|
||||
const { page, els } = fakePage([{ src: "./viewer.html?file=a.pdf#p2" }])
|
||||
path.normalizeRelativeURLs(page, "https://garden.example/notes/page")
|
||||
assert.deepStrictEqual(els[0].attrs, { src: "/notes/viewer.html?file=a.pdf#p2" })
|
||||
})
|
||||
})
|
||||
+1
-1
@@ -57,7 +57,7 @@ export const QUARTZ = "quartz"
|
||||
// https://github.com/natemoo-re/micromorph/blob/main/src/utils.ts#L5
|
||||
const _rebaseHtmlElement = (el: Element, attr: string, newBase: string | URL) => {
|
||||
const rebased = new URL(el.getAttribute(attr)!, newBase)
|
||||
el.setAttribute(attr, rebased.pathname + rebased.hash)
|
||||
el.setAttribute(attr, rebased.pathname + rebased.search + rebased.hash)
|
||||
}
|
||||
export function normalizeRelativeURLs(el: Element | Document, destination: string | URL) {
|
||||
el.querySelectorAll('[href=""], [href^="./"], [href^="../"]').forEach((item) => {
|
||||
|
||||
Reference in new issue
Block a user