feat: publish filters and virtualPageHtmlPlugins for pages rendered from files (bases-page#11)

This commit is contained in:
saberzero1 committed 2026-11-09 04:32:27 +01:00
1 parent df7e0180da
commit fe6a3ea879
8 files changed
+342 -22

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings) follow the site's publish filters (quartz-community/bases-page#11). The filters see each such page with the frontmatter its page type gives it and `file.data.referencedBy`, the published pages that link to it; a page a filter rejects is not emitted and not listed in the content index, sitemap, RSS, folder pages, explorer or search, and can't be embedded. Before, every such file was published regardless of the filters. New transformer hook `virtualPageHtmlPlugins(ctx, content)`: rehype plugins run on these pages' rendered bodies, which never pass through `htmlPlugins`, so plugins such as encrypted-pages can encrypt them.
+5 -1
View File
@@ -96,6 +96,7 @@ export type QuartzTransformerPluginInstance = {
textTransform?: (ctx: BuildCtx, src: string) => string
markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
}
```
@@ -105,6 +106,7 @@ All transformer plugins must define at least a `name` field to register the plug
- `textTransform` performs a text-to-text transformation _before_ a file is parsed into the [Markdown AST](https://github.com/syntax-tree/mdast).
- `markdownPlugins` defines a list of [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md). `remark` is a tool that transforms Markdown to Markdown in a structured way.
- `htmlPlugins` defines a list of [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md). Similar to how `remark` works, `rehype` is a tool that transforms HTML to HTML in a structured way.
- `virtualPageHtmlPlugins` (Quartz 5.1+) defines rehype plugins for the pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings). Those pages are rendered when emitting and never pass through `htmlPlugins`, so a plugin that should also act on them (e.g. encryption) registers its rehype plugin here too. They run on the page's rendered body, with the page's vfile (`file.data.frontmatter`, `file.data.referencedBy`), after the filters published the page; the page then shows the resulting tree. `content` is the published content.
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
Normally for both `remark` and `rehype`, you can find existing plugins that you can use. If you'd like to create your own `remark` or `rehype` plugin, checkout the [guide to creating a plugin](https://unifiedjs.com/learn/guide/create-a-plugin/) using `unified` (the underlying AST parser and transformer library).
@@ -257,6 +259,8 @@ export type QuartzFilterPluginInstance = {
A filter plugin must define a `name` field and a `shouldPublish` function that takes in a piece of content that has been processed by all the transformers and returns a `true` or `false` depending on whether it should be passed to the emitter plugins or not.
Filters also see the pages that page types render from files (Quartz 5.1+; page types that declare `fileExtensions`, e.g. `.base` and `.canvas` pages), with the frontmatter the page type gives them and `file.data.referencedBy`: the published pages that link to them. A page a filter rejects is not emitted, listed or embeddable. Such files may have no frontmatter (`.base`, `.canvas`): [[ExplicitPublish]] publishes them when a published page links to them.
For example, here is a filter that removes drafts (Quartz has this [[RemoveDrafts|built in]]):
```ts
@@ -389,7 +393,7 @@ export interface QuartzPageTypePluginInstance {
- `name`: A unique identifier for this page type.
- `priority`: Controls matching order when multiple page types could match a slug. Higher priority page types are checked first. Default: `0`.
- `fileExtensions`: Array of file extensions this page type handles (e.g. `[".canvas"]`, `[".base"]`). Content files (`.md`) are handled by the default content page type.
- `fileExtensions`: Array of file extensions this page type handles (e.g. `[".canvas"]`, `[".base"]`). Content files (`.md`) are handled by the default content page type. The pages of such a page type stand for files: Quartz runs the site's filters on them (Quartz 5.1+), so give each page the file's `filePath` / `relativePath` and, if the file has frontmatter, that frontmatter.
- `match`: A function that determines whether a given slug/file should be rendered by this page type.
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices). It receives `{ content, cfg, ctx }` and returns the pages, or (Quartz 5.1+) a promise of them, so it can do async work such as running content through the site's transformers or bundling with esbuild. Page types generate one after another, in priority order. A plugin with an async `generate` should declare `"quartzVersion": ">=5.1.0"`, since older versions don't wait for it.
- `layout`: The layout configuration key (e.g. `"content"`, `"folder"`, `"tag"`). This determines which `byPageType` entry in `quartz.config.yaml` provides the layout overrides for this page type.
+2
View File
@@ -12,6 +12,8 @@ There may be some notes you want to avoid publishing as a website. Quartz suppor
If you'd like to only publish a select number of notes, you can instead use [[ExplicitPublish]] which will filter out all notes except for any that have `publish: true` in the frontmatter.
Bases, canvases and Excalidraw drawings follow the same filters. A drawing stored as Markdown has frontmatter of its own. A `.base` or `.canvas` file has none: with [[ExplicitPublish]] it is published when a published note links to it, and with encrypted pages it is encrypted with the password of the encrypted note that links to it.
> [!warning]
> Regardless of the filter plugin used, **all non-markdown files will be emitted and available publicly in the final build.** This includes files such as images, voice recordings, PDFs, etc.
+2
View File
@@ -16,6 +16,8 @@ This plugin filters content based on an explicit `publish` flag in the frontmatt
This plugin has no configuration options.
Files without frontmatter — `.base`, `.canvas` and `.excalidraw` files — can't be marked `publish: true`. They are published when a published page links to them (`[[Board.canvas]]`, or an embed such as `![[Board.canvas]]`), like Obsidian Publish adding the files a published note links to, and not otherwise. A base embedded in a published note renders inside it without a page of its own. A drawing stored as Markdown (`.excalidraw.md`) follows its own `publish:` like a note. (Quartz 5.1+.)
> [!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.
+144 -1
View File
@@ -8,12 +8,15 @@ import {
folderTrie,
generateVirtualPages,
pageOutputPath,
processVirtualPageHtml,
referencesByTarget,
removeStalePageOutput,
resolveLayout,
} from "./dispatcher"
import { QuartzPageTypePluginInstance } from "../types"
import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug } from "../../util/path"
import { FilePath, FullSlug, SimpleSlug } from "../../util/path"
import { Root as HtmlRoot } from "hast"
import { BuildCtx } from "../../util/ctx"
import { defaultProcessedContent } from "../vfile"
@@ -365,3 +368,143 @@ describe("folders of virtual pages (#2576)", () => {
assert.strictEqual(trie.findNode(["trips", "index"])?.data, null)
})
})
describe("publish filters on pages that stand for files (bases-page#11)", () => {
const note = (slug: string, links: string[], frontmatter: Record<string, unknown> = {}) =>
defaultProcessedContent({
slug: slug as FullSlug,
relativePath: `${slug}.md` as FilePath,
links: links as SimpleSlug[],
frontmatter: { title: slug, ...frontmatter },
})
const page = (slug: string, data: Record<string, unknown> = {}) => ({
slug: slug as FullSlug,
title: slug,
data: { relativePath: slug as FilePath, ...data },
})
// publishes notes with `publish: true`, and files a published page links to
const explicitPublish = {
name: "ExplicitPublish",
shouldPublish: (_ctx: BuildCtx, [, vfile]: ReturnType<typeof note>) =>
vfile.data.frontmatter?.publish === true || (vfile.data.referencedBy?.length ?? 0) > 0,
}
const makeCtx = (plugins: Record<string, unknown[]> = {}) =>
({
cfg: { configuration: {}, plugins: { filters: [explicitPublish], ...plugins } },
argv: {},
virtualPages: [],
}) as unknown as BuildCtx
test("referencesByTarget lists the pages linking to each target", () => {
const refs = referencesByTarget([
note("a", ["board.canvas", "b"]),
note("b", ["board.canvas", "board.canvas"]),
])
assert.deepStrictEqual(refs.get("board.canvas" as SimpleSlug), ["a", "b"])
assert.deepStrictEqual(refs.get("b" as SimpleSlug), ["a"])
})
test("file-backed pages go through the filters, with referencedBy; listings do not", async () => {
const ctx = makeCtx()
const entries = await generateVirtualPages(
[
makePageType({
name: "canvas",
fileExtensions: [".canvas"],
generate: () => [page("linked.canvas"), page("secret.canvas")],
}),
makePageType({
name: "excalidraw",
fileExtensions: [".excalidraw.md"],
generate: () => [
page("drawing.excalidraw", { frontmatter: { title: "drawing", publish: true } }),
],
}),
makePageType({ name: "tags", generate: () => [page("tags/a")] }),
],
[note("index", ["linked.canvas"], { publish: true })],
ctx,
{ head: StubHead },
{},
)
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["linked.canvas", "drawing.excalidraw", "tags/a"],
)
assert.deepStrictEqual(entries[0].vfile.data.referencedBy, ["index"])
assert.deepStrictEqual(entries[1].vfile.data.referencedBy, [])
assert.strictEqual(entries[2].vfile.data.referencedBy, undefined)
assert.deepStrictEqual(
ctx.virtualPages.map(([, vfile]) => vfile.data.slug),
["linked.canvas", "drawing.excalidraw", "tags/a"],
)
})
const rendered = (ctx: BuildCtx) => {
const [tree, vfile] = defaultProcessedContent({
slug: "board.canvas" as FullSlug,
relativePath: "board.canvas" as FilePath,
frontmatter: { title: "board", password: "pw" },
htmlAst: {
type: "root",
children: [{ type: "element", tagName: "p", properties: {}, children: [] }],
} as HtmlRoot,
})
const layout = resolveLayout(makePageType(), { head: StubHead }, {})
ctx.virtualPages.push([tree, vfile])
return {
ve: { tree, vfile, layout, vpSlug: "board.canvas" as FullSlug, fileBacked: true },
ctx,
}
}
test("virtualPageHtmlPlugins process the rendered body, which the page then shows", () => {
const seen: unknown[] = []
const { ve, ctx } = rendered(
makeCtx({
transformers: [
{
name: "Encrypt",
virtualPageHtmlPlugins: (_ctx: BuildCtx, content: unknown[]) => {
seen.push(content)
return [
() => (tree: HtmlRoot, file: { data: Record<string, unknown> }) => {
tree.children = [{ type: "text", value: "encrypted" }]
file.data.encrypted = true
},
]
},
},
],
}),
)
const Body = ve.layout.pageBody
assert.strictEqual(processVirtualPageHtml(ve, ctx, []), true)
assert.deepStrictEqual(seen, [[]])
assert.deepStrictEqual(ve.tree.children, [{ type: "text", value: "encrypted" }])
assert.strictEqual(ve.vfile.data.htmlAst, ve.tree)
assert.strictEqual((ve.vfile.data as Record<string, unknown>).encrypted, true)
assert.strictEqual(ctx.virtualPages[0][0], ve.tree)
assert.notStrictEqual(ve.layout.pageBody, Body)
})
test("a page whose processing leaves the tree alone keeps its body", () => {
const { ve, ctx } = rendered(
makeCtx({ transformers: [{ name: "Noop", virtualPageHtmlPlugins: () => [() => () => {}] }] }),
)
const Body = ve.layout.pageBody
assert.strictEqual(processVirtualPageHtml(ve, ctx, []), true)
assert.strictEqual(ve.layout.pageBody, Body)
assert.strictEqual(ve.tree.children.length, 0)
})
test("a page whose body failed to render is not published unprocessed", () => {
const { ve, ctx } = rendered(
makeCtx({ transformers: [{ name: "Encrypt", virtualPageHtmlPlugins: () => [] }] }),
)
ve.vfile.data.htmlAst = undefined
assert.strictEqual(processVirtualPageHtml(ve, ctx, []), false)
// without such plugins nothing changes
assert.strictEqual(processVirtualPageHtml(ve, makeCtx(), []), true)
})
})
+140 -8
View File
@@ -2,7 +2,15 @@ import { QuartzEmitterPlugin, QuartzPageTypePluginInstance, TreeTransform } from
import { QuartzComponent, QuartzComponentProps } from "../../components/types"
import { pageResources, renderPage } from "../../components/renderPage"
import { FullPageLayout } from "../../cfg"
import { FilePath, FullSlug, joinSegments, pathToRoot, slugifyFilePath } from "../../util/path"
import {
FilePath,
FullSlug,
SimpleSlug,
joinSegments,
pathToRoot,
simplifySlug,
slugifyFilePath,
} from "../../util/path"
import { ProcessedContent, defaultProcessedContent } from "../vfile"
import { write } from "../emitters/helpers"
import { BuildCtx, trieFromAllFiles } from "../../util/ctx"
@@ -10,6 +18,12 @@ import { StaticResources } from "../../util/resources"
import { render } from "preact-render-to-string"
import { fromHtml } from "hast-util-from-html"
import { Root as HtmlRoot } from "hast"
import { toHtml } from "hast-util-to-html"
import { unified } from "unified"
import { htmlToJsx } from "../../util/jsx"
import { trace } from "../../util/trace"
import { attributeError, originOf } from "../../util/pluginErrors"
import { rejectingFilter } from "../../processors/filter"
import fs from "fs"
import path from "path"
@@ -155,6 +169,10 @@ export type VirtualEntry = {
* content. `generate` may be async (Quartz 5.1+), e.g. to run the transformer chain or
* esbuild; page types run one after another in priority order, as before. Virtual pages
* (except the 404 page) are added to `ctx.virtualPages`.
*
* Pages of page types that render files (`fileExtensions`: `.base`, `.canvas`, …) go through the
* site's filters first, with `file.data.referencedBy` set; a page a filter rejects is dropped, so
* it is neither emitted nor listed (content index, folder pages, explorer, search) nor embeddable.
*/
export async function generateVirtualPages(
pageTypes: QuartzPageTypePluginInstance[],
@@ -165,6 +183,7 @@ export async function generateVirtualPages(
): Promise<VirtualEntry[]> {
const cfg = ctx.cfg.configuration
const virtualEntries: VirtualEntry[] = []
let references: Map<SimpleSlug, FullSlug[]> | undefined
for (const pt of pageTypes) {
if (!pt.generate) continue
const virtualPages = await pt.generate({ content, cfg, ctx })
@@ -179,6 +198,14 @@ export async function generateVirtualPages(
frontmatter: { title: vp.title, tags: [] },
...vp.data,
})
if (fileBacked) {
// A page that stands for a file is published on the same terms as a note: the site's
// filters decide, seeing the frontmatter the page type gives it (an `.excalidraw.md`
// drawing's own) and which published pages link to it (bases-page#11).
references ??= referencesByTarget(content)
vfile.data.referencedBy = references.get(simplifySlug(vpSlug)) ?? []
if (rejectingFilter(ctx, [tree, vfile]) !== undefined) continue
}
if (vpSlug !== "404") {
ctx.virtualPages.push([tree, vfile])
}
@@ -188,6 +215,26 @@ export async function generateVirtualPages(
return virtualEntries
}
/**
* @internal Exported for testing only.
*
* For each link target, the published pages that link to or embed it (`file.data.links`), in
* content order.
*/
export function referencesByTarget(content: ProcessedContent[]): Map<SimpleSlug, FullSlug[]> {
const references = new Map<SimpleSlug, FullSlug[]>()
for (const [, file] of content) {
const slug = file.data.slug
if (!slug) continue
for (const target of new Set(file.data.links ?? [])) {
const from = references.get(target)
if (from) from.push(slug)
else references.set(target, [slug])
}
}
return references
}
/**
* @internal Exported for testing only.
*
@@ -210,18 +257,71 @@ export function folderTrie(
return trieFromAllFiles([...allFiles, ...fileBacked])
}
/** Renders a page's (already rendered and processed) tree as its body. */
const RenderedBody: QuartzComponent = ({ fileData, tree }: QuartzComponentProps) =>
htmlToJsx((fileData.filePath ?? fileData.relativePath ?? fileData.slug) as FilePath, tree)
/**
* @internal Exported for testing only.
*
* Run the transformers' `virtualPageHtmlPlugins` on the rendered body (`file.data.htmlAst`) of a
* page that stands for a file — e.g. encrypted-pages encrypting a canvas. When they change the
* tree, the page shows the changed tree instead of rendering its body again. A page whose body
* failed to render, or that a plugin throws on, is left unpublished: emitting it unprocessed could
* publish what the plugin protects.
*/
export function processVirtualPageHtml(
ve: VirtualEntry,
ctx: BuildCtx,
content: ProcessedContent[],
): boolean {
if (!ve.fileBacked) return true
const transformers = (ctx.cfg.plugins?.transformers ?? []).filter((t) => t.virtualPageHtmlPlugins)
if (transformers.length === 0) return true
// its body failed to render: there is nothing to process, and it can't be emitted processed
const htmlAst = ve.vfile.data.htmlAst
if (!htmlAst) return false
const before = toHtml(htmlAst, { allowDangerousHtml: true })
for (const transformer of transformers) {
try {
const processor = unified().use(transformer.virtualPageHtmlPlugins!(ctx, content))
ve.vfile.data.htmlAst = processor.runSync(ve.vfile.data.htmlAst!, ve.vfile) as HtmlRoot
} catch (err) {
const file = ve.vfile.data.relativePath ?? ve.vpSlug
trace(
`Failed to process the HTML of \`${file}\``,
attributeError(err, { origin: originOf(transformer), stage: "html", file }) as Error,
)
return false
}
}
const processed = ve.vfile.data.htmlAst!
if (toHtml(processed, { allowDangerousHtml: true }) !== before) {
ve.tree = processed
ve.layout = { ...ve.layout, pageBody: RenderedBody }
// emitters that run later (content index, assets, …) read the page from ctx.virtualPages
const item = ctx.virtualPages.find(([, vfile]) => vfile === ve.vfile)
if (item) item[0] = processed
}
return true
}
/**
* Render each virtual page's Body component to HTML and parse it to a hast tree,
* populating both the ProcessedContent tree and vfile.data.htmlAst so that
* transclusion (e.g. ![[file.canvas]]) can inline the virtual page's content.
* populating vfile.data.htmlAst so that transclusion (e.g. ![[file.canvas]]) can inline the
* virtual page's content, then run `virtualPageHtmlPlugins` on it (pages that stand for files).
* Returns the entries to emit: those whose processing failed are removed from `ctx.virtualPages`.
*/
function populateVirtualPageHtmlAst(
virtualEntries: VirtualEntry[],
ctx: BuildCtx,
allFiles: ProcessedContent[1]["data"][],
resources: StaticResources,
) {
content: ProcessedContent[],
): VirtualEntry[] {
const cfg = ctx.cfg.configuration
const failed = new Set<VirtualEntry>()
for (const ve of virtualEntries) {
const BodyComponent = ve.layout.pageBody
const externalResources = pageResources(pathToRoot(ve.vpSlug), resources, ctx)
@@ -242,7 +342,16 @@ function populateVirtualPageHtmlAst(
// Body rendering failed — leave htmlAst empty so transclusion falls
// back to the default title-only display.
}
// processed right after rendering, so later bodies that embed this page see the result
if (!processVirtualPageHtml(ve, ctx, content)) {
failed.add(ve)
ve.vfile.data.htmlAst = undefined
}
}
if (failed.size === 0) return virtualEntries
const failedData = new Set([...failed].map((ve) => ve.vfile.data))
ctx.virtualPages = ctx.virtualPages.filter(([, vfile]) => !failedData.has(vfile.data))
return virtualEntries.filter((ve) => !failed.has(ve))
}
export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>> = (userOpts) => {
@@ -290,7 +399,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
// Render Body components to populate htmlAst for transclusion
populateVirtualPageHtmlAst(virtualEntries, ctx, allFilesWithVirtual, resources)
const entriesToEmit = populateVirtualPageHtmlAst(
virtualEntries,
ctx,
allFilesWithVirtual,
resources,
content,
)
// Phase 2: Emit regular pages (with virtual page data available for transclusion)
for (const [tree, file] of content) {
@@ -315,7 +430,7 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
}
// Phase 3: Emit virtual pages
for (const ve of virtualEntries) {
for (const ve of entriesToEmit) {
yield emitPage(
ctx,
ve.vpSlug,
@@ -371,7 +486,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
// Render Body components to populate htmlAst for transclusion
populateVirtualPageHtmlAst(virtualEntries, ctx, allFilesWithVirtual, resources)
const entriesToEmit = populateVirtualPageHtmlAst(
virtualEntries,
ctx,
allFilesWithVirtual,
resources,
content,
)
// Phase 2: Emit changed regular pages
for (const [tree, file] of content) {
@@ -398,7 +519,7 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
}
// Phase 3: Emit virtual pages
for (const ve of virtualEntries) {
for (const ve of entriesToEmit) {
yield emitPage(
ctx,
ve.vpSlug,
@@ -413,3 +534,14 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
},
}
}
declare module "vfile" {
interface DataMap {
/**
* On a page that stands for a file (`.base`, `.canvas`, …): the published pages that link to
* or embed it. Set before the site's filters see the page, e.g. so explicit-publish can publish
* a file that has no frontmatter when a published note links to it.
*/
referencedBy: FullSlug[]
}
}
+8
View File
@@ -61,6 +61,14 @@ export type QuartzTransformerPluginInstance = PluginHooks & {
textTransform?: (ctx: BuildCtx, src: string) => string
markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList
/**
* rehype plugins for the pages that page types render from files (`.base`, `.canvas`, …).
* Those pages are rendered at emit time and never pass through `htmlPlugins`; these plugins
* run on each one's rendered body (with the page's vfile, so `file.data.frontmatter` and
* `file.data.referencedBy` are available) after the site's filters published it, and the page
* shows the resulting tree. `content` is the published content. Quartz 5.1+.
*/
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
externalResources?: ExternalResourcesFn
}
+36 -12
View File
@@ -1,27 +1,51 @@
import { BuildCtx } from "../util/ctx"
import { PerfTimer } from "../util/perf"
import { ProcessedContent } from "../plugins/vfile"
import { QuartzFilterPluginInstance } from "../plugins/types"
import { attributeError, originOf } from "../util/pluginErrors"
import { recordFiltered } from "../util/diagnostics"
import { trace } from "../util/trace"
/** Whether `plugin` publishes `item`; a filter that throws reports the error and rejects it. */
function publishes(
ctx: BuildCtx,
plugin: QuartzFilterPluginInstance,
item: ProcessedContent,
): boolean {
try {
return plugin.shouldPublish(ctx, item)
} catch (err) {
const file = item[1].data.relativePath ?? item[1].data.slug
trace(
`Failed to filter \`${file}\``,
attributeError(err, { origin: originOf(plugin), stage: "filter", file }) as Error,
)
return false
}
}
/**
* Run the site's filters on one page (e.g. a virtual page that stands for a `.base` or `.canvas`
* file). Returns the name of the first filter that rejects it, or `undefined` when it is
* published. A rejection is recorded like one from `filterContent`.
*/
export function rejectingFilter(ctx: BuildCtx, item: ProcessedContent): string | undefined {
for (const plugin of ctx.cfg.plugins?.filters ?? []) {
if (publishes(ctx, plugin, item)) continue
const slug = item[1].data.slug
if (slug) recordFiltered(slug, plugin.name)
if (ctx.argv?.verbose) console.log(`[filter:${plugin.name}] ${slug}`)
return plugin.name
}
return undefined
}
export function filterContent(ctx: BuildCtx, content: ProcessedContent[]): ProcessedContent[] {
const { cfg, argv } = ctx
const perf = new PerfTimer()
const initialLength = content.length
for (const plugin of cfg.plugins.filters) {
const updatedContent = content.filter((item) => {
try {
return plugin.shouldPublish(ctx, item)
} catch (err) {
const file = item[1].data.relativePath ?? item[1].data.slug
trace(
`Failed to filter \`${file}\``,
attributeError(err, { origin: originOf(plugin), stage: "filter", file }) as Error,
)
return false
}
})
const updatedContent = content.filter((item) => publishes(ctx, plugin, item))
for (const item of content) {
if (!updatedContent.includes(item) && item[1].data.slug) {
recordFiltered(item[1].data.slug, plugin.name)