fix(extends): stack listed presets; match monorepo plugins by subdir; clearer errors

This commit is contained in:
saberzero1 committed 2026-11-26 22:32:13 +01:00
1 parent 2b061ab9de
commit a51b7df1ce
4 files changed
+278 -48

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
---
"@jackyzha0/quartz": patch
---
`extends` (experimental): presets in a list now stack. With `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, everything `a.yaml` changed was lost, because `b.yaml` was merged on top with all of `default` again. Each file of the `extends` chain is now applied once, after the bases it extends, so the order is `default` → `a.yaml` → `b.yaml` → your file, and later entries win only where they change the same thing.
Also: a plugin source with a `subdir` and no `name` is matched by repository and folder, so an entry for one plugin of a monorepo no longer changes another; `extends: []` extends nothing; an empty base file is an empty config; `HTTPS://` URLs are accepted; and `plugins:` that isn't a list gets a clear error.
+3 -2
View File
@@ -42,10 +42,11 @@ plugins:
enabled: true
```
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. Later entries in the list win.
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). A source with a `name` matches by that name; a source with a `subdir` and no `name` matches by repository and folder, so two plugins of one repository stay separate. `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
@@ -8,6 +8,7 @@ import {
deepMerge,
mergeQuartzConfigs,
pluginMatchKey,
localExtendsFiles,
resolveExtends,
resolveTarget,
fetchRemoteConfig,
@@ -70,6 +71,41 @@ describe("pluginMatchKey", () => {
})
})
describe("pluginMatchKey for monorepo subdirectories", () => {
test("two plugins of one repository without a name get different keys", () => {
const a = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/a" })
const b = pluginMatchKey({ repo: "github:me/quartz-plugins", subdir: "plugins/b" })
assert.notStrictEqual(a, b)
assert.strictEqual(a, "quartz-plugins/plugins/a")
})
test("subdir spellings are normalised", () => {
for (const subdir of ["plugins/a", "./plugins/a/", "plugins\\a", "/plugins//a"]) {
assert.strictEqual(
pluginMatchKey({ repo: "https://github.com/me/quartz-plugins.git", subdir }),
"quartz-plugins/plugins/a",
subdir,
)
}
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer", subdir: "." }), "explorer")
})
test("an overlay entry for one monorepo plugin leaves the other alone", () => {
const merged = mergeQuartzConfigs(
{
configuration: {},
plugins: [
{ source: { repo: "github:me/mono", subdir: "a" }, enabled: true },
{ source: { repo: "github:me/mono", subdir: "b" }, enabled: true },
],
},
{ plugins: [{ source: { repo: "github:me/mono", subdir: "b" }, enabled: false }] },
)
assert.deepStrictEqual(
merged.plugins.map((p) => p.enabled),
[true, false],
)
})
})
describe("mergeQuartzConfigs", () => {
test("configuration deep-merges; arrays replace; null resets a key", () => {
const merged = mergeQuartzConfigs(base(), {
@@ -227,6 +263,89 @@ describe("resolveExtends", () => {
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
})
test("presets stack: each listed base adds its own changes; a shared base applies once", async () => {
put("presets/title.yaml", {
extends: "default",
configuration: { pageTitle: "Preset A", locale: "fr-FR" },
plugins: [{ source: "@quartz-community/graph", enabled: false }],
})
put("presets/explorer.yaml", {
extends: "default",
configuration: { locale: "nl-NL" },
plugins: [{ source: "@quartz-community/explorer", options: { b: 2 } }],
})
const merged = await resolveExtends(
{ extends: ["./presets/title.yaml", "./presets/explorer.yaml"] },
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
// a's changes survive b (both extend default)
assert.strictEqual(merged.configuration.pageTitle, "Preset A")
assert.strictEqual(
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
false,
)
// b wins where both change something
assert.strictEqual(merged.configuration.locale, "nl-NL")
assert.deepStrictEqual(
merged.plugins.find((p) => pluginMatchKey(p.source) === "explorer")!.options,
{ a: 1, nested: { x: 1 }, b: 2 },
)
assert.strictEqual(merged.plugins.length, 3)
})
test("diamond: a base reached twice is applied once, at its first appearance", async () => {
put("d/common.yaml", { extends: "default", configuration: { locale: "common" } })
put("d/left.yaml", { extends: "./common.yaml", configuration: { pageTitle: "Left" } })
put("d/right.yaml", { extends: "./common.yaml", configuration: { baseUrl: "right.org" } })
const merged = await resolveExtends(
{ extends: ["./d/left.yaml", "./d/right.yaml", "./d/left.yaml"] },
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Left")
assert.strictEqual(merged.configuration.baseUrl, "right.org")
assert.strictEqual(merged.configuration.locale, "common")
assert.deepStrictEqual(
await localExtendsFiles(
{ extends: ["./d/left.yaml", "./d/right.yaml"] },
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
),
["quartz.config.default.yaml", "d/common.yaml", "d/left.yaml", "d/right.yaml"].map((f) =>
path.join(root, f),
),
)
})
test("extends: [] is no base; an empty base file is an empty config", async () => {
const data = { extends: [], configuration: { pageTitle: "x" }, plugins: [] }
assert.deepStrictEqual(await resolveExtends(data, path.join(root, "quartz.config.yaml")), {
configuration: { pageTitle: "x" },
plugins: [],
})
files[path.join(root, "empty.yaml")] = "# nothing here yet\n"
const merged = await resolveExtends(
{ extends: ["default", "./empty.yaml"], configuration: { pageTitle: "E" } },
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "E")
assert.strictEqual(merged.plugins.length, 3)
})
test("plugins that are not a list are reported clearly", async () => {
await assert.rejects(
() =>
resolveExtends(
{ extends: "default", plugins: { explorer: { enabled: false } } },
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
),
(err: Error) => err instanceof ConfigExtendsError && /must be a list/.test(err.message),
)
})
test("cycles and missing files are reported", async () => {
put("a.yaml", { extends: "./b.yaml" })
put("b.yaml", { extends: "./a.yaml" })
@@ -292,6 +411,15 @@ describe("resolveExtends", () => {
assert.strictEqual(merged.plugins.length, 3) // the local default, via the remote chain
})
test("uppercase HTTPS:// is https", async () => {
const merged = await resolveExtends(
{ extends: "HTTPS://CFG.example/base/site.yaml" },
path.join(root, "quartz.config.yaml"),
opts(),
)
assert.strictEqual(merged.configuration.pageTitle, "Remote")
})
test("only https", async () => {
await assert.rejects(
resolveExtends({ extends: "http://cfg.example/x.yaml" }, path.join(root, "q.yaml"), opts()),
+140 -46
View File
@@ -35,6 +35,8 @@ import type {
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
* tie-break between plugins with the same `order`.
* - `extends` lists stack (see resolveExtends): every file of the graph is applied once, after
* its bases, so presets that share `default` each keep their own changes.
* - A config without `extends` is used exactly as written, as before.
*/
@@ -98,20 +100,35 @@ export function deepMerge(base: unknown, overlay: unknown): unknown {
/**
* The name a plugin entry is matched by: the last path segment of its package or repository
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
* `explorer`), or the `name` of an object source.
* `explorer`), or the `name` of an object source. An object source without a `name` that
* points at a `subdir` of a repository is matched by both (`plugins/explorer` in
* `github:me/quartz-plugins` → `quartz-plugins/plugins/explorer`), so two plugins of one
* monorepo stay apart.
*/
export function pluginMatchKey(source: PluginSource): string {
if (typeof source === "object" && source !== null) {
if (source.name) return source.name
return pluginMatchKey(source.repo)
const repoKey = pluginMatchKey(source.repo)
const subdir = normalizeSubdir(source.subdir)
return subdir ? `${repoKey}/${subdir}` : repoKey
}
let s = String(source).trim()
s = s.replace(/^git\+/, "").replace(/^github:/, "")
s = s.replace(/^git\+/i, "").replace(/^github:/i, "")
s = s.split("#")[0]
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
s = s.replace(/\.git$/i, "").replace(/[\\/]+$/, "")
// an npm version/range: @scope/name@1.2.3, name@^1
s = s.replace(/(.)@[^/]*$/, "$1")
return s.slice(s.lastIndexOf("/") + 1)
return s.slice(Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\")) + 1)
}
/** `./plugins/x/`, `plugins\\x`, `/plugins/x` → `plugins/x`; empty or `.` → "". */
function normalizeSubdir(subdir: unknown): string {
if (typeof subdir !== "string") return ""
return subdir
.replace(/\\/g, "/")
.split("/")
.filter((part) => part !== "" && part !== ".")
.join("/")
}
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
@@ -131,6 +148,16 @@ function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
return merged as unknown as PluginJsonEntry
}
function pluginList<T>(value: T[] | null | undefined, where: string): T[] {
if (value === undefined || value === null) return []
if (!Array.isArray(value)) {
throw new ConfigExtendsError(
`"plugins" in ${where} must be a list of plugin entries (- source: …), not ${typeof value === "object" ? "an object" : JSON.stringify(value)}`,
)
}
return value
}
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
export function mergeQuartzConfigs(
base: QuartzPluginsJson,
@@ -142,8 +169,8 @@ export function mergeQuartzConfigs(
{ ...rest, plugins: undefined },
) as QuartzPluginsJson
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
for (const entry of overlayPlugins ?? []) {
const plugins = pluginList(base.plugins, "the base config").map((entry) => ({ ...entry }))
for (const entry of pluginList(overlayPlugins, "the extending config")) {
if (!entry || entry.source === undefined) {
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
}
@@ -176,6 +203,7 @@ const REMOTE_TIMEOUT_MS = 10_000
const REMOTE_MAX_BYTES = 1024 * 1024
const isUrl = (s: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s)
const isHttps = (s: string) => /^https:\/\//i.test(s)
function remoteCacheFile(url: string, cacheDir: string): string {
return path.join(cacheDir, createHash("sha256").update(url).digest("hex").slice(0, 32) + ".yaml")
@@ -235,7 +263,7 @@ async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOpt
signal: AbortSignal.timeout(opts.timeoutMs ?? REMOTE_TIMEOUT_MS),
headers: { accept: "application/yaml, application/json, text/plain, */*" },
})
if (res.url && !res.url.startsWith("https://")) {
if (res.url && !isHttps(res.url)) {
throw new ConfigExtendsError(`"extends: ${url}" redirected to ${res.url}, which is not https`)
}
if (!res.ok) {
@@ -263,6 +291,8 @@ async function fetchUncached(url: string, cacheDir: string, opts: FetchRemoteOpt
function parseConfigFile(file: string, raw: string): PlainObject {
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
// an empty file (or one with only comments) is an empty config
if (data === null || data === undefined) return {}
if (!isPlainObject(data)) {
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
}
@@ -281,6 +311,14 @@ function extendsTargets(value: unknown, file: string): string[] {
return list as string[]
}
function normalizeUrl(url: string): string {
try {
return new URL(url).href
} catch {
throw new ConfigExtendsError(`"extends: ${url}" is not a valid URL`)
}
}
/**
* Where an `extends` target points, seen from the file (or URL) that names it: `default` is
* the local quartz.config.default.yaml; a URL is used as is; a relative path is resolved
@@ -290,12 +328,13 @@ function extendsTargets(value: unknown, file: string): string[] {
*/
export function resolveTarget(target: string, from: string, quartzRoot: string): string {
if (target === DEFAULT_EXTENDS) return path.join(quartzRoot, DEFAULT_CONFIG_FILE)
// URLs are normalised (`HTTPS://Example.org/x` → `https://example.org/x`)
const resolved = isUrl(target)
? target
? normalizeUrl(target)
: isUrl(from)
? new URL(target, from).href
: path.resolve(path.dirname(from), target)
if (isUrl(resolved) && !resolved.startsWith("https://")) {
if (isUrl(resolved) && !isHttps(resolved)) {
throw new ConfigExtendsError(
`${from}: "extends: ${target}" — only https:// URLs can be extended`,
)
@@ -303,56 +342,111 @@ export function resolveTarget(target: string, from: string, quartzRoot: string):
return resolved
}
interface ConfigLayer {
/** Resolved path or URL ("" for the config being resolved). */
file: string
/** The file's own content, without `extends`. */
data: PlainObject
}
/**
* Apply `extends` of `data` (read from `file`, a path or URL): load each base (recursively;
* later entries of an `extends` list win), then merge `data` on top. Returns `data` itself
* when it has no `extends`, so configs without it behave exactly as before.
* Apply `extends` of `data` (read from `file`, a path or URL) and return the merged config.
* Returns `data` itself when it has no `extends` (or an empty list), so configs without it
* behave exactly as before.
*
* Every file in the `extends` graph is a layer of its own changes, applied once, after all of
* its bases (depth first, in list order). A base that several entries share (usually
* `default`) is applied at its first appearance, so for `extends: [./a.yaml, ./b.yaml]` where
* both extend `default` the order is default → a → b → this file: what a.yaml changes stays
* unless b.yaml changes the same thing (later entries win), and this file wins over all.
*/
export async function resolveExtends(
data: PlainObject,
file: string,
options: ResolveExtendsOptions = {},
seen: string[] = [],
): Promise<QuartzPluginsJson> {
if (data.extends === undefined || data.extends === null) {
const targets = data.extends === undefined || data.extends === null ? [] : data.extends
if (Array.isArray(targets) && targets.length === 0) {
const { extends: _drop, ...rest } = data
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
return ("extends" in data ? rest : data) as unknown as QuartzPluginsJson
}
const layers = await extendsLayers(data, file, options)
const [first, ...rest] = layers
let merged = first.data as unknown as QuartzPluginsJson
pluginList(merged.plugins, first.file)
for (const layer of rest) {
merged = mergeQuartzConfigs(merged, layer.data as QuartzConfigOverlay)
}
return merged
}
/**
* The local files (absolute paths) `data` extends, directly or through other bases; URLs are
* left out. For `--serve`, which rebuilds when one of them changes.
*/
export async function localExtendsFiles(
data: PlainObject,
file: string,
options: ResolveExtendsOptions = {},
): Promise<string[]> {
if (data.extends === undefined || data.extends === null) return []
const layers = await extendsLayers(data, file, options)
return layers.map((l) => l.file).filter((f) => f !== "" && !isUrl(f))
}
/** The layers of `data` in the order they are applied: bases first, `data` itself last. */
async function extendsLayers(
data: PlainObject,
file: string,
options: ResolveExtendsOptions,
): Promise<ConfigLayer[]> {
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
const fetchRemote = options.fetchRemote ?? ((url: string) => fetchRemoteConfig(url))
const quartzRoot = options.quartzRoot ?? process.cwd()
const self = isUrl(file) ? file : path.resolve(file)
const chain = [...seen, self]
const layers: ConfigLayer[] = []
const applied = new Set<string>()
let base: QuartzPluginsJson | undefined
for (const target of extendsTargets(data.extends, file)) {
const targetFile = resolveTarget(target, file, quartzRoot)
if (chain.includes(targetFile)) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...chain, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
)
}
let raw: string
if (isUrl(targetFile)) {
raw = await fetchRemote(targetFile)
} else {
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
const visit = async (node: PlainObject, nodeFile: string, chain: string[]) => {
const self = isUrl(nodeFile) ? nodeFile : path.resolve(nodeFile)
const here = [...chain, self]
const raw = node.extends
const targets = raw === undefined || raw === null ? [] : extendsTargets(raw, nodeFile)
for (const target of targets) {
const targetFile = resolveTarget(target, nodeFile, quartzRoot)
if (here.includes(targetFile)) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...here, targetFile].map((f) => (isUrl(f) ? f : path.basename(f))).join(" → ")}`,
)
}
if (applied.has(targetFile)) continue
let text: string
if (isUrl(targetFile)) {
text = await fetchRemote(targetFile)
} else {
try {
text = readFile(targetFile)
} catch {
throw new ConfigExtendsError(
`${nodeFile}: "extends: ${target}" — ${targetFile} not found`,
)
}
}
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
let parsed: PlainObject
try {
parsed = parseConfigFile(parsePath, text)
} catch (err) {
throw new ConfigExtendsError(
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
)
}
await visit(parsed, targetFile, here)
}
const parsePath = isUrl(targetFile) ? new URL(targetFile).pathname : targetFile
let parsed: PlainObject
try {
parsed = parseConfigFile(parsePath, raw)
} catch (err) {
throw new ConfigExtendsError(
`"extends: ${target}": ${targetFile} is not a valid config (${err instanceof Error ? err.message : String(err)})`,
)
}
const resolved = await resolveExtends(parsed, targetFile, options, chain)
base = base ? mergeQuartzConfigs(base, resolved as QuartzConfigOverlay) : resolved
const { extends: _drop, ...own } = node
layers.push({ file: chain.length === 0 ? "" : self, data: own })
applied.add(self)
}
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
await visit(data, file, [])
return layers
}