feat(core): report plugins that fail to load, fail CI builds on them; import npm plugin entry modules

This commit is contained in:
saberzero1 committed 2026-11-07 17:41:02 +01:00
1 parent ea75b1bdc8
commit 50203da448
9 files changed
+220 -62

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Plugins that fail to load (can't be installed, throw on import, export no plugin) are reported as errors with the plugin, version, the file and line where it failed and what to do, and listed again at the top of the end-of-build summary. Previously some of these failures were silent. Locally the build continues without them; in CI (`CI` set) it fails unless `QUARTZ_ALLOW_BROKEN_PLUGINS=1`. Fixed along the way: the entry module of npm-installed component plugins (and npm plugins without a declared category) was never imported, so their `init(options)` never ran.
+1
View File
@@ -7,6 +7,7 @@ Common issues and solutions when working with Quartz.
## Reading build output
- **Errors from plugins** say which plugin failed (name, version, source), what it was doing ("while transforming the Markdown of `notes/x.md`", "component Backlinks while rendering `features/x`"), any problems Quartz already knew about that plugin, and where to report it. To confirm a plugin is the cause, disable it (`npx quartz plugin disable <name>`) and build again.
- **Plugins that fail to load** (can't be installed, their code throws on import, no plugin found in the package) are marked `✗` with the file and line where it failed. Locally the build continues without them so you can check the rest of the site; they are listed again at the top of the end-of-build summary. In CI (`CI` set, e.g. GitHub Actions, Netlify, Vercel, Cloudflare Pages) the build fails instead, so a site with a missing feature isn't deployed — set `QUARTZ_ALLOW_BROKEN_PLUGINS=1` to deploy anyway.
- **Warnings** printed while loading the config (plugins that need a newer Quartz, plugins missing data they need, layout typos, plugin entries that are now built in) are repeated in a summary at the end of the build.
- **Notes** in that summary point out links to pages that are not on your site — including links to [[RemoveDrafts|drafts]], which are the usual cause of "this link 404s". `npx quartz build --verbose` lists every such link, the order plugins run in, the built-ins and the layout of each page type.
- **Which version am I on?** `npx quartz info` prints your Quartz version, environment and plugins — include it when asking for help (see [[versioning]]).
+2
View File
@@ -28,3 +28,5 @@ export function describeRequirementProblem(
export function describeQuartzCheckout(root?: string): QuartzCheckout
export function formatQuartzVersion(version: string | undefined, checkout?: QuartzCheckout): string
export function incompatiblePluginsFailBuild(env?: Record<string, string | undefined>): boolean
export function brokenPluginsFailBuild(env?: Record<string, string | undefined>): boolean
export function isCI(env?: Record<string, string | undefined>): boolean
+14
View File
@@ -70,6 +70,20 @@ export function describeRequirementProblem(pluginName, result, pluginVersion) {
*/
export function incompatiblePluginsFailBuild(env = process.env) {
if (env.QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS === "1") return false
return isCI(env)
}
/**
* Whether plugins that fail to load fail the build: in CI unless QUARTZ_ALLOW_BROKEN_PLUGINS=1.
* Locally the build continues without them (and says so), so the rest of the site can be checked.
*/
export function brokenPluginsFailBuild(env = process.env) {
if (env.QUARTZ_ALLOW_BROKEN_PLUGINS === "1") return false
return isCI(env)
}
/** `CI` set to anything but "", "0" or "false". */
export function isCI(env = process.env) {
const ci = env.CI
return ci !== undefined && ci !== "" && ci !== "0" && ci.toLowerCase() !== "false"
}
+14
View File
@@ -4,6 +4,7 @@ import {
checkQuartzRequirement,
describeRequirementProblem,
formatQuartzVersion,
brokenPluginsFailBuild,
incompatiblePluginsFailBuild,
readQuartzVersion,
} from "./compat.js"
@@ -64,6 +65,19 @@ describe("incompatiblePluginsFailBuild", () => {
false,
)
})
test("broken plugins have their own override", () => {
assert.strictEqual(brokenPluginsFailBuild({}), false)
assert.strictEqual(brokenPluginsFailBuild({ CI: "true" }), true)
assert.strictEqual(
brokenPluginsFailBuild({ CI: "true", QUARTZ_ALLOW_BROKEN_PLUGINS: "1" }),
false,
)
assert.strictEqual(
brokenPluginsFailBuild({ CI: "true", QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" }),
true,
)
})
})
describe("version display", () => {
+90 -53
View File
@@ -35,11 +35,13 @@ import {
CapabilityPlugin,
} from "./capabilities"
import { absorbingBuiltin, BuiltinPlan, instantiateBuiltins, planBuiltins } from "../builtins"
import { registerPluginOrigin, warn } from "../../util/diagnostics"
import { registerPluginOrigin, reportError, warn } from "../../util/diagnostics"
import { firstPluginFrame } from "../../util/trace"
import {
checkQuartzRequirement,
describeRequirementProblem,
incompatiblePluginsFailBuild,
brokenPluginsFailBuild,
readQuartzVersion,
} from "../../cli/compat.js"
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
@@ -221,11 +223,20 @@ function validateDependencies(
return { errors, warnings }
}
/**
* Import a plugin's entry module: npm plugins resolve from node_modules, git/local plugins from
* .quartz/plugins/<name>. (Importing .quartz/plugins/<name> for npm plugins used to fail silently,
* so their init(options) and entry-module side effects never ran.)
*/
async function importPluginModule(spec: ReturnType<typeof parsePluginSource>) {
return spec.npmPackage
? await import(spec.name)
: await import(toFileUrl(getPluginEntryPoint(spec.name)))
}
async function resolvePluginManifest(source: PluginSource): Promise<PluginManifest | null> {
try {
const gitSpec = parsePluginSource(source)
const entryPoint = getPluginEntryPoint(gitSpec.name)
const module = await import(toFileUrl(entryPoint))
const module = await importPluginModule(parsePluginSource(source))
return module.manifest ?? null
} catch {
return null
@@ -314,6 +325,35 @@ export async function loadQuartzConfig(
const manifests = new Map<string, PluginManifest>()
// Ensure all plugins are installed and collect native deps
// Plugins that could not be installed, imported or instantiated. The build continues without
// them locally (so the rest of the site can be checked) and fails in CI (brokenPluginsFailBuild).
const loadFailures: string[] = []
const pluginLoadFailed = (
entry: PluginJsonEntry,
manifest: PluginManifest | undefined,
what: string,
err?: unknown,
) => {
const name = manifest?.name ?? extractPluginName(entry.source)
const label = manifest?.version ? `${name}@${manifest.version}` : name
const detail = err === undefined ? "" : `: ${err instanceof Error ? err.message : String(err)}`
const frame = firstPluginFrame(err)
reportError({
area: "plugins",
plugin: name,
message: `${label} ${what}${detail}`,
hint: [
frame && `at ${frame}`,
`source: ${formatSourceDisplay(entry.source)}`,
`Try \`npx quartz plugin doctor\`, update or disable it (\`npx quartz plugin disable ${name}\`); ` +
`report it${manifest?.issues ? ` at ${manifest.issues}` : " to the plugin's author"} with the output of \`npx quartz info\`.`,
]
.filter(Boolean)
.join("\n"),
})
if (!loadFailures.includes(name)) loadFailures.push(name)
}
const allNativeDeps = new Map<string, Map<string, string>>()
for (const entry of enabledEntries) {
try {
@@ -326,11 +366,7 @@ export async function loadQuartzConfig(
allNativeDeps.set(gitSpec.name, result.nativeDeps)
}
} catch (err) {
console.error(
styleText("red", `✗`) +
` Failed to install plugin: ${styleText("yellow", formatSourceDisplay(entry.source))}\n` +
` ${err instanceof Error ? err.message : String(err)}`,
)
pluginLoadFailed(entry, undefined, "could not be installed", err)
}
}
@@ -346,11 +382,7 @@ export async function loadQuartzConfig(
manifests.set(sourceKey(entry.source), manifest)
}
} catch (err) {
console.error(
styleText("red", `✗`) +
` Failed to load manifest: ${styleText("yellow", formatSourceDisplay(entry.source))}\n` +
` ${err instanceof Error ? err.message : String(err)}`,
)
pluginLoadFailed(entry, undefined, "has an unreadable manifest (package.json → quartz)", err)
}
}
@@ -485,9 +517,8 @@ export async function loadQuartzConfig(
// Always import the main entry point for component-only plugins.
// Some plugins (e.g. Bases view registrations) rely on side effects
// in their index module to register functionality.
const entryPoint = getPluginEntryPoint(gitSpec.name)
try {
const module = await import(toFileUrl(entryPoint))
const module = await importPluginModule(gitSpec)
// If the module exports an init() function, call it with merged options
// so component-only plugins can receive user configuration from YAML.
if (typeof module.init === "function") {
@@ -495,8 +526,10 @@ export async function loadQuartzConfig(
const options = { ...manifest?.defaultOptions, ...entry.options, ...initOverrides }
await module.init(Object.keys(options).length > 0 ? options : undefined)
}
} catch (e) {
// Side-effect import failed — continue with manifest-based loading
} catch (err) {
// Components listed in the manifest are still loaded below, but whatever the entry
// module registers or initialises (Bases views, init(options) …) is missing.
pluginLoadFailed(entry, manifest, "failed to load its entry module", err)
}
if (manifest?.components && Object.keys(manifest.components).length > 0) {
await loadComponentsFromPackage(gitSpec.name, manifest)
@@ -505,9 +538,8 @@ export async function loadQuartzConfig(
await loadFramesFromPackage(gitSpec.name, manifest)
}
} else {
const entryPoint = getPluginEntryPoint(gitSpec.name)
try {
const module = await import(toFileUrl(entryPoint))
const module = await importPluginModule(gitSpec)
const detected = detectCategoryFromModule(module)
if (detected) {
categoryMap[detected].push({ entry, manifest })
@@ -517,12 +549,13 @@ export async function loadQuartzConfig(
await loadFramesFromPackage(gitSpec.name, manifest)
}
} else {
console.warn(
styleText("yellow", `⚠`) +
` Could not determine category for plugin "${extractPluginName(entry.source)}". Skipping.`,
pluginLoadFailed(
entry,
manifest,
"was skipped: its category could not be determined (set quartz.category in its package.json)",
)
}
} catch {
} catch (err) {
const hasComponents = manifest?.components && Object.keys(manifest.components).length > 0
const hasFrames = manifest?.frames && Object.keys(manifest.frames).length > 0
if (hasComponents) {
@@ -531,12 +564,14 @@ export async function loadQuartzConfig(
if (hasFrames) {
await loadFramesFromPackage(gitSpec.name, manifest)
}
if (!hasComponents && !hasFrames) {
console.warn(
styleText("yellow", `⚠`) +
` Could not load plugin "${extractPluginName(entry.source)}" to detect category. Skipping.`,
)
}
pluginLoadFailed(
entry,
manifest,
hasComponents || hasFrames
? "failed to load its entry module (only its components/frames were loaded)"
: "was skipped: its entry module failed to load",
err,
)
}
}
}
@@ -566,14 +601,8 @@ export async function loadQuartzConfig(
for (const { entry, manifest } of items) {
try {
const spec = parsePluginSource(entry.source)
let module
if (spec.npmPackage) {
module = await import(spec.name)
} else {
const entryPoint = getPluginEntryPoint(spec.name)
module = await import(toFileUrl(entryPoint))
}
const pluginName = spec.npmPackage ? spec.name : spec.name
const module = await importPluginModule(spec)
const pluginName = spec.name
if (manifest?.components && Object.keys(manifest.components).length > 0) {
await loadComponentsFromPackage(pluginName, manifest)
}
@@ -583,10 +612,10 @@ export async function loadQuartzConfig(
const factory = findFactory(module, expectedCategory)
if (!factory) {
console.warn(
styleText("yellow", `⚠`) +
` Plugin "${extractPluginName(entry.source)}" has no factory function for category "${expectedCategory}". ` +
`Ensure your plugin exports a default function, a "plugin" named export, or a single exported function.`,
pluginLoadFailed(
entry,
manifest,
`was skipped: no ${expectedCategory} factory found (export a default function, a "plugin" named export, or a single function)`,
)
continue
}
@@ -594,17 +623,18 @@ export async function loadQuartzConfig(
const options = { ...manifest?.defaultOptions, ...entry.options, ...pluginOverrides }
const instance = factory(Object.keys(options).length > 0 ? options : undefined)
if (!instance || typeof instance !== "object") {
console.warn(
styleText("yellow", `⚠`) +
` Plugin "${extractPluginName(entry.source)}" factory did not return a valid plugin instance. Skipping.`,
pluginLoadFailed(
entry,
manifest,
"was skipped: its factory did not return a plugin instance",
)
continue
}
if (!validateCategory(instance, expectedCategory)) {
console.warn(
styleText("yellow", `⚠`) +
` Plugin "${extractPluginName(entry.source)}" declares category "${expectedCategory}" ` +
`but its factory returned an instance missing the required methods. Skipping.`,
pluginLoadFailed(
entry,
manifest,
`was skipped: it declares category "${expectedCategory}" but its instance lacks the required methods`,
)
continue
}
@@ -627,10 +657,7 @@ export async function loadQuartzConfig(
})
instances.push({ order: entry.order ?? manifest?.defaultOrder ?? 50, instance })
} catch (err) {
console.error(
styleText("red", `✗`) +
` Failed to instantiate plugin "${extractPluginName(entry.source)}": ${err instanceof Error ? err.message : String(err)}`,
)
pluginLoadFailed(entry, manifest, "was skipped: it failed to initialise", err)
}
}
return instances
@@ -688,6 +715,16 @@ export async function loadQuartzConfig(
byPageType: layout.byPageType,
}),
)
if (
loadFailures.length > 0 &&
brokenPluginsFailBuild() &&
process.env.QUARTZ_CONFIG_QUIET !== "1"
) {
throw new Error(
`${loadFailures.length} enabled plugin${loadFailures.length === 1 ? "" : "s"} could not be loaded: ${loadFailures.join(", ")} (see above). ` +
`Builds in CI fail on this; locally the build continues without them. Set QUARTZ_ALLOW_BROKEN_PLUGINS=1 to build anyway.`,
)
}
return {
configuration,
plugins,
+32 -8
View File
@@ -14,7 +14,7 @@ import { isMainThread } from "node:worker_threads"
* copies (CLI + bundled build). Worker threads have their own store; they only need plugin origins.
*/
export type DiagnosticSeverity = "warning" | "info"
export type DiagnosticSeverity = "error" | "warning" | "info"
export interface Diagnostic {
severity: DiagnosticSeverity
@@ -75,7 +75,7 @@ export function recordDiagnostic(diagnostic: Diagnostic): boolean {
if (s.keys.has(key)) return false
s.keys.add(key)
s.diagnostics.push(diagnostic)
if (diagnostic.plugin && diagnostic.severity === "warning") {
if (diagnostic.plugin && diagnostic.severity !== "info") {
const list = s.knownProblems.get(diagnostic.plugin) ?? []
list.push(diagnostic.message)
s.knownProblems.set(diagnostic.plugin, list)
@@ -141,15 +141,42 @@ export function warn(diagnostic: Omit<Diagnostic, "severity">): void {
if (diagnostic.hint) console.warn(styleText("gray", ` → ${diagnostic.hint}`))
}
/** Print the end-of-build summary of warnings (and infos with --verbose). */
/**
* Record an error and print it right away (main thread, once). Used for plugins that could not be
* loaded: the build continues without them locally, so the error is repeated in the summary.
*/
export function reportError(diagnostic: Omit<Diagnostic, "severity">): void {
const fresh = recordDiagnostic({ ...diagnostic, severity: "error" })
if (!fresh || !isMainThread || process.env.QUARTZ_CONFIG_QUIET === "1") return
console.error(styleText("red", "✗") + ` ${diagnostic.message}`)
for (const line of diagnostic.hint?.split("\n") ?? [])
console.error(styleText("gray", ` → ${line}`))
}
function pushDiagnostic(lines: string[], d: Diagnostic) {
lines.push(` ${styleText("gray", `[${d.area}]`)} ${d.message}`)
for (const line of d.hint?.split("\n") ?? []) lines.push(styleText("gray", ` → ${line}`))
}
/** Print the end-of-build summary of errors, warnings (and infos with --verbose). */
export function printDiagnosticsSummary(options: { verbose?: boolean } = {}): void {
if (!isMainThread || process.env.QUARTZ_CONFIG_QUIET === "1") return
const all = getDiagnostics()
const errors = all.filter((d) => d.severity === "error")
const warnings = all.filter((d) => d.severity === "warning")
const infos = all.filter((d) => d.severity === "info")
if (warnings.length === 0 && infos.length === 0) return
if (errors.length === 0 && warnings.length === 0 && infos.length === 0) return
const lines: string[] = [""]
if (errors.length > 0) {
lines.push(
styleText(
"red",
`✗ ${errors.length} error${errors.length === 1 ? "" : "s"} — the build continued, but parts of the site may be missing:`,
),
)
for (const d of errors) pushDiagnostic(lines, d)
}
if (warnings.length > 0) {
lines.push(
styleText(
@@ -157,10 +184,7 @@ export function printDiagnosticsSummary(options: { verbose?: boolean } = {}): vo
`⚠ Build finished with ${warnings.length} warning${warnings.length === 1 ? "" : "s"}:`,
),
)
for (const d of warnings.slice(0, 15)) {
lines.push(` ${styleText("gray", `[${d.area}]`)} ${d.message}`)
if (d.hint) lines.push(styleText("gray", ` → ${d.hint}`))
}
for (const d of warnings.slice(0, 15)) pushDiagnostic(lines, d)
if (warnings.length > 15) lines.push(styleText("gray", ` … and ${warnings.length - 15} more`))
}
for (const d of options.verbose ? infos : infos.slice(0, 5)) {
+44 -1
View File
@@ -10,8 +10,10 @@ import {
knownProblemsFor,
recordFiltered,
getDiagnostics,
reportError,
printDiagnosticsSummary,
} from "./diagnostics"
import { describePluginError } from "./trace"
import { describePluginError, firstPluginFrame } from "./trace"
import { findUnresolvedLinks, reportUnresolvedLinks } from "./linkReport"
import type { BuildCtx } from "./ctx"
import type { ProcessedContent } from "../plugins/vfile"
@@ -176,3 +178,44 @@ describe("unresolved links report", () => {
)
})
})
describe("plugin load failures", () => {
beforeEach(() => resetDiagnostics())
test("firstPluginFrame prefers frames inside plugin packages", () => {
const err = new Error("boom")
err.stack = [
"Error: boom",
" at load (node:internal/modules/esm/loader:1:1)",
" at file:///site/node_modules/unified/lib/index.js:5:1",
" at init (file:///site/node_modules/@quartz-community/graph/dist/index.js:12:5)",
" at loadQuartzConfig (file:///site/quartz/plugins/loader/config-loader.ts:400:1)",
].join("\n")
assert.strictEqual(
firstPluginFrame(err),
"/site/node_modules/@quartz-community/graph/dist/index.js:12:5",
)
assert.strictEqual(firstPluginFrame("not an error"), undefined)
})
test("errors are recorded as known problems and lead the summary", (t) => {
const lines: string[] = []
t.mock.method(console, "error", () => {})
t.mock.method(console, "log", (text: string) => lines.push(text))
reportError({
area: "plugins",
plugin: "graph",
message: "graph@1.0.0 failed to load its entry module: boom",
hint: "at /x/graph/dist/index.js:1:7\nsource: @quartz-community/graph",
})
recordDiagnostic({ severity: "warning", area: "config", message: "some warning" })
assert.deepStrictEqual(knownProblemsFor({ name: "graph", displayName: "graph" }), [
"graph@1.0.0 failed to load its entry module: boom",
])
printDiagnosticsSummary()
const text = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "")
assert.match(text, /1 error — the build continued/)
assert.match(text, /→ at \/x\/graph\/dist\/index\.js:1:7\n.*→ source: @quartz-community\/graph/)
assert.ok(text.indexOf("failed to load") < text.indexOf("some warning"))
})
})
+18
View File
@@ -18,6 +18,24 @@ const STAGE_LABEL: Record<PluginErrorInfo["stage"], string> = {
config: "loading the configuration",
}
/**
* The most useful stack frame of an error thrown while loading a plugin: the first frame inside a
* plugin package, else the first frame outside node_modules. Returns e.g. "…/graph/dist/index.js:12:5".
*/
export function firstPluginFrame(err: unknown): string | undefined {
if (!(err instanceof Error) || !err.stack) return undefined
const frames = err.stack
.split("\n")
.slice(1)
.map((line) => line.trim())
.filter((line) => line.startsWith("at "))
const frame =
frames.find((l) => pluginFrame.test(l)) ?? frames.find((l) => !l.includes("node_modules"))
if (!frame) return undefined
const location = frame.match(/\(([^)]+)\)$/)?.[1] ?? frame.slice(3)
return location.replace(/^file:\/\//, "")
}
/** Lines explaining which plugin failed, why it might have, and where to report it. */
export function describePluginError(info: PluginErrorInfo): string[] {
const { origin } = info