mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
Merge pull request #2702 from jackyzha0/dev-mode/config-extends
feat(config): experimental extends: merge quartz.config.yaml onto the default config (#2440)
This commit is contained in:
12 files changed
+1192
-26
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
Experimental `extends` in `quartz.config.yaml`: `extends: default` (or a path) starts from `quartz.config.default.yaml` and applies only the changes in your file. `configuration` and `layout` merge key by key, plugin entries merge with the default entry of the same plugin. Configs without `extends` behave exactly as before.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
|
||||
@@ -23,6 +23,35 @@ layout:
|
||||
|
||||
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
|
||||
|
||||
## Extending the default configuration
|
||||
|
||||
Without a `quartz.config.yaml`, Quartz uses `quartz.config.default.yaml`. A `quartz.config.yaml` normally replaces it completely. With `extends`, your file can hold just the changes you make to another configuration instead:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
extends: default # quartz.config.default.yaml
|
||||
configuration:
|
||||
pageTitle: "My Site"
|
||||
baseUrl: example.com
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false # turn off a default plugin
|
||||
- source: "@quartz-community/explorer"
|
||||
options:
|
||||
folderDefaultState: open # only this option changes
|
||||
- source: github:me/my-plugin # a plugin the defaults don't have
|
||||
enabled: true
|
||||
```
|
||||
|
||||
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. Later entries in the list win.
|
||||
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
|
||||
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
|
||||
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
|
||||
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
|
||||
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
|
||||
|
||||
> [!warning] Experimental
|
||||
> `npx quartz plugin` commands that edit plugin entries (`enable`, `disable`, `config`, …) only see the entries in your own file so far. Edit an extending `quartz.config.yaml` by hand.
|
||||
|
||||
## General Configuration
|
||||
|
||||
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
|
||||
@@ -138,6 +167,20 @@ plugins:
|
||||
|
||||
Plugins are categorized by their type (transformer, filter, emitter, pageType) based on their manifest. The `order` field controls execution order within each category.
|
||||
|
||||
`before` and `after` name plugins that this one must run before or after (one name or a list; `obsidian-flavored-markdown`, `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` all work, as do the built-ins `frontmatter`, `links`, `drafts` and `contentIndex`). They never override `order`; they are checked against it:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
plugins:
|
||||
- source: github:me/my-transformer
|
||||
enabled: true
|
||||
order: 45
|
||||
after: obsidian-flavored-markdown # needs the links OFM creates
|
||||
```
|
||||
|
||||
- Between plugins with the same `order`, `before`/`after` decide the order (otherwise the list order does).
|
||||
- If `order` contradicts a constraint (here: OFM moved to order 50), the build stops with an error that names both orders, instead of silently running the plugins the wrong way round.
|
||||
- A name that isn't in your config is an error. A plugin that is disabled, or runs in another category (a filter named by a transformer), is skipped: the constraint applies only where both plugins run.
|
||||
|
||||
> [!note]
|
||||
> For advanced TS override of plugin configuration, you can modify `quartz.ts`:
|
||||
>
|
||||
|
||||
@@ -5,7 +5,15 @@
|
||||
// see plugin-validation.d.ts).
|
||||
|
||||
/** Top-level keys allowed on a plugin entry (mirrors quartz-plugins.schema.json). */
|
||||
export const PLUGIN_ENTRY_KEYS = ["source", "enabled", "options", "order", "layout"]
|
||||
export const PLUGIN_ENTRY_KEYS = [
|
||||
"source",
|
||||
"enabled",
|
||||
"options",
|
||||
"order",
|
||||
"before",
|
||||
"after",
|
||||
"layout",
|
||||
]
|
||||
|
||||
/** Keys allowed on an object-form `source`. */
|
||||
export const SOURCE_OBJECT_KEYS = ["repo", "subdir", "ref", "name"]
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import path from "path"
|
||||
import fs from "fs"
|
||||
import YAML from "yaml"
|
||||
import {
|
||||
ConfigExtendsError,
|
||||
deepMerge,
|
||||
mergeQuartzConfigs,
|
||||
pluginMatchKey,
|
||||
resolveExtends,
|
||||
resolveTarget,
|
||||
fetchRemoteConfig,
|
||||
} from "./config-extends"
|
||||
import os from "os"
|
||||
import type { QuartzPluginsJson } from "./types"
|
||||
|
||||
const base = (): QuartzPluginsJson => ({
|
||||
configuration: {
|
||||
pageTitle: "Quartz",
|
||||
ignorePatterns: ["private", ".obsidian"],
|
||||
theme: { typography: { header: "Schibsted Grotesk", body: "Source Sans Pro" } },
|
||||
links: { markdownLinkResolution: "shortest" },
|
||||
},
|
||||
plugins: [
|
||||
{ source: "@quartz-community/explorer", enabled: true, options: { a: 1, nested: { x: 1 } } },
|
||||
{
|
||||
source: "github:quartz-community/graph",
|
||||
enabled: true,
|
||||
order: 50,
|
||||
layout: { position: "right", priority: 10 },
|
||||
},
|
||||
{ source: "@quartz-community/comments", enabled: false },
|
||||
],
|
||||
layout: { byPageType: { folder: { exclude: ["graph"] } } },
|
||||
})
|
||||
|
||||
describe("deepMerge", () => {
|
||||
test("objects merge, other values replace, null deletes", () => {
|
||||
assert.deepStrictEqual(
|
||||
deepMerge({ a: { b: 1, c: 2 }, l: [1, 2], k: 1 }, { a: { c: 3 }, l: [9], k: null }),
|
||||
{
|
||||
a: { b: 1, c: 3 },
|
||||
l: [9],
|
||||
},
|
||||
)
|
||||
})
|
||||
test("does not modify its inputs", () => {
|
||||
const b = { a: { b: 1 } }
|
||||
deepMerge(b, { a: { b: 2 } })
|
||||
assert.deepStrictEqual(b, { a: { b: 1 } })
|
||||
})
|
||||
})
|
||||
|
||||
describe("pluginMatchKey", () => {
|
||||
test("npm, GitHub, git URL and local sources of one plugin match", () => {
|
||||
for (const source of [
|
||||
"@quartz-community/explorer",
|
||||
"@quartz-community/explorer@^2.0.0",
|
||||
"github:quartz-community/explorer",
|
||||
"github:someone/explorer#v2",
|
||||
"git+https://github.com/quartz-community/explorer.git",
|
||||
"https://github.com/quartz-community/explorer",
|
||||
"./plugins/explorer/",
|
||||
"explorer",
|
||||
{ repo: "github:quartz-community/plugins", subdir: "x", name: "explorer" },
|
||||
]) {
|
||||
assert.strictEqual(pluginMatchKey(source as never), "explorer", JSON.stringify(source))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("mergeQuartzConfigs", () => {
|
||||
test("configuration deep-merges; arrays replace; null resets a key", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
configuration: {
|
||||
pageTitle: "My garden",
|
||||
ignorePatterns: ["drafts"],
|
||||
theme: { typography: { header: "Inter" } },
|
||||
links: null,
|
||||
},
|
||||
})
|
||||
assert.strictEqual(merged.configuration.pageTitle, "My garden")
|
||||
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["drafts"])
|
||||
assert.deepStrictEqual(merged.configuration.theme, {
|
||||
typography: { header: "Inter", body: "Source Sans Pro" },
|
||||
})
|
||||
assert.ok(!("links" in merged.configuration))
|
||||
// the base plugins are kept when the overlay lists none
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("plugins match by name; enabled/order/source replace, options/layout merge", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{
|
||||
source: "github:quartz-community/explorer",
|
||||
options: { b: 2, nested: { y: 2 } },
|
||||
} as never,
|
||||
{ source: "@quartz-community/graph", enabled: false, order: 10, layout: { priority: 1 } },
|
||||
{ source: "@quartz-community/comments", enabled: true },
|
||||
],
|
||||
})
|
||||
const [explorer, graph, comments] = merged.plugins
|
||||
assert.strictEqual(explorer.source, "github:quartz-community/explorer")
|
||||
assert.strictEqual(explorer.enabled, true)
|
||||
assert.deepStrictEqual(explorer.options, { a: 1, b: 2, nested: { x: 1, y: 2 } })
|
||||
assert.strictEqual(graph.enabled, false)
|
||||
assert.strictEqual(graph.order, 10)
|
||||
assert.deepStrictEqual(graph.layout, { position: "right", priority: 1 })
|
||||
assert.strictEqual(comments.enabled, true)
|
||||
assert.strictEqual(merged.plugins.length, 3)
|
||||
})
|
||||
|
||||
test("new plugins are appended as written (no enabled → disabled, as in a full config)", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{ source: "github:me/my-plugin", enabled: true, order: 70 },
|
||||
{ source: "github:me/other" },
|
||||
],
|
||||
})
|
||||
assert.strictEqual(merged.plugins.length, 5)
|
||||
assert.deepStrictEqual(merged.plugins[3], {
|
||||
source: "github:me/my-plugin",
|
||||
enabled: true,
|
||||
order: 70,
|
||||
})
|
||||
assert.deepStrictEqual(merged.plugins[4], { source: "github:me/other" })
|
||||
})
|
||||
|
||||
test("null removes a plugin's options, layout or order (back to the plugin's defaults)", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
plugins: [
|
||||
{ source: "@quartz-community/graph", layout: null, order: null } as never,
|
||||
{ source: "@quartz-community/explorer", options: { nested: null } } as never,
|
||||
],
|
||||
})
|
||||
const [explorer, graph] = merged.plugins
|
||||
assert.ok(!("layout" in graph) && !("order" in graph))
|
||||
assert.deepStrictEqual(explorer.options, { a: 1 })
|
||||
})
|
||||
|
||||
test("layout merges; arrays like byPageType.*.exclude replace", () => {
|
||||
const merged = mergeQuartzConfigs(base(), {
|
||||
layout: { byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } } },
|
||||
})
|
||||
assert.deepStrictEqual(merged.layout, {
|
||||
byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } },
|
||||
})
|
||||
})
|
||||
|
||||
test("does not modify the base", () => {
|
||||
const b = base()
|
||||
const before = JSON.stringify(b)
|
||||
mergeQuartzConfigs(b, {
|
||||
configuration: { pageTitle: "x" },
|
||||
plugins: [{ source: "@quartz-community/explorer", options: { a: 2 } } as never],
|
||||
})
|
||||
assert.strictEqual(JSON.stringify(b), before)
|
||||
})
|
||||
|
||||
test("a plugin entry without source is an error", () => {
|
||||
assert.throws(
|
||||
() => mergeQuartzConfigs(base(), { plugins: [{ enabled: false } as never] }),
|
||||
ConfigExtendsError,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveExtends", () => {
|
||||
const files: Record<string, string> = {}
|
||||
const root = path.resolve("/site")
|
||||
const readFile = (f: string) => {
|
||||
const content = files[path.resolve(f)]
|
||||
if (content === undefined) throw new Error("ENOENT")
|
||||
return content
|
||||
}
|
||||
const put = (rel: string, data: unknown) => {
|
||||
files[path.join(root, rel)] = YAML.stringify(data)
|
||||
}
|
||||
put("quartz.config.default.yaml", base())
|
||||
|
||||
test("a config without extends is returned as is", async () => {
|
||||
const data = { configuration: { pageTitle: "x" }, plugins: [] }
|
||||
assert.strictEqual(
|
||||
await resolveExtends(data, path.join(root, "quartz.config.yaml")),
|
||||
data as never,
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: default merges onto quartz.config.default.yaml", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Mine" },
|
||||
plugins: [{ source: "@quartz-community/graph", enabled: false }],
|
||||
},
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Mine")
|
||||
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["private", ".obsidian"])
|
||||
assert.strictEqual(
|
||||
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
|
||||
false,
|
||||
)
|
||||
assert.ok(!("extends" in merged))
|
||||
})
|
||||
|
||||
test("relative paths, chains and lists (later wins)", async () => {
|
||||
put("configs/team.yaml", {
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "Team", locale: "cs-CZ" },
|
||||
})
|
||||
put("configs/dark.yaml", { configuration: { pageTitle: "Dark" } })
|
||||
const merged = await resolveExtends(
|
||||
{
|
||||
extends: ["./configs/team.yaml", "configs/dark.yaml"],
|
||||
configuration: { baseUrl: "x.org" },
|
||||
},
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
{ quartzRoot: root, readFile },
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Dark")
|
||||
assert.strictEqual(merged.configuration.locale, "cs-CZ")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "x.org")
|
||||
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
|
||||
})
|
||||
|
||||
test("cycles and missing files are reported", async () => {
|
||||
put("a.yaml", { extends: "./b.yaml" })
|
||||
put("b.yaml", { extends: "./a.yaml" })
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
/cycle/,
|
||||
)
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
/not found/,
|
||||
)
|
||||
await assert.rejects(
|
||||
() =>
|
||||
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
ConfigExtendsError,
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: default reproduces the shipped default config exactly", async () => {
|
||||
const defaultFile = path.resolve("quartz.config.default.yaml")
|
||||
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
|
||||
const merged = await resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
|
||||
assert.deepStrictEqual(merged, shipped)
|
||||
})
|
||||
|
||||
describe("https bases", () => {
|
||||
const remote: Record<string, string> = {
|
||||
"https://cfg.example/base/site.yaml": YAML.stringify({
|
||||
extends: "./common.yaml",
|
||||
configuration: { pageTitle: "Remote" },
|
||||
}),
|
||||
"https://cfg.example/base/common.yaml": YAML.stringify({
|
||||
extends: "default",
|
||||
configuration: { locale: "de-DE" },
|
||||
}),
|
||||
}
|
||||
const fetchRemote = async (url: string) => {
|
||||
if (!(url in remote)) throw new ConfigExtendsError(`404 ${url}`)
|
||||
return remote[url]
|
||||
}
|
||||
const opts = () => ({ quartzRoot: root, readFile, fetchRemote })
|
||||
|
||||
test("a URL base; its relative extends resolve against the URL; default stays local", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{ extends: "https://cfg.example/base/site.yaml", configuration: { baseUrl: "me.org" } },
|
||||
path.join(root, "quartz.config.yaml"),
|
||||
opts(),
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "Remote")
|
||||
assert.strictEqual(merged.configuration.locale, "de-DE")
|
||||
assert.strictEqual(merged.configuration.baseUrl, "me.org")
|
||||
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
|
||||
})
|
||||
|
||||
test("only https", async () => {
|
||||
await assert.rejects(
|
||||
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
|
||||
/only https/,
|
||||
)
|
||||
assert.strictEqual(
|
||||
resolveTarget("../other.yaml", "https://cfg.example/base/site.yaml", root),
|
||||
"https://cfg.example/other.yaml",
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("fetchRemoteConfig", () => {
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
|
||||
const ok = (body: string) =>
|
||||
(async () => new Response(body, { status: 200 })) as unknown as typeof fetch
|
||||
const failing = (async () => {
|
||||
throw new Error("getaddrinfo ENOTFOUND")
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
test("caches a fetched copy and falls back to it when offline or failing", async () => {
|
||||
const cacheDir = tmp()
|
||||
const url = "https://cfg.example/a.yaml"
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
|
||||
"a: 1\n",
|
||||
)
|
||||
// memoised per process: a second call does not fetch again
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
|
||||
"a: 1\n",
|
||||
)
|
||||
const warnings: string[] = []
|
||||
const other = tmp()
|
||||
fs.cpSync(cacheDir, other, { recursive: true })
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, {
|
||||
cacheDir: other,
|
||||
fetchImpl: failing,
|
||||
offline: false,
|
||||
warn: (m) => warnings.push(m),
|
||||
}),
|
||||
"a: 1\n",
|
||||
)
|
||||
assert.match(warnings[0], /using the cached copy/)
|
||||
// offline (QUARTZ_EXTENDS_OFFLINE=1, worker threads): the cache only
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig("https://cfg.example/a.yaml?x", {
|
||||
cacheDir: other,
|
||||
offline: true,
|
||||
}).catch((e: Error) => e.message),
|
||||
`"extends: https://cfg.example/a.yaml?x": no cached copy in ${other} (offline build). Build once online first.`,
|
||||
)
|
||||
})
|
||||
|
||||
test("without a cached copy a failed fetch stops the build", async () => {
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/b.yaml", {
|
||||
cacheDir: tmp(),
|
||||
fetchImpl: failing,
|
||||
offline: false,
|
||||
}),
|
||||
/could not be fetched: getaddrinfo ENOTFOUND/,
|
||||
)
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/c.yaml", { cacheDir: tmp(), offline: true }),
|
||||
/no cached copy/,
|
||||
)
|
||||
})
|
||||
|
||||
test("HTTP errors are failures, too", async () => {
|
||||
const notFound = (async () => new Response("nope", { status: 404 })) as unknown as typeof fetch
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig("https://cfg.example/d.yaml", {
|
||||
cacheDir: tmp(),
|
||||
fetchImpl: notFound,
|
||||
offline: false,
|
||||
}),
|
||||
/HTTP 404/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,358 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { createHash } from "crypto"
|
||||
import { isMainThread } from "worker_threads"
|
||||
import YAML from "yaml"
|
||||
import type {
|
||||
PluginJsonEntry,
|
||||
PluginLayoutDeclaration,
|
||||
PluginSource,
|
||||
QuartzPluginsJson,
|
||||
} from "./types"
|
||||
|
||||
/**
|
||||
* `extends:` in quartz.config.yaml (#2440): start from another config and apply only the
|
||||
* differences on top.
|
||||
*
|
||||
* ```yaml
|
||||
* extends: default # quartz.config.default.yaml next to quartz.config.yaml's Quartz
|
||||
* configuration:
|
||||
* pageTitle: My garden
|
||||
* plugins:
|
||||
* - source: "@quartz-community/explorer"
|
||||
* options: { folderDefaultState: open }
|
||||
* - source: "@quartz-community/graph"
|
||||
* enabled: false
|
||||
* ```
|
||||
*
|
||||
* Merge rules (`mergeQuartzConfigs`):
|
||||
* - `configuration` and `layout`: objects merge key by key, recursively; any other value
|
||||
* (strings, numbers, arrays such as `ignorePatterns` or `byPageType.*.exclude`) replaces the
|
||||
* base value; `null` removes the key (back to the built-in default).
|
||||
* - `plugins`: an entry matches the base entry of the same plugin (by plugin name, so
|
||||
* `github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the
|
||||
* same name replaces the original). Of a matched entry, `source`, `enabled` and `order`
|
||||
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
|
||||
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
|
||||
* tie-break between plugins with the same `order`.
|
||||
* - A config without `extends` is used exactly as written, as before.
|
||||
*/
|
||||
|
||||
/** The name `extends: default` stands for. */
|
||||
export const DEFAULT_EXTENDS = "default"
|
||||
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
|
||||
|
||||
/** A configuration mistake: reported by its message alone (no stack trace). */
|
||||
export class ConfigExtendsError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = "ConfigExtendsError"
|
||||
this.stack = `${this.name}: ${message}`
|
||||
}
|
||||
}
|
||||
|
||||
type PlainObject = Record<string, unknown>
|
||||
|
||||
/** A plugin entry in a config that extends another: only `source` is required. */
|
||||
export interface PluginOverlayEntry {
|
||||
source: PluginSource
|
||||
enabled?: boolean
|
||||
/** Merged into the base entry's options; `null` drops them (the plugin's defaults apply). */
|
||||
options?: Record<string, unknown> | null
|
||||
order?: number | null
|
||||
/** Replace the base entry's constraints; `null` removes them. */
|
||||
before?: string | string[] | null
|
||||
after?: string | string[] | null
|
||||
/** Merged into the base entry's layout; `null` drops it (the plugin's default placement). */
|
||||
layout?: Partial<PluginLayoutDeclaration> | null
|
||||
}
|
||||
|
||||
/** What a config with `extends` may contain: any part of a full config. */
|
||||
export interface QuartzConfigOverlay {
|
||||
$schema?: string
|
||||
extends?: string | string[] | null
|
||||
configuration?: Record<string, unknown>
|
||||
plugins?: PluginOverlayEntry[]
|
||||
layout?: Record<string, unknown>
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is PlainObject {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** Recursive merge: objects merge, everything else replaces, `null` deletes. */
|
||||
export function deepMerge(base: unknown, overlay: unknown): unknown {
|
||||
if (overlay === undefined) return base
|
||||
if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay
|
||||
const result: PlainObject = { ...base }
|
||||
for (const [key, value] of Object.entries(overlay)) {
|
||||
if (value === null) {
|
||||
delete result[key]
|
||||
} else {
|
||||
result[key] = deepMerge(base[key], value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a plugin entry is matched by: the last path segment of its package or repository
|
||||
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
|
||||
* `explorer`), or the `name` of an object source.
|
||||
*/
|
||||
export function pluginMatchKey(source: PluginSource): string {
|
||||
if (typeof source === "object" && source !== null) {
|
||||
if (source.name) return source.name
|
||||
return pluginMatchKey(source.repo)
|
||||
}
|
||||
let s = String(source).trim()
|
||||
s = s.replace(/^git\+/, "").replace(/^github:/, "")
|
||||
s = s.split("#")[0]
|
||||
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
|
||||
// an npm version/range: @scope/name@1.2.3, name@^1
|
||||
s = s.replace(/(.)@[^/]*$/, "$1")
|
||||
return s.slice(s.lastIndexOf("/") + 1)
|
||||
}
|
||||
|
||||
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
|
||||
const merged: PlainObject = { ...base }
|
||||
for (const [key, value] of Object.entries(overlay)) {
|
||||
if (value === undefined) continue
|
||||
if (key === "options" || key === "layout") {
|
||||
const next = value === null ? undefined : deepMerge(merged[key], value)
|
||||
if (next === undefined) delete merged[key]
|
||||
else merged[key] = next
|
||||
} else if (value === null) {
|
||||
delete merged[key]
|
||||
} else {
|
||||
merged[key] = value
|
||||
}
|
||||
}
|
||||
return merged as unknown as PluginJsonEntry
|
||||
}
|
||||
|
||||
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
|
||||
export function mergeQuartzConfigs(
|
||||
base: QuartzPluginsJson,
|
||||
overlay: QuartzConfigOverlay,
|
||||
): QuartzPluginsJson {
|
||||
const { extends: _extends, plugins: overlayPlugins, ...rest } = overlay
|
||||
const merged = deepMerge(
|
||||
{ ...base, plugins: undefined },
|
||||
{ ...rest, plugins: undefined },
|
||||
) as QuartzPluginsJson
|
||||
|
||||
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
|
||||
for (const entry of overlayPlugins ?? []) {
|
||||
if (!entry || entry.source === undefined) {
|
||||
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
|
||||
}
|
||||
const key = pluginMatchKey(entry.source)
|
||||
const index = plugins.findIndex((p) => pluginMatchKey(p.source) === key)
|
||||
if (index === -1) {
|
||||
// a new plugin, read like an entry of a full config (no `enabled` → disabled, with a warning)
|
||||
plugins.push({ ...entry } as PluginJsonEntry)
|
||||
} else {
|
||||
plugins[index] = mergePluginEntry(plugins[index], entry)
|
||||
}
|
||||
}
|
||||
merged.plugins = plugins
|
||||
merged.configuration = (merged.configuration ?? {}) as QuartzPluginsJson["configuration"]
|
||||
return merged
|
||||
}
|
||||
|
||||
export interface ResolveExtendsOptions {
|
||||
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
|
||||
quartzRoot?: string
|
||||
/** Local file reader, for tests. */
|
||||
readFile?: (file: string) => string
|
||||
/** Loader for `https://` bases; default `fetchRemoteConfig` (cached, with a timeout). */
|
||||
fetchRemote?: (url: string) => Promise<string>
|
||||
}
|
||||
|
||||
/** Where fetched remote bases are kept (offline builds, worker threads). */
|
||||
export const REMOTE_CACHE_DIR = path.join(".quartz-cache", "extends")
|
||||
const REMOTE_TIMEOUT_MS = 10_000
|
||||
const REMOTE_MAX_BYTES = 1024 * 1024
|
||||
|
||||
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
|
||||
|
||||
function remoteCacheFile(url: string, cacheDir: string): string {
|
||||
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
|
||||
}
|
||||
|
||||
export interface FetchRemoteOptions {
|
||||
cacheDir?: string
|
||||
timeoutMs?: number
|
||||
/** Only use the cache (QUARTZ_EXTENDS_OFFLINE=1; always in worker threads). */
|
||||
offline?: boolean
|
||||
fetchImpl?: typeof fetch
|
||||
warn?: (message: string) => void
|
||||
}
|
||||
|
||||
const fetched = new Map<string, Promise<string>>()
|
||||
|
||||
/**
|
||||
* Fetch a remote base config: once per process, with a timeout and a size limit. A successful
|
||||
* fetch is cached in `.quartz-cache/extends/`; when the fetch fails (offline, timeout, HTTP
|
||||
* error) the cached copy is used with a warning, and without one the build stops. Worker threads
|
||||
* and `QUARTZ_EXTENDS_OFFLINE=1` read only the cache, so every thread of a build sees the copy
|
||||
* the main thread fetched.
|
||||
*/
|
||||
export function fetchRemoteConfig(url: string, opts: FetchRemoteOptions = {}): Promise<string> {
|
||||
const cacheDir = opts.cacheDir ?? path.join(process.cwd(), REMOTE_CACHE_DIR)
|
||||
const key = `${cacheDir}\0${url}`
|
||||
let pending = fetched.get(key)
|
||||
if (!pending) {
|
||||
pending = fetchUncached(url, cacheDir, opts)
|
||||
fetched.set(key, pending)
|
||||
pending.catch(() => fetched.delete(key))
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOptions) {
|
||||
const cacheFile = remoteCacheFile(url, cacheDir)
|
||||
const cached = () => {
|
||||
try {
|
||||
return fs.readFileSync(cacheFile, "utf-8")
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const offline = opts.offline ?? (process.env.QUARTZ_EXTENDS_OFFLINE === "1" || !isMainThread)
|
||||
if (offline) {
|
||||
const copy = cached()
|
||||
if (copy !== undefined) return copy
|
||||
throw new ConfigExtendsError(
|
||||
`"extends: ${url}": no cached copy in ${cacheDir} (offline build). Build once online first.`,
|
||||
)
|
||||
}
|
||||
const warn = opts.warn ?? ((m: string) => console.warn(`⚠ ${m}`))
|
||||
let failure: string
|
||||
try {
|
||||
const res = await (opts.fetchImpl ?? fetch)(url, {
|
||||
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
|
||||
headers: { accept: "application/yaml, application/json, text/plain, */*" },
|
||||
})
|
||||
if (res.url && !res.url.startsWith("https://")) {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
|
||||
}
|
||||
if (!res.ok) {
|
||||
failure = `HTTP ${res.status}`
|
||||
} else {
|
||||
const text = await res.text()
|
||||
if (Buffer.byteLength(text) > REMOTE_MAX_BYTES) {
|
||||
throw new ConfigExtendsError(`"extends: ${url}" is larger than 1 MB`)
|
||||
}
|
||||
fs.mkdirSync(cacheDir, { recursive: true })
|
||||
fs.writeFileSync(cacheFile, text)
|
||||
return text
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ConfigExtendsError) throw err
|
||||
failure = err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
const copy = cached()
|
||||
if (copy !== undefined) {
|
||||
warn(`"extends: ${url}" could not be fetched (${failure}); using the cached copy.`)
|
||||
return copy
|
||||
}
|
||||
throw new ConfigExtendsError(`"extends: ${url}" could not be fetched: ${failure}`)
|
||||
}
|
||||
|
||||
function parseConfigFile(file: string, raw: string): PlainObject {
|
||||
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
|
||||
if (!isPlainObject(data)) {
|
||||
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
function extendsTargets(value: unknown, file: string): string[] {
|
||||
const list = Array.isArray(value) ? value : [value]
|
||||
for (const item of list) {
|
||||
if (typeof item !== "string" || item.trim() === "") {
|
||||
throw new ConfigExtendsError(
|
||||
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, an https:// URL, or a list of them`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return list as string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an `extends` target points, seen from the file (or URL) that names it: `default` is
|
||||
* the local quartz.config.default.yaml; a URL is used as is; a relative path is resolved
|
||||
* against the extending file's directory, or against its URL when that file was fetched (a
|
||||
* remote config cannot reach local files). Only https URLs are allowed. (A future
|
||||
* `npm:<package>` target would be one more case here.)
|
||||
*/
|
||||
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
|
||||
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
|
||||
const resolved = isUrl(target)
|
||||
? target
|
||||
: isUrl(from)
|
||||
? new URL(target, from).href
|
||||
: path.resolve(path.dirname(from), target)
|
||||
if (isUrl(resolved) && !resolved.startsWith("https://")) {
|
||||
throw new ConfigExtendsError(
|
||||
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
|
||||
)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply `extends` of `data` (read from `file`, a path or URL): load each base (recursively;
|
||||
* later entries of an `extends` list win), then merge `data` on top. Returns `data` itself
|
||||
* when it has no `extends`, so configs without it behave exactly as before.
|
||||
*/
|
||||
export async function resolveExtends(
|
||||
data: PlainObject,
|
||||
file: string,
|
||||
options: ResolveExtendsOptions = {},
|
||||
seen: string[] = [],
|
||||
): Promise<QuartzPluginsJson> {
|
||||
if (data.extends === undefined || data.extends === null) {
|
||||
const { extends: _drop, ...rest } = data
|
||||
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
|
||||
}
|
||||
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
|
||||
const fetchRemote = options.fetchRemote ?? ((url: string) => fetchRemoteConfig(url))
|
||||
const quartzRoot = options.quartzRoot ?? process.cwd()
|
||||
const self = isUrl(file) ? file : path.resolve(file)
|
||||
const chain = [...seen, self]
|
||||
|
||||
let base: QuartzPluginsJson | undefined
|
||||
for (const target of extendsTargets(data.extends, file)) {
|
||||
const targetFile = resolveTarget(target, file, quartzRoot)
|
||||
if (chain.includes(targetFile)) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends" cycle: ${[...chain, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
|
||||
)
|
||||
}
|
||||
let raw: string
|
||||
if (isUrl(targetFile)) {
|
||||
raw = await fetchRemote(targetFile)
|
||||
} else {
|
||||
try {
|
||||
raw = readFile(targetFile)
|
||||
} catch {
|
||||
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
|
||||
}
|
||||
}
|
||||
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
|
||||
let parsed: PlainObject
|
||||
try {
|
||||
parsed = parseConfigFile(parsePath, raw)
|
||||
} catch (err) {
|
||||
throw new ConfigExtendsError(
|
||||
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
|
||||
)
|
||||
}
|
||||
const resolved = await resolveExtends(parsed, targetFile, options, chain)
|
||||
base = base ? mergeQuartzConfigs(base, resolved as QuartzConfigOverlay) : resolved
|
||||
}
|
||||
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
|
||||
}
|
||||
@@ -61,6 +61,8 @@ import {
|
||||
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
|
||||
import { componentRegistry, RegisteredComponent } from "../../components/registry"
|
||||
import { frameRegistry } from "../../components/frames/registry"
|
||||
import { OrderItem, constraintList, normalizePluginName, orderPlugins } from "./plugin-order"
|
||||
import { resolveExtends } from "./config-extends"
|
||||
import { setSlugOptions } from "../../util/path"
|
||||
import { getCondition, getAllConditionNames } from "./conditions"
|
||||
import {
|
||||
@@ -93,16 +95,18 @@ export function resolveConfigPath(): string {
|
||||
if (fs.existsSync(LEGACY_DEFAULT_PLUGINS_JSON_PATH)) return LEGACY_DEFAULT_PLUGINS_JSON_PATH
|
||||
return CONFIG_YAML_PATH
|
||||
}
|
||||
function readPluginsJson(): QuartzPluginsJson | null {
|
||||
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
|
||||
const configPath = resolveConfigPath()
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return null
|
||||
}
|
||||
const raw = fs.readFileSync(configPath, "utf-8")
|
||||
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
|
||||
return YAML.parse(raw) as QuartzPluginsJson
|
||||
}
|
||||
return JSON.parse(raw) as QuartzPluginsJson
|
||||
const data =
|
||||
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
|
||||
// `extends:` (#2440): merge onto the base config; a config without it is used as written
|
||||
return data && typeof data === "object" && "extends" in data
|
||||
? resolveExtends(data, configPath)
|
||||
: (data as QuartzPluginsJson)
|
||||
}
|
||||
|
||||
function extractPluginName(source: PluginSource): string {
|
||||
@@ -361,7 +365,7 @@ async function getManifest(source: PluginSource): Promise<PluginManifest | null>
|
||||
export async function loadQuartzConfig(
|
||||
configOverrides?: Partial<GlobalConfiguration>,
|
||||
): Promise<QuartzConfig> {
|
||||
const json = readPluginsJson()
|
||||
const json = await readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style config directly
|
||||
@@ -660,7 +664,7 @@ export async function loadQuartzConfig(
|
||||
items: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[],
|
||||
expectedCategory: ProcessingCategory,
|
||||
) => {
|
||||
const instances: { order: number; instance: any }[] = []
|
||||
const instances: OrderItem<any>[] = []
|
||||
for (const { entry, manifest } of items) {
|
||||
try {
|
||||
const spec = parsePluginSource(entry.source)
|
||||
@@ -719,7 +723,19 @@ export async function loadQuartzConfig(
|
||||
issues: manifest?.issues,
|
||||
quartzVersion: manifest?.quartzVersion,
|
||||
})
|
||||
instances.push({ order: entry.order ?? manifest?.defaultOrder ?? 50, instance })
|
||||
const label = extractPluginName(entry.source)
|
||||
instances.push({
|
||||
order: entry.order ?? manifest?.defaultOrder ?? 50,
|
||||
instance,
|
||||
label,
|
||||
names: [
|
||||
label,
|
||||
manifest?.name,
|
||||
typeof instance.name === "string" ? instance.name : "",
|
||||
].filter((n): n is string => typeof n === "string" && n !== ""),
|
||||
before: constraintList(entry.before, "before", label),
|
||||
after: constraintList(entry.after, "after", label),
|
||||
})
|
||||
} catch (err) {
|
||||
pluginLoadFailed(entry, manifest, "was skipped: it failed to initialise", err)
|
||||
}
|
||||
@@ -737,15 +753,33 @@ export async function loadQuartzConfig(
|
||||
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
|
||||
|
||||
// Built-in processing steps take their place in plugin order (frontmatter at 0, links at 60 …);
|
||||
// on equal order a built-in runs before plugins (stable sort, built-ins listed first).
|
||||
// on equal order a built-in runs before plugins (stable sort, built-ins listed first), unless
|
||||
// `before`/`after` on an entry say otherwise (see plugin-order.ts).
|
||||
const knownPluginNames = new Set(
|
||||
[
|
||||
...json.plugins.map((e) => extractPluginName(e.source)),
|
||||
...builtinPlan.builtins.map((b) => b.spec.configKey),
|
||||
"Frontmatter",
|
||||
"Links",
|
||||
"Drafts",
|
||||
"ContentIndex",
|
||||
"Fonts",
|
||||
].map(normalizePluginName),
|
||||
)
|
||||
const withBuiltins = <T>(
|
||||
builtins: { order: number; instance: unknown }[],
|
||||
instances: { order: number; instance: T }[],
|
||||
instances: OrderItem<T>[],
|
||||
): T[] =>
|
||||
[...builtins, ...instances]
|
||||
.map((item, index) => ({ ...item, index }))
|
||||
.sort((a, b) => a.order - b.order || a.index - b.index)
|
||||
.map((item) => item.instance as T)
|
||||
orderPlugins(
|
||||
[
|
||||
...builtins.map(({ order, instance }) => {
|
||||
const name = (instance as { name: string }).name
|
||||
return { order, instance: instance as T, label: name, names: [name] }
|
||||
}),
|
||||
...instances,
|
||||
],
|
||||
knownPluginNames,
|
||||
)
|
||||
|
||||
const plugins: PluginTypes = {
|
||||
transformers: withBuiltins(
|
||||
@@ -764,7 +798,7 @@ export async function loadQuartzConfig(
|
||||
),
|
||||
],
|
||||
pageTypes: [
|
||||
...(await instantiate(pageTypes, "pageType")).map((item) => item.instance),
|
||||
...orderPlugins(await instantiate(pageTypes, "pageType"), knownPluginNames),
|
||||
...builtinPageTypes,
|
||||
],
|
||||
}
|
||||
@@ -1179,7 +1213,7 @@ export function buildQuartzLayout(
|
||||
* the renderer's layout is updated in place with the overrides applied.
|
||||
*/
|
||||
export async function loadQuartzLayout(layoutOverrides?: LayoutOverrides): Promise<QuartzLayout> {
|
||||
const json = readPluginsJson()
|
||||
const json = await readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style layout directly
|
||||
|
||||
@@ -5,6 +5,7 @@ import YAML from "yaml"
|
||||
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
|
||||
import type { PluginSource, QuartzPluginsJson } from "./types.js"
|
||||
import { absorbingBuiltin } from "../builtins/index.js"
|
||||
import { resolveExtends } from "./config-extends.js"
|
||||
|
||||
function resolveConfigPath(): string {
|
||||
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
|
||||
@@ -20,14 +21,15 @@ function resolveConfigPath(): string {
|
||||
return configYamlPath
|
||||
}
|
||||
|
||||
function readPluginsJson(): QuartzPluginsJson | null {
|
||||
async function readPluginsJson(): Promise<QuartzPluginsJson | null> {
|
||||
const configPath = resolveConfigPath()
|
||||
if (!fs.existsSync(configPath)) return null
|
||||
const raw = fs.readFileSync(configPath, "utf-8")
|
||||
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
|
||||
return YAML.parse(raw)
|
||||
}
|
||||
return JSON.parse(raw)
|
||||
const data =
|
||||
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
|
||||
return data && typeof data === "object" && "extends" in data
|
||||
? resolveExtends(data, configPath)
|
||||
: data
|
||||
}
|
||||
|
||||
async function getExternalPluginSources(): Promise<PluginSource[]> {
|
||||
@@ -45,7 +47,7 @@ async function getExternalPluginSources(): Promise<PluginSource[]> {
|
||||
// fall back to config yaml parsing
|
||||
}
|
||||
|
||||
const pluginsJson = readPluginsJson()
|
||||
const pluginsJson = await readPluginsJson()
|
||||
const entries = pluginsJson?.plugins ?? []
|
||||
return entries.filter((entry) => entry.enabled !== false).map((entry) => entry.source)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import {
|
||||
OrderItem,
|
||||
PluginOrderError,
|
||||
constraintList,
|
||||
normalizePluginName,
|
||||
orderPlugins,
|
||||
} from "./plugin-order"
|
||||
|
||||
const item = (
|
||||
name: string,
|
||||
order: number,
|
||||
c: { before?: string[]; after?: string[] } = {},
|
||||
): OrderItem<string> => ({ instance: name, order, label: name, names: [name], ...c })
|
||||
const known = (...names: string[]) => new Set(names.map(normalizePluginName))
|
||||
|
||||
describe("orderPlugins", () => {
|
||||
test("numeric order, then list position, as before", () => {
|
||||
const items = [item("c", 50), item("a", 10), item("b", 50)]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "c", "b"])
|
||||
})
|
||||
|
||||
test("before/after decide between plugins with the same order", () => {
|
||||
const items = [item("x", 50, { after: ["y"] }), item("y", 50), item("z", 50, { before: ["y"] })]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
|
||||
})
|
||||
|
||||
test("constraints that agree with order are fine and change nothing", () => {
|
||||
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
|
||||
})
|
||||
|
||||
test("a contradiction with order is an error naming both orders", () => {
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 30, { after: ["b"] }), item("b", 60)], known("a", "b")),
|
||||
(err: Error) =>
|
||||
err instanceof PluginOrderError &&
|
||||
/"a" \(order 30\) must run after "b", but "b" has order 60/.test(err.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 60, { before: ["b"] }), item("b", 30)], known("a", "b")),
|
||||
/"a" \(order 60\) must run before "b", but "b" has order 30/,
|
||||
)
|
||||
})
|
||||
|
||||
test("a cycle among equal orders is an error", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
orderPlugins(
|
||||
[item("a", 50, { after: ["b"] }), item("b", 50, { after: ["a"] })],
|
||||
known("a", "b"),
|
||||
),
|
||||
/cycle among plugins with order 50: a, b/,
|
||||
)
|
||||
})
|
||||
|
||||
test("names match loosely: package name, kebab-case, instance name", () => {
|
||||
const ofm: OrderItem<string> = {
|
||||
instance: "ofm",
|
||||
order: 40,
|
||||
label: "obsidian-flavored-markdown",
|
||||
names: ["obsidian-flavored-markdown", "ObsidianFlavoredMarkdown"],
|
||||
}
|
||||
for (const ref of [
|
||||
"ObsidianFlavoredMarkdown",
|
||||
"obsidian-flavored-markdown",
|
||||
"@quartz-community/obsidian-flavored-markdown",
|
||||
]) {
|
||||
const mine = item("mine", 40, { after: [ref] })
|
||||
assert.deepStrictEqual(orderPlugins([mine, ofm], known("obsidian-flavored-markdown")), [
|
||||
"ofm",
|
||||
"mine",
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
test("unknown names are errors; disabled or other-category plugins are skipped", () => {
|
||||
assert.throws(
|
||||
() => orderPlugins([item("a", 50, { after: ["typo"] })], known("a")),
|
||||
/"a": after: "typo" is not a plugin in this config/,
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
orderPlugins([item("a", 50, { after: ["disabled"] })], known("a", "disabled")),
|
||||
["a"],
|
||||
)
|
||||
})
|
||||
|
||||
test("a plugin cannot be ordered against itself", () => {
|
||||
assert.throws(() => orderPlugins([item("a", 50, { after: ["a"] })], known("a")), /itself/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("constraintList", () => {
|
||||
test("accepts a name or a list", () => {
|
||||
assert.deepStrictEqual(constraintList("x", "after", "p"), ["x"])
|
||||
assert.deepStrictEqual(constraintList(["x", "y"], "after", "p"), ["x", "y"])
|
||||
assert.deepStrictEqual(constraintList(undefined, "after", "p"), [])
|
||||
})
|
||||
test("rejects other values", () => {
|
||||
assert.throws(() => constraintList(3, "after", "p"), PluginOrderError)
|
||||
assert.throws(() => constraintList([""], "before", "p"), /"before" must be/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Plugin order: numeric `order` first, then checked `before:` / `after:` constraints (#2440).
|
||||
*
|
||||
* - Plugins run by `order` (lower first), as before. `before`/`after` never move a plugin past
|
||||
* a plugin with a different `order`: they are checked against it, and a contradiction
|
||||
* (`after: X` while X has a higher order) is an error that names both orders.
|
||||
* - Between plugins with the same `order`, the constraints decide; otherwise the list order does
|
||||
* (built-ins first, then the config's order), as before.
|
||||
* - Names are plugin names, matched loosely (`obsidian-flavored-markdown`,
|
||||
* `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` are the same;
|
||||
* built-ins answer to their instance name and config key, e.g. `Links` / `links`).
|
||||
* - A name that is not in the config at all is an error (likely a typo). A plugin that is in
|
||||
* the config but disabled, or runs in another category, is skipped: the constraint only
|
||||
* applies where both plugins run. A cycle among equal orders is an error.
|
||||
*
|
||||
* Constraints are plain data on config entries, so a later dependency-based scheme (e.g. from
|
||||
* the manifests' `dependencies`) can feed the same checks.
|
||||
*/
|
||||
|
||||
/** A configuration mistake: reported by its message alone (no stack trace). */
|
||||
export class PluginOrderError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = "PluginOrderError"
|
||||
this.stack = `${this.name}: ${message}`
|
||||
}
|
||||
}
|
||||
|
||||
/** Loose plugin name: lowercase, scope and punctuation removed. */
|
||||
export function normalizePluginName(name: string): string {
|
||||
const bare = name.trim().replace(/^@[^/]+\//, "")
|
||||
return bare.toLowerCase().replace(/[^a-z0-9]/g, "")
|
||||
}
|
||||
|
||||
export interface OrderItem<T> {
|
||||
instance: T
|
||||
order: number
|
||||
/** Display name used in messages. */
|
||||
label: string
|
||||
/** Every name this plugin answers to. */
|
||||
names: string[]
|
||||
before?: string[]
|
||||
after?: string[]
|
||||
}
|
||||
|
||||
/** Accepts `before: X` and `before: [X, Y]`; anything else is an error. */
|
||||
export function constraintList(value: unknown, field: string, label: string): string[] {
|
||||
if (value === undefined || value === null) return []
|
||||
const list = Array.isArray(value) ? value : [value]
|
||||
for (const v of list) {
|
||||
if (typeof v !== "string" || v.trim() === "") {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${label}": "${field}" must be a plugin name or a list of plugin names`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return list as string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort one category's plugins. `known` holds the normalized names of every plugin in the
|
||||
* config (enabled or not, any category) and of the built-ins, to tell typos from plugins that
|
||||
* just don't run here.
|
||||
*/
|
||||
export function orderPlugins<T>(items: OrderItem<T>[], known: ReadonlySet<string>): T[] {
|
||||
const indexed = items.map((item, index) => ({ ...item, index }))
|
||||
const byName = new Map<string, (typeof indexed)[number]>()
|
||||
for (const item of indexed) {
|
||||
for (const name of item.names) {
|
||||
const key = normalizePluginName(name)
|
||||
if (!byName.has(key)) byName.set(key, item)
|
||||
}
|
||||
}
|
||||
|
||||
// edges: earlier → later
|
||||
const later = new Map<number, Set<number>>()
|
||||
const addEdge = (
|
||||
first: (typeof indexed)[number],
|
||||
second: (typeof indexed)[number],
|
||||
why: string,
|
||||
) => {
|
||||
if (first === second) {
|
||||
throw new PluginOrderError(`plugin "${first.label}": ${why} names the plugin itself`)
|
||||
}
|
||||
if (first.order > second.order) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${second.label}" (order ${second.order}) ${why}, but "${first.label}" has order ${first.order}, so it runs later. ` +
|
||||
`Give "${second.label}" an order above ${first.order}, or "${first.label}" one below ${second.order}.`,
|
||||
)
|
||||
}
|
||||
if (!later.has(first.index)) later.set(first.index, new Set())
|
||||
later.get(first.index)!.add(second.index)
|
||||
}
|
||||
|
||||
for (const item of indexed) {
|
||||
for (const [field, names] of [
|
||||
["after", item.after ?? []],
|
||||
["before", item.before ?? []],
|
||||
] as const) {
|
||||
for (const name of names) {
|
||||
const key = normalizePluginName(name)
|
||||
const other = byName.get(key)
|
||||
if (!other) {
|
||||
if (!known.has(key)) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${item.label}": ${field}: "${name}" is not a plugin in this config`,
|
||||
)
|
||||
}
|
||||
continue // disabled, or not in this category
|
||||
}
|
||||
if (field === "after") addEdge(other, item, `must run after "${other.label}"`)
|
||||
else {
|
||||
// phrase the message from the constrained plugin's point of view
|
||||
if (item.order > other.order) {
|
||||
throw new PluginOrderError(
|
||||
`plugin "${item.label}" (order ${item.order}) must run before "${other.label}", but "${other.label}" has order ${other.order}, so it runs earlier. ` +
|
||||
`Give "${item.label}" an order below ${other.order}, or "${other.label}" one above ${item.order}.`,
|
||||
)
|
||||
}
|
||||
addEdge(item, other, `must run before "${other.label}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// numeric order, then list position; within one order, a stable topological sort
|
||||
const sorted = [...indexed].sort((a, b) => a.order - b.order || a.index - b.index)
|
||||
if (later.size === 0) return sorted.map((i) => i.instance)
|
||||
|
||||
const result: (typeof indexed)[number][] = []
|
||||
let start = 0
|
||||
while (start < sorted.length) {
|
||||
let end = start
|
||||
while (end < sorted.length && sorted[end].order === sorted[start].order) end++
|
||||
const group = sorted.slice(start, end)
|
||||
const inGroup = new Set(group.map((g) => g.index))
|
||||
const indegree = new Map(group.map((g) => [g.index, 0]))
|
||||
for (const g of group) {
|
||||
for (const next of later.get(g.index) ?? []) {
|
||||
if (inGroup.has(next)) indegree.set(next, indegree.get(next)! + 1)
|
||||
}
|
||||
}
|
||||
const remaining = [...group]
|
||||
while (remaining.length > 0) {
|
||||
const pos = remaining.findIndex((g) => indegree.get(g.index) === 0)
|
||||
if (pos === -1) {
|
||||
throw new PluginOrderError(
|
||||
`"before"/"after" form a cycle among plugins with order ${group[0].order}: ${remaining.map((g) => g.label).join(", ")}`,
|
||||
)
|
||||
}
|
||||
const [next] = remaining.splice(pos, 1)
|
||||
result.push(next)
|
||||
for (const n of later.get(next.index) ?? []) {
|
||||
if (inGroup.has(n)) indegree.set(n, indegree.get(n)! - 1)
|
||||
}
|
||||
}
|
||||
start = end
|
||||
}
|
||||
return result.map((i) => i.instance)
|
||||
}
|
||||
@@ -165,6 +165,9 @@ export interface PluginJsonEntry {
|
||||
enabled: boolean
|
||||
options?: Record<string, unknown>
|
||||
order?: number
|
||||
/** Plugins this one must run before / after (checked against `order`; see plugin-order.ts). */
|
||||
before?: string | string[]
|
||||
after?: string | string[]
|
||||
layout?: PluginLayoutDeclaration
|
||||
}
|
||||
|
||||
|
||||
@@ -3,16 +3,54 @@
|
||||
"title": "Quartz Plugins Configuration Schema",
|
||||
"description": "Schema for validating quartz.config.yaml (and legacy quartz.plugins.json) configuration files",
|
||||
"type": "object",
|
||||
"required": ["configuration", "plugins"],
|
||||
"additionalProperties": false,
|
||||
"if": {
|
||||
"required": ["extends"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"plugins": {
|
||||
"items": {
|
||||
"required": ["source"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"else": {
|
||||
"required": ["configuration", "plugins"],
|
||||
"properties": {
|
||||
"configuration": {
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"]
|
||||
},
|
||||
"plugins": {
|
||||
"items": {
|
||||
"required": ["source", "enabled"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "JSON Schema reference"
|
||||
},
|
||||
"extends": {
|
||||
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"configuration": {
|
||||
"type": "object",
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"pageTitle": {
|
||||
@@ -374,7 +412,6 @@
|
||||
"description": "Array of plugin configurations",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["source", "enabled"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"source": {
|
||||
@@ -419,6 +456,36 @@
|
||||
"minimum": 0,
|
||||
"description": "Plugin execution order"
|
||||
},
|
||||
"before": {
|
||||
"description": "Plugin name(s) this plugin must run before. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"description": "Plugin name(s) this plugin must run after. Checked against order: between plugins with the same order it decides, a contradiction with order is an error.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
|
||||
Reference in new issue
Block a user