mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
Merge pull request #2709 from jackyzha0/dev-mode/5-3-core-fixes
fix: pre-5.3 audit fixes (broken-link marks, stand-in dates, extends, CLI, order, conditions, head, frontmatter links, release workflow)
This commit is contained in:
35 files changed
+1163
-145
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Links: links to files Quartz emits, such as `[feed](/index.xml)`, `/sitemap.xml`, `/static/icon.png` or `/404.html`, are no longer marked `broken`. A link is only marked when its target is known to be missing: a page that doesn't exist, or a vault file (image, audio, video, PDF, canvas, base) the content doesn't have. Other files may come from an emitter, so they are left unmarked.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
`extends` (experimental): `npx quartz plugin list`, `status`, `doctor`, `install`, `prune` and `npx quartz info` read the merged configuration, as the build does. Before, they saw only the entries in your own file, so `list` showed a handful of plugins and `doctor` warned that overlay entries without `enabled` are disabled. `enable`, `disable` and `config` now work on plugins from a base by adding or changing your own entry for them (only that change is written; the merged configuration never is), `config --unset` resets an option a base sets with `null`, and `remove` refuses a plugin that comes from a base. `npx quartz build --serve` also rebuilds when a local base file changes.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
`extends` (experimental): presets in a list now stack. With `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, everything `a.yaml` changed was lost, because `b.yaml` was merged on top with all of `default` again. Each file of the `extends` chain is now applied once, after the bases it extends, so the order is `default` → `a.yaml` → `b.yaml` → your file, and later entries win only where they change the same thing.
|
||||
|
||||
Also: a plugin source with a `subdir` and no `name` is matched by repository and folder, so an entry for one plugin of a monorepo no longer changes another; `extends: []` extends nothing; an empty base file is an empty config; `HTTPS://` URLs are accepted; and `plugins:` that isn't a list gets a clear error.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Layout conditions: `is-folder-index` is false on tag pages. The all-tags page (`tags/index`) matched it, so components meant for folder pages showed there; nothing under `tags/` counts as a folder index now.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Markdown links in frontmatter are read as CommonMark reads them: angle-bracket destinations with parentheses (`[b](<Note (2024).md>)`), balanced parentheses in plain destinations (`[d](Note_(2024).md)`), titles in `"…"`, `'…'` or `(…)` (`[c](<My Note.md> "t")`), and backslash escapes. They pointed at `note-(2024` and `my-note.md-t`, so the linked note got no backlink or graph edge.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
A note whose name ends in "index" (`reindex.md`) is an `og:type: article` again. The home page and folder index pages were told apart by the slug ending in `index`, not by its last segment, so such notes were `website` and had no article dates.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Plugin order: `before:` / `after:` naming a plugin that is built into Quartz now (`crawl-links`, `remove-draft`, `content-index`) passed validation but was ignored. They now mean the built-in that replaced them (`links`, `drafts`, `contentIndex`), so `before: crawl-links` orders the plugin before link processing, and is checked against its `order` like `before: links`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Build-time stand-in dates are no longer written as real dates. A page whose date no source gives (for example `defaultDateType: published` and no `published:`, or an invalid one) gets the build time from the date plugin; `contentIndex.json` now leaves its `date` out, and `article:published_time` / `article:modified_time` are only set for real dates (an invalid `published:` gave the build time). RSS and the sitemap keep the build time. created-modified-date 1.0.5 lists its stand-ins in `file.data.fallbackDates`; with older versions a `published` date only counts when the frontmatter sets it.
|
||||
@@ -2,4 +2,4 @@
|
||||
"@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, tags and folder pages resolve to the stripped addresses, and the old addresses redirect to them; heading anchors keep their diacritics. Letters without a separate accent (`ł`, `ø`, `ß`) are kept, as are Korean, Japanese, Chinese, Indic, Hebrew and Arabic text. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do.
|
||||
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses, and the old addresses redirect to them; heading anchors keep their diacritics. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
|
||||
@@ -46,12 +46,32 @@ jobs:
|
||||
if: steps.changesets.outputs.has-changesets == 'false'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Each step can be re-run: an existing tag on this commit, or an existing release, is
|
||||
# kept, and the Docker build is started again (a failed run used to stop at "already
|
||||
# exists" on the next attempt).
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG="v$VERSION"
|
||||
if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
|
||||
echo "$TAG already exists — nothing to release."
|
||||
exit 0
|
||||
# The commit the tag points at on GitHub (empty when there is no tag yet); an annotated
|
||||
# tag is followed to its commit.
|
||||
tag_commit() {
|
||||
local ref type sha
|
||||
ref=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq '.object.type + " " + .object.sha' 2>/dev/null) || return 0
|
||||
read -r type sha <<<"$ref"
|
||||
if [ "$type" = "tag" ]; then
|
||||
sha=$(gh api "repos/$GITHUB_REPOSITORY/git/tags/$sha" --jq '.object.sha')
|
||||
fi
|
||||
echo "$sha"
|
||||
}
|
||||
EXISTING=$(tag_commit)
|
||||
if [ -n "$EXISTING" ] && [ "$EXISTING" != "$GITHUB_SHA" ]; then
|
||||
if git merge-base --is-ancestor "$EXISTING" "$GITHUB_SHA" 2>/dev/null; then
|
||||
echo "$TAG was released at $EXISTING — nothing to release."
|
||||
exit 0
|
||||
fi
|
||||
echo "::error::$TAG already exists but points at $EXISTING, which is not this commit ($GITHUB_SHA) or one of its ancestors. Check the tag (delete it if it is wrong), then re-run this workflow."
|
||||
exit 1
|
||||
fi
|
||||
# Only versions produced by `changeset version` are released (guards against tagging
|
||||
# an arbitrary commit with a version that was never released through this workflow).
|
||||
@@ -65,8 +85,18 @@ jobs:
|
||||
# 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
|
||||
if [ -z "$EXISTING" ]; then
|
||||
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
|
||||
else
|
||||
echo "$TAG already points at this commit — keeping it."
|
||||
fi
|
||||
if gh release view "$TAG" >/dev/null 2>&1; then
|
||||
echo "The $TAG release already exists — keeping it."
|
||||
else
|
||||
gh release create "$TAG" --verify-tag --title "Quartz $VERSION" --notes-file release-notes.md
|
||||
fi
|
||||
# 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.
|
||||
# never built the versioned images; start it for the tag explicitly. Started with
|
||||
# `--ref vX.Y.Z`, the run's GITHUB_REF is refs/tags/vX.Y.Z, which is all
|
||||
# docker/metadata-action's `type=semver` tags need (it checks the ref, not the event).
|
||||
gh workflow run docker-build-push.yaml --ref "$TAG"
|
||||
@@ -42,15 +42,19 @@ plugins:
|
||||
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.
|
||||
- `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. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
|
||||
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
|
||||
- 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.
|
||||
- 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). A source with a `name` matches by that name; a source with a `subdir` and no `name` matches by repository and folder, so two plugins of one repository stay separate. `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.
|
||||
|
||||
- `npx quartz build --serve` also rebuilds when a local file your config extends changes.
|
||||
- `npx quartz plugin` commands and `npx quartz info` read the merged configuration, as the build does: `plugin list`, `status`, `doctor`, `install` and `prune` see the plugins your bases configure. Commands that change plugins only ever write your own file, never the merged result: `enable`, `disable` and `config --set` add or change your entry for the plugin (`- source: …` with just that change), `config --unset` removes your value and, when a base sets the option, sets it to `null` so the plugin's default applies, and `add` appends a full entry. `remove` refuses a plugin that a base configures (it can't be removed from your file); disable it instead.
|
||||
|
||||
> [!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.
|
||||
> `extends` is experimental: the merge rules may still change.
|
||||
|
||||
## General Configuration
|
||||
|
||||
@@ -86,7 +90,7 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `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.
|
||||
- Only Latin letters change: they lose their accents (`á č é ů …`), and Latin letters without a decomposition fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`). Other scripts (Chinese, Japanese, Korean, Greek, Cyrillic, Arabic, Hebrew, Devanagari, …) are left as written, marks included.
|
||||
- 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.
|
||||
@@ -167,7 +171,7 @@ 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:
|
||||
`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`; the names of the plugins they replaced, `crawl-links`, `remove-draft` and `content-index`, mean those built-ins). They never override `order`; they are checked against it:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
plugins:
|
||||
|
||||
+9
-9
@@ -132,15 +132,15 @@ plugins:
|
||||
|
||||
Available conditions:
|
||||
|
||||
| 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` |
|
||||
| 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), not on tag pages (`tags/` and `tags/<tag>`) |
|
||||
| `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.
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ Options:
|
||||
- `openLinksInNewTab`: If `true`, configures external links to open in a new tab. Defaults to `false`.
|
||||
- `lazyLoad`: If `true`, adds lazy loading to resource elements (`img`, `video`, etc.) to improve page load performance. Defaults to `false`.
|
||||
- `externalLinkIcon`: Adds an icon next to external links when `true` (default) to visually distinguishing them from internal links.
|
||||
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed. Links to pages that a filter removes (e.g. [[RemoveDrafts|drafts]] or pages without `publish: true` under [[ExplicitPublish]]) are marked `broken` too, since they 404; they also get `data-filtered="<filter name>"`. A folder link stays unbroken when only the folder's `index.md` is removed, because the folder still gets a generated folder page.
|
||||
- `disableBrokenWikilinks`: If `true`, internal links whose resolved slug is not present in the site (i.e. no matching file under `markdownLinkResolution`) gain an additional `broken` CSS class alongside `internal`, so they can be styled distinctly. Defaults to `true`, as Obsidian marks unresolved links. Applies to both wikilinks and regular Markdown links, since both are indistinguishable `<a>` elements by the time links are processed. Only targets Quartz can check are marked: pages, and files of the types a vault holds (images, audio, video, PDFs, canvases, bases) that the content doesn't have. Links to other files, which Quartz or a plugin may emit (`index.xml`, `sitemap.xml`, `robots.txt`, anything under `static/`), are never marked. Links to pages that a filter removes (e.g. [[RemoveDrafts|drafts]] or pages without `publish: true` under [[ExplicitPublish]]) are marked `broken` too, since they 404; they also get `data-filtered="<filter name>"`. A folder link stays unbroken when only the folder's `index.md` is removed, because the folder still gets a generated folder page.
|
||||
- `enabled`: set to `false` to turn link processing off (not recommended — links break on nested pages and backlinks/graph are empty).
|
||||
- `order`: position among transformers. Defaults to `60`, after the Markdown flavour plugins (e.g. [[ObsidianFlavoredMarkdown]] at `40`) that turn wikilinks into links.
|
||||
|
||||
|
||||
Generated
+4
-4
@@ -97,7 +97,7 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.0",
|
||||
"@quartz-community/utils": "^1.3.1",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
@@ -3230,9 +3230,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/utils": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.0.tgz",
|
||||
"integrity": "sha512-XL4P2oHrt1DeGMZpi3iSoHLi1akl8ddDIjhCoqKiIc8I+BNCaq5GI1HYnJx+VdQr4dYgTlXTLulLiO4OHMZNlg==",
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.1.tgz",
|
||||
"integrity": "sha512-HGlcmwzt+nzu77sVfERtGFgw9CqO0/sApDX4RBM4pJZOxBDFKOL+5aKOw3TlHUW+57GJeDO1QM464foXbp+VWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.0",
|
||||
"@quartz-community/utils": "^1.3.1",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
|
||||
+12
-5
@@ -39,6 +39,7 @@ import {
|
||||
readPluginsJson,
|
||||
writePluginsJson,
|
||||
updateGlobalConfig,
|
||||
extendedConfigFiles,
|
||||
LOCKFILE_PATH,
|
||||
} from "./plugin-data.js"
|
||||
import {
|
||||
@@ -619,11 +620,17 @@ export async function handleBuild(argv) {
|
||||
"quartz.config.default.yaml",
|
||||
])
|
||||
const extraWatch = process.env.QUARTZ_CONFIG_PATH ? [process.env.QUARTZ_CONFIG_PATH] : []
|
||||
chokidar
|
||||
.watch([...paths, ...extraWatch], { ignoreInitial: true })
|
||||
.on("add", () => build(clientRefresh))
|
||||
.on("change", () => build(clientRefresh))
|
||||
.on("unlink", () => build(clientRefresh))
|
||||
// local files the config extends (and the files they extend); looked up again after each
|
||||
// change, so a newly added base is watched too
|
||||
const watcher = chokidar.watch([...paths, ...extraWatch, ...(await extendedConfigFiles())], {
|
||||
ignoreInitial: true,
|
||||
})
|
||||
const rebuild = async () => {
|
||||
await build(clientRefresh)
|
||||
const bases = await extendedConfigFiles()
|
||||
if (bases.length > 0) watcher.add(bases)
|
||||
}
|
||||
watcher.on("add", rebuild).on("change", rebuild).on("unlink", rebuild)
|
||||
|
||||
console.log(styleText("gray", "hint: exit with ctrl+c"))
|
||||
}
|
||||
|
||||
+11
-2
@@ -23,6 +23,7 @@ import { builtinKeyFor, describeBuiltins } from "./builtin-migration.js"
|
||||
import { shortPluginName } from "./plugin-validation.js"
|
||||
import {
|
||||
readConfigWithDiagnostics,
|
||||
resolveEffectiveConfig,
|
||||
readLockfile,
|
||||
extractPluginName,
|
||||
formatSource,
|
||||
@@ -56,10 +57,18 @@ function readPackage(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
export function collectInfo(root = process.cwd()) {
|
||||
export async function collectInfo(root = process.cwd()) {
|
||||
const version = readQuartzVersion(root)
|
||||
const checkout = describeQuartzCheckout(root)
|
||||
const config = readConfigWithDiagnostics()
|
||||
// with `extends`, the merged configuration the build uses
|
||||
if (config.data && !config.error) {
|
||||
try {
|
||||
config.data = await resolveEffectiveConfig(config.data, config.path)
|
||||
} catch (err) {
|
||||
config.error = `extends: ${String(err?.message ?? err)}`
|
||||
}
|
||||
}
|
||||
const lockfile = readLockfile()
|
||||
const entries = Array.isArray(config.data?.plugins) ? config.data.plugins : []
|
||||
|
||||
@@ -176,7 +185,7 @@ export function formatInfoMarkdown(info) {
|
||||
}
|
||||
|
||||
export async function handleInfo({ json = false } = {}) {
|
||||
const info = collectInfo()
|
||||
const info = await collectInfo()
|
||||
if (json) {
|
||||
console.log(JSON.stringify(info, null, 2))
|
||||
return
|
||||
|
||||
@@ -158,6 +158,65 @@ export function readPluginsJson() {
|
||||
return data
|
||||
}
|
||||
|
||||
/** Whether a config (as read from its file) extends another (`extends:` with at least one base). */
|
||||
export function configExtends(data) {
|
||||
if (!isPlainObject(data)) return false
|
||||
const value = data.extends
|
||||
if (value === undefined || value === null) return false
|
||||
return !Array.isArray(value) || value.length > 0
|
||||
}
|
||||
|
||||
let configExtendsModule
|
||||
/**
|
||||
* The build's `extends` implementation (quartz/plugins/loader/config-extends.ts), loaded through
|
||||
* tsx only when a config uses `extends`, so the CLI merges exactly as the build does.
|
||||
*/
|
||||
export function loadConfigExtendsModule() {
|
||||
configExtendsModule ??= import("tsx/esm/api").then(({ tsImport }) =>
|
||||
tsImport("../plugins/loader/config-extends.ts", import.meta.url),
|
||||
)
|
||||
return configExtendsModule
|
||||
}
|
||||
|
||||
/**
|
||||
* The configuration the build uses: the config file with its `extends` applied. A config
|
||||
* without `extends` is returned as read. Read-only commands (list, status, doctor, info,
|
||||
* install, prune) use this; commands that edit the file keep using readPluginsJson(), which
|
||||
* returns only what the user's file contains. Throws a clear error when a base can't be loaded.
|
||||
*/
|
||||
export async function resolveEffectiveConfig(data, configPath = resolveConfigPath()) {
|
||||
if (!configExtends(data)) return data
|
||||
const { resolveExtends } = await loadConfigExtendsModule()
|
||||
return resolveExtends(data, configPath)
|
||||
}
|
||||
|
||||
/** readPluginsJson() with `extends` applied; reports a base that can't be loaded and returns null. */
|
||||
export async function readEffectivePluginsJson() {
|
||||
const data = readPluginsJson()
|
||||
try {
|
||||
return await resolveEffectiveConfig(data)
|
||||
} catch (err) {
|
||||
console.error(`✗ ${path.basename(resolveConfigPath())}: ${String(err?.message ?? err)}`)
|
||||
process.exitCode = 1
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Local files the config extends (directly or through other bases), for `--serve` to watch.
|
||||
* Empty when it extends nothing or a base can't be loaded (the build reports that).
|
||||
*/
|
||||
export async function extendedConfigFiles() {
|
||||
const data = readPluginsJson()
|
||||
if (!configExtends(data)) return []
|
||||
try {
|
||||
const { localExtendsFiles } = await loadConfigExtendsModule()
|
||||
return await localExtendsFiles(data, resolveConfigPath())
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Path of the config file the CLI reads from (may be a default/legacy file). */
|
||||
export function getConfigReadPath() {
|
||||
return resolveConfigPath()
|
||||
|
||||
@@ -4,6 +4,11 @@ import os from "os"
|
||||
import { styleText } from "util"
|
||||
import {
|
||||
readPluginsJson,
|
||||
readEffectivePluginsJson,
|
||||
resolveEffectiveConfig,
|
||||
configExtends,
|
||||
loadConfigExtendsModule,
|
||||
getConfigReadPath,
|
||||
writePluginsJson,
|
||||
readLockfile,
|
||||
writeLockfile,
|
||||
@@ -128,6 +133,67 @@ function resolveConfigEntryOrReport(json, name) {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* For commands that edit quartz.config.yaml: `json` is the user's own file (what gets written
|
||||
* back) and `effective` the configuration the build uses (with `extends` applied; the same
|
||||
* object without it). Plugins are looked up in `effective`; changes go to the user's entry for
|
||||
* the plugin (see overlayEntryFor), never the merged configuration. Returns null after
|
||||
* reporting when a base can't be loaded.
|
||||
*/
|
||||
async function readConfigForEdit() {
|
||||
const json = readPluginsJson()
|
||||
if (!configExtends(json)) return { json, effective: json, extending: false }
|
||||
try {
|
||||
const effective = await resolveEffectiveConfig(json, getConfigReadPath())
|
||||
const { pluginMatchKey } = await loadConfigExtendsModule()
|
||||
return { json, effective, extending: true, matchKey: pluginMatchKey }
|
||||
} catch (err) {
|
||||
console.log(
|
||||
styleText(
|
||||
"red",
|
||||
`✗ ${path.basename(getConfigReadPath())}: ${String(err?.message ?? err)} — nothing changed`,
|
||||
),
|
||||
)
|
||||
markFailed()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's entry for a plugin of the merged configuration (matched as `extends` merges
|
||||
* entries; the last one wins when there are several). With `create`, an entry
|
||||
* `{ source }` is added when the user's file has none, which then changes only what is set in it.
|
||||
*/
|
||||
function overlayEntryFor(edit, mergedEntry, create = false) {
|
||||
if (!edit.extending) return mergedEntry
|
||||
if (edit.json.plugins == null) edit.json.plugins = []
|
||||
if (!Array.isArray(edit.json.plugins)) {
|
||||
throw new Error(`"plugins" in ${path.basename(getConfigReadPath())} must be a list`)
|
||||
}
|
||||
const key = edit.matchKey(mergedEntry.source)
|
||||
let entry = edit.json.plugins.findLast((e) => {
|
||||
try {
|
||||
return e?.source !== undefined && edit.matchKey(e.source) === key
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
if (!entry && create) {
|
||||
entry = { source: mergedEntry.source }
|
||||
edit.json.plugins.push(entry)
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
function hasOptionPath(obj, segments) {
|
||||
let node = obj
|
||||
for (const segment of segments) {
|
||||
if (node === null || typeof node !== "object" || !(segment in node)) return false
|
||||
node = node[segment]
|
||||
}
|
||||
return node !== undefined && node !== null
|
||||
}
|
||||
|
||||
/** Read the manifest (`quartz` field of package.json) of a configured plugin, if installed. */
|
||||
function readEntryManifest(source) {
|
||||
const dir = resolvePluginDir(source)
|
||||
@@ -427,7 +493,7 @@ async function regeneratePluginIndex() {
|
||||
// npm plugins in the config are part of the index too (they used to be dropped here until the
|
||||
// next build regenerated it); the generator is shared with the build, see plugin-index.js
|
||||
const npmPackages = []
|
||||
for (const entry of readPluginsJson()?.plugins ?? []) {
|
||||
for (const entry of (await readEffectivePluginsJson())?.plugins ?? []) {
|
||||
if (builtinMessage(entry.source)) continue
|
||||
try {
|
||||
const parsed = parseGitSource(entry.source)
|
||||
@@ -455,7 +521,9 @@ export async function handlePluginInstallUnified({
|
||||
|
||||
// Plugins that are built into core now (crawl-links, remove-draft, content-index) are never
|
||||
// cloned or built, even if the config or the lockfile still lists them.
|
||||
const rawPluginsJson = readPluginsJson()
|
||||
// with `extends`, the plugins of the merged configuration (as the build loads them)
|
||||
const rawPluginsJson = await readEffectivePluginsJson()
|
||||
if (!rawPluginsJson && configExtends(readPluginsJson())) return
|
||||
const pluginsJson = rawPluginsJson && {
|
||||
...rawPluginsJson,
|
||||
plugins: (rawPluginsJson.plugins ?? []).filter((entry) => !builtinMessage(entry.source)),
|
||||
@@ -1476,8 +1544,12 @@ export async function handlePluginAdd(
|
||||
fs.mkdirSync(PLUGINS_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
const configured = pluginsJson?.plugins ?? []
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
// added entries go to the user's file; "already configured" also covers plugins that come
|
||||
// from an `extends` base
|
||||
const pluginsJson = edit.json
|
||||
const configured = Array.isArray(edit.effective?.plugins) ? edit.effective.plugins : []
|
||||
|
||||
const addedPlugins = []
|
||||
let hadFailure = false
|
||||
@@ -1696,7 +1768,11 @@ export async function handlePluginAdd(
|
||||
writeLockfile(lockfile)
|
||||
}
|
||||
|
||||
if (pluginsJson?.plugins && addedPlugins.length > 0) {
|
||||
// an extending config may have no `plugins:` yet
|
||||
if (pluginsJson && pluginsJson.plugins == null && addedPlugins.length > 0) {
|
||||
pluginsJson.plugins = []
|
||||
}
|
||||
if (Array.isArray(pluginsJson?.plugins) && addedPlugins.length > 0) {
|
||||
for (const { pluginDir, source, configSource } of addedPlugins) {
|
||||
const manifest = readManifestFromPackageJson(pluginDir)
|
||||
const newEntry = {
|
||||
@@ -1774,13 +1850,36 @@ export async function handlePluginAdd(
|
||||
|
||||
export async function handlePluginRemove(names) {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
const pluginsJson = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const pluginsJson = edit.json
|
||||
// With `extends`: the plugins the bases configure (without the user's entries). Those can't
|
||||
// be removed from the user's file, only disabled.
|
||||
const basePlugins = edit.extending
|
||||
? ((await resolveEffectiveConfig({ ...pluginsJson, plugins: [] }, getConfigReadPath()))
|
||||
.plugins ?? [])
|
||||
: []
|
||||
let lockfileChanged = false
|
||||
let configChanged = false
|
||||
let removedFiles = false
|
||||
const removedSources = []
|
||||
|
||||
for (const name of names) {
|
||||
const fromBase = findConfigEntries(basePlugins, name, nameHelpers).indices
|
||||
if (fromBase.length > 0) {
|
||||
const label = extractPluginName(basePlugins[fromBase[0]].source)
|
||||
console.log(
|
||||
styleText(
|
||||
"red",
|
||||
`✗ ${label} comes from the configuration ${path.basename(getConfigReadPath())} extends, so it can't be removed from your file.`,
|
||||
),
|
||||
)
|
||||
console.log(
|
||||
styleText("gray", ` Turn it off with 'npx quartz plugin disable ${label}' instead.`),
|
||||
)
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
// Prefer the config entry (accepts short names such as "explorer").
|
||||
const { indices } = findConfigEntries(pluginsJson?.plugins ?? [], name, nameHelpers)
|
||||
const configIndex = indices.length === 1 ? indices[0] : -1
|
||||
@@ -1892,7 +1991,9 @@ export async function handlePluginRemove(names) {
|
||||
}
|
||||
|
||||
async function setEnabled(names, enabled) {
|
||||
const json = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const json = edit.json
|
||||
const verb = enabled ? "enable" : "disable"
|
||||
if (!json) {
|
||||
console.log(styleText("red", `✗ No quartz.config.yaml found. Cannot ${verb} plugins.`))
|
||||
@@ -1903,12 +2004,13 @@ async function setEnabled(names, enabled) {
|
||||
let changed = false
|
||||
for (const name of names) {
|
||||
const builtin = builtinMessage(name)
|
||||
if (builtin && !(json.plugins ?? []).some((e) => officialPluginName(e.source) === name)) {
|
||||
const plugins = Array.isArray(edit.effective.plugins) ? edit.effective.plugins : []
|
||||
if (builtin && !plugins.some((e) => officialPluginName(e.source) === name)) {
|
||||
console.log(styleText("yellow", `⚠ ${builtin}`))
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
const resolved = resolveConfigEntryOrReport(json, name)
|
||||
const resolved = resolveConfigEntryOrReport(edit.effective, name)
|
||||
if (!resolved) continue
|
||||
const { entry } = resolved
|
||||
const label = extractPluginName(entry.source)
|
||||
@@ -1917,7 +2019,8 @@ async function setEnabled(names, enabled) {
|
||||
console.log(styleText("gray", `✓ ${label} is already ${verb}d`))
|
||||
continue
|
||||
}
|
||||
entry.enabled = enabled
|
||||
// with `extends`: set in the user's entry for the plugin (added if needed)
|
||||
overlayEntryFor(edit, entry, true).enabled = enabled
|
||||
changed = true
|
||||
console.log(styleText("green", `✓ ${enabled ? "Enabled" : "Disabled"} ${label}`))
|
||||
if (
|
||||
@@ -1962,14 +2065,18 @@ function printOptionIssues(issues, label) {
|
||||
}
|
||||
|
||||
export async function handlePluginConfig(name, options = {}) {
|
||||
const json = readPluginsJson()
|
||||
const edit = await readConfigForEdit()
|
||||
if (!edit) return
|
||||
const json = edit.json
|
||||
if (!json) {
|
||||
console.log(styleText("red", "✗ No quartz.config.yaml found."))
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
|
||||
const resolved = resolveConfigEntryOrReport(json, name)
|
||||
// `entry` is the plugin as the build sees it (merged with `extends` bases); changes go to
|
||||
// `target`, the user's own entry for it
|
||||
const resolved = resolveConfigEntryOrReport(edit.effective, name)
|
||||
if (!resolved) return
|
||||
const { entry } = resolved
|
||||
const label = extractPluginName(entry.source)
|
||||
@@ -1979,7 +2086,8 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
const unsets = [options.unset ?? []].flat().filter((v) => v !== undefined)
|
||||
|
||||
if (sets.length > 0 || unsets.length > 0) {
|
||||
if (!entry.options || typeof entry.options !== "object") entry.options = {}
|
||||
const target = overlayEntryFor(edit, entry, true)
|
||||
if (!target.options || typeof target.options !== "object") target.options = {}
|
||||
let changed = false
|
||||
for (const assignment of sets) {
|
||||
const eqIndex = String(assignment).indexOf("=")
|
||||
@@ -1996,7 +2104,7 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
continue
|
||||
}
|
||||
const value = parseCliValue(assignment.slice(eqIndex + 1))
|
||||
setOptionPath(entry.options, segments, value)
|
||||
setOptionPath(target.options, segments, value)
|
||||
changed = true
|
||||
console.log(
|
||||
styleText("green", `✓ Set ${label}.${segments.join(".")} = ${JSON.stringify(value)}`),
|
||||
@@ -2010,7 +2118,29 @@ export async function handlePluginConfig(name, options = {}) {
|
||||
}
|
||||
for (const keyPath of unsets) {
|
||||
const segments = parseOptionPath(String(keyPath))
|
||||
if (unsetOptionPath(entry.options, segments)) {
|
||||
if (edit.extending) {
|
||||
// drop the user's value, then reset a value a base still sets with `null` (merging
|
||||
// removes the key, so the plugin's default applies)
|
||||
const hadOwn = unsetOptionPath(target.options, segments)
|
||||
const merged = await resolveEffectiveConfig(json, getConfigReadPath())
|
||||
const key = edit.matchKey(entry.source)
|
||||
const now = (merged.plugins ?? []).findLast((e) => edit.matchKey(e.source) === key)
|
||||
const fromBase = hasOptionPath(now?.options, segments)
|
||||
if (fromBase) setOptionPath(target.options, segments, null)
|
||||
if (hadOwn || fromBase) {
|
||||
changed = true
|
||||
console.log(
|
||||
styleText(
|
||||
"green",
|
||||
`✓ Unset ${label}.${segments.join(".")} (plugin default applies${fromBase ? "; null overrides the extended config" : ""})`,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
console.log(styleText("yellow", `⚠ ${label} has no option "${keyPath}" set`))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (unsetOptionPath(target.options, segments)) {
|
||||
changed = true
|
||||
console.log(
|
||||
styleText("green", `✓ Unset ${label}.${segments.join(".")} (plugin default applies)`),
|
||||
@@ -2102,7 +2232,8 @@ function collectUntrackedEntries(pluginsJson, lockfile) {
|
||||
|
||||
export async function handlePluginList() {
|
||||
const lockfile = readLockfile()
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) return
|
||||
const { npm, missing } = collectUntrackedEntries(pluginsJson, lockfile)
|
||||
const lockEntries = Object.entries(lockfile?.plugins ?? {})
|
||||
|
||||
@@ -2222,7 +2353,8 @@ export async function handlePluginList() {
|
||||
|
||||
export async function handlePluginStatus() {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) return
|
||||
const { npm } = collectUntrackedEntries(pluginsJson, lockfile)
|
||||
if (Object.keys(lockfile.plugins).length === 0 && npm.length === 0) {
|
||||
console.log(styleText("gray", "No plugins installed"))
|
||||
@@ -2459,7 +2591,23 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
report("info", null, `using ${configLabel} (no quartz.config.yaml yet)`)
|
||||
}
|
||||
|
||||
if (!Array.isArray(config.data?.plugins)) {
|
||||
// With `extends`, check the merged configuration (what the build loads); --fix still edits
|
||||
// only this file.
|
||||
const extending = configExtends(config.data)
|
||||
const effectiveOf = async (data) => (extending ? resolveEffectiveConfig(data, config.path) : data)
|
||||
let effective
|
||||
try {
|
||||
effective = await effectiveOf(config.data)
|
||||
} catch (err) {
|
||||
report("error", configLabel, `extends: ${String(err?.message ?? err)}`)
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
if (extending) {
|
||||
report("info", null, `${configLabel} uses extends; checking the merged configuration`)
|
||||
}
|
||||
|
||||
if (!Array.isArray(effective?.plugins)) {
|
||||
report("error", configLabel, "`plugins` must be a list")
|
||||
markFailed()
|
||||
return
|
||||
@@ -2474,6 +2622,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
for (const change of changes) console.log(styleText("green", `✓ ${change}`))
|
||||
console.log()
|
||||
config.data = migrated
|
||||
effective = await effectiveOf(migrated)
|
||||
} else {
|
||||
for (const { name, key } of migrations) {
|
||||
report(
|
||||
@@ -2487,9 +2636,11 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
}
|
||||
}
|
||||
const absorbed = new Set(
|
||||
migrations.filter((m) => m.name !== "note-properties").map((m) => m.entry),
|
||||
findBuiltinMigrations(effective)
|
||||
.filter((m) => m.name !== "note-properties")
|
||||
.map((m) => m.entry),
|
||||
)
|
||||
const plugins = config.data.plugins.filter((entry) => !absorbed.has(entry))
|
||||
const plugins = effective.plugins.filter((entry) => !absorbed.has(entry))
|
||||
|
||||
const lockfile = readLockfile()
|
||||
if (fs.existsSync(LOCKFILE_PATH) && !lockfile) {
|
||||
@@ -2669,7 +2820,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
// satisfied by the built-in: its entries were absorbed above.
|
||||
const builtinKey = builtinKeyFor(dep)
|
||||
if (builtinKey) {
|
||||
const builtin = describeBuiltins(config.data.configuration).find(
|
||||
const builtin = describeBuiltins(effective.configuration).find(
|
||||
(b) => b.key === builtinKey,
|
||||
)
|
||||
if (builtin && !builtin.enabled) {
|
||||
@@ -2771,7 +2922,13 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
|
||||
return
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
// plugins of the merged configuration: a plugin from an `extends` base is not an orphan
|
||||
const pluginsJson = await readEffectivePluginsJson()
|
||||
if (!pluginsJson && configExtends(readPluginsJson())) {
|
||||
console.log(styleText("red", "✗ Not pruning: the configuration could not be resolved."))
|
||||
markFailed()
|
||||
return
|
||||
}
|
||||
const configuredNames = new Set(
|
||||
(pluginsJson?.plugins ?? []).map((entry) => extractPluginName(entry.source)),
|
||||
)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import test, { describe, beforeEach, afterEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { execSync } from "child_process"
|
||||
import { execSync, spawnSync } from "child_process"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import YAML from "yaml"
|
||||
import {
|
||||
buildPluginAsync,
|
||||
checkoutPinnedCommitAsync,
|
||||
@@ -212,3 +213,84 @@ describe("checkoutPinnedCommitAsync", () => {
|
||||
assert.strictEqual(fs.readFileSync(path.join(dir, "package-lock.json"), "utf-8"), `{ "v": 1 }`)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin commands with an extending config", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
// stdout and stderr, whatever the exit code (doctor fails on npm plugins that aren't installed)
|
||||
const run = (dir, args) => {
|
||||
const result = spawnSync(process.execPath, [cli, ...args.split(" ")], {
|
||||
cwd: dir,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
return { output: result.stdout + result.stderr, status: result.status }
|
||||
}
|
||||
const site = () => {
|
||||
const dir = path.join(root, "site")
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.0" }`)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.default.yaml"),
|
||||
[
|
||||
"configuration:",
|
||||
" pageTitle: Default",
|
||||
"plugins:",
|
||||
' - source: "@quartz-community/graph"',
|
||||
" enabled: true",
|
||||
" options: { depth: 1, scale: 2 }",
|
||||
' - source: "@quartz-community/comments"',
|
||||
" enabled: false",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.yaml"),
|
||||
[
|
||||
"extends: default",
|
||||
"plugins:",
|
||||
' - source: "@quartz-community/graph"',
|
||||
" options: { depth: 3 }",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
return dir
|
||||
}
|
||||
const read = (dir) => fs.readFileSync(path.join(dir, "quartz.config.yaml"), "utf-8")
|
||||
|
||||
test("list and doctor read the merged configuration", () => {
|
||||
const dir = site()
|
||||
const list = run(dir, "plugin list").output
|
||||
assert.match(list, /@quartz-community\/comments .*disabled/)
|
||||
assert.match(list, /@quartz-community\/graph .*enabled/)
|
||||
const doctor = run(dir, "plugin doctor").output
|
||||
assert.match(doctor, /Checking plugins/)
|
||||
assert.doesNotMatch(doctor, /no `enabled` field/)
|
||||
})
|
||||
|
||||
test("enable, disable and config change only the user's entries", () => {
|
||||
const dir = site()
|
||||
run(dir, "plugin enable comments")
|
||||
run(dir, "plugin disable graph")
|
||||
run(dir, "plugin config graph --unset scale")
|
||||
run(dir, "plugin config graph --unset depth")
|
||||
const out = read(dir)
|
||||
assert.match(out, /^extends: default$/m)
|
||||
assert.doesNotMatch(out, /pageTitle/) // the merged configuration is not written back
|
||||
const data = YAML.parse(out)
|
||||
assert.deepStrictEqual(data.plugins, [
|
||||
// the base sets both: null drops them from the merged options, so the plugin's defaults
|
||||
// apply (the user's own depth: 3 is gone too)
|
||||
{ source: "@quartz-community/graph", options: { depth: null, scale: null }, enabled: false },
|
||||
{ source: "@quartz-community/comments", enabled: true },
|
||||
])
|
||||
})
|
||||
|
||||
test("remove refuses a plugin that comes from a base", () => {
|
||||
const dir = site()
|
||||
const { output, status } = run(dir, "plugin remove comments")
|
||||
assert.match(output, /comes from the configuration/)
|
||||
assert.strictEqual(status, 1)
|
||||
assert.doesNotMatch(read(dir), /comments/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { h } from "preact"
|
||||
import { render } from "preact-render-to-string"
|
||||
import HeadConstructor from "./Head"
|
||||
import type { QuartzComponentProps } from "./types"
|
||||
|
||||
const Head = HeadConstructor()
|
||||
|
||||
function head(fileData: Record<string, unknown>): string {
|
||||
const props = {
|
||||
cfg: {
|
||||
pageTitle: "Site",
|
||||
baseUrl: "example.org",
|
||||
locale: "en-US",
|
||||
theme: { cdnCaching: false, typography: {} },
|
||||
},
|
||||
fileData: { relativePath: `${fileData.slug}.md`, frontmatter: { title: "T" }, ...fileData },
|
||||
externalResources: { css: [], js: [], additionalHead: [] },
|
||||
ctx: { cfg: { plugins: { emitters: [] } } },
|
||||
} as unknown as QuartzComponentProps
|
||||
return render(h(Head, props))
|
||||
}
|
||||
const meta = (html: string, property: string) =>
|
||||
new RegExp(`<meta property="${property}" content="([^"]*)"`).exec(html)?.[1]
|
||||
|
||||
describe("Head", () => {
|
||||
test("a note whose name ends in 'index' is an article; index pages are not", () => {
|
||||
assert.strictEqual(meta(head({ slug: "reindex" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "notes/reindex" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "index" }), "og:type"), "website")
|
||||
assert.strictEqual(meta(head({ slug: "notes/index" }), "og:type"), "website")
|
||||
})
|
||||
|
||||
test("article dates: only real ones (no build-time stand-ins, no invalid published:)", () => {
|
||||
const now = new Date()
|
||||
const real = new Date("2024-05-06T00:00:00")
|
||||
const modified = new Date("2025-01-02T03:04:05.000Z")
|
||||
// created-modified-date >= 1.0.5 marks the stand-ins
|
||||
let html = head({
|
||||
slug: "a",
|
||||
dates: { created: now, modified, published: now },
|
||||
fallbackDates: ["published"],
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), undefined)
|
||||
assert.strictEqual(meta(html, "article:modified_time"), modified.toISOString())
|
||||
// older versions: an invalid `published:` gave the build time
|
||||
html = head({
|
||||
slug: "a",
|
||||
frontmatter: { title: "T", published: "not a date" },
|
||||
dates: { created: now, modified, published: now },
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), undefined)
|
||||
html = head({
|
||||
slug: "a",
|
||||
frontmatter: { title: "T", published: "2024-05-06" },
|
||||
dates: { created: now, modified, published: real },
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:published_time"), real.toISOString())
|
||||
html = head({
|
||||
slug: "a",
|
||||
dates: { created: now, modified: now, published: now },
|
||||
fallbackDates: ["modified", "published"],
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:modified_time"), undefined)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/re
|
||||
import { googleFontHref, googleFontSubsetHref } from "../util/theme"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import { unescapeHTML } from "../util/escape"
|
||||
import { realDate } from "../util/dates"
|
||||
|
||||
export default (() => {
|
||||
const Head: QuartzComponent = ({
|
||||
@@ -37,14 +38,13 @@ export default (() => {
|
||||
const isArticle =
|
||||
!isNotFound &&
|
||||
fileData.relativePath !== undefined &&
|
||||
!fileData.slug!.endsWith("index") &&
|
||||
fileData.slug !== "index" &&
|
||||
!fileData.slug!.endsWith("/index") &&
|
||||
!fileData.slug!.startsWith("tags/")
|
||||
const isoDate = (d: unknown) =>
|
||||
d instanceof Date && !isNaN(d.getTime()) ? d.toISOString() : undefined
|
||||
// Without a frontmatter date, the published date is only the build time.
|
||||
const published =
|
||||
isArticle && fileData.frontmatter?.published ? isoDate(fileData.dates?.published) : undefined
|
||||
const modified = isArticle ? isoDate(fileData.dates?.modified) : undefined
|
||||
// Real dates only: a date no source gave is the build time (see util/dates), and an
|
||||
// invalid `published:` gives none.
|
||||
const published = isArticle ? realDate(fileData, "published")?.toISOString() : undefined
|
||||
const modified = isArticle ? realDate(fileData, "modified")?.toISOString() : undefined
|
||||
|
||||
const usesCustomOgImage = ctx.cfg.plugins.emitters.some((e) => e.name === "CustomOgImages")
|
||||
const ogImageDefaultPath = `https://${cfg.baseUrl}/static/og-image.png`
|
||||
|
||||
@@ -7,6 +7,7 @@ import { VFile } from "vfile"
|
||||
import { Element, Root, Text } from "hast"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { BUILTINS, instantiateBuiltins, officialPluginName, planBuiltins, PlanInput } from "."
|
||||
import { normalizePluginName, orderPlugins } from "../loader/plugin-order"
|
||||
import {
|
||||
Frontmatter,
|
||||
normalizeFrontmatter,
|
||||
@@ -181,6 +182,39 @@ describe("planBuiltins", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin order constraints naming a replaced plugin", () => {
|
||||
test("after: crawl-links / before: remove-draft order against the built-in", () => {
|
||||
const transformers = instantiateBuiltins(plan([]), "transformer")
|
||||
const links = transformers.find((b) => b.instance.name === "Links")!
|
||||
assert.ok(links.names.includes("crawl-links"))
|
||||
const known = new Set(
|
||||
[...transformers.flatMap((b) => b.names), "my-plugin"].map(normalizePluginName),
|
||||
)
|
||||
// same order as Links (60): without the mapping the constraint was ignored and the list
|
||||
// order (built-ins first) put Links first anyway, so run it before
|
||||
const mine = {
|
||||
order: 60,
|
||||
instance: { name: "Mine" },
|
||||
label: "my-plugin",
|
||||
names: ["my-plugin"],
|
||||
before: ["crawl-links"],
|
||||
}
|
||||
const ordered = orderPlugins(
|
||||
[
|
||||
...transformers.map((b) => ({
|
||||
order: b.order,
|
||||
instance: b.instance as { name: string },
|
||||
label: b.instance.name,
|
||||
names: b.names,
|
||||
})),
|
||||
mine,
|
||||
],
|
||||
known,
|
||||
).map((i) => i.name)
|
||||
assert.ok(ordered.indexOf("Mine") < ordered.indexOf("Links"), ordered.join(", "))
|
||||
})
|
||||
})
|
||||
|
||||
describe("frontmatter built-in", () => {
|
||||
const ctx = () => ({ allSlugs: [] as FullSlug[] }) as unknown as BuildCtx
|
||||
|
||||
@@ -235,6 +269,35 @@ describe("frontmatter built-in", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("frontmatter Markdown links: parentheses, titles and escapes as CommonMark reads them (#2672)", () => {
|
||||
assert.deepStrictEqual(
|
||||
extractLinksFromValue([
|
||||
"[b](<Note (2024).md>)",
|
||||
'[c](<My Note.md> "t")',
|
||||
"[d](notes/Note_(2024).md)",
|
||||
"[e](other.md 'single')",
|
||||
"[f](other.md (paren title))",
|
||||
'[g](<a b.md> "t" )',
|
||||
"[h](a\\(1\\).md)",
|
||||
"[i](./My Note.md)",
|
||||
"[j](unclosed.md",
|
||||
"two: [k](k.md) and [l](<l l.md>)",
|
||||
]),
|
||||
[
|
||||
"Note (2024).md",
|
||||
"My Note.md",
|
||||
"notes/Note_(2024).md",
|
||||
"other.md",
|
||||
"other.md",
|
||||
"a b.md",
|
||||
"a(1).md",
|
||||
"./My Note.md",
|
||||
"k.md",
|
||||
"l l.md",
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("reads YAML frontmatter with YAML 1.2's core schema, as Obsidian does", () => {
|
||||
const data = readFrontmatterData(
|
||||
"---\ntitle: Hello world\ndate: 2024-01-02\ndraft: True\nn: 012\nnone: ~\nratio: .5\nalias: yes\n---\n",
|
||||
@@ -532,6 +595,42 @@ describe("links built-in", () => {
|
||||
assert.deepStrictEqual(broken, [false, false, true])
|
||||
})
|
||||
|
||||
test("links to files Quartz emits are not broken; missing vault files are", () => {
|
||||
const targets = [
|
||||
"/index.xml",
|
||||
"/sitemap.xml",
|
||||
"/static/icon.png",
|
||||
"/robots.txt",
|
||||
"/404.html",
|
||||
"/page.html",
|
||||
"/pic.png",
|
||||
"/missing.png",
|
||||
"/missing.pdf",
|
||||
"/missing.html",
|
||||
"/v1.2",
|
||||
]
|
||||
const { els } = run(
|
||||
targets.map((t) => a(t)),
|
||||
"page",
|
||||
{},
|
||||
["page", "pic.png"],
|
||||
)
|
||||
const broken = els.map((e) => (e.properties.className as string[]).includes("broken"))
|
||||
assert.deepStrictEqual(broken, [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
])
|
||||
})
|
||||
|
||||
test("disableBrokenWikilinks: false leaves missing targets unmarked", () => {
|
||||
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: false }, ["page"])
|
||||
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
|
||||
@@ -643,6 +742,48 @@ describe("content index built-in", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("stand-in dates of the date plugin are not written to contentIndex.json", () => {
|
||||
const now = new Date()
|
||||
const published = new Date("2024-05-06T00:00:00")
|
||||
const json = JSON.parse(
|
||||
serializeContentIndex(
|
||||
buildContentIndex(ctxWith([]), [
|
||||
// created-modified-date >= 1.0.5 lists the dates it filled with the build time
|
||||
page("marked", {
|
||||
defaultDateType: "published",
|
||||
dates: { created: now, modified: now, published: now },
|
||||
fallbackDates: ["published"],
|
||||
}),
|
||||
// older versions don't: a published date only counts when frontmatter sets it
|
||||
page("old", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "OLD" },
|
||||
dates: { created: now, modified: now, published: now },
|
||||
}),
|
||||
page("invalid", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "INV", published: "not a date" },
|
||||
dates: { created: now, modified: now, published: now },
|
||||
}),
|
||||
page("real", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "REAL", published: "2024-05-06" },
|
||||
dates: { created: now, modified: now, published },
|
||||
fallbackDates: [],
|
||||
}),
|
||||
page("oldReal", {
|
||||
defaultDateType: "published",
|
||||
frontmatter: { title: "OR", published: "2024-05-06" },
|
||||
dates: { created: now, modified: now, published },
|
||||
}),
|
||||
]),
|
||||
),
|
||||
)
|
||||
for (const slug of ["marked", "old", "invalid"]) assert.ok(!("date" in json[slug]), slug)
|
||||
assert.strictEqual(json.real.date, published.toISOString())
|
||||
assert.strictEqual(json.oldReal.date, published.toISOString())
|
||||
})
|
||||
|
||||
test("plugins add fields through extendContentIndex", () => {
|
||||
const ctx = ctxWith([
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@ import fs from "node:fs/promises"
|
||||
import { Root } from "hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import { styleText } from "util"
|
||||
import { getDate } from "@quartz-community/utils"
|
||||
import { dateIsFromFrontmatter as dateIsFromFrontmatterOfType, realDate } from "../../util/dates"
|
||||
import { ContentIndexConfig, GlobalConfiguration } from "../../cfg"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { escapeHTML } from "../../util/escape"
|
||||
@@ -152,7 +152,8 @@ export function prepareContentIndex(ctx: BuildCtx, content: ProcessedContent[]):
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages without a date get the build time, so RSS and the sitemap keep working as before.
|
||||
* Pages without a date, or with one the date plugin filled in with the build time (its
|
||||
* `fallbackDates`), 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).
|
||||
*/
|
||||
@@ -164,32 +165,19 @@ function buildTimeDate(): Date {
|
||||
}
|
||||
|
||||
function entryDate(data: QuartzPluginData): Date {
|
||||
const date = getDate(data as Parameters<typeof getDate>[0])
|
||||
// a stand-in date of the date plugin (fallbackDates) is a build-time date as well
|
||||
const date = realDate(data, data.defaultDateType as string | undefined)
|
||||
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.
|
||||
* (`defaultDateType`). See util/dates.
|
||||
*/
|
||||
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()
|
||||
return dateIsFromFrontmatterOfType(data, date)
|
||||
}
|
||||
|
||||
/** Pages whose date came from frontmatter (see dateIsFromFrontmatter). */
|
||||
|
||||
@@ -67,7 +67,76 @@ export function slugifyWikilinkTarget(target: string): string {
|
||||
}
|
||||
|
||||
const WIKILINK_PATTERN = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g
|
||||
const MDLINK_PATTERN = /\[(?:[^\]]*)\]\(([^)]+)\)/g
|
||||
/** The start of a Markdown link: `[text](`; the destination is parsed by markdownLinkTarget. */
|
||||
const MDLINK_START = /\[(?:[^\]]*)\]\(/g
|
||||
|
||||
const ASCII_PUNCTUATION = /[!-/:-@[-`{-~]/
|
||||
const isSpace = (c: string | undefined) => c === " " || c === "\t" || c === "\n" || c === "\r"
|
||||
/** CommonMark backslash escapes: `\(` → `(` (only before ASCII punctuation). */
|
||||
const unescapeLink = (s: string) => s.replace(/\\([!-/:-@[-`{-~])/g, "$1")
|
||||
|
||||
/**
|
||||
* The destination of the Markdown link whose `(` ends at `start` in `s`, as CommonMark reads
|
||||
* it: `<…>` (may hold spaces and parentheses) or a plain destination (ends at a space or an
|
||||
* unbalanced `)`), then an optional title in `"…"`, `'…'` or `(…)`. A plain destination
|
||||
* with spaces that isn't followed by a title (`[x](./My Note.md)`, which Obsidian accepts)
|
||||
* runs to the closing `)`. Returns undefined when there is no closing `)`.
|
||||
*/
|
||||
export function markdownLinkTarget(s: string, start: number): string | undefined {
|
||||
let i = start
|
||||
while (isSpace(s[i])) i++
|
||||
const destStart = i
|
||||
let dest: string
|
||||
if (s[i] === "<") {
|
||||
let j = i + 1
|
||||
while (j < s.length && s[j] !== ">" && s[j] !== "<" && s[j] !== "\n") {
|
||||
j += s[j] === "\\" && ASCII_PUNCTUATION.test(s[j + 1] ?? "") ? 2 : 1
|
||||
}
|
||||
if (s[j] !== ">") return undefined
|
||||
dest = unescapeLink(s.slice(i + 1, j))
|
||||
i = j + 1
|
||||
} else {
|
||||
let depth = 0
|
||||
while (i < s.length) {
|
||||
const c = s[i]
|
||||
if (c === "\\" && ASCII_PUNCTUATION.test(s[i + 1] ?? "")) {
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (isSpace(c)) break
|
||||
if (c === "(") depth++
|
||||
else if (c === ")") {
|
||||
if (depth === 0) break
|
||||
depth--
|
||||
}
|
||||
i++
|
||||
}
|
||||
dest = unescapeLink(s.slice(destStart, i))
|
||||
}
|
||||
while (isSpace(s[i])) i++
|
||||
if (s[i] === ")") return dest
|
||||
const close = s[i] === '"' ? '"' : s[i] === "'" ? "'" : s[i] === "(" ? ")" : undefined
|
||||
if (close) {
|
||||
let j = i + 1
|
||||
while (j < s.length && s[j] !== close) {
|
||||
j += s[j] === "\\" && ASCII_PUNCTUATION.test(s[j + 1] ?? "") ? 2 : 1
|
||||
}
|
||||
let k = j + 1
|
||||
while (isSpace(s[k])) k++
|
||||
if (j < s.length && s[k] === ")") return dest
|
||||
}
|
||||
if (s[destStart] === "<") return undefined
|
||||
// lenient: a plain destination with spaces, up to the `)` that closes the link
|
||||
let depth = 0
|
||||
for (let j = destStart; j < s.length; j++) {
|
||||
if (s[j] === "(") depth++
|
||||
else if (s[j] === ")") {
|
||||
if (depth === 0) return unescapeLink(s.slice(destStart, j).trim())
|
||||
depth--
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** All link targets (wikilinks and Markdown links) inside a frontmatter value, recursively. */
|
||||
export function extractLinksFromValue(value: unknown): string[] {
|
||||
@@ -75,11 +144,11 @@ export function extractLinksFromValue(value: unknown): string[] {
|
||||
const links: string[] = []
|
||||
for (const match of value.matchAll(WIKILINK_PATTERN))
|
||||
links.push(slugifyWikilinkTarget(match[1]!))
|
||||
for (const match of value.matchAll(MDLINK_PATTERN)) {
|
||||
// `[x](<./My Note.md>)`: CommonMark's angle-bracket destination, which
|
||||
// Obsidian writes for paths with spaces. The brackets aren't part of it.
|
||||
const dest = match[1]!.trim()
|
||||
links.push(dest.startsWith("<") && dest.endsWith(">") ? dest.slice(1, -1) : dest)
|
||||
for (const match of value.matchAll(MDLINK_START)) {
|
||||
// `[x](<./My Note.md> "title")`: angle-bracket destinations (which Obsidian writes for
|
||||
// paths with spaces), balanced parentheses and titles, as CommonMark reads them
|
||||
const dest = markdownLinkTarget(value, match.index! + match[0].length)
|
||||
if (dest) links.push(dest)
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ export function planBuiltins(input: PlanInput): BuiltinPlan {
|
||||
export function instantiateBuiltins<C extends BuiltinCategory>(
|
||||
plan: BuiltinPlan,
|
||||
category: C,
|
||||
): { order: number; instance: BuiltinInstance }[] {
|
||||
): { order: number; instance: BuiltinInstance; names: string[] }[] {
|
||||
return (
|
||||
plan.builtins
|
||||
.filter((b) => b.enabled && b.spec.category === category)
|
||||
@@ -318,7 +318,13 @@ export function instantiateBuiltins<C extends BuiltinCategory>(
|
||||
category: b.spec.category,
|
||||
builtin: true,
|
||||
})
|
||||
return { order: b.order, instance }
|
||||
// `before`/`after` may name the built-in by its config key or by the plugin it
|
||||
// replaced (`after: crawl-links` is `after: links`)
|
||||
return {
|
||||
order: b.order,
|
||||
instance,
|
||||
names: [instance.name, b.spec.configKey, ...b.spec.absorbs],
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -89,6 +89,31 @@ export function pageExists(allSlugs: readonly string[], full: string): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/** File types Obsidian opens from the vault (embeds and attachments): a link to one that the content doesn't have names a missing file. */
|
||||
const VAULT_FILE_TYPES = new Set(
|
||||
"avif bmp gif jpeg jpg png svg webp flac m4a mp3 ogg wav 3gp mkv mov mp4 ogv webm pdf canvas base".split(
|
||||
" ",
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether an internal link target is known to be missing, so it gets the `broken` class.
|
||||
* Only targets Quartz can check are: pages (see pageExists) and files of the types a vault
|
||||
* holds (images, audio, video, PDFs, canvases, bases), which the content copies as assets.
|
||||
* Anything else may be a file Quartz or a plugin emits and the transformers can't know about
|
||||
* (`index.xml`, `sitemap.xml`, `robots.txt`, `static/…`, og images), so it is not marked.
|
||||
*/
|
||||
export function linkTargetMissing(allSlugs: readonly string[], full: string): boolean {
|
||||
// the not-found page is always emitted (`.html` is dropped from links like `.md`)
|
||||
if (full === "404" || pageExists(allSlugs, full)) return false
|
||||
// quartz/static and plugin assets are served at static/
|
||||
if (full.startsWith("static/")) return false
|
||||
const name = full.slice(full.lastIndexOf("/") + 1)
|
||||
const ext = /\.([a-z][a-z0-9]{0,9})$/i.exec(name)?.[1]?.toLowerCase()
|
||||
if (ext === undefined) return true
|
||||
return VAULT_FILE_TYPES.has(ext)
|
||||
}
|
||||
|
||||
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
|
||||
const FILTERED_ATTR = "data-filtered"
|
||||
|
||||
@@ -278,7 +303,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
outgoing.add(simplifySlug(full))
|
||||
node.properties["data-slug"] = full
|
||||
|
||||
if (opts.disableBrokenWikilinks && !pageExists(ctx.allSlugs, full)) {
|
||||
if (opts.disableBrokenWikilinks && linkTargetMissing(ctx.allSlugs, full)) {
|
||||
classes.push("broken")
|
||||
node.properties.className = classes
|
||||
}
|
||||
|
||||
@@ -76,6 +76,13 @@ describe("index conditions (#2465)", () => {
|
||||
assert.strictEqual(run("is-folder-index", "folder/indexes"), false)
|
||||
assert.strictEqual(run("is-folder-index", undefined), false)
|
||||
})
|
||||
|
||||
test("is-folder-index is false on tag pages (the all-tags page is tags/index)", () => {
|
||||
assert.strictEqual(run("is-folder-index", "tags/index"), false)
|
||||
assert.strictEqual(run("is-folder-index", "tags/a/index"), false)
|
||||
assert.strictEqual(run("is-folder-index", "tags/a"), false)
|
||||
assert.strictEqual(run("is-folder-index", "my-tags/index"), true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("not-<condition> negation", () => {
|
||||
|
||||
@@ -7,9 +7,11 @@ 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.
|
||||
// Tag pages aren't folders: `tags/` belongs to them (the all-tags page `tags/index`, and
|
||||
// `tags/<tag>` pages), so nothing under it is a folder index.
|
||||
"is-folder-index": (props) => {
|
||||
const slug = props.fileData.slug
|
||||
return typeof slug === "string" && slug.endsWith("/index")
|
||||
return typeof slug === "string" && slug.endsWith("/index") && !slug.startsWith("tags/")
|
||||
},
|
||||
"has-tags": (props) => {
|
||||
const tags = props.fileData.frontmatter?.tags
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
deepMerge,
|
||||
mergeQuartzConfigs,
|
||||
pluginMatchKey,
|
||||
localExtendsFiles,
|
||||
resolveExtends,
|
||||
resolveTarget,
|
||||
fetchRemoteConfig,
|
||||
@@ -70,6 +71,41 @@ describe("pluginMatchKey", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("pluginMatchKey for monorepo subdirectories", () => {
|
||||
test("two plugins of one repository without a name get different keys", () => {
|
||||
const a = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/a" })
|
||||
const b = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/b" })
|
||||
assert.notStrictEqual(a, b)
|
||||
assert.strictEqual(a, "quartz-plugins/plugins/a")
|
||||
})
|
||||
test("subdir spellings are normalised", () => {
|
||||
for (const subdir of ["plugins/a", "./plugins/a/", "plugins\\a", "/plugins//a"]) {
|
||||
assert.strictEqual(
|
||||
pluginMatchKey({ repo: "https://github.com/me/quartz-plugins.git", subdir }),
|
||||
"quartz-plugins/plugins/a",
|
||||
subdir,
|
||||
)
|
||||
}
|
||||
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer", subdir: "." }), "explorer")
|
||||
})
|
||||
test("an overlay entry for one monorepo plugin leaves the other alone", () => {
|
||||
const merged = mergeQuartzConfigs(
|
||||
{
|
||||
configuration: {},
|
||||
plugins: [
|
||||
{ source: { repo: "github:me/mono", subdir: "a" }, enabled: true },
|
||||
{ source: { repo: "github:me/mono", subdir: "b" }, enabled: true },
|
||||
],
|
||||
},
|
||||
{ plugins: [{ source: { repo: "github:me/mono", subdir: "b" }, enabled: false }] },
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
merged.plugins.map((p) => p.enabled),
|
||||
[true, false],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("mergeQuartzConfigs", () => {
|
||||
test("configuration deep-merges; arrays replace; null resets a key", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
@@ -227,6 +263,89 @@ describe("resolveExtends", () => {
|
||||
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
|
||||
})
|
||||
|
||||
test("presets stack: each listed base adds its own changes; a shared base applies once", async () => {
|
||||
put("presets/title.yaml", {
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Preset A", locale: "fr-FR" },
|
||||
plugins: [{ source: "@quartz-community/graph", enabled: false }],
|
||||
})
|
||||
put("presets/explorer.yaml", {
|
||||
extends: "default",
|
||||
configuration: { locale: "nl-NL" },
|
||||
plugins: [{ source: "@quartz-community/explorer", options: { b: 2 } }],
|
||||
})
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["./presets/title.yaml", "./presets/explorer.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
// a's changes survive b (both extend default)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Preset A")
|
||||
assert.strictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
|
||||
false,
|
||||
)
|
||||
// b wins where both change something
|
||||
assert.strictEqual(merged.configuration.locale, "nl-NL")
|
||||
assert.deepStrictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "explorer")!.options,
|
||||
{ a: 1, nested: { x: 1 }, b: 2 },
|
||||
)
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("diamond: a base reached twice is applied once, at its first appearance", async () => {
|
||||
put("d/common.yaml", { extends: "default", configuration: { locale: "common" } })
|
||||
put("d/left.yaml", { extends: "./common.yaml", configuration: { pageTitle: "Left" } })
|
||||
put("d/right.yaml", { extends: "./common.yaml", configuration: { baseUrl: "right.org" } })
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["./d/left.yaml", "./d/right.yaml", "./d/left.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Left")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "right.org")
|
||||
assert.strictEqual(merged.configuration.locale, "common")
|
||||
assert.deepStrictEqual(
|
||||
await localExtendsFiles(
|
||||
{ extends: ["./d/left.yaml", "./d/right.yaml"] },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
),
|
||||
["quartz.config.default.yaml", "d/common.yaml", "d/left.yaml", "d/right.yaml"].map((f) =>
|
||||
path.join(root, f),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: [] is no base; an empty base file is an empty config", async () => {
|
||||
const data = { extends: [], configuration: { pageTitle: "x" }, plugins: [] }
|
||||
assert.deepStrictEqual(await resolveExtends(data, path.join(root, "quartz.config.yaml")), {
|
||||
configuration: { pageTitle: "x" },
|
||||
plugins: [],
|
||||
})
|
||||
files[path.join(root, "empty.yaml")] = "# nothing here yet\n"
|
||||
const merged = await resolveExtends(
|
||||
{ extends: ["default", "./empty.yaml"], configuration: { pageTitle: "E" } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "E")
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("plugins that are not a list are reported clearly", async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends(
|
||||
{ extends: "default", plugins: { explorer: { enabled: false } } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
),
|
||||
(err: Error) => err instanceof ConfigExtendsError && /must be a list/.test(err.message),
|
||||
)
|
||||
})
|
||||
|
||||
test("cycles and missing files are reported", async () => {
|
||||
put("a.yaml", { extends: "./b.yaml" })
|
||||
put("b.yaml", { extends: "./a.yaml" })
|
||||
@@ -292,6 +411,15 @@ describe("resolveExtends", () => {
|
||||
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
|
||||
})
|
||||
|
||||
test("uppercase HTTPS:// is https", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{ extends: "HTTPS://CFG.example/base/site.yaml" },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
opts(),
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Remote")
|
||||
})
|
||||
|
||||
test("only https", async () => {
|
||||
await assert.rejects(
|
||||
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
|
||||
|
||||
@@ -35,6 +35,8 @@ import type {
|
||||
* 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`.
|
||||
* - `extends` lists stack (see resolveExtends): every file of the graph is applied once, after
|
||||
* its bases, so presets that share `default` each keep their own changes.
|
||||
* - A config without `extends` is used exactly as written, as before.
|
||||
*/
|
||||
|
||||
@@ -98,20 +100,35 @@ export function deepMerge(base: unknown, overlay: unknown): unknown {
|
||||
/**
|
||||
* 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.
|
||||
* `explorer`), or the `name` of an object source. An object source without a `name` that
|
||||
* points at a `subdir` of a repository is matched by both (`plugins/explorer` in
|
||||
* `github:me/quartz-plugins` → `quartz-plugins/plugins/explorer`), so two plugins of one
|
||||
* monorepo stay apart.
|
||||
*/
|
||||
export function pluginMatchKey(source: PluginSource): string {
|
||||
if (typeof source === "object" && source !== null) {
|
||||
if (source.name) return source.name
|
||||
return pluginMatchKey(source.repo)
|
||||
const repoKey = pluginMatchKey(source.repo)
|
||||
const subdir = normalizeSubdir(source.subdir)
|
||||
return subdir ? `${repoKey}/${subdir}` : repoKey
|
||||
}
|
||||
let s = String(source).trim()
|
||||
s = s.replace(/^git\+/, "").replace(/^github:/, "")
|
||||
s = s.replace(/^git\+/i, "").replace(/^github:/i, "")
|
||||
s = s.split("#")[0]
|
||||
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
|
||||
s = s.replace(/\.git$/i, "").replace(/[\\/]+$/, "")
|
||||
// an npm version/range: @scope/name@1.2.3, name@^1
|
||||
s = s.replace(/(.)@[^/]*$/, "$1")
|
||||
return s.slice(s.lastIndexOf("/") + 1)
|
||||
return s.slice(Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\")) + 1)
|
||||
}
|
||||
|
||||
/** `./plugins/x/`, `plugins\\x`, `/plugins/x` → `plugins/x`; empty or `.` → "". */
|
||||
function normalizeSubdir(subdir: unknown): string {
|
||||
if (typeof subdir !== "string") return ""
|
||||
return subdir
|
||||
.replace(/\\/g, "/")
|
||||
.split("/")
|
||||
.filter((part) => part !== "" && part !== ".")
|
||||
.join("/")
|
||||
}
|
||||
|
||||
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
|
||||
@@ -131,6 +148,16 @@ function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
|
||||
return merged as unknown as PluginJsonEntry
|
||||
}
|
||||
|
||||
function pluginList<T>(value: T[] | null | undefined, where: string): T[] {
|
||||
if (value === undefined || value === null) return []
|
||||
if (!Array.isArray(value)) {
|
||||
throw new ConfigExtendsError(
|
||||
`"plugins" in ${where} must be a list of plugin entries (- source: …), not ${typeof value === "object" ? "an object" : JSON.stringify(value)}`,
|
||||
)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
|
||||
export function mergeQuartzConfigs(
|
||||
base: QuartzPluginsJson,
|
||||
@@ -142,8 +169,8 @@ export function mergeQuartzConfigs(
|
||||
{ ...rest, plugins: undefined },
|
||||
) as QuartzPluginsJson
|
||||
|
||||
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
|
||||
for (const entry of overlayPlugins ?? []) {
|
||||
const plugins = pluginList(base.plugins, "the base config").map((entry) => ({ ...entry }))
|
||||
for (const entry of pluginList(overlayPlugins, "the extending config")) {
|
||||
if (!entry || entry.source === undefined) {
|
||||
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
|
||||
}
|
||||
@@ -176,6 +203,7 @@ const REMOTE_TIMEOUT_MS = 10_000
|
||||
const REMOTE_MAX_BYTES = 1024 * 1024
|
||||
|
||||
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
|
||||
const isHttps = (s: string) => /^https:\/\//i.test(s)
|
||||
|
||||
function remoteCacheFile(url: string, cacheDir: string): string {
|
||||
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
|
||||
@@ -235,7 +263,7 @@ async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOpt
|
||||
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
|
||||
headers: { accept: "application/yaml, application/json, text/plain, */*" },
|
||||
})
|
||||
if (res.url && !res.url.startsWith("https://")) {
|
||||
if (res.url && !isHttps(res.url)) {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
|
||||
}
|
||||
if (!res.ok) {
|
||||
@@ -263,6 +291,8 @@ async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOpt
|
||||
|
||||
function parseConfigFile(file: string, raw: string): PlainObject {
|
||||
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
|
||||
// an empty file (or one with only comments) is an empty config
|
||||
if (data === null || data === undefined) return {}
|
||||
if (!isPlainObject(data)) {
|
||||
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
|
||||
}
|
||||
@@ -281,6 +311,14 @@ function extendsTargets(value: unknown, file: string): string[] {
|
||||
return list as string[]
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
try {
|
||||
return new URL(url).href
|
||||
} catch {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" is not a valid URL`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -290,12 +328,13 @@ function extendsTargets(value: unknown, file: string): string[] {
|
||||
*/
|
||||
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
|
||||
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
|
||||
// URLs are normalised (`HTTPS://Example.org/x` → `https://example.org/x`)
|
||||
const resolved = isUrl(target)
|
||||
? target
|
||||
? normalizeUrl(target)
|
||||
: isUrl(from)
|
||||
? new URL(target, from).href
|
||||
: path.resolve(path.dirname(from), target)
|
||||
if (isUrl(resolved) && !resolved.startsWith("https://")) {
|
||||
if (isUrl(resolved) && !isHttps(resolved)) {
|
||||
throw new ConfigExtendsError(
|
||||
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
|
||||
)
|
||||
@@ -303,56 +342,111 @@ export function resolveTarget(target: string, from: string, quartzRoot: string):
|
||||
return resolved
|
||||
}
|
||||
|
||||
interface ConfigLayer {
|
||||
/** Resolved path or URL ("" for the config being resolved). */
|
||||
file: string
|
||||
/** The file's own content, without `extends`. */
|
||||
data: PlainObject
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Apply `extends` of `data` (read from `file`, a path or URL) and return the merged config.
|
||||
* Returns `data` itself when it has no `extends` (or an empty list), so configs without it
|
||||
* behave exactly as before.
|
||||
*
|
||||
* Every file in the `extends` graph is a layer of its own changes, applied once, after all of
|
||||
* its bases (depth first, in list order). A base that several entries share (usually
|
||||
* `default`) is applied at its first appearance, so for `extends: [./a.yaml, ./b.yaml]` where
|
||||
* both extend `default` the order is default → a → b → this file: what a.yaml changes stays
|
||||
* unless b.yaml changes the same thing (later entries win), and this file wins over all.
|
||||
*/
|
||||
export async function resolveExtends(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions = {},
|
||||
seen: string[] = [],
|
||||
): Promise<QuartzPluginsJson> {
|
||||
if (data.extends === undefined || data.extends === null) {
|
||||
const targets = data.extends === undefined || data.extends === null ? [] : data.extends
|
||||
if (Array.isArray(targets) && targets.length === 0) {
|
||||
const { extends: _drop, ...rest } = data
|
||||
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
|
||||
return ("extends" in data ? rest : data) as unknown as QuartzPluginsJson
|
||||
}
|
||||
const layers = await extendsLayers(data, file, options)
|
||||
const [first, ...rest] = layers
|
||||
let merged = first.data as unknown as QuartzPluginsJson
|
||||
pluginList(merged.plugins, first.file)
|
||||
for (const layer of rest) {
|
||||
merged = mergeQuartzConfigs(merged, layer.data as QuartzConfigOverlay)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* The local files (absolute paths) `data` extends, directly or through other bases; URLs are
|
||||
* left out. For `--serve`, which rebuilds when one of them changes.
|
||||
*/
|
||||
export async function localExtendsFiles(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions = {},
|
||||
): Promise<string[]> {
|
||||
if (data.extends === undefined || data.extends === null) return []
|
||||
const layers = await extendsLayers(data, file, options)
|
||||
return layers.map((l) => l.file).filter((f) => f !== "" && !isUrl(f))
|
||||
}
|
||||
|
||||
/** The layers of `data` in the order they are applied: bases first, `data` itself last. */
|
||||
async function extendsLayers(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions,
|
||||
): Promise<ConfigLayer[]> {
|
||||
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]
|
||||
const layers: ConfigLayer[] = []
|
||||
const applied = new Set<string>()
|
||||
|
||||
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 visit = async (node: PlainObject, nodeFile: string, chain: string[]) => {
|
||||
const self = isUrl(nodeFile) ? nodeFile : path.resolve(nodeFile)
|
||||
const here = [...chain, self]
|
||||
const raw = node.extends
|
||||
const targets = raw === undefined || raw === null ? [] : extendsTargets(raw, nodeFile)
|
||||
for (const target of targets) {
|
||||
const targetFile = resolveTarget(target, nodeFile, quartzRoot)
|
||||
if (here.includes(targetFile)) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends" cycle: ${[...here, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
|
||||
)
|
||||
}
|
||||
if (applied.has(targetFile)) continue
|
||||
let text: string
|
||||
if (isUrl(targetFile)) {
|
||||
text = await fetchRemote(targetFile)
|
||||
} else {
|
||||
try {
|
||||
text = readFile(targetFile)
|
||||
} catch {
|
||||
throw new ConfigExtendsError(
|
||||
`${nodeFile}: "extends: ${target}" — ${targetFile} not found`,
|
||||
)
|
||||
}
|
||||
}
|
||||
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
|
||||
let parsed: PlainObject
|
||||
try {
|
||||
parsed = parseConfigFile(parsePath, text)
|
||||
} catch (err) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
|
||||
)
|
||||
}
|
||||
await visit(parsed, targetFile, here)
|
||||
}
|
||||
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
|
||||
const { extends: _drop, ...own } = node
|
||||
layers.push({ file: chain.length === 0 ? "" : self, data: own })
|
||||
applied.add(self)
|
||||
}
|
||||
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
|
||||
|
||||
await visit(data, file, [])
|
||||
return layers
|
||||
}
|
||||
@@ -758,7 +758,7 @@ export async function loadQuartzConfig(
|
||||
const knownPluginNames = new Set(
|
||||
[
|
||||
...json.plugins.map((e) => extractPluginName(e.source)),
|
||||
...builtinPlan.builtins.map((b) => b.spec.configKey),
|
||||
...builtinPlan.builtins.flatMap((b) => [b.spec.configKey, ...b.spec.absorbs]),
|
||||
"Frontmatter",
|
||||
"Links",
|
||||
"Drafts",
|
||||
@@ -767,14 +767,14 @@ export async function loadQuartzConfig(
|
||||
].map(normalizePluginName),
|
||||
)
|
||||
const withBuiltins = <T>(
|
||||
builtins: { order: number; instance: unknown }[],
|
||||
builtins: { order: number; instance: unknown; names?: string[] }[],
|
||||
instances: OrderItem<T>[],
|
||||
): T[] =>
|
||||
orderPlugins(
|
||||
[
|
||||
...builtins.map(({ order, instance }) => {
|
||||
...builtins.map(({ order, instance, names }) => {
|
||||
const name = (instance as { name: string }).name
|
||||
return { order, instance: instance as T, label: name, names: [name] }
|
||||
return { order, instance: instance as T, label: name, names: names ?? [name] }
|
||||
}),
|
||||
...instances,
|
||||
],
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { realDate } from "./dates"
|
||||
import type { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
const data = (d: Record<string, unknown>) => d as unknown as QuartzPluginData
|
||||
|
||||
describe("realDate", () => {
|
||||
const now = new Date()
|
||||
const fm = new Date("2024-05-06T00:00:00")
|
||||
|
||||
test("drops dates the date plugin lists in fallbackDates", () => {
|
||||
const d = data({ dates: { modified: now, published: now }, fallbackDates: ["published"] })
|
||||
assert.strictEqual(realDate(d, "published"), undefined)
|
||||
assert.strictEqual(realDate(d, "modified"), now)
|
||||
})
|
||||
|
||||
test("without fallbackDates (older plugin), published needs a matching frontmatter value", () => {
|
||||
assert.strictEqual(realDate(data({ dates: { published: now } }), "published"), undefined)
|
||||
assert.strictEqual(
|
||||
realDate(
|
||||
data({ frontmatter: { published: "nope" }, dates: { published: now } }),
|
||||
"published",
|
||||
),
|
||||
undefined,
|
||||
)
|
||||
assert.strictEqual(
|
||||
realDate(
|
||||
data({ frontmatter: { published: "2024-05-06" }, dates: { published: fm } }),
|
||||
"published",
|
||||
),
|
||||
fm,
|
||||
)
|
||||
assert.strictEqual(realDate(data({ dates: { modified: now } }), "modified"), now)
|
||||
})
|
||||
|
||||
test("missing and invalid dates", () => {
|
||||
assert.strictEqual(realDate(data({}), "modified"), undefined)
|
||||
assert.strictEqual(
|
||||
realDate(data({ dates: { modified: new Date(NaN) } }), "modified"),
|
||||
undefined,
|
||||
)
|
||||
assert.strictEqual(realDate(data({ dates: { modified: now } }), undefined), undefined)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
export type DateType = "created" | "modified" | "published"
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
/**
|
||||
* Dates in `dates` that no source gave, so the date plugin filled them with the build time
|
||||
* (created-modified-date ≥ 1.0.5). Absent with older versions.
|
||||
*/
|
||||
fallbackDates: DateType[]
|
||||
}
|
||||
}
|
||||
|
||||
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
/**
|
||||
* Whether the page's `dates[type]` is the one its frontmatter sets for that type (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,
|
||||
type: string | undefined = data.defaultDateType as string | undefined,
|
||||
): boolean {
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) return false
|
||||
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()
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's date of this type when it is a real one, `undefined` when it is missing, invalid
|
||||
* or a stand-in (the build time the date plugin fills in for a date no source gave).
|
||||
*
|
||||
* The date plugin lists stand-ins in `fallbackDates`. Older versions don't, so without that
|
||||
* list a `published` date only counts when it is the frontmatter's (frontmatter is its only
|
||||
* source); `created` and `modified` are taken as they are.
|
||||
*/
|
||||
export function realDate(data: QuartzPluginData, type: string | undefined): Date | undefined {
|
||||
if (!type) return undefined
|
||||
const date = (data.dates as Record<string, unknown> | undefined)?.[type]
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) return undefined
|
||||
const fallbacks = data.fallbackDates
|
||||
if (Array.isArray(fallbacks)) return fallbacks.includes(type as DateType) ? undefined : date
|
||||
if (type === "published" && !dateIsFromFrontmatter(data, date, "published")) return undefined
|
||||
return date
|
||||
}
|
||||
@@ -427,8 +427,9 @@ describe("slugs.stripDiacritics (#2410)", () => {
|
||||
assert.strictEqual(slug("がぎぐ.md"), "がぎぐ")
|
||||
assert.strictEqual(slug("हिन्दी.md"), "हिन्दी")
|
||||
assert.strictEqual(slug("日本語/中文.md"), "日本語/中文")
|
||||
// letters without a decomposition are kept
|
||||
assert.strictEqual(slug("Łódź ø ß.md"), "łodz-ø-ß")
|
||||
// Latin letters without a decomposition fold to ASCII (utils 1.3.1)
|
||||
assert.strictEqual(slug("Łódź ø ß.md"), "lodz-o-ss")
|
||||
assert.strictEqual(slug("Æsir.md"), "aesir")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user