feat(config): before/after plugin constraints checked against order; https:// extends with cache (#2440)

This commit is contained in:
saberzero1 committed 2026-11-26 17:14:21 +01:00
1 parent df11e31ef3
commit c2293500d7
11 files changed
+661 -48

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
+16 -1
View File
@@ -42,7 +42,8 @@ plugins:
enabled: true
```
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), 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. 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.
@@ -161,6 +162,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`:
>
+9 -1
View File
@@ -5,7 +5,15 @@
// see plugin-validation.d.ts).
/** Top-level keys allowed on a plugin entry (mirrors quartz-plugins.schema.json). */
export const PLUGIN_ENTRY_KEYS = ["source", "enabled", "options", "order", "layout"]
export const PLUGIN_ENTRY_KEYS = [
"source",
"enabled",
"options",
"order",
"before",
"after",
"layout",
]
/** Keys allowed on an object-form `source`. */
export const SOURCE_OBJECT_KEYS = ["repo", "subdir", "ref", "name"]
+130 -12
View File
@@ -9,7 +9,10 @@ import {
mergeQuartzConfigs,
pluginMatchKey,
resolveExtends,
resolveTarget,
fetchRemoteConfig,
} from "./config-extends"
import os from "os"
import type { QuartzPluginsJson } from "./types"
const base = (): QuartzPluginsJson => ({
@@ -177,13 +180,16 @@ describe("resolveExtends", () => {
}
put("quartz.config.default.yaml", base())
test("a config without extends is returned as is", () => {
test("a config without extends is returned as is", async () => {
const data = { configuration: { pageTitle: "x" }, plugins: [] }
assert.strictEqual(resolveExtends(data, path.join(root, "quartz.config.yaml")), data as never)
assert.strictEqual(
await resolveExtends(data, path.join(root, "quartz.config.yaml")),
data as never,
)
})
test("extends: default merges onto quartz.config.default.yaml", () => {
const merged = resolveExtends(
test("extends: default merges onto quartz.config.default.yaml", async () => {
const merged = await resolveExtends(
{
extends: "default",
configuration: { pageTitle: "Mine" },
@@ -201,13 +207,13 @@ describe("resolveExtends", () => {
assert.ok(!("extends" in merged))
})
test("relative paths, chains and lists (later wins)", () => {
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 = resolveExtends(
const merged = await resolveExtends(
{
extends: ["./configs/team.yaml", "configs/dark.yaml"],
configuration: { baseUrl: "x.org" },
@@ -221,10 +227,10 @@ describe("resolveExtends", () => {
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
})
test("cycles and missing files are reported", () => {
test("cycles and missing files are reported", async () => {
put("a.yaml", { extends: "./b.yaml" })
put("b.yaml", { extends: "./a.yaml" })
assert.throws(
await assert.rejects(
() =>
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
@@ -232,7 +238,7 @@ describe("resolveExtends", () => {
}),
/cycle/,
)
assert.throws(
await assert.rejects(
() =>
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
@@ -240,7 +246,7 @@ describe("resolveExtends", () => {
}),
/not found/,
)
assert.throws(
await assert.rejects(
() =>
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
@@ -250,10 +256,122 @@ describe("resolveExtends", () => {
)
})
test("extends: default reproduces the shipped default config exactly", () => {
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 = resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
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/,
)
})
})
+159 -20
View File
@@ -1,5 +1,7 @@
import fs from "fs"
import path from "path"
import { createHash } from "crypto"
import { isMainThread } from "worker_threads"
import YAML from "yaml"
import type {
PluginJsonEntry,
@@ -40,7 +42,14 @@ import type {
export const DEFAULT_EXTENDS = "default"
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
export class ConfigExtendsError extends Error {}
/** 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>
@@ -51,6 +60,9 @@ export interface PluginOverlayEntry {
/** 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
}
@@ -152,8 +164,101 @@ export function mergeQuartzConfigs(
export interface ResolveExtendsOptions {
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
quartzRoot?: string
/** File reader, for tests. */
/** 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 {
@@ -169,7 +274,7 @@ function extendsTargets(value: unknown, file: string): string[] {
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, or a list of them`,
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, an https:// URL, or a list of them`,
)
}
}
@@ -177,42 +282,76 @@ function extendsTargets(value: unknown, file: string): string[] {
}
/**
* Apply `extends` of `data` (read from `file`): 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.
* 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 resolveExtends(
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[] = [],
): QuartzPluginsJson {
): 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 chain = [...seen, path.resolve(file)]
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 =
target === DEFAULT_EXTENDS
? path.join(quartzRoot, DEFAULT_CONFIG_FILE)
: path.resolve(path.dirname(file), target)
if (chain.includes(path.resolve(targetFile))) {
const targetFile = resolveTarget(target, file, quartzRoot)
if (chain.includes(targetFile)) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...chain, targetFile].map((f) => path.basename(f)).join(" → ")}`,
`"extends" cycle: ${[...chain, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
)
}
let raw: string
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
if (isUrl(targetFile)) {
raw = await fetchRemote(targetFile)
} else {
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
}
}
const resolved = resolveExtends(parseConfigFile(targetFile, raw), targetFile, options, chain)
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)
+43 -12
View File
@@ -61,6 +61,7 @@ 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 { getCondition, getAllConditionNames } from "./conditions"
import {
@@ -93,7 +94,7 @@ 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
@@ -363,7 +364,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
@@ -659,7 +660,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)
@@ -718,7 +719,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)
}
@@ -736,15 +749,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(
@@ -763,7 +794,7 @@ export async function loadQuartzConfig(
),
],
pageTypes: [
...(await instantiate(pageTypes, "pageType")).map((item) => item.instance),
...orderPlugins(await instantiate(pageTypes, "pageType"), knownPluginNames),
...builtinPageTypes,
],
}
@@ -1178,7 +1209,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
+2 -2
View File
@@ -21,7 +21,7 @@ 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")
@@ -47,7 +47,7 @@ async function getExternalPluginSources(): Promise<PluginSource[]> {
// fall back to config yaml parsing
}
const pluginsJson = readPluginsJson()
const pluginsJson = await readPluginsJson()
const entries = pluginsJson?.plugins ?? []
return entries.filter((entry) => entry.enabled !== false).map((entry) => entry.source)
}
+104
View File
@@ -0,0 +1,104 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import {
OrderItem,
PluginOrderError,
constraintList,
normalizePluginName,
orderPlugins,
} from "./plugin-order"
const item = (
name: string,
order: number,
c: { before?: string[]; after?: string[] } = {},
): OrderItem<string> => ({ instance: name, order, label: name, names: [name], ...c })
const known = (...names: string[]) => new Set(names.map(normalizePluginName))
describe("orderPlugins", () => {
test("numeric order, then list position, as before", () => {
const items = [item("c", 50), item("a", 10), item("b", 50)]
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "c", "b"])
})
test("before/after decide between plugins with the same order", () => {
const items = [item("x", 50, { after: ["y"] }), item("y", 50), item("z", 50, { before: ["y"] })]
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
})
test("constraints that agree with order are fine and change nothing", () => {
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
})
test("a contradiction with order is an error naming both orders", () => {
assert.throws(
() => orderPlugins([item("a", 30, { after: ["b"] }), item("b", 60)], known("a", "b")),
(err: Error) =>
err instanceof PluginOrderError &&
/"a" \(order 30\) must run after "b", but "b" has order 60/.test(err.message),
)
assert.throws(
() => orderPlugins([item("a", 60, { before: ["b"] }), item("b", 30)], known("a", "b")),
/"a" \(order 60\) must run before "b", but "b" has order 30/,
)
})
test("a cycle among equal orders is an error", () => {
assert.throws(
() =>
orderPlugins(
[item("a", 50, { after: ["b"] }), item("b", 50, { after: ["a"] })],
known("a", "b"),
),
/cycle among plugins with order 50: a, b/,
)
})
test("names match loosely: package name, kebab-case, instance name", () => {
const ofm: OrderItem<string> = {
instance: "ofm",
order: 40,
label: "obsidian-flavored-markdown",
names: ["obsidian-flavored-markdown", "ObsidianFlavoredMarkdown"],
}
for (const ref of [
"ObsidianFlavoredMarkdown",
"obsidian-flavored-markdown",
"@quartz-community/obsidian-flavored-markdown",
]) {
const mine = item("mine", 40, { after: [ref] })
assert.deepStrictEqual(orderPlugins([mine, ofm], known("obsidian-flavored-markdown")), [
"ofm",
"mine",
])
}
})
test("unknown names are errors; disabled or other-category plugins are skipped", () => {
assert.throws(
() => orderPlugins([item("a", 50, { after: ["typo"] })], known("a")),
/"a": after: "typo" is not a plugin in this config/,
)
assert.deepStrictEqual(
orderPlugins([item("a", 50, { after: ["disabled"] })], known("a", "disabled")),
["a"],
)
})
test("a plugin cannot be ordered against itself", () => {
assert.throws(() => orderPlugins([item("a", 50, { after: ["a"] })], known("a")), /itself/)
})
})
describe("constraintList", () => {
test("accepts a name or a list", () => {
assert.deepStrictEqual(constraintList("x", "after", "p"), ["x"])
assert.deepStrictEqual(constraintList(["x", "y"], "after", "p"), ["x", "y"])
assert.deepStrictEqual(constraintList(undefined, "after", "p"), [])
})
test("rejects other values", () => {
assert.throws(() => constraintList(3, "after", "p"), PluginOrderError)
assert.throws(() => constraintList([""], "before", "p"), /"before" must be/)
})
})
+160
View File
@@ -0,0 +1,160 @@
/**
* Plugin order: numeric `order` first, then checked `before:` / `after:` constraints (#2440).
*
* - Plugins run by `order` (lower first), as before. `before`/`after` never move a plugin past
* a plugin with a different `order`: they are checked against it, and a contradiction
* (`after: X` while X has a higher order) is an error that names both orders.
* - Between plugins with the same `order`, the constraints decide; otherwise the list order does
* (built-ins first, then the config's order), as before.
* - Names are plugin names, matched loosely (`obsidian-flavored-markdown`,
* `ObsidianFlavoredMarkdown` and `@quartz-community/obsidian-flavored-markdown` are the same;
* built-ins answer to their instance name and config key, e.g. `Links` / `links`).
* - A name that is not in the config at all is an error (likely a typo). A plugin that is in
* the config but disabled, or runs in another category, is skipped: the constraint only
* applies where both plugins run. A cycle among equal orders is an error.
*
* Constraints are plain data on config entries, so a later dependency-based scheme (e.g. from
* the manifests' `dependencies`) can feed the same checks.
*/
/** A configuration mistake: reported by its message alone (no stack trace). */
export class PluginOrderError extends Error {
constructor(message: string) {
super(message)
this.name = "PluginOrderError"
this.stack = `${this.name}: ${message}`
}
}
/** Loose plugin name: lowercase, scope and punctuation removed. */
export function normalizePluginName(name: string): string {
const bare = name.trim().replace(/^@[^/]+\//, "")
return bare.toLowerCase().replace(/[^a-z0-9]/g, "")
}
export interface OrderItem<T> {
instance: T
order: number
/** Display name used in messages. */
label: string
/** Every name this plugin answers to. */
names: string[]
before?: string[]
after?: string[]
}
/** Accepts `before: X` and `before: [X, Y]`; anything else is an error. */
export function constraintList(value: unknown, field: string, label: string): string[] {
if (value === undefined || value === null) return []
const list = Array.isArray(value) ? value : [value]
for (const v of list) {
if (typeof v !== "string" || v.trim() === "") {
throw new PluginOrderError(
`plugin "${label}": "${field}" must be a plugin name or a list of plugin names`,
)
}
}
return list as string[]
}
/**
* Sort one category's plugins. `known` holds the normalized names of every plugin in the
* config (enabled or not, any category) and of the built-ins, to tell typos from plugins that
* just don't run here.
*/
export function orderPlugins<T>(items: OrderItem<T>[], known: ReadonlySet<string>): T[] {
const indexed = items.map((item, index) => ({ ...item, index }))
const byName = new Map<string, (typeof indexed)[number]>()
for (const item of indexed) {
for (const name of item.names) {
const key = normalizePluginName(name)
if (!byName.has(key)) byName.set(key, item)
}
}
// edges: earlier → later
const later = new Map<number, Set<number>>()
const addEdge = (
first: (typeof indexed)[number],
second: (typeof indexed)[number],
why: string,
) => {
if (first === second) {
throw new PluginOrderError(`plugin "${first.label}": ${why} names the plugin itself`)
}
if (first.order > second.order) {
throw new PluginOrderError(
`plugin "${second.label}" (order ${second.order}) ${why}, but "${first.label}" has order ${first.order}, so it runs later. ` +
`Give "${second.label}" an order above ${first.order}, or "${first.label}" one below ${second.order}.`,
)
}
if (!later.has(first.index)) later.set(first.index, new Set())
later.get(first.index)!.add(second.index)
}
for (const item of indexed) {
for (const [field, names] of [
["after", item.after ?? []],
["before", item.before ?? []],
] as const) {
for (const name of names) {
const key = normalizePluginName(name)
const other = byName.get(key)
if (!other) {
if (!known.has(key)) {
throw new PluginOrderError(
`plugin "${item.label}": ${field}: "${name}" is not a plugin in this config`,
)
}
continue // disabled, or not in this category
}
if (field === "after") addEdge(other, item, `must run after "${other.label}"`)
else {
// phrase the message from the constrained plugin's point of view
if (item.order > other.order) {
throw new PluginOrderError(
`plugin "${item.label}" (order ${item.order}) must run before "${other.label}", but "${other.label}" has order ${other.order}, so it runs earlier. ` +
`Give "${item.label}" an order below ${other.order}, or "${other.label}" one above ${item.order}.`,
)
}
addEdge(item, other, `must run before "${other.label}"`)
}
}
}
}
// numeric order, then list position; within one order, a stable topological sort
const sorted = [...indexed].sort((a, b) => a.order - b.order || a.index - b.index)
if (later.size === 0) return sorted.map((i) => i.instance)
const result: (typeof indexed)[number][] = []
let start = 0
while (start < sorted.length) {
let end = start
while (end < sorted.length && sorted[end].order === sorted[start].order) end++
const group = sorted.slice(start, end)
const inGroup = new Set(group.map((g) => g.index))
const indegree = new Map(group.map((g) => [g.index, 0]))
for (const g of group) {
for (const next of later.get(g.index) ?? []) {
if (inGroup.has(next)) indegree.set(next, indegree.get(next)! + 1)
}
}
const remaining = [...group]
while (remaining.length > 0) {
const pos = remaining.findIndex((g) => indegree.get(g.index) === 0)
if (pos === -1) {
throw new PluginOrderError(
`"before"/"after" form a cycle among plugins with order ${group[0].order}: ${remaining.map((g) => g.label).join(", ")}`,
)
}
const [next] = remaining.splice(pos, 1)
result.push(next)
for (const n of later.get(next.index) ?? []) {
if (inGroup.has(n)) indegree.set(n, indegree.get(n)! - 1)
}
}
start = end
}
return result.map((i) => i.instance)
}
+3
View File
@@ -165,6 +165,9 @@ export interface PluginJsonEntry {
enabled: boolean
options?: Record<string, unknown>
order?: number
/** Plugins this one must run before / after (checked against `order`; see plugin-order.ts). */
before?: string | string[]
after?: string | string[]
layout?: PluginLayoutDeclaration
}
+30
View File
@@ -444,6 +444,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,