Compare commits

..
Author SHA1 Message Date
saberzero1 85d2b43df0 fix(plugins): a disabled dependency is a warning, not a missing plugin that fails the build 2026-11-09 21:59:17 +01:00
saberzero1 db6e72fad7 fix(plugins): read the flat optionSchema first-party plugins ship (type enum + values); accept values of the default type 2026-11-09 21:58:50 +01:00
saberzero1 e8a192ece5 fix(capabilities): quartzStaticUrl and quartzPrefetch are core globals 2026-11-09 21:43:21 +01:00
saberzero1 e41ebf644a fix(plugins): option checks read quartz.optionSchema as well as configSchema 2026-11-09 21:42:50 +01:00
Emile Bangma 33ff9eaccf Merge pull request #2621 from jackyzha0/dev-mode/prefetch
feat: prefetching (configuration.prefetch)
2026-11-09 19:50:27 +01:00
Emile Bangma fa89733d4f Merge pull request #2620 from jackyzha0/dev-mode/builtin-dependencies
fix(plugins): dependencies on plugins built into core are satisfied by the built-in
2026-11-09 19:50:23 +01:00
saberzero1 6210f284d2 feat: prefetching (configuration.prefetch: viewport by default, hover, off), with and without SPA routing 2026-11-09 19:40:17 +01:00
saberzero1 ac8cc4b045 fix(plugins): dependencies on plugins built into core are satisfied by the built-in 2026-11-09 19:28:04 +01:00
Emile Bangma 0770178fa5 Merge pull request #2619 from jackyzha0/dev-mode/lockfile-path-fixes
chore: lockfile for alias-redirects 1.0.3 and created-modified-date 1.0.3
2026-11-09 18:44:49 +01:00
saberzero1 8854aebf7d chore: lockfile for alias-redirects 1.0.3 and created-modified-date 1.0.3 (Windows path fixes) 2026-11-09 18:39:22 +01:00
Emile Bangma bebabb1445 Merge pull request #2618 from jackyzha0/dev-mode/windows-local-sources
fix: Windows spellings of local plugin sources; pretty links cut only at /
2026-11-09 18:19:30 +01:00
saberzero1 7d255c3a0b fix(links): shorten pretty link text with path.posix (Windows also cut at a backslash) 2026-11-09 18:14:28 +01:00
saberzero1 f5ef8f738d fix(plugins): recognise .\ and ..\ local plugin sources (Windows spelling) 2026-11-09 18:11:49 +01:00
Emile Bangma e7da9cebf4 Merge pull request #2616 from WhoAmI-WhereAmI/fix/npm-plugin-index-windows
fix: npm plugin index generation on Windows
2026-11-09 18:08:19 +01:00
saberzero1 28581e8e54 test: npm plugins are found through import.meta.resolve; changeset for the Windows plugin index fix 2026-11-09 18:01:48 +01:00
Emile Bangma 4ff86a7809 Merge pull request #2617 from jackyzha0/dev-mode/link-facts
fix(links): link facts as in Obsidian 1.15.0
2026-11-09 16:37:27 +01:00
saberzero1 7688df602b chore: lockfile for utils 1.2.0 and Obsidian Flavored Markdown 2.1.3 (rehype-obsidian 1.3.0, remark-obsidian 2.2.1) 2026-11-09 16:35:34 +01:00
saberzero1 fc865525b7 fix(links): undecodable link paths are external, NFC paths, missing images show their path (Obsidian 1.15.0) 2026-11-09 15:57:06 +01:00
WhoAmI-WhereAmI 0f294f7139 Fix npm plugin index generation on Windows 2026-11-09 15:51:42 +09:00
Emile Bangma 3c7cba46ae Merge pull request #2615 from jackyzha0/dev-mode/lockfile-bases-1.2.1
chore: lockfile for BasesPage 1.2.1
2026-11-09 05:56:42 +01:00
39 changed files with 846 additions and 76 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
A plugin that lists a plugin now built into Quartz in `quartz.dependencies` (`@quartz-community/crawl-links`, `remove-draft` or `content-index`) no longer fails the build with "requires crawl-links. Run: npx quartz plugin add …". The built-in (`configuration.links`, `drafts`, `contentIndex`) satisfies the dependency. A warning is shown when that built-in is disabled. `npx quartz plugin doctor` checks the same way.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Plugins can declare `window.quartzStaticUrl` and `window.quartzPrefetch` in `capabilities.requires.globals` without a false "nothing provides it" warning: Quartz counts both as its own (`quartzPrefetch` unless `prefetch` is off).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
A plugin whose dependency is configured but disabled gets the intended warning ("depends on X which is disabled") instead of failing the build with "requires X. Run: npx quartz plugin add X".
+10
View File
@@ -0,0 +1,10 @@
---
"@jackyzha0/quartz": patch
---
Links as in Obsidian 1.15.0:
- A Markdown link whose path is not valid percent-encoding (`[x](%zz)`, `[x](a%E2.md)`) is an external link. Before, it failed the whole build with `URI malformed`.
- Link paths are NFC-normalized, so a link spelled with a decomposed `é` reaches `café.md`.
- An image of a file the site doesn't have, with no alt text, gets its percent-decoded path as alt (`![](missing%20pic.png)` → “missing pic.png”), as Obsidian names a missing embed.
- A wikilink's `^id` no longer names its paragraph (Obsidian Flavored Markdown).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Plugin option checks use the option schemas first-party plugins ship. These are declared as `quartz.optionSchema`, the name Quartz Syncer reads, as a flat map of option to type (`{ limit: { type: "number" }, mode: { type: "enum", values: [...] } }`). Before, only a JSON Schema in `quartz.configSchema` was read, so no first-party plugin's schema was used. A misspelled option, an enum value that isn't allowed, or a value of the wrong type is now a warning. A value of the same type as the plugin's default is always accepted, even where a schema disagrees.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
On Windows, regenerating `.quartz/plugins/index.ts` (`npm run install-plugins`, which also runs before every `npm run build`) no longer skips npm plugins with "dist/index.d.ts could not be found", which left exports such as `ExternalPlugin.Explorer` undefined. The package's location was read from a `file:` URL's pathname (`/C:/…`), which is not a Windows path.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Plugin fixes for Windows: relative aliases (`./old`, `../x`) redirect to the right page (alias-redirects 1.0.3), and git dates of notes in folders are read from git instead of the filesystem (created-modified-date 1.0.3).
+11
View File
@@ -0,0 +1,11 @@
---
"@jackyzha0/quartz": minor
---
Prefetching: Quartz fetches pages before their links are followed, so they open at once. New `configuration.prefetch`:
- `viewport` (default): links on screen are fetched while the browser is idle, and links pointed at, focused or touched first.
- `hover`: only links pointed at, focused or touched.
- `"off"`.
It works with and without SPA routing. With SPA routing, fetched pages are kept in memory (five minutes, at most 40) and used by both page navigation and popover previews, which no longer download a page the router fetches again. Without it, Quartz asks the browser to prefetch (Speculation Rules, or `<link rel="prefetch">`). Nothing is prefetched from links to other sites, files, or pages the site doesn't have, or with Data Saver on or a 2G connection (except links pointed at). Add `data-no-prefetch` to a link to exclude it. See https://quartz.jzhao.xyz/features/prefetching
@@ -0,0 +1,7 @@
---
"@jackyzha0/quartz": patch
---
A local plugin source written with Windows separators (`.\my-plugin`, `..\plugins\my-plugin`) is recognised as a local path. Before, it was read as a git or npm source and failed with "Expected github:owner/repo".
Pretty links shorten link text the same way on every OS: Windows also cut it at a backslash (`[[a\b]]` showed `b`).
+1
View File
@@ -27,6 +27,7 @@ This part of the configuration concerns anything that can affect the whole site.
- `pageTitleSuffix`: a string added to the end of the page title. This only applies to the browser tab title, not the title shown at the top of the page.
- `enableSPA`: whether to enable [[SPA Routing]] on your site.
- `enablePopovers`: whether to enable [[popover previews]] on your site.
- `prefetch`: fetch pages before their links are followed, so they open at once ([[prefetching]]): `viewport` (default, links on screen and links pointed at), `hover` (only links pointed at) or `"off"`. Works with and without SPA routing.
- `analytics`: what to use for analytics on your site. Values can be
- `null`: don't use analytics;
- `{ provider: 'google', tagId: '<your-google-tag>' }`: use Google Analytics;
+2
View File
@@ -11,3 +11,5 @@ Under the hood, this is done by hijacking page navigations and instead fetching
## Configuration
- Disable SPA Routing: set the `enableSPA` field of the [[configuration]] in `quartz.config.yaml` to be `false`.
Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once.
+32
View File
@@ -0,0 +1,32 @@
---
title: Prefetching
tags:
- feature
---
Quartz fetches the pages a reader is likely to open next before they click, so following a link shows the page at once instead of waiting for the network. It works with and without [[SPA Routing]].
## How it works
- **`viewport`** (the default): links on screen are fetched while the browser is idle, two at a time and at most 30 per page view. Pointing at a link or focusing it with the keyboard fetches it first, and touching it on a phone fetches it immediately.
- **`hover`**: only links that are pointed at for a moment, focused or touched are fetched.
With [[SPA Routing]], Quartz keeps the fetched pages in memory for five minutes (at most 40 of them), and both page navigation and [[popover previews]] use them, so a page is never downloaded twice. Without SPA routing every link is a normal page load, so Quartz asks the browser to prefetch instead: with [Speculation Rules](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API) where the browser supports them, otherwise with `<link rel="prefetch">`.
Quartz never prefetches:
- links to other sites, links that open in a new tab, and downloads;
- links to files such as images and PDFs (only pages);
- with `viewport`, links on screen to pages that aren't in the site's content index (so a broken link in your layout doesn't show up as a 404 on every page);
- anything but links the reader points at, when the browser asks to save data (Data Saver) or the connection is 2G.
To exclude a single link, add `data-no-prefetch` to it in HTML. Links with `data-router-ignore` are never prefetched either.
## Configuration
Set `prefetch` in the [[configuration]] in `quartz.config.yaml`:
```yaml title="quartz.config.yaml"
configuration:
prefetch: viewport # or hover, or "off"
```
+19
View File
@@ -10,8 +10,27 @@ export declare global {
): void
dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K] | UIEvent): void
}
/** A page fetched ahead by prefetch.inline.ts (`url` is where it came from, after redirects). */
interface PrefetchedPage {
url: string
contentType: string
/** The HTML; missing when the link turned out not to be a page. */
text?: string
}
interface Window {
spaNavigate(url: URL, isBack: boolean = false)
addCleanup(fn: (...args: any[]) => void)
/**
* Set when prefetching is on: the page at `url` from the prefetch cache, or fetched now and
* kept (undefined if it could not be fetched).
*/
quartzPrefetch?: {
load(url: URL): Promise<PrefetchedPage | undefined>
}
/** Absolute URL of the site's static/ folder (renderPage.tsx) */
quartzStaticUrl?: string
/** Prefetch settings, written by componentResources.ts ahead of prefetch.inline.ts */
__quartzPrefetchMode?: "viewport" | "hover"
__quartzSpa?: boolean
}
}
+25 -25
View File
@@ -13,7 +13,7 @@
"@floating-ui/dom": "^1.7.4",
"@myriaddreamin/rehype-typst": "^0.7.0",
"@napi-rs/simple-git": "1.1.0",
"@quartz-community/alias-redirects": "^1.0.2",
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.3",
"@quartz-community/bases-page": "^1.2.1",
@@ -24,7 +24,7 @@
"@quartz-community/comments": "^1.0.2",
"@quartz-community/content-meta": "^1.0.2",
"@quartz-community/content-page": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.2",
"@quartz-community/created-modified-date": "^1.0.3",
"@quartz-community/darkmode": "^1.0.2",
"@quartz-community/description": "^1.0.2",
"@quartz-community/encrypted-pages": "^1.1.1",
@@ -38,7 +38,7 @@
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.0.1",
"@quartz-community/note-properties": "^1.1.4",
"@quartz-community/obsidian-flavored-markdown": "^2.1.2",
"@quartz-community/obsidian-flavored-markdown": "^2.1.3",
"@quartz-community/og-image": "^1.1.1",
"@quartz-community/ox-hugo": "^1.0.1",
"@quartz-community/page-title": "^1.0.2",
@@ -98,7 +98,7 @@
"devDependencies": {
"@changesets/cli": "^2.29.2",
"@quartz-community/types": "^1.3.0",
"@quartz-community/utils": "^1.1.1",
"@quartz-community/utils": "^1.2.0",
"@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9",
"@types/node": "^26.5.1",
@@ -2354,9 +2354,9 @@
}
},
"node_modules/@quartz-community/alias-redirects": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.2.tgz",
"integrity": "sha512-QdcaorfE0UVqy4EnZel0minOHODybU+6v0ZlK4knFFV6QT8ISi8WlL79RnOV51jxRJkRBR3E7CED8kCa3l/RCA==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.3.tgz",
"integrity": "sha512-kA3MiAneoHlC09uQJxF1ex1GktkUf9Rm53b0ybeJrtNEcteRoqBCELHB+pf6hUj9i/k2Epx0J8RyTSe/zwTg2A==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2602,9 +2602,9 @@
}
},
"node_modules/@quartz-community/created-modified-date": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/created-modified-date/-/created-modified-date-1.0.2.tgz",
"integrity": "sha512-XMfFV4hwBVrRxtMO8QjWhXqarOHaip483oW3YHfqqcCfInlVCrDHRzAgpurOvTcLrlc60p6S7sZfRXwQYko/Sw==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/created-modified-date/-/created-modified-date-1.0.3.tgz",
"integrity": "sha512-oSFR4oK5ELG/Ya2Z1ah51P8p7q9dDaNTSg1cA4Op4c1xETfCmwIfS0wx6gF62MsypSR9uRavr+cfDJXxsujjWg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
@@ -2917,15 +2917,15 @@
}
},
"node_modules/@quartz-community/obsidian-flavored-markdown": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.1.2.tgz",
"integrity": "sha512-aayc91CLyI2nwq0vs4i+7Q8723QuVjADk/EaQlg47GEM3MuRS5RcgEC+NBCeA59/JnJyqqmLHTC1ZITQ9L+Yww==",
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.1.3.tgz",
"integrity": "sha512-p5fls4M7ocUKrlF8MmfrlnNPEvBFZ5diVNVVkLsgTwCvzf19MrnczeKb3Q2yI2S1G2Xb0rXsq8kmF8faj+Q79A==",
"license": "MIT",
"dependencies": {
"@quartz-community/rehype-obsidian": "^1.2.0",
"@quartz-community/remark-obsidian": "^2.2.0",
"@quartz-community/rehype-obsidian": "^1.3.0",
"@quartz-community/remark-obsidian": "^2.2.1",
"@quartz-community/types": "^1.1.0",
"@quartz-community/utils": "^1.1.0",
"@quartz-community/utils": "^1.2.0",
"pele": "^1.13.0"
},
"engines": {
@@ -3089,18 +3089,18 @@
}
},
"node_modules/@quartz-community/rehype-obsidian": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.2.1.tgz",
"integrity": "sha512-wuxPcG5ie4J7x7KMfOZMDSgyNKFJf6x6I+I6H4XaZ4WX4sPlEfMUDTvxBoHRHpstqfCRX5Hy73d/K9/rYAZdnw==",
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.3.0.tgz",
"integrity": "sha512-62YFEr3NR/Z2G/wcq30/VVKTlT4RUKezWfwGTQkNC+9mAXcUb3gAwjgiUJwylXZQyZmBf+SZsCNmdhIb7CPh/g==",
"license": "MIT",
"engines": {
"node": ">=22"
}
},
"node_modules/@quartz-community/remark-obsidian": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.0.tgz",
"integrity": "sha512-uSuUA3CA2ebAls7IXaevgQGqqbho1fR0lORKUTmhOTEUTYt8GBkl7ipaik4Y7x3q1LzUflejgFIGl/0XO83OGw==",
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.1.tgz",
"integrity": "sha512-Q18F/Px8db8Evf6uwPKz0RMhZNyrsH2Okzhr6FWcsm51fYgJR+SiO98/2fmXQ3wnqV2eeJC7ZMzi81SDjK8vrg==",
"license": "MIT",
"engines": {
"node": ">=22"
@@ -3342,9 +3342,9 @@
}
},
"node_modules/@quartz-community/utils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.1.1.tgz",
"integrity": "sha512-iHjEOlbpqznut9YkoflXxd2Bl5TaBcMFwIouRxp2HTBcbCQbmHtAsL3sdLheC1YeM9bMxeFLAN2b7rIBR2r/og==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.2.0.tgz",
"integrity": "sha512-X32uBfhfNACQw2Ciw6F0XQ9qSoTMQeh78/2ZEj8cYuOk7VTowNf0dpjtSDKAxs1co6aSpIEcDZBIG6p953UPiQ==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
+4 -4
View File
@@ -43,7 +43,7 @@
"@floating-ui/dom": "^1.7.4",
"@myriaddreamin/rehype-typst": "^0.7.0",
"@napi-rs/simple-git": "1.1.0",
"@quartz-community/alias-redirects": "^1.0.2",
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.3",
"@quartz-community/bases-page": "^1.2.1",
@@ -54,7 +54,7 @@
"@quartz-community/comments": "^1.0.2",
"@quartz-community/content-meta": "^1.0.2",
"@quartz-community/content-page": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.2",
"@quartz-community/created-modified-date": "^1.0.3",
"@quartz-community/darkmode": "^1.0.2",
"@quartz-community/description": "^1.0.2",
"@quartz-community/encrypted-pages": "^1.1.1",
@@ -68,7 +68,7 @@
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.0.1",
"@quartz-community/note-properties": "^1.1.4",
"@quartz-community/obsidian-flavored-markdown": "^2.1.2",
"@quartz-community/obsidian-flavored-markdown": "^2.1.3",
"@quartz-community/og-image": "^1.1.1",
"@quartz-community/ox-hugo": "^1.0.1",
"@quartz-community/page-title": "^1.0.2",
@@ -125,7 +125,7 @@
"devDependencies": {
"@changesets/cli": "^2.29.2",
"@quartz-community/types": "^1.3.0",
"@quartz-community/utils": "^1.1.1",
"@quartz-community/utils": "^1.2.0",
"@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9",
"@types/node": "^26.5.1",
+1
View File
@@ -4,6 +4,7 @@ configuration:
pageTitleSuffix: ""
enableSPA: true
enablePopovers: true
prefetch: viewport
analytics:
provider: plausible
locale: en-US
+6
View File
@@ -68,6 +68,12 @@ export interface GlobalConfiguration {
enableSPA: boolean
/** Whether to display Wikipedia-style popovers when hovering over links */
enablePopovers: boolean
/**
* Fetch pages before their links are followed, so they open at once (works with and without
* SPA routing). `viewport` (default): links on screen, while the browser is idle, and links
* pointed at. `hover`: only links pointed at, focused or touched. `off`: never.
*/
prefetch?: "viewport" | "hover" | "off"
/** Analytics mode */
analytics: Analytics
/** Glob patterns to not search */
+4
View File
@@ -264,6 +264,10 @@ export function isLocalSource(source) {
if (url.startsWith("./") || url.startsWith("../") || url.startsWith("/")) {
return true
}
// Windows relative paths (.\plugin, ..\plugin)
if (url.startsWith(".\\") || url.startsWith("..\\")) {
return true
}
// Windows absolute paths (e.g. C:\ or D:/)
if (/^[A-Za-z]:[\\/]/.test(url)) {
return true
+26 -1
View File
@@ -1,7 +1,12 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import YAML from "yaml"
import { stringifyConfigYaml, parseGitSource, extractPluginName } from "./plugin-data.js"
import {
stringifyConfigYaml,
parseGitSource,
extractPluginName,
isLocalSource,
} from "./plugin-data.js"
const ORIGINAL = `# yaml-language-server: $schema=./quartz/plugins/quartz-plugins.schema.json
configuration:
@@ -92,3 +97,23 @@ describe("parseGitSource", () => {
assert.throws(() => parseGitSource("github:onlyowner"), /Expected github:owner\/repo/)
})
})
describe("isLocalSource", () => {
test("recognises local paths in POSIX and Windows spellings", () => {
for (const source of [
"./p",
"../p",
"/p",
".\\p",
"..\\a\\p",
"C:\\a\\p",
"D:/p",
{ repo: ".\\p" },
]) {
assert.ok(isLocalSource(source), JSON.stringify(source))
}
for (const source of ["github:a/b", "a/b", "https://github.com/a/b.git"]) {
assert.ok(!isLocalSource(source), source)
}
})
})
+18
View File
@@ -52,6 +52,7 @@ import {
} from "./subprocess.js"
import { writePluginIndex } from "./plugin-index.js"
import {
builtinKeyFor,
builtinMessage,
describeBuiltins,
findBuiltinMigrations,
@@ -2662,6 +2663,23 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
if (deprecation) report("warning", null, deprecation.message, deprecation.hint)
if (enabled) {
for (const dep of manifest.dependencies ?? []) {
// A plugin that is built into core now (crawl-links → configuration.links, …) is
// satisfied by the built-in: its entries were absorbed above.
const builtinKey = builtinKeyFor(dep)
if (builtinKey) {
const builtin = describeBuiltins(config.data.configuration).find(
(b) => b.key === builtinKey,
)
if (builtin && !builtin.enabled) {
report(
"warning",
label,
`depends on ${dep}, which is built into Quartz now as configuration.${builtinKey} and is disabled`,
`Enable configuration.${builtinKey} in quartz.config.yaml.`,
)
}
continue
}
const depEntry =
enabledSources.get(dep) ??
plugins.find((e) => {
+3 -2
View File
@@ -12,6 +12,7 @@
*/
import fs from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { styleText } from "node:util"
import { isIdentifier, jsString } from "./subprocess.js"
@@ -135,8 +136,8 @@ export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = f
for (const pkg of npmPackages) {
let distIndex
try {
const pkgJson = new URL(import.meta.resolve(`${pkg}/package.json`)).pathname
distIndex = path.join(path.dirname(decodeURIComponent(pkgJson)), "dist", "index.d.ts")
const pkgJson = fileURLToPath(import.meta.resolve(`${pkg}/package.json`))
distIndex = path.join(path.dirname(pkgJson), "dist", "index.d.ts")
} catch {
if (verbose) console.log(styleText("yellow", `⚠`), `Skipping npm package ${pkg}: not found`)
continue
+14
View File
@@ -46,6 +46,20 @@ function fakeSite() {
}
describe("plugin index", () => {
// npm plugins are found through import.meta.resolve, which returns a file: URL. Its pathname
// is not a path on Windows (`/C:/…`), so every npm plugin was skipped there (#2616).
test("npm plugins are found through their package.json", () => {
const pluginsDir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-plugin-index-npm-"))
const entry = collectPluginExports({
pluginsDir,
npmPackages: ["@quartz-community/explorer"],
}).get("quartz-community__explorer")
assert.ok(entry, "@quartz-community/explorer was skipped")
assert.ok(entry.overridable.includes("Explorer"))
assert.strictEqual(entry.importPath, "@quartz-community/explorer")
fs.rmSync(pluginsDir, { recursive: true, force: true })
})
test("component constructors re-exported from a sub-module are wrapped (#2565)", () => {
const { root, pluginsDir } = fakeSite()
const entry = collectPluginExports({ pluginsDir }).get("my-widget")!
+35 -4
View File
@@ -137,14 +137,38 @@ export function findConfigEntries(plugins, query, { extractName, formatSource })
return { indices: [], suggestion }
}
/**
* The JSON Schema of a plugin's options: `configSchema`, or `optionSchema`, the name first-party
* plugins (and Quartz Syncer) use. An `optionSchema` is usually a flat map of option name to
* property schema (`{ limit: { type: "number" }, mode: { type: "enum", values: [...] } }`); it is
* read as `{ type: "object", properties: … }`, with `type: "enum"` + `values` as a JSON `enum`.
*
* @param {{ configSchema?: any, optionSchema?: any }} manifest
* @returns {any | null}
*/
export function optionsSchemaOf(manifest) {
const declared = manifest.configSchema ?? manifest.optionSchema
if (!isPlainObject(declared)) return null
if (isPlainObject(declared.properties) || declared.type === "object") return declared
const properties = {}
for (const [key, prop] of Object.entries(declared)) {
if (!isPlainObject(prop)) continue
properties[key] =
prop.type === "enum" && Array.isArray(prop.values)
? { ...prop, type: undefined, enum: prop.values }
: prop
}
return { type: "object", properties }
}
/**
* Validate a plugin's options against its manifest (`defaultOptions` and, when
* present, `configSchema`). Unknown keys are only flagged as warnings when they
* present, `configSchema`, or its alias `optionSchema`). Unknown keys are only flagged as warnings when they
* look like a typo of a known key (or the schema forbids extra keys), because
* many plugins accept options that have no default.
*
* @param {unknown} options
* @param {{ defaultOptions?: Record<string, unknown>, configSchema?: any } | null | undefined} manifest
* @param {{ defaultOptions?: Record<string, unknown>, configSchema?: any, optionSchema?: any } | null | undefined} manifest
* @param {string} [prefix]
* @returns {Array<{ severity: "warning" | "info", path: string, message: string, suggestion?: string }>}
*/
@@ -153,7 +177,7 @@ export function validatePluginOptions(options, manifest, prefix = "") {
if (!isPlainObject(options) || !manifest) return issues
const defaults = isPlainObject(manifest.defaultOptions) ? manifest.defaultOptions : {}
const schema = isPlainObject(manifest.configSchema) ? manifest.configSchema : null
const schema = optionsSchemaOf(manifest)
const schemaProps = schema && isPlainObject(schema.properties) ? schema.properties : {}
const known = new Set([...Object.keys(defaults), ...Object.keys(schemaProps)])
if (known.size === 0) return issues
@@ -211,7 +235,14 @@ export function validatePluginOptions(options, manifest, prefix = "") {
? describeType(defaults[key])
: null
const actual = describeType(value)
if (expected && expected !== actual) {
// a value of the default's own type is fine even when the schema says otherwise (schemas
// can lag behind: recent-notes' `linkToMore` is typed string, its default is false)
const matchesDefault =
key in defaults &&
defaults[key] !== null &&
defaults[key] !== undefined &&
describeType(defaults[key]) === actual
if (expected && expected !== actual && !matchesDefault) {
const shown = key in defaults ? ` (default: ${JSON.stringify(defaults[key])})` : ""
issues.push({
severity: "warning",
+45
View File
@@ -137,6 +137,51 @@ describe("validatePluginOptions", () => {
assert.strictEqual(issues[0].suggestion, "dark")
assert.strictEqual(issues[1].severity, "warning")
})
// first-party plugins (and Quartz Syncer) name the field optionSchema, as a flat map
test("reads a flat optionSchema, with type enum + values", () => {
const manifest = {
defaultOptions: { limit: 3 },
optionSchema: {
limit: { type: "number" },
mode: { type: "enum", values: ["light", "dark"] },
show: { type: "boolean" },
},
}
const issues = validatePluginOptions({ mode: "drak", limit: "5", shwo: true }, manifest)
assert.deepStrictEqual(
issues.map((i) => [i.path, i.severity, i.suggestion]),
[
["mode", "warning", "dark"],
["limit", "warning", undefined],
["shwo", "warning", "show"],
],
)
assert.deepStrictEqual(validatePluginOptions({ mode: "dark", show: false }, manifest), [])
})
test("accepts a value of the default's type when the schema disagrees", () => {
const manifest = {
defaultOptions: { linkToMore: false },
optionSchema: { linkToMore: { type: "string" } },
}
assert.deepStrictEqual(validatePluginOptions({ linkToMore: false }, manifest), [])
assert.deepStrictEqual(validatePluginOptions({ linkToMore: "tags/" }, manifest), [])
assert.strictEqual(validatePluginOptions({ linkToMore: 3 }, manifest)[0]?.severity, "warning")
})
test("reads optionSchema as the same schema", () => {
const issues = validatePluginOptions(
{ mode: "drak" },
{
optionSchema: {
type: "object",
properties: { mode: { type: "string", enum: ["light", "dark"] } },
},
},
)
assert.strictEqual(issues[0]?.suggestion, "dark")
})
})
describe("validatePluginEntry", () => {
+10 -6
View File
@@ -55,12 +55,16 @@ async function mouseEnterHandler(
return
}
const response = await fetchCanonical(targetUrl).catch((err) => {
console.error(err)
})
// A page fetched ahead (prefetch.inline.ts) is used as is, instead of fetching it again.
const prefetched = await window.quartzPrefetch?.load(targetUrl)
const response = prefetched
? undefined
: await fetchCanonical(targetUrl).catch((err) => {
console.error(err)
})
if (!response) return
const rawContentType = response.headers.get("Content-Type")
if (!prefetched && !response) return
const rawContentType = prefetched?.contentType ?? response?.headers.get("Content-Type")
if (!rawContentType) return
const [contentType] = rawContentType.split(";")
const [contentTypeCategory, typeInfo] = contentType.split("/")
@@ -93,7 +97,7 @@ async function mouseEnterHandler(
}
break
default:
const contents = await response.text()
const contents = prefetched ? (prefetched.text ?? "") : await response!.text()
const html = p.parseFromString(contents, "text/html")
normalizeRelativeURLs(html, targetUrl)
// prepend all IDs inside popovers to prevent duplicates
@@ -0,0 +1,265 @@
import { fetchCanonical } from "./util"
/**
* Prefetching: fetch the pages a reader is likely to open next, so following a link shows the
* page at once instead of waiting for the network.
*
* - `viewport` (default): links on screen are fetched while the browser is idle, a few at a
* time; pointing at or focusing a link fetches it first.
* - `hover`: only links pointed at (after a short pause), focused, or touched.
*
* With SPA routing the pages are kept here, and the router (spa.inline.ts) and popovers
* (popover.inline.ts) take them through `window.quartzPrefetch`. Without it, every link is a full
* page load, so the browser prefetches instead: Speculation Rules where supported, otherwise
* `<link rel="prefetch">`. Nothing is prefetched with Data Saver on or on a 2G connection,
* except links pointed at.
*
* The mode is set by componentResources.ts, which prepends `window.__quartzPrefetchMode = …`.
*/
type Mode = "viewport" | "hover"
/** How long a fetched page is used before it is fetched again. */
const MAX_AGE_MS = 5 * 60 * 1000
/** Pages kept in memory (the oldest go first). */
const MAX_PAGES = 40
/** Pages fetched at once from the viewport. */
const CONCURRENCY = 2
/** Pages fetched from the viewport per page view. */
const VIEWPORT_BUDGET = 30
/** Pointing at a link this long counts as intent (instant.page's figure). */
const HOVER_DELAY_MS = 65
const mode: Mode = window.__quartzPrefetchMode === "hover" ? "hover" : "viewport"
const spa = window.__quartzSpa === true
type Cached = { time: number; page: Promise<PrefetchedPage | undefined> }
const cache = new Map<string, Cached>()
const requested = new Set<string>()
function keyOf(url: URL): string {
const u = new URL(url)
u.hash = ""
return u.toString()
}
function constrained(): boolean {
const connection = (
navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } }
).connection
return !!connection?.saveData || /(^|-)2g$/.test(connection?.effectiveType ?? "")
}
/** A same-site page link worth fetching ahead, or undefined. */
function targetOf(a: HTMLAnchorElement): URL | undefined {
if (!a.href || a.target === "_blank" || a.hasAttribute("download")) return
if ("routerIgnore" in a.dataset || "noPrefetch" in a.dataset) return
let url: URL
try {
url = new URL(a.href)
} catch {
return
}
if (url.origin !== window.location.origin || !/^https?:$/.test(url.protocol)) return
if (url.pathname === window.location.pathname && url.search === window.location.search) return
// pages have no extension (or .html); a link to an image, PDF or file is not worth the bytes
const last = url.pathname.split("/").pop() ?? ""
if (/\.[A-Za-z0-9]+$/.test(last) && !/\.html?$/i.test(last)) return
return url
}
async function load(url: URL, priority: "low" | "high"): Promise<PrefetchedPage | undefined> {
try {
const res = await fetchCanonical(url, { priority } as RequestInit)
if (!res.ok) return undefined
const contentType = res.headers.get("content-type") ?? ""
if (!contentType.startsWith("text/html")) {
await res.body?.cancel()
return { url: res.url || url.toString(), contentType }
}
return { url: res.url || url.toString(), contentType, text: await res.text() }
} catch {
return undefined
}
}
function remember(url: URL, priority: "low" | "high" = "low"): Promise<PrefetchedPage | undefined> {
const key = keyOf(url)
const hit = cache.get(key)
if (hit && Date.now() - hit.time < MAX_AGE_MS) return hit.page
const page = load(url, priority)
cache.set(key, { time: Date.now(), page })
// a failed fetch is not kept, so following the link fetches it normally
page.then((p) => p === undefined && cache.get(key)?.page === page && cache.delete(key))
while (cache.size > MAX_PAGES) cache.delete(cache.keys().next().value!)
return page
}
const supportsSpeculationRules =
typeof HTMLScriptElement !== "undefined" &&
typeof HTMLScriptElement.supports === "function" &&
HTMLScriptElement.supports("speculationrules")
/** Without SPA routing: ask the browser to prefetch the page for the navigation. */
function hintBrowser(url: URL) {
const key = keyOf(url)
if (requested.has(key)) return
requested.add(key)
if (supportsSpeculationRules) {
const script = document.createElement("script")
script.type = "speculationrules"
script.textContent = JSON.stringify({ prefetch: [{ source: "list", urls: [key] }] })
document.head.appendChild(script)
} else {
const link = document.createElement("link")
link.rel = "prefetch"
link.href = key
link.setAttribute("as", "document")
document.head.appendChild(link)
}
}
function prefetch(url: URL) {
if (spa) void remember(url)
else hintBrowser(url)
}
window.quartzPrefetch = {
// The page from the cache, or fetched now and kept: whoever asks first (a popover on
// mouseenter, the prefetcher after its hover delay, the router on click) fetches it once.
load: (url: URL) => remember(url, "high"),
}
// --- intent: pointing at, focusing or touching a link -------------------------------------
let hoverTimer: ReturnType<typeof setTimeout> | undefined
const anchorOf = (target: EventTarget | null) =>
target instanceof Element ? target.closest("a") : null
document.addEventListener(
"pointerover",
(event) => {
const a = anchorOf(event.target)
const url = a && targetOf(a)
if (!url) return
clearTimeout(hoverTimer)
hoverTimer = setTimeout(() => prefetch(url), HOVER_DELAY_MS)
},
{ passive: true },
)
document.addEventListener(
"pointerout",
(event) => {
if (anchorOf(event.target)) clearTimeout(hoverTimer)
},
{ passive: true },
)
for (const type of ["pointerdown", "focusin"] as const) {
document.addEventListener(
type,
(event) => {
const a = anchorOf(event.target)
const url = a && targetOf(a)
if (url) prefetch(url)
},
{ passive: true },
)
}
// --- viewport: links on screen, while the browser is idle --------------------------------
const idle = (fn: () => void) =>
"requestIdleCallback" in window
? window.requestIdleCallback(fn, { timeout: 2000 })
: setTimeout(fn, 200)
let observer: IntersectionObserver | undefined
let queue: URL[] = []
let active = 0
let budget = VIEWPORT_BUDGET
function pump() {
while (active < CONCURRENCY && queue.length > 0 && budget > 0) {
const url = queue.shift()!
if (cache.has(keyOf(url)) || requested.has(keyOf(url))) continue
budget--
active++
idle(() => {
if (spa) {
remember(url).finally(() => {
active--
pump()
})
} else {
hintBrowser(url)
active--
pump()
}
})
}
}
// Links on screen are fetched only when they name a page the site has (the content index, plus
// the folder and tag pages it doesn't list): a link in a layout to a page that doesn't exist
// would otherwise log a 404 on every page view. Without a content index, any link counts.
let known: Set<string> | undefined
const knownReady: Promise<void> = (
typeof fetchData === "undefined" ? Promise.resolve({}) : fetchData
).then((index) => {
const slugs = Object.keys(index ?? {})
if (slugs.length > 0) known = new Set(slugs)
})
function isKnownPage(url: URL): boolean {
if (!known) return true
const root = window.quartzStaticUrl ? new URL("..", window.quartzStaticUrl).pathname : "/"
if (!url.pathname.startsWith(root)) return false
let slug: string
try {
slug = decodeURI(url.pathname.slice(root.length)).replace(/\.html?$/i, "")
} catch {
return false
}
if (slug === "" || slug.endsWith("/")) slug += "index"
return known.has(slug) || slug.endsWith("index") || slug.startsWith("tags/")
}
let observed = new WeakSet<Element>()
let queued = new Set<string>()
/** Watch the links on the page not watched yet (components may add theirs after `nav`). */
function scan() {
if (!observer) return
for (const a of document.querySelectorAll<HTMLAnchorElement>("a[href]")) {
if (observed.has(a)) continue
observed.add(a)
if (targetOf(a)) observer.observe(a)
}
}
function watchViewport() {
observer?.disconnect()
observer = undefined
queue = []
queued = new Set()
observed = new WeakSet()
budget = VIEWPORT_BUDGET
if (mode !== "viewport" || constrained() || !("IntersectionObserver" in window)) return
observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue
observer?.unobserve(entry.target)
const url = targetOf(entry.target as HTMLAnchorElement)
if (!url || !isKnownPage(url) || queued.has(keyOf(url))) continue
queued.add(keyOf(url))
queue.push(url)
}
pump()
})
// after the other `nav` handlers have rendered their links (explorer, backlinks, …)
idle(() => knownReady.then(scan))
}
// every page view (SPA navigations included) brings new links
document.addEventListener("nav", watchViewport)
document.addEventListener("render", () => idle(() => knownReady.then(scan)))
+29 -16
View File
@@ -72,22 +72,35 @@ async function _navigate(url: URL, isBack: boolean = false) {
// canonical link) changes the base its relative links resolve against, and the address bar
// should show it too. fetch() drops the #hash, so keep the requested one.
let finalUrl = url
const contents = await fetchCanonical(url)
.then((res) => {
if (res.url) {
finalUrl = new URL(res.url)
finalUrl.hash = url.hash
}
const contentType = res.headers.get("content-type")
if (contentType?.startsWith("text/html")) {
return res.text()
} else {
window.location.assign(url)
}
})
.catch(() => {
window.location.assign(url)
})
// A page fetched ahead (prefetch.inline.ts) is shown at once; one still loading is awaited.
const prefetched = await window.quartzPrefetch?.load(url)
if (prefetched && prefetched.text === undefined) {
// not a page (e.g. a file served without an extension): let the browser open it
window.location.assign(url)
return
}
if (prefetched) {
finalUrl = new URL(prefetched.url)
finalUrl.hash = url.hash
}
const contents = prefetched
? prefetched.text
: await fetchCanonical(url)
.then((res) => {
if (res.url) {
finalUrl = new URL(res.url)
finalUrl.hash = url.hash
}
const contentType = res.headers.get("content-type")
if (contentType?.startsWith("text/html")) {
return res.text()
} else {
window.location.assign(url)
}
})
.catch(() => {
window.location.assign(url)
})
if (!contents) return
+3 -3
View File
@@ -32,8 +32,8 @@ export function removeAllChildren(node: HTMLElement) {
// way less robust - we only care about our own generated redirects after all.
const canonicalRegex = /<link rel="canonical" href="([^"]*)">/
export async function fetchCanonical(url: URL): Promise<Response> {
const res = await fetch(`${url}`)
export async function fetchCanonical(url: URL, init?: RequestInit): Promise<Response> {
const res = await fetch(`${url}`, init)
if (!res.headers.get("content-type")?.startsWith("text/html")) {
return res
}
@@ -42,5 +42,5 @@ export async function fetchCanonical(url: URL): Promise<Response> {
// to allow the caller to read it if it's was not a redirect
const text = await res.clone().text()
const [_, redirect] = text.match(canonicalRegex) ?? []
return redirect ? fetch(`${new URL(redirect, url)}`) : res
return redirect ? fetch(`${new URL(redirect, url)}`, init) : res
}
+47 -1
View File
@@ -4,7 +4,7 @@ import { unified } from "unified"
import remarkParse from "remark-parse"
import remarkRehype from "remark-rehype"
import { VFile } from "vfile"
import { Element, Root } from "hast"
import { Element, Root, Text } from "hast"
import { visit } from "unist-util-visit"
import { BUILTINS, instantiateBuiltins, officialPluginName, planBuiltins, PlanInput } from "."
import {
@@ -361,6 +361,52 @@ describe("links built-in", () => {
assert.strictEqual(els[1].properties.src, "../../media/a.mp4")
})
// Obsidian 1.15.0 (remark-obsidian 2.2.1's triage, re-probed): a path that is not valid
// percent-encoding names no file, so the link is external; `x:y` has a scheme, `../x:y` doesn't
test("links Obsidian reads as external", () => {
const { els } = run([a("%zz"), a("a%E2.md"), a("x:y"), a("../x:y")], "sub/note", {}, ["xy"])
const classes = els.filter((e) => e.tagName === "a").map((e) => e.properties.className)
assert.deepStrictEqual(
classes.map((c) => (c as string[])[0]),
["external", "external", "external", "internal"],
)
})
test("an image of a missing file without alt text shows its decoded path", () => {
const img = (src: string, alt?: string): Element => ({
type: "element",
tagName: "img",
properties: alt === undefined ? { src } : { src, alt },
children: [],
})
const { els } = run(
[
img("missing%20pic.png"),
img("missing%20image.png", "alt"),
img("pic.png"),
img("/static/x.png"),
],
"page",
{ markdownLinkResolution: "absolute" },
["page", "pic.png"],
)
assert.deepStrictEqual(
els.map((e) => e.properties.alt),
["missing pic.png", "alt", undefined, undefined],
)
})
test("pretty links keep the last /-separated part of the link text, on every OS", () => {
const { els } = run([a("folder/note"), a("a\\b")], "page", { prettyLinks: true }, [
"folder/note",
"a\\b",
])
assert.deepStrictEqual(
els.filter((e) => e.tagName === "a").map((e) => (e.children[0] as Text).value),
["note", "a\\b"],
)
})
test("disableBrokenWikilinks adds a broken class to missing targets", () => {
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: true }, ["page"])
assert.ok((els[0].properties.className as string[]).includes("broken"))
+20 -4
View File
@@ -8,6 +8,7 @@ import { LinksConfig } from "../../cfg"
import {
FullSlug,
RelativeURL,
linkPathDecodes,
SimpleSlug,
TransformOptions,
resolveRelative,
@@ -46,7 +47,9 @@ export const legacyCrawlLinksDefaults: Partial<LinksConfig> = {
}
const isAbsolute = isAbsoluteUrl as (url: string, options?: { httpOnly?: boolean }) => boolean
const isExternalUrl = (url: string) => isAbsolute(url, { httpOnly: false })
// As in Obsidian: a URL with a scheme (`x:y`, but not `../x:y`), or a link whose path is not valid
// percent-encoding (`%zz`, `a%E2.md`), which names no file
const isExternalUrl = (url: string) => isAbsolute(url, { httpOnly: false }) || !linkPathDecodes(url)
const EXTERNAL_ICON_PATH =
"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"
@@ -163,7 +166,8 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
!textChild.value.startsWith("#") &&
!classes.includes("alias")
) {
textChild.value = path.basename(textChild.value)
// link text is not an OS path: path.posix, or Windows would also cut at a backslash
textChild.value = path.posix.basename(textChild.value)
}
}
}
@@ -175,8 +179,20 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
typeof node.properties.src === "string"
) {
if (opts.lazyLoad) node.properties.loading = "lazy"
if (!isExternalUrl(node.properties.src)) {
node.properties.src = resolveLink(node.properties.src as RelativeURL)
const src = node.properties.src
if (!isExternalUrl(src)) {
node.properties.src = resolveLink(src as RelativeURL)
// An embed of a file the site doesn't have: Obsidian shows its path, percent-decoded
// (`![](missing%20pic.png)` → “missing pic.png”). The image shows its alt text, so
// an image without one gets the path; an author's alt text is kept.
const target =
node.tagName === "img" && !node.properties.alt && !src.startsWith("#")
? canonicalSlug(node.properties.src as string, curSlug)
: undefined
// (quartz/static is served at static/ but holds no content files)
if (target && !target.startsWith("static/") && !ctx.allSlugs.includes(target)) {
node.properties.alt = decodeURI(splitAnchor(src)[0])
}
}
}
@@ -7,6 +7,8 @@ import { emitStaticAssets } from "./staticAssets"
import spaRouterScript from "../../components/scripts/spa.inline"
// @ts-ignore
import popoverScript from "../../components/scripts/popover.inline"
// @ts-ignore
import prefetchScript from "../../components/scripts/prefetch.inline"
import baseStyles from "../../styles/base.scss"
import customStyles from "../../styles/custom.scss"
import popoverStyle from "../../components/styles/popover.scss"
@@ -270,6 +272,18 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
`)
}
// Prefetching (before the router or the no-SPA shim: both dispatch the first `nav`). Its
// settings lead the same script, since the other scripts load in parallel.
// (`prefetch: false` in YAML means off as well)
const prefetch = (cfg.prefetch as unknown) === false ? "off" : (cfg.prefetch ?? "viewport")
if (prefetch !== "off") {
componentResources.afterDOMLoaded.push(
`window.__quartzPrefetchMode = ${js(prefetch)};\n` +
`window.__quartzSpa = ${cfg.enableSPA ? "true" : "false"};\n` +
prefetchScript,
)
}
if (cfg.enableSPA) {
componentResources.afterDOMLoaded.push(spaRouterScript)
} else {
@@ -197,3 +197,12 @@ describe("validatePluginCapabilities", () => {
assert.deepStrictEqual(report.warnings, [])
})
})
describe("core globals", () => {
test("quartzStaticUrl always, quartzPrefetch unless prefetching is off", () => {
assert.ok(coreCapabilities().globals?.includes("quartzStaticUrl"))
assert.ok(coreCapabilities().globals?.includes("quartzPrefetch"))
assert.ok(coreCapabilities({ prefetch: "hover" }).globals?.includes("quartzPrefetch"))
assert.ok(!coreCapabilities({ prefetch: "off" }).globals?.includes("quartzPrefetch"))
})
})
+15 -4
View File
@@ -87,14 +87,25 @@ export interface CapabilityReport {
* Capabilities Quartz core itself always provides (independent of plugins).
* Kept deliberately small: only things core code sets or renders unconditionally.
*/
export function coreCapabilities(configuration?: { enableSPA?: boolean }): CapabilityList {
export function coreCapabilities(configuration?: {
enableSPA?: boolean
prefetch?: string | boolean
}): CapabilityList {
const prefetch = configuration?.prefetch !== "off" && configuration?.prefetch !== false
return {
// quartz/processors/parse.ts
data: ["slug", "filePath", "relativePath"],
// renderPage.tsx / frames
dom: ["#quartz-body", ".page", ".center", "article", ".popover-hint", ".sidebar"],
// renderPage.tsx (fetchData), componentResources.ts (spaNavigate/addCleanup, SPA or not)
globals: ["fetchData", "addCleanup", "spaNavigate"],
// renderPage.tsx (fetchData, quartzStaticUrl), componentResources.ts (spaNavigate/addCleanup,
// SPA or not; quartzPrefetch unless prefetching is off)
globals: [
"fetchData",
"addCleanup",
"spaNavigate",
"quartzStaticUrl",
...(prefetch ? ["quartzPrefetch"] : []),
],
// componentResources.ts dispatches "nav" in both modes; spa.inline.ts adds "prenav"
events: configuration?.enableSPA === false ? ["nav"] : ["nav", "prenav"],
}
@@ -303,7 +314,7 @@ export async function validatePluginCapabilities<E extends { enabled: boolean }>
manifestFor: (
entry: E,
) => Promise<ManifestLike | null | undefined> | ManifestLike | null | undefined
configuration?: { enableSPA?: boolean }
configuration?: { enableSPA?: boolean; prefetch?: string | boolean }
/** Built-in processing steps (see plugins/builtins): enabled ones provide, others are suggested. */
builtins?: { enabled: CapabilityPlugin[]; available: CapabilityPlugin[] }
}): Promise<CapabilityReport> {
+69 -1
View File
@@ -1,6 +1,13 @@
import test, { describe, afterEach } from "node:test"
import assert from "node:assert"
import { buildLayoutForEntries, isExcluded, resolveGroups } from "./config-loader"
import {
buildLayoutForEntries,
isExcluded,
resolveGroups,
validateDependencies,
} from "./config-loader"
import { planBuiltins } from "../builtins"
import type { PluginManifest } from "./types"
import { componentRegistry } from "../../components/registry"
import type { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
import { PluginJsonEntry, LayoutPosition } from "./types"
@@ -321,3 +328,64 @@ describe("isExcluded", () => {
assert.ok(!isExcluded("@quartz-community/explorer", ["reader-mode"]))
})
})
// crawl-links, remove-draft and content-index are built into core in 5.1: their entries are
// absorbed before dependencies are checked, so a plugin depending on one must be satisfied by the
// built-in (a community plugin depending on crawl-links failed every 5.1 build).
describe("dependencies on plugins that are built in now", () => {
const source = "github:someone/cloudflare-media"
const check = (configuration: Record<string, unknown>, order?: number) => {
const entry: PluginJsonEntry = { source, enabled: true, options: {}, order }
const manifest = {
name: "cloudflare-media",
category: "transformer",
defaultOrder: 65,
dependencies: ["@quartz-community/crawl-links"],
} as unknown as PluginManifest
const plan = planBuiltins({
configuration,
entries: [],
nameOf: () => "",
providesOf: () => undefined,
})
return validateDependencies([entry], new Map([[source, manifest]]), plan.builtins)
}
test("are satisfied by the enabled built-in", () => {
assert.deepStrictEqual(check({}), { errors: [], warnings: [] })
})
test("warn when the built-in is disabled", () => {
const { errors, warnings } = check({ links: false })
assert.deepStrictEqual(errors, [])
assert.match(warnings[0], /built into Quartz now as configuration\.links and is disabled/)
})
test("must still run after the built-in in the same stage", () => {
const { errors } = check({}, 50)
assert.match(errors[0], /order: 50.*configuration\.links, order: 60/)
})
test("other missing dependencies still fail", () => {
const entry: PluginJsonEntry = { source, enabled: true, options: {} }
const manifest = { dependencies: ["@quartz-community/explorer"] } as unknown as PluginManifest
const { errors } = validateDependencies([entry], new Map([[source, manifest]]), [])
assert.match(errors[0], /requires "@quartz-community\/explorer"/)
})
})
describe("a dependency that is configured but disabled", () => {
test("is a warning, not a missing plugin", () => {
const dep = "@quartz-community/explorer"
const entries: PluginJsonEntry[] = [
{ source: "github:someone/x", enabled: true, options: {} },
{ source: dep, enabled: false, options: {} },
]
const manifests = new Map<string, PluginManifest>([
["github:someone/x", { dependencies: [dep] } as unknown as PluginManifest],
])
const { errors, warnings } = validateDependencies(entries, manifests, [])
assert.deepStrictEqual(errors, [])
assert.match(warnings[0], /depends on "@quartz-community\/explorer" which is disabled/)
})
})
+41 -4
View File
@@ -41,7 +41,13 @@ import {
parseCapabilities,
CapabilityPlugin,
} from "./capabilities"
import { absorbingBuiltin, BuiltinPlan, instantiateBuiltins, planBuiltins } from "../builtins"
import {
absorbingBuiltin,
BuiltinPlan,
instantiateBuiltins,
PlannedBuiltin,
planBuiltins,
} from "../builtins"
import { registerPluginOrigin, reportError, warn } from "../../util/diagnostics"
import { firstPluginFrame } from "../../util/trace"
import {
@@ -146,9 +152,10 @@ interface DependencyValidationResult {
warnings: string[]
}
function validateDependencies(
export function validateDependencies(
entries: PluginJsonEntry[],
manifests: Map<string, PluginManifest>,
builtins: PlannedBuiltin[] = [],
): DependencyValidationResult {
const errors: string[] = []
const warnings: string[] = []
@@ -172,6 +179,31 @@ function validateDependencies(
const depEntry = sourceToEntry.get(dep)
const depName = extractPluginName(dep)
// A plugin that is built into core now (crawl-links → configuration.links, …) has no entry
// to find: its entries are absorbed before this check. The built-in satisfies it.
const builtin = depEntry
? undefined
: builtins.find((b) => b.spec === absorbingBuiltin({ source: dep } as PluginJsonEntry))
if (builtin) {
if (!builtin.enabled) {
warnings.push(
`Plugin "${pluginName}" depends on "${depName}", which is built into Quartz now as ` +
`configuration.${builtin.spec.configKey} and is disabled. "${pluginName}" may not function correctly.`,
)
} else if (
pluginOrder < builtin.order &&
[manifest.category].flat().includes(builtin.spec.category)
) {
// order only decides between plugins of the same stage (a transformer after links)
errors.push(
`Plugin "${pluginName}" (order: ${pluginOrder}) depends on "${depName}" (built in as ` +
`configuration.${builtin.spec.configKey}, order: ${builtin.order}), but "${pluginName}" is ` +
`configured to run first. Increase "${pluginName}"'s order above ${builtin.order}.`,
)
}
continue
}
if (!depEntry) {
errors.push(
`Plugin "${pluginName}" requires "${depName}". Run: npx quartz plugin add ${dep}`,
@@ -183,6 +215,8 @@ function validateDependencies(
warnings.push(
`Plugin "${pluginName}" depends on "${depName}" which is disabled. "${pluginName}" may not function correctly.`,
)
// it doesn't run, so its order doesn't matter (and its manifest isn't loaded)
continue
}
const depManifest = manifests.get(dep)
@@ -293,7 +327,8 @@ async function readManifestFromPackageJson(source: PluginSource): Promise<Plugin
defaultOrder: q.defaultOrder,
defaultEnabled: q.defaultEnabled,
defaultOptions: q.defaultOptions,
configSchema: q.configSchema,
// first-party plugins (and Quartz Syncer) call it optionSchema
configSchema: q.configSchema ?? q.optionSchema,
components: q.components,
frames: q.frames,
}
@@ -473,7 +508,9 @@ export async function loadQuartzConfig(
)
// Validate dependencies
const validation = validateDependencies(enabledEntries, manifests)
// all entries: a dependency that is configured but disabled is a warning, not "missing"
// (validateDependencies skips disabled plugins itself)
const validation = validateDependencies(pluginEntries, manifests, builtinPlan.builtins)
for (const warning of validation.warnings) {
console.warn(styleText("yellow", `⚠`) + ` ${warning}`)
}
+20 -1
View File
@@ -3,7 +3,7 @@ import assert from "node:assert"
import fs from "fs"
import os from "os"
import path from "path"
import { parsePluginSource, readLockedCommit } from "./gitLoader"
import { isLocalSource, parsePluginSource, readLockedCommit } from "./gitLoader"
describe("parsePluginSource", () => {
test("owner/repo shorthand supports #ref", () => {
@@ -13,6 +13,25 @@ describe("parsePluginSource", () => {
assert.strictEqual(spec.ref, "dev")
})
test("local sources are recognised in POSIX and Windows spellings", () => {
for (const source of [
"./plugin",
"../plugin",
"/abs/plugin",
".\\plugin",
"..\\plugins\\x",
"C:\\sites\\plugin",
"D:/plugin",
{ repo: ".\\plugin" },
]) {
assert.ok(isLocalSource(source), JSON.stringify(source))
}
for (const source of ["github:a/b", "a/b", "https://github.com/a/b.git", "@scope/pkg"]) {
assert.ok(!isLocalSource(source), source)
}
assert.strictEqual(parsePluginSource(".\\plugin").local, true)
})
test("unknown sources get an explanatory error", () => {
assert.throws(() => parsePluginSource("explorer"), /Expected github:owner\/repo/)
})
+4
View File
@@ -111,6 +111,10 @@ export function isLocalSource(source: PluginSource): boolean {
if (source.startsWith("./") || source.startsWith("../") || source.startsWith("/")) {
return true
}
// Windows relative paths (.\plugin, ..\plugin)
if (source.startsWith(".\\") || source.startsWith("..\\")) {
return true
}
// Windows absolute paths (e.g. C:\ or D:/)
if (/^[A-Za-z]:[\\/]/.test(source)) {
return true
@@ -31,6 +31,12 @@
"type": "boolean",
"description": "Enable hover popovers for links"
},
"prefetch": {
"type": "string",
"enum": ["viewport", "hover", "off"],
"default": "viewport",
"description": "Fetch pages before their links are followed: links on screen and pointed at (viewport), only links pointed at (hover), or never (off)"
},
"locale": {
"type": "string",
"description": "Locale code for the site"
+1
View File
@@ -20,6 +20,7 @@ export {
splitAnchor,
slugTag,
transformInternalLink,
linkPathDecodes,
transformLink,
normalizeHastElement,
} from "@quartz-community/utils"