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:
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
|
||||
}
|
||||
Reference in New Issue
Block a user