Merge remote-tracking branch 'origin/v5' into dev-mode/filtered-slugs

# Conflicts:
#	quartz/plugins/builtins/links.ts
This commit is contained in:
saberzero1 committed 2026-11-26 19:02:58 +01:00
commit c608817610
40 files changed
+1698 -71

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Experimental `extends` in `quartz.config.yaml`: `extends: default` (or a path) starts from `quartz.config.default.yaml` and applies only the changes in your file. `configuration` and `layout` merge key by key, plugin entries merge with the default entry of the same plugin. Configs without `extends` behave exactly as before.
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries have `dateFromFrontmatter: true` when their `date` is the one set in the page's frontmatter for the configured date type (not from git or the file system), so client-side components can tell explicit dates apart, e.g. for folder dates in the explorer.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries now include the page's `date` (the one `defaultDateType` selects) as an ISO 8601 string, so client-side components such as the explorer can sort by date. Pages without a date have no `date` field.
+6
View File
@@ -0,0 +1,6 @@
---
"@jackyzha0/quartz": patch
---
- `@quartz-community/graph` 1.0.7: the local graph on folder index pages shows the folder's connections instead of a single node.
- `@quartz-community/utils` 1.2.1: `unescapeHTML` decodes each entity once, so a page description that mentions `&lt;br&gt;` keeps it in the page's meta tags instead of turning it into `<br>`.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Layout conditions: add `is-index` (only on the home page) and `is-folder-index` (only on folder index pages), and let `not-<condition>` negate any condition, built-in or registered (`not-has-tags`, `not-has-backlinks`, …).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Release tags are verified on GitHub: the release workflow creates each `vX.Y.Z` tag as a lightweight tag on the merged release commit (which GitHub signs) instead of letting the release create an unsigned annotated tag. It also starts the Docker build for the tag, so versioned images (`5.3.0`, `5.3`) are published for each release (none were built for 5.1.0–5.2.2).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks and folder pages resolve to the stripped addresses; heading anchors and non-Latin scripts are unchanged. With `@quartz-community/utils` 1.3+ the option also reaches plugins that slug through utils (tag pages, canvas, bases, alias-redirects).
+11 -5
View File
@@ -21,6 +21,7 @@ jobs:
permissions:
contents: write
pull-requests: write
actions: write # start the Docker build for the new tag
steps:
- uses: actions/checkout@v7
with:
@@ -59,8 +60,13 @@ jobs:
echo "CHANGELOG.md has no section for $VERSION — not tagging."
exit 0
fi
# GitHub creates the tag, on the commit this push brought (the merged release PR). A tag
# made here with `git tag -a` is an unsigned tag object, which GitHub marks "Unverified"
# (jackyzha0/quartz#2455). This one points straight at the commit, which shows as verified
# because GitHub signs the commits it merges. `git describe --tags` sees it all the same.
gh release create "$TAG" --target "$GITHUB_SHA" --title "Quartz $VERSION" --notes-file release-notes.md
# The tag is a lightweight ref straight to the merged release commit, created here
# before the release. GitHub signs the commits it merges, so the tag shows as verified.
# Letting `gh release create` make the tag instead gives an unsigned annotated tag
# object (tagger: whoever merged the release PR), which GitHub marks "Unverified"
# (jackyzha0/quartz#2455). `git describe --tags` reads lightweight tags as well.
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
gh release create "$TAG" --verify-tag --title "Quartz $VERSION" --notes-file release-notes.md
# A tag created with GITHUB_TOKEN doesn't trigger `on: push: tags`, so the Docker workflow
# never built the versioned images; start it for the tag explicitly.
gh workflow run docker-build-push.yaml --ref "$TAG"
+3 -2
View File
@@ -556,10 +556,10 @@ export const MyFrame: PageFrame = {
`,
render({ componentData, pageBody: Content, footer: Footers }: PageFrameProps): unknown {
return (
<div class="center">
<main class="center">
{Content(componentData) as ComponentChildren}
{Footers.map((Footer) => Footer(componentData) as ComponentChildren)}
</div>
</main>
)
},
}
@@ -569,6 +569,7 @@ Key requirements:
- `name`: A unique string identifier. This is what page types and YAML config reference.
- `render()`: Receives all layout slots (header, sidebars, content, footer) and returns JSX for the inner page structure. Note that `footer` is a `QuartzComponent[]` (an array) — frames should iterate over it with `.map()` to render all footer components.
- Put the page's content in a `<main>` element (and sidebars in `<aside>`), as the built-in frames do, so screen readers can jump to it.
- `css` (optional): Frame-specific CSS. Scope it with `.page[data-frame="my-frame"]` selectors to avoid conflicts.
**2. Re-export the frame:**
+48
View File
@@ -23,6 +23,35 @@ layout:
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
## Extending the default configuration
Without a `quartz.config.yaml`, Quartz uses `quartz.config.default.yaml`. A `quartz.config.yaml` normally replaces it completely. With `extends`, your file can hold just the changes you make to another configuration instead:
```yaml title="quartz.config.yaml"
extends: default # quartz.config.default.yaml
configuration:
pageTitle: "My Site"
baseUrl: example.com
plugins:
- source: "@quartz-community/graph"
enabled: false # turn off a default plugin
- source: "@quartz-community/explorer"
options:
folderDefaultState: open # only this option changes
- source: github:me/my-plugin # a plugin the defaults don't have
enabled: true
```
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. Later entries in the list win.
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
> [!warning] Experimental
> `npx quartz plugin` commands that edit plugin entries (`enable`, `disable`, `config`, …) only see the entries in your own file so far. Edit an extending `quartz.config.yaml` by hand.
## General Configuration
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
@@ -54,6 +83,11 @@ This part of the configuration concerns anything that can affect the whole site.
- `"all"` (default): every file that isn't ignored.
- `"referenced"`: only files a published page links to or embeds. Use this with [[ExplicitPublish]] or [[private pages|drafts]], so that files only unpublished notes use stay private.
- Files that Quartz renders as pages themselves (e.g. `.base` and `.canvas` files) are never copied as raw assets.
- `slugs`: how file paths become URLs.
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
- Only combining accents (`á č é ů …`) are removed. Letters without a decomposition (`ø`, `ł`, `ß`, `æ`) and non-Latin scripts (Chinese, Japanese, Korean, Arabic, Devanagari, …) are kept as they are.
- Turning it on changes the URLs of existing pages; links shared elsewhere to the old addresses will 404 unless you add the old addresses as `aliases`.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `theme`: configure how the site looks.
- `fontOrigin`: where to load fonts from.
@@ -133,6 +167,20 @@ plugins:
Plugins are categorized by their type (transformer, filter, emitter, pageType) based on their manifest. The `order` field controls execution order within each category.
`before` and `after` name plugins that this one must run before or after (one name or a list; `obsidian-flavored-markdown`, `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` all work, as do the built-ins `frontmatter`, `links`, `drafts` and `contentIndex`). They never override `order`; they are checked against it:
```yaml title="quartz.config.yaml"
plugins:
- source: github:me/my-transformer
enabled: true
order: 45
after: obsidian-flavored-markdown # needs the links OFM creates
```
- Between plugins with the same `order`, `before`/`after` decide the order (otherwise the list order does).
- If `order` contradicts a constraint (here: OFM moved to order 50), the build stops with an error that names both orders, instead of silently running the plugins the wrong way round.
- A name that isn't in your config is an error. A plugin that is disabled, or runs in another category (a filter named by a transformer), is skipped: the constraint applies only where both plugins run.
> [!note]
> For advanced TS override of plugin configuration, you can modify `quartz.ts`:
>
+2
View File
@@ -15,4 +15,6 @@ Under the hood, this is done by hijacking page navigations and instead fetching
Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once; the fetched pages are also reused by [[popover previews]].
Back and Forward return to where you were on each page: the router keeps each history entry's scroll position and restores it after the page is swapped in, and a reload keeps it too. Links to a heading on the same page add a history entry and only scroll, so Back returns to where you clicked.
Redirects are followed: when a link is redirected (for example `folder` → `folder/` on static hosts, or an alias page to its canonical page), the address bar shows the final URL and relative links on the new page resolve against it.
+11 -6
View File
@@ -170,12 +170,17 @@ plugins:
Available built-in conditions:
| Condition | Description |
| --------------- | ----------------------------------------------------- |
| `not-index` | Only render when the page is not the root `index.md` |
| `has-tags` | Only render when the page has tags in its frontmatter |
| `has-backlinks` | Only render when the page has backlinks |
| `has-toc` | Only render when the page has a table of contents |
| Condition | Description |
| ----------------- | --------------------------------------------------------------------------- |
| `is-index` | Only render on the root `index.md` (the home page) |
| `not-index` | Only render when the page is not the root `index.md` |
| `is-folder-index` | Only render on a folder's index page (`folder/index.md` or a generated one) |
| `has-tags` | Only render when the page has tags in its frontmatter |
| `has-backlinks` | Only render when the page has backlinks |
| `has-toc` | Only render when the page has a table of contents |
| `not-<condition>` | Negates any other condition, e.g. `not-has-tags`, `not-has-backlinks` |
The `not-` prefix also works for conditions registered by plugins or in `quartz.ts`. To change the layout of a whole page type (folder pages, tag pages, …) rather than single pages, use `layout.byPageType` (see [[layout#Per-page-type overrides]]).
### TS Override
+9 -6
View File
@@ -132,12 +132,15 @@ plugins:
Available conditions:
| Condition | Effect |
| --------------- | ------------------------------------------------------------------------ |
| `not-index` | Hidden on the root index page, shown everywhere else |
| `has-tags` | Only shown on pages that have tags in frontmatter |
| `has-backlinks` | Only shown on pages that another (listed) page links to |
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
| Condition | Effect |
| ----------------- | ---------------------------------------------------------------------------- |
| `is-index` | Only shown on the root index page (the home page) |
| `not-index` | Hidden on the root index page, shown everywhere else |
| `is-folder-index` | Only shown on folder index pages (`folder/index.md` or a generated one) |
| `has-tags` | Only shown on pages that have tags in frontmatter |
| `has-backlinks` | Only shown on pages that another (listed) page links to |
| `has-toc` | Only shown on pages with a table of contents (needs `table-of-contents`) |
| `not-<condition>` | Negates any condition, built-in or registered: `not-has-tags`, `not-has-toc` |
Plugins can register additional conditions. An unknown condition name prints a warning at build time and the component is always shown.
+1
View File
@@ -63,6 +63,7 @@ With Quartz 5.1, `.base` pages follow the site's publish filters (e.g. [[Explici
This plugin accepts the following configuration options:
- `propertyLabels`: How column and property labels are shown. `"name"` (default) shows a property's name as Obsidian does (`priority`, `file name`); `"title"` title-cases it (`Priority`, `Name`). A property's `displayName` is always used.
- `defaultViewType`: Open a base on its first view of this type. Unset by default: a base opens on its first view, as in Obsidian.
- `linkResolution`: How to resolve internal links in view renderers. Should match `configuration.links.markdownLinkResolution` (built-in [[CrawlLinks|link processing]]). Can be `"absolute"`, `"relative"`, or `"shortest"`. Defaults to `"shortest"`.
- `customViews`: A map of custom view renderers. Keys are view type names. These override built-in renderers for the same type, or add new view types. Requires a TS override.
+4
View File
@@ -36,6 +36,10 @@ Options:
> [!note]
> An existing `@quartz-community/content-index` entry is applied to `configuration.contentIndex` automatically. Run `npx quartz plugin doctor --fix` to move it.
## `contentIndex.json`
Each entry of `static/contentIndex.json` is keyed by slug and holds `slug`, `filePath`, `title`, `links`, `tags` and `content` (the page's text), plus `date` when the page has one: the date selected by `defaultDateType` of [[CreatedModifiedDate]] (the same date [[ContentMeta]] shows and the RSS feed uses), as an ISO 8601 string such as `"2024-01-02T03:04:05.000Z"`. Client-side components can use it to sort by date, e.g. `new Date(entry.date)`. When that date is the one the page's frontmatter sets for the configured date type (e.g. `modified:` / `lastmod:` with `defaultDateType: modified`), rather than one from git or the file system, the entry also has `dateFromFrontmatter: true`; otherwise the field is absent.
## Adding fields
Plugins can add their own fields to each entry of `contentIndex.json` with `extendContentIndex` — see [[making plugins#Extending the content index]].
+1 -1
View File
@@ -22,7 +22,7 @@ This plugin accepts the following configuration options:
- `mathJaxOptions`: Additional options passed to the MathJax renderer. See the [MathJax docs](https://docs.mathjax.org/en/latest/options/) for available options.
- `typstOptions`: Additional options passed to the Typst renderer.
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr.
With KaTeX, the KaTeX stylesheet and its copy-tex script are loaded from jsDelivr. The stylesheet blocks rendering only on pages with math; elsewhere it loads in the background, ready for pages opened with SPA navigation.
### Default options
+1
View File
@@ -34,6 +34,7 @@ This plugin accepts the following configuration options:
- `enableVideoEmbed`: If `true` (default), enables the embedding of video files.
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content, including custom task characters (e.g. `- [?]`, `- [!]`, `- [/]`). Defaults to `false`; the default `quartz.config.yaml` turns it on.
- `enableObsidianUri`: If `true` (default), marks `obsidian://` protocol links with a CSS class and data attribute for custom styling.
- `blockWrappers`: If `true` (default), wraps each top-level block in the `div` Obsidian puts it in (`div.el-p > p`), which Obsidian themes space blocks with. No visible change without a theme.
- `foldHeadings`: If `true`, headings fold as in Obsidian's reading view ("Fold heading"): an arrow before each heading, shown on hover, hides everything up to the next heading of the same or a higher level. Defaults to `false`.
- `foldLists`: If `true`, list items with a sublist fold as in Obsidian's reading view ("Fold indent"): an arrow before the item, shown on hover, hides its sublist. Defaults to `false`.
+8 -8
View File
@@ -34,7 +34,7 @@
"@quartz-community/folder-page": "^1.1.1",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.1.2",
"@quartz-community/graph": "^1.0.6",
"@quartz-community/graph": "^1.0.7",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.1",
"@quartz-community/note-properties": "^1.2.0",
@@ -97,7 +97,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.2.0",
"@quartz-community/utils": "^1.2.1",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
@@ -2734,9 +2734,9 @@
}
},
"node_modules/@quartz-community/graph": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.6.tgz",
"integrity": "sha512-cZ7ymjZ0tyLA32ms92WVpUhcV4kGEYw5vivV4YaTwYFuu6YxuIn7YqlyUlqEAwcy6HvMgbLJZVX9O6vKpANn+A==",
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.7.tgz",
"integrity": "sha512-UEYxW5exKlAU5/P0Ixbf08iFxIoBzKRsFCJ4wCAcywGSNvW3uFnmhuSYin9ZQA1M3PUBnXxnMJR9JuP8x7F5yg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -3230,9 +3230,9 @@
}
},
"node_modules/@quartz-community/utils": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.2.0.tgz",
"integrity": "sha512-X32uBfhfNACQw2Ciw6F0XQ9qSoTMQeh78/2ZEj8cYuOk7VTowNf0dpjtSDKAxs1co6aSpIEcDZBIG6p953UPiQ==",
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.2.1.tgz",
"integrity": "sha512-VVz1ZG/scBbboDYMxz4WZOnh6sPBNUCMwdO2O3eUZK0qR4kP0FPtTfWnrivNrdIacktZReihnPTiGcx78VuDvw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
+2 -2
View File
@@ -64,7 +64,7 @@
"@quartz-community/folder-page": "^1.1.1",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.1.2",
"@quartz-community/graph": "^1.0.6",
"@quartz-community/graph": "^1.0.7",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.1",
"@quartz-community/note-properties": "^1.2.0",
@@ -124,7 +124,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.2.0",
"@quartz-community/utils": "^1.2.1",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
+10
View File
@@ -109,6 +109,16 @@ export interface GlobalConfiguration {
* - "referenced": Only copy assets referenced by published pages
*/
publishAssets?: "all" | "referenced"
/** How file paths become URLs. */
slugs?: SlugsConfig
}
export interface SlugsConfig {
/**
* Strip accents and other diacritics from generated slugs (`české/čeština.md` →
* `ceske/cestina`), aliases and permalinks; links are resolved the same way. Off by default.
*/
stripDiacritics?: boolean
}
/** Shared by every built-in: `enabled: false` turns it off (e.g. to replace it with a plugin). */
+9 -1
View File
@@ -5,7 +5,15 @@
// see plugin-validation.d.ts).
/** Top-level keys allowed on a plugin entry (mirrors quartz-plugins.schema.json). */
export const PLUGIN_ENTRY_KEYS = ["source", "enabled", "options", "order", "layout"]
export const PLUGIN_ENTRY_KEYS = [
"source",
"enabled",
"options",
"order",
"before",
"after",
"layout",
]
/** Keys allowed on an object-form `source`. */
export const SOURCE_OBJECT_KEYS = ["repo", "subdir", "ref", "name"]
+90 -1
View File
@@ -34,7 +34,8 @@ import {
import type { PluginJsonEntry } from "../loader/types"
import type { BuildCtx } from "../../util/ctx"
import type { ContentDetails } from "../types"
import type { FullSlug } from "../../util/path"
import type { FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions } from "../../util/path"
import type { ProcessedContent } from "../vfile"
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
@@ -365,6 +366,43 @@ describe("links built-in", () => {
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
})
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
setSlugOptions({ stripDiacritics: true })
try {
const img: Element = {
type: "element",
tagName: "img",
properties: { src: "obr%C3%A1zek.png" },
children: [],
}
const { els, file } = run(
[a("./%C4%8Ce%C5%A1tina#%C4%8Cesk%C3%BD-nadpis", "Čeština"), a("Příliš"), img],
"ceske/page",
{ markdownLinkResolution: "shortest" },
["ceske/page", "ceske/cestina", "jine/prilis", "ceske/obrazek.png"],
)
const [cestina, prilis] = els.filter((e) => e.tagName === "a")
assert.strictEqual(cestina.properties.href, "../ceske/cestina#český-nadpis")
assert.ok(!(cestina.properties.className as string[]).includes("broken"))
assert.strictEqual(prilis.properties.href, "../jine/prilis")
assert.strictEqual(
els.find((e) => e.tagName === "img")!.properties.src,
"../ceske/obrazek.png",
)
assert.ok(file.data.links?.includes("ceske/cestina" as SimpleSlug))
} finally {
setSlugOptions(undefined)
}
})
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
"page",
"jine/příliš",
])
assert.strictEqual(els[0].properties.href, "./jine/příliš")
})
test("footnote anchors stay internal without Obsidian's note-link class", () => {
const fn = (props: Record<string, unknown>): Element => ({
type: "element",
@@ -554,6 +592,57 @@ describe("content index built-in", () => {
])
})
test("writes the page date to contentIndex.json as an ISO string (explorer#5)", () => {
const created = new Date("2024-01-02T03:04:05.000Z")
const modified = new Date("2025-06-07T08:09:10.000Z")
const dated = page("dated", { defaultDateType: "created", dates: { created, modified } })
const idx = buildContentIndex(ctxWith([]), [dated, page("undated")])
const json = JSON.parse(serializeContentIndex(idx))
assert.strictEqual(json.dated.date, "2024-01-02T03:04:05.000Z")
assert.ok(!("description" in json.dated))
// pages without a date keep the build-time stand-in for RSS, but not in the JSON
assert.ok(idx.get("undated" as FullSlug)!.date instanceof Date)
assert.ok(!("date" in json.undated))
})
test("dateFromFrontmatter marks dates set in frontmatter for the configured type", () => {
const fmModified = new Date("2024-03-04T00:00:00") // local midnight, like the date plugin
const gitModified = new Date("2025-01-01T10:00:00.000Z")
const created = new Date("2020-01-01T00:00:00.000Z")
const fromFm = page("fm", {
defaultDateType: "modified",
frontmatter: { title: "FM", modified: "2024-03-04" },
dates: { created, modified: fmModified },
})
const fromGit = page("git", {
defaultDateType: "modified",
frontmatter: { title: "GIT", created: "2020-01-01T00:00:00.000Z" },
dates: { created, modified: gitModified },
})
// frontmatter has a date, but for another type than the configured one
const otherType = page("other", {
defaultDateType: "created",
frontmatter: { title: "O", modified: "2024-03-04" },
dates: { created: gitModified, modified: fmModified },
})
// frontmatter value lost to a higher-priority source (date differs)
const overridden = page("over", {
defaultDateType: "modified",
frontmatter: { title: "OV", modified: "2023-01-01" },
dates: { created, modified: gitModified },
})
const json = JSON.parse(
serializeContentIndex(
buildContentIndex(ctxWith([]), [fromFm, fromGit, otherType, overridden, page("undated")]),
),
)
assert.strictEqual(json.fm.dateFromFrontmatter, true)
assert.strictEqual(json.fm.date, fmModified.toISOString())
for (const slug of ["git", "other", "over", "undated"]) {
assert.ok(!("dateFromFrontmatter" in json[slug]), slug)
}
})
test("plugins add fields through extendContentIndex", () => {
const ctx = ctxWith([
{
+63 -6
View File
@@ -53,6 +53,7 @@ export const CORE_CONTENT_INDEX_FIELDS = new Set([
"content",
"richContent",
"date",
"dateFromFrontmatter",
"description",
])
@@ -150,6 +151,50 @@ export function prepareContentIndex(ctx: BuildCtx, content: ProcessedContent[]):
return index
}
/**
* Pages without a date get the build time, so RSS and the sitemap keep working as before.
* Those stand-in dates are remembered here and not written to contentIndex.json, where a
* build-time date would look like a real one to client-side sorting (explorer, recent notes).
*/
const buildTimeDates = new WeakSet<Date>()
function buildTimeDate(): Date {
const date = new Date()
buildTimeDates.add(date)
return date
}
function entryDate(data: QuartzPluginData): Date {
const date = getDate(data as Parameters<typeof getDate>[0])
if (!date) return buildTimeDate()
if (dateIsFromFrontmatter(data, date)) frontmatterDates.add(date)
return date
}
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
/**
* Whether the page's `date` is the one its frontmatter sets for the configured date type
* (`defaultDateType`: created / modified / published, after the frontmatter built-in's
* aliases such as `date` or `lastmod`), rather than one from git or the file system. Compared
* by value, so it holds whatever `priority` the date plugin uses. Date-only values
* (`2024-01-02`) are local midnight, as the date plugin reads them.
*/
export function dateIsFromFrontmatter(data: QuartzPluginData, date: Date | undefined): boolean {
if (!(date instanceof Date) || isNaN(date.getTime())) return false
const type = data.defaultDateType as string | undefined
const frontmatter = data.frontmatter as Record<string, unknown> | undefined
if (!type || !frontmatter) return false
let raw = frontmatter[type]
if (raw === undefined || raw === null || raw === "") return false
if (typeof raw === "string" && DATE_ONLY.test(raw)) raw = `${raw}T00:00:00`
if (!(raw instanceof Date) && typeof raw !== "string" && typeof raw !== "number") return false
const fromFrontmatter = new Date(raw)
return !isNaN(fromFrontmatter.getTime()) && fromFrontmatter.getTime() === date.getTime()
}
/** Pages whose date came from frontmatter (see dateIsFromFrontmatter). */
const frontmatterDates = new WeakSet<Date>()
/** Build the index from processed content (also used by tests and potentially other emitters). */
export function buildContentIndex(
ctx: BuildCtx,
@@ -176,7 +221,7 @@ export function buildContentIndex(
options.rssFullHtml && data.encrypted !== true
? escapeHTML(toHtml(tree as Root, { allowDangerousHtml: true }))
: undefined,
date: getDate(data as Parameters<typeof getDate>[0]) ?? new Date(),
date: entryDate(data),
description: (data.description as string | undefined) ?? "",
}
index.set(slug, applyContentIndexExtensions(ctx, extensions, entry, data))
@@ -240,13 +285,25 @@ function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?:
</rss>`
}
/** Entries as written to contentIndex.json (date and description are RSS/sitemap-only). */
/**
* Entries as written to contentIndex.json. `date` is the page's date (the one
* `defaultDateType` selects, as shown by ContentMeta and used by RSS) as an ISO 8601 string,
* left out for pages without a date. `dateFromFrontmatter: true` is added when that date is the
* one the page's frontmatter sets for the date type (absent otherwise). `description` is
* RSS-only.
*/
export function serializeContentIndex(idx: ContentIndexMap): string {
const simplified = Object.fromEntries(
Array.from(idx).map(([slug, { date: _date, description: _description, ...rest }]) => [
slug,
rest,
]),
Array.from(idx).map(([slug, { date, description: _description, ...rest }]) => {
const hasDate = date instanceof Date && !isNaN(date.getTime()) && !buildTimeDates.has(date)
if (!hasDate) return [slug, rest]
return [
slug,
frontmatterDates.has(date)
? { ...rest, date: date.toISOString(), dateFromFrontmatter: true }
: { ...rest, date: date.toISOString() },
]
}),
)
return JSON.stringify(simplified)
}
+25 -1
View File
@@ -15,6 +15,8 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -152,6 +154,28 @@ export function markLinksToRemovedPages(
/** The Links instance marks links to removed pages after filtering (see build.ts). */
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
* so the path part of the target is stripped the same way before it is resolved (wikilinks
* from obsidian-flavored-markdown are slugged with the plain rules first). The `#anchor` is
* left alone: heading ids keep their diacritics.
*/
function slugOptionsOnLinkPath(raw: string): string {
if (!getSlugOptions().stripDiacritics) return raw
const hash = raw.indexOf("#")
const linkPath = hash === -1 ? raw : raw.slice(0, hash)
const anchor = hash === -1 ? "" : raw.slice(hash)
let decoded = linkPath
try {
decoded = decodeURI(linkPath)
} catch {
// not percent-encoded (or malformed): strip as written
}
const stripped = applySlugOptions(decoded)
return stripped === decoded ? raw : stripped + anchor
}
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
const instance: LinksInstance = {
@@ -178,7 +202,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, raw, transformOptions)
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
+59 -1
View File
@@ -1,6 +1,6 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { getCondition, hasBacklinks } from "./conditions"
import { getCondition, hasBacklinks, registerCondition } from "./conditions"
import type { QuartzComponentProps } from "../../components/types"
type Props = Pick<QuartzComponentProps, "fileData" | "allFiles">
@@ -51,3 +51,61 @@ describe("has-backlinks condition", () => {
assert.strictEqual(hasBacklinks({ fileData: { slug: "a" } } as unknown as Props), false)
})
})
describe("index conditions (#2465)", () => {
const run = (name: string, slug: string | undefined) =>
getCondition(name)!({ fileData: { slug }, allFiles: [] } as unknown as QuartzComponentProps)
test("is-index is true only on the root index page", () => {
assert.strictEqual(run("is-index", "index"), true)
assert.strictEqual(run("is-index", "folder/index"), false)
assert.strictEqual(run("is-index", "page"), false)
assert.strictEqual(run("is-index", undefined), false)
})
test("is-index and not-index are complements", () => {
for (const slug of ["index", "folder/index", "a/b", undefined]) {
assert.strictEqual(run("is-index", slug), !run("not-index", slug))
}
})
test("is-folder-index matches folder index pages, not the root index", () => {
assert.strictEqual(run("is-folder-index", "folder/index"), true)
assert.strictEqual(run("is-folder-index", "a/b/index"), true)
assert.strictEqual(run("is-folder-index", "index"), false)
assert.strictEqual(run("is-folder-index", "folder/indexes"), false)
assert.strictEqual(run("is-folder-index", undefined), false)
})
})
describe("not-<condition> negation", () => {
const withTags = { fileData: { slug: "a", frontmatter: { tags: ["x"] } }, allFiles: [] }
const noTags = { fileData: { slug: "a", frontmatter: {} }, allFiles: [] }
const call = (name: string, p: unknown) => getCondition(name)!(p as QuartzComponentProps)
test("not-has-tags negates has-tags", () => {
assert.strictEqual(call("not-has-tags", withTags), false)
assert.strictEqual(call("not-has-tags", noTags), true)
})
test("negates custom conditions too", () => {
registerCondition("is-draft-test", (p) => p.fileData.slug === "draft")
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "draft" } }), false)
assert.strictEqual(call("not-is-draft-test", { fileData: { slug: "x" } }), true)
})
test("an exact name wins over negation (not-index is its own built-in)", () => {
assert.strictEqual(call("not-index", { fileData: { slug: "index" } }), false)
assert.strictEqual(call("not-index", { fileData: { slug: "a" } }), true)
})
test("unknown names stay unknown", () => {
assert.strictEqual(getCondition("not-nonexistent"), undefined)
assert.strictEqual(getCondition("not-"), undefined)
assert.strictEqual(getCondition("nonexistent"), undefined)
})
test("double negation works", () => {
assert.strictEqual(call("not-not-has-tags", withTags), true)
})
})
+20 -1
View File
@@ -4,7 +4,13 @@ import { FullSlug, simplifySlug } from "../../util/path"
export type ConditionPredicate = (props: QuartzComponentProps) => boolean
const builtinConditions: Record<string, ConditionPredicate> = {
"is-index": (props) => props.fileData.slug === "index",
"not-index": (props) => props.fileData.slug !== "index",
// A folder's index page: `folder/index.md` or a generated folder page, not the root index.
"is-folder-index": (props) => {
const slug = props.fileData.slug
return typeof slug === "string" && slug.endsWith("/index")
},
"has-tags": (props) => {
const tags = props.fileData.frontmatter?.tags
return Array.isArray(tags) && tags.length > 0
@@ -36,8 +42,21 @@ export function registerCondition(name: string, predicate: ConditionPredicate):
customConditions.set(name, predicate)
}
const NEGATION_PREFIX = "not-"
/**
* Look up a condition. Besides the registered names, `not-<name>` negates any other
* condition (`not-has-tags`, `not-is-folder-index`, a custom `not-<custom>`), unless a
* condition with that exact name exists (`not-index` is its own built-in).
*/
export function getCondition(name: string): ConditionPredicate | undefined {
return customConditions.get(name) ?? builtinConditions[name]
const direct = customConditions.get(name) ?? builtinConditions[name]
if (direct) return direct
if (name.startsWith(NEGATION_PREFIX)) {
const inner = getCondition(name.slice(NEGATION_PREFIX.length))
if (inner) return (props) => !inner(props)
}
return undefined
}
export function getAllConditionNames(): string[] {
@@ -0,0 +1,377 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import path from "path"
import fs from "fs"
import YAML from "yaml"
import {
ConfigExtendsError,
deepMerge,
mergeQuartzConfigs,
pluginMatchKey,
resolveExtends,
resolveTarget,
fetchRemoteConfig,
} from "./config-extends"
import os from "os"
import type { QuartzPluginsJson } from "./types"
const base = (): QuartzPluginsJson => ({
configuration: {
pageTitle: "Quartz",
ignorePatterns: ["private", ".obsidian"],
theme: { typography: { header: "Schibsted Grotesk", body: "Source Sans Pro" } },
links: { markdownLinkResolution: "shortest" },
},
plugins: [
{ source: "@quartz-community/explorer", enabled: true, options: { a: 1, nested: { x: 1 } } },
{
source: "github:quartz-community/graph",
enabled: true,
order: 50,
layout: { position: "right", priority: 10 },
},
{ source: "@quartz-community/comments", enabled: false },
],
layout: { byPageType: { folder: { exclude: ["graph"] } } },
})
describe("deepMerge", () => {
test("objects merge, other values replace, null deletes", () => {
assert.deepStrictEqual(
deepMerge({ a: { b: 1, c: 2 }, l: [1, 2], k: 1 }, { a: { c: 3 }, l: [9], k: null }),
{
a: { b: 1, c: 3 },
l: [9],
},
)
})
test("does not modify its inputs", () => {
const b = { a: { b: 1 } }
deepMerge(b, { a: { b: 2 } })
assert.deepStrictEqual(b, { a: { b: 1 } })
})
})
describe("pluginMatchKey", () => {
test("npm, GitHub, git URL and local sources of one plugin match", () => {
for (const source of [
"@quartz-community/explorer",
"@quartz-community/explorer@^2.0.0",
"github:quartz-community/explorer",
"github:someone/explorer#v2",
"git+https://github.com/quartz-community/explorer.git",
"https://github.com/quartz-community/explorer",
"./plugins/explorer/",
"explorer",
{ repo: "github:quartz-community/plugins", subdir: "x", name: "explorer" },
]) {
assert.strictEqual(pluginMatchKey(source as never), "explorer", JSON.stringify(source))
}
})
})
describe("mergeQuartzConfigs", () => {
test("configuration deep-merges; arrays replace; null resets a key", () => {
const merged = mergeQuartzConfigs(base(), {
configuration: {
pageTitle: "My garden",
ignorePatterns: ["drafts"],
theme: { typography: { header: "Inter" } },
links: null,
},
})
assert.strictEqual(merged.configuration.pageTitle, "My garden")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["drafts"])
assert.deepStrictEqual(merged.configuration.theme, {
typography: { header: "Inter", body: "Source Sans Pro" },
})
assert.ok(!("links" in merged.configuration))
// the base plugins are kept when the overlay lists none
assert.strictEqual(merged.plugins.length, 3)
})
test("plugins match by name; enabled/order/source replace, options/layout merge", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{
source: "github:quartz-community/explorer",
options: { b: 2, nested: { y: 2 } },
} as never,
{ source: "@quartz-community/graph", enabled: false, order: 10, layout: { priority: 1 } },
{ source: "@quartz-community/comments", enabled: true },
],
})
const [explorer, graph, comments] = merged.plugins
assert.strictEqual(explorer.source, "github:quartz-community/explorer")
assert.strictEqual(explorer.enabled, true)
assert.deepStrictEqual(explorer.options, { a: 1, b: 2, nested: { x: 1, y: 2 } })
assert.strictEqual(graph.enabled, false)
assert.strictEqual(graph.order, 10)
assert.deepStrictEqual(graph.layout, { position: "right", priority: 1 })
assert.strictEqual(comments.enabled, true)
assert.strictEqual(merged.plugins.length, 3)
})
test("new plugins are appended as written (no enabled → disabled, as in a full config)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "github:me/my-plugin", enabled: true, order: 70 },
{ source: "github:me/other" },
],
})
assert.strictEqual(merged.plugins.length, 5)
assert.deepStrictEqual(merged.plugins[3], {
source: "github:me/my-plugin",
enabled: true,
order: 70,
})
assert.deepStrictEqual(merged.plugins[4], { source: "github:me/other" })
})
test("null removes a plugin's options, layout or order (back to the plugin's defaults)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "@quartz-community/graph", layout: null, order: null } as never,
{ source: "@quartz-community/explorer", options: { nested: null } } as never,
],
})
const [explorer, graph] = merged.plugins
assert.ok(!("layout" in graph) && !("order" in graph))
assert.deepStrictEqual(explorer.options, { a: 1 })
})
test("layout merges; arrays like byPageType.*.exclude replace", () => {
const merged = mergeQuartzConfigs(base(), {
layout: { byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } } },
})
assert.deepStrictEqual(merged.layout, {
byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } },
})
})
test("does not modify the base", () => {
const b = base()
const before = JSON.stringify(b)
mergeQuartzConfigs(b, {
configuration: { pageTitle: "x" },
plugins: [{ source: "@quartz-community/explorer", options: { a: 2 } } as never],
})
assert.strictEqual(JSON.stringify(b), before)
})
test("a plugin entry without source is an error", () => {
assert.throws(
() => mergeQuartzConfigs(base(), { plugins: [{ enabled: false } as never] }),
ConfigExtendsError,
)
})
})
describe("resolveExtends", () => {
const files: Record<string, string> = {}
const root = path.resolve("/site")
const readFile = (f: string) => {
const content = files[path.resolve(f)]
if (content === undefined) throw new Error("ENOENT")
return content
}
const put = (rel: string, data: unknown) => {
files[path.join(root, rel)] = YAML.stringify(data)
}
put("quartz.config.default.yaml", base())
test("a config without extends is returned as is", async () => {
const data = { configuration: { pageTitle: "x" }, plugins: [] }
assert.strictEqual(
await resolveExtends(data, path.join(root, "quartz.config.yaml")),
data as never,
)
})
test("extends: default merges onto quartz.config.default.yaml", async () => {
const merged = await resolveExtends(
{
extends: "default",
configuration: { pageTitle: "Mine" },
plugins: [{ source: "@quartz-community/graph", enabled: false }],
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Mine")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["private", ".obsidian"])
assert.strictEqual(
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
false,
)
assert.ok(!("extends" in merged))
})
test("relative paths, chains and lists (later wins)", async () => {
put("configs/team.yaml", {
extends: "default",
configuration: { pageTitle: "Team", locale: "cs-CZ" },
})
put("configs/dark.yaml", { configuration: { pageTitle: "Dark" } })
const merged = await resolveExtends(
{
extends: ["./configs/team.yaml", "configs/dark.yaml"],
configuration: { baseUrl: "x.org" },
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Dark")
assert.strictEqual(merged.configuration.locale, "cs-CZ")
assert.strictEqual(merged.configuration.baseUrl, "x.org")
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
})
test("cycles and missing files are reported", async () => {
put("a.yaml", { extends: "./b.yaml" })
put("b.yaml", { extends: "./a.yaml" })
await assert.rejects(
() =>
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/cycle/,
)
await assert.rejects(
() =>
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/not found/,
)
await assert.rejects(
() =>
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
ConfigExtendsError,
)
})
test("extends: default reproduces the shipped default config exactly", async () => {
const defaultFile = path.resolve("quartz.config.default.yaml")
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
const merged = await resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
assert.deepStrictEqual(merged, shipped)
})
describe("https bases", () => {
const remote: Record<string, string> = {
"https://cfg.example/base/site.yaml": YAML.stringify({
extends: "./common.yaml",
configuration: { pageTitle: "Remote" },
}),
"https://cfg.example/base/common.yaml": YAML.stringify({
extends: "default",
configuration: { locale: "de-DE" },
}),
}
const fetchRemote = async (url: string) => {
if (!(url in remote)) throw new ConfigExtendsError(`404 ${url}`)
return remote[url]
}
const opts = () => ({ quartzRoot: root, readFile, fetchRemote })
test("a URL base; its relative extends resolve against the URL; default stays local", async () => {
const merged = await resolveExtends(
{ extends: "https://cfg.example/base/site.yaml", configuration: { baseUrl: "me.org" } },
path.join(root, "quartz.config.yaml"),
opts(),
)
assert.strictEqual(merged.configuration.pageTitle, "Remote")
assert.strictEqual(merged.configuration.locale, "de-DE")
assert.strictEqual(merged.configuration.baseUrl, "me.org")
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
})
test("only https", async () => {
await assert.rejects(
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
/only https/,
)
assert.strictEqual(
resolveTarget("../other.yaml", "https://cfg.example/base/site.yaml", root),
"https://cfg.example/other.yaml",
)
})
})
})
describe("fetchRemoteConfig", () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
const ok = (body: string) =>
(async () => new Response(body, { status: 200 })) as unknown as typeof fetch
const failing = (async () => {
throw new Error("getaddrinfo ENOTFOUND")
}) as unknown as typeof fetch
test("caches a fetched copy and falls back to it when offline or failing", async () => {
const cacheDir = tmp()
const url = "https://cfg.example/a.yaml"
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
"a: 1\n",
)
// memoised per process: a second call does not fetch again
assert.strictEqual(
await fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
"a: 1\n",
)
const warnings: string[] = []
const other = tmp()
fs.cpSync(cacheDir, other, { recursive: true })
assert.strictEqual(
await fetchRemoteConfig(url, {
cacheDir: other,
fetchImpl: failing,
offline: false,
warn: (m) => warnings.push(m),
}),
"a: 1\n",
)
assert.match(warnings[0], /using the cached copy/)
// offline (QUARTZ_EXTENDS_OFFLINE=1, worker threads): the cache only
assert.strictEqual(
await fetchRemoteConfig("https://cfg.example/a.yaml?x", {
cacheDir: other,
offline: true,
}).catch((e: Error) => e.message),
`"extends: https://cfg.example/a.yaml?x": no cached copy in ${other} (offline build). Build once online first.`,
)
})
test("without a cached copy a failed fetch stops the build", async () => {
await assert.rejects(
fetchRemoteConfig("https://cfg.example/b.yaml", {
cacheDir: tmp(),
fetchImpl: failing,
offline: false,
}),
/could not be fetched: getaddrinfo ENOTFOUND/,
)
await assert.rejects(
fetchRemoteConfig("https://cfg.example/c.yaml", { cacheDir: tmp(), offline: true }),
/no cached copy/,
)
})
test("HTTP errors are failures, too", async () => {
const notFound = (async () => new Response("nope", { status: 404 })) as unknown as typeof fetch
await assert.rejects(
fetchRemoteConfig("https://cfg.example/d.yaml", {
cacheDir: tmp(),
fetchImpl: notFound,
offline: false,
}),
/HTTP 404/,
)
})
})
+358
View File
@@ -0,0 +1,358 @@
import fs from "fs"
import path from "path"
import { createHash } from "crypto"
import { isMainThread } from "worker_threads"
import YAML from "yaml"
import type {
PluginJsonEntry,
PluginLayoutDeclaration,
PluginSource,
QuartzPluginsJson,
} from "./types"
/**
* `extends:` in quartz.config.yaml (#2440): start from another config and apply only the
* differences on top.
*
* ```yaml
* extends: default # quartz.config.default.yaml next to quartz.config.yaml's Quartz
* configuration:
* pageTitle: My garden
* plugins:
* - source: "@quartz-community/explorer"
* options: { folderDefaultState: open }
* - source: "@quartz-community/graph"
* enabled: false
* ```
*
* Merge rules (`mergeQuartzConfigs`):
* - `configuration` and `layout`: objects merge key by key, recursively; any other value
* (strings, numbers, arrays such as `ignorePatterns` or `byPageType.*.exclude`) replaces the
* base value; `null` removes the key (back to the built-in default).
* - `plugins`: an entry matches the base entry of the same plugin (by plugin name, so
* `github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the
* same name replaces the original). Of a matched entry, `source`, `enabled` and `order`
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
* tie-break between plugins with the same `order`.
* - A config without `extends` is used exactly as written, as before.
*/
/** The name `extends: default` stands for. */
export const DEFAULT_EXTENDS = "default"
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
/** A configuration mistake: reported by its message alone (no stack trace). */
export class ConfigExtendsError extends Error {
constructor(message: string) {
super(message)
this.name = "ConfigExtendsError"
this.stack = `${this.name}: ${message}`
}
}
type PlainObject = Record<string, unknown>
/** A plugin entry in a config that extends another: only `source` is required. */
export interface PluginOverlayEntry {
source: PluginSource
enabled?: boolean
/** Merged into the base entry's options; `null` drops them (the plugin's defaults apply). */
options?: Record<string, unknown> | null
order?: number | null
/** Replace the base entry's constraints; `null` removes them. */
before?: string | string[] | null
after?: string | string[] | null
/** Merged into the base entry's layout; `null` drops it (the plugin's default placement). */
layout?: Partial<PluginLayoutDeclaration> | null
}
/** What a config with `extends` may contain: any part of a full config. */
export interface QuartzConfigOverlay {
$schema?: string
extends?: string | string[] | null
configuration?: Record<string, unknown>
plugins?: PluginOverlayEntry[]
layout?: Record<string, unknown>
}
function isPlainObject(value: unknown): value is PlainObject {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
/** Recursive merge: objects merge, everything else replaces, `null` deletes. */
export function deepMerge(base: unknown, overlay: unknown): unknown {
if (overlay === undefined) return base
if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay
const result: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === null) {
delete result[key]
} else {
result[key] = deepMerge(base[key], value)
}
}
return result
}
/**
* The name a plugin entry is matched by: the last path segment of its package or repository
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
* `explorer`), or the `name` of an object source.
*/
export function pluginMatchKey(source: PluginSource): string {
if (typeof source === "object" && source !== null) {
if (source.name) return source.name
return pluginMatchKey(source.repo)
}
let s = String(source).trim()
s = s.replace(/^git\+/, "").replace(/^github:/, "")
s = s.split("#")[0]
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
// an npm version/range: @scope/name@1.2.3, name@^1
s = s.replace(/(.)@[^/]*$/, "$1")
return s.slice(s.lastIndexOf("/") + 1)
}
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
const merged: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === undefined) continue
if (key === "options" || key === "layout") {
const next = value === null ? undefined : deepMerge(merged[key], value)
if (next === undefined) delete merged[key]
else merged[key] = next
} else if (value === null) {
delete merged[key]
} else {
merged[key] = value
}
}
return merged as unknown as PluginJsonEntry
}
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
export function mergeQuartzConfigs(
base: QuartzPluginsJson,
overlay: QuartzConfigOverlay,
): QuartzPluginsJson {
const { extends: _extends, plugins: overlayPlugins, ...rest } = overlay
const merged = deepMerge(
{ ...base, plugins: undefined },
{ ...rest, plugins: undefined },
) as QuartzPluginsJson
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
for (const entry of overlayPlugins ?? []) {
if (!entry || entry.source === undefined) {
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
}
const key = pluginMatchKey(entry.source)
const index = plugins.findIndex((p) => pluginMatchKey(p.source) === key)
if (index === -1) {
// a new plugin, read like an entry of a full config (no `enabled` → disabled, with a warning)
plugins.push({ ...entry } as PluginJsonEntry)
} else {
plugins[index] = mergePluginEntry(plugins[index], entry)
}
}
merged.plugins = plugins
merged.configuration = (merged.configuration ?? {}) as QuartzPluginsJson["configuration"]
return merged
}
export interface ResolveExtendsOptions {
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
quartzRoot?: string
/** Local file reader, for tests. */
readFile?: (file: string) => string
/** Loader for `https://` bases; default `fetchRemoteConfig` (cached, with a timeout). */
fetchRemote?: (url: string) => Promise<string>
}
/** Where fetched remote bases are kept (offline builds, worker threads). */
export const REMOTE_CACHE_DIR = path.join(".quartz-cache", "extends")
const REMOTE_TIMEOUT_MS = 10_000
const REMOTE_MAX_BYTES = 1024 * 1024
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
function remoteCacheFile(url: string, cacheDir: string): string {
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
}
export interface FetchRemoteOptions {
cacheDir?: string
timeoutMs?: number
/** Only use the cache (QUARTZ_EXTENDS_OFFLINE=1; always in worker threads). */
offline?: boolean
fetchImpl?: typeof fetch
warn?: (message: string) => void
}
const fetched = new Map<string, Promise<string>>()
/**
* Fetch a remote base config: once per process, with a timeout and a size limit. A successful
* fetch is cached in `.quartz-cache/extends/`; when the fetch fails (offline, timeout, HTTP
* error) the cached copy is used with a warning, and without one the build stops. Worker threads
* and `QUARTZ_EXTENDS_OFFLINE=1` read only the cache, so every thread of a build sees the copy
* the main thread fetched.
*/
export function fetchRemoteConfig(url: string, opts: FetchRemoteOptions = {}): Promise<string> {
const cacheDir = opts.cacheDir ?? path.join(process.cwd(), REMOTE_CACHE_DIR)
const key = `${cacheDir}\0${url}`
let pending = fetched.get(key)
if (!pending) {
pending = fetchUncached(url, cacheDir, opts)
fetched.set(key, pending)
pending.catch(() => fetched.delete(key))
}
return pending
}
async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOptions) {
const cacheFile = remoteCacheFile(url, cacheDir)
const cached = () => {
try {
return fs.readFileSync(cacheFile, "utf-8")
} catch {
return undefined
}
}
const offline = opts.offline ?? (process.env.QUARTZ_EXTENDS_OFFLINE === "1" || !isMainThread)
if (offline) {
const copy = cached()
if (copy !== undefined) return copy
throw new ConfigExtendsError(
`"extends: ${url}": no cached copy in ${cacheDir} (offline build). Build once online first.`,
)
}
const warn = opts.warn ?? ((m: string) => console.warn(`⚠ ${m}`))
let failure: string
try {
const res = await (opts.fetchImpl ?? fetch)(url, {
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
headers: { accept: "application/yaml, application/json, text/plain, */*" },
})
if (res.url && !res.url.startsWith("https://")) {
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
}
if (!res.ok) {
failure = `HTTP ${res.status}`
} else {
const text = await res.text()
if (Buffer.byteLength(text) > REMOTE_MAX_BYTES) {
throw new ConfigExtendsError(`"extends: ${url}" is larger than 1 MB`)
}
fs.mkdirSync(cacheDir, { recursive: true })
fs.writeFileSync(cacheFile, text)
return text
}
} catch (err) {
if (err instanceof ConfigExtendsError) throw err
failure = err instanceof Error ? err.message : String(err)
}
const copy = cached()
if (copy !== undefined) {
warn(`"extends: ${url}" could not be fetched (${failure}); using the cached copy.`)
return copy
}
throw new ConfigExtendsError(`"extends: ${url}" could not be fetched: ${failure}`)
}
function parseConfigFile(file: string, raw: string): PlainObject {
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
if (!isPlainObject(data)) {
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
}
return data
}
function extendsTargets(value: unknown, file: string): string[] {
const list = Array.isArray(value) ? value : [value]
for (const item of list) {
if (typeof item !== "string" || item.trim() === "") {
throw new ConfigExtendsError(
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, an https:// URL, or a list of them`,
)
}
}
return list as string[]
}
/**
* Where an `extends` target points, seen from the file (or URL) that names it: `default` is
* the local quartz.config.default.yaml; a URL is used as is; a relative path is resolved
* against the extending file's directory, or against its URL when that file was fetched (a
* remote config cannot reach local files). Only https URLs are allowed. (A future
* `npm:<package>` target would be one more case here.)
*/
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
const resolved = isUrl(target)
? target
: isUrl(from)
? new URL(target, from).href
: path.resolve(path.dirname(from), target)
if (isUrl(resolved) && !resolved.startsWith("https://")) {
throw new ConfigExtendsError(
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
)
}
return resolved
}
/**
* Apply `extends` of `data` (read from `file`, a path or URL): load each base (recursively;
* later entries of an `extends` list win), then merge `data` on top. Returns `data` itself
* when it has no `extends`, so configs without it behave exactly as before.
*/
export async function resolveExtends(
data: PlainObject,
file: string,
options: ResolveExtendsOptions = {},
seen: string[] = [],
): Promise<QuartzPluginsJson> {
if (data.extends === undefined || data.extends === null) {
const { extends: _drop, ...rest } = data
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
}
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
const fetchRemote = options.fetchRemote ?? ((url: string) => fetchRemoteConfig(url))
const quartzRoot = options.quartzRoot ?? process.cwd()
const self = isUrl(file) ? file : path.resolve(file)
const chain = [...seen, self]
let base: QuartzPluginsJson | undefined
for (const target of extendsTargets(data.extends, file)) {
const targetFile = resolveTarget(target, file, quartzRoot)
if (chain.includes(targetFile)) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...chain, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
)
}
let raw: string
if (isUrl(targetFile)) {
raw = await fetchRemote(targetFile)
} else {
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
}
}
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
let parsed: PlainObject
try {
parsed = parseConfigFile(parsePath, raw)
} catch (err) {
throw new ConfigExtendsError(
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
)
}
const resolved = await resolveExtends(parsed, targetFile, options, chain)
base = base ? mergeQuartzConfigs(base, resolved as QuartzConfigOverlay) : resolved
}
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
}
+54 -16
View File
@@ -61,6 +61,9 @@ import {
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
import { componentRegistry, RegisteredComponent } from "../../components/registry"
import { frameRegistry } from "../../components/frames/registry"
import { OrderItem, constraintList, normalizePluginName, orderPlugins } from "./plugin-order"
import { resolveExtends } from "./config-extends"
import { setSlugOptions } from "../../util/path"
import { getCondition, getAllConditionNames } from "./conditions"
import {
LAYOUT_SLOTS,
@@ -92,16 +95,18 @@ export function resolveConfigPath(): string {
if (fs.existsSync(LEGACY_DEFAULT_PLUGINS_JSON_PATH)) return LEGACY_DEFAULT_PLUGINS_JSON_PATH
return CONFIG_YAML_PATH
}
function readPluginsJson(): QuartzPluginsJson | null {
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath)) {
return null
}
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw) as QuartzPluginsJson
}
return JSON.parse(raw) as QuartzPluginsJson
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
// `extends:` (#2440): merge onto the base config; a config without it is used as written
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: (data as QuartzPluginsJson)
}
function extractPluginName(source: PluginSource): string {
@@ -360,11 +365,12 @@ async function getManifest(source: PluginSource): Promise<PluginManifest | null>
export async function loadQuartzConfig(
configOverrides?: Partial<GlobalConfiguration>,
): Promise<QuartzConfig> {
const json = readPluginsJson()
const json = await readPluginsJson()
if (!json) {
// Fallback: import old-style config directly
const oldConfig = await import("../../../quartz")
setSlugOptions(oldConfig.default?.configuration?.slugs)
return oldConfig.default
}
@@ -372,6 +378,8 @@ export async function loadQuartzConfig(
...(json.configuration as unknown as GlobalConfiguration),
...configOverrides,
}
// before anything computes a slug (this runs in the main thread and in every worker)
setSlugOptions(configuration.slugs)
// Entries of official plugins that are now built into core (crawl-links, remove-draft,
// content-index) are handled by the built-ins below and never installed or loaded.
@@ -656,7 +664,7 @@ export async function loadQuartzConfig(
items: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[],
expectedCategory: ProcessingCategory,
) => {
const instances: { order: number; instance: any }[] = []
const instances: OrderItem<any>[] = []
for (const { entry, manifest } of items) {
try {
const spec = parsePluginSource(entry.source)
@@ -715,7 +723,19 @@ export async function loadQuartzConfig(
issues: manifest?.issues,
quartzVersion: manifest?.quartzVersion,
})
instances.push({ order: entry.order ?? manifest?.defaultOrder ?? 50, instance })
const label = extractPluginName(entry.source)
instances.push({
order: entry.order ?? manifest?.defaultOrder ?? 50,
instance,
label,
names: [
label,
manifest?.name,
typeof instance.name === "string" ? instance.name : "",
].filter((n): n is string => typeof n === "string" && n !== ""),
before: constraintList(entry.before, "before", label),
after: constraintList(entry.after, "after", label),
})
} catch (err) {
pluginLoadFailed(entry, manifest, "was skipped: it failed to initialise", err)
}
@@ -733,15 +753,33 @@ export async function loadQuartzConfig(
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
// Built-in processing steps take their place in plugin order (frontmatter at 0, links at 60 …);
// on equal order a built-in runs before plugins (stable sort, built-ins listed first).
// on equal order a built-in runs before plugins (stable sort, built-ins listed first), unless
// `before`/`after` on an entry say otherwise (see plugin-order.ts).
const knownPluginNames = new Set(
[
...json.plugins.map((e) => extractPluginName(e.source)),
...builtinPlan.builtins.map((b) => b.spec.configKey),
"Frontmatter",
"Links",
"Drafts",
"ContentIndex",
"Fonts",
].map(normalizePluginName),
)
const withBuiltins = <T>(
builtins: { order: number; instance: unknown }[],
instances: { order: number; instance: T }[],
instances: OrderItem<T>[],
): T[] =>
[...builtins, ...instances]
.map((item, index) => ({ ...item, index }))
.sort((a, b) => a.order - b.order || a.index - b.index)
.map((item) => item.instance as T)
orderPlugins(
[
...builtins.map(({ order, instance }) => {
const name = (instance as { name: string }).name
return { order, instance: instance as T, label: name, names: [name] }
}),
...instances,
],
knownPluginNames,
)
const plugins: PluginTypes = {
transformers: withBuiltins(
@@ -760,7 +798,7 @@ export async function loadQuartzConfig(
),
],
pageTypes: [
...(await instantiate(pageTypes, "pageType")).map((item) => item.instance),
...orderPlugins(await instantiate(pageTypes, "pageType"), knownPluginNames),
...builtinPageTypes,
],
}
@@ -1175,7 +1213,7 @@ export function buildQuartzLayout(
* the renderer's layout is updated in place with the overrides applied.
*/
export async function loadQuartzLayout(layoutOverrides?: LayoutOverrides): Promise<QuartzLayout> {
const json = readPluginsJson()
const json = await readPluginsJson()
if (!json) {
// Fallback: import old-style layout directly
+8 -6
View File
@@ -5,6 +5,7 @@ import YAML from "yaml"
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
import type { PluginSource, QuartzPluginsJson } from "./types.js"
import { absorbingBuiltin } from "../builtins/index.js"
import { resolveExtends } from "./config-extends.js"
function resolveConfigPath(): string {
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
@@ -20,14 +21,15 @@ function resolveConfigPath(): string {
return configYamlPath
}
function readPluginsJson(): QuartzPluginsJson | null {
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath)) return null
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw)
}
return JSON.parse(raw)
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: data
}
async function getExternalPluginSources(): Promise<PluginSource[]> {
@@ -45,7 +47,7 @@ async function getExternalPluginSources(): Promise<PluginSource[]> {
// fall back to config yaml parsing
}
const pluginsJson = readPluginsJson()
const pluginsJson = await readPluginsJson()
const entries = pluginsJson?.plugins ?? []
return entries.filter((entry) => entry.enabled !== false).map((entry) => entry.source)
}
+104
View File
@@ -0,0 +1,104 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import {
OrderItem,
PluginOrderError,
constraintList,
normalizePluginName,
orderPlugins,
} from "./plugin-order"
const item = (
name: string,
order: number,
c: { before?: string[]; after?: string[] } = {},
): OrderItem<string> => ({ instance: name, order, label: name, names: [name], ...c })
const known = (...names: string[]) => new Set(names.map(normalizePluginName))
describe("orderPlugins", () => {
test("numeric order, then list position, as before", () => {
const items = [item("c", 50), item("a", 10), item("b", 50)]
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "c", "b"])
})
test("before/after decide between plugins with the same order", () => {
const items = [item("x", 50, { after: ["y"] }), item("y", 50), item("z", 50, { before: ["y"] })]
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
})
test("constraints that agree with order are fine and change nothing", () => {
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
})
test("a contradiction with order is an error naming both orders", () => {
assert.throws(
() => orderPlugins([item("a", 30, { after: ["b"] }), item("b", 60)], known("a", "b")),
(err: Error) =>
err instanceof PluginOrderError &&
/"a" \(order 30\) must run after "b", but "b" has order 60/.test(err.message),
)
assert.throws(
() => orderPlugins([item("a", 60, { before: ["b"] }), item("b", 30)], known("a", "b")),
/"a" \(order 60\) must run before "b", but "b" has order 30/,
)
})
test("a cycle among equal orders is an error", () => {
assert.throws(
() =>
orderPlugins(
[item("a", 50, { after: ["b"] }), item("b", 50, { after: ["a"] })],
known("a", "b"),
),
/cycle among plugins with order 50: a, b/,
)
})
test("names match loosely: package name, kebab-case, instance name", () => {
const ofm: OrderItem<string> = {
instance: "ofm",
order: 40,
label: "obsidian-flavored-markdown",
names: ["obsidian-flavored-markdown", "ObsidianFlavoredMarkdown"],
}
for (const ref of [
"ObsidianFlavoredMarkdown",
"obsidian-flavored-markdown",
"@quartz-community/obsidian-flavored-markdown",
]) {
const mine = item("mine", 40, { after: [ref] })
assert.deepStrictEqual(orderPlugins([mine, ofm], known("obsidian-flavored-markdown")), [
"ofm",
"mine",
])
}
})
test("unknown names are errors; disabled or other-category plugins are skipped", () => {
assert.throws(
() => orderPlugins([item("a", 50, { after: ["typo"] })], known("a")),
/"a": after: "typo" is not a plugin in this config/,
)
assert.deepStrictEqual(
orderPlugins([item("a", 50, { after: ["disabled"] })], known("a", "disabled")),
["a"],
)
})
test("a plugin cannot be ordered against itself", () => {
assert.throws(() => orderPlugins([item("a", 50, { after: ["a"] })], known("a")), /itself/)
})
})
describe("constraintList", () => {
test("accepts a name or a list", () => {
assert.deepStrictEqual(constraintList("x", "after", "p"), ["x"])
assert.deepStrictEqual(constraintList(["x", "y"], "after", "p"), ["x", "y"])
assert.deepStrictEqual(constraintList(undefined, "after", "p"), [])
})
test("rejects other values", () => {
assert.throws(() => constraintList(3, "after", "p"), PluginOrderError)
assert.throws(() => constraintList([""], "before", "p"), /"before" must be/)
})
})
+160
View File
@@ -0,0 +1,160 @@
/**
* Plugin order: numeric `order` first, then checked `before:` / `after:` constraints (#2440).
*
* - Plugins run by `order` (lower first), as before. `before`/`after` never move a plugin past
* a plugin with a different `order`: they are checked against it, and a contradiction
* (`after: X` while X has a higher order) is an error that names both orders.
* - Between plugins with the same `order`, the constraints decide; otherwise the list order does
* (built-ins first, then the config's order), as before.
* - Names are plugin names, matched loosely (`obsidian-flavored-markdown`,
* `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` are the same;
* built-ins answer to their instance name and config key, e.g. `Links` / `links`).
* - A name that is not in the config at all is an error (likely a typo). A plugin that is in
* the config but disabled, or runs in another category, is skipped: the constraint only
* applies where both plugins run. A cycle among equal orders is an error.
*
* Constraints are plain data on config entries, so a later dependency-based scheme (e.g. from
* the manifests' `dependencies`) can feed the same checks.
*/
/** A configuration mistake: reported by its message alone (no stack trace). */
export class PluginOrderError extends Error {
constructor(message: string) {
super(message)
this.name = "PluginOrderError"
this.stack = `${this.name}: ${message}`
}
}
/** Loose plugin name: lowercase, scope and punctuation removed. */
export function normalizePluginName(name: string): string {
const bare = name.trim().replace(/^@[^/]+\//, "")
return bare.toLowerCase().replace(/[^a-z0-9]/g, "")
}
export interface OrderItem<T> {
instance: T
order: number
/** Display name used in messages. */
label: string
/** Every name this plugin answers to. */
names: string[]
before?: string[]
after?: string[]
}
/** Accepts `before: X` and `before: [X, Y]`; anything else is an error. */
export function constraintList(value: unknown, field: string, label: string): string[] {
if (value === undefined || value === null) return []
const list = Array.isArray(value) ? value : [value]
for (const v of list) {
if (typeof v !== "string" || v.trim() === "") {
throw new PluginOrderError(
`plugin "${label}": "${field}" must be a plugin name or a list of plugin names`,
)
}
}
return list as string[]
}
/**
* Sort one category's plugins. `known` holds the normalized names of every plugin in the
* config (enabled or not, any category) and of the built-ins, to tell typos from plugins that
* just don't run here.
*/
export function orderPlugins<T>(items: OrderItem<T>[], known: ReadonlySet<string>): T[] {
const indexed = items.map((item, index) => ({ ...item, index }))
const byName = new Map<string, (typeof indexed)[number]>()
for (const item of indexed) {
for (const name of item.names) {
const key = normalizePluginName(name)
if (!byName.has(key)) byName.set(key, item)
}
}
// edges: earlier → later
const later = new Map<number, Set<number>>()
const addEdge = (
first: (typeof indexed)[number],
second: (typeof indexed)[number],
why: string,
) => {
if (first === second) {
throw new PluginOrderError(`plugin "${first.label}": ${why} names the plugin itself`)
}
if (first.order > second.order) {
throw new PluginOrderError(
`plugin "${second.label}" (order ${second.order}) ${why}, but "${first.label}" has order ${first.order}, so it runs later. ` +
`Give "${second.label}" an order above ${first.order}, or "${first.label}" one below ${second.order}.`,
)
}
if (!later.has(first.index)) later.set(first.index, new Set())
later.get(first.index)!.add(second.index)
}
for (const item of indexed) {
for (const [field, names] of [
["after", item.after ?? []],
["before", item.before ?? []],
] as const) {
for (const name of names) {
const key = normalizePluginName(name)
const other = byName.get(key)
if (!other) {
if (!known.has(key)) {
throw new PluginOrderError(
`plugin "${item.label}": ${field}: "${name}" is not a plugin in this config`,
)
}
continue // disabled, or not in this category
}
if (field === "after") addEdge(other, item, `must run after "${other.label}"`)
else {
// phrase the message from the constrained plugin's point of view
if (item.order > other.order) {
throw new PluginOrderError(
`plugin "${item.label}" (order ${item.order}) must run before "${other.label}", but "${other.label}" has order ${other.order}, so it runs earlier. ` +
`Give "${item.label}" an order below ${other.order}, or "${other.label}" one above ${item.order}.`,
)
}
addEdge(item, other, `must run before "${other.label}"`)
}
}
}
}
// numeric order, then list position; within one order, a stable topological sort
const sorted = [...indexed].sort((a, b) => a.order - b.order || a.index - b.index)
if (later.size === 0) return sorted.map((i) => i.instance)
const result: (typeof indexed)[number][] = []
let start = 0
while (start < sorted.length) {
let end = start
while (end < sorted.length && sorted[end].order === sorted[start].order) end++
const group = sorted.slice(start, end)
const inGroup = new Set(group.map((g) => g.index))
const indegree = new Map(group.map((g) => [g.index, 0]))
for (const g of group) {
for (const next of later.get(g.index) ?? []) {
if (inGroup.has(next)) indegree.set(next, indegree.get(next)! + 1)
}
}
const remaining = [...group]
while (remaining.length > 0) {
const pos = remaining.findIndex((g) => indegree.get(g.index) === 0)
if (pos === -1) {
throw new PluginOrderError(
`"before"/"after" form a cycle among plugins with order ${group[0].order}: ${remaining.map((g) => g.label).join(", ")}`,
)
}
const [next] = remaining.splice(pos, 1)
result.push(next)
for (const n of later.get(next.index) ?? []) {
if (inGroup.has(n)) indegree.set(n, indegree.get(n)! - 1)
}
}
start = end
}
return result.map((i) => i.instance)
}
+3
View File
@@ -165,6 +165,9 @@ export interface PluginJsonEntry {
enabled: boolean
options?: Record<string, unknown>
order?: number
/** Plugins this one must run before / after (checked against `order`; see plugin-order.ts). */
before?: string | string[]
after?: string | string[]
layout?: PluginLayoutDeclaration
}
+22 -1
View File
@@ -16,7 +16,7 @@ import {
} from "./dispatcher"
import { QuartzPageTypePluginInstance } from "../types"
import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug, SimpleSlug } from "../../util/path"
import { FilePath, FullSlug, SimpleSlug, setSlugOptions } from "../../util/path"
import { Root as HtmlRoot } from "hast"
import { BuildCtx } from "../../util/ctx"
import { defaultProcessedContent } from "../vfile"
@@ -278,6 +278,27 @@ describe("generateVirtualPages", () => {
assert.strictEqual(ctx.virtualPages.length, 2)
})
test("slugs.stripDiacritics moves folder pages to the stripped folder slug (#2410)", async () => {
setSlugOptions({ stripDiacritics: true })
try {
const entries = await generateVirtualPages(
[makePageType({ generate: () => [page("české/index"), page("tags/čeština")] })],
[],
makeCtx(),
{ head: StubHead },
{},
)
// tag pages keep their slugs: tag links are slugged by the plugins that render them
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["ceske/index", "tags/čeština"],
)
assert.strictEqual(entries[0].vfile.data.slug, "ceske/index")
} finally {
setSlugOptions(undefined)
}
})
test("keeps the 404 page out of ctx.virtualPages", async () => {
const ctx = makeCtx()
const entries = await generateVirtualPages(
+4 -1
View File
@@ -15,6 +15,7 @@ import {
pathToRoot,
simplifySlug,
slugifyFilePath,
applySlugOptions,
} from "../../util/path"
import { ProcessedContent, defaultProcessedContent } from "../vfile"
import { write } from "../emitters/helpers"
@@ -215,7 +216,9 @@ export async function generateVirtualPages(
const layout = resolveLayout(pt, defaults, byPageType)
const fileBacked = (pt.fileExtensions?.length ?? 0) > 0
for (const vp of virtualPages) {
const vpSlug = vp.slug as FullSlug
// A folder's page lives at the folder's slug; with `slugs.stripDiacritics` that is the
// stripped one, whatever the page type computed from the file path (folder-page).
const vpSlug = (vp.slug.endsWith("/index") ? applySlugOptions(vp.slug) : vp.slug) as FullSlug
const vpRelativePath = (vpSlug + ".md") as FilePath
const [tree, vfile] = defaultProcessedContent({
slug: vpSlug,
+83 -4
View File
@@ -3,16 +3,54 @@
"title": "Quartz Plugins Configuration Schema",
"description": "Schema for validating quartz.config.yaml (and legacy quartz.plugins.json) configuration files",
"type": "object",
"required": ["configuration", "plugins"],
"additionalProperties": false,
"if": {
"required": ["extends"]
},
"then": {
"properties": {
"plugins": {
"items": {
"required": ["source"]
}
}
}
},
"else": {
"required": ["configuration", "plugins"],
"properties": {
"configuration": {
"required": ["pageTitle", "enableSPA", "locale", "theme"]
},
"plugins": {
"items": {
"required": ["source", "enabled"]
}
}
}
},
"properties": {
"$schema": {
"type": "string",
"description": "JSON Schema reference"
},
"extends": {
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
]
},
"configuration": {
"type": "object",
"required": ["pageTitle", "enableSPA", "locale", "theme"],
"additionalProperties": false,
"properties": {
"pageTitle": {
@@ -195,6 +233,18 @@
"default": "all",
"description": "Controls which assets are copied to public. \"all\" copies all non-markdown files; \"referenced\" only copies assets referenced by published pages"
},
"slugs": {
"type": "object",
"additionalProperties": false,
"description": "How file paths become URLs (slugs).",
"properties": {
"stripDiacritics": {
"type": "boolean",
"default": false,
"description": "Strip accents and other diacritics from generated slugs (české/čeština.md → ceske/cestina). Applies to file and folder names, aliases and permalinks; links are resolved the same way."
}
}
},
"frontmatter": {
"description": "Built-in frontmatter parsing: titles, tags, aliases, dates, drafts. Default order 0.",
"oneOf": [
@@ -362,7 +412,6 @@
"description": "Array of plugin configurations",
"items": {
"type": "object",
"required": ["source", "enabled"],
"additionalProperties": false,
"properties": {
"source": {
@@ -407,6 +456,36 @@
"minimum": 0,
"description": "Plugin execution order"
},
"before": {
"description": "Plugin name(s) this plugin must run before. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
]
},
"after": {
"description": "Plugin name(s) this plugin must run after. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
]
},
"options": {
"type": "object",
"additionalProperties": true,
@@ -432,7 +511,7 @@
},
"condition": {
"type": "string",
"description": "Render only when this condition holds. Built-in: not-index, has-tags, has-backlinks, has-toc; plugins may register more."
"description": "Render only when this condition holds. Built-in: is-index, not-index, is-folder-index, has-tags, has-backlinks, has-toc; plugins may register more. Prefix any condition with not- to negate it (not-has-tags)."
},
"group": {
"type": "string",
+4 -1
View File
@@ -31,7 +31,10 @@ export type ContentDetails = {
tags: string[]
content: string
richContent?: string
/** RSS / sitemap only — not written to contentIndex.json. */
/**
* The page's date (see `defaultDateType`). Written to contentIndex.json as an ISO 8601
* string, and only for pages that have a date.
*/
date?: Date
/** RSS / sitemap only — not written to contentIndex.json. */
description?: string
+47
View File
@@ -392,3 +392,50 @@ describe("resolveRelative", () => {
assert.strictEqual(path.resolveRelative("abc/def" as FullSlug, "ghi/" as SimpleSlug), "../ghi/")
})
})
describe("slugs.stripDiacritics (#2410)", () => {
const withStrip = <T>(fn: () => T): T => {
path.setSlugOptions({ stripDiacritics: true })
try {
return fn()
} finally {
path.setSlugOptions(undefined)
}
}
test("off by default: slugs keep their diacritics", () => {
assert.strictEqual(path.slugifyFilePath("české/čeština.md" as path.FilePath), "české/čeština")
})
test("strips diacritics from folder and file names", () => {
withStrip(() => {
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
assert.strictEqual(slug("české/Čeština.md"), "ceske/cestina")
assert.strictEqual(slug("Příliš žluťoučký kůň.md"), "prilis-zlutoucky-kun")
assert.strictEqual(slug("Café/Crème brûlée.md"), "cafe/creme-brulee")
assert.strictEqual(slug("Tiếng Việt.md"), "tieng-viet")
assert.strictEqual(slug("obrázek.PNG"), "obrazek.PNG")
// decomposed input (macOS file names) gives the same slug
assert.strictEqual(slug("čeština.md"), "cestina")
})
})
test("keeps scripts whose marks are not Latin diacritics", () => {
withStrip(() => {
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
assert.strictEqual(slug("한국어.md"), "한국어")
assert.strictEqual(slug("がぎぐ.md"), "がぎぐ")
assert.strictEqual(slug("हिन्दी.md"), "हिन्दी")
assert.strictEqual(slug("日本語/中文.md"), "日本語/中文")
// letters without a decomposition are kept
assert.strictEqual(slug("Łódź ø ß.md"), "łodz-ø-ß")
})
})
test("is idempotent", () => {
withStrip(() => {
const once = path.slugifyFilePath("Čeština/Ž.md" as path.FilePath)
assert.strictEqual(path.slugifyFilePath(`${once}.md` as path.FilePath), once)
})
})
})
+56 -1
View File
@@ -6,7 +6,6 @@ export {
isRelativeURL,
isAbsoluteURL,
getFullSlug,
slugifyFilePath,
simplifySlug,
joinSegments,
endsWith,
@@ -35,6 +34,62 @@ export type {
// --- v5-specific exports below ---
import { slugifyFilePath as slugifyFilePathBase } from "@quartz-community/utils"
import * as quartzUtils from "@quartz-community/utils"
import type { FilePath as _FilePath, FullSlug as _FullSlug } from "@quartz-community/utils"
export interface SlugOptions {
/** Strip accents and other diacritics (`č` → `c`, `é` → `e`) from generated slugs. */
stripDiacritics?: boolean
}
let slugOptions: SlugOptions = {}
/**
* Set how core turns file paths into slugs (`configuration.slugs`). Called when the config is
* loaded, in the main thread and in every worker, so all slugs of a build agree.
*/
export function setSlugOptions(options: SlugOptions | undefined): void {
slugOptions = { ...(options ?? {}) }
// @quartz-community/utils 1.3+ applies the same options to every slug it computes, for core
// and for plugins (tag pages, canvas, bases, alias-redirects …). Older utils lack it; core's
// own wrapper below and the links/dispatcher handling then cover core's slugs. Stripping is
// idempotent, so both applying is harmless. (Drop the wrapper once core requires utils 1.3.)
const utilsSetter = (quartzUtils as { setSlugOptions?: (o: SlugOptions | undefined) => void })
.setSlugOptions
utilsSetter?.(slugOptions)
}
export function getSlugOptions(): Readonly<SlugOptions> {
return slugOptions
}
/**
* Remove combining diacritical marks (U+0300–U+036F) after canonical decomposition:
* `Čeština` → `Cestina`, `Ελληνικά` → `Ελληνικα`. The string is recomposed afterwards, so
* scripts whose marks are outside that block (Hangul, kana with dakuten, Devanagari, Arabic)
* keep their usual form. Letters without a decomposition (`ø`, `ł`, `ß`, `æ`) are kept.
*/
export function stripDiacritics(s: string): string {
return s
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.normalize("NFC")
}
/** `stripDiacritics` when `configuration.slugs.stripDiacritics` is on, else unchanged. */
export function applySlugOptions(s: string): string {
return slugOptions.stripDiacritics ? stripDiacritics(s) : s
}
/**
* Slug of a content file path (see `@quartz-community/utils`), honouring
* `configuration.slugs` (see setSlugOptions).
*/
export function slugifyFilePath(fp: _FilePath, excludeExt?: boolean): _FullSlug {
return slugifyFilePathBase(applySlugOptions(fp) as _FilePath, excludeExt)
}
export const QUARTZ = "quartz"
// from micromorph/src/utils.ts