feat(v5): add plugin system (#2295)
* feat(plugins): v5 plugin system * feat(plugins): explorer as community plugin * feat(plugins): graph as community plugin * chore: update package-lock.json * chore: update package-lock.json * docs: updated plugin-specific docs * chore: update package-lock.json * chore: update package-lock.json * chore: update package-lock.json * Implement Git-based plugin system with dogfooding for community plugins - Remove npm dependencies for @quartz-community/* plugins - Add gitLoader.ts for installing plugins from GitHub - Update quartz.layout.ts to import from .quartz/plugins/ - Add install-plugins.ts script for prebuild hook - Add .quartz/ to .gitignore * Add comprehensive Git-based plugin CLI with lockfile support - Create quartz.lock.json format for tracking exact plugin commits - Add 'npx quartz plugin' commands: install, add, remove, update, list, restore - Plugin state is fully reproducible via lockfile - No npm dependencies required for community plugins * Fix TypeScript errors in git-installed plugins - Install @quartz-community/types as devDependency - Fix plugin imports to define types locally - Fix search inline script fetchData bug - Format code with prettier * fix(types): install types from github * docs: updated plugin-specific docs * Update Dockerfile and add CI/CD documentation - Add plugin install step to Dockerfile - Create docs/ci-cd.md with pipeline configuration guide * Update GitHub Actions workflows for v5 branch and Git-based plugins - Change branch references from v4 to v5 - Add plugin caching to speed up builds - Use 'npx quartz plugin install' instead of 'restore' - Update Docker workflow branch trigger * Update quartz.lock.json with fixed plugin versions * fix(docker): install command * docs: add plugin migration analysis document Comprehensive analysis of which Quartz v4 components and plugins can be migrated to separate repositories, including: - Component analysis (25 components) - Plugin analysis (transformers, emitters, filters) - Migration strategies for different plugin types - Lessons learned from Explorer/Graph/Search migrations - Recommended migration order * chore: updated plugins * chore: updated plugins * chore: updated dependencies * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: tsconfig * feat: build installed plugins * chore: updated plugins * chore: updated plugins * chore: update explorer plugin with duplication fix * docs: Quartz v5 * chore: update graph plugin with navigation fix * fix: update explorer plugin with toggle fix * fix: update explorer plugin - ensure toggle buttons always work * fix: create plugin components once to prevent duplicate script registration * chore: updated plugins * chore: updated plugins * feat: migrate 7 feature components to community plugins (Phase B) Migrate ArticleTitle, TagList, PageTitle, Darkmode, ReaderMode, ContentMeta, and Footer from internal components to community plugins. Update layout to use Plugin.X() pattern, remove internal component files and their styles/scripts. Add MIGRATION_TASKS.md documenting the full migration roadmap. * chore: updated plugins * refactor: delete 6 internal component duplicates (Phase A) Remove Backlinks, Breadcrumbs, RecentNotes, Search, TableOfContents, Comments, and OverflowList — all replaced by community plugins. Delete associated styles (6) and scripts (3). Switch layout to use Plugin.Breadcrumbs() instead of Component.Breadcrumbs(). * refactor: unify QuartzComponent type to structural interface (Phase C) - Changed QuartzComponent from ComponentType<QuartzComponentProps> to callable type ((props: QuartzComponentProps) => any) - Added optional displayName property for better debugging - Removed ComponentType import from preact - Removed all 13 'as QuartzComponent' type casts from quartz.layout.ts - Community plugin components now directly assignable without casts * feat: add PageType plugin infrastructure (Phase D Step 4) * feat: add PageTypePluginEntry for cross-boundary type compatibility Introduce PageTypePluginEntry with never[] parameter types to accept both internal and community PageType plugins in config arrays without casts, working around branded FullSlug contravariance mismatch. * refactor: update dispatcher to cast PageTypePluginEntry at boundary Add getPageTypes() helper that casts config's PageTypePluginEntry[] to QuartzPageTypePluginInstance[] in one place. Cast VirtualPage.slug to FullSlug at emitPage/defaultProcessedContent call sites. * feat: integrate community PageType plugins (Phase D Step 6) Replace old page-rendering emitters with PageTypeDispatcher emitter and pageTypes array. Restructure quartz.layout.ts from three separate exports to unified layout object with defaults and byPageType record. Install content-page, folder-page, tag-page community plugins. * refactor: delete old page-rendering emitters Remove ContentPage, FolderPage, TagPage, and NotFoundPage emitters now replaced by community PageType plugins and the PageTypeDispatcher. * refactor: remove migrated page body components Delete Content, FolderContent, TagContent page components now provided by community PageType plugins. Update components barrel export. * fix: update lockfile to fixed folder-page and tag-page commits Points to commits that remove duplicate PageList/SortFn re-exports, fixing TS2300 duplicate identifier errors in generated plugin index. * chore: updated plugins * fix: populate ctx.trie in PageTypeDispatcher before rendering Components like FolderContent depend on ctx.trie for folder hierarchy. The dispatcher now lazily initializes it via trieFromAllFiles in emit and force-rebuilds it in partialEmit to reflect file changes. * chore: update lockfile to fixed folder-page commit * chore: updated plugins * chore: update explorer plugin to fix SPA folder navigation * feat: extract transformers to community plugins and fix type compatibility - Delete 12 internal transformer files (keep FrontMatter as internal) - Switch quartz.config.ts to use ExternalPlugin.* for all transformers - Align branded types with @quartz-community/types (_brand, FullSlug etc.) - Add vfile DataMap augmentations for fields from extracted transformers - Update all 29 plugins to @quartz-community/types v0.2.1 * Migrate filters to external plugins (remove-draft, explicit-publish) Delete internal RemoveDrafts and ExplicitPublish filter implementations, install them as community plugins, and update quartz.config.ts to use ExternalPlugin.RemoveDrafts(). * Migrate emitters to external plugins (alias-redirects, cname, favicon, content-index, og-image) * refactor: remove inline scripts/styles migrated to plugins Delete dead code: callout, checkbox, mermaid inline scripts and styles are now bundled by the obsidian-flavored-markdown plugin. Clipboard script and styles moved to the syntax-highlighting plugin. listPage.scss was unreferenced. Body.tsx simplified to a pure layout wrapper. * refactor: consolidate utils to re-export from @quartz-community/utils * fix: use dangerouslySetInnerHTML for inline CSS to prevent HTML-escaping Preact was escaping & characters in SCSS-compiled CSS (e.g. & nesting) into &, breaking CSS rules. Using dangerouslySetInnerHTML bypasses the escaping, matching how browsers expect style element content. * chore: update plugins with inline script transpilation fix * chore: updated plugins * docs: update plugin API sections for v5 community plugins * docs: rewrite documentation for v5 plugin system Update feature docs, hosting, CI/CD, getting started, configuration, layout, architecture, creating components, making plugins, and migration guide to reflect the v5 community plugin architecture. * docs: fix outdated v4 references in documentation * chore: remove completed migration planning docs * chore: updated plugins * chore: cleanup * chore: cleanup * chore: bump version to 5.0.0 * chore: updated dependencies * feat: integrate CanvasPage plugin with types, assets, config, layout, and documentation * chore: updated dependencies * chore: updated dependencies * chore: updated linter * chore: update canvas-page plugin to c942fcb * chore: updated plugins * chore: update canvas-page plugin to f88f1b9 * chore: updated plugins * chore: update canvas-page plugin to 079304c * chore: updated plugins * chore: canvas layout * chore: update canvas-page plugin to 38d49e1 * chore: updated plugins * chore: update canvas-page plugin to 505c099 * chore: updated plugins * chore: updated plugins * fix: Obsidian flavored markdown * fix: Obsidian flavored markdown * fix: Obsidian flavored markdown * chore: cleanup * chore: updated plugins * feat: configuration files * feat: Quartz TUI * feat(tui): YAML configuration * chore: tsup * chore: tsup * feat: support array categories in plugin manifests Plugins like note-properties export both transformer and component functionality. Allow PluginManifest.category to be a single value or an array, with config-loader resolving to the first processing category (transformer/filter/emitter/pageType) for dispatch. * refactor: remove built-in FrontMatter transformer Frontmatter processing is now handled by the note-properties plugin, which provides the same YAML/TOML parsing plus link extraction and a visual properties panel. The built-in transformer is no longer needed. * feat: add note-properties plugin to default configuration Register note-properties as the first plugin (order 5) in both the user config and the default config. Placed in beforeBody layout zone with priority 15 (between article-title at 10 and content-meta at 20). * docs: add plugin management strategy and syncer v5 notes Document the plugin management system design decisions and provide implementation guidance for the Quartz Syncer v5 integration. * feat: add bases-page plugin to default configuration Enable Obsidian Bases (.base) file support with bases page type and layout entry in both user and default config. * docs: update syncer notes with bases-page, note-properties, and spacer Add all three new plugins to the quick reference table (40 total). Add content, canvas, and bases page types to byPageType documentation. * chore: updated plugins * fix: update CI to Node 24 and regenerate lockfiles for clean install * fix: resolve type errors for CI checks * chore: updated plugins * chore: updated plugins * fix: plugin mapping from configuration * fix: CI * fix: CI * docs: rewrite Frontmatter documentation for note-properties plugin * chore: updated plugins * docs: Quartz v5 * chore: updated plugins * chore: updated plugins * refactor: extract TUI to standalone plugin repository * chore: linting * docs: Quartz v5 * feat: update and upgrade commands * chore: updated plugins * chore: updated plugins * chore: cleanup * chore: cleanup * chore: cleanup * chore: cleanup * chore: cleanup * fix: layout group priority * fix: view classes * fix: include virtual pages in content index for explorer visibility * docs: add board, gallery, and cards view examples to navigation page * chore: updated plugins * fix: include virtualPages in worker serializable build context * fix: set relativePath on virtual pages to prevent explorer crash * fix: exclude 404 * fix(links): virtual page links * fix(links): virtual page transclusion * docs: architecture overview * fix: only call scripts one per page * fix: type error in component registry instantiate method * fix: left layout order * fix(layout): remove tag-list by default * docs(plugins): updated plugin list defaults * fix(layout): priorities * feat: add PageFrame system for custom page layouts * feat: integrate PageFrame into rendering pipeline * feat: add frame resolution to page type dispatcher and config loader * style: add CSS grid overrides for full-width and minimal page frames * feat: set minimal frame for 404 and update canvas-page plugin * docs: add PageFrame system to architecture overview * fix: wrap frame.render() in array to satisfy Body children type * chore: format * fix: use absolute asset paths for 404 page so it works in subdirectories * fix(layout): priorities * docs: page frames * feat: add FrameRegistry for plugin-provided page frames Plugins can now register custom page frames via their manifest's 'frames' field. Frames are loaded alongside components during plugin initialization and resolved by name at render time with fallback to built-in frames. * feat(layout): page frames * fix(layout): linting * fix: inject frame CSS into page so plugin-provided frames render correctly * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * docs: canvas * chore: updated plugins * chore: updated plugins * chore: updated plugins * feat: add TreeTransform hook, fix multi-category plugins, and resolve cross-plugin dependencies - Add TreeTransform type and treeTransforms hook to pageType plugins, enabling render-time HAST tree mutations (e.g. bases-page inline codeblock resolution) - Fix config-loader to push multi-category plugins into ALL matching processing buckets instead of only the first match - Add side-effect import for component-only plugins so view registrations (e.g. leaflet-map via globalThis ViewRegistry) execute at load time - Add npm prune --omit=dev and cross-plugin peer dependency symlinking to buildPlugin() to prevent duplicate-singleton issues from nested node_modules * chore: format * chore: test docs * chore: updated plugins * fix: prevent HTML-escaping of inline style and script content in htmlToJsx Add dangerouslySetInnerHTML overrides for <style> and <script> elements so that CSS/JS injected by tree transforms is not HTML-escaped during preact-render-to-string serialization. * chore: update plugin lockfile for htmlToJsx migration * chore: update leaflet-map plugin (fix deferred L.Control) * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: updated plugins * chore: test npx quartz upgrade * feat(templates): add obsidian, ttrpg, blog templates * docs: move bases * docs: removed leaflet demo * feat(cli): configure baseUrl during create * docs: updated cli commands * docs: updated documentation for v5 * feat(cli): prune and resolve * chore: rebuild lockfile * docs: cli documentation * docs: plugin development and setup guide * chore: deleted redundant files * fix(build): fallback config * chore: updated lockfile * docs: removed outdated v3 setup * feat(cli): allow non-default branch plugins * docs: install branch commands * feat(cli): allow local plugins * docs: install local commands * feat: add render event type and listener for in-place DOM re-initialization * docs: add EncryptedPages plugin documentation * docs: add encrypted pages live demo page - New password-protected demo page (password: quartz) showing the plugin in action - Link to demo from EncryptedPages plugin page with password hint callout * feat: add encrypted-pages plugin to all templates - Enabled by default in default, obsidian, and ttrpg templates - Disabled by default in blog template * chore: updated plugins * chore: updated layouts * chore: updated plugins * feat: stacked pages * feat: added stacked page panes * docs: touch-ups
This commit is contained in:
51
quartz/plugins/config.ts
Normal file
51
quartz/plugins/config.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
QuartzTransformerPluginInstance,
|
||||
QuartzFilterPluginInstance,
|
||||
QuartzEmitterPluginInstance,
|
||||
PageTypePluginEntry,
|
||||
} from "./types"
|
||||
import { LoadedPlugin } from "./loader/types"
|
||||
|
||||
export interface PluginConfiguration {
|
||||
transformers: (QuartzTransformerPluginInstance | LoadedPlugin)[]
|
||||
filters: (QuartzFilterPluginInstance | LoadedPlugin)[]
|
||||
emitters: (QuartzEmitterPluginInstance | LoadedPlugin)[]
|
||||
pageTypes?: (PageTypePluginEntry | LoadedPlugin)[]
|
||||
}
|
||||
|
||||
export function isLoadedPlugin(plugin: unknown): plugin is LoadedPlugin {
|
||||
return (
|
||||
typeof plugin === "object" &&
|
||||
plugin !== null &&
|
||||
"plugin" in plugin &&
|
||||
"manifest" in plugin &&
|
||||
"type" in plugin &&
|
||||
typeof (plugin as LoadedPlugin).plugin === "function"
|
||||
)
|
||||
}
|
||||
|
||||
export function getPluginInstance<T extends object | undefined>(
|
||||
plugin:
|
||||
| QuartzTransformerPluginInstance
|
||||
| QuartzFilterPluginInstance
|
||||
| QuartzEmitterPluginInstance
|
||||
| PageTypePluginEntry
|
||||
| LoadedPlugin,
|
||||
options?: T,
|
||||
):
|
||||
| QuartzTransformerPluginInstance
|
||||
| QuartzFilterPluginInstance
|
||||
| QuartzEmitterPluginInstance
|
||||
| PageTypePluginEntry {
|
||||
if (isLoadedPlugin(plugin)) {
|
||||
const factory = plugin.plugin as (
|
||||
opts?: T,
|
||||
) =>
|
||||
| QuartzTransformerPluginInstance
|
||||
| QuartzFilterPluginInstance
|
||||
| QuartzEmitterPluginInstance
|
||||
| PageTypePluginEntry
|
||||
return factory(options)
|
||||
}
|
||||
return plugin
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { QuartzComponentProps } from "../../components/types"
|
||||
import BodyConstructor from "../../components/Body"
|
||||
import { pageResources, renderPage } from "../../components/renderPage"
|
||||
import { FullPageLayout } from "../../cfg"
|
||||
import { FullSlug } from "../../util/path"
|
||||
import { sharedPageComponents } from "../../../quartz.layout"
|
||||
import { NotFound } from "../../components"
|
||||
import { defaultProcessedContent } from "../vfile"
|
||||
import { write } from "./helpers"
|
||||
import { i18n } from "../../i18n"
|
||||
|
||||
export const NotFoundPage: QuartzEmitterPlugin = () => {
|
||||
const opts: FullPageLayout = {
|
||||
...sharedPageComponents,
|
||||
pageBody: NotFound(),
|
||||
beforeBody: [],
|
||||
left: [],
|
||||
right: [],
|
||||
}
|
||||
|
||||
const { head: Head, pageBody, footer: Footer } = opts
|
||||
const Body = BodyConstructor()
|
||||
|
||||
return {
|
||||
name: "404Page",
|
||||
getQuartzComponents() {
|
||||
return [Head, Body, pageBody, Footer]
|
||||
},
|
||||
async *emit(ctx, _content, resources) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const slug = "404" as FullSlug
|
||||
|
||||
const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
|
||||
const path = url.pathname as FullSlug
|
||||
const notFound = i18n(cfg.locale).pages.error.title
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug,
|
||||
text: notFound,
|
||||
description: notFound,
|
||||
frontmatter: { title: notFound, tags: [] },
|
||||
})
|
||||
const externalResources = pageResources(path, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: vfile.data,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles: [],
|
||||
}
|
||||
|
||||
yield write({
|
||||
ctx,
|
||||
content: renderPage(cfg, slug, componentData, opts, externalResources),
|
||||
slug,
|
||||
ext: ".html",
|
||||
})
|
||||
},
|
||||
async *partialEmit() {},
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { FullSlug, isRelativeURL, resolveRelative, simplifySlug } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { write } from "./helpers"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { VFile } from "vfile"
|
||||
import path from "path"
|
||||
|
||||
async function* processFile(ctx: BuildCtx, file: VFile) {
|
||||
const ogSlug = simplifySlug(file.data.slug!)
|
||||
|
||||
for (const aliasTarget of file.data.aliases ?? []) {
|
||||
const aliasTargetSlug = (
|
||||
isRelativeURL(aliasTarget)
|
||||
? path.normalize(path.join(ogSlug, "..", aliasTarget))
|
||||
: aliasTarget
|
||||
) as FullSlug
|
||||
|
||||
const redirUrl = resolveRelative(aliasTargetSlug, ogSlug)
|
||||
yield write({
|
||||
ctx,
|
||||
content: `
|
||||
<!DOCTYPE html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<title>${ogSlug}</title>
|
||||
<link rel="canonical" href="${redirUrl}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="refresh" content="0; url=${redirUrl}">
|
||||
</head>
|
||||
</html>
|
||||
`,
|
||||
slug: aliasTargetSlug,
|
||||
ext: ".html",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const AliasRedirects: QuartzEmitterPlugin = () => ({
|
||||
name: "AliasRedirects",
|
||||
async *emit(ctx, content) {
|
||||
for (const [_tree, file] of content) {
|
||||
yield* processFile(ctx, file)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, _content, _resources, changeEvents) {
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
if (changeEvent.type === "add" || changeEvent.type === "change") {
|
||||
// add new ones if this file still exists
|
||||
yield* processFile(ctx, changeEvent.file)
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,14 +1,30 @@
|
||||
import { FilePath, joinSegments, slugifyFilePath } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { QuartzEmitterPlugin, QuartzPageTypePluginInstance } from "../types"
|
||||
import path from "path"
|
||||
import fs from "fs"
|
||||
import { glob } from "../../util/glob"
|
||||
import { Argv } from "../../util/ctx"
|
||||
import { Argv, BuildCtx } from "../../util/ctx"
|
||||
import { QuartzConfig } from "../../cfg"
|
||||
|
||||
const filesToCopy = async (argv: Argv, cfg: QuartzConfig) => {
|
||||
// glob all non MD files in content folder and copy it over
|
||||
return await glob("**", argv.directory, ["**/*.md", ...cfg.configuration.ignorePatterns])
|
||||
function getPageTypeExtensions(ctx: BuildCtx): Set<string> {
|
||||
const extensions = new Set<string>()
|
||||
const pageTypes = (ctx.cfg.plugins.pageTypes ?? []) as unknown as QuartzPageTypePluginInstance[]
|
||||
for (const pt of pageTypes) {
|
||||
if (pt.fileExtensions) {
|
||||
for (const ext of pt.fileExtensions) {
|
||||
extensions.add(ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
return extensions
|
||||
}
|
||||
|
||||
const filesToCopy = async (argv: Argv, cfg: QuartzConfig, excludeExtensions: Set<string>) => {
|
||||
const excludePatterns = ["**/*.md", ...cfg.configuration.ignorePatterns]
|
||||
for (const ext of excludeExtensions) {
|
||||
excludePatterns.push(`**/*${ext}`)
|
||||
}
|
||||
return await glob("**", argv.directory, excludePatterns)
|
||||
}
|
||||
|
||||
const copyFile = async (argv: Argv, fp: FilePath) => {
|
||||
@@ -17,7 +33,6 @@ const copyFile = async (argv: Argv, fp: FilePath) => {
|
||||
const name = slugifyFilePath(fp)
|
||||
const dest = joinSegments(argv.output, name) as FilePath
|
||||
|
||||
// ensure dir exists
|
||||
const dir = path.dirname(dest) as FilePath
|
||||
await fs.promises.mkdir(dir, { recursive: true })
|
||||
|
||||
@@ -28,16 +43,18 @@ const copyFile = async (argv: Argv, fp: FilePath) => {
|
||||
export const Assets: QuartzEmitterPlugin = () => {
|
||||
return {
|
||||
name: "Assets",
|
||||
async *emit({ argv, cfg }) {
|
||||
const fps = await filesToCopy(argv, cfg)
|
||||
async *emit(ctx) {
|
||||
const excludeExtensions = getPageTypeExtensions(ctx)
|
||||
const fps = await filesToCopy(ctx.argv, ctx.cfg, excludeExtensions)
|
||||
for (const fp of fps) {
|
||||
yield copyFile(argv, fp)
|
||||
yield copyFile(ctx.argv, fp)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, _content, _resources, changeEvents) {
|
||||
const excludeExtensions = getPageTypeExtensions(ctx)
|
||||
for (const changeEvent of changeEvents) {
|
||||
const ext = path.extname(changeEvent.path)
|
||||
if (ext === ".md") continue
|
||||
if (ext === ".md" || excludeExtensions.has(ext)) continue
|
||||
|
||||
if (changeEvent.type === "add" || changeEvent.type === "change") {
|
||||
yield copyFile(ctx.argv, changeEvent.path)
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { write } from "./helpers"
|
||||
import { styleText } from "util"
|
||||
import { FullSlug } from "../../util/path"
|
||||
|
||||
export function extractDomainFromBaseUrl(baseUrl: string) {
|
||||
const url = new URL(`https://${baseUrl}`)
|
||||
return url.hostname
|
||||
}
|
||||
|
||||
export const CNAME: QuartzEmitterPlugin = () => ({
|
||||
name: "CNAME",
|
||||
async emit(ctx) {
|
||||
if (!ctx.cfg.configuration.baseUrl) {
|
||||
console.warn(
|
||||
styleText("yellow", "CNAME emitter requires `baseUrl` to be set in your configuration"),
|
||||
)
|
||||
return []
|
||||
}
|
||||
const content = extractDomainFromBaseUrl(ctx.cfg.configuration.baseUrl)
|
||||
if (!content) {
|
||||
return []
|
||||
}
|
||||
|
||||
const path = await write({
|
||||
ctx,
|
||||
content,
|
||||
slug: "CNAME" as FullSlug,
|
||||
ext: "",
|
||||
})
|
||||
return [path]
|
||||
},
|
||||
async *partialEmit() {},
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import styles from "../../styles/custom.scss"
|
||||
import popoverStyle from "../../components/styles/popover.scss"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { QuartzComponent } from "../../components/types"
|
||||
import { componentRegistry } from "../../components/registry"
|
||||
import {
|
||||
googleFontHref,
|
||||
googleFontSubsetHref,
|
||||
@@ -27,6 +28,7 @@ type ComponentResources = {
|
||||
|
||||
function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
const allComponents: Set<QuartzComponent> = new Set()
|
||||
|
||||
for (const emitter of ctx.cfg.plugins.emitters) {
|
||||
const components = emitter.getQuartzComponents?.(ctx) ?? []
|
||||
for (const component of components) {
|
||||
@@ -34,6 +36,10 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
}
|
||||
}
|
||||
|
||||
for (const component of componentRegistry.getAllComponents()) {
|
||||
allComponents.add(component)
|
||||
}
|
||||
|
||||
const componentResources = {
|
||||
css: new Set<string>(),
|
||||
beforeDOMLoaded: new Set<string>(),
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import { Root } from "hast"
|
||||
import { GlobalConfiguration } from "../../cfg"
|
||||
import { getDate } from "../../components/Date"
|
||||
import { escapeHTML } from "../../util/escape"
|
||||
import { FilePath, FullSlug, SimpleSlug, joinSegments, simplifySlug } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import { write } from "./helpers"
|
||||
import { i18n } from "../../i18n"
|
||||
|
||||
export type ContentIndexMap = Map<FullSlug, ContentDetails>
|
||||
export type ContentDetails = {
|
||||
slug: FullSlug
|
||||
filePath: FilePath
|
||||
title: string
|
||||
links: SimpleSlug[]
|
||||
tags: string[]
|
||||
content: string
|
||||
richContent?: string
|
||||
date?: Date
|
||||
description?: string
|
||||
}
|
||||
|
||||
interface Options {
|
||||
enableSiteMap: boolean
|
||||
enableRSS: boolean
|
||||
rssLimit?: number
|
||||
rssFullHtml: boolean
|
||||
rssSlug: string
|
||||
includeEmptyFiles: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
enableSiteMap: true,
|
||||
enableRSS: true,
|
||||
rssLimit: 10,
|
||||
rssFullHtml: false,
|
||||
rssSlug: "index",
|
||||
includeEmptyFiles: true,
|
||||
}
|
||||
|
||||
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndexMap): string {
|
||||
const base = cfg.baseUrl ?? ""
|
||||
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<url>
|
||||
<loc>https://${joinSegments(base, encodeURI(slug))}</loc>
|
||||
${content.date && `<lastmod>${content.date.toISOString()}</lastmod>`}
|
||||
</url>`
|
||||
const urls = Array.from(idx)
|
||||
.map(([slug, content]) => createURLEntry(simplifySlug(slug), content))
|
||||
.join("")
|
||||
return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}</urlset>`
|
||||
}
|
||||
|
||||
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?: number): string {
|
||||
const base = cfg.baseUrl ?? ""
|
||||
|
||||
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item>
|
||||
<title>${escapeHTML(content.title)}</title>
|
||||
<link>https://${joinSegments(base, encodeURI(slug))}</link>
|
||||
<guid>https://${joinSegments(base, encodeURI(slug))}</guid>
|
||||
<description><![CDATA[ ${content.richContent ?? content.description} ]]></description>
|
||||
<pubDate>${content.date?.toUTCString()}</pubDate>
|
||||
</item>`
|
||||
|
||||
const items = Array.from(idx)
|
||||
.sort(([_, f1], [__, f2]) => {
|
||||
if (f1.date && f2.date) {
|
||||
return f2.date.getTime() - f1.date.getTime()
|
||||
} else if (f1.date && !f2.date) {
|
||||
return -1
|
||||
} else if (!f1.date && f2.date) {
|
||||
return 1
|
||||
}
|
||||
|
||||
return f1.title.localeCompare(f2.title)
|
||||
})
|
||||
.map(([slug, content]) => createURLEntry(simplifySlug(slug), content))
|
||||
.slice(0, limit ?? idx.size)
|
||||
.join("")
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>${escapeHTML(cfg.pageTitle)}</title>
|
||||
<link>https://${base}</link>
|
||||
<description>${!!limit ? i18n(cfg.locale).pages.rss.lastFewNotes({ count: limit }) : i18n(cfg.locale).pages.rss.recentNotes} on ${escapeHTML(
|
||||
cfg.pageTitle,
|
||||
)}</description>
|
||||
<generator>Quartz -- quartz.jzhao.xyz</generator>
|
||||
${items}
|
||||
</channel>
|
||||
</rss>`
|
||||
}
|
||||
|
||||
export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
|
||||
opts = { ...defaultOptions, ...opts }
|
||||
return {
|
||||
name: "ContentIndex",
|
||||
async *emit(ctx, content) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const linkIndex: ContentIndexMap = new Map()
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
const date = getDate(ctx.cfg.configuration, file.data) ?? new Date()
|
||||
if (opts?.includeEmptyFiles || (file.data.text && file.data.text !== "")) {
|
||||
linkIndex.set(slug, {
|
||||
slug,
|
||||
filePath: file.data.relativePath!,
|
||||
title: file.data.frontmatter?.title!,
|
||||
links: file.data.links ?? [],
|
||||
tags: file.data.frontmatter?.tags ?? [],
|
||||
content: file.data.text ?? "",
|
||||
richContent: opts?.rssFullHtml
|
||||
? escapeHTML(toHtml(tree as Root, { allowDangerousHtml: true }))
|
||||
: undefined,
|
||||
date: date,
|
||||
description: file.data.description ?? "",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (opts?.enableSiteMap) {
|
||||
yield write({
|
||||
ctx,
|
||||
content: generateSiteMap(cfg, linkIndex),
|
||||
slug: "sitemap" as FullSlug,
|
||||
ext: ".xml",
|
||||
})
|
||||
}
|
||||
|
||||
if (opts?.enableRSS) {
|
||||
yield write({
|
||||
ctx,
|
||||
content: generateRSSFeed(cfg, linkIndex, opts.rssLimit),
|
||||
slug: (opts?.rssSlug ?? "index") as FullSlug,
|
||||
ext: ".xml",
|
||||
})
|
||||
}
|
||||
|
||||
const fp = joinSegments("static", "contentIndex") as FullSlug
|
||||
const simplifiedIndex = Object.fromEntries(
|
||||
Array.from(linkIndex).map(([slug, content]) => {
|
||||
// remove description and from content index as nothing downstream
|
||||
// actually uses it. we only keep it in the index as we need it
|
||||
// for the RSS feed
|
||||
delete content.description
|
||||
delete content.date
|
||||
return [slug, content]
|
||||
}),
|
||||
)
|
||||
|
||||
yield write({
|
||||
ctx,
|
||||
content: JSON.stringify(simplifiedIndex),
|
||||
slug: fp,
|
||||
ext: ".json",
|
||||
})
|
||||
},
|
||||
externalResources: (ctx) => {
|
||||
if (opts?.enableRSS) {
|
||||
return {
|
||||
additionalHead: [
|
||||
<link
|
||||
rel="alternate"
|
||||
type="application/rss+xml"
|
||||
title="RSS Feed"
|
||||
href={`https://${ctx.cfg.configuration.baseUrl}/index.xml`}
|
||||
/>,
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import path from "path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { QuartzComponentProps } from "../../components/types"
|
||||
import HeaderConstructor from "../../components/Header"
|
||||
import BodyConstructor from "../../components/Body"
|
||||
import { pageResources, renderPage } from "../../components/renderPage"
|
||||
import { FullPageLayout } from "../../cfg"
|
||||
import { pathToRoot } from "../../util/path"
|
||||
import { defaultContentPageLayout, sharedPageComponents } from "../../../quartz.layout"
|
||||
import { Content } from "../../components"
|
||||
import { styleText } from "util"
|
||||
import { write } from "./helpers"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { Node } from "unist"
|
||||
import { StaticResources } from "../../util/resources"
|
||||
import { QuartzPluginData } from "../vfile"
|
||||
|
||||
async function processContent(
|
||||
ctx: BuildCtx,
|
||||
tree: Node,
|
||||
fileData: QuartzPluginData,
|
||||
allFiles: QuartzPluginData[],
|
||||
opts: FullPageLayout,
|
||||
resources: StaticResources,
|
||||
) {
|
||||
const slug = fileData.slug!
|
||||
const cfg = ctx.cfg.configuration
|
||||
const externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles,
|
||||
}
|
||||
|
||||
const content = renderPage(cfg, slug, componentData, opts, externalResources)
|
||||
return write({
|
||||
ctx,
|
||||
content,
|
||||
slug,
|
||||
ext: ".html",
|
||||
})
|
||||
}
|
||||
|
||||
export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOpts) => {
|
||||
const opts: FullPageLayout = {
|
||||
...sharedPageComponents,
|
||||
...defaultContentPageLayout,
|
||||
pageBody: Content(),
|
||||
...userOpts,
|
||||
}
|
||||
|
||||
const { head: Head, header, beforeBody, pageBody, afterBody, left, right, footer: Footer } = opts
|
||||
const Header = HeaderConstructor()
|
||||
const Body = BodyConstructor()
|
||||
|
||||
return {
|
||||
name: "ContentPage",
|
||||
getQuartzComponents() {
|
||||
return [
|
||||
Head,
|
||||
Header,
|
||||
Body,
|
||||
...header,
|
||||
...beforeBody,
|
||||
pageBody,
|
||||
...afterBody,
|
||||
...left,
|
||||
...right,
|
||||
Footer,
|
||||
]
|
||||
},
|
||||
async *emit(ctx, content, resources) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
let containsIndex = false
|
||||
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
if (slug === "index") {
|
||||
containsIndex = true
|
||||
}
|
||||
|
||||
// only process home page, non-tag pages, and non-index pages
|
||||
if (slug.endsWith("/index") || slug.startsWith("tags/")) continue
|
||||
yield processContent(ctx, tree, file.data, allFiles, opts, resources)
|
||||
}
|
||||
|
||||
if (!containsIndex) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`\nWarning: you seem to be missing an \`index.md\` home page file at the root of your \`${ctx.argv.directory}\` folder (\`${path.join(ctx.argv.directory, "index.md")} does not exist\`). This may cause errors when deploying.`,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, content, resources, changeEvents) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
|
||||
// find all slugs that changed or were added
|
||||
const changedSlugs = new Set<string>()
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
if (changeEvent.type === "add" || changeEvent.type === "change") {
|
||||
changedSlugs.add(changeEvent.file.data.slug!)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
if (!changedSlugs.has(slug)) continue
|
||||
if (slug.endsWith("/index") || slug.startsWith("tags/")) continue
|
||||
|
||||
yield processContent(ctx, tree, file.data, allFiles, opts, resources)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import sharp from "sharp"
|
||||
import { joinSegments, QUARTZ, FullSlug } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { write } from "./helpers"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
|
||||
export const Favicon: QuartzEmitterPlugin = () => ({
|
||||
name: "Favicon",
|
||||
async *emit({ argv }) {
|
||||
const iconPath = joinSegments(QUARTZ, "static", "icon.png")
|
||||
|
||||
const faviconContent = sharp(iconPath).resize(48, 48).toFormat("png")
|
||||
|
||||
yield write({
|
||||
ctx: { argv } as BuildCtx,
|
||||
slug: "favicon" as FullSlug,
|
||||
ext: ".ico",
|
||||
content: faviconContent,
|
||||
})
|
||||
},
|
||||
async *partialEmit() {},
|
||||
})
|
||||
@@ -1,170 +0,0 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { QuartzComponentProps } from "../../components/types"
|
||||
import HeaderConstructor from "../../components/Header"
|
||||
import BodyConstructor from "../../components/Body"
|
||||
import { pageResources, renderPage } from "../../components/renderPage"
|
||||
import { ProcessedContent, QuartzPluginData, defaultProcessedContent } from "../vfile"
|
||||
import { FullPageLayout } from "../../cfg"
|
||||
import path from "path"
|
||||
import {
|
||||
FullSlug,
|
||||
SimpleSlug,
|
||||
stripSlashes,
|
||||
joinSegments,
|
||||
pathToRoot,
|
||||
simplifySlug,
|
||||
} from "../../util/path"
|
||||
import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout"
|
||||
import { FolderContent } from "../../components"
|
||||
import { write } from "./helpers"
|
||||
import { i18n, TRANSLATIONS } from "../../i18n"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { StaticResources } from "../../util/resources"
|
||||
interface FolderPageOptions extends FullPageLayout {
|
||||
sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number
|
||||
}
|
||||
|
||||
async function* processFolderInfo(
|
||||
ctx: BuildCtx,
|
||||
folderInfo: Record<SimpleSlug, ProcessedContent>,
|
||||
allFiles: QuartzPluginData[],
|
||||
opts: FullPageLayout,
|
||||
resources: StaticResources,
|
||||
) {
|
||||
for (const [folder, folderContent] of Object.entries(folderInfo) as [
|
||||
SimpleSlug,
|
||||
ProcessedContent,
|
||||
][]) {
|
||||
const slug = joinSegments(folder, "index") as FullSlug
|
||||
const [tree, file] = folderContent
|
||||
const cfg = ctx.cfg.configuration
|
||||
const externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: file.data,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles,
|
||||
}
|
||||
|
||||
const content = renderPage(cfg, slug, componentData, opts, externalResources)
|
||||
yield write({
|
||||
ctx,
|
||||
content,
|
||||
slug,
|
||||
ext: ".html",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function computeFolderInfo(
|
||||
folders: Set<SimpleSlug>,
|
||||
content: ProcessedContent[],
|
||||
locale: keyof typeof TRANSLATIONS,
|
||||
): Record<SimpleSlug, ProcessedContent> {
|
||||
// Create default folder descriptions
|
||||
const folderInfo: Record<SimpleSlug, ProcessedContent> = Object.fromEntries(
|
||||
[...folders].map((folder) => [
|
||||
folder,
|
||||
defaultProcessedContent({
|
||||
slug: joinSegments(folder, "index") as FullSlug,
|
||||
frontmatter: {
|
||||
title: `${i18n(locale).pages.folderContent.folder}: ${folder}`,
|
||||
tags: [],
|
||||
},
|
||||
}),
|
||||
]),
|
||||
)
|
||||
|
||||
// Update with actual content if available
|
||||
for (const [tree, file] of content) {
|
||||
const slug = stripSlashes(simplifySlug(file.data.slug!)) as SimpleSlug
|
||||
if (folders.has(slug)) {
|
||||
folderInfo[slug] = [tree, file]
|
||||
}
|
||||
}
|
||||
|
||||
return folderInfo
|
||||
}
|
||||
|
||||
function _getFolders(slug: FullSlug): SimpleSlug[] {
|
||||
var folderName = path.dirname(slug ?? "") as SimpleSlug
|
||||
const parentFolderNames = [folderName]
|
||||
|
||||
while (folderName !== ".") {
|
||||
folderName = path.dirname(folderName ?? "") as SimpleSlug
|
||||
parentFolderNames.push(folderName)
|
||||
}
|
||||
return parentFolderNames
|
||||
}
|
||||
|
||||
export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (userOpts) => {
|
||||
const opts: FullPageLayout = {
|
||||
...sharedPageComponents,
|
||||
...defaultListPageLayout,
|
||||
pageBody: FolderContent({ sort: userOpts?.sort }),
|
||||
...userOpts,
|
||||
}
|
||||
|
||||
const { head: Head, header, beforeBody, pageBody, afterBody, left, right, footer: Footer } = opts
|
||||
const Header = HeaderConstructor()
|
||||
const Body = BodyConstructor()
|
||||
|
||||
return {
|
||||
name: "FolderPage",
|
||||
getQuartzComponents() {
|
||||
return [
|
||||
Head,
|
||||
Header,
|
||||
Body,
|
||||
...header,
|
||||
...beforeBody,
|
||||
pageBody,
|
||||
...afterBody,
|
||||
...left,
|
||||
...right,
|
||||
Footer,
|
||||
]
|
||||
},
|
||||
async *emit(ctx, content, resources) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
const cfg = ctx.cfg.configuration
|
||||
|
||||
const folders: Set<SimpleSlug> = new Set(
|
||||
allFiles.flatMap((data) => {
|
||||
return data.slug
|
||||
? _getFolders(data.slug).filter(
|
||||
(folderName) => folderName !== "." && folderName !== "tags",
|
||||
)
|
||||
: []
|
||||
}),
|
||||
)
|
||||
|
||||
const folderInfo = computeFolderInfo(folders, content, cfg.locale)
|
||||
yield* processFolderInfo(ctx, folderInfo, allFiles, opts, resources)
|
||||
},
|
||||
async *partialEmit(ctx, content, resources, changeEvents) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
const cfg = ctx.cfg.configuration
|
||||
|
||||
// Find all folders that need to be updated based on changed files
|
||||
const affectedFolders: Set<SimpleSlug> = new Set()
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
const slug = changeEvent.file.data.slug!
|
||||
const folders = _getFolders(slug).filter(
|
||||
(folderName) => folderName !== "." && folderName !== "tags",
|
||||
)
|
||||
folders.forEach((folder) => affectedFolders.add(folder))
|
||||
}
|
||||
|
||||
// If there are affected folders, rebuild their pages
|
||||
if (affectedFolders.size > 0) {
|
||||
const folderInfo = computeFolderInfo(affectedFolders, content, cfg.locale)
|
||||
yield* processFolderInfo(ctx, folderInfo, allFiles, opts, resources)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,3 @@
|
||||
export { ContentPage } from "./contentPage"
|
||||
export { TagPage } from "./tagPage"
|
||||
export { FolderPage } from "./folderPage"
|
||||
export { ContentIndex as ContentIndex } from "./contentIndex"
|
||||
export { AliasRedirects } from "./aliases"
|
||||
export { Assets } from "./assets"
|
||||
export { Static } from "./static"
|
||||
export { Favicon } from "./favicon"
|
||||
export { ComponentResources } from "./componentResources"
|
||||
export { NotFoundPage } from "./404"
|
||||
export { CNAME } from "./cname"
|
||||
export { CustomOgImages } from "./ogImage"
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { i18n } from "../../i18n"
|
||||
import { unescapeHTML } from "../../util/escape"
|
||||
import { FullSlug, getFileExtension, isAbsoluteURL, joinSegments, QUARTZ } from "../../util/path"
|
||||
import { ImageOptions, SocialImageOptions, defaultImage, getSatoriFonts } from "../../util/og"
|
||||
import sharp from "sharp"
|
||||
import satori, { SatoriOptions } from "satori"
|
||||
import { loadEmoji, getIconCode } from "../../util/emoji"
|
||||
import { Readable } from "stream"
|
||||
import { write } from "./helpers"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { QuartzPluginData } from "../vfile"
|
||||
import fs from "node:fs/promises"
|
||||
import { styleText } from "util"
|
||||
|
||||
const defaultOptions: SocialImageOptions = {
|
||||
colorScheme: "lightMode",
|
||||
width: 1200,
|
||||
height: 630,
|
||||
imageStructure: defaultImage,
|
||||
excludeRoot: false,
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates social image (OG/twitter standard) and saves it as `.webp` inside the public folder
|
||||
* @param opts options for generating image
|
||||
*/
|
||||
async function generateSocialImage(
|
||||
{ cfg, description, fonts, title, fileData }: ImageOptions,
|
||||
userOpts: SocialImageOptions,
|
||||
): Promise<Readable> {
|
||||
const { width, height } = userOpts
|
||||
const iconPath = joinSegments(QUARTZ, "static", "icon.png")
|
||||
let iconBase64: string | undefined = undefined
|
||||
try {
|
||||
const iconData = await fs.readFile(iconPath)
|
||||
iconBase64 = `data:image/png;base64,${iconData.toString("base64")}`
|
||||
} catch (err) {
|
||||
console.warn(styleText("yellow", `Warning: Could not find icon at ${iconPath}`))
|
||||
}
|
||||
|
||||
const imageComponent = userOpts.imageStructure({
|
||||
cfg,
|
||||
userOpts,
|
||||
title,
|
||||
description,
|
||||
fonts,
|
||||
fileData,
|
||||
iconBase64,
|
||||
})
|
||||
|
||||
const svg = await satori(imageComponent, {
|
||||
width,
|
||||
height,
|
||||
fonts,
|
||||
loadAdditionalAsset: async (languageCode: string, segment: string) => {
|
||||
if (languageCode === "emoji") {
|
||||
return await loadEmoji(getIconCode(segment))
|
||||
}
|
||||
|
||||
return languageCode
|
||||
},
|
||||
})
|
||||
|
||||
return sharp(Buffer.from(svg)).webp({ quality: 40 })
|
||||
}
|
||||
|
||||
async function processOgImage(
|
||||
ctx: BuildCtx,
|
||||
fileData: QuartzPluginData,
|
||||
fonts: SatoriOptions["fonts"],
|
||||
fullOptions: SocialImageOptions,
|
||||
) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const slug = fileData.slug!
|
||||
const titleSuffix = cfg.pageTitleSuffix ?? ""
|
||||
const title =
|
||||
(fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
|
||||
const description =
|
||||
fileData.frontmatter?.socialDescription ??
|
||||
fileData.frontmatter?.description ??
|
||||
unescapeHTML(fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description)
|
||||
|
||||
const stream = await generateSocialImage(
|
||||
{
|
||||
title,
|
||||
description,
|
||||
fonts,
|
||||
cfg,
|
||||
fileData,
|
||||
},
|
||||
fullOptions,
|
||||
)
|
||||
|
||||
return write({
|
||||
ctx,
|
||||
content: stream,
|
||||
slug: `${slug}-og-image` as FullSlug,
|
||||
ext: ".webp",
|
||||
})
|
||||
}
|
||||
|
||||
export const CustomOgImagesEmitterName = "CustomOgImages"
|
||||
export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> = (userOpts) => {
|
||||
const fullOptions = { ...defaultOptions, ...userOpts }
|
||||
|
||||
return {
|
||||
name: CustomOgImagesEmitterName,
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async *emit(ctx, content, _resources) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const headerFont = cfg.theme.typography.header
|
||||
const bodyFont = cfg.theme.typography.body
|
||||
const fonts = await getSatoriFonts(headerFont, bodyFont)
|
||||
|
||||
for (const [_tree, vfile] of content) {
|
||||
if (vfile.data.frontmatter?.socialImage !== undefined) continue
|
||||
yield processOgImage(ctx, vfile.data, fonts, fullOptions)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, _content, _resources, changeEvents) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const headerFont = cfg.theme.typography.header
|
||||
const bodyFont = cfg.theme.typography.body
|
||||
const fonts = await getSatoriFonts(headerFont, bodyFont)
|
||||
|
||||
// find all slugs that changed or were added
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
if (changeEvent.file.data.frontmatter?.socialImage !== undefined) continue
|
||||
if (changeEvent.type === "add" || changeEvent.type === "change") {
|
||||
yield processOgImage(ctx, changeEvent.file.data, fonts, fullOptions)
|
||||
}
|
||||
}
|
||||
},
|
||||
externalResources: (ctx) => {
|
||||
if (!ctx.cfg.configuration.baseUrl) {
|
||||
return {}
|
||||
}
|
||||
|
||||
const baseUrl = ctx.cfg.configuration.baseUrl
|
||||
return {
|
||||
additionalHead: [
|
||||
(pageData) => {
|
||||
const isRealFile = pageData.filePath !== undefined
|
||||
let userDefinedOgImagePath = pageData.frontmatter?.socialImage
|
||||
|
||||
if (userDefinedOgImagePath) {
|
||||
userDefinedOgImagePath = isAbsoluteURL(userDefinedOgImagePath)
|
||||
? userDefinedOgImagePath
|
||||
: `https://${baseUrl}/static/${userDefinedOgImagePath}`
|
||||
}
|
||||
|
||||
const generatedOgImagePath = isRealFile
|
||||
? `https://${baseUrl}/${pageData.slug!}-og-image.webp`
|
||||
: undefined
|
||||
const defaultOgImagePath = `https://${baseUrl}/static/og-image.png`
|
||||
const ogImagePath = userDefinedOgImagePath ?? generatedOgImagePath ?? defaultOgImagePath
|
||||
const ogImageMimeType = `image/${getFileExtension(ogImagePath) ?? "png"}`
|
||||
return (
|
||||
<>
|
||||
{!userDefinedOgImagePath && (
|
||||
<>
|
||||
<meta property="og:image:width" content={fullOptions.width.toString()} />
|
||||
<meta property="og:image:height" content={fullOptions.height.toString()} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<meta property="og:image" content={ogImagePath} />
|
||||
<meta property="og:image:url" content={ogImagePath} />
|
||||
<meta name="twitter:image" content={ogImagePath} />
|
||||
<meta property="og:image:type" content={ogImageMimeType} />
|
||||
</>
|
||||
)
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import { QuartzComponentProps } from "../../components/types"
|
||||
import HeaderConstructor from "../../components/Header"
|
||||
import BodyConstructor from "../../components/Body"
|
||||
import { pageResources, renderPage } from "../../components/renderPage"
|
||||
import { ProcessedContent, QuartzPluginData, defaultProcessedContent } from "../vfile"
|
||||
import { FullPageLayout } from "../../cfg"
|
||||
import { FullSlug, getAllSegmentPrefixes, joinSegments, pathToRoot } from "../../util/path"
|
||||
import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout"
|
||||
import { TagContent } from "../../components"
|
||||
import { write } from "./helpers"
|
||||
import { i18n, TRANSLATIONS } from "../../i18n"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { StaticResources } from "../../util/resources"
|
||||
|
||||
interface TagPageOptions extends FullPageLayout {
|
||||
sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number
|
||||
}
|
||||
|
||||
function computeTagInfo(
|
||||
allFiles: QuartzPluginData[],
|
||||
content: ProcessedContent[],
|
||||
locale: keyof typeof TRANSLATIONS,
|
||||
): [Set<string>, Record<string, ProcessedContent>] {
|
||||
const tags: Set<string> = new Set(
|
||||
allFiles.flatMap((data) => data.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes),
|
||||
)
|
||||
|
||||
// add base tag
|
||||
tags.add("index")
|
||||
|
||||
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
|
||||
[...tags].map((tag) => {
|
||||
const title =
|
||||
tag === "index"
|
||||
? i18n(locale).pages.tagContent.tagIndex
|
||||
: `${i18n(locale).pages.tagContent.tag}: ${tag}`
|
||||
return [
|
||||
tag,
|
||||
defaultProcessedContent({
|
||||
slug: joinSegments("tags", tag) as FullSlug,
|
||||
frontmatter: { title, tags: [] },
|
||||
}),
|
||||
]
|
||||
}),
|
||||
)
|
||||
|
||||
// Update with actual content if available
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
if (slug.startsWith("tags/")) {
|
||||
const tag = slug.slice("tags/".length)
|
||||
if (tags.has(tag)) {
|
||||
tagDescriptions[tag] = [tree, file]
|
||||
if (file.data.frontmatter?.title === tag) {
|
||||
file.data.frontmatter.title = `${i18n(locale).pages.tagContent.tag}: ${tag}`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [tags, tagDescriptions]
|
||||
}
|
||||
|
||||
async function processTagPage(
|
||||
ctx: BuildCtx,
|
||||
tag: string,
|
||||
tagContent: ProcessedContent,
|
||||
allFiles: QuartzPluginData[],
|
||||
opts: FullPageLayout,
|
||||
resources: StaticResources,
|
||||
) {
|
||||
const slug = joinSegments("tags", tag) as FullSlug
|
||||
const [tree, file] = tagContent
|
||||
const cfg = ctx.cfg.configuration
|
||||
const externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: file.data,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles,
|
||||
}
|
||||
|
||||
const content = renderPage(cfg, slug, componentData, opts, externalResources)
|
||||
return write({
|
||||
ctx,
|
||||
content,
|
||||
slug: file.data.slug!,
|
||||
ext: ".html",
|
||||
})
|
||||
}
|
||||
|
||||
export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts) => {
|
||||
const opts: FullPageLayout = {
|
||||
...sharedPageComponents,
|
||||
...defaultListPageLayout,
|
||||
pageBody: TagContent({ sort: userOpts?.sort }),
|
||||
...userOpts,
|
||||
}
|
||||
|
||||
const { head: Head, header, beforeBody, pageBody, afterBody, left, right, footer: Footer } = opts
|
||||
const Header = HeaderConstructor()
|
||||
const Body = BodyConstructor()
|
||||
|
||||
return {
|
||||
name: "TagPage",
|
||||
getQuartzComponents() {
|
||||
return [
|
||||
Head,
|
||||
Header,
|
||||
Body,
|
||||
...header,
|
||||
...beforeBody,
|
||||
pageBody,
|
||||
...afterBody,
|
||||
...left,
|
||||
...right,
|
||||
Footer,
|
||||
]
|
||||
},
|
||||
async *emit(ctx, content, resources) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
const cfg = ctx.cfg.configuration
|
||||
const [tags, tagDescriptions] = computeTagInfo(allFiles, content, cfg.locale)
|
||||
|
||||
for (const tag of tags) {
|
||||
yield processTagPage(ctx, tag, tagDescriptions[tag], allFiles, opts, resources)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, content, resources, changeEvents) {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
const cfg = ctx.cfg.configuration
|
||||
|
||||
// Find all tags that need to be updated based on changed files
|
||||
const affectedTags: Set<string> = new Set()
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
const slug = changeEvent.file.data.slug!
|
||||
|
||||
// If it's a tag page itself that changed
|
||||
if (slug.startsWith("tags/")) {
|
||||
const tag = slug.slice("tags/".length)
|
||||
affectedTags.add(tag)
|
||||
}
|
||||
|
||||
// If a file with tags changed, we need to update those tag pages
|
||||
const fileTags = changeEvent.file.data.frontmatter?.tags ?? []
|
||||
fileTags.flatMap(getAllSegmentPrefixes).forEach((tag) => affectedTags.add(tag))
|
||||
|
||||
// Always update the index tag page if any file changes
|
||||
affectedTags.add("index")
|
||||
}
|
||||
|
||||
// If there are affected tags, rebuild their pages
|
||||
if (affectedTags.size > 0) {
|
||||
// We still need to compute all tags because tag pages show all tags
|
||||
const [_tags, tagDescriptions] = computeTagInfo(allFiles, content, cfg.locale)
|
||||
|
||||
for (const tag of affectedTags) {
|
||||
if (tagDescriptions[tag]) {
|
||||
yield processTagPage(ctx, tag, tagDescriptions[tag], allFiles, opts, resources)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { QuartzFilterPlugin } from "../types"
|
||||
|
||||
export const RemoveDrafts: QuartzFilterPlugin<{}> = () => ({
|
||||
name: "RemoveDrafts",
|
||||
shouldPublish(_ctx, [_tree, vfile]) {
|
||||
const draftFlag: boolean =
|
||||
vfile.data?.frontmatter?.draft === true || vfile.data?.frontmatter?.draft === "true"
|
||||
return !draftFlag
|
||||
},
|
||||
})
|
||||
@@ -1,8 +0,0 @@
|
||||
import { QuartzFilterPlugin } from "../types"
|
||||
|
||||
export const ExplicitPublish: QuartzFilterPlugin = () => ({
|
||||
name: "ExplicitPublish",
|
||||
shouldPublish(_ctx, [_tree, vfile]) {
|
||||
return vfile.data?.frontmatter?.publish === true || vfile.data?.frontmatter?.publish === "true"
|
||||
},
|
||||
})
|
||||
@@ -1,2 +1 @@
|
||||
export { RemoveDrafts } from "./draft"
|
||||
export { ExplicitPublish } from "./explicit"
|
||||
export {}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { StaticResources } from "../util/resources"
|
||||
import { FilePath, FullSlug } from "../util/path"
|
||||
import { FilePath, FullSlug, SimpleSlug } from "../util/path"
|
||||
import { BuildCtx } from "../util/ctx"
|
||||
import { Root as HtmlRoot } from "hast"
|
||||
import { Element } from "hast"
|
||||
|
||||
export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
|
||||
const staticResources: StaticResources = {
|
||||
@@ -45,6 +47,10 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
|
||||
export * from "./transformers"
|
||||
export * from "./filters"
|
||||
export * from "./emitters"
|
||||
export * from "./types"
|
||||
export * from "./config"
|
||||
export * as PageTypes from "./pageTypes"
|
||||
export * as PluginLoader from "./loader"
|
||||
|
||||
declare module "vfile" {
|
||||
// inserted in processors.ts
|
||||
@@ -52,5 +58,32 @@ declare module "vfile" {
|
||||
slug: FullSlug
|
||||
filePath: FilePath
|
||||
relativePath: FilePath
|
||||
// from description transformer
|
||||
description: string
|
||||
text: string
|
||||
// from crawl-links transformer
|
||||
links: SimpleSlug[]
|
||||
// from table-of-contents transformer
|
||||
toc: { depth: number; text: string; slug: string }[]
|
||||
collapseToc: boolean
|
||||
// from obsidian-flavored-markdown transformer
|
||||
blocks: Record<string, Element>
|
||||
htmlAst: HtmlRoot
|
||||
hasMermaidDiagram: boolean | undefined
|
||||
// from frontmatter transformer (e.g. note-properties)
|
||||
frontmatter: {
|
||||
title: string
|
||||
tags: string[]
|
||||
description?: string
|
||||
socialDescription?: string
|
||||
lang?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
// from created-modified-date transformer
|
||||
dates: {
|
||||
created: Date
|
||||
modified: Date
|
||||
published: Date
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
72
quartz/plugins/loader/componentLoader.ts
Normal file
72
quartz/plugins/loader/componentLoader.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { componentRegistry } from "../../components/registry"
|
||||
import { ComponentManifest, PluginManifest } from "./types"
|
||||
import { QuartzComponentConstructor } from "../../components/types"
|
||||
import { getPluginSubpathEntry, toFileUrl } from "./gitLoader"
|
||||
|
||||
export async function loadComponentsFromPackage(
|
||||
pluginName: string,
|
||||
manifest: PluginManifest | null,
|
||||
subdir?: string,
|
||||
): Promise<void> {
|
||||
if (!manifest?.components) return
|
||||
|
||||
try {
|
||||
const componentsPath = getPluginSubpathEntry(pluginName, "./components", subdir)
|
||||
|
||||
let componentsModule: Record<string, unknown>
|
||||
if (componentsPath) {
|
||||
componentsModule = await import(toFileUrl(componentsPath))
|
||||
} else {
|
||||
componentsModule = await import(`${pluginName}/components`)
|
||||
}
|
||||
|
||||
const componentEntries = Object.entries(manifest.components)
|
||||
for (const [exportName, componentManifest] of componentEntries) {
|
||||
const component = componentsModule[exportName]
|
||||
if (!component) {
|
||||
console.warn(
|
||||
`Component "${exportName}" declared in manifest but not found in ${pluginName}/components`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// Register under the fully-qualified key (pluginName/exportName)
|
||||
componentRegistry.register(
|
||||
`${pluginName}/${exportName}`,
|
||||
component as QuartzComponentConstructor,
|
||||
pluginName,
|
||||
componentManifest as ComponentManifest,
|
||||
)
|
||||
|
||||
// Also register under just the export name (e.g. "Footer", "NotePropertiesComponent")
|
||||
// so buildLayoutForEntries can find it via PascalCase conversion of plugin name
|
||||
if (!componentRegistry.get(exportName)) {
|
||||
componentRegistry.register(
|
||||
exportName,
|
||||
component as QuartzComponentConstructor,
|
||||
pluginName,
|
||||
componentManifest as ComponentManifest,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// If plugin has exactly one component, also register under just the plugin name
|
||||
// (e.g. "footer", "note-properties") for direct kebab-case lookup
|
||||
if (componentEntries.length === 1) {
|
||||
const [exportName] = componentEntries[0]
|
||||
const component = componentsModule[exportName]
|
||||
if (component && !componentRegistry.get(pluginName)) {
|
||||
componentRegistry.register(
|
||||
pluginName,
|
||||
component as QuartzComponentConstructor,
|
||||
pluginName,
|
||||
componentEntries[0][1] as ComponentManifest,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (manifest.components && Object.keys(manifest.components).length > 0) {
|
||||
console.warn(`Plugin "${pluginName}" declares components but failed to load them`)
|
||||
}
|
||||
}
|
||||
}
|
||||
33
quartz/plugins/loader/conditions.ts
Normal file
33
quartz/plugins/loader/conditions.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { QuartzComponentProps } from "../../components/types"
|
||||
|
||||
export type ConditionPredicate = (props: QuartzComponentProps) => boolean
|
||||
|
||||
const builtinConditions: Record<string, ConditionPredicate> = {
|
||||
"not-index": (props) => props.fileData.slug !== "index",
|
||||
"has-tags": (props) => {
|
||||
const tags = props.fileData.frontmatter?.tags
|
||||
return Array.isArray(tags) && tags.length > 0
|
||||
},
|
||||
"has-backlinks": (props) => {
|
||||
const backlinks = (props.fileData as Record<string, unknown>).backlinks
|
||||
return Array.isArray(backlinks) && backlinks.length > 0
|
||||
},
|
||||
"has-toc": (props) => {
|
||||
const toc = (props.fileData as Record<string, unknown>).toc
|
||||
return Array.isArray(toc) && toc.length > 0
|
||||
},
|
||||
}
|
||||
|
||||
const customConditions = new Map<string, ConditionPredicate>()
|
||||
|
||||
export function registerCondition(name: string, predicate: ConditionPredicate): void {
|
||||
customConditions.set(name, predicate)
|
||||
}
|
||||
|
||||
export function getCondition(name: string): ConditionPredicate | undefined {
|
||||
return customConditions.get(name) ?? builtinConditions[name]
|
||||
}
|
||||
|
||||
export function getAllConditionNames(): string[] {
|
||||
return [...Object.keys(builtinConditions), ...customConditions.keys()]
|
||||
}
|
||||
840
quartz/plugins/loader/config-loader.ts
Normal file
840
quartz/plugins/loader/config-loader.ts
Normal file
@@ -0,0 +1,840 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import YAML from "yaml"
|
||||
import { styleText } from "util"
|
||||
import { QuartzConfig, GlobalConfiguration, FullPageLayout } from "../../cfg"
|
||||
import { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
|
||||
import { PluginTypes } from "../types"
|
||||
import {
|
||||
PluginManifest,
|
||||
PluginJsonEntry,
|
||||
QuartzPluginsJson,
|
||||
LayoutConfig,
|
||||
PluginLayoutDeclaration,
|
||||
FlexGroupConfig,
|
||||
} from "./types"
|
||||
import {
|
||||
parsePluginSource,
|
||||
installPlugin,
|
||||
getPluginEntryPoint,
|
||||
toFileUrl,
|
||||
isLocalSource,
|
||||
} from "./gitLoader"
|
||||
import { loadComponentsFromPackage } from "./componentLoader"
|
||||
import { loadFramesFromPackage } from "./frameLoader"
|
||||
import { componentRegistry } from "../../components/registry"
|
||||
import { getCondition } from "./conditions"
|
||||
|
||||
const CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.yaml")
|
||||
const DEFAULT_CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.default.yaml")
|
||||
const LEGACY_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.json")
|
||||
const LEGACY_DEFAULT_PLUGINS_JSON_PATH = path.join(process.cwd(), "quartz.plugins.default.json")
|
||||
|
||||
function resolveConfigPath(): string {
|
||||
if (fs.existsSync(CONFIG_YAML_PATH)) return CONFIG_YAML_PATH
|
||||
if (fs.existsSync(LEGACY_PLUGINS_JSON_PATH)) return LEGACY_PLUGINS_JSON_PATH
|
||||
if (fs.existsSync(DEFAULT_CONFIG_YAML_PATH)) return DEFAULT_CONFIG_YAML_PATH
|
||||
if (fs.existsSync(LEGACY_DEFAULT_PLUGINS_JSON_PATH)) return LEGACY_DEFAULT_PLUGINS_JSON_PATH
|
||||
return CONFIG_YAML_PATH
|
||||
}
|
||||
function readPluginsJson(): QuartzPluginsJson | null {
|
||||
const configPath = resolveConfigPath()
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return null
|
||||
}
|
||||
const raw = fs.readFileSync(configPath, "utf-8")
|
||||
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
|
||||
return YAML.parse(raw) as QuartzPluginsJson
|
||||
}
|
||||
return JSON.parse(raw) as QuartzPluginsJson
|
||||
}
|
||||
|
||||
function extractPluginName(source: string): string {
|
||||
// Local file paths: use directory basename
|
||||
if (isLocalSource(source)) {
|
||||
return path.basename(source.replace(/[\/]+$/, ""))
|
||||
}
|
||||
if (source.startsWith("github:")) {
|
||||
const withoutPrefix = source.replace("github:", "")
|
||||
const [repoPath] = withoutPrefix.split("#")
|
||||
const parts = repoPath.split("/")
|
||||
return parts[parts.length - 1]
|
||||
}
|
||||
if (source.startsWith("git+") || source.startsWith("https://")) {
|
||||
const url = source.replace("git+", "")
|
||||
const match = url.match(/\/([^/]+?)(?:\.git)?(?:#|$)/)
|
||||
return match?.[1] ?? source
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
interface DependencyValidationResult {
|
||||
errors: string[]
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
function validateDependencies(
|
||||
entries: PluginJsonEntry[],
|
||||
manifests: Map<string, PluginManifest>,
|
||||
): DependencyValidationResult {
|
||||
const errors: string[] = []
|
||||
const warnings: string[] = []
|
||||
|
||||
const sourceToEntry = new Map<string, PluginJsonEntry>()
|
||||
const nameToSource = new Map<string, string>()
|
||||
for (const entry of entries) {
|
||||
sourceToEntry.set(entry.source, entry)
|
||||
nameToSource.set(extractPluginName(entry.source), entry.source)
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.enabled) continue
|
||||
const manifest = manifests.get(entry.source)
|
||||
if (!manifest?.dependencies?.length) continue
|
||||
|
||||
const pluginName = manifest.displayName || extractPluginName(entry.source)
|
||||
const pluginOrder = entry.order ?? manifest.defaultOrder ?? 50
|
||||
|
||||
for (const dep of manifest.dependencies) {
|
||||
const depEntry = sourceToEntry.get(dep)
|
||||
const depName = extractPluginName(dep)
|
||||
|
||||
if (!depEntry) {
|
||||
errors.push(
|
||||
`Plugin "${pluginName}" requires "${depName}". Run: npx quartz plugin add ${dep}`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!depEntry.enabled) {
|
||||
warnings.push(
|
||||
`Plugin "${pluginName}" depends on "${depName}" which is disabled. "${pluginName}" may not function correctly.`,
|
||||
)
|
||||
}
|
||||
|
||||
const depManifest = manifests.get(dep)
|
||||
const depOrder = depEntry.order ?? depManifest?.defaultOrder ?? 50
|
||||
|
||||
if (pluginOrder < depOrder) {
|
||||
errors.push(
|
||||
`Plugin "${pluginName}" (order: ${pluginOrder}) depends on "${depName}" (order: ${depOrder}), ` +
|
||||
`but "${pluginName}" is configured to run first. Either increase "${pluginName}"'s order above ${depOrder} ` +
|
||||
`or decrease "${depName}"'s order below ${pluginOrder}.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Circular dependency detection
|
||||
const graph = new Map<string, string[]>()
|
||||
for (const entry of entries) {
|
||||
const manifest = manifests.get(entry.source)
|
||||
if (manifest?.dependencies?.length) {
|
||||
graph.set(entry.source, manifest.dependencies)
|
||||
}
|
||||
}
|
||||
|
||||
const visited = new Set<string>()
|
||||
const inStack = new Set<string>()
|
||||
|
||||
function detectCycle(node: string, pathSoFar: string[]): string[] | null {
|
||||
if (inStack.has(node)) {
|
||||
const cycleStart = pathSoFar.indexOf(node)
|
||||
return pathSoFar.slice(cycleStart).concat(node)
|
||||
}
|
||||
if (visited.has(node)) return null
|
||||
|
||||
visited.add(node)
|
||||
inStack.add(node)
|
||||
|
||||
for (const dep of graph.get(node) ?? []) {
|
||||
const cycle = detectCycle(dep, [...pathSoFar, node])
|
||||
if (cycle) return cycle
|
||||
}
|
||||
|
||||
inStack.delete(node)
|
||||
return null
|
||||
}
|
||||
|
||||
for (const node of graph.keys()) {
|
||||
const cycle = detectCycle(node, [])
|
||||
if (cycle) {
|
||||
const names = cycle.map(extractPluginName)
|
||||
errors.push(`Circular dependency detected: ${names.join(" → ")}`)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { errors, warnings }
|
||||
}
|
||||
|
||||
async function resolvePluginManifest(source: string): Promise<PluginManifest | null> {
|
||||
try {
|
||||
const gitSpec = parsePluginSource(source)
|
||||
const entryPoint = getPluginEntryPoint(gitSpec.name, gitSpec.subdir)
|
||||
const module = await import(toFileUrl(entryPoint))
|
||||
return module.manifest ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function readManifestFromPackageJson(source: string): Promise<PluginManifest | null> {
|
||||
try {
|
||||
const gitSpec = parsePluginSource(source)
|
||||
const pluginDir = path.join(process.cwd(), ".quartz", "plugins", gitSpec.name)
|
||||
const pkgPath = path.join(pluginDir, "package.json")
|
||||
if (!fs.existsSync(pkgPath)) return null
|
||||
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
|
||||
if (!pkg.quartz) return null
|
||||
|
||||
const q = pkg.quartz
|
||||
return {
|
||||
name: q.name ?? gitSpec.name,
|
||||
displayName: q.displayName ?? q.name ?? gitSpec.name,
|
||||
description: q.description ?? pkg.description ?? "No description",
|
||||
version: q.version ?? pkg.version ?? "1.0.0",
|
||||
author: q.author ?? pkg.author,
|
||||
homepage: q.homepage ?? pkg.homepage,
|
||||
category: q.category,
|
||||
quartzVersion: q.quartzVersion,
|
||||
dependencies: q.dependencies,
|
||||
defaultOrder: q.defaultOrder,
|
||||
defaultEnabled: q.defaultEnabled,
|
||||
defaultOptions: q.defaultOptions,
|
||||
configSchema: q.configSchema,
|
||||
components: q.components,
|
||||
frames: q.frames,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function getManifest(source: string): Promise<PluginManifest | null> {
|
||||
// Try package.json quartz field first (preferred), then fall back to manifest.ts export
|
||||
return (await readManifestFromPackageJson(source)) ?? (await resolvePluginManifest(source))
|
||||
}
|
||||
|
||||
export async function loadQuartzConfig(
|
||||
configOverrides?: Partial<GlobalConfiguration>,
|
||||
): Promise<QuartzConfig> {
|
||||
const json = readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style config directly
|
||||
const oldConfig = await import("../../../quartz")
|
||||
return oldConfig.default
|
||||
}
|
||||
|
||||
const configuration = {
|
||||
...(json.configuration as unknown as GlobalConfiguration),
|
||||
...configOverrides,
|
||||
}
|
||||
|
||||
const enabledEntries = json.plugins.filter((e) => e.enabled)
|
||||
const manifests = new Map<string, PluginManifest>()
|
||||
|
||||
// Ensure all plugins are installed and collect manifests
|
||||
for (const entry of enabledEntries) {
|
||||
try {
|
||||
const gitSpec = parsePluginSource(entry.source)
|
||||
await installPlugin(gitSpec, { verbose: false })
|
||||
|
||||
const manifest = await getManifest(entry.source)
|
||||
if (manifest) {
|
||||
manifests.set(entry.source, manifest)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
styleText("red", `✗`) +
|
||||
` Failed to install plugin: ${styleText("yellow", entry.source)}\n` +
|
||||
` ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate dependencies
|
||||
const validation = validateDependencies(enabledEntries, manifests)
|
||||
for (const warning of validation.warnings) {
|
||||
console.warn(styleText("yellow", `⚠`) + ` ${warning}`)
|
||||
}
|
||||
if (validation.errors.length > 0) {
|
||||
for (const error of validation.errors) {
|
||||
console.error(styleText("red", `✗`) + ` ${error}`)
|
||||
}
|
||||
throw new Error(
|
||||
`Plugin dependency validation failed with ${validation.errors.length} error(s). See above for details.`,
|
||||
)
|
||||
}
|
||||
|
||||
// Categorize and sort plugins
|
||||
const transformers: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[] = []
|
||||
const filters: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[] = []
|
||||
const emitters: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[] = []
|
||||
const pageTypes: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[] = []
|
||||
|
||||
for (const entry of enabledEntries) {
|
||||
const manifest = manifests.get(entry.source)
|
||||
const category = manifest?.category
|
||||
// Resolve processing categories: for array categories (e.g. ["transformer", "pageType", "component"]),
|
||||
// push the plugin into ALL matching processing category buckets.
|
||||
// "component" is handled separately via loadComponentsFromPackage during instantiation.
|
||||
const processingCategories = ["transformer", "filter", "emitter", "pageType"] as const
|
||||
const categoryMap: Record<string, typeof transformers> = {
|
||||
transformer: transformers,
|
||||
filter: filters,
|
||||
emitter: emitters,
|
||||
pageType: pageTypes,
|
||||
}
|
||||
|
||||
const categories = Array.isArray(category) ? category : category ? [category] : []
|
||||
const matchedProcessing = categories.filter((c) =>
|
||||
(processingCategories as readonly string[]).includes(c),
|
||||
)
|
||||
|
||||
if (matchedProcessing.length > 0) {
|
||||
for (const cat of matchedProcessing) {
|
||||
categoryMap[cat].push({ entry, manifest })
|
||||
}
|
||||
} else {
|
||||
const gitSpec = parsePluginSource(entry.source)
|
||||
const isComponentOnly = categories.length > 0 && categories.every((c) => c === "component")
|
||||
|
||||
if (isComponentOnly) {
|
||||
// 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, gitSpec.subdir)
|
||||
try {
|
||||
await import(toFileUrl(entryPoint))
|
||||
} catch (e) {
|
||||
// Side-effect import failed — continue with manifest-based loading
|
||||
}
|
||||
if (manifest?.components && Object.keys(manifest.components).length > 0) {
|
||||
await loadComponentsFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
if (manifest?.frames && Object.keys(manifest.frames).length > 0) {
|
||||
await loadFramesFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
} else {
|
||||
const entryPoint = getPluginEntryPoint(gitSpec.name, gitSpec.subdir)
|
||||
try {
|
||||
const module = await import(toFileUrl(entryPoint))
|
||||
const detected = detectCategoryFromModule(module)
|
||||
if (detected) {
|
||||
categoryMap[detected].push({ entry, manifest })
|
||||
} else if (manifest?.components && Object.keys(manifest.components).length > 0) {
|
||||
await loadComponentsFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
if (manifest?.frames && Object.keys(manifest.frames).length > 0) {
|
||||
await loadFramesFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
} else {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`) +
|
||||
` Could not determine category for plugin "${extractPluginName(entry.source)}". Skipping.`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
const hasComponents = manifest?.components && Object.keys(manifest.components).length > 0
|
||||
const hasFrames = manifest?.frames && Object.keys(manifest.frames).length > 0
|
||||
if (hasComponents) {
|
||||
await loadComponentsFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
if (hasFrames) {
|
||||
await loadFramesFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
if (!hasComponents && !hasFrames) {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`) +
|
||||
` Could not load plugin "${extractPluginName(entry.source)}" to detect category. Skipping.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by order within each category
|
||||
const sortByOrder = (
|
||||
a: { entry: PluginJsonEntry; manifest: PluginManifest | undefined },
|
||||
b: { entry: PluginJsonEntry; manifest: PluginManifest | undefined },
|
||||
) => {
|
||||
const orderA = a.entry.order ?? a.manifest?.defaultOrder ?? 50
|
||||
const orderB = b.entry.order ?? b.manifest?.defaultOrder ?? 50
|
||||
return orderA - orderB
|
||||
}
|
||||
|
||||
transformers.sort(sortByOrder)
|
||||
filters.sort(sortByOrder)
|
||||
emitters.sort(sortByOrder)
|
||||
pageTypes.sort(sortByOrder)
|
||||
|
||||
// Instantiate plugins
|
||||
const instantiate = async (
|
||||
items: { entry: PluginJsonEntry; manifest: PluginManifest | undefined }[],
|
||||
expectedCategory: ProcessingCategory,
|
||||
) => {
|
||||
const instances = []
|
||||
for (const { entry, manifest } of items) {
|
||||
try {
|
||||
const gitSpec = parsePluginSource(entry.source)
|
||||
const entryPoint = getPluginEntryPoint(gitSpec.name, gitSpec.subdir)
|
||||
const module = await import(toFileUrl(entryPoint))
|
||||
if (manifest?.components && Object.keys(manifest.components).length > 0) {
|
||||
await loadComponentsFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
if (manifest?.frames && Object.keys(manifest.frames).length > 0) {
|
||||
await loadFramesFromPackage(gitSpec.name, manifest, gitSpec.subdir)
|
||||
}
|
||||
|
||||
const factory = findFactory(module, expectedCategory)
|
||||
if (!factory) {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`) +
|
||||
` Plugin "${extractPluginName(entry.source)}" has no factory function for category "${expectedCategory}". Skipping.`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
const options = { ...manifest?.defaultOptions, ...entry.options }
|
||||
instances.push(factory(Object.keys(options).length > 0 ? options : undefined))
|
||||
} catch (err) {
|
||||
console.error(
|
||||
styleText("red", `✗`) +
|
||||
` Failed to instantiate plugin "${extractPluginName(entry.source)}": ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return instances
|
||||
}
|
||||
|
||||
// Import built-in plugins
|
||||
const builtinPlugins = await import("../index")
|
||||
const builtinTransformers: unknown[] = []
|
||||
const builtinEmitters = [
|
||||
builtinPlugins.ComponentResources(),
|
||||
builtinPlugins.Assets(),
|
||||
builtinPlugins.Static(),
|
||||
]
|
||||
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
|
||||
|
||||
const plugins: PluginTypes = {
|
||||
transformers: [...builtinTransformers, ...(await instantiate(transformers, "transformer"))],
|
||||
filters: await instantiate(filters, "filter"),
|
||||
emitters: [...builtinEmitters, ...(await instantiate(emitters, "emitter"))],
|
||||
pageTypes: [...(await instantiate(pageTypes, "pageType")), ...builtinPageTypes],
|
||||
}
|
||||
|
||||
// Load layout and add PageTypeDispatcher to emitters.
|
||||
// This must happen after plugin instantiation so the component registry is populated.
|
||||
const layout = await loadQuartzLayout()
|
||||
plugins.emitters.push(
|
||||
builtinPlugins.PageTypes.PageTypeDispatcher({
|
||||
defaults: layout.defaults,
|
||||
byPageType: layout.byPageType,
|
||||
}),
|
||||
)
|
||||
return {
|
||||
configuration,
|
||||
plugins,
|
||||
}
|
||||
}
|
||||
|
||||
type ProcessingCategory = "transformer" | "filter" | "emitter" | "pageType"
|
||||
|
||||
function matchesCategory(factory: Function, expected: ProcessingCategory): boolean {
|
||||
try {
|
||||
const instance = factory()
|
||||
if (!instance || typeof instance !== "object") return false
|
||||
switch (expected) {
|
||||
case "pageType":
|
||||
return "match" in instance && "body" in instance && "layout" in instance
|
||||
case "emitter":
|
||||
return "emit" in instance
|
||||
case "filter":
|
||||
return "shouldPublish" in instance
|
||||
case "transformer":
|
||||
return (
|
||||
"textTransform" in instance || "markdownPlugins" in instance || "htmlPlugins" in instance
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function findFactory(
|
||||
module: Record<string, unknown>,
|
||||
expectedCategory: ProcessingCategory,
|
||||
): Function | null {
|
||||
if (
|
||||
typeof module.default === "function" &&
|
||||
matchesCategory(module.default as Function, expectedCategory)
|
||||
) {
|
||||
return module.default as Function
|
||||
}
|
||||
if (
|
||||
typeof module.plugin === "function" &&
|
||||
matchesCategory(module.plugin as Function, expectedCategory)
|
||||
) {
|
||||
return module.plugin as Function
|
||||
}
|
||||
|
||||
for (const [, value] of Object.entries(module)) {
|
||||
if (typeof value === "function" && matchesCategory(value as Function, expectedCategory)) {
|
||||
return value as Function
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function detectCategoryFromModule(module: unknown): ProcessingCategory | null {
|
||||
if (!module || typeof module !== "object") return null
|
||||
const mod = module as Record<string, unknown>
|
||||
|
||||
if (typeof mod.default === "function") {
|
||||
// Try to instantiate and inspect
|
||||
try {
|
||||
const instance = (mod.default as Function)()
|
||||
if (instance && typeof instance === "object") {
|
||||
if ("match" in instance && "body" in instance && "layout" in instance) return "pageType"
|
||||
if ("emit" in instance) return "emitter"
|
||||
if ("shouldPublish" in instance) return "filter"
|
||||
if (
|
||||
"textTransform" in instance ||
|
||||
"markdownPlugins" in instance ||
|
||||
"htmlPlugins" in instance
|
||||
)
|
||||
return "transformer"
|
||||
}
|
||||
} catch {
|
||||
// Couldn't instantiate, skip detection
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function loadQuartzLayout(layoutOverrides?: {
|
||||
defaults?: Partial<FullPageLayout>
|
||||
byPageType?: Record<string, Partial<FullPageLayout>>
|
||||
}): Promise<{
|
||||
defaults: Partial<FullPageLayout>
|
||||
byPageType: Record<string, Partial<FullPageLayout>>
|
||||
}> {
|
||||
const json = readPluginsJson()
|
||||
|
||||
if (!json) {
|
||||
// Fallback: import old-style layout directly
|
||||
const oldLayout = await import("../../../quartz")
|
||||
return oldLayout.layout
|
||||
}
|
||||
|
||||
const enabledWithLayout = json.plugins.filter((e) => e.enabled && e.layout)
|
||||
const layoutConfig = json.layout ?? {}
|
||||
|
||||
// Build default layout for all page types
|
||||
const defaultLayout = buildLayoutForEntries(enabledWithLayout, layoutConfig)
|
||||
|
||||
// Build per-page-type overrides
|
||||
const byPageType: Record<string, Partial<FullPageLayout>> = {}
|
||||
if (layoutConfig.byPageType) {
|
||||
for (const [pageType, override] of Object.entries(layoutConfig.byPageType)) {
|
||||
let filteredEntries = enabledWithLayout
|
||||
|
||||
// Apply exclusions
|
||||
if (override.exclude?.length) {
|
||||
filteredEntries = filteredEntries.filter((e) => {
|
||||
const name = extractPluginName(e.source)
|
||||
return !override.exclude!.includes(name)
|
||||
})
|
||||
}
|
||||
|
||||
const ptLayout = buildLayoutForEntries(filteredEntries, layoutConfig)
|
||||
|
||||
// Apply position overrides (empty array = clear position)
|
||||
if (override.positions) {
|
||||
for (const [pos, components] of Object.entries(override.positions)) {
|
||||
if (Array.isArray(components) && components.length === 0) {
|
||||
const key = pos as keyof Pick<
|
||||
FullPageLayout,
|
||||
"left" | "right" | "beforeBody" | "afterBody"
|
||||
>
|
||||
if (key in ptLayout) {
|
||||
;(ptLayout as Record<string, unknown>)[key] = []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply frame template override
|
||||
if (override.template) {
|
||||
ptLayout.frame = override.template
|
||||
}
|
||||
|
||||
byPageType[pageType] = ptLayout
|
||||
}
|
||||
}
|
||||
|
||||
// Add Head (built-in) and Footer (plugin)
|
||||
const HeadModule = await import("../../components/Head")
|
||||
const head = HeadModule.default()
|
||||
|
||||
// Find footer from component registry (loaded during plugin instantiation)
|
||||
const footerEntry = json.plugins.find(
|
||||
(e) => e.enabled && extractPluginName(e.source) === "footer",
|
||||
)
|
||||
let footer: QuartzComponent | undefined
|
||||
if (footerEntry) {
|
||||
// Try registry lookup: plugin name ("footer") or export name ("Footer")
|
||||
const footerReg = componentRegistry.get("footer") ?? componentRegistry.get("Footer")
|
||||
if (footerReg) {
|
||||
if (typeof footerReg.component === "function" && !("displayName" in footerReg.component)) {
|
||||
// It's a constructor — use registry cache for consistent instances
|
||||
const opts = { ...footerEntry.options }
|
||||
footer = componentRegistry.instantiate(
|
||||
footerReg.component as QuartzComponentConstructor,
|
||||
Object.keys(opts).length > 0 ? opts : undefined,
|
||||
)
|
||||
} else {
|
||||
footer = footerReg.component as QuartzComponent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply structural defaults
|
||||
defaultLayout.head = head
|
||||
defaultLayout.header = defaultLayout.header ?? []
|
||||
if (footer) {
|
||||
defaultLayout.footer = footer
|
||||
}
|
||||
|
||||
// Ensure all byPageType entries inherit structural slots
|
||||
for (const pageType of Object.keys(byPageType)) {
|
||||
const pt = byPageType[pageType]
|
||||
if (!pt.head) pt.head = head
|
||||
if (!pt.header) pt.header = []
|
||||
if (footer && !pt.footer) pt.footer = footer
|
||||
}
|
||||
|
||||
const mergedDefaults = { ...defaultLayout, ...layoutOverrides?.defaults }
|
||||
const mergedByPageType = { ...byPageType }
|
||||
if (layoutOverrides?.byPageType) {
|
||||
for (const [pageType, overrideLayout] of Object.entries(layoutOverrides.byPageType)) {
|
||||
mergedByPageType[pageType] = { ...mergedByPageType[pageType], ...overrideLayout }
|
||||
}
|
||||
}
|
||||
|
||||
return { defaults: mergedDefaults, byPageType: mergedByPageType }
|
||||
}
|
||||
|
||||
function buildLayoutForEntries(
|
||||
entries: PluginJsonEntry[],
|
||||
layoutConfig: LayoutConfig,
|
||||
): Partial<FullPageLayout> {
|
||||
const positions: Record<
|
||||
string,
|
||||
{
|
||||
component: QuartzComponent
|
||||
priority: number
|
||||
group?: string
|
||||
groupOptions?: PluginLayoutDeclaration["groupOptions"]
|
||||
}[]
|
||||
> = {
|
||||
left: [],
|
||||
right: [],
|
||||
beforeBody: [],
|
||||
afterBody: [],
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.layout) continue
|
||||
|
||||
const layout = entry.layout
|
||||
const name = extractPluginName(entry.source)
|
||||
|
||||
// Look up component from registry
|
||||
const registered =
|
||||
componentRegistry.get(name) ?? componentRegistry.get(`${entry.source}/${name}`)
|
||||
if (!registered) {
|
||||
// Try common naming patterns
|
||||
const pascalName = name
|
||||
.split("-")
|
||||
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.join("")
|
||||
const altRegistered = componentRegistry.get(pascalName)
|
||||
if (!altRegistered) continue
|
||||
}
|
||||
|
||||
const reg =
|
||||
registered ??
|
||||
componentRegistry.get(
|
||||
name
|
||||
.split("-")
|
||||
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.join(""),
|
||||
)
|
||||
if (!reg) continue
|
||||
|
||||
let component: QuartzComponent
|
||||
if (typeof reg.component === "function" && !("displayName" in reg.component)) {
|
||||
// It's a constructor — use registry cache to avoid duplicate instances
|
||||
// (and duplicate afterDOMLoaded scripts) across page-type layouts
|
||||
const opts = { ...entry.options }
|
||||
const optsArg = Object.keys(opts).length > 0 ? opts : undefined
|
||||
component = componentRegistry.instantiate(
|
||||
reg.component as QuartzComponentConstructor,
|
||||
optsArg,
|
||||
)
|
||||
} else {
|
||||
component = reg.component as QuartzComponent
|
||||
}
|
||||
|
||||
// Apply display modifier
|
||||
if (layout.display && layout.display !== "all") {
|
||||
component = applyDisplayWrapper(component, layout.display)
|
||||
}
|
||||
|
||||
// Apply condition
|
||||
if (layout.condition) {
|
||||
component = applyConditionWrapper(component, layout.condition)
|
||||
}
|
||||
|
||||
const posArray = positions[layout.position]
|
||||
if (posArray) {
|
||||
posArray.push({
|
||||
component,
|
||||
priority: layout.priority,
|
||||
group: layout.group,
|
||||
groupOptions: layout.groupOptions,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by priority and resolve groups
|
||||
const result: Partial<FullPageLayout> = {}
|
||||
|
||||
for (const [position, items] of Object.entries(positions)) {
|
||||
items.sort((a, b) => a.priority - b.priority)
|
||||
|
||||
const resolved = resolveGroups(items, layoutConfig.groups ?? {})
|
||||
const key = position as keyof Pick<
|
||||
FullPageLayout,
|
||||
"left" | "right" | "beforeBody" | "afterBody"
|
||||
>
|
||||
;(result as Record<string, QuartzComponent[]>)[key] = resolved
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function resolveGroups(
|
||||
items: {
|
||||
component: QuartzComponent
|
||||
priority: number
|
||||
group?: string
|
||||
groupOptions?: PluginLayoutDeclaration["groupOptions"]
|
||||
}[],
|
||||
groups: Record<string, FlexGroupConfig>,
|
||||
): QuartzComponent[] {
|
||||
// Collect grouped components and track the effective priority for each group.
|
||||
// Effective priority = explicit group config priority ?? first member's priority.
|
||||
const groupedComponents = new Map<
|
||||
string,
|
||||
{ component: QuartzComponent; groupOptions?: PluginLayoutDeclaration["groupOptions"] }[]
|
||||
>()
|
||||
const groupPriority = new Map<string, number>()
|
||||
|
||||
for (const item of items) {
|
||||
if (item.group) {
|
||||
if (!groupedComponents.has(item.group)) {
|
||||
groupedComponents.set(item.group, [])
|
||||
// Use explicit group priority from config if set, otherwise fall back to first member's priority
|
||||
const groupConfig = groups[item.group]
|
||||
groupPriority.set(item.group, groupConfig?.priority ?? item.priority)
|
||||
}
|
||||
groupedComponents.get(item.group)!.push({
|
||||
component: item.component,
|
||||
groupOptions: item.groupOptions,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Build a unified list of renderable entries (ungrouped components + flex groups),
|
||||
// each with a priority, so we can sort them together.
|
||||
type RenderEntry = { priority: number; component: QuartzComponent }
|
||||
const entries: RenderEntry[] = []
|
||||
const processedGroups = new Set<string>()
|
||||
|
||||
for (const item of items) {
|
||||
if (item.group) {
|
||||
// Only emit the flex group once (on first encounter)
|
||||
if (processedGroups.has(item.group)) continue
|
||||
processedGroups.add(item.group)
|
||||
|
||||
const members = groupedComponents.get(item.group)!
|
||||
const groupConfig = groups[item.group] ?? {}
|
||||
|
||||
const flexComponents = members.map((m) => ({
|
||||
Component: m.component,
|
||||
grow: m.groupOptions?.grow,
|
||||
shrink: m.groupOptions?.shrink,
|
||||
basis: m.groupOptions?.basis,
|
||||
order: m.groupOptions?.order,
|
||||
align: m.groupOptions?.align,
|
||||
justify: m.groupOptions?.justify,
|
||||
}))
|
||||
|
||||
// Dynamically import Flex to avoid circular dependencies
|
||||
const FlexModule = require("../../components/Flex")
|
||||
const Flex = FlexModule.default as Function
|
||||
const flexComponent = Flex({
|
||||
components: flexComponents,
|
||||
direction: groupConfig.direction ?? "row",
|
||||
wrap: groupConfig.wrap,
|
||||
gap: groupConfig.gap ?? "1rem",
|
||||
}) as QuartzComponent
|
||||
|
||||
entries.push({ priority: groupPriority.get(item.group)!, component: flexComponent })
|
||||
} else {
|
||||
entries.push({ priority: item.priority, component: item.component })
|
||||
}
|
||||
}
|
||||
|
||||
// Stable sort by priority (items already arrive sorted, so equal priorities preserve order)
|
||||
entries.sort((a, b) => a.priority - b.priority)
|
||||
|
||||
return entries.map((e) => e.component)
|
||||
}
|
||||
|
||||
function applyDisplayWrapper(
|
||||
component: QuartzComponent,
|
||||
display: "mobile-only" | "desktop-only",
|
||||
): QuartzComponent {
|
||||
if (display === "mobile-only") {
|
||||
const MobileOnly = require("../../components/MobileOnly").default as Function
|
||||
return MobileOnly(component) as QuartzComponent
|
||||
} else {
|
||||
const DesktopOnly = require("../../components/DesktopOnly").default as Function
|
||||
return DesktopOnly(component) as QuartzComponent
|
||||
}
|
||||
}
|
||||
|
||||
function applyConditionWrapper(component: QuartzComponent, conditionName: string): QuartzComponent {
|
||||
const predicate = getCondition(conditionName)
|
||||
if (!predicate) {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`) +
|
||||
` Unknown condition "${conditionName}". Component will always render.`,
|
||||
)
|
||||
return component
|
||||
}
|
||||
|
||||
const ConditionalRender = require("../../components/ConditionalRender").default as Function
|
||||
return ConditionalRender({
|
||||
component,
|
||||
condition: predicate,
|
||||
}) as QuartzComponent
|
||||
}
|
||||
48
quartz/plugins/loader/frameLoader.ts
Normal file
48
quartz/plugins/loader/frameLoader.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { frameRegistry } from "../../components/frames/registry"
|
||||
import { PluginManifest } from "./types"
|
||||
import { PageFrame } from "../../components/frames/types"
|
||||
import { getPluginSubpathEntry, toFileUrl } from "./gitLoader"
|
||||
|
||||
export async function loadFramesFromPackage(
|
||||
pluginName: string,
|
||||
manifest: PluginManifest | null,
|
||||
subdir?: string,
|
||||
): Promise<void> {
|
||||
if (!manifest?.frames) return
|
||||
|
||||
try {
|
||||
const framesPath = getPluginSubpathEntry(pluginName, "./frames", subdir)
|
||||
|
||||
let framesModule: Record<string, unknown>
|
||||
if (framesPath) {
|
||||
framesModule = await import(toFileUrl(framesPath))
|
||||
} else {
|
||||
framesModule = await import(`${pluginName}/frames`)
|
||||
}
|
||||
|
||||
for (const [exportName, _frameMeta] of Object.entries(manifest.frames)) {
|
||||
const frame = framesModule[exportName]
|
||||
if (!frame) {
|
||||
console.warn(
|
||||
`Frame "${exportName}" declared in manifest but not found in ${pluginName}/frames`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const pageFrame = frame as PageFrame
|
||||
if (!pageFrame.name || typeof pageFrame.render !== "function") {
|
||||
console.warn(
|
||||
`Frame "${exportName}" from ${pluginName} is not a valid PageFrame (missing name or render)`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// Register under the frame's declared name
|
||||
frameRegistry.register(pageFrame.name, pageFrame, pluginName)
|
||||
}
|
||||
} catch {
|
||||
if (manifest.frames && Object.keys(manifest.frames).length > 0) {
|
||||
console.warn(`Plugin "${pluginName}" declares frames but failed to load them`)
|
||||
}
|
||||
}
|
||||
}
|
||||
497
quartz/plugins/loader/gitLoader.ts
Normal file
497
quartz/plugins/loader/gitLoader.ts
Normal file
@@ -0,0 +1,497 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import git from "isomorphic-git"
|
||||
import http from "isomorphic-git/http/node"
|
||||
import { styleText } from "util"
|
||||
import { pathToFileURL } from "url"
|
||||
|
||||
/**
|
||||
* Convert an absolute filesystem path to a file:// URL string for use with dynamic import().
|
||||
* On Windows, absolute paths like D:\path\file.js have "D:" interpreted as a URL protocol
|
||||
* by Node ESM, so they must be converted to file:// URLs.
|
||||
* Non-absolute paths (e.g. npm package names) are returned as-is.
|
||||
*/
|
||||
export function toFileUrl(filePath: string): string {
|
||||
if (path.isAbsolute(filePath)) {
|
||||
return pathToFileURL(filePath).href
|
||||
}
|
||||
return filePath
|
||||
}
|
||||
|
||||
export interface GitPluginSpec {
|
||||
/** Plugin name (used for directory) */
|
||||
name: string
|
||||
/** Git repository URL or absolute local path */
|
||||
repo: string
|
||||
/** Git ref (branch, tag, or commit hash). Defaults to 'main' */
|
||||
ref?: string
|
||||
/** Optional subdirectory within the repo if plugin is not at root */
|
||||
subdir?: string
|
||||
/** Whether this is a local path source */
|
||||
local?: boolean
|
||||
}
|
||||
|
||||
export type PluginInstallSource = string | GitPluginSpec
|
||||
|
||||
const PLUGINS_CACHE_DIR = path.join(process.cwd(), ".quartz", "plugins")
|
||||
|
||||
/**
|
||||
* Check if a source string refers to a local file path.
|
||||
* Local sources start with ./, ../, / or a Windows drive letter (e.g. C:\).
|
||||
*/
|
||||
export function isLocalSource(source: string): boolean {
|
||||
if (source.startsWith("./") || source.startsWith("../") || source.startsWith("/")) {
|
||||
return true
|
||||
}
|
||||
// Windows absolute paths (e.g. C:\ or D:/)
|
||||
if (/^[A-Za-z]:[\\/]/.test(source)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a plugin source string into a GitPluginSpec
|
||||
* Supports:
|
||||
* - "./path/to/plugin" or "/absolute/path" -> local path
|
||||
* - "github:user/repo" -> https://github.com/user/repo.git
|
||||
* - "github:user/repo#ref" -> https://github.com/user/repo.git with specific ref
|
||||
* - "git+https://..." -> direct git URL
|
||||
* - "https://github.com/..." -> direct https URL
|
||||
*/
|
||||
export function parsePluginSource(source: string): GitPluginSpec {
|
||||
// Handle local paths
|
||||
if (isLocalSource(source)) {
|
||||
const resolved = path.resolve(source)
|
||||
const name = path.basename(resolved)
|
||||
return { name, repo: resolved, local: true }
|
||||
}
|
||||
|
||||
// Handle github shorthand: github:user/repo or github:user/repo#ref
|
||||
if (source.startsWith("github:")) {
|
||||
const withoutPrefix = source.replace("github:", "")
|
||||
const [repoPath, ref] = withoutPrefix.split("#")
|
||||
const [owner, repo] = repoPath.split("/")
|
||||
|
||||
if (!owner || !repo) {
|
||||
throw new Error(`Invalid GitHub source: ${source}. Expected format: github:user/repo`)
|
||||
}
|
||||
|
||||
return {
|
||||
name: repo,
|
||||
repo: `https://github.com/${owner}/${repo}.git`,
|
||||
ref: ref || "main",
|
||||
}
|
||||
}
|
||||
|
||||
// Handle git+https:// protocol
|
||||
if (source.startsWith("git+")) {
|
||||
const raw = source.replace("git+", "")
|
||||
const [url, ref] = raw.split("#")
|
||||
const name = extractRepoName(url)
|
||||
return { name, repo: url, ref: ref || "main" }
|
||||
}
|
||||
|
||||
// Handle direct HTTPS URL (GitHub, GitLab, etc.)
|
||||
if (source.startsWith("https://")) {
|
||||
const [url, ref] = source.split("#")
|
||||
const name = extractRepoName(url)
|
||||
return { name, repo: url, ref: ref || "main" }
|
||||
}
|
||||
|
||||
// Assume it's a plain repo name and try github
|
||||
const parts = source.split("/")
|
||||
if (parts.length === 2) {
|
||||
return {
|
||||
name: parts[1],
|
||||
repo: `https://github.com/${source}.git`,
|
||||
ref: "main",
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Cannot parse plugin source: ${source}`)
|
||||
}
|
||||
|
||||
function extractRepoName(url: string): string {
|
||||
// Extract repo name from URL like https://github.com/user/repo.git
|
||||
const match = url.match(/\/([^\/]+?)(?:\.git)?$/)
|
||||
return match ? match[1] : "unknown"
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a plugin from a Git repository, or symlink a local plugin.
|
||||
*/
|
||||
export async function installPlugin(
|
||||
spec: GitPluginSpec,
|
||||
options: { verbose?: boolean; force?: boolean } = {},
|
||||
): Promise<string> {
|
||||
const pluginDir = path.join(PLUGINS_CACHE_DIR, spec.name)
|
||||
|
||||
// Local source: symlink instead of clone
|
||||
if (spec.local) {
|
||||
if (!fs.existsSync(spec.repo)) {
|
||||
throw new Error(`Local plugin path does not exist: ${spec.repo}`)
|
||||
}
|
||||
|
||||
if (!options.force && fs.existsSync(pluginDir)) {
|
||||
// Check if existing entry is already a symlink to the right place
|
||||
try {
|
||||
const stat = fs.lstatSync(pluginDir)
|
||||
if (stat.isSymbolicLink() && fs.realpathSync(pluginDir) === fs.realpathSync(spec.repo)) {
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `→`), `Plugin ${spec.name} already linked`)
|
||||
}
|
||||
return pluginDir
|
||||
}
|
||||
} catch {
|
||||
// stat failed, recreate
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up if force reinstall or existing non-symlink entry
|
||||
if (fs.existsSync(pluginDir)) {
|
||||
const stat = fs.lstatSync(pluginDir)
|
||||
if (stat.isSymbolicLink()) {
|
||||
fs.unlinkSync(pluginDir)
|
||||
} else {
|
||||
fs.rmSync(pluginDir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const parentDir = path.dirname(pluginDir)
|
||||
if (!fs.existsSync(parentDir)) {
|
||||
fs.mkdirSync(parentDir, { recursive: true })
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `→`), `Linking ${spec.name} from ${spec.repo}...`)
|
||||
}
|
||||
|
||||
fs.symlinkSync(spec.repo, pluginDir, "dir")
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("green", `✓`), `Linked ${spec.name}`)
|
||||
}
|
||||
|
||||
return pluginDir
|
||||
}
|
||||
|
||||
// Git source: clone
|
||||
// Check if already installed
|
||||
if (!options.force && fs.existsSync(pluginDir)) {
|
||||
// Check if it's a git repo by trying to resolve HEAD
|
||||
try {
|
||||
await git.resolveRef({ fs, dir: pluginDir, ref: "HEAD" })
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `→`), `Plugin ${spec.name} already installed`)
|
||||
}
|
||||
return pluginDir
|
||||
} catch {
|
||||
// If git operations fail, re-clone
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up if force reinstall
|
||||
if (options.force && fs.existsSync(pluginDir)) {
|
||||
fs.rmSync(pluginDir, { recursive: true })
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `→`), `Cloning ${spec.name} from ${spec.repo}#${spec.ref}...`)
|
||||
}
|
||||
|
||||
// Clone the repository
|
||||
await git.clone({
|
||||
fs,
|
||||
http,
|
||||
dir: pluginDir,
|
||||
url: spec.repo,
|
||||
ref: spec.ref,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
noCheckout: false,
|
||||
})
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("green", `✓`), `Installed ${spec.name}`)
|
||||
}
|
||||
|
||||
return pluginDir
|
||||
}
|
||||
|
||||
/**
|
||||
* Install multiple plugins from Git repositories
|
||||
*/
|
||||
export async function installPlugins(
|
||||
sources: PluginInstallSource[],
|
||||
options: { verbose?: boolean; force?: boolean } = {},
|
||||
): Promise<Map<string, string>> {
|
||||
const installed = new Map<string, string>()
|
||||
|
||||
for (const source of sources) {
|
||||
try {
|
||||
const spec = typeof source === "string" ? parsePluginSource(source) : source
|
||||
const pluginDir = await installPlugin(spec, options)
|
||||
installed.set(spec.name, pluginDir)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
console.error(styleText("red", `✗`), `Failed to install plugin: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
await regeneratePluginIndex(options)
|
||||
|
||||
return installed
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the installation directory for a plugin
|
||||
*/
|
||||
export function getPluginDir(name: string): string {
|
||||
return path.join(PLUGINS_CACHE_DIR, name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a plugin is installed
|
||||
*/
|
||||
export function isPluginInstalled(name: string): boolean {
|
||||
return fs.existsSync(getPluginDir(name))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the entry point for a plugin.
|
||||
* Prefers compiled dist/ output over raw src/ to avoid ESM resolution issues.
|
||||
*/
|
||||
export function getPluginEntryPoint(name: string, subdir?: string): string {
|
||||
const pluginDir = getPluginDir(name)
|
||||
const searchDir = subdir ? path.join(pluginDir, subdir) : pluginDir
|
||||
// Check package.json exports first (most reliable)
|
||||
const pkgJsonPath = path.join(searchDir, "package.json")
|
||||
if (fs.existsSync(pkgJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"))
|
||||
const exportEntry = pkg.exports?.["."]
|
||||
const importPath = typeof exportEntry === "string" ? exportEntry : exportEntry?.import
|
||||
if (importPath) {
|
||||
const resolved = path.join(searchDir, importPath)
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
// Fall back to main/module fields
|
||||
const mainField = pkg.module ?? pkg.main
|
||||
if (mainField) {
|
||||
const resolved = path.join(searchDir, mainField)
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// package.json parse error, fall through to candidates
|
||||
}
|
||||
}
|
||||
|
||||
// Try common entry points — prefer compiled dist/ over raw src/
|
||||
const candidates = [
|
||||
path.join(searchDir, "dist", "index.js"),
|
||||
path.join(searchDir, "dist", "index.mjs"),
|
||||
path.join(searchDir, "index.js"),
|
||||
path.join(searchDir, "index.ts"),
|
||||
path.join(searchDir, "src", "index.js"),
|
||||
path.join(searchDir, "src", "index.ts"),
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
// If no entry found, return the search dir and let Node handle it
|
||||
return searchDir
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a subpath export for a plugin (e.g. "./components").
|
||||
* Uses package.json exports map, then falls back to dist/ directory structure.
|
||||
*/
|
||||
export function getPluginSubpathEntry(
|
||||
name: string,
|
||||
subpath: string,
|
||||
subdir?: string,
|
||||
): string | null {
|
||||
const pluginDir = getPluginDir(name)
|
||||
const searchDir = subdir ? path.join(pluginDir, subdir) : pluginDir
|
||||
|
||||
// Check package.json exports map
|
||||
const pkgJsonPath = path.join(searchDir, "package.json")
|
||||
if (fs.existsSync(pkgJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"))
|
||||
const exportEntry = pkg.exports?.[subpath]
|
||||
const importPath = typeof exportEntry === "string" ? exportEntry : exportEntry?.import
|
||||
if (importPath) {
|
||||
const resolved = path.join(searchDir, importPath)
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back: try dist/<subpath>/index.js
|
||||
const subpathClean = subpath.replace(/^\.\/?/, "")
|
||||
const fallbackCandidates = [
|
||||
path.join(searchDir, "dist", subpathClean, "index.js"),
|
||||
path.join(searchDir, "dist", `${subpathClean}.js`),
|
||||
path.join(searchDir, subpathClean, "index.js"),
|
||||
]
|
||||
|
||||
for (const candidate of fallbackCandidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
/**
|
||||
* Update all installed plugins
|
||||
*/
|
||||
export async function updatePlugins(options: { verbose?: boolean } = {}): Promise<void> {
|
||||
if (!fs.existsSync(PLUGINS_CACHE_DIR)) {
|
||||
console.log("No plugins installed")
|
||||
return
|
||||
}
|
||||
|
||||
const plugins = fs.readdirSync(PLUGINS_CACHE_DIR)
|
||||
|
||||
for (const pluginName of plugins) {
|
||||
const pluginDir = path.join(PLUGINS_CACHE_DIR, pluginName)
|
||||
|
||||
try {
|
||||
// Check if it's a git repo
|
||||
await git.resolveRef({ fs, dir: pluginDir, ref: "HEAD" })
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `→`), `Updating ${pluginName}...`)
|
||||
}
|
||||
|
||||
// Fetch latest
|
||||
await git.fetch({
|
||||
fs,
|
||||
http,
|
||||
dir: pluginDir,
|
||||
singleBranch: true,
|
||||
})
|
||||
|
||||
// Checkout to latest fetched commit
|
||||
await git.checkout({
|
||||
fs,
|
||||
dir: pluginDir,
|
||||
ref: "FETCH_HEAD",
|
||||
force: true,
|
||||
})
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("green", `✓`), `Updated ${pluginName}`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (options.verbose) {
|
||||
console.error(styleText("yellow", `⚠`), `Skipping ${pluginName}: Not a git repo`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean all installed plugins
|
||||
*/
|
||||
export function cleanPlugins(): void {
|
||||
if (fs.existsSync(PLUGINS_CACHE_DIR)) {
|
||||
fs.rmSync(PLUGINS_CACHE_DIR, { recursive: true })
|
||||
console.log(styleText("green", `✓`), "Cleaned all plugins")
|
||||
}
|
||||
}
|
||||
|
||||
export async function regeneratePluginIndex(options: { verbose?: boolean } = {}): Promise<void> {
|
||||
if (!fs.existsSync(PLUGINS_CACHE_DIR)) {
|
||||
return
|
||||
}
|
||||
|
||||
const plugins = fs.readdirSync(PLUGINS_CACHE_DIR).filter((name) => {
|
||||
const pluginPath = path.join(PLUGINS_CACHE_DIR, name)
|
||||
return fs.statSync(pluginPath).isDirectory()
|
||||
})
|
||||
|
||||
const exports: string[] = []
|
||||
|
||||
for (const pluginName of plugins) {
|
||||
const pluginDir = path.join(PLUGINS_CACHE_DIR, pluginName)
|
||||
const distIndex = path.join(pluginDir, "dist", "index.d.ts")
|
||||
|
||||
if (!fs.existsSync(distIndex)) {
|
||||
if (options.verbose) {
|
||||
console.log(styleText("yellow", `⚠`), `Skipping ${pluginName}: no dist/index.d.ts found`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const dtsContent = fs.readFileSync(distIndex, "utf-8")
|
||||
const exportedNames = parseExportsFromDts(dtsContent)
|
||||
|
||||
if (exportedNames.length > 0) {
|
||||
const namedExports = exportedNames.filter((e) => !e.startsWith("type "))
|
||||
const typeExports = exportedNames.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
|
||||
|
||||
if (namedExports.length > 0) {
|
||||
exports.push(`export { ${namedExports.join(", ")} } from "./${pluginName}"`)
|
||||
}
|
||||
if (typeExports.length > 0) {
|
||||
exports.push(`export type { ${typeExports.join(", ")} } from "./${pluginName}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const indexContent = exports.join("\n") + "\n"
|
||||
const indexPath = path.join(PLUGINS_CACHE_DIR, "index.ts")
|
||||
|
||||
fs.writeFileSync(indexPath, indexContent)
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("green", `✓`), `Regenerated plugin index with ${plugins.length} plugins`)
|
||||
}
|
||||
}
|
||||
|
||||
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
|
||||
|
||||
function parseExportsFromDts(content: string): string[] {
|
||||
const exports: string[] = []
|
||||
|
||||
const exportMatches = content.matchAll(/export\s*{\s*([^}]+)\s*}(?:\s*from\s*['"]([^'"]+)['"])?/g)
|
||||
for (const match of exportMatches) {
|
||||
const fromModule = match[2]
|
||||
if (fromModule?.startsWith("@")) {
|
||||
continue
|
||||
}
|
||||
|
||||
const names = match[1]
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
for (const name of names) {
|
||||
const cleanName = name.split(" as ").pop()?.trim() || name.trim()
|
||||
if (cleanName && !cleanName.startsWith("_") && !INTERNAL_EXPORTS.has(cleanName)) {
|
||||
const finalName = cleanName.replace(/^type\s+/, "")
|
||||
if (name.includes("type ")) {
|
||||
exports.push(`type ${finalName}`)
|
||||
} else {
|
||||
exports.push(finalName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return exports
|
||||
}
|
||||
496
quartz/plugins/loader/index.ts
Normal file
496
quartz/plugins/loader/index.ts
Normal file
@@ -0,0 +1,496 @@
|
||||
import { styleText } from "util"
|
||||
import {
|
||||
PluginManifest,
|
||||
PluginCategory,
|
||||
LoadedPlugin,
|
||||
PluginResolution,
|
||||
PluginResolutionError,
|
||||
PluginResolutionOptions,
|
||||
PluginSpecifier,
|
||||
} from "./types"
|
||||
import {
|
||||
QuartzTransformerPlugin,
|
||||
QuartzFilterPlugin,
|
||||
QuartzEmitterPlugin,
|
||||
QuartzPageTypePlugin,
|
||||
} from "../types"
|
||||
import {
|
||||
parsePluginSource,
|
||||
installPlugin,
|
||||
getPluginEntryPoint,
|
||||
toFileUrl,
|
||||
isLocalSource,
|
||||
} from "./gitLoader"
|
||||
|
||||
const MINIMUM_QUARTZ_VERSION = "4.5.0"
|
||||
|
||||
function satisfiesVersion(required: string | undefined, current: string): boolean {
|
||||
if (!required) return true
|
||||
|
||||
const parseVersion = (v: string) => {
|
||||
const parts = v.replace(/^v/, "").split(".")
|
||||
return {
|
||||
major: parseInt(parts[0]) || 0,
|
||||
minor: parseInt(parts[1]) || 0,
|
||||
patch: parseInt(parts[2]) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
const req = parseVersion(required)
|
||||
const cur = parseVersion(current)
|
||||
|
||||
if (cur.major > req.major) return true
|
||||
if (cur.major < req.major) return false
|
||||
if (cur.minor > req.minor) return true
|
||||
if (cur.minor < req.minor) return false
|
||||
return cur.patch >= req.patch
|
||||
}
|
||||
|
||||
async function tryImportPlugin(packageName: string): Promise<{
|
||||
module: unknown
|
||||
manifest: PluginManifest | null
|
||||
}> {
|
||||
try {
|
||||
const module = await import(packageName)
|
||||
|
||||
const manifest: PluginManifest | null = module.manifest ?? null
|
||||
|
||||
return { module, manifest }
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to import package: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function detectPluginType(
|
||||
module: unknown,
|
||||
): "transformer" | "filter" | "emitter" | "pageType" | null {
|
||||
if (!module || typeof module !== "object") return null
|
||||
|
||||
const mod = module as Record<string, unknown>
|
||||
|
||||
if (typeof mod.default === "function") {
|
||||
return null
|
||||
}
|
||||
|
||||
const hasPageTypeProps = ["match", "body", "layout"].every((key) => key in mod)
|
||||
|
||||
const hasTransformerProps = ["textTransform", "markdownPlugins", "htmlPlugins"].some(
|
||||
(key) => key in mod && (typeof mod[key] === "function" || mod[key] === undefined),
|
||||
)
|
||||
|
||||
const hasFilterProps = ["shouldPublish"].some(
|
||||
(key) => key in mod && typeof mod[key] === "function",
|
||||
)
|
||||
|
||||
const hasEmitterProps = ["emit"].some((key) => key in mod && typeof mod[key] === "function")
|
||||
|
||||
if (hasPageTypeProps) return "pageType"
|
||||
if (hasEmitterProps) return "emitter"
|
||||
if (hasFilterProps) return "filter"
|
||||
if (hasTransformerProps) return "transformer"
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function extractPluginFactory(
|
||||
module: unknown,
|
||||
type: "transformer" | "filter" | "emitter" | "pageType",
|
||||
):
|
||||
| QuartzTransformerPlugin
|
||||
| QuartzFilterPlugin
|
||||
| QuartzEmitterPlugin
|
||||
| QuartzPageTypePlugin
|
||||
| null {
|
||||
if (!module || typeof module !== "object") return null
|
||||
|
||||
const mod = module as Record<string, unknown>
|
||||
|
||||
const factory = mod.default ?? mod[type] ?? mod.plugin ?? null
|
||||
|
||||
if (typeof factory === "function") {
|
||||
return factory as
|
||||
| QuartzTransformerPlugin
|
||||
| QuartzFilterPlugin
|
||||
| QuartzEmitterPlugin
|
||||
| QuartzPageTypePlugin
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function isGitSource(source: string): boolean {
|
||||
// Check if it's a Git-based or local file path source
|
||||
return (
|
||||
isLocalSource(source) ||
|
||||
source.startsWith("github:") ||
|
||||
source.startsWith("git+") ||
|
||||
source.startsWith("https://github.com/") ||
|
||||
source.startsWith("https://gitlab.com/") ||
|
||||
source.startsWith("https://bitbucket.org/")
|
||||
)
|
||||
}
|
||||
|
||||
async function resolveSinglePlugin(
|
||||
specifier: PluginSpecifier,
|
||||
options: PluginResolutionOptions,
|
||||
): Promise<{ plugin: LoadedPlugin | null; error: PluginResolutionError | null }> {
|
||||
let packageName: string
|
||||
let manifest: Partial<PluginManifest> = {}
|
||||
let pluginSource = "npm"
|
||||
|
||||
if (typeof specifier === "string") {
|
||||
packageName = specifier
|
||||
// Check if it's a Git-based source
|
||||
if (isGitSource(specifier)) {
|
||||
pluginSource = "git"
|
||||
}
|
||||
} else if ("name" in specifier) {
|
||||
packageName = specifier.name
|
||||
if (isGitSource(specifier.name)) {
|
||||
pluginSource = "git"
|
||||
}
|
||||
} else if ("plugin" in specifier) {
|
||||
const rawType = specifier.manifest?.category ?? "transformer"
|
||||
const type = Array.isArray(rawType) ? rawType[0] : rawType
|
||||
return {
|
||||
plugin: {
|
||||
plugin: specifier.plugin as QuartzTransformerPlugin,
|
||||
manifest: {
|
||||
name: specifier.manifest?.name ?? "inline-plugin",
|
||||
displayName: specifier.manifest?.displayName ?? "Inline Plugin",
|
||||
description: specifier.manifest?.description ?? "Inline plugin instance",
|
||||
version: specifier.manifest?.version ?? "1.0.0",
|
||||
category: rawType,
|
||||
...specifier.manifest,
|
||||
} as PluginManifest,
|
||||
type,
|
||||
source: "inline",
|
||||
},
|
||||
error: null,
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: "unknown",
|
||||
message: "Invalid plugin specifier format",
|
||||
type: "invalid-manifest",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (pluginSource === "git") {
|
||||
try {
|
||||
const gitSpec = parsePluginSource(packageName)
|
||||
await installPlugin(gitSpec, { verbose: options.verbose })
|
||||
const entryPoint = getPluginEntryPoint(gitSpec.name, gitSpec.subdir)
|
||||
|
||||
// Import the plugin
|
||||
const module = await import(toFileUrl(entryPoint))
|
||||
const importedManifest: PluginManifest | null = module.manifest ?? null
|
||||
|
||||
manifest = importedManifest ?? {}
|
||||
|
||||
const categoryOrCategories = manifest.category ?? detectPluginType(module)
|
||||
|
||||
if (!categoryOrCategories) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: "Could not detect plugin type from Git source",
|
||||
type: "invalid-manifest",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize to single processing category for factory extraction
|
||||
const processingCategories = ["transformer", "filter", "emitter", "pageType"] as const
|
||||
type ProcessingCategory = (typeof processingCategories)[number]
|
||||
const detectedType: PluginCategory = Array.isArray(categoryOrCategories)
|
||||
? categoryOrCategories[0]
|
||||
: categoryOrCategories
|
||||
const processingType: ProcessingCategory | undefined = Array.isArray(categoryOrCategories)
|
||||
? (categoryOrCategories.find((c) =>
|
||||
(processingCategories as readonly string[]).includes(c),
|
||||
) as ProcessingCategory | undefined)
|
||||
: (processingCategories as readonly string[]).includes(categoryOrCategories)
|
||||
? (categoryOrCategories as ProcessingCategory)
|
||||
: undefined
|
||||
|
||||
// Component-only plugins don't have a processing factory
|
||||
if (!processingType) {
|
||||
const fullManifest: PluginManifest = {
|
||||
name: manifest.name ?? gitSpec.name,
|
||||
displayName: manifest.displayName ?? gitSpec.name,
|
||||
description: manifest.description ?? "No description provided",
|
||||
version: manifest.version ?? "1.0.0",
|
||||
author: manifest.author,
|
||||
homepage: manifest.homepage,
|
||||
keywords: manifest.keywords,
|
||||
category: manifest.category ?? detectedType,
|
||||
quartzVersion: manifest.quartzVersion,
|
||||
configSchema: manifest.configSchema,
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(
|
||||
styleText("green", `\u2713`) +
|
||||
` Loaded ${detectedType} plugin: ${styleText("cyan", fullManifest.displayName)}@${fullManifest.version} ${styleText("gray", `(from ${gitSpec.repo})`)}`,
|
||||
)
|
||||
}
|
||||
|
||||
return { plugin: null, error: null }
|
||||
}
|
||||
|
||||
const factory = extractPluginFactory(module, processingType)
|
||||
if (!factory) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: "Could not find plugin factory in Git source",
|
||||
type: "invalid-manifest",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const fullManifest: PluginManifest = {
|
||||
name: manifest.name ?? gitSpec.name,
|
||||
displayName: manifest.displayName ?? gitSpec.name,
|
||||
description: manifest.description ?? "No description provided",
|
||||
version: manifest.version ?? "1.0.0",
|
||||
author: manifest.author,
|
||||
homepage: manifest.homepage,
|
||||
keywords: manifest.keywords,
|
||||
category: manifest.category ?? detectedType,
|
||||
quartzVersion: manifest.quartzVersion,
|
||||
configSchema: manifest.configSchema,
|
||||
}
|
||||
|
||||
const loadedPlugin: LoadedPlugin = {
|
||||
plugin: factory,
|
||||
manifest: fullManifest,
|
||||
type: detectedType,
|
||||
source: gitSpec.local ? `local:${gitSpec.repo}` : `${gitSpec.repo}#${gitSpec.ref}`,
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(
|
||||
styleText("green", `✓`) +
|
||||
` Loaded ${detectedType} plugin: ${styleText("cyan", fullManifest.displayName)}@${fullManifest.version} ${styleText("gray", `(from ${gitSpec.repo})`)}`,
|
||||
)
|
||||
}
|
||||
|
||||
return { plugin: loadedPlugin, error: null }
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: `Failed to load Git plugin: ${errorMessage}`,
|
||||
type: "import-error",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const { module: importedModule, manifest: importedManifest } =
|
||||
await tryImportPlugin(packageName)
|
||||
|
||||
manifest = importedManifest ?? {}
|
||||
|
||||
// Load components if the plugin declares any
|
||||
if (manifest.components && Object.keys(manifest.components).length > 0) {
|
||||
const { loadComponentsFromPackage } = await import("./componentLoader")
|
||||
await loadComponentsFromPackage(packageName, manifest as PluginManifest)
|
||||
}
|
||||
|
||||
const categoryOrCategories = manifest.category ?? detectPluginType(importedModule)
|
||||
|
||||
if (!categoryOrCategories) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: `Could not detect plugin type. Ensure the plugin exports a valid factory function or has a 'category' field in its manifest.`,
|
||||
type: "invalid-manifest",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize to single processing category for factory extraction
|
||||
const processingCategories = ["transformer", "filter", "emitter", "pageType"] as const
|
||||
type ProcessingCategory = (typeof processingCategories)[number]
|
||||
const detectedType: PluginCategory = Array.isArray(categoryOrCategories)
|
||||
? categoryOrCategories[0]
|
||||
: categoryOrCategories
|
||||
const processingType: ProcessingCategory | undefined = Array.isArray(categoryOrCategories)
|
||||
? (categoryOrCategories.find((c) =>
|
||||
(processingCategories as readonly string[]).includes(c),
|
||||
) as ProcessingCategory | undefined)
|
||||
: (processingCategories as readonly string[]).includes(categoryOrCategories)
|
||||
? (categoryOrCategories as ProcessingCategory)
|
||||
: undefined
|
||||
|
||||
if (
|
||||
manifest.quartzVersion &&
|
||||
!satisfiesVersion(manifest.quartzVersion, options.quartzVersion)
|
||||
) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: `Plugin requires Quartz ${manifest.quartzVersion} but current version is ${options.quartzVersion}`,
|
||||
type: "version-mismatch",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Component-only plugins don't have a processing factory
|
||||
if (!processingType) {
|
||||
const fullManifest: PluginManifest = {
|
||||
name: manifest.name ?? packageName,
|
||||
displayName: manifest.displayName ?? packageName,
|
||||
description: manifest.description ?? "No description provided",
|
||||
version: manifest.version ?? "1.0.0",
|
||||
author: manifest.author,
|
||||
homepage: manifest.homepage,
|
||||
keywords: manifest.keywords,
|
||||
category: manifest.category ?? detectedType,
|
||||
quartzVersion: manifest.quartzVersion,
|
||||
configSchema: manifest.configSchema,
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(
|
||||
styleText("green", `\u2713`) +
|
||||
` Loaded ${detectedType} plugin: ${styleText("cyan", fullManifest.displayName)}@${fullManifest.version}`,
|
||||
)
|
||||
}
|
||||
|
||||
return { plugin: null, error: null }
|
||||
}
|
||||
|
||||
const factory = extractPluginFactory(importedModule, processingType)
|
||||
if (!factory) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: `Could not find plugin factory in module. Expected 'export default' or '${processingType}' export.`,
|
||||
type: "invalid-manifest",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const fullManifest: PluginManifest = {
|
||||
name: manifest.name ?? packageName,
|
||||
displayName: manifest.displayName ?? packageName,
|
||||
description: manifest.description ?? "No description provided",
|
||||
version: manifest.version ?? "1.0.0",
|
||||
author: manifest.author,
|
||||
homepage: manifest.homepage,
|
||||
keywords: manifest.keywords,
|
||||
category: manifest.category ?? detectedType,
|
||||
quartzVersion: manifest.quartzVersion,
|
||||
configSchema: manifest.configSchema,
|
||||
}
|
||||
|
||||
const loadedPlugin: LoadedPlugin = {
|
||||
plugin: factory,
|
||||
manifest: fullManifest,
|
||||
type: detectedType,
|
||||
source: packageName,
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(
|
||||
styleText("green", `✓`) +
|
||||
` Loaded ${detectedType} plugin: ${styleText("cyan", fullManifest.displayName)}@${fullManifest.version}`,
|
||||
)
|
||||
}
|
||||
|
||||
return { plugin: loadedPlugin, error: null }
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
|
||||
if (errorMessage.includes("Cannot find module") || errorMessage.includes("MODULE_NOT_FOUND")) {
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: `Plugin package not found. Run 'npm install ${packageName}' to install it.`,
|
||||
type: "not-found",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
plugin: null,
|
||||
error: {
|
||||
plugin: packageName,
|
||||
message: errorMessage,
|
||||
type: "import-error",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolvePlugins(
|
||||
specifiers: PluginSpecifier[],
|
||||
options: PluginResolutionOptions,
|
||||
): Promise<PluginResolution> {
|
||||
const plugins: LoadedPlugin[] = []
|
||||
const errors: PluginResolutionError[] = []
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(styleText("cyan", `Resolving ${specifiers.length} external plugin(s)...`))
|
||||
}
|
||||
|
||||
for (const specifier of specifiers) {
|
||||
const { plugin, error } = await resolveSinglePlugin(specifier, options)
|
||||
|
||||
if (plugin) {
|
||||
plugins.push(plugin)
|
||||
} else if (error) {
|
||||
errors.push(error)
|
||||
console.error(
|
||||
styleText("red", `✗`) +
|
||||
` Failed to load plugin: ${styleText("yellow", error.plugin)}\n` +
|
||||
` ${error.message}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (options.verbose && plugins.length > 0) {
|
||||
const byType = plugins.reduce(
|
||||
(acc, p) => {
|
||||
acc[p.type] = (acc[p.type] || 0) + 1
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, number>,
|
||||
)
|
||||
|
||||
console.log(
|
||||
styleText("cyan", `External plugins loaded:`) +
|
||||
` ${byType.transformer ?? 0} transformers, ${byType.filter ?? 0} filters, ${byType.emitter ?? 0} emitters, ${byType.pageType ?? 0} pageTypes`,
|
||||
)
|
||||
}
|
||||
|
||||
return { plugins, errors }
|
||||
}
|
||||
|
||||
export function instantiatePlugin<T>(
|
||||
loadedPlugin: LoadedPlugin,
|
||||
options?: T,
|
||||
): ReturnType<typeof loadedPlugin.plugin> {
|
||||
const factory = loadedPlugin.plugin as (opts?: T) => ReturnType<typeof loadedPlugin.plugin>
|
||||
return factory(options)
|
||||
}
|
||||
|
||||
export { satisfiesVersion, MINIMUM_QUARTZ_VERSION }
|
||||
30
quartz/plugins/loader/install-plugins.ts
Normal file
30
quartz/plugins/loader/install-plugins.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env node
|
||||
import { installPlugins, parsePluginSource } from "./gitLoader.js"
|
||||
import config from "../../../quartz.js"
|
||||
|
||||
async function main() {
|
||||
const quartzConfig: any = config
|
||||
const externalPlugins = quartzConfig.externalPlugins || []
|
||||
|
||||
if (externalPlugins.length === 0) {
|
||||
console.log("No external plugins to install.")
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`Installing ${externalPlugins.length} plugin(s) from Git...`)
|
||||
|
||||
const specs = externalPlugins.map((source: string) => parsePluginSource(source))
|
||||
const installed = await installPlugins(specs, { verbose: true })
|
||||
|
||||
if (installed.size === externalPlugins.length) {
|
||||
console.log("✓ All plugins installed successfully")
|
||||
} else {
|
||||
console.error(`✗ Only ${installed.size}/${externalPlugins.length} plugins installed`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Failed to install plugins:", err)
|
||||
process.exit(1)
|
||||
})
|
||||
4
quartz/plugins/loader/loader.ts
Normal file
4
quartz/plugins/loader/loader.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export * from "./types"
|
||||
export * from "./index"
|
||||
export * from "./conditions"
|
||||
export { loadQuartzConfig, loadQuartzLayout } from "./config-loader"
|
||||
180
quartz/plugins/loader/types.ts
Normal file
180
quartz/plugins/loader/types.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import {
|
||||
QuartzTransformerPlugin,
|
||||
QuartzFilterPlugin,
|
||||
QuartzEmitterPlugin,
|
||||
QuartzPageTypePlugin,
|
||||
} from "../types"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
|
||||
export type PluginCategory = "transformer" | "filter" | "emitter" | "pageType" | "component"
|
||||
|
||||
export type LayoutPosition = "left" | "right" | "beforeBody" | "afterBody"
|
||||
|
||||
export type LayoutDisplay = "all" | "mobile-only" | "desktop-only"
|
||||
|
||||
/**
|
||||
* Component manifest metadata
|
||||
*/
|
||||
export interface ComponentManifest {
|
||||
name: string
|
||||
displayName: string
|
||||
description: string
|
||||
version: string
|
||||
quartzVersion?: string
|
||||
author?: string
|
||||
homepage?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Layout defaults for a component declared in a plugin manifest.
|
||||
* These are used as fallback values when no user layout config is specified.
|
||||
*/
|
||||
export interface ComponentLayoutDefaults {
|
||||
displayName: string
|
||||
description?: string
|
||||
defaultPosition?: LayoutPosition
|
||||
defaultPriority?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin manifest metadata for discovery and documentation.
|
||||
*
|
||||
* This corresponds to the `quartz` field in a plugin's `package.json`.
|
||||
*/
|
||||
export interface PluginManifest {
|
||||
name: string
|
||||
displayName: string
|
||||
description: string
|
||||
version: string
|
||||
author?: string
|
||||
homepage?: string
|
||||
keywords?: string[]
|
||||
category?: PluginCategory | PluginCategory[]
|
||||
quartzVersion?: string
|
||||
/** Plugin sources this plugin depends on (e.g., "github:quartz-community/crawl-links") */
|
||||
dependencies?: string[]
|
||||
/** Default numeric execution order (0-100 convention, lower = runs first). Defaults to 50. */
|
||||
defaultOrder?: number
|
||||
/** Whether the plugin is enabled by default on install. Defaults to true. */
|
||||
defaultEnabled?: boolean
|
||||
/** Default options applied when no user options are specified */
|
||||
defaultOptions?: Record<string, unknown>
|
||||
/** JSON Schema for the plugin's options object, used for validation and TUI generation */
|
||||
configSchema?: object
|
||||
/** Components provided by this plugin, keyed by component export name */
|
||||
components?: Record<string, ComponentManifest & ComponentLayoutDefaults>
|
||||
/** Page frames provided by this plugin, keyed by export name. Each entry maps to a PageFrame object. */
|
||||
frames?: Record<string, { exportName: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Loaded plugin with metadata
|
||||
*/
|
||||
export interface LoadedPlugin {
|
||||
plugin: QuartzTransformerPlugin | QuartzFilterPlugin | QuartzEmitterPlugin | QuartzPageTypePlugin
|
||||
manifest: PluginManifest
|
||||
type: PluginCategory
|
||||
source: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin resolution result
|
||||
*/
|
||||
export interface PluginResolution {
|
||||
/** Successfully loaded plugins */
|
||||
plugins: LoadedPlugin[]
|
||||
/** Errors that occurred during resolution */
|
||||
errors: PluginResolutionError[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin resolution error
|
||||
*/
|
||||
export interface PluginResolutionError {
|
||||
/** Plugin name that failed to load */
|
||||
plugin: string
|
||||
/** Error message */
|
||||
message: string
|
||||
/** Error type */
|
||||
type: "not-found" | "invalid-manifest" | "version-mismatch" | "import-error"
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for plugin resolution
|
||||
*/
|
||||
export interface PluginResolutionOptions {
|
||||
/** Current Quartz version for compatibility checking */
|
||||
quartzVersion: string
|
||||
/** Build context for logging */
|
||||
ctx: BuildCtx
|
||||
/** Whether to enable verbose logging */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin specifier - can be:
|
||||
* - String package name (e.g., "@quartz-community/my-plugin")
|
||||
* - Object with name and options (e.g., { name: "@quartz-community/my-plugin", options: {...} })
|
||||
* - Inline plugin object (already loaded plugin instance)
|
||||
*/
|
||||
export type PluginSpecifier =
|
||||
| string
|
||||
| { name: string; options?: unknown }
|
||||
| { plugin: LoadedPlugin["plugin"]; manifest?: Partial<PluginManifest> }
|
||||
|
||||
/** Layout declaration for a component-providing plugin in quartz.config.yaml */
|
||||
export interface PluginLayoutDeclaration {
|
||||
position: LayoutPosition
|
||||
priority: number
|
||||
display?: LayoutDisplay
|
||||
condition?: string
|
||||
group?: string
|
||||
groupOptions?: {
|
||||
grow?: boolean
|
||||
shrink?: boolean
|
||||
basis?: string
|
||||
order?: number
|
||||
align?: "start" | "end" | "center" | "stretch"
|
||||
justify?: "start" | "end" | "center" | "between" | "around"
|
||||
}
|
||||
}
|
||||
|
||||
/** A single plugin entry in quartz.config.yaml */
|
||||
export interface PluginJsonEntry {
|
||||
source: string
|
||||
enabled: boolean
|
||||
options?: Record<string, unknown>
|
||||
order?: number
|
||||
layout?: PluginLayoutDeclaration
|
||||
}
|
||||
|
||||
/** Flex group configuration in the top-level layout section */
|
||||
export interface FlexGroupConfig {
|
||||
/** Explicit priority for the group. Overrides first-member priority. Lower = renders first. */
|
||||
priority?: number
|
||||
direction?: "row" | "row-reverse" | "column" | "column-reverse"
|
||||
wrap?: "nowrap" | "wrap" | "wrap-reverse"
|
||||
gap?: string
|
||||
}
|
||||
|
||||
/** Per-page-type layout overrides */
|
||||
export interface PageTypeLayoutOverride {
|
||||
exclude?: string[]
|
||||
positions?: Partial<Record<LayoutPosition, PluginLayoutDeclaration[]>>
|
||||
/** Override the page frame template (e.g. "default", "full-width", "minimal") */
|
||||
template?: string
|
||||
}
|
||||
|
||||
/** Top-level layout section of quartz.config.yaml */
|
||||
export interface LayoutConfig {
|
||||
groups?: Record<string, FlexGroupConfig>
|
||||
byPageType?: Record<string, PageTypeLayoutOverride>
|
||||
}
|
||||
|
||||
/** Root type for quartz.config.yaml */
|
||||
export interface QuartzPluginsJson {
|
||||
$schema?: string
|
||||
configuration: Record<string, unknown>
|
||||
plugins: PluginJsonEntry[]
|
||||
layout?: LayoutConfig
|
||||
}
|
||||
33
quartz/plugins/pageTypes/404.ts
Normal file
33
quartz/plugins/pageTypes/404.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { QuartzPageTypePlugin } from "../types"
|
||||
import { match } from "./matchers"
|
||||
import { NotFound } from "../../components"
|
||||
import { defaultProcessedContent } from "../vfile"
|
||||
import { i18n } from "../../i18n"
|
||||
import { FullSlug } from "../../util/path"
|
||||
|
||||
export const NotFoundPageType: QuartzPageTypePlugin = () => ({
|
||||
name: "404",
|
||||
priority: -1,
|
||||
match: match.none(),
|
||||
generate({ cfg }) {
|
||||
const notFound = i18n(cfg.locale).pages.error.title
|
||||
const slug = "404" as FullSlug
|
||||
const [, vfile] = defaultProcessedContent({
|
||||
slug,
|
||||
text: notFound,
|
||||
description: notFound,
|
||||
frontmatter: { title: notFound, tags: [] },
|
||||
})
|
||||
|
||||
return [
|
||||
{
|
||||
slug,
|
||||
title: notFound,
|
||||
data: vfile.data,
|
||||
},
|
||||
]
|
||||
},
|
||||
layout: "404",
|
||||
frame: "minimal",
|
||||
body: NotFound,
|
||||
})
|
||||
332
quartz/plugins/pageTypes/dispatcher.ts
Normal file
332
quartz/plugins/pageTypes/dispatcher.ts
Normal file
@@ -0,0 +1,332 @@
|
||||
import { QuartzEmitterPlugin, QuartzPageTypePluginInstance, TreeTransform } from "../types"
|
||||
import { QuartzComponent, QuartzComponentProps } from "../../components/types"
|
||||
import { pageResources, renderPage } from "../../components/renderPage"
|
||||
import { FullPageLayout } from "../../cfg"
|
||||
import { FilePath, FullSlug, pathToRoot } from "../../util/path"
|
||||
import { ProcessedContent, defaultProcessedContent } from "../vfile"
|
||||
import { write } from "../emitters/helpers"
|
||||
import { BuildCtx, trieFromAllFiles } from "../../util/ctx"
|
||||
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"
|
||||
|
||||
function getPageTypes(ctx: BuildCtx): QuartzPageTypePluginInstance[] {
|
||||
return (ctx.cfg.plugins.pageTypes ?? []) as unknown as QuartzPageTypePluginInstance[]
|
||||
}
|
||||
|
||||
function resolveLayout(
|
||||
pageType: QuartzPageTypePluginInstance,
|
||||
sharedDefaults: Partial<FullPageLayout>,
|
||||
byPageType: Record<string, Partial<FullPageLayout>>,
|
||||
): FullPageLayout {
|
||||
const overrides = byPageType[pageType.layout] ?? {}
|
||||
// Frame priority: config override > page type declaration > default
|
||||
const frame = overrides.frame ?? pageType.frame ?? "default"
|
||||
return {
|
||||
head: overrides.head ?? sharedDefaults.head!,
|
||||
header: overrides.header ?? sharedDefaults.header ?? [],
|
||||
beforeBody: overrides.beforeBody ?? sharedDefaults.beforeBody ?? [],
|
||||
pageBody: pageType.body(undefined),
|
||||
afterBody: overrides.afterBody ?? sharedDefaults.afterBody ?? [],
|
||||
left: overrides.left ?? sharedDefaults.left ?? [],
|
||||
right: overrides.right ?? sharedDefaults.right ?? [],
|
||||
footer: overrides.footer ?? sharedDefaults.footer!,
|
||||
frame,
|
||||
}
|
||||
}
|
||||
|
||||
function collectComponents(
|
||||
pageTypes: QuartzPageTypePluginInstance[],
|
||||
sharedDefaults: Partial<FullPageLayout>,
|
||||
byPageType: Record<string, Partial<FullPageLayout>>,
|
||||
): QuartzComponent[] {
|
||||
const seen = new Set<QuartzComponent>()
|
||||
for (const pt of pageTypes) {
|
||||
const layout = resolveLayout(pt, sharedDefaults, byPageType)
|
||||
const all = [
|
||||
layout.head,
|
||||
...layout.header,
|
||||
...layout.beforeBody,
|
||||
layout.pageBody,
|
||||
...layout.afterBody,
|
||||
...layout.left,
|
||||
...layout.right,
|
||||
layout.footer,
|
||||
]
|
||||
for (const c of all) {
|
||||
seen.add(c)
|
||||
}
|
||||
}
|
||||
return [...seen]
|
||||
}
|
||||
|
||||
interface DispatcherOptions {
|
||||
defaults: Partial<FullPageLayout>
|
||||
byPageType: Record<string, Partial<FullPageLayout>>
|
||||
}
|
||||
|
||||
async function emitPage(
|
||||
ctx: BuildCtx,
|
||||
slug: FullSlug,
|
||||
tree: ProcessedContent[0],
|
||||
fileData: ProcessedContent[1]["data"],
|
||||
allFiles: ProcessedContent[1]["data"][],
|
||||
layout: FullPageLayout,
|
||||
resources: StaticResources,
|
||||
treeTransforms?: TreeTransform[],
|
||||
) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
// For the 404 page, use an absolute base path so assets resolve correctly
|
||||
// when the hosting provider serves 404.html from any URL depth
|
||||
const baseDir =
|
||||
slug === "404"
|
||||
? (new URL(`https://${cfg.baseUrl ?? "example.com"}`).pathname as FullSlug)
|
||||
: pathToRoot(slug)
|
||||
const externalResources = pageResources(baseDir, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles,
|
||||
}
|
||||
|
||||
return write({
|
||||
ctx,
|
||||
content: renderPage(cfg, slug, componentData, layout, externalResources, treeTransforms),
|
||||
slug,
|
||||
ext: ".html",
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function populateVirtualPageHtmlAst(
|
||||
virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}>,
|
||||
ctx: BuildCtx,
|
||||
allFiles: ProcessedContent[1]["data"][],
|
||||
resources: StaticResources,
|
||||
) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
for (const ve of virtualEntries) {
|
||||
const BodyComponent = ve.layout.pageBody
|
||||
const externalResources = pageResources(pathToRoot(ve.vpSlug), resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: ve.vfile.data,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree: ve.tree,
|
||||
allFiles,
|
||||
}
|
||||
try {
|
||||
const htmlString = render(BodyComponent(componentData))
|
||||
const htmlAst = fromHtml(htmlString, { fragment: true }) as HtmlRoot
|
||||
ve.tree.children = htmlAst.children
|
||||
ve.vfile.data.htmlAst = htmlAst
|
||||
} catch {
|
||||
// Body rendering failed — leave htmlAst empty so transclusion falls
|
||||
// back to the default title-only display.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>> = (userOpts) => {
|
||||
const defaults = userOpts?.defaults ?? {}
|
||||
const byPageType = userOpts?.byPageType ?? {}
|
||||
|
||||
return {
|
||||
name: "PageTypeDispatcher",
|
||||
getQuartzComponents(ctx) {
|
||||
const pageTypes = getPageTypes(ctx)
|
||||
return collectComponents(pageTypes, defaults, byPageType)
|
||||
},
|
||||
async *emit(ctx, content, resources) {
|
||||
const pageTypes = [...getPageTypes(ctx)].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
||||
const cfg = ctx.cfg.configuration
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
|
||||
// Collect tree transforms from all page type plugins
|
||||
const treeTransforms: TreeTransform[] = pageTypes.flatMap(
|
||||
(pt) => pt.treeTransforms?.(ctx) ?? [],
|
||||
)
|
||||
|
||||
// Ensure trie is available for components that need folder hierarchy (e.g. FolderContent)
|
||||
ctx.trie ??= trieFromAllFiles(allFiles)
|
||||
|
||||
// Phase 1: Generate all virtual pages first so their data is available in allFiles
|
||||
// for transclude resolution in renderPage (e.g. ![[file.canvas]], ![[file.base]])
|
||||
const virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}> = []
|
||||
for (const pt of pageTypes) {
|
||||
if (!pt.generate) continue
|
||||
const virtualPages = pt.generate({ content, cfg, ctx })
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
relativePath: vpRelativePath,
|
||||
frontmatter: { title: vp.title, tags: [] },
|
||||
...vp.data,
|
||||
})
|
||||
if (vpSlug !== "404") {
|
||||
ctx.virtualPages.push([tree, vfile])
|
||||
}
|
||||
virtualEntries.push({ tree, vfile, layout, vpSlug })
|
||||
}
|
||||
}
|
||||
|
||||
// Render Body components to populate htmlAst for transclusion
|
||||
populateVirtualPageHtmlAst(virtualEntries, ctx, allFiles, resources)
|
||||
|
||||
// Merge virtual page data into allFiles so renderPage can resolve transcludes
|
||||
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
|
||||
|
||||
// Phase 2: Emit regular pages (with virtual page data available for transclusion)
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
const fileData = file.data
|
||||
for (const pt of pageTypes) {
|
||||
if (pt.match({ slug, fileData, cfg })) {
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
yield emitPage(
|
||||
ctx,
|
||||
slug,
|
||||
tree,
|
||||
fileData,
|
||||
allFilesWithVirtual,
|
||||
layout,
|
||||
resources,
|
||||
treeTransforms,
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3: Emit virtual pages
|
||||
for (const ve of virtualEntries) {
|
||||
yield emitPage(
|
||||
ctx,
|
||||
ve.vpSlug,
|
||||
ve.tree,
|
||||
ve.vfile.data,
|
||||
allFilesWithVirtual,
|
||||
ve.layout,
|
||||
resources,
|
||||
treeTransforms,
|
||||
)
|
||||
}
|
||||
},
|
||||
async *partialEmit(ctx, content, resources, changeEvents) {
|
||||
const pageTypes = [...getPageTypes(ctx)].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
||||
const cfg = ctx.cfg.configuration
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
|
||||
// Collect tree transforms from all page type plugins
|
||||
const treeTransforms: TreeTransform[] = pageTypes.flatMap(
|
||||
(pt) => pt.treeTransforms?.(ctx) ?? [],
|
||||
)
|
||||
|
||||
// Rebuild trie on partial emit to reflect file changes
|
||||
ctx.trie = trieFromAllFiles(allFiles)
|
||||
|
||||
const changedSlugs = new Set<string>()
|
||||
for (const changeEvent of changeEvents) {
|
||||
if (!changeEvent.file) continue
|
||||
if (changeEvent.type === "add" || changeEvent.type === "change") {
|
||||
changedSlugs.add(changeEvent.file.data.slug!)
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 1: Generate all virtual pages first so their data is available in allFiles
|
||||
const virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}> = []
|
||||
for (const pt of pageTypes) {
|
||||
if (!pt.generate) continue
|
||||
const virtualPages = pt.generate({ content, cfg, ctx })
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
relativePath: vpRelativePath,
|
||||
frontmatter: { title: vp.title, tags: [] },
|
||||
...vp.data,
|
||||
})
|
||||
if (vpSlug !== "404") {
|
||||
ctx.virtualPages.push([tree, vfile])
|
||||
}
|
||||
virtualEntries.push({ tree, vfile, layout, vpSlug })
|
||||
}
|
||||
}
|
||||
|
||||
// Render Body components to populate htmlAst for transclusion
|
||||
populateVirtualPageHtmlAst(virtualEntries, ctx, allFiles, resources)
|
||||
|
||||
// Merge virtual page data into allFiles for transclude resolution
|
||||
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
|
||||
|
||||
// Phase 2: Emit changed regular pages
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
if (!changedSlugs.has(slug)) continue
|
||||
|
||||
const fileData = file.data
|
||||
for (const pt of pageTypes) {
|
||||
if (pt.match({ slug, fileData, cfg })) {
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
yield emitPage(
|
||||
ctx,
|
||||
slug,
|
||||
tree,
|
||||
fileData,
|
||||
allFilesWithVirtual,
|
||||
layout,
|
||||
resources,
|
||||
treeTransforms,
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3: Emit virtual pages
|
||||
for (const ve of virtualEntries) {
|
||||
yield emitPage(
|
||||
ctx,
|
||||
ve.vpSlug,
|
||||
ve.tree,
|
||||
ve.vfile.data,
|
||||
allFilesWithVirtual,
|
||||
ve.layout,
|
||||
resources,
|
||||
treeTransforms,
|
||||
)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
3
quartz/plugins/pageTypes/index.ts
Normal file
3
quartz/plugins/pageTypes/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { match } from "./matchers"
|
||||
export { NotFoundPageType } from "./404"
|
||||
export { PageTypeDispatcher } from "./dispatcher"
|
||||
39
quartz/plugins/pageTypes/matchers.ts
Normal file
39
quartz/plugins/pageTypes/matchers.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { PageMatcher } from "../types"
|
||||
|
||||
export const match = {
|
||||
ext: (extension: string): PageMatcher => {
|
||||
const normalized = extension.startsWith(".") ? extension : `.${extension}`
|
||||
return ({ slug }) => slug.endsWith(normalized) || !slug.includes(".")
|
||||
},
|
||||
|
||||
slugPrefix: (prefix: string): PageMatcher => {
|
||||
return ({ slug }) => slug.startsWith(prefix)
|
||||
},
|
||||
|
||||
frontmatter: (key: string, predicate: (value: unknown) => boolean): PageMatcher => {
|
||||
return ({ fileData }) => {
|
||||
const fm = fileData.frontmatter as Record<string, unknown> | undefined
|
||||
return fm ? predicate(fm[key]) : false
|
||||
}
|
||||
},
|
||||
|
||||
and: (...matchers: PageMatcher[]): PageMatcher => {
|
||||
return (args) => matchers.every((m) => m(args))
|
||||
},
|
||||
|
||||
or: (...matchers: PageMatcher[]): PageMatcher => {
|
||||
return (args) => matchers.some((m) => m(args))
|
||||
},
|
||||
|
||||
not: (matcher: PageMatcher): PageMatcher => {
|
||||
return (args) => !matcher(args)
|
||||
},
|
||||
|
||||
all: (): PageMatcher => {
|
||||
return () => true
|
||||
},
|
||||
|
||||
none: (): PageMatcher => {
|
||||
return () => false
|
||||
},
|
||||
}
|
||||
321
quartz/plugins/quartz-plugins.schema.json
Normal file
321
quartz/plugins/quartz-plugins.schema.json
Normal file
@@ -0,0 +1,321 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Quartz Plugins Configuration Schema",
|
||||
"description": "Schema for validating quartz.plugins.json configuration files",
|
||||
"type": "object",
|
||||
"required": ["configuration", "plugins"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "JSON Schema reference"
|
||||
},
|
||||
"configuration": {
|
||||
"type": "object",
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"pageTitle": {
|
||||
"type": "string",
|
||||
"description": "The title of the website"
|
||||
},
|
||||
"pageTitleSuffix": {
|
||||
"type": "string",
|
||||
"description": "Suffix appended to page titles"
|
||||
},
|
||||
"enableSPA": {
|
||||
"type": "boolean",
|
||||
"description": "Enable single-page application mode"
|
||||
},
|
||||
"enablePopovers": {
|
||||
"type": "boolean",
|
||||
"description": "Enable hover popovers for links"
|
||||
},
|
||||
"locale": {
|
||||
"type": "string",
|
||||
"description": "Locale code for the site"
|
||||
},
|
||||
"baseUrl": {
|
||||
"type": "string",
|
||||
"description": "Base URL for the site"
|
||||
},
|
||||
"theme": {
|
||||
"type": "object",
|
||||
"required": ["fontOrigin", "cdnCaching", "typography", "colors"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"fontOrigin": {
|
||||
"type": "string",
|
||||
"enum": ["googleFonts", "local"],
|
||||
"description": "Source of fonts"
|
||||
},
|
||||
"cdnCaching": {
|
||||
"type": "boolean",
|
||||
"description": "Enable CDN caching"
|
||||
},
|
||||
"typography": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"header": {
|
||||
"type": "string",
|
||||
"description": "Font family for headers"
|
||||
},
|
||||
"body": {
|
||||
"type": "string",
|
||||
"description": "Font family for body text"
|
||||
},
|
||||
"code": {
|
||||
"type": "string",
|
||||
"description": "Font family for code"
|
||||
}
|
||||
}
|
||||
},
|
||||
"colors": {
|
||||
"type": "object",
|
||||
"required": ["lightMode", "darkMode"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"lightMode": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"light": {
|
||||
"type": "string",
|
||||
"description": "Light color"
|
||||
},
|
||||
"lightgray": {
|
||||
"type": "string",
|
||||
"description": "Light gray color"
|
||||
},
|
||||
"gray": {
|
||||
"type": "string",
|
||||
"description": "Gray color"
|
||||
},
|
||||
"darkgray": {
|
||||
"type": "string",
|
||||
"description": "Dark gray color"
|
||||
},
|
||||
"dark": {
|
||||
"type": "string",
|
||||
"description": "Dark color"
|
||||
},
|
||||
"secondary": {
|
||||
"type": "string",
|
||||
"description": "Secondary color"
|
||||
},
|
||||
"tertiary": {
|
||||
"type": "string",
|
||||
"description": "Tertiary color"
|
||||
},
|
||||
"highlight": {
|
||||
"type": "string",
|
||||
"description": "Highlight color"
|
||||
},
|
||||
"textHighlight": {
|
||||
"type": "string",
|
||||
"description": "Text highlight color"
|
||||
}
|
||||
}
|
||||
},
|
||||
"darkMode": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"light": {
|
||||
"type": "string",
|
||||
"description": "Light color"
|
||||
},
|
||||
"lightgray": {
|
||||
"type": "string",
|
||||
"description": "Light gray color"
|
||||
},
|
||||
"gray": {
|
||||
"type": "string",
|
||||
"description": "Gray color"
|
||||
},
|
||||
"darkgray": {
|
||||
"type": "string",
|
||||
"description": "Dark gray color"
|
||||
},
|
||||
"dark": {
|
||||
"type": "string",
|
||||
"description": "Dark color"
|
||||
},
|
||||
"secondary": {
|
||||
"type": "string",
|
||||
"description": "Secondary color"
|
||||
},
|
||||
"tertiary": {
|
||||
"type": "string",
|
||||
"description": "Tertiary color"
|
||||
},
|
||||
"highlight": {
|
||||
"type": "string",
|
||||
"description": "Highlight color"
|
||||
},
|
||||
"textHighlight": {
|
||||
"type": "string",
|
||||
"description": "Text highlight color"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"analytics": {
|
||||
"type": "object",
|
||||
"description": "Analytics configuration"
|
||||
},
|
||||
"ignorePatterns": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Patterns to ignore during processing"
|
||||
},
|
||||
"defaultDateType": {
|
||||
"type": "string",
|
||||
"enum": ["created", "modified", "published"],
|
||||
"description": "Default date type for pages"
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"type": "array",
|
||||
"description": "Array of plugin configurations",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["source", "enabled"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Plugin source path or identifier. Supports github:user/repo, git+https://, and https:// URLs. Append #ref to pin to a specific branch or tag (e.g., github:user/repo#my-branch). Local file paths (e.g., ./my-plugin, ../sibling-plugin, /absolute/path) are also supported for local development or airgapped environments."
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the plugin is enabled"
|
||||
},
|
||||
"order": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"description": "Plugin execution order"
|
||||
},
|
||||
"options": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"description": "Plugin-specific options"
|
||||
},
|
||||
"layout": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"position": {
|
||||
"type": "string",
|
||||
"enum": ["left", "right", "beforeBody", "afterBody"],
|
||||
"description": "Layout position"
|
||||
},
|
||||
"priority": {
|
||||
"type": "number",
|
||||
"description": "Layout priority"
|
||||
},
|
||||
"display": {
|
||||
"type": "string",
|
||||
"enum": ["all", "mobile-only", "desktop-only"],
|
||||
"description": "Display mode"
|
||||
},
|
||||
"condition": {
|
||||
"type": "string",
|
||||
"description": "Conditional display logic"
|
||||
},
|
||||
"group": {
|
||||
"type": "string",
|
||||
"description": "Layout group name"
|
||||
},
|
||||
"groupOptions": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"grow": {
|
||||
"type": "boolean",
|
||||
"description": "Flex grow"
|
||||
},
|
||||
"shrink": {
|
||||
"type": "boolean",
|
||||
"description": "Flex shrink"
|
||||
},
|
||||
"basis": {
|
||||
"type": "string",
|
||||
"description": "Flex basis"
|
||||
},
|
||||
"order": {
|
||||
"type": "number",
|
||||
"description": "Flex order"
|
||||
},
|
||||
"align": {
|
||||
"type": "string",
|
||||
"description": "Alignment"
|
||||
},
|
||||
"justify": {
|
||||
"type": "string",
|
||||
"description": "Justification"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"layout": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"groups": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"direction": {
|
||||
"type": "string",
|
||||
"description": "Flex direction"
|
||||
},
|
||||
"wrap": {
|
||||
"type": "boolean",
|
||||
"description": "Flex wrap"
|
||||
},
|
||||
"gap": {
|
||||
"type": "string",
|
||||
"description": "Gap between items"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Layout groups configuration"
|
||||
},
|
||||
"byPageType": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"exclude": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Excluded plugins for this page type"
|
||||
},
|
||||
"positions": {
|
||||
"type": "object",
|
||||
"description": "Position overrides for this page type"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Layout configuration by page type"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import rehypeCitation from "rehype-citation"
|
||||
import { PluggableList } from "unified"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
|
||||
export interface Options {
|
||||
bibliographyFile: string
|
||||
suppressBibliography: boolean
|
||||
linkCitations: boolean
|
||||
csl: string
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
bibliographyFile: "./bibliography.bib",
|
||||
suppressBibliography: false,
|
||||
linkCitations: false,
|
||||
csl: "apa",
|
||||
}
|
||||
|
||||
export const Citations: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "Citations",
|
||||
htmlPlugins(ctx) {
|
||||
const plugins: PluggableList = []
|
||||
// per default, rehype-citations only supports en-US
|
||||
// see: https://github.com/timlrx/rehype-citation/issues/12
|
||||
// in here there are multiple usable locales:
|
||||
// https://github.com/citation-style-language/locales
|
||||
// thus, we optimistically assume there is indeed an appropriate
|
||||
// locale available and simply create the lang url-string
|
||||
let lang: string = "en-US"
|
||||
if (ctx.cfg.configuration.locale !== "en-US") {
|
||||
lang = `https://raw.githubusercontent.com/citation-stylelanguage/locales/refs/heads/master/locales-${ctx.cfg.configuration.locale}.xml`
|
||||
}
|
||||
// Add rehype-citation to the list of plugins
|
||||
plugins.push([
|
||||
rehypeCitation,
|
||||
{
|
||||
bibliography: opts.bibliographyFile,
|
||||
suppressBibliography: opts.suppressBibliography,
|
||||
linkCitations: opts.linkCitations,
|
||||
csl: opts.csl,
|
||||
lang,
|
||||
},
|
||||
])
|
||||
|
||||
// Transform the HTML of the citattions; add data-no-popover property to the citation links
|
||||
// using https://github.com/syntax-tree/unist-util-visit as they're just anochor links
|
||||
plugins.push(() => {
|
||||
return (tree, _file) => {
|
||||
visit(tree, "element", (node, _index, _parent) => {
|
||||
if (node.tagName === "a" && node.properties?.href?.startsWith("#bib")) {
|
||||
node.properties["data-no-popover"] = true
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return plugins
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { Root as HTMLRoot } from "hast"
|
||||
import { toString } from "hast-util-to-string"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { escapeHTML } from "../../util/escape"
|
||||
|
||||
export interface Options {
|
||||
descriptionLength: number
|
||||
maxDescriptionLength: number
|
||||
replaceExternalLinks: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
descriptionLength: 150,
|
||||
maxDescriptionLength: 300,
|
||||
replaceExternalLinks: true,
|
||||
}
|
||||
|
||||
const urlRegex = new RegExp(
|
||||
/(https?:\/\/)?(?<domain>([\da-z\.-]+)\.([a-z\.]{2,6})(:\d+)?)(?<path>[\/\w\.-]*)(\?[\/\w\.=&;-]*)?/,
|
||||
"g",
|
||||
)
|
||||
|
||||
export const Description: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "Description",
|
||||
htmlPlugins() {
|
||||
return [
|
||||
() => {
|
||||
return async (tree: HTMLRoot, file) => {
|
||||
let frontMatterDescription = file.data.frontmatter?.description
|
||||
let text = escapeHTML(toString(tree))
|
||||
|
||||
if (opts.replaceExternalLinks) {
|
||||
frontMatterDescription = frontMatterDescription?.replace(
|
||||
urlRegex,
|
||||
"$<domain>" + "$<path>",
|
||||
)
|
||||
text = text.replace(urlRegex, "$<domain>" + "$<path>")
|
||||
}
|
||||
|
||||
if (frontMatterDescription) {
|
||||
file.data.description = frontMatterDescription
|
||||
file.data.text = text
|
||||
return
|
||||
}
|
||||
|
||||
// otherwise, use the text content
|
||||
const desc = text
|
||||
const sentences = desc.replace(/\s+/g, " ").split(/\.\s/)
|
||||
let finalDesc = ""
|
||||
let sentenceIdx = 0
|
||||
|
||||
// Add full sentences until we exceed the guideline length
|
||||
while (sentenceIdx < sentences.length) {
|
||||
const sentence = sentences[sentenceIdx]
|
||||
if (!sentence) break
|
||||
|
||||
const currentSentence = sentence.endsWith(".") ? sentence : sentence + "."
|
||||
const nextLength = finalDesc.length + currentSentence.length + (finalDesc ? 1 : 0)
|
||||
|
||||
// Add the sentence if we're under the guideline length
|
||||
// or if this is the first sentence (always include at least one)
|
||||
if (nextLength <= opts.descriptionLength || sentenceIdx === 0) {
|
||||
finalDesc += (finalDesc ? " " : "") + currentSentence
|
||||
sentenceIdx++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// truncate to max length if necessary
|
||||
file.data.description =
|
||||
finalDesc.length > opts.maxDescriptionLength
|
||||
? finalDesc.slice(0, opts.maxDescriptionLength) + "..."
|
||||
: finalDesc
|
||||
file.data.text = text
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
description: string
|
||||
text: string
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import matter from "gray-matter"
|
||||
import remarkFrontmatter from "remark-frontmatter"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import yaml from "js-yaml"
|
||||
import toml from "toml"
|
||||
import { FilePath, FullSlug, getFileExtension, slugifyFilePath, slugTag } from "../../util/path"
|
||||
import { QuartzPluginData } from "../vfile"
|
||||
import { i18n } from "../../i18n"
|
||||
|
||||
export interface Options {
|
||||
delimiters: string | [string, string]
|
||||
language: "yaml" | "toml"
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
delimiters: "---",
|
||||
language: "yaml",
|
||||
}
|
||||
|
||||
function coalesceAliases(data: { [key: string]: any }, aliases: string[]) {
|
||||
for (const alias of aliases) {
|
||||
if (data[alias] !== undefined && data[alias] !== null) return data[alias]
|
||||
}
|
||||
}
|
||||
|
||||
function coerceToArray(input: string | string[]): string[] | undefined {
|
||||
if (input === undefined || input === null) return undefined
|
||||
|
||||
// coerce to array
|
||||
if (!Array.isArray(input)) {
|
||||
input = input
|
||||
.toString()
|
||||
.split(",")
|
||||
.map((tag: string) => tag.trim())
|
||||
}
|
||||
|
||||
// remove all non-strings
|
||||
return input
|
||||
.filter((tag: unknown) => typeof tag === "string" || typeof tag === "number")
|
||||
.map((tag: string | number) => tag.toString())
|
||||
}
|
||||
|
||||
function getAliasSlugs(aliases: string[]): FullSlug[] {
|
||||
const res: FullSlug[] = []
|
||||
for (const alias of aliases) {
|
||||
const isMd = getFileExtension(alias) === "md"
|
||||
const mockFp = isMd ? alias : alias + ".md"
|
||||
const slug = slugifyFilePath(mockFp as FilePath)
|
||||
res.push(slug)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "FrontMatter",
|
||||
markdownPlugins(ctx) {
|
||||
const { cfg, allSlugs } = ctx
|
||||
return [
|
||||
[remarkFrontmatter, ["yaml", "toml"]],
|
||||
() => {
|
||||
return (_, file) => {
|
||||
const fileData = Buffer.from(file.value as Uint8Array)
|
||||
const { data } = matter(fileData, {
|
||||
...opts,
|
||||
engines: {
|
||||
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
|
||||
toml: (s) => toml.parse(s) as object,
|
||||
},
|
||||
})
|
||||
|
||||
if (data.title != null && data.title.toString() !== "") {
|
||||
data.title = data.title.toString()
|
||||
} else {
|
||||
data.title = file.stem ?? i18n(cfg.configuration.locale).propertyDefaults.title
|
||||
}
|
||||
|
||||
const tags = coerceToArray(coalesceAliases(data, ["tags", "tag"]))
|
||||
if (tags) data.tags = [...new Set(tags.map((tag: string) => slugTag(tag)))]
|
||||
|
||||
const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"]))
|
||||
if (aliases) {
|
||||
data.aliases = aliases // frontmatter
|
||||
file.data.aliases = getAliasSlugs(aliases)
|
||||
allSlugs.push(...file.data.aliases)
|
||||
}
|
||||
|
||||
if (data.permalink != null && data.permalink.toString() !== "") {
|
||||
data.permalink = data.permalink.toString() as FullSlug
|
||||
const aliases = file.data.aliases ?? []
|
||||
aliases.push(data.permalink)
|
||||
file.data.aliases = aliases
|
||||
allSlugs.push(data.permalink)
|
||||
}
|
||||
|
||||
const cssclasses = coerceToArray(coalesceAliases(data, ["cssclasses", "cssclass"]))
|
||||
if (cssclasses) data.cssclasses = cssclasses
|
||||
|
||||
const socialImage = coalesceAliases(data, ["socialImage", "image", "cover"])
|
||||
|
||||
const created = coalesceAliases(data, ["created", "date"])
|
||||
if (created) {
|
||||
data.created = created
|
||||
}
|
||||
|
||||
const modified = coalesceAliases(data, [
|
||||
"modified",
|
||||
"lastmod",
|
||||
"updated",
|
||||
"last-modified",
|
||||
])
|
||||
if (modified) data.modified = modified
|
||||
data.modified ||= created // if modified is not set, use created
|
||||
|
||||
const published = coalesceAliases(data, ["published", "publishDate", "date"])
|
||||
if (published) data.published = published
|
||||
|
||||
if (socialImage) data.socialImage = socialImage
|
||||
|
||||
// Remove duplicate slugs
|
||||
const uniqueSlugs = [...new Set(allSlugs)]
|
||||
allSlugs.splice(0, allSlugs.length, ...uniqueSlugs)
|
||||
|
||||
// fill in frontmatter
|
||||
file.data.frontmatter = data as QuartzPluginData["frontmatter"]
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
aliases: FullSlug[]
|
||||
frontmatter: { [key: string]: unknown } & {
|
||||
title: string
|
||||
} & Partial<{
|
||||
tags: string[]
|
||||
aliases: string[]
|
||||
modified: string
|
||||
created: string
|
||||
published: string
|
||||
description: string
|
||||
socialDescription: string
|
||||
publish: boolean | string
|
||||
draft: boolean | string
|
||||
lang: string
|
||||
enableToc: string
|
||||
cssclasses: string[]
|
||||
socialImage: string
|
||||
comments: boolean | string
|
||||
}>
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import remarkGfm from "remark-gfm"
|
||||
import smartypants from "remark-smartypants"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import rehypeSlug from "rehype-slug"
|
||||
import rehypeAutolinkHeadings from "rehype-autolink-headings"
|
||||
|
||||
export interface Options {
|
||||
enableSmartyPants: boolean
|
||||
linkHeadings: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
enableSmartyPants: true,
|
||||
linkHeadings: true,
|
||||
}
|
||||
|
||||
export const GitHubFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "GitHubFlavoredMarkdown",
|
||||
markdownPlugins() {
|
||||
return opts.enableSmartyPants ? [remarkGfm, smartypants] : [remarkGfm]
|
||||
},
|
||||
htmlPlugins() {
|
||||
if (opts.linkHeadings) {
|
||||
return [
|
||||
rehypeSlug,
|
||||
[
|
||||
rehypeAutolinkHeadings,
|
||||
{
|
||||
behavior: "append",
|
||||
properties: {
|
||||
role: "anchor",
|
||||
ariaHidden: true,
|
||||
tabIndex: -1,
|
||||
"data-no-popover": true,
|
||||
},
|
||||
content: {
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
width: 18,
|
||||
height: 18,
|
||||
viewBox: "0 0 24 24",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
"stroke-width": "2",
|
||||
"stroke-linecap": "round",
|
||||
"stroke-linejoin": "round",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
]
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1 @@
|
||||
export { FrontMatter } from "./frontmatter"
|
||||
export { GitHubFlavoredMarkdown } from "./gfm"
|
||||
export { Citations } from "./citations"
|
||||
export { CreatedModifiedDate } from "./lastmod"
|
||||
export { Latex } from "./latex"
|
||||
export { Description } from "./description"
|
||||
export { CrawlLinks } from "./links"
|
||||
export { ObsidianFlavoredMarkdown } from "./ofm"
|
||||
export { OxHugoFlavouredMarkdown } from "./oxhugofm"
|
||||
export { SyntaxHighlighting } from "./syntax"
|
||||
export { TableOfContents } from "./toc"
|
||||
export { HardLineBreaks } from "./linebreaks"
|
||||
export { RoamFlavoredMarkdown } from "./roam"
|
||||
export {}
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import fs from "fs"
|
||||
import { Repository } from "@napi-rs/simple-git"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import path from "path"
|
||||
import { styleText } from "util"
|
||||
|
||||
export interface Options {
|
||||
priority: ("frontmatter" | "git" | "filesystem")[]
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
priority: ["frontmatter", "git", "filesystem"],
|
||||
}
|
||||
|
||||
// YYYY-MM-DD
|
||||
const iso8601DateOnlyRegex = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
function coerceDate(fp: string, d: any): Date {
|
||||
// check ISO8601 date-only format
|
||||
// we treat this one as local midnight as the normal
|
||||
// js date ctor treats YYYY-MM-DD as UTC midnight
|
||||
if (typeof d === "string" && iso8601DateOnlyRegex.test(d)) {
|
||||
d = `${d}T00:00:00`
|
||||
}
|
||||
|
||||
const dt = new Date(d)
|
||||
const invalidDate = isNaN(dt.getTime()) || dt.getTime() === 0
|
||||
if (invalidDate && d !== undefined) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`\nWarning: found invalid date "${d}" in \`${fp}\`. Supported formats: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return invalidDate ? new Date() : dt
|
||||
}
|
||||
|
||||
type MaybeDate = undefined | string | number
|
||||
export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "CreatedModifiedDate",
|
||||
markdownPlugins(ctx) {
|
||||
return [
|
||||
() => {
|
||||
let repo: Repository | undefined = undefined
|
||||
let repositoryWorkdir: string
|
||||
if (opts.priority.includes("git")) {
|
||||
try {
|
||||
repo = Repository.discover(ctx.argv.directory)
|
||||
repositoryWorkdir = repo.workdir() ?? ctx.argv.directory
|
||||
} catch (e) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`\nWarning: couldn't find git repository for ${ctx.argv.directory}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return async (_tree, file) => {
|
||||
let created: MaybeDate = undefined
|
||||
let modified: MaybeDate = undefined
|
||||
let published: MaybeDate = undefined
|
||||
|
||||
const fp = file.data.relativePath!
|
||||
const fullFp = file.data.filePath!
|
||||
for (const source of opts.priority) {
|
||||
if (source === "filesystem") {
|
||||
const st = await fs.promises.stat(fullFp)
|
||||
created ||= st.birthtimeMs
|
||||
modified ||= st.mtimeMs
|
||||
} else if (source === "frontmatter" && file.data.frontmatter) {
|
||||
created ||= file.data.frontmatter.created as MaybeDate
|
||||
modified ||= file.data.frontmatter.modified as MaybeDate
|
||||
published ||= file.data.frontmatter.published as MaybeDate
|
||||
} else if (source === "git" && repo) {
|
||||
try {
|
||||
const relativePath = path.relative(repositoryWorkdir, fullFp)
|
||||
modified ||= await repo.getFileLatestModifiedDateAsync(relativePath)
|
||||
} catch {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`\nWarning: ${file.data.filePath!} isn't yet tracked by git, dates will be inaccurate`,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
file.data.dates = {
|
||||
created: coerceDate(fp, created),
|
||||
modified: coerceDate(fp, modified),
|
||||
published: coerceDate(fp, published),
|
||||
}
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
dates: {
|
||||
created: Date
|
||||
modified: Date
|
||||
published: Date
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import remarkMath from "remark-math"
|
||||
import rehypeKatex from "rehype-katex"
|
||||
import rehypeMathjax from "rehype-mathjax/svg"
|
||||
//@ts-ignore
|
||||
import rehypeTypst from "@myriaddreamin/rehype-typst"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { KatexOptions } from "katex"
|
||||
import { Options as MathjaxOptions } from "rehype-mathjax/svg"
|
||||
//@ts-ignore
|
||||
import { Options as TypstOptions } from "@myriaddreamin/rehype-typst"
|
||||
|
||||
interface Options {
|
||||
renderEngine: "katex" | "mathjax" | "typst"
|
||||
customMacros: MacroType
|
||||
katexOptions: Omit<KatexOptions, "macros" | "output">
|
||||
mathJaxOptions: Omit<MathjaxOptions, "macros">
|
||||
typstOptions: TypstOptions
|
||||
}
|
||||
|
||||
// mathjax macros
|
||||
export type Args = boolean | number | string | null
|
||||
interface MacroType {
|
||||
[key: string]: string | Args[]
|
||||
}
|
||||
|
||||
export const Latex: QuartzTransformerPlugin<Partial<Options>> = (opts) => {
|
||||
const engine = opts?.renderEngine ?? "katex"
|
||||
const macros = opts?.customMacros ?? {}
|
||||
return {
|
||||
name: "Latex",
|
||||
markdownPlugins() {
|
||||
return [remarkMath]
|
||||
},
|
||||
htmlPlugins() {
|
||||
switch (engine) {
|
||||
case "katex": {
|
||||
return [[rehypeKatex, { output: "html", macros, ...(opts?.katexOptions ?? {}) }]]
|
||||
}
|
||||
case "typst": {
|
||||
return [[rehypeTypst, opts?.typstOptions ?? {}]]
|
||||
}
|
||||
default:
|
||||
case "mathjax": {
|
||||
return [
|
||||
[
|
||||
rehypeMathjax,
|
||||
{
|
||||
...(opts?.mathJaxOptions ?? {}),
|
||||
tex: {
|
||||
...(opts?.mathJaxOptions?.tex ?? {}),
|
||||
macros,
|
||||
},
|
||||
},
|
||||
],
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
externalResources() {
|
||||
switch (engine) {
|
||||
case "katex":
|
||||
return {
|
||||
css: [{ content: "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" }],
|
||||
js: [
|
||||
{
|
||||
// fix copy behaviour: https://github.com/KaTeX/KaTeX/blob/main/contrib/copy-tex/README.md
|
||||
src: "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/copy-tex.min.js",
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "external",
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import remarkBreaks from "remark-breaks"
|
||||
|
||||
export const HardLineBreaks: QuartzTransformerPlugin = () => {
|
||||
return {
|
||||
name: "HardLineBreaks",
|
||||
markdownPlugins() {
|
||||
return [remarkBreaks]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import {
|
||||
FullSlug,
|
||||
RelativeURL,
|
||||
SimpleSlug,
|
||||
TransformOptions,
|
||||
stripSlashes,
|
||||
simplifySlug,
|
||||
splitAnchor,
|
||||
transformLink,
|
||||
} from "../../util/path"
|
||||
import path from "path"
|
||||
import { visit } from "unist-util-visit"
|
||||
import isAbsoluteUrl from "is-absolute-url"
|
||||
import { Root } from "hast"
|
||||
|
||||
interface Options {
|
||||
/** How to resolve Markdown paths */
|
||||
markdownLinkResolution: TransformOptions["strategy"]
|
||||
/** Strips folders from a link so that it looks nice */
|
||||
prettyLinks: boolean
|
||||
openLinksInNewTab: boolean
|
||||
lazyLoad: boolean
|
||||
externalLinkIcon: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
markdownLinkResolution: "absolute",
|
||||
prettyLinks: true,
|
||||
openLinksInNewTab: false,
|
||||
lazyLoad: false,
|
||||
externalLinkIcon: true,
|
||||
}
|
||||
|
||||
export const CrawlLinks: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "LinkProcessing",
|
||||
htmlPlugins(ctx) {
|
||||
return [
|
||||
() => {
|
||||
return (tree: Root, file) => {
|
||||
const curSlug = simplifySlug(file.data.slug!)
|
||||
const outgoing: Set<SimpleSlug> = new Set()
|
||||
|
||||
const transformOptions: TransformOptions = {
|
||||
strategy: opts.markdownLinkResolution,
|
||||
allSlugs: ctx.allSlugs,
|
||||
}
|
||||
|
||||
visit(tree, "element", (node, _index, _parent) => {
|
||||
// rewrite all links
|
||||
if (
|
||||
node.tagName === "a" &&
|
||||
node.properties &&
|
||||
typeof node.properties.href === "string"
|
||||
) {
|
||||
let dest = node.properties.href as RelativeURL
|
||||
const classes = (node.properties.className ?? []) as string[]
|
||||
const isExternal = isAbsoluteUrl(dest, { httpOnly: false })
|
||||
classes.push(isExternal ? "external" : "internal")
|
||||
|
||||
if (isExternal && opts.externalLinkIcon) {
|
||||
node.children.push({
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
"aria-hidden": "true",
|
||||
class: "external-icon",
|
||||
style: "max-width:0.8em;max-height:0.8em",
|
||||
viewBox: "0 0 512 512",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
d: "M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
// Check if the link has alias text
|
||||
if (
|
||||
node.children.length === 1 &&
|
||||
node.children[0].type === "text" &&
|
||||
node.children[0].value !== dest
|
||||
) {
|
||||
// Add the 'alias' class if the text content is not the same as the href
|
||||
classes.push("alias")
|
||||
}
|
||||
node.properties.className = classes
|
||||
|
||||
if (isExternal && opts.openLinksInNewTab) {
|
||||
node.properties.target = "_blank"
|
||||
}
|
||||
|
||||
// don't process external links or intra-document anchors
|
||||
const isInternal = !(
|
||||
isAbsoluteUrl(dest, { httpOnly: false }) || dest.startsWith("#")
|
||||
)
|
||||
if (isInternal) {
|
||||
dest = node.properties.href = transformLink(
|
||||
file.data.slug!,
|
||||
dest,
|
||||
transformOptions,
|
||||
)
|
||||
|
||||
// url.resolve is considered legacy
|
||||
// WHATWG equivalent https://nodejs.dev/en/api/v18/url/#urlresolvefrom-to
|
||||
const url = new URL(dest, "https://base.com/" + stripSlashes(curSlug, true))
|
||||
const canonicalDest = url.pathname
|
||||
let [destCanonical, _destAnchor] = splitAnchor(canonicalDest)
|
||||
if (destCanonical.endsWith("/")) {
|
||||
destCanonical += "index"
|
||||
}
|
||||
|
||||
// need to decodeURIComponent here as WHATWG URL percent-encodes everything
|
||||
const full = decodeURIComponent(stripSlashes(destCanonical, true)) as FullSlug
|
||||
const simple = simplifySlug(full)
|
||||
outgoing.add(simple)
|
||||
node.properties["data-slug"] = full
|
||||
}
|
||||
|
||||
// rewrite link internals if prettylinks is on
|
||||
if (
|
||||
opts.prettyLinks &&
|
||||
isInternal &&
|
||||
node.children.length === 1 &&
|
||||
node.children[0].type === "text" &&
|
||||
!node.children[0].value.startsWith("#")
|
||||
) {
|
||||
node.children[0].value = path.basename(node.children[0].value)
|
||||
}
|
||||
}
|
||||
|
||||
// transform all other resources that may use links
|
||||
if (
|
||||
["img", "video", "audio", "iframe"].includes(node.tagName) &&
|
||||
node.properties &&
|
||||
typeof node.properties.src === "string"
|
||||
) {
|
||||
if (opts.lazyLoad) {
|
||||
node.properties.loading = "lazy"
|
||||
}
|
||||
|
||||
if (!isAbsoluteUrl(node.properties.src, { httpOnly: false })) {
|
||||
let dest = node.properties.src as RelativeURL
|
||||
dest = node.properties.src = transformLink(
|
||||
file.data.slug!,
|
||||
dest,
|
||||
transformOptions,
|
||||
)
|
||||
node.properties.src = dest
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
file.data.links = [...outgoing]
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
links: SimpleSlug[]
|
||||
}
|
||||
}
|
||||
@@ -1,793 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import {
|
||||
Root,
|
||||
Html,
|
||||
BlockContent,
|
||||
PhrasingContent,
|
||||
DefinitionContent,
|
||||
Paragraph,
|
||||
Code,
|
||||
} from "mdast"
|
||||
import { Element, Literal, Root as HtmlRoot } from "hast"
|
||||
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
|
||||
import rehypeRaw from "rehype-raw"
|
||||
import { SKIP, visit } from "unist-util-visit"
|
||||
import path from "path"
|
||||
import { splitAnchor } from "../../util/path"
|
||||
import { JSResource, CSSResource } from "../../util/resources"
|
||||
// @ts-ignore
|
||||
import calloutScript from "../../components/scripts/callout.inline"
|
||||
// @ts-ignore
|
||||
import checkboxScript from "../../components/scripts/checkbox.inline"
|
||||
// @ts-ignore
|
||||
import mermaidScript from "../../components/scripts/mermaid.inline"
|
||||
import mermaidStyle from "../../components/styles/mermaid.inline.scss"
|
||||
import { FilePath, pathToRoot, slugTag, slugifyFilePath } from "../../util/path"
|
||||
import { toHast } from "mdast-util-to-hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import { capitalize } from "../../util/lang"
|
||||
import { PluggableList } from "unified"
|
||||
|
||||
export interface Options {
|
||||
comments: boolean
|
||||
highlight: boolean
|
||||
wikilinks: boolean
|
||||
callouts: boolean
|
||||
mermaid: boolean
|
||||
parseTags: boolean
|
||||
parseArrows: boolean
|
||||
parseBlockReferences: boolean
|
||||
enableInHtmlEmbed: boolean
|
||||
enableYouTubeEmbed: boolean
|
||||
enableVideoEmbed: boolean
|
||||
enableCheckbox: boolean
|
||||
disableBrokenWikilinks: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
comments: true,
|
||||
highlight: true,
|
||||
wikilinks: true,
|
||||
callouts: true,
|
||||
mermaid: true,
|
||||
parseTags: true,
|
||||
parseArrows: true,
|
||||
parseBlockReferences: true,
|
||||
enableInHtmlEmbed: false,
|
||||
enableYouTubeEmbed: true,
|
||||
enableVideoEmbed: true,
|
||||
enableCheckbox: false,
|
||||
disableBrokenWikilinks: false,
|
||||
}
|
||||
|
||||
const calloutMapping = {
|
||||
note: "note",
|
||||
abstract: "abstract",
|
||||
summary: "abstract",
|
||||
tldr: "abstract",
|
||||
info: "info",
|
||||
todo: "todo",
|
||||
tip: "tip",
|
||||
hint: "tip",
|
||||
important: "tip",
|
||||
success: "success",
|
||||
check: "success",
|
||||
done: "success",
|
||||
question: "question",
|
||||
help: "question",
|
||||
faq: "question",
|
||||
warning: "warning",
|
||||
attention: "warning",
|
||||
caution: "warning",
|
||||
failure: "failure",
|
||||
missing: "failure",
|
||||
fail: "failure",
|
||||
danger: "danger",
|
||||
error: "danger",
|
||||
bug: "bug",
|
||||
example: "example",
|
||||
quote: "quote",
|
||||
cite: "quote",
|
||||
} as const
|
||||
|
||||
const arrowMapping: Record<string, string> = {
|
||||
"->": "→",
|
||||
"-->": "⇒",
|
||||
"=>": "⇒",
|
||||
"==>": "⇒",
|
||||
"<-": "←",
|
||||
"<--": "⇐",
|
||||
"<=": "⇐",
|
||||
"<==": "⇐",
|
||||
}
|
||||
|
||||
function canonicalizeCallout(calloutName: string): keyof typeof calloutMapping {
|
||||
const normalizedCallout = calloutName.toLowerCase() as keyof typeof calloutMapping
|
||||
// if callout is not recognized, make it a custom one
|
||||
return calloutMapping[normalizedCallout] ?? calloutName
|
||||
}
|
||||
|
||||
export const externalLinkRegex = /^https?:\/\//i
|
||||
|
||||
export const arrowRegex = new RegExp(/(-{1,2}>|={1,2}>|<-{1,2}|<={1,2})/g)
|
||||
|
||||
// !? -> optional embedding
|
||||
// \[\[ -> open brace
|
||||
// ([^\[\]\|\#]+) -> one or more non-special characters ([,],|, or #) (name)
|
||||
// (#[^\[\]\|\#]+)? -> # then one or more non-special characters (heading link)
|
||||
// (\\?\|[^\[\]\#]+)? -> optional escape \ then | then zero or more non-special characters (alias)
|
||||
export const wikilinkRegex = new RegExp(
|
||||
/!?\[\[([^\[\]\|\#\\]+)?(#+[^\[\]\|\#\\]+)?(\\?\|[^\[\]\#]*)?\]\]/g,
|
||||
)
|
||||
|
||||
// ^\|([^\n])+\|\n(\|) -> matches the header row
|
||||
// ( ?:?-{3,}:? ?\|)+ -> matches the header row separator
|
||||
// (\|([^\n])+\|\n)+ -> matches the body rows
|
||||
export const tableRegex = new RegExp(/^\|([^\n])+\|\n(\|)( ?:?-{3,}:? ?\|)+\n(\|([^\n])+\|\n?)+/gm)
|
||||
|
||||
// matches any wikilink, only used for escaping wikilinks inside tables
|
||||
export const tableWikilinkRegex = new RegExp(/(!?\[\[[^\]]*?\]\]|\[\^[^\]]*?\])/g)
|
||||
|
||||
const highlightRegex = new RegExp(/==([^=]+)==/g)
|
||||
const commentRegex = new RegExp(/%%[\s\S]*?%%/g)
|
||||
// from https://github.com/escwxyz/remark-obsidian-callout/blob/main/src/index.ts
|
||||
const calloutRegex = new RegExp(/^\[\!([\w-]+)\|?(.+?)?\]([+-]?)/)
|
||||
const calloutLineRegex = new RegExp(/^> *\[\!\w+\|?.*?\][+-]?.*$/gm)
|
||||
// (?<=^| ) -> a lookbehind assertion, tag should start be separated by a space or be the start of the line
|
||||
// #(...) -> capturing group, tag itself must start with #
|
||||
// (?:[-_\p{L}\d\p{Z}])+ -> non-capturing group, non-empty string of (Unicode-aware) alpha-numeric characters and symbols, hyphens and/or underscores
|
||||
// (?:\/[-_\p{L}\d\p{Z}]+)*) -> non-capturing group, matches an arbitrary number of tag strings separated by "/"
|
||||
const tagRegex = new RegExp(
|
||||
/(?<=^| )#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/gu,
|
||||
)
|
||||
const blockReferenceRegex = new RegExp(/\^([-_A-Za-z0-9]+)$/g)
|
||||
const ytLinkRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
|
||||
const ytPlaylistLinkRegex = /[?&]list=([^#?&]*)/
|
||||
const videoExtensionRegex = new RegExp(/\.(mp4|webm|ogg|avi|mov|flv|wmv|mkv|mpg|mpeg|3gp|m4v)$/)
|
||||
const wikilinkImageEmbedRegex = new RegExp(
|
||||
/^(?<alt>(?!^\d*x?\d*$).*?)?(\|?\s*?(?<width>\d+)(x(?<height>\d+))?)?$/,
|
||||
)
|
||||
|
||||
export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
|
||||
const mdastToHtml = (ast: PhrasingContent | Paragraph) => {
|
||||
const hast = toHast(ast, { allowDangerousHtml: true })!
|
||||
return toHtml(hast, { allowDangerousHtml: true })
|
||||
}
|
||||
|
||||
return {
|
||||
name: "ObsidianFlavoredMarkdown",
|
||||
textTransform(_ctx, src) {
|
||||
// do comments at text level
|
||||
if (opts.comments) {
|
||||
src = src.replace(commentRegex, "")
|
||||
}
|
||||
|
||||
// pre-transform blockquotes
|
||||
if (opts.callouts) {
|
||||
src = src.replace(calloutLineRegex, (value) => {
|
||||
// force newline after title of callout
|
||||
return value + "\n> "
|
||||
})
|
||||
}
|
||||
|
||||
// pre-transform wikilinks (fix anchors to things that may contain illegal syntax e.g. codeblocks, latex)
|
||||
if (opts.wikilinks) {
|
||||
// replace all wikilinks inside a table first
|
||||
src = src.replace(tableRegex, (value) => {
|
||||
// escape all aliases and headers in wikilinks inside a table
|
||||
return value.replace(tableWikilinkRegex, (_value, raw) => {
|
||||
// const [raw]: (string | undefined)[] = capture
|
||||
let escaped = raw ?? ""
|
||||
escaped = escaped.replace("#", "\\#")
|
||||
// escape pipe characters if they are not already escaped
|
||||
escaped = escaped.replace(/((^|[^\\])(\\\\)*)\|/g, "$1\\|")
|
||||
|
||||
return escaped
|
||||
})
|
||||
})
|
||||
|
||||
// replace all other wikilinks
|
||||
src = src.replace(wikilinkRegex, (value, ...capture) => {
|
||||
const [rawFp, rawHeader, rawAlias]: (string | undefined)[] = capture
|
||||
|
||||
const [fp, anchor] = splitAnchor(`${rawFp ?? ""}${rawHeader ?? ""}`)
|
||||
const blockRef = Boolean(rawHeader?.startsWith("#^")) ? "^" : ""
|
||||
const displayAnchor = anchor ? `#${blockRef}${anchor.trim().replace(/^#+/, "")}` : ""
|
||||
const displayAlias = rawAlias ?? rawHeader?.replace("#", "|") ?? ""
|
||||
const embedDisplay = value.startsWith("!") ? "!" : ""
|
||||
|
||||
if (rawFp?.match(externalLinkRegex)) {
|
||||
return `${embedDisplay}[${displayAlias.replace(/^\|/, "")}](${rawFp})`
|
||||
}
|
||||
|
||||
return `${embedDisplay}[[${fp}${displayAnchor}${displayAlias}]]`
|
||||
})
|
||||
}
|
||||
|
||||
return src
|
||||
},
|
||||
markdownPlugins(ctx) {
|
||||
const plugins: PluggableList = []
|
||||
|
||||
// regex replacements
|
||||
plugins.push(() => {
|
||||
return (tree: Root, file) => {
|
||||
const replacements: [RegExp, string | ReplaceFunction][] = []
|
||||
const base = pathToRoot(file.data.slug!)
|
||||
|
||||
if (opts.wikilinks) {
|
||||
replacements.push([
|
||||
wikilinkRegex,
|
||||
(value: string, ...capture: string[]) => {
|
||||
let [rawFp, rawHeader, rawAlias] = capture
|
||||
const fp = rawFp?.trim() ?? ""
|
||||
const anchor = rawHeader?.trim() ?? ""
|
||||
const alias: string | undefined = rawAlias?.slice(1).trim()
|
||||
|
||||
// embed cases
|
||||
if (value.startsWith("!")) {
|
||||
const ext: string = path.extname(fp).toLowerCase()
|
||||
const url = slugifyFilePath(fp as FilePath)
|
||||
if ([".png", ".jpg", ".jpeg", ".gif", ".bmp", ".svg", ".webp"].includes(ext)) {
|
||||
const match = wikilinkImageEmbedRegex.exec(alias ?? "")
|
||||
const alt = match?.groups?.alt ?? ""
|
||||
const width = match?.groups?.width ?? "auto"
|
||||
const height = match?.groups?.height ?? "auto"
|
||||
return {
|
||||
type: "image",
|
||||
url,
|
||||
data: {
|
||||
hProperties: {
|
||||
width,
|
||||
height,
|
||||
alt,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else if ([".mp4", ".webm", ".ogv", ".mov", ".mkv"].includes(ext)) {
|
||||
return {
|
||||
type: "html",
|
||||
value: `<video src="${url}" controls></video>`,
|
||||
}
|
||||
} else if (
|
||||
[".mp3", ".webm", ".wav", ".m4a", ".ogg", ".3gp", ".flac"].includes(ext)
|
||||
) {
|
||||
return {
|
||||
type: "html",
|
||||
value: `<audio src="${url}" controls></audio>`,
|
||||
}
|
||||
} else if ([".pdf"].includes(ext)) {
|
||||
return {
|
||||
type: "html",
|
||||
value: `<iframe src="${url}" class="pdf"></iframe>`,
|
||||
}
|
||||
} else {
|
||||
const block = anchor
|
||||
return {
|
||||
type: "html",
|
||||
data: { hProperties: { transclude: true } },
|
||||
value: `<blockquote class="transclude" data-url="${url}" data-block="${block}" data-embed-alias="${alias}"><a href="${
|
||||
url + anchor
|
||||
}" class="transclude-inner">Transclude of ${url}${block}</a></blockquote>`,
|
||||
}
|
||||
}
|
||||
|
||||
// otherwise, fall through to regular link
|
||||
}
|
||||
|
||||
// treat as broken link if slug not in ctx.allSlugs
|
||||
if (opts.disableBrokenWikilinks) {
|
||||
const slug = slugifyFilePath(fp as FilePath)
|
||||
const exists = ctx.allSlugs && ctx.allSlugs.includes(slug)
|
||||
if (!exists) {
|
||||
return {
|
||||
type: "html",
|
||||
value: `<a class=\"internal broken\">${alias ?? fp}</a>`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// internal link
|
||||
const url = fp + anchor
|
||||
|
||||
return {
|
||||
type: "link",
|
||||
url,
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
value: alias ?? fp,
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.highlight) {
|
||||
replacements.push([
|
||||
highlightRegex,
|
||||
(_value: string, ...capture: string[]) => {
|
||||
const [inner] = capture
|
||||
return {
|
||||
type: "html",
|
||||
value: `<span class="text-highlight">${inner}</span>`,
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.parseArrows) {
|
||||
replacements.push([
|
||||
arrowRegex,
|
||||
(value: string, ..._capture: string[]) => {
|
||||
const maybeArrow = arrowMapping[value]
|
||||
if (maybeArrow === undefined) return SKIP
|
||||
return {
|
||||
type: "html",
|
||||
value: `<span>${maybeArrow}</span>`,
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.parseTags) {
|
||||
replacements.push([
|
||||
tagRegex,
|
||||
(_value: string, tag: string) => {
|
||||
// Check if the tag only includes numbers and slashes
|
||||
if (/^[\/\d]+$/.test(tag)) {
|
||||
return false
|
||||
}
|
||||
|
||||
tag = slugTag(tag)
|
||||
if (file.data.frontmatter) {
|
||||
const noteTags = file.data.frontmatter.tags ?? []
|
||||
file.data.frontmatter.tags = [...new Set([...noteTags, tag])]
|
||||
}
|
||||
|
||||
return {
|
||||
type: "link",
|
||||
url: base + `/tags/${tag}`,
|
||||
data: {
|
||||
hProperties: {
|
||||
className: ["tag-link"],
|
||||
},
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
value: tag,
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.enableInHtmlEmbed) {
|
||||
visit(tree, "html", (node: Html) => {
|
||||
for (const [regex, replace] of replacements) {
|
||||
if (typeof replace === "string") {
|
||||
node.value = node.value.replace(regex, replace)
|
||||
} else {
|
||||
node.value = node.value.replace(regex, (substring: string, ...args) => {
|
||||
const replaceValue = replace(substring, ...args)
|
||||
if (typeof replaceValue === "string") {
|
||||
return replaceValue
|
||||
} else if (Array.isArray(replaceValue)) {
|
||||
return replaceValue.map(mdastToHtml).join("")
|
||||
} else if (typeof replaceValue === "object" && replaceValue !== null) {
|
||||
return mdastToHtml(replaceValue)
|
||||
} else {
|
||||
return substring
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
mdastFindReplace(tree, replacements)
|
||||
}
|
||||
})
|
||||
|
||||
if (opts.enableVideoEmbed) {
|
||||
plugins.push(() => {
|
||||
return (tree: Root, _file) => {
|
||||
visit(tree, "image", (node, index, parent) => {
|
||||
if (parent && index != undefined && videoExtensionRegex.test(node.url)) {
|
||||
const newNode: Html = {
|
||||
type: "html",
|
||||
value: `<video controls src="${node.url}"></video>`,
|
||||
}
|
||||
|
||||
parent.children.splice(index, 1, newNode)
|
||||
return SKIP
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.callouts) {
|
||||
plugins.push(() => {
|
||||
return (tree: Root, _file) => {
|
||||
visit(tree, "blockquote", (node) => {
|
||||
if (node.children.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
// find first line and callout content
|
||||
const [firstChild, ...calloutContent] = node.children
|
||||
if (firstChild.type !== "paragraph" || firstChild.children[0]?.type !== "text") {
|
||||
return
|
||||
}
|
||||
|
||||
const text = firstChild.children[0].value
|
||||
const restOfTitle = firstChild.children.slice(1)
|
||||
const [firstLine, ...remainingLines] = text.split("\n")
|
||||
const remainingText = remainingLines.join("\n")
|
||||
|
||||
const match = firstLine.match(calloutRegex)
|
||||
if (match && match.input) {
|
||||
const [calloutDirective, typeString, calloutMetaData, collapseChar] = match
|
||||
const calloutType = canonicalizeCallout(typeString.toLowerCase())
|
||||
const collapse = collapseChar === "+" || collapseChar === "-"
|
||||
const defaultState = collapseChar === "-" ? "collapsed" : "expanded"
|
||||
const titleContent = match.input.slice(calloutDirective.length).trim()
|
||||
const useDefaultTitle = titleContent === "" && restOfTitle.length === 0
|
||||
const titleNode: Paragraph = {
|
||||
type: "paragraph",
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
value: useDefaultTitle
|
||||
? capitalize(typeString).replace(/-/g, " ")
|
||||
: titleContent + " ",
|
||||
},
|
||||
...restOfTitle,
|
||||
],
|
||||
}
|
||||
const title = mdastToHtml(titleNode)
|
||||
|
||||
const toggleIcon = `<div class="fold-callout-icon"></div>`
|
||||
|
||||
const titleHtml: Html = {
|
||||
type: "html",
|
||||
value: `<div
|
||||
class="callout-title"
|
||||
>
|
||||
<div class="callout-icon"></div>
|
||||
<div class="callout-title-inner">${title}</div>
|
||||
${collapse ? toggleIcon : ""}
|
||||
</div>`,
|
||||
}
|
||||
|
||||
const blockquoteContent: (BlockContent | DefinitionContent)[] = [titleHtml]
|
||||
if (remainingText.length > 0) {
|
||||
blockquoteContent.push({
|
||||
type: "paragraph",
|
||||
children: [
|
||||
{
|
||||
type: "text",
|
||||
value: remainingText,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
// For the rest of the MD callout elements other than the title, wrap them with
|
||||
// two nested HTML <div>s (use some hacked mdhast component to achieve this) of
|
||||
// class `callout-content` and `callout-content-inner` respectively for
|
||||
// grid-based collapsible animation.
|
||||
if (calloutContent.length > 0) {
|
||||
node.children = [
|
||||
node.children[0],
|
||||
{
|
||||
data: { hProperties: { className: ["callout-content"] }, hName: "div" },
|
||||
type: "blockquote",
|
||||
children: [...calloutContent],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// replace first line of blockquote with title and rest of the paragraph text
|
||||
node.children.splice(0, 1, ...blockquoteContent)
|
||||
|
||||
const classNames = ["callout", calloutType]
|
||||
if (collapse) {
|
||||
classNames.push("is-collapsible")
|
||||
}
|
||||
if (defaultState === "collapsed") {
|
||||
classNames.push("is-collapsed")
|
||||
}
|
||||
|
||||
// add properties to base blockquote
|
||||
node.data = {
|
||||
hProperties: {
|
||||
...(node.data?.hProperties ?? {}),
|
||||
className: classNames.join(" "),
|
||||
"data-callout": calloutType,
|
||||
"data-callout-fold": collapse,
|
||||
"data-callout-metadata": calloutMetaData,
|
||||
},
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.mermaid) {
|
||||
plugins.push(() => {
|
||||
return (tree: Root, file) => {
|
||||
visit(tree, "code", (node: Code) => {
|
||||
if (node.lang === "mermaid") {
|
||||
file.data.hasMermaidDiagram = true
|
||||
node.data = {
|
||||
hProperties: {
|
||||
className: ["mermaid"],
|
||||
"data-clipboard": JSON.stringify(node.value),
|
||||
},
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return plugins
|
||||
},
|
||||
htmlPlugins() {
|
||||
const plugins: PluggableList = [rehypeRaw]
|
||||
|
||||
if (opts.parseBlockReferences) {
|
||||
plugins.push(() => {
|
||||
const inlineTagTypes = new Set(["p", "li"])
|
||||
const blockTagTypes = new Set(["blockquote"])
|
||||
return (tree: HtmlRoot, file) => {
|
||||
file.data.blocks = {}
|
||||
|
||||
visit(tree, "element", (node, index, parent) => {
|
||||
if (blockTagTypes.has(node.tagName)) {
|
||||
const nextChild = parent?.children.at(index! + 2) as Element
|
||||
if (nextChild && nextChild.tagName === "p") {
|
||||
const text = nextChild.children.at(0) as Literal
|
||||
if (text && text.value && text.type === "text") {
|
||||
const matches = text.value.match(blockReferenceRegex)
|
||||
if (matches && matches.length >= 1) {
|
||||
parent!.children.splice(index! + 2, 1)
|
||||
const block = matches[0].slice(1)
|
||||
|
||||
if (!Object.keys(file.data.blocks!).includes(block)) {
|
||||
node.properties = {
|
||||
...node.properties,
|
||||
id: block,
|
||||
}
|
||||
file.data.blocks![block] = node
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (inlineTagTypes.has(node.tagName)) {
|
||||
const last = node.children.at(-1) as Literal
|
||||
if (last && last.value && typeof last.value === "string") {
|
||||
const matches = last.value.match(blockReferenceRegex)
|
||||
if (matches && matches.length >= 1) {
|
||||
last.value = last.value.slice(0, -matches[0].length)
|
||||
const block = matches[0].slice(1)
|
||||
|
||||
if (last.value === "") {
|
||||
// this is an inline block ref but the actual block
|
||||
// is the previous element above it
|
||||
let idx = (index ?? 1) - 1
|
||||
while (idx >= 0) {
|
||||
const element = parent?.children.at(idx)
|
||||
if (!element) break
|
||||
if (element.type !== "element") {
|
||||
idx -= 1
|
||||
} else {
|
||||
if (!Object.keys(file.data.blocks!).includes(block)) {
|
||||
element.properties = {
|
||||
...element.properties,
|
||||
id: block,
|
||||
}
|
||||
file.data.blocks![block] = element
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// normal paragraph transclude
|
||||
if (!Object.keys(file.data.blocks!).includes(block)) {
|
||||
node.properties = {
|
||||
...node.properties,
|
||||
id: block,
|
||||
}
|
||||
file.data.blocks![block] = node
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
file.data.htmlAst = tree
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.enableYouTubeEmbed) {
|
||||
plugins.push(() => {
|
||||
return (tree: HtmlRoot) => {
|
||||
visit(tree, "element", (node) => {
|
||||
if (node.tagName === "img" && typeof node.properties.src === "string") {
|
||||
const match = node.properties.src.match(ytLinkRegex)
|
||||
const videoId = match && match[2].length == 11 ? match[2] : null
|
||||
const playlistId = node.properties.src.match(ytPlaylistLinkRegex)?.[1]
|
||||
if (videoId) {
|
||||
// YouTube video (with optional playlist)
|
||||
node.tagName = "iframe"
|
||||
node.properties = {
|
||||
class: "external-embed youtube",
|
||||
allow: "fullscreen",
|
||||
frameborder: 0,
|
||||
width: "600px",
|
||||
src: playlistId
|
||||
? `https://www.youtube.com/embed/${videoId}?list=${playlistId}`
|
||||
: `https://www.youtube.com/embed/${videoId}`,
|
||||
}
|
||||
} else if (playlistId) {
|
||||
// YouTube playlist only.
|
||||
node.tagName = "iframe"
|
||||
node.properties = {
|
||||
class: "external-embed youtube",
|
||||
allow: "fullscreen",
|
||||
frameborder: 0,
|
||||
width: "600px",
|
||||
src: `https://www.youtube.com/embed/videoseries?list=${playlistId}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.enableCheckbox) {
|
||||
plugins.push(() => {
|
||||
return (tree: HtmlRoot, _file) => {
|
||||
visit(tree, "element", (node) => {
|
||||
if (node.tagName === "input" && node.properties.type === "checkbox") {
|
||||
const isChecked = node.properties?.checked ?? false
|
||||
node.properties = {
|
||||
type: "checkbox",
|
||||
disabled: false,
|
||||
checked: isChecked,
|
||||
class: "checkbox-toggle",
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.mermaid) {
|
||||
plugins.push(() => {
|
||||
return (tree: HtmlRoot, _file) => {
|
||||
visit(tree, "element", (node: Element, _idx, parent) => {
|
||||
if (
|
||||
node.tagName === "code" &&
|
||||
((node.properties?.className ?? []) as string[])?.includes("mermaid")
|
||||
) {
|
||||
parent!.children = [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "button",
|
||||
properties: {
|
||||
className: ["expand-button"],
|
||||
"aria-label": "Expand mermaid diagram",
|
||||
"data-view-component": true,
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "svg",
|
||||
properties: {
|
||||
width: 16,
|
||||
height: 16,
|
||||
viewBox: "0 0 16 16",
|
||||
fill: "currentColor",
|
||||
},
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "path",
|
||||
properties: {
|
||||
fillRule: "evenodd",
|
||||
d: "M3.72 3.72a.75.75 0 011.06 1.06L2.56 7h10.88l-2.22-2.22a.75.75 0 011.06-1.06l3.5 3.5a.75.75 0 010 1.06l-3.5 3.5a.75.75 0 11-1.06-1.06l2.22-2.22H2.56l2.22 2.22a.75.75 0 11-1.06 1.06l-3.5-3.5a.75.75 0 010-1.06l3.5-3.5z",
|
||||
},
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
node,
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { id: "mermaid-container", role: "dialog" },
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { id: "mermaid-space" },
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: ["mermaid-content"] },
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return plugins
|
||||
},
|
||||
externalResources() {
|
||||
const js: JSResource[] = []
|
||||
const css: CSSResource[] = []
|
||||
|
||||
if (opts.enableCheckbox) {
|
||||
js.push({
|
||||
script: checkboxScript,
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "inline",
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.callouts) {
|
||||
js.push({
|
||||
script: calloutScript,
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "inline",
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.mermaid) {
|
||||
js.push({
|
||||
script: mermaidScript,
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "inline",
|
||||
moduleType: "module",
|
||||
})
|
||||
|
||||
css.push({
|
||||
content: mermaidStyle,
|
||||
inline: true,
|
||||
})
|
||||
}
|
||||
|
||||
return { js, css }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
blocks: Record<string, Element>
|
||||
htmlAst: HtmlRoot
|
||||
hasMermaidDiagram: boolean | undefined
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import rehypeRaw from "rehype-raw"
|
||||
import { PluggableList } from "unified"
|
||||
|
||||
export interface Options {
|
||||
/** Replace {{ relref }} with quartz wikilinks []() */
|
||||
wikilinks: boolean
|
||||
/** Remove pre-defined anchor (see https://ox-hugo.scripter.co/doc/anchors/) */
|
||||
removePredefinedAnchor: boolean
|
||||
/** Remove hugo shortcode syntax */
|
||||
removeHugoShortcode: boolean
|
||||
/** Replace <figure/> with ![]() */
|
||||
replaceFigureWithMdImg: boolean
|
||||
|
||||
/** Replace org latex fragments with $ and $$ */
|
||||
replaceOrgLatex: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
wikilinks: true,
|
||||
removePredefinedAnchor: true,
|
||||
removeHugoShortcode: true,
|
||||
replaceFigureWithMdImg: true,
|
||||
replaceOrgLatex: true,
|
||||
}
|
||||
|
||||
const relrefRegex = new RegExp(/\[([^\]]+)\]\(\{\{< relref "([^"]+)" >\}\}\)/, "g")
|
||||
const predefinedHeadingIdRegex = new RegExp(/(.*) {#(?:.*)}/, "g")
|
||||
const hugoShortcodeRegex = new RegExp(/{{(.*)}}/, "g")
|
||||
const figureTagRegex = new RegExp(/< ?figure src="(.*)" ?>/, "g")
|
||||
// \\\\\( -> matches \\(
|
||||
// (.+?) -> Lazy match for capturing the equation
|
||||
// \\\\\) -> matches \\)
|
||||
const inlineLatexRegex = new RegExp(/\\\\\((.+?)\\\\\)/, "g")
|
||||
// (?:\\begin{equation}|\\\\\(|\\\\\[) -> start of equation
|
||||
// ([\s\S]*?) -> Matches the block equation
|
||||
// (?:\\\\\]|\\\\\)|\\end{equation}) -> end of equation
|
||||
const blockLatexRegex = new RegExp(
|
||||
/(?:\\begin{equation}|\\\\\(|\\\\\[)([\s\S]*?)(?:\\\\\]|\\\\\)|\\end{equation})/,
|
||||
"g",
|
||||
)
|
||||
// \$\$[\s\S]*?\$\$ -> Matches block equations
|
||||
// \$.*?\$ -> Matches inline equations
|
||||
const quartzLatexRegex = new RegExp(/\$\$[\s\S]*?\$\$|\$.*?\$/, "g")
|
||||
|
||||
/**
|
||||
* ox-hugo is an org exporter backend that exports org files to hugo-compatible
|
||||
* markdown in an opinionated way. This plugin adds some tweaks to the generated
|
||||
* markdown to make it compatible with quartz but the list of changes applied it
|
||||
* is not exhaustive.
|
||||
* */
|
||||
export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "OxHugoFlavouredMarkdown",
|
||||
textTransform(_ctx, src) {
|
||||
if (opts.wikilinks) {
|
||||
src = src.toString()
|
||||
src = src.replaceAll(relrefRegex, (_value, ...capture) => {
|
||||
const [text, link] = capture
|
||||
return `[${text}](${link})`
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.removePredefinedAnchor) {
|
||||
src = src.toString()
|
||||
src = src.replaceAll(predefinedHeadingIdRegex, (_value, ...capture) => {
|
||||
const [headingText] = capture
|
||||
return headingText
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.removeHugoShortcode) {
|
||||
src = src.toString()
|
||||
src = src.replaceAll(hugoShortcodeRegex, (_value, ...capture) => {
|
||||
const [scContent] = capture
|
||||
return scContent
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.replaceFigureWithMdImg) {
|
||||
src = src.toString()
|
||||
src = src.replaceAll(figureTagRegex, (_value, ...capture) => {
|
||||
const [src] = capture
|
||||
return ``
|
||||
})
|
||||
}
|
||||
|
||||
if (opts.replaceOrgLatex) {
|
||||
src = src.toString()
|
||||
src = src.replaceAll(inlineLatexRegex, (_value, ...capture) => {
|
||||
const [eqn] = capture
|
||||
return `$${eqn}$`
|
||||
})
|
||||
src = src.replaceAll(blockLatexRegex, (_value, ...capture) => {
|
||||
const [eqn] = capture
|
||||
return `$$${eqn}$$`
|
||||
})
|
||||
|
||||
// ox-hugo escapes _ as \_
|
||||
src = src.replaceAll(quartzLatexRegex, (value) => {
|
||||
return value.replaceAll("\\_", "_")
|
||||
})
|
||||
}
|
||||
return src
|
||||
},
|
||||
htmlPlugins() {
|
||||
const plugins: PluggableList = [rehypeRaw]
|
||||
return plugins
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { PluggableList } from "unified"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
|
||||
import { Root, Html, Paragraph, Text, Link, Parent } from "mdast"
|
||||
import { BuildVisitor } from "unist-util-visit"
|
||||
|
||||
export interface Options {
|
||||
orComponent: boolean
|
||||
TODOComponent: boolean
|
||||
DONEComponent: boolean
|
||||
videoComponent: boolean
|
||||
audioComponent: boolean
|
||||
pdfComponent: boolean
|
||||
blockquoteComponent: boolean
|
||||
tableComponent: boolean
|
||||
attributeComponent: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
orComponent: true,
|
||||
TODOComponent: true,
|
||||
DONEComponent: true,
|
||||
videoComponent: true,
|
||||
audioComponent: true,
|
||||
pdfComponent: true,
|
||||
blockquoteComponent: true,
|
||||
tableComponent: true,
|
||||
attributeComponent: true,
|
||||
}
|
||||
|
||||
const orRegex = new RegExp(/{{or:(.*?)}}/, "g")
|
||||
const TODORegex = new RegExp(/{{.*?\bTODO\b.*?}}/, "g")
|
||||
const DONERegex = new RegExp(/{{.*?\bDONE\b.*?}}/, "g")
|
||||
|
||||
const blockquoteRegex = new RegExp(/(\[\[>\]\])\s*(.*)/, "g")
|
||||
const roamHighlightRegex = new RegExp(/\^\^(.+)\^\^/, "g")
|
||||
const roamItalicRegex = new RegExp(/__(.+)__/, "g")
|
||||
|
||||
function isSpecialEmbed(node: Paragraph): boolean {
|
||||
if (node.children.length !== 2) return false
|
||||
|
||||
const [textNode, linkNode] = node.children
|
||||
return (
|
||||
textNode.type === "text" &&
|
||||
textNode.value.startsWith("{{[[") &&
|
||||
linkNode.type === "link" &&
|
||||
linkNode.children[0].type === "text" &&
|
||||
linkNode.children[0].value.endsWith("}}")
|
||||
)
|
||||
}
|
||||
|
||||
function transformSpecialEmbed(node: Paragraph, opts: Options): Html | null {
|
||||
const [textNode, linkNode] = node.children as [Text, Link]
|
||||
const embedType = textNode.value.match(/\{\{\[\[(.*?)\]\]:/)?.[1]?.toLowerCase()
|
||||
const url = linkNode.url.slice(0, -2) // Remove the trailing '}}'
|
||||
|
||||
switch (embedType) {
|
||||
case "audio":
|
||||
return opts.audioComponent
|
||||
? {
|
||||
type: "html",
|
||||
value: `<audio controls>
|
||||
<source src="${url}" type="audio/mpeg">
|
||||
<source src="${url}" type="audio/ogg">
|
||||
Your browser does not support the audio tag.
|
||||
</audio>`,
|
||||
}
|
||||
: null
|
||||
case "video":
|
||||
if (!opts.videoComponent) return null
|
||||
// Check if it's a YouTube video
|
||||
const youtubeMatch = url.match(
|
||||
/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/,
|
||||
)
|
||||
if (youtubeMatch) {
|
||||
const videoId = youtubeMatch[1].split("&")[0] // Remove additional parameters
|
||||
const playlistMatch = url.match(/[?&]list=([^#\&\?]*)/)
|
||||
const playlistId = playlistMatch ? playlistMatch[1] : null
|
||||
|
||||
return {
|
||||
type: "html",
|
||||
value: `<iframe
|
||||
class="external-embed youtube"
|
||||
width="600px"
|
||||
height="350px"
|
||||
src="https://www.youtube.com/embed/${videoId}${playlistId ? `?list=${playlistId}` : ""}"
|
||||
frameborder="0"
|
||||
allow="fullscreen"
|
||||
></iframe>`,
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
type: "html",
|
||||
value: `<video controls>
|
||||
<source src="${url}" type="video/mp4">
|
||||
<source src="${url}" type="video/webm">
|
||||
Your browser does not support the video tag.
|
||||
</video>`,
|
||||
}
|
||||
}
|
||||
case "pdf":
|
||||
return opts.pdfComponent
|
||||
? {
|
||||
type: "html",
|
||||
value: `<embed src="${url}" type="application/pdf" width="100%" height="600px" />`,
|
||||
}
|
||||
: null
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const RoamFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (
|
||||
userOpts,
|
||||
) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
|
||||
return {
|
||||
name: "RoamFlavoredMarkdown",
|
||||
markdownPlugins() {
|
||||
const plugins: PluggableList = []
|
||||
|
||||
plugins.push(() => {
|
||||
return (tree: Root) => {
|
||||
const replacements: [RegExp, ReplaceFunction][] = []
|
||||
|
||||
// Handle special embeds (audio, video, PDF)
|
||||
if (opts.audioComponent || opts.videoComponent || opts.pdfComponent) {
|
||||
visit(tree, "paragraph", ((node: Paragraph, index: number, parent: Parent | null) => {
|
||||
if (isSpecialEmbed(node)) {
|
||||
const transformedNode = transformSpecialEmbed(node, opts)
|
||||
if (transformedNode && parent) {
|
||||
parent.children[index] = transformedNode
|
||||
}
|
||||
}
|
||||
}) as BuildVisitor<Root, "paragraph">)
|
||||
}
|
||||
|
||||
// Roam italic syntax
|
||||
replacements.push([
|
||||
roamItalicRegex,
|
||||
(_value: string, match: string) => ({
|
||||
type: "emphasis",
|
||||
children: [{ type: "text", value: match }],
|
||||
}),
|
||||
])
|
||||
|
||||
// Roam highlight syntax
|
||||
replacements.push([
|
||||
roamHighlightRegex,
|
||||
(_value: string, inner: string) => ({
|
||||
type: "html",
|
||||
value: `<span class="text-highlight">${inner}</span>`,
|
||||
}),
|
||||
])
|
||||
|
||||
if (opts.orComponent) {
|
||||
replacements.push([
|
||||
orRegex,
|
||||
(match: string) => {
|
||||
const matchResult = match.match(/{{or:(.*?)}}/)
|
||||
if (matchResult === null) {
|
||||
return { type: "html", value: "" }
|
||||
}
|
||||
const optionsString: string = matchResult[1]
|
||||
const options: string[] = optionsString.split("|")
|
||||
const selectHtml: string = `<select>${options.map((option: string) => `<option value="${option}">${option}</option>`).join("")}</select>`
|
||||
return { type: "html", value: selectHtml }
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.TODOComponent) {
|
||||
replacements.push([
|
||||
TODORegex,
|
||||
() => ({
|
||||
type: "html",
|
||||
value: `<input type="checkbox" disabled>`,
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.DONEComponent) {
|
||||
replacements.push([
|
||||
DONERegex,
|
||||
() => ({
|
||||
type: "html",
|
||||
value: `<input type="checkbox" checked disabled>`,
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
if (opts.blockquoteComponent) {
|
||||
replacements.push([
|
||||
blockquoteRegex,
|
||||
(_match: string, _marker: string, content: string) => ({
|
||||
type: "html",
|
||||
value: `<blockquote>${content.trim()}</blockquote>`,
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
mdastFindReplace(tree, replacements)
|
||||
}
|
||||
})
|
||||
|
||||
return plugins
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import rehypePrettyCode, { Options as CodeOptions, Theme as CodeTheme } from "rehype-pretty-code"
|
||||
|
||||
interface Theme extends Record<string, CodeTheme> {
|
||||
light: CodeTheme
|
||||
dark: CodeTheme
|
||||
}
|
||||
|
||||
interface Options {
|
||||
theme?: Theme
|
||||
keepBackground?: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
theme: {
|
||||
light: "github-light",
|
||||
dark: "github-dark",
|
||||
},
|
||||
keepBackground: false,
|
||||
}
|
||||
|
||||
export const SyntaxHighlighting: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts: CodeOptions = { ...defaultOptions, ...userOpts }
|
||||
|
||||
return {
|
||||
name: "SyntaxHighlighting",
|
||||
htmlPlugins() {
|
||||
return [[rehypePrettyCode, opts]]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import { Root } from "mdast"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { toString } from "mdast-util-to-string"
|
||||
import Slugger from "github-slugger"
|
||||
|
||||
export interface Options {
|
||||
maxDepth: 1 | 2 | 3 | 4 | 5 | 6
|
||||
minEntries: number
|
||||
showByDefault: boolean
|
||||
collapseByDefault: boolean
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
maxDepth: 3,
|
||||
minEntries: 1,
|
||||
showByDefault: true,
|
||||
collapseByDefault: false,
|
||||
}
|
||||
|
||||
interface TocEntry {
|
||||
depth: number
|
||||
text: string
|
||||
slug: string // this is just the anchor (#some-slug), not the canonical slug
|
||||
}
|
||||
|
||||
const slugAnchor = new Slugger()
|
||||
export const TableOfContents: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "TableOfContents",
|
||||
markdownPlugins() {
|
||||
return [
|
||||
() => {
|
||||
return async (tree: Root, file) => {
|
||||
const display = file.data.frontmatter?.enableToc ?? opts.showByDefault
|
||||
if (display) {
|
||||
slugAnchor.reset()
|
||||
const toc: TocEntry[] = []
|
||||
let highestDepth: number = opts.maxDepth
|
||||
visit(tree, "heading", (node) => {
|
||||
if (node.depth <= opts.maxDepth) {
|
||||
const text = toString(node)
|
||||
highestDepth = Math.min(highestDepth, node.depth)
|
||||
toc.push({
|
||||
depth: node.depth,
|
||||
text,
|
||||
slug: slugAnchor.slug(text),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
if (toc.length > 0 && toc.length > opts.minEntries) {
|
||||
file.data.toc = toc.map((entry) => ({
|
||||
...entry,
|
||||
depth: entry.depth - highestDepth,
|
||||
}))
|
||||
file.data.collapseToc = opts.collapseByDefault
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
toc: TocEntry[]
|
||||
collapseToc: boolean
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,22 @@
|
||||
import { PluggableList } from "unified"
|
||||
import { StaticResources } from "../util/resources"
|
||||
import { ProcessedContent } from "./vfile"
|
||||
import { QuartzComponent } from "../components/types"
|
||||
import { FilePath } from "../util/path"
|
||||
import { ProcessedContent, QuartzPluginData } from "./vfile"
|
||||
import {
|
||||
QuartzComponent,
|
||||
QuartzComponentConstructor,
|
||||
QuartzComponentProps,
|
||||
} from "../components/types"
|
||||
import { FilePath, FullSlug } from "../util/path"
|
||||
import { BuildCtx } from "../util/ctx"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
import { VFile } from "vfile"
|
||||
import { Root } from "hast"
|
||||
|
||||
export interface PluginTypes {
|
||||
transformers: QuartzTransformerPluginInstance[]
|
||||
filters: QuartzFilterPluginInstance[]
|
||||
emitters: QuartzEmitterPluginInstance[]
|
||||
pageTypes?: PageTypePluginEntry[]
|
||||
}
|
||||
|
||||
type OptionType = object | undefined
|
||||
@@ -63,3 +70,71 @@ export type QuartzEmitterPluginInstance = {
|
||||
getQuartzComponents?: (ctx: BuildCtx) => QuartzComponent[]
|
||||
externalResources?: ExternalResourcesFn
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PageType Plugin Types
|
||||
// ============================================================================
|
||||
|
||||
export type PageMatcher = (args: {
|
||||
slug: string
|
||||
fileData: QuartzPluginData
|
||||
cfg: GlobalConfiguration
|
||||
[key: string]: unknown
|
||||
}) => boolean
|
||||
|
||||
export interface VirtualPage {
|
||||
slug: string
|
||||
title: string
|
||||
data: Partial<QuartzPluginData> & Record<string, unknown>
|
||||
}
|
||||
|
||||
export type PageGenerator = (args: {
|
||||
content: ProcessedContent[]
|
||||
cfg: GlobalConfiguration
|
||||
ctx: BuildCtx
|
||||
[key: string]: unknown
|
||||
}) => VirtualPage[]
|
||||
|
||||
/** A function that mutates a HAST tree at render time, when allFiles is available. */
|
||||
export type TreeTransform = (
|
||||
root: Root,
|
||||
slug: FullSlug,
|
||||
componentData: QuartzComponentProps,
|
||||
) => void
|
||||
|
||||
export type QuartzPageTypePlugin<Options extends OptionType = undefined> = (
|
||||
opts?: Options,
|
||||
) => QuartzPageTypePluginInstance
|
||||
|
||||
export interface QuartzPageTypePluginInstance {
|
||||
name: string
|
||||
priority?: number
|
||||
fileExtensions?: string[]
|
||||
match: PageMatcher
|
||||
generate?: PageGenerator
|
||||
layout: string
|
||||
/** Optional page frame name (e.g. "default", "full-width", "minimal"). Defaults to "default". */
|
||||
frame?: string
|
||||
body: QuartzComponentConstructor
|
||||
/** Optional render-time HAST tree transforms (e.g. resolving inline codeblocks). */
|
||||
treeTransforms?: (ctx: BuildCtx) => TreeTransform[]
|
||||
}
|
||||
|
||||
// Structural supertype accepted in plugin configuration arrays.
|
||||
// Community plugins use a differently-branded FullSlug in their PageMatcher,
|
||||
// making them incompatible with the internal PageMatcher under strict
|
||||
// function-parameter contravariance. This wider entry type avoids forcing
|
||||
// casts in quartz.ts while the dispatcher safely calls match/generate
|
||||
// with the correct arguments at runtime.
|
||||
export interface PageTypePluginEntry {
|
||||
name: string
|
||||
priority?: number
|
||||
fileExtensions?: string[]
|
||||
match: (...args: never[]) => boolean
|
||||
generate?: (...args: never[]) => VirtualPage[]
|
||||
layout: string
|
||||
/** Optional page frame name (e.g. "default", "full-width", "minimal"). Defaults to "default". */
|
||||
frame?: string
|
||||
body: QuartzComponentConstructor
|
||||
treeTransforms?: (...args: never[]) => TreeTransform[]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user