Compare commits

..
16 changed files with 220 additions and 22 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Plugins can declare `window.quartzStaticUrl` and `window.quartzPrefetch` in `capabilities.requires.globals` without a false "nothing provides it" warning: Quartz counts both as its own (`quartzPrefetch` unless `prefetch` is off).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
A plugin whose dependency is configured but disabled gets the intended warning ("depends on X which is disabled") instead of failing the build with "requires X. Run: npx quartz plugin add X".
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Plugin option checks use the option schemas first-party plugins ship. These are declared as `quartz.optionSchema`, the name Quartz Syncer reads, as a flat map of option to type (`{ limit: { type: "number" }, mode: { type: "enum", values: [...] } }`). Before, only a JSON Schema in `quartz.configSchema` was read, so no first-party plugin's schema was used. A misspelled option, an enum value that isn't allowed, or a value of the wrong type is now a warning. A value of the same type as the plugin's default is always accepted, even where a schema disagrees.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Sites created with `npx quartz create` from a template (default, blog, docs, obsidian, ttrpg) run GitHubFlavoredMarkdown before ObsidianFlavoredMarkdown (orders 30 and 40), as the default config does and 5.1 requires. The templates still had the old orders (40 and 30). The obsidian and ttrpg templates no longer set `parseArrows`, which ObsidianFlavoredMarkdown doesn't have.
+35 -4
View File
@@ -137,14 +137,38 @@ export function findConfigEntries(plugins, query, { extractName, formatSource })
return { indices: [], suggestion }
}
/**
* The JSON Schema of a plugin's options: `configSchema`, or `optionSchema`, the name first-party
* plugins (and Quartz Syncer) use. An `optionSchema` is usually a flat map of option name to
* property schema (`{ limit: { type: "number" }, mode: { type: "enum", values: [...] } }`); it is
* read as `{ type: "object", properties: … }`, with `type: "enum"` + `values` as a JSON `enum`.
*
* @param {{ configSchema?: any, optionSchema?: any }} manifest
* @returns {any | null}
*/
export function optionsSchemaOf(manifest) {
const declared = manifest.configSchema ?? manifest.optionSchema
if (!isPlainObject(declared)) return null
if (isPlainObject(declared.properties) || declared.type === "object") return declared
const properties = {}
for (const [key, prop] of Object.entries(declared)) {
if (!isPlainObject(prop)) continue
properties[key] =
prop.type === "enum" && Array.isArray(prop.values)
? { ...prop, type: undefined, enum: prop.values }
: prop
}
return { type: "object", properties }
}
/**
* Validate a plugin's options against its manifest (`defaultOptions` and, when
* present, `configSchema`). Unknown keys are only flagged as warnings when they
* present, `configSchema`, or its alias `optionSchema`). Unknown keys are only flagged as warnings when they
* look like a typo of a known key (or the schema forbids extra keys), because
* many plugins accept options that have no default.
*
* @param {unknown} options
* @param {{ defaultOptions?: Record<string, unknown>, configSchema?: any } | null | undefined} manifest
* @param {{ defaultOptions?: Record<string, unknown>, configSchema?: any, optionSchema?: any } | null | undefined} manifest
* @param {string} [prefix]
* @returns {Array<{ severity: "warning" | "info", path: string, message: string, suggestion?: string }>}
*/
@@ -153,7 +177,7 @@ export function validatePluginOptions(options, manifest, prefix = "") {
if (!isPlainObject(options) || !manifest) return issues
const defaults = isPlainObject(manifest.defaultOptions) ? manifest.defaultOptions : {}
const schema = isPlainObject(manifest.configSchema) ? manifest.configSchema : null
const schema = optionsSchemaOf(manifest)
const schemaProps = schema && isPlainObject(schema.properties) ? schema.properties : {}
const known = new Set([...Object.keys(defaults), ...Object.keys(schemaProps)])
if (known.size === 0) return issues
@@ -211,7 +235,14 @@ export function validatePluginOptions(options, manifest, prefix = "") {
? describeType(defaults[key])
: null
const actual = describeType(value)
if (expected && expected !== actual) {
// a value of the default's own type is fine even when the schema says otherwise (schemas
// can lag behind: recent-notes' `linkToMore` is typed string, its default is false)
const matchesDefault =
key in defaults &&
defaults[key] !== null &&
defaults[key] !== undefined &&
describeType(defaults[key]) === actual
if (expected && expected !== actual && !matchesDefault) {
const shown = key in defaults ? ` (default: ${JSON.stringify(defaults[key])})` : ""
issues.push({
severity: "warning",
+45
View File
@@ -137,6 +137,51 @@ describe("validatePluginOptions", () => {
assert.strictEqual(issues[0].suggestion, "dark")
assert.strictEqual(issues[1].severity, "warning")
})
// first-party plugins (and Quartz Syncer) name the field optionSchema, as a flat map
test("reads a flat optionSchema, with type enum + values", () => {
const manifest = {
defaultOptions: { limit: 3 },
optionSchema: {
limit: { type: "number" },
mode: { type: "enum", values: ["light", "dark"] },
show: { type: "boolean" },
},
}
const issues = validatePluginOptions({ mode: "drak", limit: "5", shwo: true }, manifest)
assert.deepStrictEqual(
issues.map((i) => [i.path, i.severity, i.suggestion]),
[
["mode", "warning", "dark"],
["limit", "warning", undefined],
["shwo", "warning", "show"],
],
)
assert.deepStrictEqual(validatePluginOptions({ mode: "dark", show: false }, manifest), [])
})
test("accepts a value of the default's type when the schema disagrees", () => {
const manifest = {
defaultOptions: { linkToMore: false },
optionSchema: { linkToMore: { type: "string" } },
}
assert.deepStrictEqual(validatePluginOptions({ linkToMore: false }, manifest), [])
assert.deepStrictEqual(validatePluginOptions({ linkToMore: "tags/" }, manifest), [])
assert.strictEqual(validatePluginOptions({ linkToMore: 3 }, manifest)[0]?.severity, "warning")
})
test("reads optionSchema as the same schema", () => {
const issues = validatePluginOptions(
{ mode: "drak" },
{
optionSchema: {
type: "object",
properties: { mode: { type: "string", enum: ["light", "dark"] } },
},
},
)
assert.strictEqual(issues[0]?.suggestion, "dark")
})
})
describe("validatePluginEntry", () => {
+63
View File
@@ -0,0 +1,63 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import fs from "node:fs"
import path from "node:path"
import { createRequire } from "node:module"
import YAML from "yaml"
import { validatePluginOptions } from "./plugin-validation.js"
const root = path.resolve(import.meta.dirname, "..", "..")
const templatesDir = path.join(import.meta.dirname, "templates")
const configs = [
path.join(root, "quartz.config.default.yaml"),
...fs
.readdirSync(templatesDir)
.filter((f) => f.endsWith(".yaml"))
.map((f) => path.join(templatesDir, f)),
]
const require = createRequire(path.join(root, "package.json"))
// Options the plugins read but their manifests don't declare yet (no defaultOptions entry or
// schema): accepted here until the manifest lists them.
const UNDECLARED_BUT_REAL = {
"@quartz-community/recent-notes": ["title"],
"@quartz-themes/core": ["variation"],
}
function manifestOf(source) {
try {
return JSON.parse(fs.readFileSync(require.resolve(`${source}/package.json`), "utf8")).quartz
} catch {
return undefined
}
}
for (const file of configs) {
const name = path.relative(root, file)
const plugins = YAML.parse(fs.readFileSync(file, "utf8")).plugins ?? []
const bySource = new Map(plugins.map((entry) => [entry.source, entry]))
describe(name, () => {
test("runs GitHubFlavoredMarkdown before ObsidianFlavoredMarkdown", () => {
const gfm = bySource.get("@quartz-community/github-flavored-markdown")
const ofm = bySource.get("@quartz-community/obsidian-flavored-markdown")
if (!gfm || !ofm) return
assert.ok(gfm.order < ofm.order, `GFM order ${gfm.order} must be below OFM ${ofm.order}`)
})
test("sets only options the plugins have", () => {
const problems = []
for (const entry of plugins) {
if (typeof entry.source !== "string" || !entry.options) continue
const manifest = manifestOf(entry.source)
if (!manifest) continue
const allowed = UNDECLARED_BUT_REAL[entry.source] ?? []
for (const issue of validatePluginOptions(entry.options, manifest)) {
if (allowed.includes(issue.path)) continue
problems.push(`${entry.source}: ${issue.message}`)
}
}
assert.deepStrictEqual(problems, [])
})
})
}
+2 -2
View File
@@ -70,10 +70,10 @@ plugins:
options:
enableInHtmlEmbed: false
enableCheckbox: true
order: 30
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
order: 30
- source: "@quartz-community/table-of-contents"
enabled: true
order: 50
+2 -2
View File
@@ -70,10 +70,10 @@ plugins:
options:
enableInHtmlEmbed: false
enableCheckbox: true
order: 30
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
order: 30
- source: "@quartz-community/table-of-contents"
enabled: true
order: 50
+2 -2
View File
@@ -71,10 +71,10 @@ plugins:
options:
enableInHtmlEmbed: false
enableCheckbox: true
order: 30
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
order: 30
- source: "@quartz-community/table-of-contents"
enabled: true
order: 50
+2 -3
View File
@@ -75,16 +75,15 @@ plugins:
callouts: true
mermaid: true
parseTags: true
parseArrows: true
parseBlockReferences: true
enableInHtmlEmbed: false
enableYouTubeEmbed: true
enableVideoEmbed: true
enableCheckbox: true
order: 30
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
order: 30
- source: "@quartz-community/table-of-contents"
enabled: true
order: 50
+2 -3
View File
@@ -75,16 +75,15 @@ plugins:
callouts: true
mermaid: true
parseTags: true
parseArrows: true
parseBlockReferences: true
enableInHtmlEmbed: false
enableYouTubeEmbed: true
enableVideoEmbed: true
enableCheckbox: true
order: 30
order: 40
- source: "@quartz-community/github-flavored-markdown"
enabled: true
order: 40
order: 30
- source: "@quartz-community/table-of-contents"
enabled: true
order: 50
@@ -197,3 +197,12 @@ describe("validatePluginCapabilities", () => {
assert.deepStrictEqual(report.warnings, [])
})
})
describe("core globals", () => {
test("quartzStaticUrl always, quartzPrefetch unless prefetching is off", () => {
assert.ok(coreCapabilities().globals?.includes("quartzStaticUrl"))
assert.ok(coreCapabilities().globals?.includes("quartzPrefetch"))
assert.ok(coreCapabilities({ prefetch: "hover" }).globals?.includes("quartzPrefetch"))
assert.ok(!coreCapabilities({ prefetch: "off" }).globals?.includes("quartzPrefetch"))
})
})
+15 -4
View File
@@ -87,14 +87,25 @@ export interface CapabilityReport {
* Capabilities Quartz core itself always provides (independent of plugins).
* Kept deliberately small: only things core code sets or renders unconditionally.
*/
export function coreCapabilities(configuration?: { enableSPA?: boolean }): CapabilityList {
export function coreCapabilities(configuration?: {
enableSPA?: boolean
prefetch?: string | boolean
}): CapabilityList {
const prefetch = configuration?.prefetch !== "off" && configuration?.prefetch !== false
return {
// quartz/processors/parse.ts
data: ["slug", "filePath", "relativePath"],
// renderPage.tsx / frames
dom: ["#quartz-body", ".page", ".center", "article", ".popover-hint", ".sidebar"],
// renderPage.tsx (fetchData), componentResources.ts (spaNavigate/addCleanup, SPA or not)
globals: ["fetchData", "addCleanup", "spaNavigate"],
// renderPage.tsx (fetchData, quartzStaticUrl), componentResources.ts (spaNavigate/addCleanup,
// SPA or not; quartzPrefetch unless prefetching is off)
globals: [
"fetchData",
"addCleanup",
"spaNavigate",
"quartzStaticUrl",
...(prefetch ? ["quartzPrefetch"] : []),
],
// componentResources.ts dispatches "nav" in both modes; spa.inline.ts adds "prenav"
events: configuration?.enableSPA === false ? ["nav"] : ["nav", "prenav"],
}
@@ -303,7 +314,7 @@ export async function validatePluginCapabilities<E extends { enabled: boolean }>
manifestFor: (
entry: E,
) => Promise<ManifestLike | null | undefined> | ManifestLike | null | undefined
configuration?: { enableSPA?: boolean }
configuration?: { enableSPA?: boolean; prefetch?: string | boolean }
/** Built-in processing steps (see plugins/builtins): enabled ones provide, others are suggested. */
builtins?: { enabled: CapabilityPlugin[]; available: CapabilityPlugin[] }
}): Promise<CapabilityReport> {
@@ -373,3 +373,19 @@ describe("dependencies on plugins that are built in now", () => {
assert.match(errors[0], /requires "@quartz-community\/explorer"/)
})
})
describe("a dependency that is configured but disabled", () => {
test("is a warning, not a missing plugin", () => {
const dep = "@quartz-community/explorer"
const entries: PluginJsonEntry[] = [
{ source: "github:someone/x", enabled: true, options: {} },
{ source: dep, enabled: false, options: {} },
]
const manifests = new Map<string, PluginManifest>([
["github:someone/x", { dependencies: [dep] } as unknown as PluginManifest],
])
const { errors, warnings } = validateDependencies(entries, manifests, [])
assert.deepStrictEqual(errors, [])
assert.match(warnings[0], /depends on "@quartz-community\/explorer" which is disabled/)
})
})
+7 -2
View File
@@ -215,6 +215,8 @@ export function validateDependencies(
warnings.push(
`Plugin "${pluginName}" depends on "${depName}" which is disabled. "${pluginName}" may not function correctly.`,
)
// it doesn't run, so its order doesn't matter (and its manifest isn't loaded)
continue
}
const depManifest = manifests.get(dep)
@@ -325,7 +327,8 @@ async function readManifestFromPackageJson(source: PluginSource): Promise<Plugin
defaultOrder: q.defaultOrder,
defaultEnabled: q.defaultEnabled,
defaultOptions: q.defaultOptions,
configSchema: q.configSchema,
// first-party plugins (and Quartz Syncer) call it optionSchema
configSchema: q.configSchema ?? q.optionSchema,
components: q.components,
frames: q.frames,
}
@@ -505,7 +508,9 @@ export async function loadQuartzConfig(
)
// Validate dependencies
const validation = validateDependencies(enabledEntries, manifests, builtinPlan.builtins)
// all entries: a dependency that is configured but disabled is a warning, not "missing"
// (validateDependencies skips disabled plugins itself)
const validation = validateDependencies(pluginEntries, manifests, builtinPlan.builtins)
for (const warning of validation.warnings) {
console.warn(styleText("yellow", `⚠`) + ` ${warning}`)
}