fix(assets): match published (slugified) names, <object data>, srcset and encoded paths for publishAssets: referenced

Follow-up to #2544: references were compared with source paths, so "my photo.png"
(published as my-photo.png) and ofm's <object data> SVG embeds were dropped. The
integration test swapped the repository's own quartz.config.yaml to build a fixture
site; replaced by unit tests of the emitter. Documented publishAssets.
This commit is contained in:
saberzero1 committed 2026-11-07 22:23:03 +01:00
1 parent 63ea0b7190
commit 3103485049
14 files changed
+156 -389

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New `configuration.publishAssets: "referenced"` (default `"all"`): only copy the images, PDFs and other files that published pages link to or embed, so files that only unpublished notes use stay private (#2531, from #2544). References are matched against published (slugified) file names and include `<object data>` SVG embeds, `srcset` and URL-encoded paths.
+3
View File
@@ -45,6 +45,9 @@ This part of the configuration concerns anything that can affect the whole site.
- You will be prompted to set this during [[create|`npx quartz create`]]. The CLI automatically strips any `https://` or `http://` protocol prefixes and trailing slashes for you.
- This should also include the subpath if you are [[hosting]] on GitHub pages without a custom domain. For example, if my repository is `jackyzha0/quartz`, GitHub pages would deploy to `https://jackyzha0.github.io/quartz` and the `baseUrl` would be `jackyzha0.github.io/quartz`.
- Note that Quartz 5 will avoid using this as much as possible and use relative URLs whenever it can to make sure your site works no matter _where_ you end up actually deploying it.
- `publishAssets`: which non-Markdown files (images, PDFs, …) from `content` are copied to the site.
- `"all"` (default): every file that isn't ignored.
- `"referenced"`: only files a published page links to or embeds. Use this with [[ExplicitPublish]] or [[private pages|drafts]], so that files only unpublished notes use stay private.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `theme`: configure how the site looks.
- `fontOrigin`: where to load fonts from.
+3
View File
@@ -16,6 +16,9 @@ This plugin filters content based on an explicit `publish` flag in the frontmatt
This plugin has no configuration options.
> [!tip]
> Images and other files are copied to your site whether or not a published page uses them. Set `configuration.publishAssets: referenced` to only publish the files that published pages link to or embed.
## API
- Category: Filter
+99 -117
View File
@@ -1,130 +1,112 @@
import test, { describe, before, after } from "node:test"
import test, { describe } from "node:test"
import assert from "node:assert"
import fs from "fs/promises"
import path from "path"
import { fileURLToPath } from "url"
import { spawn } from "child_process"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { VFile } from "vfile"
import type { Root, Element } from "hast"
import { Assets } from "./assets"
import type { BuildCtx } from "../../util/ctx"
import type { ProcessedContent } from "../vfile"
import type { StaticResources } from "../../util/resources"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const el = (tagName: string, properties: Element["properties"]): Element => ({
type: "element",
tagName,
properties,
children: [],
})
// Repo root is 3 levels up from quartz/plugins/emitters/
const REPO_ROOT = path.join(__dirname, "..", "..", "..")
const TEST_FIXTURE = path.join(REPO_ROOT, "test", "fixtures", "asset-filtering")
const OUTPUT_DIR = path.join(TEST_FIXTURE, "public")
const TEST_CONFIG = path.join(TEST_FIXTURE, "quartz.config.yaml")
// The CLI always resolves `quartz.config.yaml` relative to process.cwd(),
// so building the fixture requires temporarily swapping the repo's own
// config file. This is not parallel-safe against other processes touching
// that file, but no other test in this suite does.
const REPO_CONFIG = path.join(REPO_ROOT, "quartz.config.yaml")
async function cleanOutput() {
await fs.rm(OUTPUT_DIR, { recursive: true, force: true })
/** A published page whose rendered tree contains the given elements. */
function page(slug: string, relativePath: string, ...children: Element[]): ProcessedContent {
const tree: Root = { type: "root", children }
const file = new VFile("")
file.data = { slug, relativePath } as VFile["data"]
return [tree as never, file]
}
function runQuartzBuild(): Promise<{ code: number; stdout: string; stderr: string }> {
return new Promise((resolve) => {
const child = spawn(
process.execPath,
async function emitReferenced(files: string[], content: ProcessedContent[]) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-assets-referenced-"))
const directory = path.join(root, "content")
const output = path.join(root, "public")
for (const f of files) {
fs.mkdirSync(path.dirname(path.join(directory, f)), { recursive: true })
fs.writeFileSync(path.join(directory, f), "x")
}
const ctx = {
argv: { directory, output },
cfg: {
configuration: { publishAssets: "referenced", ignorePatterns: [] },
plugins: { pageTypes: [] },
},
} as unknown as BuildCtx
const written: string[] = []
for await (const fp of Assets().emit(ctx, content, {} as StaticResources) as AsyncIterable<
Promise<string> | string
>) {
written.push(
path
.relative(output, await fp)
.split(path.sep)
.join("/"),
)
}
fs.rmSync(root, { recursive: true, force: true })
return written.sort()
}
describe('publishAssets: "referenced" (#2531)', () => {
test("copies only files published pages reference, however they reference them", async () => {
const written = await emitReferenced(
[
path.join(REPO_ROOT, "quartz/bootstrap-cli.mjs"),
"build",
"-d",
"test/fixtures/asset-filtering",
"-o",
"test/fixtures/asset-filtering/public",
"images/my photo.png", // published under its slugified name
"diagram.svg",
"files/report.pdf",
"hero.png",
"été.png",
"secret.png", // only an unpublished page links to it (not in `content`)
"orphan.png",
"notes/private.md",
],
[
page(
"notes/page",
"notes/page.md",
el("img", { src: "../images/my-photo.png" }),
el("object", { data: "../diagram.svg", type: "image/svg+xml" }), // ofm's SVG embed
el("a", { href: "/files/report.pdf" }),
el("img", { src: "x", srcSet: "../hero.png 2x, ../hero.png 1x" }),
el("img", { src: "../%C3%A9t%C3%A9.png" }),
el("a", { href: "https://example.com/orphan.png" }),
),
],
{
cwd: REPO_ROOT,
stdio: ["ignore", "pipe", "pipe"],
},
)
let stdout = ""
let stderr = ""
child.stdout?.on("data", (data) => {
stdout += data.toString()
})
child.stderr?.on("data", (data) => {
stderr += data.toString()
})
child.on("close", (code) => {
resolve({ code: code ?? 0, stdout, stderr })
})
child.on("error", (err) => {
resolve({ code: 1, stdout, stderr: err.message })
})
})
}
describe("Assets emitter with publishAssets config", () => {
let originalConfig: string | null = null
before(async () => {
await cleanOutput()
originalConfig = await fs.readFile(REPO_CONFIG, "utf-8").catch(() => null)
const testConfigContent = await fs.readFile(TEST_CONFIG, "utf-8")
await fs.writeFile(REPO_CONFIG, testConfigContent)
assert.deepStrictEqual(written, [
"diagram.svg",
"files/report.pdf",
"hero.png",
"images/my-photo.png",
"été.png",
])
})
after(async () => {
await cleanOutput()
// Restore original config exactly as it was (or remove it if it never existed)
if (originalConfig !== null) {
await fs.writeFile(REPO_CONFIG, originalConfig)
} else {
await fs.rm(REPO_CONFIG, { force: true })
test('"all" (the default) still copies everything but Markdown', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-assets-all-"))
const directory = path.join(root, "content")
fs.mkdirSync(directory, { recursive: true })
fs.writeFileSync(path.join(directory, "orphan.png"), "x")
fs.writeFileSync(path.join(directory, "page.md"), "# x")
const ctx = {
argv: { directory, output: path.join(root, "public") },
cfg: { configuration: { ignorePatterns: [] }, plugins: { pageTypes: [] } },
} as unknown as BuildCtx
const written: string[] = []
for await (const fp of Assets().emit(ctx, [], {} as StaticResources) as AsyncIterable<
Promise<string> | string
>) {
written.push(path.basename(await fp))
}
})
test("publishAssets: 'referenced' only copies assets referenced by published pages", async () => {
const result = await runQuartzBuild()
if (result.code !== 0) {
console.error("Build failed:", result.stderr)
console.error("stdout:", result.stdout)
}
assert.strictEqual(result.code, 0, "Build should succeed")
const rawFiles = await fs.readdir(OUTPUT_DIR, { recursive: true })
// Normalize to POSIX separators — fs.readdir uses the platform separator
// (backslashes on Windows), but the assertions below use forward slashes.
const publicFiles = rawFiles.map((f) => f.split(path.sep).join("/"))
// Should exist: published page + its referenced assets
assert.ok(publicFiles.includes("content/published.html"), "published.html should exist")
assert.ok(
publicFiles.includes("content/diagram.png"),
"diagram.png (referenced by published) should exist",
)
assert.ok(
publicFiles.includes("content/assets/nested.png"),
"nested.png (referenced by published) should exist",
)
// Should NOT exist: filtered pages + their assets
assert.ok(
!publicFiles.includes("content/private.html"),
"private.html should NOT exist (filtered)",
)
assert.ok(
!publicFiles.includes("content/secret.png"),
"secret.png should NOT exist (only referenced by private)",
)
assert.ok(!publicFiles.includes("content/draft.html"), "draft.html should NOT exist (filtered)")
assert.ok(
!publicFiles.includes("content/draft-img.png"),
"draft-img.png should NOT exist (only referenced by draft)",
)
// Should NOT exist: orphan assets
assert.ok(
!publicFiles.includes("content/orphan.png"),
"orphan.png should NOT exist (unreferenced)",
)
fs.rmSync(root, { recursive: true, force: true })
assert.deepStrictEqual(written, ["orphan.png"])
})
})
+46 -32
View File
@@ -26,38 +26,50 @@ function normalizeAssetPath(raw: string): string {
return path.posix.normalize(raw.split("?")[0].split("#")[0]).replace(/^\.\//, "")
}
// Attributes that point at files: images, media, embeds (<object data>), downloads (<a href>)
const URL_ATTRIBUTES = ["src", "href", "data", "poster"] as const
function decode(value: string): string {
try {
return decodeURIComponent(value)
} catch {
return value
}
}
/**
* Site paths of everything published pages link to or embed. Page hrefs are relative to the
* page's output location (its slug), and point at slugified file names.
*/
function extractAssetReferences(content: ProcessedContent[]): Set<string> {
const assets = new Set<string>()
for (const [tree, file] of content) {
const baseDir = file.data.relativePath ? path.posix.dirname(file.data.relativePath) : ""
const location = file.data.slug ?? file.data.relativePath ?? ""
const baseDir = path.posix.dirname(location) === "." ? "" : path.posix.dirname(location)
const add = (raw: string) => {
if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith("//") || raw.startsWith("#")) return
let ref = decode(raw.split("?")[0].split("#")[0])
if (!ref) return
ref = ref.startsWith("/") ? ref.slice(1) : path.posix.join(baseDir, ref)
ref = path.posix.normalize(ref).replace(/^\.\//, "")
if (ref && !ref.startsWith("..")) assets.add(ref)
}
visit(tree, "element", (node: Element) => {
// Track both src (images, video, audio, iframe) and href (links to downloadable files)
const src = node.properties?.src
const href = node.properties?.href
for (const assetPath of [src, href]) {
if (!assetPath || typeof assetPath !== "string") continue
if (
assetPath.startsWith("http://") ||
assetPath.startsWith("https://") ||
assetPath.startsWith("data:")
)
continue
let normalized = assetPath.split("?")[0].split("#")[0]
// Handle root-relative paths (e.g., "/diagram.png") by stripping leading slash
if (normalized.startsWith("/")) {
normalized = normalized.slice(1)
}
if (baseDir && !normalized.startsWith("/")) {
normalized = path.posix.join(baseDir, normalized)
}
normalized = path.posix.normalize(normalized).replace(/^\.\//, "")
if (normalized) {
assets.add(normalized)
}
for (const attr of URL_ATTRIBUTES) {
const value = node.properties?.[attr]
if (typeof value === "string") add(value)
}
const srcset = node.properties?.srcSet ?? node.properties?.srcset
for (const candidate of Array.isArray(srcset)
? srcset
: typeof srcset === "string"
? srcset.split(",")
: []) {
const url = String(candidate).trim().split(/\s+/)[0]
if (url) add(url)
}
})
}
@@ -65,6 +77,11 @@ function extractAssetReferences(content: ProcessedContent[]): Set<string> {
return assets
}
/** Whether a content file is referenced, by its source path or its published (slugified) path. */
function isReferenced(references: Set<string>, fp: string): boolean {
return references.has(normalizeAssetPath(fp)) || references.has(slugifyFilePath(fp as FilePath))
}
const filesToCopy = async (argv: Argv, cfg: QuartzConfig, excludeExtensions: Set<string>) => {
const excludePatterns = ["**/*.md", ...cfg.configuration.ignorePatterns]
for (const ext of excludeExtensions) {
@@ -99,7 +116,7 @@ export const Assets: QuartzEmitterPlugin = () => {
if (publishAssets === "referenced") {
const referencedAssets = extractAssetReferences(content)
for (const fp of allCandidates) {
if (referencedAssets.has(normalizeAssetPath(fp))) {
if (isReferenced(referencedAssets, fp)) {
yield copyFile(ctx.argv, fp)
}
}
@@ -125,9 +142,8 @@ export const Assets: QuartzEmitterPlugin = () => {
const referencedAssets = extractAssetReferences(content)
const allCandidates = await filesToCopy(ctx.argv, ctx.cfg, excludeExtensions)
for (const fp of allCandidates) {
const normalized = normalizeAssetPath(fp)
const dest = joinSegments(ctx.argv.output, slugifyFilePath(fp)) as FilePath
if (referencedAssets.has(normalized)) {
if (isReferenced(referencedAssets, fp)) {
yield copyFile(ctx.argv, fp)
} else {
await fs.promises.rm(dest, { force: true })
@@ -148,9 +164,7 @@ export const Assets: QuartzEmitterPlugin = () => {
continue
}
const normalized = normalizeAssetPath(changeEvent.path)
if (publishAssets === "referenced" && !referencedAssets!.has(normalized)) {
if (publishAssets === "referenced" && !isReferenced(referencedAssets!, changeEvent.path)) {
continue
}
@@ -1 +0,0 @@
fake png content
-1
View File
@@ -1 +0,0 @@
fake png content
-1
View File
@@ -1 +0,0 @@
fake png content
-10
View File
@@ -1,10 +0,0 @@
---
title: "Draft Note"
draft: true
---
# Draft Note
This is a draft.
![Draft Image](draft-img.png)
-1
View File
@@ -1 +0,0 @@
fake png content
-10
View File
@@ -1,10 +0,0 @@
---
title: "Private Note"
publish: false
---
# Private Note
This is NOT published.
![Secret](secret.png)
-12
View File
@@ -1,12 +0,0 @@
---
title: "Published Note"
publish: true
---
# Published Note
This is published.
![Diagram](diagram.png)
![Nested](assets/nested.png)
-1
View File
@@ -1 +0,0 @@
fake png content
-203
View File
@@ -1,203 +0,0 @@
# yaml-language-server: $schema=../../../quartz/plugins/quartz-plugins.schema.json
configuration:
pageTitle: "Asset Filtering Test"
enableSPA: true
enablePopovers: true
locale: en-US
baseUrl: "localhost"
theme:
fontOrigin: googleFonts
cdnCaching: false
typography:
header: Schibsted Grotesk
body: Source Sans Pro
code: IBM Plex Mono
colors:
lightMode:
light: "#ffffff"
lightgray: "#eeeeee"
gray: "#cccccc"
darkgray: "#666666"
dark: "#333333"
secondary: "#0066cc"
tertiary: "#666666"
highlight: "rgba(0,0,0,0.1)"
textHighlight: "#ffff00"
darkMode:
light: "#1a1a1a"
lightgray: "#333333"
gray: "#666666"
darkgray: "#999999"
dark: "#ffffff"
secondary: "#66aaff"
tertiary: "#999999"
highlight: "rgba(255,255,255,0.1)"
textHighlight: "#ffff00"
publishAssets: "referenced"
ignorePatterns: []
plugins:
- source: "@quartz-community/created-modified-date"
enabled: true
options:
defaultDateType: modified
priority:
- frontmatter
- git
- filesystem
- source: "@quartz-community/syntax-highlighting"
enabled: true
options:
theme:
light: github-light
dark: github-dark
keepBackground: false
- source: "@quartz-community/obsidian-flavored-markdown"
enabled: true
options:
enableInHtmlEmbed: false
enableCheckbox: true
- source: "@quartz-community/github-flavored-markdown"
enabled: true
- source: "@quartz-community/table-of-contents"
enabled: true
layout:
position: right
priority: 30
- source: "@quartz-community/crawl-links"
enabled: true
options:
markdownLinkResolution: shortest
- source: "@quartz-community/description"
enabled: true
- source: "@quartz-community/latex"
enabled: true
options:
renderEngine: katex
- source: "@quartz-community/quartz-fonts"
enabled: true
- source: "@quartz-community/remove-draft"
enabled: true
- source: "@quartz-community/explicit-publish"
enabled: true
- source: "@quartz-community/alias-redirects"
enabled: true
- source: "@quartz-community/content-index"
enabled: true
options:
enableSiteMap: true
enableRSS: true
- source: "@quartz-community/favicon"
enabled: true
- source: "@quartz-community/og-image"
enabled: true
- source: "@quartz-community/cname"
enabled: true
- source: "@quartz-community/canvas-page"
enabled: true
- source: "@quartz-community/content-page"
enabled: true
- source: "@quartz-community/folder-page"
enabled: true
- source: "@quartz-community/tag-page"
enabled: true
- source: "@quartz-community/explorer"
enabled: true
layout:
position: left
priority: 50
- source: "@quartz-community/graph"
enabled: true
layout:
position: right
priority: 10
- source: "@quartz-community/search"
enabled: true
layout:
position: left
priority: 20
group: toolbar
groupOptions:
grow: true
- source: "@quartz-community/backlinks"
enabled: true
layout:
position: right
priority: 50
- source: "@quartz-community/article-title"
enabled: true
layout:
position: beforeBody
priority: 10
- source: "@quartz-community/content-meta"
enabled: true
layout:
position: beforeBody
priority: 20
- source: "@quartz-community/page-title"
enabled: true
layout:
position: left
priority: 10
- source: "@quartz-community/darkmode"
enabled: true
layout:
position: left
priority: 30
group: toolbar
- source: "@quartz-community/reader-mode"
enabled: true
layout:
position: left
priority: 35
group: toolbar
- source: "@quartz-community/breadcrumbs"
enabled: true
layout:
position: beforeBody
priority: 5
condition: not-index
- source: "@quartz-community/footer"
enabled: true
options:
links:
GitHub: https://github.com/jackyzha0/quartz
Discord Community: https://discord.gg/cRFFHYye7t
layout:
position: footer
priority: 50
- source: "@quartz-community/spacer"
enabled: true
options: {}
layout:
position: left
priority: 25
display: mobile-only
- source: "@quartz-community/bases-page"
enabled: true
options: {}
- source: "@quartz-community/note-properties"
enabled: true
options:
includeAll: false
includedProperties:
- description
- tags
- aliases
excludedProperties: []
hidePropertiesView: false
delimiters: "---"
language: yaml
layout:
position: beforeBody
priority: 15
display: all
- source: "@quartz-community/unlisted-pages"
enabled: true
options: {}
- source: "@quartz-community/encrypted-pages"
enabled: true
options:
iterations: 600000
passwordField: password
unlistWhenEncrypted: false
outputPath: static/encryptedContentIndex.json