@sigx/ssg 0.3.1 β 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +358 -358
- package/dist/build-DP9zez3B.js.map +1 -1
- package/dist/client.js.map +1 -1
- package/dist/dev.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/plugin-EIAzPLvE.js.map +1 -1
- package/dist/plugin.d.ts +9 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +99 -0
- package/dist/plugin.js.map +1 -0
- package/dist/virtual-entries-CH-0HuqJ.js.map +1 -1
- package/package.json +23 -13
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js +0 -2357
- package/dist/cli.js.map +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-DP9zez3B.js","names":[],"sources":["../src/sitemap.ts","../src/build.ts"],"sourcesContent":["/**\r\n * Sitemap Generation\r\n *\r\n * Generates XML sitemaps for SSG sites following the sitemap protocol.\r\n * https://www.sitemaps.org/protocol.html\r\n */\r\n\r\nimport fs from 'node:fs/promises';\r\nimport path from 'node:path';\r\nimport type { SSGConfig, PageBuildResult } from './types';\r\n\r\n/**\r\n * Sitemap entry with optional metadata\r\n */\r\nexport interface SitemapEntry {\r\n /** URL path (relative to site base) */\r\n path: string;\r\n /** Last modification date */\r\n lastmod?: Date | string;\r\n /** Change frequency hint */\r\n changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';\r\n /** Priority relative to other pages (0.0 to 1.0) */\r\n priority?: number;\r\n}\r\n\r\n/**\r\n * Sitemap generation options\r\n */\r\nexport interface SitemapOptions {\r\n /** Include all built pages automatically */\r\n includePages?: boolean;\r\n /** Additional URLs to include */\r\n additionalUrls?: SitemapEntry[];\r\n /** URLs to exclude (glob patterns or exact matches) */\r\n exclude?: string[];\r\n /** Default change frequency */\r\n defaultChangefreq?: SitemapEntry['changefreq'];\r\n /** Default priority */\r\n defaultPriority?: number;\r\n}\r\n\r\n/**\r\n * Generate sitemap XML content\r\n */\r\nexport function generateSitemap(\r\n entries: SitemapEntry[],\r\n config: SSGConfig\r\n): string {\r\n const siteUrl = config.site?.url?.replace(/\\/$/, '') || '';\r\n const base = config.base?.replace(/\\/$/, '') || '';\r\n\r\n const urlEntries = entries.map((entry) => {\r\n const loc = `${siteUrl}${base}${entry.path}`;\r\n const lastmod = entry.lastmod\r\n ? typeof entry.lastmod === 'string'\r\n ? entry.lastmod\r\n : entry.lastmod.toISOString().split('T')[0]\r\n : undefined;\r\n\r\n return ` <url>\r\n <loc>${escapeXml(loc)}</loc>${lastmod ? `\r\n <lastmod>${lastmod}</lastmod>` : ''}${entry.changefreq ? `\r\n <changefreq>${entry.changefreq}</changefreq>` : ''}${entry.priority !== undefined ? `\r\n <priority>${entry.priority.toFixed(1)}</priority>` : ''}\r\n </url>`;\r\n });\r\n\r\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\r\n${urlEntries.join('\\n')}\r\n</urlset>`;\r\n}\r\n\r\n/**\r\n * Generate robots.txt content\r\n */\r\nexport function generateRobotsTxt(config: SSGConfig, sitemapPath = '/sitemap.xml'): string {\r\n const siteUrl = config.site?.url?.replace(/\\/$/, '') || '';\r\n const base = config.base?.replace(/\\/$/, '') || '';\r\n\r\n return `User-agent: *\r\nAllow: /\r\n\r\nSitemap: ${siteUrl}${base}${sitemapPath}\r\n`;\r\n}\r\n\r\n/**\r\n * Convert page build results to sitemap entries\r\n */\r\nexport function pagesToSitemapEntries(\r\n pages: PageBuildResult[],\r\n options: SitemapOptions = {}\r\n): SitemapEntry[] {\r\n const {\r\n exclude = [],\r\n defaultChangefreq = 'weekly',\r\n defaultPriority = 0.5,\r\n } = options;\r\n\r\n return pages\r\n .filter((page) => {\r\n // Filter out excluded paths\r\n for (const pattern of exclude) {\r\n if (pattern.includes('*')) {\r\n // Simple glob matching\r\n const regex = new RegExp(\r\n '^' + pattern.replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$'\r\n );\r\n if (regex.test(page.path)) return false;\r\n } else if (page.path === pattern) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n })\r\n .map((page) => {\r\n // Determine priority based on path depth\r\n const depth = page.path.split('/').filter(Boolean).length;\r\n let priority = defaultPriority;\r\n \r\n if (page.path === '/') {\r\n priority = 1.0; // Homepage highest priority\r\n } else if (depth === 1) {\r\n priority = 0.8; // Top-level pages\r\n } else if (depth === 2) {\r\n priority = 0.6; // Second-level pages\r\n }\r\n\r\n return {\r\n path: page.path,\r\n changefreq: defaultChangefreq,\r\n priority,\r\n };\r\n });\r\n}\r\n\r\n/**\r\n * Write sitemap and robots.txt to output directory\r\n */\r\nexport async function writeSitemap(\r\n pages: PageBuildResult[],\r\n config: SSGConfig,\r\n outDir: string,\r\n options: SitemapOptions = {}\r\n): Promise<{ sitemapPath: string; robotsPath: string }> {\r\n // Generate entries from pages\r\n const entries = pagesToSitemapEntries(pages, options);\r\n\r\n // Add additional URLs if provided\r\n if (options.additionalUrls) {\r\n entries.push(...options.additionalUrls);\r\n }\r\n\r\n // Generate sitemap XML\r\n const sitemapContent = generateSitemap(entries, config);\r\n const sitemapPath = path.join(outDir, 'sitemap.xml');\r\n await fs.writeFile(sitemapPath, sitemapContent, 'utf-8');\r\n\r\n // Generate robots.txt\r\n const robotsContent = generateRobotsTxt(config);\r\n const robotsPath = path.join(outDir, 'robots.txt');\r\n await fs.writeFile(robotsPath, robotsContent, 'utf-8');\r\n\r\n return { sitemapPath, robotsPath };\r\n}\r\n\r\n/**\r\n * Escape special XML characters\r\n */\r\nfunction escapeXml(str: string): string {\r\n return str\r\n .replace(/&/g, '&')\r\n .replace(/</g, '<')\r\n .replace(/>/g, '>')\r\n .replace(/\"/g, '"')\r\n .replace(/'/g, ''');\r\n}\r\n","/**\r\n * SSG Build CLI\r\n *\r\n * Static site generation build process:\r\n * 1. Load configuration\r\n * 2. Scan routes and expand dynamic paths\r\n * 3. Build with Vite for production\r\n * 4. Render each route to static HTML\r\n * 5. Write output files\r\n * 6. Generate sitemap and robots.txt\r\n */\r\n\r\nimport path from 'node:path';\r\nimport fs from 'node:fs/promises';\r\nimport fsSync from 'node:fs';\r\nimport { createRequire } from 'node:module';\r\nimport { pathToFileURL } from 'node:url';\r\nimport type { SSGConfig, BuildOptions, BuildResult, PageBuildResult, SSGRoute, PageModule } from './types';\r\nimport { loadConfig, resolveConfigPaths } from './config';\r\nimport { scanPages, isDynamicRoute, extractParams, expandDynamicRoute } from './routing/index';\r\nimport { discoverLayouts } from './layouts/index';\r\nimport { writeSitemap } from './sitemap';\r\nimport {\r\n detectCustomEntries,\r\n generateClientEntry,\r\n generateServerEntry,\r\n generateProductionHtmlTemplate,\r\n VIRTUAL_CLIENT_ID,\r\n VIRTUAL_SERVER_ID,\r\n} from './vite/virtual-entries';\r\n\r\n/**\r\n * Build static site\r\n */\r\nexport async function build(options: BuildOptions = {}): Promise<BuildResult> {\r\n const startTime = Date.now();\r\n const root = process.cwd();\r\n const warnings: string[] = [];\r\n const pages: PageBuildResult[] = [];\r\n\r\n console.log('\\nπ @sigx/ssg - Building static site...\\n');\r\n\r\n // Step 1: Load configuration\r\n console.log('π¦ Loading configuration...');\r\n const config = await loadConfig(options.configPath);\r\n const resolvedConfig = resolveConfigPaths(config, root);\r\n\r\n // Step 2: Scan routes\r\n console.log('π Scanning pages...');\r\n const routes = await scanPages(resolvedConfig, root);\r\n console.log(` Found ${routes.length} page(s)`);\r\n\r\n // Step 3: Discover layouts\r\n console.log('π Discovering layouts...');\r\n const layouts = await discoverLayouts(resolvedConfig, root);\r\n console.log(` Found ${layouts.length} layout(s)`);\r\n\r\n // Step 4: Detect entry points\r\n const entryDetection = detectCustomEntries(root, resolvedConfig);\r\n if (entryDetection.useVirtualClient || entryDetection.useVirtualServer) {\r\n console.log('π¦ Using zero-config mode');\r\n if (entryDetection.useVirtualClient) console.log(' β Virtual client entry');\r\n if (entryDetection.useVirtualServer) console.log(' β Virtual server entry');\r\n if (entryDetection.useVirtualHtml) console.log(' β Virtual HTML template');\r\n }\r\n\r\n // Get entry points (may create temp files for virtual entries)\r\n const clientEntry = await getClientEntryPoint(resolvedConfig, root);\r\n const ssrEntry = await getSSREntryPoint(resolvedConfig, root);\r\n\r\n // Always write HTML template for the build (either generated or updated from custom)\r\n // This ensures Vite processes it and outputs index.html\r\n const htmlTemplatePath = path.join(root, 'index.html');\r\n let cleanupHtml = false;\r\n let originalHtmlContent: string | null = null;\r\n \r\n // Save original HTML content if we're modifying a custom one\r\n if (!entryDetection.useVirtualHtml && fsSync.existsSync(htmlTemplatePath)) {\r\n originalHtmlContent = fsSync.readFileSync(htmlTemplatePath, 'utf-8');\r\n }\r\n \r\n const htmlContent = await getHtmlTemplate(resolvedConfig, root, clientEntry);\r\n fsSync.writeFileSync(htmlTemplatePath, htmlContent, 'utf-8');\r\n cleanupHtml = entryDetection.useVirtualHtml; // Only cleanup (delete) if we generated it\r\n\r\n // Step 5: Build with Vite\r\n console.log('π¨ Building with Vite...');\r\n const vite = await import('vite');\r\n\r\n try {\r\n // Build client bundle\r\n // Note: We don't empty the outDir since vite build may have already run\r\n // Always use HTML as input so Vite outputs index.html properly\r\n const clientInput = htmlTemplatePath;\r\n \r\n await vite.build({\r\n root,\r\n mode: 'production',\r\n build: {\r\n outDir: resolvedConfig.outDir,\r\n emptyOutDir: false,\r\n ssrManifest: true,\r\n rollupOptions: {\r\n input: clientInput,\r\n },\r\n },\r\n logLevel: options.verbose ? 'info' : 'warn',\r\n });\r\n\r\n // Build SSR bundle\r\n const ssrOutDir = path.join(resolvedConfig.outDir!, '.ssg');\r\n await vite.build({\r\n root,\r\n mode: 'production',\r\n build: {\r\n outDir: ssrOutDir,\r\n ssr: true,\r\n rollupOptions: {\r\n input: ssrEntry,\r\n },\r\n },\r\n logLevel: options.verbose ? 'info' : 'warn',\r\n });\r\n\r\n // Step 6: Collect all paths to render\r\n console.log('π Collecting paths to render...');\r\n const pathsToRender = await collectPaths(routes, root, warnings);\r\n console.log(` ${pathsToRender.length} path(s) to render`);\r\n\r\n // Pre-create all output directories to avoid mkdir contention during parallel rendering\r\n const outputDirs = new Set<string>();\r\n for (const pathInfo of pathsToRender) {\r\n const outputPath = getOutputPath(pathInfo.path, resolvedConfig.outDir!);\r\n outputDirs.add(path.dirname(outputPath));\r\n }\r\n await Promise.all(\r\n Array.from(outputDirs).map(dir => fs.mkdir(dir, { recursive: true }))\r\n );\r\n\r\n // Step 7: Render each path to HTML\r\n console.log('π¨ Rendering pages...');\r\n\r\n // Determine the SSR entry output name (based on input file name)\r\n const ssrEntryBasename = path.basename(ssrEntry, path.extname(ssrEntry));\r\n const ssrEntryName = ssrEntryBasename + '.js';\r\n\r\n // Pre-load the SSR module once for all pages\r\n const entryPath = path.join(ssrOutDir, ssrEntryName);\r\n const entryModule = await import(pathToFileURL(entryPath).href);\r\n\r\n // Load HTML template once\r\n const templatePath = path.join(resolvedConfig.outDir!, 'index.html');\r\n const template = await fs.readFile(templatePath, 'utf-8');\r\n\r\n // Parallel rendering configuration - higher concurrency since rendering is CPU-bound\r\n const CONCURRENCY = options.concurrency ?? 20; // Number of pages to render in parallel\r\n const verbose = options.verbose ?? false;\r\n\r\n interface RenderResult {\r\n pathInfo: PathToRender;\r\n html: string;\r\n outputPath: string;\r\n renderTime: number;\r\n }\r\n\r\n // Render a single page (CPU-bound, no I/O)\r\n async function renderPage(pathInfo: PathToRender): Promise<RenderResult | null> {\r\n const renderStart = Date.now();\r\n\r\n try {\r\n // Render the app\r\n const appHtml = await entryModule.render(pathInfo.path, {\r\n params: pathInfo.params,\r\n props: pathInfo.props,\r\n });\r\n\r\n // Inject into template\r\n let html = template.replace('<!--app-html-->', appHtml);\r\n const headTags = generateHeadTags(pathInfo, resolvedConfig);\r\n html = html.replace('<!--head-tags-->', headTags);\r\n\r\n const outputPath = getOutputPath(pathInfo.path, resolvedConfig.outDir!);\r\n const renderTime = Date.now() - renderStart;\r\n\r\n return { pathInfo, html, outputPath, renderTime };\r\n } catch (err) {\r\n const errorMessage = err instanceof Error ? err.message : String(err);\r\n console.error(` β ${pathInfo.path}: ${errorMessage}`);\r\n warnings.push(`Failed to render ${pathInfo.path}: ${errorMessage}`);\r\n return null;\r\n }\r\n }\r\n\r\n // Render all pages in parallel batches (CPU-bound, no I/O)\r\n console.log(' Phase 1: Rendering...');\r\n const renderPhaseStart = Date.now();\r\n const renderResults: RenderResult[] = [];\r\n \r\n for (let i = 0; i < pathsToRender.length; i += CONCURRENCY) {\r\n const batch = pathsToRender.slice(i, i + CONCURRENCY);\r\n const results = await Promise.all(batch.map(renderPage));\r\n \r\n for (const result of results) {\r\n if (result) {\r\n renderResults.push(result);\r\n }\r\n }\r\n }\r\n const renderPhaseDuration = Date.now() - renderPhaseStart;\r\n console.log(` Phase 1 complete: ${renderResults.length} pages in ${renderPhaseDuration}ms (${Math.round(renderPhaseDuration / renderResults.length)}ms avg)`);\r\n\r\n // Write all files in parallel with limited concurrency\r\n console.log(' Phase 2: Writing files...');\r\n const writePhaseStart = Date.now();\r\n const WRITE_CONCURRENCY = 10; // Limit parallel writes to reduce I/O contention\r\n \r\n for (let i = 0; i < renderResults.length; i += WRITE_CONCURRENCY) {\r\n const batch = renderResults.slice(i, i + WRITE_CONCURRENCY);\r\n await Promise.all(batch.map(async (result) => {\r\n await fs.writeFile(result.outputPath, result.html, 'utf-8');\r\n const size = Buffer.byteLength(result.html, 'utf-8');\r\n\r\n pages.push({\r\n path: result.pathInfo.path,\r\n file: result.outputPath,\r\n time: result.renderTime,\r\n size,\r\n });\r\n \r\n if (verbose) {\r\n console.log(` β ${result.pathInfo.path} (${result.renderTime}ms, ${formatBytes(size)})`);\r\n }\r\n }));\r\n }\r\n const writePhaseDuration = Date.now() - writePhaseStart;\r\n console.log(` Phase 2 complete: ${renderResults.length} files in ${writePhaseDuration}ms`);\r\n \r\n // Summary (non-verbose)\r\n if (!verbose) {\r\n console.log(` β Rendered ${renderResults.length} pages`);\r\n }\r\n\r\n // Step 8: Clean up SSR build\r\n await fs.rm(ssrOutDir, { recursive: true, force: true });\r\n\r\n // Step 9: Generate sitemap and robots.txt\r\n if (pages.length > 0) {\r\n console.log('πΊοΈ Generating sitemap...');\r\n await writeSitemap(pages, resolvedConfig, resolvedConfig.outDir!);\r\n console.log(' β sitemap.xml');\r\n console.log(' β robots.txt');\r\n }\r\n\r\n } finally {\r\n // Clean up temporary entry files\r\n await cleanupTempEntries(root);\r\n \r\n // Clean up or restore HTML template\r\n if (cleanupHtml) {\r\n // We generated a virtual HTML, remove it\r\n try {\r\n await fs.unlink(htmlTemplatePath);\r\n } catch {\r\n // Ignore\r\n }\r\n } else if (originalHtmlContent !== null) {\r\n // We modified a custom HTML, restore the original\r\n try {\r\n await fs.writeFile(htmlTemplatePath, originalHtmlContent, 'utf-8');\r\n } catch {\r\n // Ignore\r\n }\r\n }\r\n }\r\n\r\n // Done\r\n const totalTime = Date.now() - startTime;\r\n\r\n console.log(`\\nβ
Built ${pages.length} page(s) in ${totalTime}ms`);\r\n\r\n if (warnings.length > 0) {\r\n console.log(`\\nβ οΈ ${warnings.length} warning(s):`);\r\n for (const warning of warnings) {\r\n console.log(` - ${warning}`);\r\n }\r\n }\r\n\r\n console.log(`\\nπ Output: ${resolvedConfig.outDir}\\n`);\r\n\r\n return {\r\n pages,\r\n totalTime,\r\n warnings,\r\n };\r\n}\r\n\r\n/**\r\n * Path information for rendering\r\n */\r\ninterface PathToRender {\r\n path: string;\r\n route: SSGRoute;\r\n params: Record<string, string>;\r\n props?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Collect all paths to render, expanding dynamic routes\r\n */\r\nasync function collectPaths(\r\n routes: SSGRoute[],\r\n root: string,\r\n warnings: string[]\r\n): Promise<PathToRender[]> {\r\n const paths: PathToRender[] = [];\r\n\r\n for (const route of routes) {\r\n if (isDynamicRoute(route)) {\r\n // Load module and call getStaticPaths\r\n try {\r\n const moduleUrl = pathToFileURL(route.file).href;\r\n const pageModule = (await import(moduleUrl)) as PageModule;\r\n\r\n if (!pageModule.getStaticPaths) {\r\n const params = extractParams(route.path).join(', ');\r\n console.warn(\r\n `\\nβ οΈ SSG102: Dynamic route missing getStaticPaths()\\n` +\r\n ` π ${route.file}\\n` +\r\n ` Route: ${route.path} (params: ${params})\\n` +\r\n ` π‘ Export getStaticPaths() to generate static pages:\\n\\n` +\r\n ` export async function getStaticPaths() {\\n` +\r\n ` return [{ params: { ${params.split(', ')[0]}: 'value' } }];\\n` +\r\n ` }\\n`\r\n );\r\n warnings.push(\r\n `Route ${route.path} has dynamic segments [${params}] but no getStaticPaths() export. Skipping.`\r\n );\r\n continue;\r\n }\r\n\r\n const staticPaths = await pageModule.getStaticPaths();\r\n\r\n for (const staticPath of staticPaths) {\r\n const expandedPaths = expandDynamicRoute(route, [staticPath]);\r\n for (const expandedPath of expandedPaths) {\r\n paths.push({\r\n path: expandedPath,\r\n route,\r\n params: staticPath.params,\r\n props: staticPath.props,\r\n });\r\n }\r\n }\r\n } catch (err) {\r\n warnings.push(`Failed to load ${route.file}: ${err}`);\r\n }\r\n } else {\r\n paths.push({\r\n path: route.path,\r\n route,\r\n params: {},\r\n });\r\n }\r\n }\r\n\r\n return paths;\r\n}\r\n\r\n/**\r\n * Render a page to HTML\r\n */\r\nasync function renderPage(\r\n pathInfo: PathToRender,\r\n config: SSGConfig,\r\n ssrOutDir: string,\r\n ssrEntryName: string\r\n): Promise<string> {\r\n // Load the SSR entry module\r\n // This should export a render function that returns HTML string\r\n const entryPath = path.join(ssrOutDir, ssrEntryName);\r\n const entryModule = await import(pathToFileURL(entryPath).href);\r\n\r\n // Render the app - the entry module's render function handles SSR\r\n const appHtml = await entryModule.render(pathInfo.path, {\r\n params: pathInfo.params,\r\n props: pathInfo.props,\r\n });\r\n\r\n // Load HTML template\r\n const templatePath = path.join(config.outDir!, 'index.html');\r\n let template = await fs.readFile(templatePath, 'utf-8');\r\n\r\n // Inject app HTML\r\n template = template.replace('<!--app-html-->', appHtml);\r\n\r\n // Inject head tags if any\r\n const headTags = generateHeadTags(pathInfo, config);\r\n template = template.replace('<!--head-tags-->', headTags);\r\n\r\n return template;\r\n}\r\n\r\n/**\r\n * Generate head tags for a page\r\n */\r\nfunction generateHeadTags(pathInfo: PathToRender, config: SSGConfig): string {\r\n const tags: string[] = [];\r\n const meta = pathInfo.route.meta || {};\r\n\r\n // Title\r\n const title = meta.title || config.site?.title;\r\n if (title) {\r\n tags.push(`<title>${escapeHtml(title)}</title>`);\r\n }\r\n\r\n // Description\r\n const description = meta.description || config.site?.description;\r\n if (description) {\r\n tags.push(`<meta name=\"description\" content=\"${escapeHtml(description)}\">`);\r\n }\r\n\r\n // Canonical URL\r\n if (config.site?.url) {\r\n const canonical = new URL(pathInfo.path, config.site.url).href;\r\n tags.push(`<link rel=\"canonical\" href=\"${canonical}\">`);\r\n }\r\n\r\n return tags.join('\\n ');\r\n}\r\n\r\n/**\r\n * Get output file path for a URL path\r\n */\r\nfunction getOutputPath(urlPath: string, outDir: string): string {\r\n // Normalize path\r\n let normalized = urlPath.replace(/^\\//, '').replace(/\\/$/, '');\r\n\r\n if (!normalized) {\r\n normalized = 'index';\r\n }\r\n\r\n // Add .html extension or /index.html for directories\r\n if (!normalized.endsWith('.html')) {\r\n normalized = path.join(normalized, 'index.html');\r\n }\r\n\r\n return path.join(outDir, normalized);\r\n}\r\n\r\n/**\r\n * Get SSR entry point\r\n * Returns virtual module ID if no custom entry exists\r\n */\r\nasync function getSSREntryPoint(config: SSGConfig, root: string): Promise<string> {\r\n // Check for custom entry points\r\n const detection = detectCustomEntries(root, config);\r\n \r\n if (!detection.useVirtualServer && detection.customServerPath) {\r\n return detection.customServerPath;\r\n }\r\n\r\n // Use virtual server entry - we need to write a temp file for the build\r\n // because Rollup input must be a real file path\r\n const virtualServerCode = generateServerEntry(config);\r\n const tempServerPath = path.join(root, '.ssg-temp-entry-server.tsx');\r\n fsSync.writeFileSync(tempServerPath, virtualServerCode, 'utf-8');\r\n \r\n return tempServerPath;\r\n}\r\n\r\n/**\r\n * Get client entry point\r\n * Returns virtual module ID if no custom entry exists\r\n */\r\nasync function getClientEntryPoint(config: SSGConfig, root: string): Promise<string> {\r\n const detection = detectCustomEntries(root, config);\r\n \r\n if (!detection.useVirtualClient && detection.customClientPath) {\r\n return detection.customClientPath;\r\n }\r\n\r\n // Use virtual client entry - write a temp file\r\n const virtualClientCode = generateClientEntry(config, detection);\r\n const tempClientPath = path.join(root, '.ssg-temp-entry-client.tsx');\r\n fsSync.writeFileSync(tempClientPath, virtualClientCode, 'utf-8');\r\n \r\n return tempClientPath;\r\n}\r\n\r\n/**\r\n * Clean up temporary entry files\r\n */\r\nasync function cleanupTempEntries(root: string): Promise<void> {\r\n const tempFiles = [\r\n path.join(root, '.ssg-temp-entry-server.tsx'),\r\n path.join(root, '.ssg-temp-entry-client.tsx'),\r\n ];\r\n \r\n for (const file of tempFiles) {\r\n try {\r\n await fs.unlink(file);\r\n } catch {\r\n // Ignore if file doesn't exist\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Get or generate HTML template\r\n */\r\nasync function getHtmlTemplate(config: SSGConfig, root: string, clientEntryPath: string): Promise<string> {\r\n const detection = detectCustomEntries(root, config);\r\n \r\n if (!detection.useVirtualHtml && detection.customHtmlPath) {\r\n // Read custom HTML and update the script src to point to the temp entry file\r\n let html = await fs.readFile(detection.customHtmlPath, 'utf-8');\r\n // Replace any virtual SSG client paths with the actual temp entry path\r\n // Use relative path from root for the script src\r\n const relativePath = './' + path.relative(root, clientEntryPath).replace(/\\\\/g, '/');\r\n html = html.replace(\r\n /<script([^>]*)\\s+src=[\"']?\\/@ssg\\/client\\.tsx[\"']?/g,\r\n `<script$1 src=\"${relativePath}\"`\r\n );\r\n return html;\r\n }\r\n\r\n // Generate virtual HTML template\r\n return generateProductionHtmlTemplate(config, clientEntryPath);\r\n}\r\n\r\n/**\r\n * Format bytes to human-readable string\r\n */\r\nfunction formatBytes(bytes: number): string {\r\n if (bytes < 1024) return `${bytes}B`;\r\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\r\n}\r\n\r\n/**\r\n * Escape HTML special characters\r\n */\r\nfunction escapeHtml(str: string): string {\r\n return str\r\n .replace(/&/g, '&')\r\n .replace(/</g, '<')\r\n .replace(/>/g, '>')\r\n .replace(/\"/g, '"')\r\n .replace(/'/g, ''');\r\n}\r\n"],"mappings":";;;;;;AA4CA,SAAgB,EACZ,GACA,GACM;CACN,IAAM,IAAU,EAAO,MAAM,KAAK,QAAQ,OAAO,GAAG,IAAI,IAClD,IAAO,EAAO,MAAM,QAAQ,OAAO,GAAG,IAAI;AAkBhD,QAAO;;EAhBY,EAAQ,KAAK,MAAU;EACtC,IAAM,IAAM,GAAG,IAAU,IAAO,EAAM,QAChC,IAAU,EAAM,UAChB,OAAO,EAAM,WAAY,WACrB,EAAM,UACN,EAAM,QAAQ,aAAa,CAAC,MAAM,IAAI,CAAC,KAC3C,KAAA;AAEN,SAAO;WACJ,EAAU,EAAI,CAAC,QAAQ,IAAU;eAC7B,EAAQ,cAAc,KAAK,EAAM,aAAa;kBAC3C,EAAM,WAAW,iBAAiB,KAAK,EAAM,aAAa,KAAA,IACnB,KAD+B;gBACxE,EAAM,SAAS,QAAQ,EAAE,CAAC,aAAkB;;GAEtD,CAIO,KAAK,KAAK,CAAC;;;AAOxB,SAAgB,EAAkB,GAAmB,IAAc,gBAAwB;AAIvF,QAAO;;;WAHS,EAAO,MAAM,KAAK,QAAQ,OAAO,GAAG,IAAI,KAC3C,EAAO,MAAM,QAAQ,OAAO,GAAG,IAAI,KAKxB,EAAY;;;AAOxC,SAAgB,EACZ,GACA,IAA0B,EAAE,EACd;CACd,IAAM,EACF,aAAU,EAAE,EACZ,uBAAoB,UACpB,qBAAkB,OAClB;AAEJ,QAAO,E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rB,QAAQ,MAAM,SAAS,CACvB,QAAQ,MAAM,QAAQ"}
|
|
1
|
+
{"version":3,"file":"build-DP9zez3B.js","names":[],"sources":["../src/sitemap.ts","../src/build.ts"],"sourcesContent":["/**\n * Sitemap Generation\n *\n * Generates XML sitemaps for SSG sites following the sitemap protocol.\n * https://www.sitemaps.org/protocol.html\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { SSGConfig, PageBuildResult } from './types';\n\n/**\n * Sitemap entry with optional metadata\n */\nexport interface SitemapEntry {\n /** URL path (relative to site base) */\n path: string;\n /** Last modification date */\n lastmod?: Date | string;\n /** Change frequency hint */\n changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';\n /** Priority relative to other pages (0.0 to 1.0) */\n priority?: number;\n}\n\n/**\n * Sitemap generation options\n */\nexport interface SitemapOptions {\n /** Include all built pages automatically */\n includePages?: boolean;\n /** Additional URLs to include */\n additionalUrls?: SitemapEntry[];\n /** URLs to exclude (glob patterns or exact matches) */\n exclude?: string[];\n /** Default change frequency */\n defaultChangefreq?: SitemapEntry['changefreq'];\n /** Default priority */\n defaultPriority?: number;\n}\n\n/**\n * Generate sitemap XML content\n */\nexport function generateSitemap(\n entries: SitemapEntry[],\n config: SSGConfig\n): string {\n const siteUrl = config.site?.url?.replace(/\\/$/, '') || '';\n const base = config.base?.replace(/\\/$/, '') || '';\n\n const urlEntries = entries.map((entry) => {\n const loc = `${siteUrl}${base}${entry.path}`;\n const lastmod = entry.lastmod\n ? typeof entry.lastmod === 'string'\n ? entry.lastmod\n : entry.lastmod.toISOString().split('T')[0]\n : undefined;\n\n return ` <url>\n <loc>${escapeXml(loc)}</loc>${lastmod ? `\n <lastmod>${lastmod}</lastmod>` : ''}${entry.changefreq ? `\n <changefreq>${entry.changefreq}</changefreq>` : ''}${entry.priority !== undefined ? `\n <priority>${entry.priority.toFixed(1)}</priority>` : ''}\n </url>`;\n });\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n${urlEntries.join('\\n')}\n</urlset>`;\n}\n\n/**\n * Generate robots.txt content\n */\nexport function generateRobotsTxt(config: SSGConfig, sitemapPath = '/sitemap.xml'): string {\n const siteUrl = config.site?.url?.replace(/\\/$/, '') || '';\n const base = config.base?.replace(/\\/$/, '') || '';\n\n return `User-agent: *\nAllow: /\n\nSitemap: ${siteUrl}${base}${sitemapPath}\n`;\n}\n\n/**\n * Convert page build results to sitemap entries\n */\nexport function pagesToSitemapEntries(\n pages: PageBuildResult[],\n options: SitemapOptions = {}\n): SitemapEntry[] {\n const {\n exclude = [],\n defaultChangefreq = 'weekly',\n defaultPriority = 0.5,\n } = options;\n\n return pages\n .filter((page) => {\n // Filter out excluded paths\n for (const pattern of exclude) {\n if (pattern.includes('*')) {\n // Simple glob matching\n const regex = new RegExp(\n '^' + pattern.replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$'\n );\n if (regex.test(page.path)) return false;\n } else if (page.path === pattern) {\n return false;\n }\n }\n return true;\n })\n .map((page) => {\n // Determine priority based on path depth\n const depth = page.path.split('/').filter(Boolean).length;\n let priority = defaultPriority;\n \n if (page.path === '/') {\n priority = 1.0; // Homepage highest priority\n } else if (depth === 1) {\n priority = 0.8; // Top-level pages\n } else if (depth === 2) {\n priority = 0.6; // Second-level pages\n }\n\n return {\n path: page.path,\n changefreq: defaultChangefreq,\n priority,\n };\n });\n}\n\n/**\n * Write sitemap and robots.txt to output directory\n */\nexport async function writeSitemap(\n pages: PageBuildResult[],\n config: SSGConfig,\n outDir: string,\n options: SitemapOptions = {}\n): Promise<{ sitemapPath: string; robotsPath: string }> {\n // Generate entries from pages\n const entries = pagesToSitemapEntries(pages, options);\n\n // Add additional URLs if provided\n if (options.additionalUrls) {\n entries.push(...options.additionalUrls);\n }\n\n // Generate sitemap XML\n const sitemapContent = generateSitemap(entries, config);\n const sitemapPath = path.join(outDir, 'sitemap.xml');\n await fs.writeFile(sitemapPath, sitemapContent, 'utf-8');\n\n // Generate robots.txt\n const robotsContent = generateRobotsTxt(config);\n const robotsPath = path.join(outDir, 'robots.txt');\n await fs.writeFile(robotsPath, robotsContent, 'utf-8');\n\n return { sitemapPath, robotsPath };\n}\n\n/**\n * Escape special XML characters\n */\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n","/**\n * SSG Build CLI\n *\n * Static site generation build process:\n * 1. Load configuration\n * 2. Scan routes and expand dynamic paths\n * 3. Build with Vite for production\n * 4. Render each route to static HTML\n * 5. Write output files\n * 6. Generate sitemap and robots.txt\n */\n\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport type { SSGConfig, BuildOptions, BuildResult, PageBuildResult, SSGRoute, PageModule } from './types';\nimport { loadConfig, resolveConfigPaths } from './config';\nimport { scanPages, isDynamicRoute, extractParams, expandDynamicRoute } from './routing/index';\nimport { discoverLayouts } from './layouts/index';\nimport { writeSitemap } from './sitemap';\nimport {\n detectCustomEntries,\n generateClientEntry,\n generateServerEntry,\n generateProductionHtmlTemplate,\n VIRTUAL_CLIENT_ID,\n VIRTUAL_SERVER_ID,\n} from './vite/virtual-entries';\n\n/**\n * Build static site\n */\nexport async function build(options: BuildOptions = {}): Promise<BuildResult> {\n const startTime = Date.now();\n const root = process.cwd();\n const warnings: string[] = [];\n const pages: PageBuildResult[] = [];\n\n console.log('\\nπ @sigx/ssg - Building static site...\\n');\n\n // Step 1: Load configuration\n console.log('π¦ Loading configuration...');\n const config = await loadConfig(options.configPath);\n const resolvedConfig = resolveConfigPaths(config, root);\n\n // Step 2: Scan routes\n console.log('π Scanning pages...');\n const routes = await scanPages(resolvedConfig, root);\n console.log(` Found ${routes.length} page(s)`);\n\n // Step 3: Discover layouts\n console.log('π Discovering layouts...');\n const layouts = await discoverLayouts(resolvedConfig, root);\n console.log(` Found ${layouts.length} layout(s)`);\n\n // Step 4: Detect entry points\n const entryDetection = detectCustomEntries(root, resolvedConfig);\n if (entryDetection.useVirtualClient || entryDetection.useVirtualServer) {\n console.log('π¦ Using zero-config mode');\n if (entryDetection.useVirtualClient) console.log(' β Virtual client entry');\n if (entryDetection.useVirtualServer) console.log(' β Virtual server entry');\n if (entryDetection.useVirtualHtml) console.log(' β Virtual HTML template');\n }\n\n // Get entry points (may create temp files for virtual entries)\n const clientEntry = await getClientEntryPoint(resolvedConfig, root);\n const ssrEntry = await getSSREntryPoint(resolvedConfig, root);\n\n // Always write HTML template for the build (either generated or updated from custom)\n // This ensures Vite processes it and outputs index.html\n const htmlTemplatePath = path.join(root, 'index.html');\n let cleanupHtml = false;\n let originalHtmlContent: string | null = null;\n \n // Save original HTML content if we're modifying a custom one\n if (!entryDetection.useVirtualHtml && fsSync.existsSync(htmlTemplatePath)) {\n originalHtmlContent = fsSync.readFileSync(htmlTemplatePath, 'utf-8');\n }\n \n const htmlContent = await getHtmlTemplate(resolvedConfig, root, clientEntry);\n fsSync.writeFileSync(htmlTemplatePath, htmlContent, 'utf-8');\n cleanupHtml = entryDetection.useVirtualHtml; // Only cleanup (delete) if we generated it\n\n // Step 5: Build with Vite\n console.log('π¨ Building with Vite...');\n const vite = await import('vite');\n\n try {\n // Build client bundle\n // Note: We don't empty the outDir since vite build may have already run\n // Always use HTML as input so Vite outputs index.html properly\n const clientInput = htmlTemplatePath;\n \n await vite.build({\n root,\n mode: 'production',\n build: {\n outDir: resolvedConfig.outDir,\n emptyOutDir: false,\n ssrManifest: true,\n rollupOptions: {\n input: clientInput,\n },\n },\n logLevel: options.verbose ? 'info' : 'warn',\n });\n\n // Build SSR bundle\n const ssrOutDir = path.join(resolvedConfig.outDir!, '.ssg');\n await vite.build({\n root,\n mode: 'production',\n build: {\n outDir: ssrOutDir,\n ssr: true,\n rollupOptions: {\n input: ssrEntry,\n },\n },\n logLevel: options.verbose ? 'info' : 'warn',\n });\n\n // Step 6: Collect all paths to render\n console.log('π Collecting paths to render...');\n const pathsToRender = await collectPaths(routes, root, warnings);\n console.log(` ${pathsToRender.length} path(s) to render`);\n\n // Pre-create all output directories to avoid mkdir contention during parallel rendering\n const outputDirs = new Set<string>();\n for (const pathInfo of pathsToRender) {\n const outputPath = getOutputPath(pathInfo.path, resolvedConfig.outDir!);\n outputDirs.add(path.dirname(outputPath));\n }\n await Promise.all(\n Array.from(outputDirs).map(dir => fs.mkdir(dir, { recursive: true }))\n );\n\n // Step 7: Render each path to HTML\n console.log('π¨ Rendering pages...');\n\n // Determine the SSR entry output name (based on input file name)\n const ssrEntryBasename = path.basename(ssrEntry, path.extname(ssrEntry));\n const ssrEntryName = ssrEntryBasename + '.js';\n\n // Pre-load the SSR module once for all pages\n const entryPath = path.join(ssrOutDir, ssrEntryName);\n const entryModule = await import(pathToFileURL(entryPath).href);\n\n // Load HTML template once\n const templatePath = path.join(resolvedConfig.outDir!, 'index.html');\n const template = await fs.readFile(templatePath, 'utf-8');\n\n // Parallel rendering configuration - higher concurrency since rendering is CPU-bound\n const CONCURRENCY = options.concurrency ?? 20; // Number of pages to render in parallel\n const verbose = options.verbose ?? false;\n\n interface RenderResult {\n pathInfo: PathToRender;\n html: string;\n outputPath: string;\n renderTime: number;\n }\n\n // Render a single page (CPU-bound, no I/O)\n async function renderPage(pathInfo: PathToRender): Promise<RenderResult | null> {\n const renderStart = Date.now();\n\n try {\n // Render the app\n const appHtml = await entryModule.render(pathInfo.path, {\n params: pathInfo.params,\n props: pathInfo.props,\n });\n\n // Inject into template\n let html = template.replace('<!--app-html-->', appHtml);\n const headTags = generateHeadTags(pathInfo, resolvedConfig);\n html = html.replace('<!--head-tags-->', headTags);\n\n const outputPath = getOutputPath(pathInfo.path, resolvedConfig.outDir!);\n const renderTime = Date.now() - renderStart;\n\n return { pathInfo, html, outputPath, renderTime };\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n console.error(` β ${pathInfo.path}: ${errorMessage}`);\n warnings.push(`Failed to render ${pathInfo.path}: ${errorMessage}`);\n return null;\n }\n }\n\n // Render all pages in parallel batches (CPU-bound, no I/O)\n console.log(' Phase 1: Rendering...');\n const renderPhaseStart = Date.now();\n const renderResults: RenderResult[] = [];\n \n for (let i = 0; i < pathsToRender.length; i += CONCURRENCY) {\n const batch = pathsToRender.slice(i, i + CONCURRENCY);\n const results = await Promise.all(batch.map(renderPage));\n \n for (const result of results) {\n if (result) {\n renderResults.push(result);\n }\n }\n }\n const renderPhaseDuration = Date.now() - renderPhaseStart;\n console.log(` Phase 1 complete: ${renderResults.length} pages in ${renderPhaseDuration}ms (${Math.round(renderPhaseDuration / renderResults.length)}ms avg)`);\n\n // Write all files in parallel with limited concurrency\n console.log(' Phase 2: Writing files...');\n const writePhaseStart = Date.now();\n const WRITE_CONCURRENCY = 10; // Limit parallel writes to reduce I/O contention\n \n for (let i = 0; i < renderResults.length; i += WRITE_CONCURRENCY) {\n const batch = renderResults.slice(i, i + WRITE_CONCURRENCY);\n await Promise.all(batch.map(async (result) => {\n await fs.writeFile(result.outputPath, result.html, 'utf-8');\n const size = Buffer.byteLength(result.html, 'utf-8');\n\n pages.push({\n path: result.pathInfo.path,\n file: result.outputPath,\n time: result.renderTime,\n size,\n });\n \n if (verbose) {\n console.log(` β ${result.pathInfo.path} (${result.renderTime}ms, ${formatBytes(size)})`);\n }\n }));\n }\n const writePhaseDuration = Date.now() - writePhaseStart;\n console.log(` Phase 2 complete: ${renderResults.length} files in ${writePhaseDuration}ms`);\n \n // Summary (non-verbose)\n if (!verbose) {\n console.log(` β Rendered ${renderResults.length} pages`);\n }\n\n // Step 8: Clean up SSR build\n await fs.rm(ssrOutDir, { recursive: true, force: true });\n\n // Step 9: Generate sitemap and robots.txt\n if (pages.length > 0) {\n console.log('πΊοΈ Generating sitemap...');\n await writeSitemap(pages, resolvedConfig, resolvedConfig.outDir!);\n console.log(' β sitemap.xml');\n console.log(' β robots.txt');\n }\n\n } finally {\n // Clean up temporary entry files\n await cleanupTempEntries(root);\n \n // Clean up or restore HTML template\n if (cleanupHtml) {\n // We generated a virtual HTML, remove it\n try {\n await fs.unlink(htmlTemplatePath);\n } catch {\n // Ignore\n }\n } else if (originalHtmlContent !== null) {\n // We modified a custom HTML, restore the original\n try {\n await fs.writeFile(htmlTemplatePath, originalHtmlContent, 'utf-8');\n } catch {\n // Ignore\n }\n }\n }\n\n // Done\n const totalTime = Date.now() - startTime;\n\n console.log(`\\nβ
Built ${pages.length} page(s) in ${totalTime}ms`);\n\n if (warnings.length > 0) {\n console.log(`\\nβ οΈ ${warnings.length} warning(s):`);\n for (const warning of warnings) {\n console.log(` - ${warning}`);\n }\n }\n\n console.log(`\\nπ Output: ${resolvedConfig.outDir}\\n`);\n\n return {\n pages,\n totalTime,\n warnings,\n };\n}\n\n/**\n * Path information for rendering\n */\ninterface PathToRender {\n path: string;\n route: SSGRoute;\n params: Record<string, string>;\n props?: Record<string, unknown>;\n}\n\n/**\n * Collect all paths to render, expanding dynamic routes\n */\nasync function collectPaths(\n routes: SSGRoute[],\n root: string,\n warnings: string[]\n): Promise<PathToRender[]> {\n const paths: PathToRender[] = [];\n\n for (const route of routes) {\n if (isDynamicRoute(route)) {\n // Load module and call getStaticPaths\n try {\n const moduleUrl = pathToFileURL(route.file).href;\n const pageModule = (await import(moduleUrl)) as PageModule;\n\n if (!pageModule.getStaticPaths) {\n const params = extractParams(route.path).join(', ');\n console.warn(\n `\\nβ οΈ SSG102: Dynamic route missing getStaticPaths()\\n` +\n ` π ${route.file}\\n` +\n ` Route: ${route.path} (params: ${params})\\n` +\n ` π‘ Export getStaticPaths() to generate static pages:\\n\\n` +\n ` export async function getStaticPaths() {\\n` +\n ` return [{ params: { ${params.split(', ')[0]}: 'value' } }];\\n` +\n ` }\\n`\n );\n warnings.push(\n `Route ${route.path} has dynamic segments [${params}] but no getStaticPaths() export. Skipping.`\n );\n continue;\n }\n\n const staticPaths = await pageModule.getStaticPaths();\n\n for (const staticPath of staticPaths) {\n const expandedPaths = expandDynamicRoute(route, [staticPath]);\n for (const expandedPath of expandedPaths) {\n paths.push({\n path: expandedPath,\n route,\n params: staticPath.params,\n props: staticPath.props,\n });\n }\n }\n } catch (err) {\n warnings.push(`Failed to load ${route.file}: ${err}`);\n }\n } else {\n paths.push({\n path: route.path,\n route,\n params: {},\n });\n }\n }\n\n return paths;\n}\n\n/**\n * Render a page to HTML\n */\nasync function renderPage(\n pathInfo: PathToRender,\n config: SSGConfig,\n ssrOutDir: string,\n ssrEntryName: string\n): Promise<string> {\n // Load the SSR entry module\n // This should export a render function that returns HTML string\n const entryPath = path.join(ssrOutDir, ssrEntryName);\n const entryModule = await import(pathToFileURL(entryPath).href);\n\n // Render the app - the entry module's render function handles SSR\n const appHtml = await entryModule.render(pathInfo.path, {\n params: pathInfo.params,\n props: pathInfo.props,\n });\n\n // Load HTML template\n const templatePath = path.join(config.outDir!, 'index.html');\n let template = await fs.readFile(templatePath, 'utf-8');\n\n // Inject app HTML\n template = template.replace('<!--app-html-->', appHtml);\n\n // Inject head tags if any\n const headTags = generateHeadTags(pathInfo, config);\n template = template.replace('<!--head-tags-->', headTags);\n\n return template;\n}\n\n/**\n * Generate head tags for a page\n */\nfunction generateHeadTags(pathInfo: PathToRender, config: SSGConfig): string {\n const tags: string[] = [];\n const meta = pathInfo.route.meta || {};\n\n // Title\n const title = meta.title || config.site?.title;\n if (title) {\n tags.push(`<title>${escapeHtml(title)}</title>`);\n }\n\n // Description\n const description = meta.description || config.site?.description;\n if (description) {\n tags.push(`<meta name=\"description\" content=\"${escapeHtml(description)}\">`);\n }\n\n // Canonical URL\n if (config.site?.url) {\n const canonical = new URL(pathInfo.path, config.site.url).href;\n tags.push(`<link rel=\"canonical\" href=\"${canonical}\">`);\n }\n\n return tags.join('\\n ');\n}\n\n/**\n * Get output file path for a URL path\n */\nfunction getOutputPath(urlPath: string, outDir: string): string {\n // Normalize path\n let normalized = urlPath.replace(/^\\//, '').replace(/\\/$/, '');\n\n if (!normalized) {\n normalized = 'index';\n }\n\n // Add .html extension or /index.html for directories\n if (!normalized.endsWith('.html')) {\n normalized = path.join(normalized, 'index.html');\n }\n\n return path.join(outDir, normalized);\n}\n\n/**\n * Get SSR entry point\n * Returns virtual module ID if no custom entry exists\n */\nasync function getSSREntryPoint(config: SSGConfig, root: string): Promise<string> {\n // Check for custom entry points\n const detection = detectCustomEntries(root, config);\n \n if (!detection.useVirtualServer && detection.customServerPath) {\n return detection.customServerPath;\n }\n\n // Use virtual server entry - we need to write a temp file for the build\n // because Rollup input must be a real file path\n const virtualServerCode = generateServerEntry(config);\n const tempServerPath = path.join(root, '.ssg-temp-entry-server.tsx');\n fsSync.writeFileSync(tempServerPath, virtualServerCode, 'utf-8');\n \n return tempServerPath;\n}\n\n/**\n * Get client entry point\n * Returns virtual module ID if no custom entry exists\n */\nasync function getClientEntryPoint(config: SSGConfig, root: string): Promise<string> {\n const detection = detectCustomEntries(root, config);\n \n if (!detection.useVirtualClient && detection.customClientPath) {\n return detection.customClientPath;\n }\n\n // Use virtual client entry - write a temp file\n const virtualClientCode = generateClientEntry(config, detection);\n const tempClientPath = path.join(root, '.ssg-temp-entry-client.tsx');\n fsSync.writeFileSync(tempClientPath, virtualClientCode, 'utf-8');\n \n return tempClientPath;\n}\n\n/**\n * Clean up temporary entry files\n */\nasync function cleanupTempEntries(root: string): Promise<void> {\n const tempFiles = [\n path.join(root, '.ssg-temp-entry-server.tsx'),\n path.join(root, '.ssg-temp-entry-client.tsx'),\n ];\n \n for (const file of tempFiles) {\n try {\n await fs.unlink(file);\n } catch {\n // Ignore if file doesn't exist\n }\n }\n}\n\n/**\n * Get or generate HTML template\n */\nasync function getHtmlTemplate(config: SSGConfig, root: string, clientEntryPath: string): Promise<string> {\n const detection = detectCustomEntries(root, config);\n \n if (!detection.useVirtualHtml && detection.customHtmlPath) {\n // Read custom HTML and update the script src to point to the temp entry file\n let html = await fs.readFile(detection.customHtmlPath, 'utf-8');\n // Replace any virtual SSG client paths with the actual temp entry path\n // Use relative path from root for the script src\n const relativePath = './' + path.relative(root, clientEntryPath).replace(/\\\\/g, '/');\n html = html.replace(\n /<script([^>]*)\\s+src=[\"']?\\/@ssg\\/client\\.tsx[\"']?/g,\n `<script$1 src=\"${relativePath}\"`\n );\n return html;\n }\n\n // Generate virtual HTML template\n return generateProductionHtmlTemplate(config, clientEntryPath);\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n}\n\n/**\n * Escape HTML special characters\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n"],"mappings":";;;;;;AA4CA,SAAgB,EACZ,GACA,GACM;CACN,IAAM,IAAU,EAAO,MAAM,KAAK,QAAQ,OAAO,GAAG,IAAI,IAClD,IAAO,EAAO,MAAM,QAAQ,OAAO,GAAG,IAAI;CAkBhD,OAAO;;EAhBY,EAAQ,KAAK,MAAU;EACtC,IAAM,IAAM,GAAG,IAAU,IAAO,EAAM,QAChC,IAAU,EAAM,UAChB,OAAO,EAAM,WAAY,WACrB,EAAM,UACN,EAAM,QAAQ,aAAa,CAAC,MAAM,IAAI,CAAC,KAC3C,KAAA;EAEN,OAAO;WACJ,EAAU,EAAI,CAAC,QAAQ,IAAU;eAC7B,EAAQ,cAAc,KAAK,EAAM,aAAa;kBAC3C,EAAM,WAAW,iBAAiB,KAAK,EAAM,aAAa,KAAA,IACnB,KAD+B;gBACxE,EAAM,SAAS,QAAQ,EAAE,CAAC,aAAkB;;GAM1D,CAAW,KAAK,KAAK,CAAC;;;AAOxB,SAAgB,EAAkB,GAAmB,IAAc,gBAAwB;CAIvF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IAAQ,OAAa,GAAG,EAAM,KAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,MACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAMjD,SAAS,EAAW,GAAqB;CACrC,OAAO,EACF,QAAQ,MAAM,QAAQ,CACtB,QAAQ,MAAM,OAAO,CACrB,QAAQ,MAAM,OAAO,CACrB,QAAQ,MAAM,SAAS,CACvB,QAAQ,MAAM,QAAQ"}
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * SSG Client Runtime\n *\n * Client-side utilities for SSG sites:\n * - Hydration plugin\n * - Route prefetching\n * - Client-side navigation\n */\n\nexport { ssrClientPlugin } from '@sigx/server-renderer/client';\n\n/**\n * Prefetch a route's assets\n */\nexport function prefetch(path: string): void {\n // Create a link element for prefetching\n const link = document.createElement('link');\n link.rel = 'prefetch';\n link.href = path;\n document.head.appendChild(link);\n}\n\n/**\n * Setup prefetch on link hover\n */\nexport function setupPrefetch(options: { delay?: number } = {}): void {\n const { delay = 100 } = options;\n const prefetched = new Set<string>();\n\n document.addEventListener('mouseover', (event) => {\n const target = event.target as HTMLElement;\n const anchor = target.closest('a');\n\n if (!anchor) return;\n\n const href = anchor.getAttribute('href');\n if (!href || href.startsWith('http') || href.startsWith('#')) return;\n if (prefetched.has(href)) return;\n\n // Delay prefetch slightly to avoid unnecessary requests\n const timeoutId = setTimeout(() => {\n prefetched.add(href);\n prefetch(href);\n }, delay);\n\n anchor.addEventListener(\n 'mouseleave',\n () => clearTimeout(timeoutId),\n { once: true }\n );\n });\n}\n\n/**\n * Check if the page was statically generated\n */\nexport function isStaticPage(): boolean {\n return !document.documentElement.hasAttribute('data-ssr');\n}\n\n/**\n * Get initial state embedded in the page\n */\nexport function getInitialState<T = Record<string, unknown>>(): T | null {\n const script = document.getElementById('__SSG_STATE__');\n if (!script) return null;\n\n try {\n return JSON.parse(script.textContent || '');\n } catch {\n return null;\n }\n}\n"],"mappings":";;AAcA,SAAgB,EAAS,GAAoB;CAEzC,IAAM,IAAO,SAAS,cAAc,OAAO;CAG3C,AAFA,EAAK,MAAM,YACX,EAAK,OAAO,GACZ,SAAS,KAAK,YAAY,EAAK;;AAMnC,SAAgB,EAAc,IAA8B,EAAE,EAAQ;CAClE,IAAM,EAAE,WAAQ,QAAQ,GAClB,oBAAa,IAAI,KAAa;CAEpC,SAAS,iBAAiB,cAAc,MAAU;EAE9C,IAAM,IADS,EAAM,OACC,QAAQ,IAAI;EAElC,IAAI,CAAC,GAAQ;EAEb,IAAM,IAAO,EAAO,aAAa,OAAO;EAExC,IADI,CAAC,KAAQ,EAAK,WAAW,OAAO,IAAI,EAAK,WAAW,IAAI,IACxD,EAAW,IAAI,EAAK,EAAE;EAG1B,IAAM,IAAY,iBAAiB;GAE/B,AADA,EAAW,IAAI,EAAK,EACpB,EAAS,EAAK;KACf,EAAM;EAET,EAAO,iBACH,oBACM,aAAa,EAAU,EAC7B,EAAE,MAAM,IAAM,CACjB;GACH;;AAMN,SAAgB,IAAwB;CACpC,OAAO,CAAC,SAAS,gBAAgB,aAAa,WAAW;;AAM7D,SAAgB,IAAyD;CACrE,IAAM,IAAS,SAAS,eAAe,gBAAgB;CACvD,IAAI,CAAC,GAAQ,OAAO;CAEpB,IAAI;EACA,OAAO,KAAK,MAAM,EAAO,eAAe,GAAG;SACvC;EACJ,OAAO"}
|
package/dist/dev.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","names":[],"sources":["../src/dev.ts"],"sourcesContent":["/**\
|
|
1
|
+
{"version":3,"file":"dev.js","names":[],"sources":["../src/dev.ts"],"sourcesContent":["/**\n * SSG Dev Server\n *\n * Starts a Vite development server with SSG plugins pre-configured.\n * Provides a unified `ssg dev` command for zero-config development.\n */\n\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport type { SSGConfig } from './types';\nimport { loadConfig } from './config';\nimport { ssgPlugin } from './vite/plugin';\n\n/**\n * Dev server options\n */\nexport interface DevOptions {\n /**\n * Path to ssg.config.ts\n */\n configPath?: string;\n\n /**\n * Port to run dev server on\n * @default 5173\n */\n port?: number;\n\n /**\n * Host to bind to\n * @default 'localhost'\n */\n host?: string | boolean;\n\n /**\n * Open browser automatically\n * @default false\n */\n open?: boolean;\n\n /**\n * Enable verbose logging\n */\n verbose?: boolean;\n}\n\n/**\n * Start the SSG development server\n */\nexport async function dev(options: DevOptions = {}): Promise<void> {\n const root = process.cwd();\n\n console.log('\\nπ @sigx/ssg - Starting development server...\\n');\n\n // Load SSG config\n const ssgConfig = await loadConfig(options.configPath);\n\n // Check if user has a vite.config.ts\n const hasViteConfig = fs.existsSync(path.join(root, 'vite.config.ts')) ||\n fs.existsSync(path.join(root, 'vite.config.js')) ||\n fs.existsSync(path.join(root, 'vite.config.mjs'));\n\n // Import Vite\n const vite = await import('vite');\n\n if (hasViteConfig) {\n // User has their own vite.config - use it directly\n // They should have ssgPlugin() configured already\n console.log('π¦ Using existing vite.config\\n');\n\n const server = await vite.createServer({\n root,\n server: {\n port: options.port,\n host: options.host,\n open: options.open,\n },\n });\n\n await server.listen();\n server.printUrls();\n } else {\n // Zero-config mode - configure everything automatically\n console.log('π¦ Zero-config mode enabled\\n');\n\n // Try to import @sigx/vite plugin\n let sigxPlugin: ((...args: any[]) => any) | undefined;\n try {\n const sigxVite = await import('@sigx/vite');\n sigxPlugin = sigxVite.sigxPlugin;\n } catch {\n console.warn('β οΈ @sigx/vite not found, JSX transform may not work');\n console.warn(' Install with: npm install @sigx/vite\\n');\n }\n\n // Build plugins array\n const plugins: any[] = [];\n\n // Add Tailwind CSS if available\n try {\n // @ts-expect-error - Optional dependency\n const tailwind = await import('@tailwindcss/vite');\n plugins.push(tailwind.default());\n } catch {\n // Tailwind not installed, skip\n }\n\n // Add SignalX plugin if available\n if (sigxPlugin) {\n plugins.push(sigxPlugin());\n }\n\n // Add SSG plugin\n plugins.push(...ssgPlugin({ configPath: options.configPath }));\n\n const server = await vite.createServer({\n root,\n plugins,\n // Vite 8 uses oxc instead of esbuild for JSX transforms\n oxc: {\n jsx: {\n runtime: 'automatic',\n importSource: 'sigx',\n }\n },\n server: {\n port: options.port ?? 5173,\n host: options.host,\n open: options.open,\n },\n });\n\n await server.listen();\n server.printUrls();\n }\n}\n\n/**\n * Preview the production build\n */\nexport async function preview(options: DevOptions = {}): Promise<void> {\n const root = process.cwd();\n\n console.log('\\nπ @sigx/ssg - Preview server...\\n');\n\n const vite = await import('vite');\n\n const server = await vite.preview({\n root,\n preview: {\n port: options.port ?? 4173,\n host: options.host,\n open: options.open,\n },\n });\n\n server.printUrls();\n console.log('\\n');\n}\n"],"mappings":";;;;;AAiDA,eAAsB,EAAI,IAAsB,EAAE,EAAiB;CAC/D,IAAM,IAAO,QAAQ,KAAK;CAKR,AAHlB,QAAQ,IAAI,oDAAoD,EAG9C,MAAM,EAAW,EAAQ,WAAW;CAGtD,IAAM,IAAgB,EAAG,WAAW,EAAK,KAAK,GAAM,iBAAiB,CAAC,IAClE,EAAG,WAAW,EAAK,KAAK,GAAM,iBAAiB,CAAC,IAChD,EAAG,WAAW,EAAK,KAAK,GAAM,kBAAkB,CAAC,EAG/C,IAAO,MAAM,OAAO;CAE1B,IAAI,GAAe;EAGf,QAAQ,IAAI,kCAAkC;EAE9C,IAAM,IAAS,MAAM,EAAK,aAAa;GACnC;GACA,QAAQ;IACJ,MAAM,EAAQ;IACd,MAAM,EAAQ;IACd,MAAM,EAAQ;IACjB;GACJ,CAAC;EAGF,AADA,MAAM,EAAO,QAAQ,EACrB,EAAO,WAAW;QACf;EAEH,QAAQ,IAAI,gCAAgC;EAG5C,IAAI;EACJ,IAAI;GAEA,KAAa,MADU,OAAO,eACR;UAClB;GAEJ,AADA,QAAQ,KAAK,uDAAuD,EACpE,QAAQ,KAAK,4CAA4C;;EAI7D,IAAM,IAAiB,EAAE;EAGzB,IAAI;GAEA,IAAM,IAAW,MAAM,OAAO;GAC9B,EAAQ,KAAK,EAAS,SAAS,CAAC;UAC5B;EAUR,AALI,KACA,EAAQ,KAAK,GAAY,CAAC,EAI9B,EAAQ,KAAK,GAAG,EAAU,EAAE,YAAY,EAAQ,YAAY,CAAC,CAAC;EAE9D,IAAM,IAAS,MAAM,EAAK,aAAa;GACnC;GACA;GAEA,KAAK,EACD,KAAK;IACD,SAAS;IACT,cAAc;IACjB,EACJ;GACD,QAAQ;IACJ,MAAM,EAAQ,QAAQ;IACtB,MAAM,EAAQ;IACd,MAAM,EAAQ;IACjB;GACJ,CAAC;EAGF,AADA,MAAM,EAAO,QAAQ,EACrB,EAAO,WAAW;;;AAO1B,eAAsB,EAAQ,IAAsB,EAAE,EAAiB;CACnE,IAAM,IAAO,QAAQ,KAAK;CAgB1B,AAdA,QAAQ,IAAI,uCAAuC,GAanD,OATqB,MAFF,OAAO,SAEA,QAAQ;EAC9B;EACA,SAAS;GACL,MAAM,EAAQ,QAAQ;GACtB,MAAM,EAAQ;GACd,MAAM,EAAQ;GACjB;EACJ,CAAC,EAEK,WAAW,EAClB,QAAQ,IAAI,KAAK"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * SSG Error Classes and Utilities\n *\n * Provides structured error messages with file locations and suggestions\n * for common issues encountered during development and build.\n */\n\nimport path from 'node:path';\n\n/**\n * Base SSG error with enhanced formatting\n */\nexport class SSGError extends Error {\n readonly code: string;\n readonly file?: string;\n readonly line?: number;\n readonly suggestion?: string;\n\n constructor(\n message: string,\n options: {\n code: string;\n file?: string;\n line?: number;\n suggestion?: string;\n cause?: Error;\n }\n ) {\n super(message);\n this.name = 'SSGError';\n this.code = options.code;\n this.file = options.file;\n this.line = options.line;\n this.suggestion = options.suggestion;\n this.cause = options.cause;\n }\n\n /**\n * Format error for console output with colors\n */\n format(root?: string): string {\n const lines: string[] = [];\n \n // Header with error code\n lines.push(`\\nβ ${this.code}: ${this.message}\\n`);\n \n // File location\n if (this.file) {\n const displayPath = root ? path.relative(root, this.file) : this.file;\n if (this.line) {\n lines.push(` π ${displayPath}:${this.line}`);\n } else {\n lines.push(` π ${displayPath}`);\n }\n }\n \n // Suggestion\n if (this.suggestion) {\n lines.push(`\\n π‘ ${this.suggestion}`);\n }\n \n lines.push('');\n return lines.join('\\n');\n }\n}\n\n/**\n * Error codes for categorization\n */\nexport const ErrorCodes = {\n // Config errors\n CONFIG_NOT_FOUND: 'SSG001',\n CONFIG_INVALID: 'SSG002',\n CONFIG_THEME_NOT_FOUND: 'SSG003',\n \n // Route/Page errors\n PAGE_NOT_FOUND: 'SSG100',\n PAGE_INVALID_EXPORT: 'SSG101',\n DYNAMIC_ROUTE_NO_PATHS: 'SSG102',\n LAYOUT_NOT_FOUND: 'SSG103',\n \n // Build errors\n BUILD_RENDER_FAILED: 'SSG300',\n BUILD_VITE_FAILED: 'SSG301',\n \n // MDX errors\n MDX_PARSE_ERROR: 'SSG400',\n MDX_FRONTMATTER_ERROR: 'SSG401',\n} as const;\n\n// ============================================================================\n// Config Errors\n// ============================================================================\n\nexport function configNotFoundError(searchedPaths: string[]): SSGError {\n return new SSGError(\n 'No SSG configuration file found',\n {\n code: ErrorCodes.CONFIG_NOT_FOUND,\n suggestion: `Create ssg.config.ts in your project root:\\n\\n` +\n ` import { defineSSGConfig } from '@sigx/ssg';\\n` +\n ` export default defineSSGConfig({ site: { title: 'My Site' } });`,\n }\n );\n}\n\nexport function themeNotFoundError(themeName: string): SSGError {\n return new SSGError(\n `Theme package \"${themeName}\" not found`,\n {\n code: ErrorCodes.CONFIG_THEME_NOT_FOUND,\n suggestion: `Install the theme package:\\n\\n npm install ${themeName}`,\n }\n );\n}\n\n// ============================================================================\n// Route/Page Errors\n// ============================================================================\n\nexport function layoutNotFoundError(layoutName: string, pagePath: string, availableLayouts: string[]): SSGError {\n const available = availableLayouts.length > 0\n ? `Available layouts: ${availableLayouts.join(', ')}`\n : 'No layouts found. Create one in src/layouts/';\n \n return new SSGError(\n `Layout \"${layoutName}\" not found`,\n {\n code: ErrorCodes.LAYOUT_NOT_FOUND,\n file: pagePath,\n suggestion: `${available}\\n\\n To use a layout, set it in frontmatter:\\n ---\\n layout: default\\n ---`,\n }\n );\n}\n\nexport function dynamicRouteNoPaths(filePath: string, routePath: string): SSGError {\n return new SSGError(\n `Dynamic route has no getStaticPaths export`,\n {\n code: ErrorCodes.DYNAMIC_ROUTE_NO_PATHS,\n file: filePath,\n suggestion: `Dynamic routes like \"${routePath}\" require a getStaticPaths export:\\n\\n` +\n ` export async function getStaticPaths() {\\n` +\n ` return [{ params: { slug: 'example' } }];\\n` +\n ` }`,\n }\n );\n}\n\nexport function pageInvalidExport(filePath: string): SSGError {\n return new SSGError(\n `Page file has no default export`,\n {\n code: ErrorCodes.PAGE_INVALID_EXPORT,\n file: filePath,\n suggestion: `Pages must export a default component:\\n\\n` +\n ` export default component(() => {\\n` +\n ` return () => <div>Page content</div>;\\n` +\n ` });`,\n }\n );\n}\n\n// ============================================================================\n// Build Errors\n// ============================================================================\n\nexport function buildRenderError(path: string, error: Error): SSGError {\n return new SSGError(\n `Failed to render page: ${path}`,\n {\n code: ErrorCodes.BUILD_RENDER_FAILED,\n suggestion: `Check the error details below. Common causes:\\n` +\n ` - Runtime error in component code\\n` +\n ` - Missing dependencies during SSR\\n` +\n ` - Browser APIs used during server render`,\n cause: error,\n }\n );\n}\n\n// ============================================================================\n// MDX Errors\n// ============================================================================\n\nexport function mdxParseError(file: string, error: Error, line?: number): SSGError {\n return new SSGError(\n `Failed to parse MDX file`,\n {\n code: ErrorCodes.MDX_PARSE_ERROR,\n file,\n line,\n suggestion: `Check the MDX syntax. Common issues:\\n` +\n ` - Unclosed JSX tags\\n` +\n ` - Invalid JavaScript expressions\\n` +\n ` - Mixing HTML with JSX incorrectly`,\n cause: error,\n }\n );\n}\n\n// ============================================================================\n// Error Handler\n// ============================================================================\n\n/**\n * Format and log an SSG error with full context\n */\nexport function handleError(error: unknown, root?: string): never {\n if (error instanceof SSGError) {\n console.error(error.format(root));\n if (error.cause) {\n console.error(' Caused by:', error.cause);\n }\n } else if (error instanceof Error) {\n console.error(`\\nβ ${error.name}: ${error.message}\\n`);\n if (error.stack) {\n console.error(error.stack);\n }\n } else {\n console.error('\\nβ Unknown error:', error);\n }\n \n process.exit(1);\n}\n\n/**\n * Wrap an async function with error handling\n */\nexport function withErrorHandling<T>(\n fn: () => Promise<T>,\n root?: string\n): Promise<T> {\n return fn().catch((error) => {\n handleError(error, root);\n });\n}\n"],"mappings":";;;;;AAYA,IAAa,IAAb,cAA8B,MAAM;CAChC;CACA;CACA;CACA;CAEA,YACI,GACA,GAOF;EAOE,AANA,MAAM,EAAQ,EACd,KAAK,OAAO,YACZ,KAAK,OAAO,EAAQ,MACpB,KAAK,OAAO,EAAQ,MACpB,KAAK,OAAO,EAAQ,MACpB,KAAK,aAAa,EAAQ,YAC1B,KAAK,QAAQ,EAAQ;;CAMzB,OAAO,GAAuB;EAC1B,IAAM,IAAkB,EAAE;EAM1B,IAHA,EAAM,KAAK,OAAO,KAAK,KAAK,IAAI,KAAK,QAAQ,IAAI,EAG7C,KAAK,MAAM;GACX,IAAM,IAAc,IAAO,EAAK,SAAS,GAAM,KAAK,KAAK,GAAG,KAAK;GACjE,AAAI,KAAK,OACL,EAAM,KAAK,SAAS,EAAY,GAAG,KAAK,OAAO,GAE/C,EAAM,KAAK,SAAS,IAAc;;EAU1C,OALI,KAAK,cACL,EAAM,KAAK,WAAW,KAAK,aAAa,EAG5C,EAAM,KAAK,GAAG,EACP,EAAM,KAAK,KAAK;;GAOlB,IAAa;CAEtB,kBAAkB;CAClB,gBAAgB;CAChB,wBAAwB;CAGxB,gBAAgB;CAChB,qBAAqB;CACrB,wBAAwB;CACxB,kBAAkB;CAGlB,qBAAqB;CACrB,mBAAmB;CAGnB,iBAAiB;CACjB,uBAAuB;CAC1B;AAwHD,SAAgB,EAAY,GAAgB,GAAsB;CAe9D,AAdI,aAAiB,KACjB,QAAQ,MAAM,EAAM,OAAO,EAAK,CAAC,EAC7B,EAAM,SACN,QAAQ,MAAM,iBAAiB,EAAM,MAAM,IAExC,aAAiB,SACxB,QAAQ,MAAM,OAAO,EAAM,KAAK,IAAI,EAAM,QAAQ,IAAI,EAClD,EAAM,SACN,QAAQ,MAAM,EAAM,MAAM,IAG9B,QAAQ,MAAM,sBAAsB,EAAM,EAG9C,QAAQ,KAAK,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-EIAzPLvE.js","names":[],"sources":["../src/mdx/shiki.ts","../src/mdx/rehype-headings.ts","../src/mdx/plugin.ts","../src/vite/plugin.ts"],"sourcesContent":["/**\r\n * Shiki syntax highlighting integration\r\n *\r\n * Provides code block highlighting for Markdown/MDX content.\r\n */\r\n\r\nimport { createHighlighter, type Highlighter, type BundledLanguage, type BundledTheme } from 'shiki';\r\nimport type { ShikiConfig } from '../types';\r\n\r\n/**\r\n * Cached highlighter instance\r\n */\r\nlet highlighterPromise: Promise<Highlighter> | null = null;\r\n\r\n/**\r\n * Default Shiki configuration\r\n */\r\nconst DEFAULT_CONFIG: Required<ShikiConfig> = {\r\n light: 'github-light',\r\n dark: 'github-dark',\r\n langs: ['javascript', 'typescript', 'jsx', 'tsx', 'json', 'css', 'html', 'markdown', 'bash', 'shell'],\r\n};\r\n\r\n/**\r\n * Initialize or get the Shiki highlighter\r\n */\r\nexport async function getHighlighter(config?: ShikiConfig): Promise<Highlighter> {\r\n if (!highlighterPromise) {\r\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\r\n\r\n highlighterPromise = createHighlighter({\r\n themes: [mergedConfig.light as BundledTheme, mergedConfig.dark as BundledTheme],\r\n langs: mergedConfig.langs as BundledLanguage[],\r\n });\r\n }\r\n\r\n return highlighterPromise;\r\n}\r\n\r\n/**\r\n * Tab types for preview blocks\r\n */\r\nexport type TabType = 'preview' | 'code' | 'console';\r\n\r\n/**\r\n * Highlight code with Shiki\r\n */\r\nexport async function highlightCode(\r\n code: string,\r\n lang: string,\r\n config?: ShikiConfig,\r\n meta?: { filename?: string; live?: boolean; tabs?: TabType[] }\r\n): Promise<string> {\r\n const highlighter = await getHighlighter(config);\r\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\r\n\r\n // Check if language is loaded\r\n const loadedLangs = highlighter.getLoadedLanguages();\r\n const effectiveLang = loadedLangs.includes(lang as BundledLanguage) ? lang : 'text';\r\n\r\n // Generate HTML with both themes for CSS-based switching\r\n const codeHtml = highlighter.codeToHtml(code, {\r\n lang: effectiveLang as BundledLanguage,\r\n themes: {\r\n light: mergedConfig.light as BundledTheme,\r\n dark: mergedConfig.dark as BundledTheme,\r\n },\r\n });\r\n\r\n // Wrap in code-window structure\r\n const filename = meta?.filename ?? '';\r\n const isLive = meta?.live ?? false;\r\n const tabs = meta?.tabs; // undefined means no tabbed view, just code\r\n const hasTabs = tabs && tabs.length > 0;\r\n \r\n const filenameHtml = filename \r\n ? `<span class=\"code-window-filename\">${escapeHtml(filename)}</span>`\r\n : `<span class=\"code-window-lang\">${getLanguageLabel(effectiveLang)}</span>`;\r\n\r\n // For preview blocks (has tabs), render a LivePreview island component\r\n if (hasTabs) {\r\n const base64Code = encodeBase64(code);\r\n \r\n // Generate tab buttons HTML based on tabs array\r\n const firstTab = tabs[0];\r\n const tabButtonsHtml = tabs.map((tab, i) => {\r\n const label = tab.charAt(0).toUpperCase() + tab.slice(1);\r\n const isActive = i === 0;\r\n return `<button class=\"code-window-tab${isActive ? ' code-window-tab-active' : ''}\">${label}</button>`;\r\n }).join('\\n ');\r\n \r\n // Return an island marker that will be hydrated on the client\r\n // Use code-window styling for consistency with the nice terminal look\r\n const html = `<div \r\n class=\"live-preview-island\" \r\n data-island=\"LivePreview\" \r\n data-island-strategy=\"visible\"\r\n data-island-props=\"${escapeHtml(JSON.stringify({\r\n code: base64Code,\r\n highlightedCode: codeHtml,\r\n language: effectiveLang,\r\n filename: filename,\r\n tabs: tabs,\r\n live: isLive\r\n }))}\"\r\n>\r\n <div class=\"code-window code-window-live code-window-preview\">\r\n <div class=\"code-window-header\">\r\n <div class=\"code-window-header-left\">\r\n <div class=\"code-window-dots\">\r\n <span class=\"code-window-dot dot-red\"></span>\r\n <span class=\"code-window-dot dot-yellow\"></span>\r\n <span class=\"code-window-dot dot-green\"></span>\r\n </div>\r\n ${filenameHtml}\r\n </div>\r\n <div class=\"code-window-tabs\">\r\n ${tabButtonsHtml}\r\n </div>\r\n <button class=\"code-window-try-live\" disabled>β‘ Try Live</button>\r\n </div>\r\n <div class=\"code-window-preview-pane\"${firstTab !== 'preview' ? ' style=\"display:none;\"' : ''}>\r\n <div class=\"code-window-preview-loading\">\r\n <span class=\"code-window-spinner\"></span>\r\n Loading preview...\r\n </div>\r\n </div>\r\n <div class=\"code-window-console-pane\"${firstTab !== 'console' ? ' style=\"display:none;\"' : ''}>\r\n <div class=\"code-window-console-empty\">No console output</div>\r\n </div>\r\n <div class=\"code-window-content\"${firstTab !== 'code' ? ' style=\"display:none;\"' : ''}>\r\n ${codeHtml}\r\n </div>\r\n </div>\r\n</div>`;\r\n return html;\r\n }\r\n\r\n // Add \"Try Live\" button for live code blocks\r\n const tryLiveButton = isLive \r\n ? `<button class=\"code-window-try-live\" data-live-code=\"${escapeHtml(encodeBase64(code))}\" data-lang=\"${effectiveLang}\" data-filename=\"${escapeHtml(filename)}\" title=\"Open in Live Playground\">β‘ Try Live</button>`\r\n : '';\r\n\r\n const html = `<div class=\"code-window${isLive ? ' code-window-live' : ''}\">\r\n <div class=\"code-window-header\">\r\n <div class=\"code-window-header-left\">\r\n <div class=\"code-window-dots\">\r\n <span class=\"code-window-dot dot-red\"></span>\r\n <span class=\"code-window-dot dot-yellow\"></span>\r\n <span class=\"code-window-dot dot-green\"></span>\r\n </div>\r\n ${filenameHtml}\r\n </div>\r\n ${tryLiveButton}\r\n </div>\r\n <div class=\"code-window-content\">\r\n ${codeHtml}\r\n </div>\r\n </div>`;\r\n\r\n return html;\r\n}\r\n\r\n/**\r\n * Encode string to base64 (works in both Node.js and browser)\r\n */\r\nfunction encodeBase64(str: string): string {\r\n // Use Buffer in Node.js\r\n if (typeof Buffer !== 'undefined') {\r\n return Buffer.from(str, 'utf-8').toString('base64');\r\n }\r\n // Fallback for browser (shouldn't be needed during SSG build)\r\n return btoa(unescape(encodeURIComponent(str)));\r\n}\r\n\r\n/**\r\n * Get a display label for a language\r\n */\r\nfunction getLanguageLabel(lang: string): string {\r\n const labels: Record<string, string> = {\r\n 'tsx': 'TSX',\r\n 'jsx': 'JSX',\r\n 'ts': 'TypeScript',\r\n 'typescript': 'TypeScript',\r\n 'js': 'JavaScript',\r\n 'javascript': 'JavaScript',\r\n 'css': 'CSS',\r\n 'html': 'HTML',\r\n 'json': 'JSON',\r\n 'bash': 'Terminal',\r\n 'shell': 'Terminal',\r\n 'sh': 'Terminal',\r\n 'md': 'Markdown',\r\n 'markdown': 'Markdown',\r\n 'python': 'Python',\r\n 'py': 'Python',\r\n 'rust': 'Rust',\r\n 'go': 'Go',\r\n 'text': '',\r\n };\r\n return labels[lang.toLowerCase()] ?? lang.toUpperCase();\r\n}\r\n\r\n/**\r\n * Escape HTML special characters\r\n */\r\nfunction escapeHtml(str: string): string {\r\n return str\r\n .replace(/&/g, '&')\r\n .replace(/</g, '<')\r\n .replace(/>/g, '>')\r\n .replace(/\"/g, '"')\r\n .replace(/'/g, ''');\r\n}\r\n\r\n/**\r\n * Create a rehype plugin for Shiki\r\n */\r\nexport function rehypeShiki(config?: ShikiConfig) {\r\n return async (tree: any) => {\r\n const { visit } = await import('unist-util-visit');\r\n const { fromHtml } = await import('hast-util-from-html');\r\n\r\n const nodesToProcess: Array<{ node: any; parent: any; index: number }> = [];\r\n\r\n visit(tree, 'element', (node: any, index: number | undefined, parent: any) => {\r\n // Look for <pre><code> elements\r\n if (\r\n node.tagName === 'pre' &&\r\n node.children?.[0]?.tagName === 'code'\r\n ) {\r\n nodesToProcess.push({ node, parent, index: index ?? 0 });\r\n }\r\n });\r\n\r\n // Process nodes in parallel\r\n await Promise.all(\r\n nodesToProcess.map(async ({ node, parent, index }) => {\r\n const codeNode = node.children[0];\r\n\r\n // Extract language from class (e.g., \"language-typescript\")\r\n const className = codeNode.properties?.className?.[0] || '';\r\n const lang = className.replace(/^language-/, '') || 'text';\r\n\r\n // Extract filename from meta string if present\r\n // Supports: ```tsx filename=\"Counter.tsx\" or ```tsx title=\"Counter.tsx\"\r\n const metaString = codeNode.data?.meta || codeNode.properties?.metastring || '';\r\n const filename = extractMeta(metaString, 'filename') || extractMeta(metaString, 'title') || '';\r\n \r\n // Check for \"live\" flag in meta string (e.g., ```tsx live)\r\n const isLive = /\\blive\\b/i.test(metaString);\r\n \r\n // Parse tabs from meta string - order determines tab order\r\n // Supported keywords: preview, code, console\r\n // Example: ```tsx code preview console live -> tabs: [code, preview, console], with live button\r\n const tabKeywords = ['preview', 'code', 'console'] as const;\r\n const tabs: TabType[] = [];\r\n \r\n // Find all tab keywords and their positions\r\n const tabPositions: Array<{ tab: TabType; index: number }> = [];\r\n for (const keyword of tabKeywords) {\r\n const regex = new RegExp(`\\\\b${keyword}\\\\b`, 'i');\r\n const match = metaString.match(regex);\r\n if (match && match.index !== undefined) {\r\n tabPositions.push({ tab: keyword, index: match.index });\r\n }\r\n }\r\n \r\n // Sort by position (order of appearance in meta string)\r\n tabPositions.sort((a, b) => a.index - b.index);\r\n \r\n // Extract just the tab names in order\r\n for (const { tab } of tabPositions) {\r\n tabs.push(tab);\r\n }\r\n\r\n // Get raw code content\r\n const code = getTextContent(codeNode);\r\n\r\n // Highlight with Shiki (with meta info)\r\n // Only pass tabs if at least one tab keyword was found\r\n const html = await highlightCode(code.trim(), lang, config, { \r\n filename, \r\n live: isLive, \r\n tabs: tabs.length > 0 ? tabs : undefined \r\n });\r\n\r\n // Parse the HTML string into HAST nodes\r\n const fragment = fromHtml(html, { fragment: true });\r\n \r\n // Replace node with the parsed HAST fragment's children\r\n if (parent && typeof index === 'number' && fragment.children.length > 0) {\r\n // Use the first element from the fragment (should be the code-window div)\r\n parent.children[index] = fragment.children[0];\r\n }\r\n })\r\n );\r\n };\r\n}\r\n\r\n/**\r\n * Extract a meta value from a meta string\r\n * Supports: filename=\"value\" or filename='value' or filename=value\r\n */\r\nfunction extractMeta(metaString: string, key: string): string | null {\r\n if (!metaString) return null;\r\n \r\n // Match: key=\"value\" or key='value' or key=value\r\n const regex = new RegExp(`${key}=[\"']?([^\"'\\\\s]+)[\"']?`, 'i');\r\n const match = metaString.match(regex);\r\n return match ? match[1] : null;\r\n}\r\n\r\n/**\r\n * Extract text content from an AST node\r\n */\r\nfunction getTextContent(node: any): string {\r\n if (node.type === 'text') {\r\n return node.value;\r\n }\r\n\r\n if (node.children) {\r\n return node.children.map(getTextContent).join('');\r\n }\r\n\r\n return '';\r\n}\r\n\r\n/**\r\n * Load additional language on demand\r\n */\r\nexport async function loadLanguage(lang: string): Promise<void> {\r\n const highlighter = await getHighlighter();\r\n const loadedLangs = highlighter.getLoadedLanguages();\r\n\r\n if (!loadedLangs.includes(lang as BundledLanguage)) {\r\n try {\r\n await highlighter.loadLanguage(lang as BundledLanguage);\r\n } catch {\r\n console.warn(`Shiki: Language \"${lang}\" not available, using plain text`);\r\n }\r\n }\r\n}\r\n","/**\r\n * Rehype plugin to extract headings from MDX/MD content\r\n *\r\n * Extracts headings (h2-h6 by default) with their IDs and text content\r\n * for use in table of contents generation.\r\n */\r\n\r\nimport { visit } from 'unist-util-visit';\r\nimport { toString } from 'hast-util-to-string';\r\nimport type { TocHeading } from '../types';\r\n\r\n/**\r\n * Options for the rehype headings plugin\r\n */\r\nexport interface RehypeHeadingsOptions {\r\n /**\r\n * Minimum heading level to include (1-6)\r\n * @default 2\r\n */\r\n minLevel?: number;\r\n\r\n /**\r\n * Maximum heading level to include (1-6)\r\n * @default 3\r\n */\r\n maxLevel?: number;\r\n}\r\n\r\n/**\r\n * Rehype plugin to extract headings from the document\r\n *\r\n * Stores extracted headings in `file.data.headings` for later use.\r\n *\r\n * @example\r\n * ```ts\r\n * import { rehypeExtractHeadings } from './rehype-headings';\r\n *\r\n * // Use with unified\r\n * unified()\r\n * .use(rehypeSlug) // First add IDs to headings\r\n * .use(rehypeExtractHeadings, { minLevel: 2, maxLevel: 3 })\r\n * ```\r\n */\r\nexport function rehypeExtractHeadings(options: RehypeHeadingsOptions = {}) {\r\n const { minLevel = 2, maxLevel = 3 } = options;\r\n\r\n return (tree: any, file: any) => {\r\n const headings: TocHeading[] = [];\r\n\r\n visit(tree, 'element', (node: any) => {\r\n // Check if this is a heading element (h1-h6)\r\n const match = /^h([1-6])$/.exec(node.tagName);\r\n if (!match) return;\r\n\r\n const level = parseInt(match[1], 10);\r\n\r\n // Skip headings outside configured range\r\n if (level < minLevel || level > maxLevel) return;\r\n\r\n // Get the heading ID (should be set by rehype-slug)\r\n const id = node.properties?.id;\r\n if (!id) return;\r\n\r\n // Extract text content from the heading\r\n const text = toString(node).trim();\r\n if (!text) return;\r\n\r\n headings.push({ id, text, level });\r\n });\r\n\r\n // Store headings in file data for later access\r\n file.data = file.data || {};\r\n file.data.headings = headings;\r\n };\r\n}\r\n\r\nexport default rehypeExtractHeadings;\r\n","/**\r\n * MDX Vite plugin\r\n *\r\n * Transforms MDX files into SignalX components with:\r\n * - Frontmatter extraction\r\n * - Shiki syntax highlighting\r\n * - SignalX JSX runtime integration\r\n */\r\n\r\nimport type { Plugin, ResolvedConfig } from 'vite';\r\nimport type { SSGConfig, MarkdownConfig, PageMeta, TocHeading } from '../types';\r\nimport { parseFrontmatter, extractTitleFromContent } from './frontmatter';\r\nimport { rehypeShiki } from './shiki';\r\nimport { rehypeExtractHeadings } from './rehype-headings';\r\n\r\n/**\r\n * MDX plugin options\r\n */\r\nexport interface MDXPluginOptions {\r\n /**\r\n * Markdown configuration\r\n */\r\n markdown?: MarkdownConfig;\r\n\r\n /**\r\n * SSG configuration (for layout resolution)\r\n */\r\n ssgConfig?: SSGConfig;\r\n}\r\n\r\n/**\r\n * Create the MDX Vite plugin\r\n */\r\nexport function mdxPlugin(options: MDXPluginOptions = {}): Plugin {\r\n const { markdown = {} } = options;\r\n\r\n let mdxRollup: any;\r\n let viteConfig: ResolvedConfig;\r\n\r\n return {\r\n name: 'sigx-ssg-mdx',\r\n enforce: 'pre',\r\n\r\n async configResolved(config) {\r\n viteConfig = config;\r\n // Dynamically import @mdx-js/rollup\r\n const mdxModule = await import('@mdx-js/rollup');\r\n const remarkFrontmatter = (await import('remark-frontmatter')).default;\r\n const remarkMdxFrontmatter = (await import('remark-mdx-frontmatter')).default;\r\n const remarkGfm = (await import('remark-gfm')).default;\r\n const rehypeSlug = (await import('rehype-slug')).default;\r\n const rehypeAutolinkHeadings = (await import('rehype-autolink-headings')).default;\r\n\r\n // Get TOC config from SSG config\r\n const tocConfig = options.ssgConfig?.toc || { minLevel: 2, maxLevel: 3 };\r\n\r\n // Build rehype plugins array\r\n const rehypePlugins: any[] = [];\r\n\r\n // Add rehype-slug first to generate heading IDs\r\n rehypePlugins.push(rehypeSlug);\r\n\r\n // Add autolink headings (clickable anchor links)\r\n rehypePlugins.push([rehypeAutolinkHeadings, {\r\n behavior: 'append',\r\n properties: {\r\n class: 'heading-anchor',\r\n ariaHidden: true,\r\n tabIndex: -1,\r\n },\r\n content: {\r\n type: 'element',\r\n tagName: 'span',\r\n properties: { class: 'heading-anchor-icon' },\r\n children: [{ type: 'text', value: '#' }],\r\n },\r\n }]);\r\n\r\n // Add heading extraction for TOC\r\n rehypePlugins.push([rehypeExtractHeadings, tocConfig]);\r\n\r\n // Add Shiki if enabled\r\n if (markdown.shiki !== false) {\r\n const shikiConfig = typeof markdown.shiki === 'object' ? markdown.shiki : undefined;\r\n rehypePlugins.push([rehypeShiki, shikiConfig]);\r\n }\r\n\r\n // Add custom rehype plugins\r\n if (markdown.rehypePlugins) {\r\n rehypePlugins.push(...markdown.rehypePlugins);\r\n }\r\n\r\n // Build remark plugins array\r\n const remarkPlugins: any[] = [\r\n remarkFrontmatter,\r\n [remarkMdxFrontmatter, { name: 'frontmatter' }],\r\n remarkGfm,\r\n ];\r\n\r\n // Add custom remark plugins\r\n if (markdown.remarkPlugins) {\r\n remarkPlugins.push(...markdown.remarkPlugins);\r\n }\r\n\r\n // Create MDX plugin\r\n // Use jsx: false to output function calls instead of JSX syntax\r\n // This avoids needing esbuild to process .mdx files as JSX\r\n mdxRollup = mdxModule.default({\r\n jsx: false,\r\n jsxImportSource: 'sigx',\r\n remarkPlugins,\r\n rehypePlugins,\r\n providerImportSource: undefined,\r\n });\r\n },\r\n\r\n async transform(code, id) {\r\n // Only process MDX and MD files\r\n if (!/\\.mdx?$/.test(id)) {\r\n return null;\r\n }\r\n\r\n // Parse frontmatter first\r\n const { data: frontmatter, content } = parseFrontmatter(code);\r\n\r\n // Extract title from content if not in frontmatter\r\n if (!frontmatter.title) {\r\n const extractedTitle = extractTitleFromContent(content);\r\n if (extractedTitle) {\r\n frontmatter.title = extractedTitle;\r\n }\r\n }\r\n\r\n // Transform MDX content\r\n if (!mdxRollup?.transform) {\r\n throw new Error('MDX plugin not initialized');\r\n }\r\n\r\n const result = await mdxRollup.transform(code, id);\r\n\r\n if (!result) {\r\n return null;\r\n }\r\n\r\n // Extract headings from the file data (set by rehype-extract-headings)\r\n // Note: We need to process the content to get headings\r\n const headings = await extractHeadingsFromContent(content, options);\r\n\r\n // Create module ID for HMR tracking (normalize path separators)\r\n const moduleId = id.replace(/\\\\/g, '/');\r\n\r\n // Inject frontmatter export and wrap in SignalX component\r\n const transformedCode = wrapMDXComponent(\r\n result.code,\r\n frontmatter,\r\n headings,\r\n moduleId,\r\n viteConfig.command === 'serve'\r\n );\r\n\r\n return {\r\n code: transformedCode,\r\n map: result.map,\r\n };\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Wrap MDX output in a SignalX component\r\n * \r\n * Note: remark-mdx-frontmatter already exports `frontmatter`, so we only add the layout export\r\n * \r\n * In dev mode, we:\r\n * 1. Wrap MDXContent in a sigx component() for proper HMR tracking\r\n * 2. Inject HMR registration code so the component updates live\r\n */\r\nfunction wrapMDXComponent(\r\n code: string,\r\n frontmatter: PageMeta,\r\n headings: TocHeading[],\r\n moduleId: string,\r\n isDev: boolean\r\n): string {\r\n // The MDX output already includes frontmatter export from remark-mdx-frontmatter\r\n // We need to add the layout export for the SSG routing system\r\n \r\n // In dev mode, wrap in sigx component for HMR support\r\n if (isDev) {\r\n // Generate a component name from the file path for debugging\r\n const fileName = moduleId.split('/').pop()?.replace(/\\.mdx?$/, '') || 'MDXPage';\r\n const componentName = fileName.charAt(0).toUpperCase() + fileName.slice(1).replace(/[^a-zA-Z0-9]/g, '') + 'Page';\r\n \r\n // The MDX output has \"export default function MDXContent(...)\" \r\n // We need to:\r\n // 1. Remove the \"export default\" from MDXContent to avoid duplicate exports\r\n // 2. Wrap it in a sigx component for HMR\r\n // 3. Export the wrapped component as default\r\n const modifiedCode = code\r\n .replace(/export\\s+default\\s+function\\s+MDXContent/g, 'function _MDXContent')\r\n .replace(/export\\s+{\\s*MDXContent\\s+as\\s+default\\s*}/g, '');\r\n \r\n return `\r\nimport { registerHMRModule } from '@sigx/vite/hmr';\r\nimport { component as __component } from 'sigx';\r\nregisterHMRModule('${moduleId}');\r\n\r\n${modifiedCode}\r\n\r\n// Export layout from frontmatter for SSG routing\r\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\r\n\r\n// Export headings for table of contents\r\nexport const headings = ${JSON.stringify(headings)};\r\n\r\n// Wrap MDXContent in a sigx component for HMR support\r\nconst MDXPage = __component(() => {\r\n return () => _MDXContent({});\r\n}, { name: '${componentName}' });\r\n\r\nexport default MDXPage;\r\n\r\nif (import.meta.hot) {\r\n // Accept HMR updates with a callback to trigger re-render after module is updated\r\n import.meta.hot.accept((newModule) => {\r\n if (newModule) {\r\n // Notify LayoutRouter to clear its cache and re-render with new module\r\n window.dispatchEvent(new CustomEvent('sigx:mdx-hmr', { \r\n detail: { moduleId: '${moduleId}', newModule } \r\n }));\r\n }\r\n });\r\n}\r\n`;\r\n }\r\n \r\n // Production: just add exports without HMR wrapper\r\n return `\r\n${code}\r\n\r\n// Export layout from frontmatter for SSG routing\r\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\r\n\r\n// Export headings for table of contents\r\nexport const headings = ${JSON.stringify(headings)};\r\n`;\r\n}\r\n\r\n/**\r\n * Extract headings from markdown/MDX content\r\n */\r\nasync function extractHeadingsFromContent(\r\n content: string,\r\n options: MDXPluginOptions\r\n): Promise<TocHeading[]> {\r\n const { unified } = await import('unified');\r\n const remarkParse = (await import('remark-parse')).default;\r\n const remarkRehype = (await import('remark-rehype')).default;\r\n const rehypeSlug = (await import('rehype-slug')).default;\r\n const rehypeStringify = (await import('rehype-stringify')).default;\r\n\r\n // Get TOC config\r\n const tocConfig = options.ssgConfig?.toc || { minLevel: 2, maxLevel: 3 };\r\n\r\n // Process markdown to extract headings\r\n // Note: rehype-stringify is required for unified to have a compiler\r\n const processor = unified()\r\n .use(remarkParse)\r\n .use(remarkRehype)\r\n .use(rehypeSlug)\r\n .use(rehypeExtractHeadings, tocConfig)\r\n .use(rehypeStringify);\r\n\r\n const file = await processor.process(content);\r\n return (file.data as any).headings || [];\r\n}\r\n\r\n/**\r\n * Create a simple markdown-only plugin (no MDX features)\r\n */\r\nexport function markdownPlugin(options: MDXPluginOptions = {}): Plugin {\r\n return {\r\n name: 'sigx-ssg-markdown',\r\n enforce: 'pre',\r\n\r\n async transform(code, id) {\r\n // Only process .md files (not .mdx)\r\n if (!/\\.md$/.test(id) || /\\.mdx$/.test(id)) {\r\n return null;\r\n }\r\n\r\n // Parse frontmatter\r\n const { data: frontmatter, content } = parseFrontmatter(code);\r\n\r\n // Extract title if not in frontmatter\r\n if (!frontmatter.title) {\r\n const extractedTitle = extractTitleFromContent(content);\r\n if (extractedTitle) {\r\n frontmatter.title = extractedTitle;\r\n }\r\n }\r\n\r\n // Convert markdown to simple HTML using a lightweight parser\r\n // For full MD support, the MDX plugin should be used\r\n const html = await simpleMarkdownToHtml(content, options);\r\n \r\n // Extract headings for TOC\r\n const headings = await extractHeadingsFromContent(content, options);\r\n \r\n const frontmatterJSON = JSON.stringify(frontmatter);\r\n const headingsJSON = JSON.stringify(headings);\r\n\r\n return {\r\n code: `\r\nimport { jsx as _jsx } from 'sigx/jsx-runtime';\r\n\r\nexport const frontmatter = ${frontmatterJSON};\r\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\r\nexport const headings = ${headingsJSON};\r\n\r\nexport default function MDContent(props) {\r\n return _jsx('div', {\r\n class: 'markdown-content',\r\n dangerouslySetInnerHTML: { __html: ${JSON.stringify(html)} }\r\n });\r\n}\r\n`,\r\n map: null,\r\n };\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Simple markdown to HTML conversion\r\n * For basic markdown without custom components\r\n */\r\nasync function simpleMarkdownToHtml(markdown: string, options: MDXPluginOptions = {}): Promise<string> {\r\n // Use unified for basic markdown processing\r\n const { unified } = await import('unified');\r\n const remarkParse = (await import('remark-parse')).default;\r\n const remarkRehype = (await import('remark-rehype')).default;\r\n const rehypeSlug = (await import('rehype-slug')).default;\r\n const rehypeStringify = (await import('rehype-stringify')).default;\r\n\r\n const result = await unified()\r\n .use(remarkParse)\r\n .use(remarkRehype)\r\n .use(rehypeSlug) // Add IDs to headings\r\n .use(rehypeStringify)\r\n .process(markdown);\r\n\r\n return String(result);\r\n}\r\n","/**\r\n * SSG Vite Plugin\r\n *\r\n * Main Vite plugin for @sigx/ssg that integrates:\r\n * - File-based routing with virtual modules\r\n * - Layout system\r\n * - MDX processing\r\n * - HMR for development\r\n * - Zero-config entry point generation\r\n */\r\n\r\nimport type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';\r\nimport path from 'node:path';\r\nimport fs from 'node:fs';\r\nimport type { SSGConfig } from '../types';\r\nimport { defineSSGConfig, loadConfig } from '../config';\r\nimport { scanPages } from '../routing/scanner';\r\nimport { generateRoutesModule, generateLazyRoutesModule, VIRTUAL_ROUTES_ID, RESOLVED_VIRTUAL_ROUTES_ID } from '../routing/virtual';\r\nimport { generateNavigationModule, VIRTUAL_NAVIGATION_ID, RESOLVED_VIRTUAL_NAVIGATION_ID } from '../routing/virtual-navigation';\r\nimport { discoverLayouts } from '../layouts/resolver';\r\nimport { generateLayoutsModule, VIRTUAL_LAYOUTS_ID, RESOLVED_VIRTUAL_LAYOUTS_ID } from '../layouts/virtual';\r\nimport { mdxPlugin } from '../mdx/plugin';\r\nimport { parseFrontmatter } from '../mdx/frontmatter';\r\nimport {\r\n detectCustomEntries,\r\n generateClientEntry,\r\n generateServerEntry,\r\n generateHtmlTemplate,\r\n VIRTUAL_CLIENT_ID,\r\n RESOLVED_VIRTUAL_CLIENT_ID,\r\n VIRTUAL_SERVER_ID,\r\n RESOLVED_VIRTUAL_SERVER_ID,\r\n SSG_CLIENT_ENTRY_PATH,\r\n type EntryDetectionResult,\r\n} from './virtual-entries';\r\n\r\n/**\r\n * SSG Plugin options\r\n */\r\nexport interface SSGPluginOptions extends Partial<SSGConfig> {\r\n /**\r\n * Path to ssg.config.ts\r\n */\r\n configPath?: string;\r\n \r\n /**\r\n * Enable built-in MDX processing. Set to false if using external MDX plugin.\r\n * @default true\r\n */\r\n enableMdx?: boolean;\r\n}\r\n\r\n/**\r\n * Virtual module for SSG config\r\n */\r\nconst VIRTUAL_CONFIG_ID = 'virtual:ssg-config';\r\nconst RESOLVED_VIRTUAL_CONFIG_ID = '\\0' + VIRTUAL_CONFIG_ID;\r\n\r\n/**\r\n * Create the SSG Vite plugin\r\n */\r\nexport function ssgPlugin(options: SSGPluginOptions = {}): Plugin[] {\r\n let config: ResolvedConfig;\r\n let ssgConfig: SSGConfig;\r\n let root: string;\r\n let server: ViteDevServer | undefined;\r\n let entryDetection: EntryDetectionResult;\r\n\r\n // Cache for virtual modules\r\n let routesCache: { routes: any[]; code: string } | null = null;\r\n let layoutsCache: { layouts: any[]; code: string } | null = null;\r\n let navigationCache: { code: string } | null = null;\r\n \r\n // Cache for frontmatter hashes to detect changes\r\n const frontmatterHashCache = new Map<string, string>();\r\n\r\n const mainPlugin: Plugin = {\r\n name: 'sigx-ssg',\r\n enforce: 'pre',\r\n\r\n async configResolved(resolvedConfig) {\r\n config = resolvedConfig;\r\n root = resolvedConfig.root;\r\n\r\n // Load SSG config - always try to load from file first\r\n const fileConfig = await loadConfig(options.configPath);\r\n \r\n // Merge file config with plugin options (plugin options take precedence)\r\n ssgConfig = defineSSGConfig({\r\n ...fileConfig,\r\n ...options,\r\n });\r\n\r\n // Detect custom entry points\r\n entryDetection = detectCustomEntries(root, ssgConfig);\r\n\r\n // Log zero-config mode status\r\n if (entryDetection.useVirtualClient || entryDetection.useVirtualServer) {\r\n console.log('π¦ @sigx/ssg: Using zero-config mode');\r\n if (entryDetection.useVirtualClient) {\r\n console.log(' β Virtual client entry');\r\n }\r\n if (entryDetection.useVirtualServer) {\r\n console.log(' β Virtual server entry');\r\n }\r\n if (entryDetection.globalCssPath) {\r\n console.log(` β Auto-importing ${entryDetection.globalCssPath}`);\r\n }\r\n }\r\n },\r\n\r\n configureServer(devServer) {\r\n server = devServer;\r\n\r\n // Watch pages and layouts directories for changes\r\n const pagesDir = path.resolve(root, ssgConfig.pages || 'src/pages');\r\n const layoutsDir = path.resolve(root, ssgConfig.layouts || 'src/layouts');\r\n const contentDir = path.resolve(root, ssgConfig.content || 'src/content');\r\n\r\n // Clear caches and trigger HMR on file changes\r\n devServer.watcher.on('add', (file) => {\r\n if (file.startsWith(pagesDir)) {\r\n routesCache = null;\r\n navigationCache = null;\r\n invalidateModule(RESOLVED_VIRTUAL_ROUTES_ID);\r\n invalidateModule(RESOLVED_VIRTUAL_NAVIGATION_ID);\r\n } else if (file.startsWith(layoutsDir)) {\r\n layoutsCache = null;\r\n invalidateModule(RESOLVED_VIRTUAL_LAYOUTS_ID);\r\n }\r\n });\r\n\r\n devServer.watcher.on('unlink', (file) => {\r\n if (file.startsWith(pagesDir)) {\r\n routesCache = null;\r\n navigationCache = null;\r\n // Clean up frontmatter hash cache\r\n frontmatterHashCache.delete(file);\r\n invalidateModule(RESOLVED_VIRTUAL_ROUTES_ID);\r\n invalidateModule(RESOLVED_VIRTUAL_NAVIGATION_ID);\r\n } else if (file.startsWith(layoutsDir)) {\r\n layoutsCache = null;\r\n invalidateModule(RESOLVED_VIRTUAL_LAYOUTS_ID);\r\n }\r\n });\r\n\r\n // Handle MDX/MD file content changes for frontmatter updates\r\n devServer.watcher.on('change', async (file) => {\r\n if (!file.startsWith(pagesDir)) return;\r\n if (!/\\.mdx?$/.test(file)) return;\r\n \r\n try {\r\n const content = await fs.promises.readFile(file, 'utf-8');\r\n const { data: newFrontmatter } = parseFrontmatter(content);\r\n const newHash = JSON.stringify(newFrontmatter);\r\n const oldHash = frontmatterHashCache.get(file);\r\n \r\n // Update the cache\r\n frontmatterHashCache.set(file, newHash);\r\n \r\n // If frontmatter changed, invalidate navigation (titles, categories may have changed)\r\n if (oldHash !== undefined && oldHash !== newHash) {\r\n navigationCache = null;\r\n routesCache = null;\r\n \r\n const navMod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_NAVIGATION_ID);\r\n if (navMod) {\r\n devServer.moduleGraph.invalidateModule(navMod);\r\n }\r\n \r\n const routesMod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ROUTES_ID);\r\n if (routesMod) {\r\n devServer.moduleGraph.invalidateModule(routesMod);\r\n }\r\n \r\n // Send HMR update for navigation changes\r\n devServer.ws.send({ type: 'full-reload' });\r\n }\r\n } catch (err) {\r\n // File read error, ignore\r\n }\r\n });\r\n\r\n function invalidateModule(id: string) {\r\n const mod = devServer.moduleGraph.getModuleById(id);\r\n if (mod) {\r\n devServer.moduleGraph.invalidateModule(mod);\r\n devServer.ws.send({ type: 'full-reload' });\r\n }\r\n }\r\n\r\n // Serve virtual HTML template if no index.html exists\r\n if (entryDetection.useVirtualHtml) {\r\n devServer.middlewares.use((req, res, next) => {\r\n // Skip virtual modules and special Vite paths\r\n if (req.url?.startsWith('/@') || \r\n req.url?.startsWith('/__') || \r\n req.url?.includes('virtual:') ||\r\n req.url?.includes('node_modules') ||\r\n req.url?.startsWith('/@vite') ||\r\n req.url?.startsWith('/@fs')) {\r\n return next();\r\n }\r\n \r\n // Only handle requests for HTML pages (not assets with extensions)\r\n if (req.url && (req.url === '/' || !req.url.includes('.'))) {\r\n const html = generateHtmlTemplate(ssgConfig);\r\n // Transform HTML through Vite for HMR injection\r\n devServer.transformIndexHtml(req.url, html).then((transformedHtml) => {\r\n res.setHeader('Content-Type', 'text/html');\r\n res.end(transformedHtml);\r\n }).catch(next);\r\n return;\r\n }\r\n next();\r\n });\r\n }\r\n },\r\n\r\n resolveId(id) {\r\n // Handle virtual modules\r\n if (id === VIRTUAL_ROUTES_ID) {\r\n return RESOLVED_VIRTUAL_ROUTES_ID;\r\n }\r\n if (id === VIRTUAL_LAYOUTS_ID) {\r\n return RESOLVED_VIRTUAL_LAYOUTS_ID;\r\n }\r\n if (id === VIRTUAL_CONFIG_ID) {\r\n return RESOLVED_VIRTUAL_CONFIG_ID;\r\n }\r\n if (id === VIRTUAL_NAVIGATION_ID) {\r\n return RESOLVED_VIRTUAL_NAVIGATION_ID;\r\n }\r\n // Handle virtual entry points (both formats)\r\n if (id === VIRTUAL_CLIENT_ID || id === SSG_CLIENT_ENTRY_PATH) {\r\n return RESOLVED_VIRTUAL_CLIENT_ID;\r\n }\r\n if (id === VIRTUAL_SERVER_ID) {\r\n return RESOLVED_VIRTUAL_SERVER_ID;\r\n }\r\n return null;\r\n },\r\n\r\n async load(id) {\r\n // Generate virtual routes module\r\n if (id === RESOLVED_VIRTUAL_ROUTES_ID) {\r\n if (!routesCache) {\r\n const routes = await scanPages(ssgConfig, root);\r\n // Use lazy loading in dev mode for proper HMR and MDX processing\r\n const code = config.command === 'serve'\r\n ? generateLazyRoutesModule(routes, ssgConfig)\r\n : generateRoutesModule(routes, ssgConfig);\r\n routesCache = { routes, code };\r\n }\r\n return routesCache.code;\r\n }\r\n\r\n // Generate virtual layouts module\r\n if (id === RESOLVED_VIRTUAL_LAYOUTS_ID) {\r\n if (!layoutsCache) {\r\n const layouts = await discoverLayouts(ssgConfig, root);\r\n const code = generateLayoutsModule(layouts, ssgConfig);\r\n layoutsCache = { layouts, code };\r\n }\r\n return layoutsCache.code;\r\n }\r\n\r\n // Generate virtual navigation module\r\n if (id === RESOLVED_VIRTUAL_NAVIGATION_ID) {\r\n if (!navigationCache) {\r\n // Ensure routes are loaded (reuse cache if available)\r\n if (!routesCache) {\r\n const routes = await scanPages(ssgConfig, root);\r\n const routesCode = config.command === 'serve'\r\n ? generateLazyRoutesModule(routes, ssgConfig)\r\n : generateRoutesModule(routes, ssgConfig);\r\n routesCache = { routes, code: routesCode };\r\n }\r\n const isDev = config.command === 'serve';\r\n const code = generateNavigationModule(routesCache.routes, ssgConfig, isDev);\r\n navigationCache = { code };\r\n }\r\n return navigationCache.code;\r\n }\r\n\r\n // Generate virtual config module\r\n if (id === RESOLVED_VIRTUAL_CONFIG_ID) {\r\n return `export default ${JSON.stringify(ssgConfig)};`;\r\n }\r\n\r\n // Generate virtual client entry (needs JSX transform)\r\n if (id === RESOLVED_VIRTUAL_CLIENT_ID) {\r\n const code = generateClientEntry(ssgConfig, entryDetection);\r\n const esbuild = await import('esbuild');\r\n const result = await esbuild.transform(code, {\r\n loader: 'tsx',\r\n jsx: 'automatic',\r\n jsxImportSource: 'sigx',\r\n });\r\n return result.code;\r\n }\r\n\r\n // Generate virtual server entry (needs JSX transform)\r\n if (id === RESOLVED_VIRTUAL_SERVER_ID) {\r\n const code = generateServerEntry(ssgConfig);\r\n const esbuild = await import('esbuild');\r\n const result = await esbuild.transform(code, {\r\n loader: 'tsx',\r\n jsx: 'automatic',\r\n jsxImportSource: 'sigx',\r\n });\r\n return result.code;\r\n }\r\n\r\n return null;\r\n },\r\n\r\n // Handle HMR for layouts and pages\r\n async handleHotUpdate({ file, server }) {\r\n const layoutsDir = path.resolve(root, ssgConfig.layouts || 'src/layouts');\r\n const pagesDir = path.resolve(root, ssgConfig.pages || 'src/pages');\r\n\r\n if (file.startsWith(layoutsDir)) {\r\n // Clear layout cache\r\n layoutsCache = null;\r\n\r\n // Invalidate the virtual layouts module\r\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_LAYOUTS_ID);\r\n if (mod) {\r\n server.moduleGraph.invalidateModule(mod);\r\n }\r\n\r\n // Also reload pages that use this layout\r\n return [];\r\n }\r\n\r\n // Handle MDX/MD file changes in pages directory\r\n if (file.startsWith(pagesDir) && /\\.mdx?$/.test(file)) {\r\n // The MDX plugin handles the transform and HMR code injection.\r\n // We just need to ensure the module is properly invalidated.\r\n // Vite will handle the rest via the injected import.meta.hot.accept()\r\n \r\n // Return undefined to let Vite handle the standard HMR flow\r\n // The MDX file already has import.meta.hot.accept() injected\r\n return undefined;\r\n }\r\n\r\n return undefined;\r\n },\r\n };\r\n\r\n // Combine with MDX plugin if enabled (default: true)\r\n const enableMdx = options.enableMdx !== false;\r\n \r\n if (enableMdx) {\r\n const mdx = mdxPlugin({\r\n markdown: options.markdown,\r\n ssgConfig: undefined as any, // Will be set by configResolved\r\n });\r\n return [mainPlugin, mdx];\r\n }\r\n \r\n return [mainPlugin];\r\n}\r\n\r\n/**\r\n * Export the plugin as default\r\n */\r\nexport default ssgPlugin;\r\n"],"mappings":";;;;;;;AAYA,IAAI,IAAkD,MAKhD,IAAwC;CAC1C,OAAO;CACP,MAAM;CACN,OAAO;EAAC;EAAc;EAAc;EAAO;EAAO;EAAQ;EAAO;EAAQ;EAAY;EAAQ;EAAQ;CACxG;AAKD,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,iBAAiB,EAAI,EAIrC,EAAE;;AAIT,KAAK,WAAW,EAAS,IAAI,UAAU,KAAK,EAAK;;EAY5D;AAaD,QAVkB,EAAQ,cAAc,KAUjC,CAAC,EAAW,GAHR,CAAC,GAJI,EAAU;EAClB,UAAU,EAAQ;EAClB,WAAW,KAAA;EACd,CAAC,CACsB"}
|
|
1
|
+
{"version":3,"file":"plugin-EIAzPLvE.js","names":[],"sources":["../src/mdx/shiki.ts","../src/mdx/rehype-headings.ts","../src/mdx/plugin.ts","../src/vite/plugin.ts"],"sourcesContent":["/**\n * Shiki syntax highlighting integration\n *\n * Provides code block highlighting for Markdown/MDX content.\n */\n\nimport { createHighlighter, type Highlighter, type BundledLanguage, type BundledTheme } from 'shiki';\nimport type { ShikiConfig } from '../types';\n\n/**\n * Cached highlighter instance\n */\nlet highlighterPromise: Promise<Highlighter> | null = null;\n\n/**\n * Default Shiki configuration\n */\nconst DEFAULT_CONFIG: Required<ShikiConfig> = {\n light: 'github-light',\n dark: 'github-dark',\n langs: ['javascript', 'typescript', 'jsx', 'tsx', 'json', 'css', 'html', 'markdown', 'bash', 'shell'],\n};\n\n/**\n * Initialize or get the Shiki highlighter\n */\nexport async function getHighlighter(config?: ShikiConfig): Promise<Highlighter> {\n if (!highlighterPromise) {\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n\n highlighterPromise = createHighlighter({\n themes: [mergedConfig.light as BundledTheme, mergedConfig.dark as BundledTheme],\n langs: mergedConfig.langs as BundledLanguage[],\n });\n }\n\n return highlighterPromise;\n}\n\n/**\n * Tab types for preview blocks\n */\nexport type TabType = 'preview' | 'code' | 'console';\n\n/**\n * Highlight code with Shiki\n */\nexport async function highlightCode(\n code: string,\n lang: string,\n config?: ShikiConfig,\n meta?: { filename?: string; live?: boolean; tabs?: TabType[] }\n): Promise<string> {\n const highlighter = await getHighlighter(config);\n const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n\n // Check if language is loaded\n const loadedLangs = highlighter.getLoadedLanguages();\n const effectiveLang = loadedLangs.includes(lang as BundledLanguage) ? lang : 'text';\n\n // Generate HTML with both themes for CSS-based switching\n const codeHtml = highlighter.codeToHtml(code, {\n lang: effectiveLang as BundledLanguage,\n themes: {\n light: mergedConfig.light as BundledTheme,\n dark: mergedConfig.dark as BundledTheme,\n },\n });\n\n // Wrap in code-window structure\n const filename = meta?.filename ?? '';\n const isLive = meta?.live ?? false;\n const tabs = meta?.tabs; // undefined means no tabbed view, just code\n const hasTabs = tabs && tabs.length > 0;\n \n const filenameHtml = filename \n ? `<span class=\"code-window-filename\">${escapeHtml(filename)}</span>`\n : `<span class=\"code-window-lang\">${getLanguageLabel(effectiveLang)}</span>`;\n\n // For preview blocks (has tabs), render a LivePreview island component\n if (hasTabs) {\n const base64Code = encodeBase64(code);\n \n // Generate tab buttons HTML based on tabs array\n const firstTab = tabs[0];\n const tabButtonsHtml = tabs.map((tab, i) => {\n const label = tab.charAt(0).toUpperCase() + tab.slice(1);\n const isActive = i === 0;\n return `<button class=\"code-window-tab${isActive ? ' code-window-tab-active' : ''}\">${label}</button>`;\n }).join('\\n ');\n \n // Return an island marker that will be hydrated on the client\n // Use code-window styling for consistency with the nice terminal look\n const html = `<div \n class=\"live-preview-island\" \n data-island=\"LivePreview\" \n data-island-strategy=\"visible\"\n data-island-props=\"${escapeHtml(JSON.stringify({\n code: base64Code,\n highlightedCode: codeHtml,\n language: effectiveLang,\n filename: filename,\n tabs: tabs,\n live: isLive\n }))}\"\n>\n <div class=\"code-window code-window-live code-window-preview\">\n <div class=\"code-window-header\">\n <div class=\"code-window-header-left\">\n <div class=\"code-window-dots\">\n <span class=\"code-window-dot dot-red\"></span>\n <span class=\"code-window-dot dot-yellow\"></span>\n <span class=\"code-window-dot dot-green\"></span>\n </div>\n ${filenameHtml}\n </div>\n <div class=\"code-window-tabs\">\n ${tabButtonsHtml}\n </div>\n <button class=\"code-window-try-live\" disabled>β‘ Try Live</button>\n </div>\n <div class=\"code-window-preview-pane\"${firstTab !== 'preview' ? ' style=\"display:none;\"' : ''}>\n <div class=\"code-window-preview-loading\">\n <span class=\"code-window-spinner\"></span>\n Loading preview...\n </div>\n </div>\n <div class=\"code-window-console-pane\"${firstTab !== 'console' ? ' style=\"display:none;\"' : ''}>\n <div class=\"code-window-console-empty\">No console output</div>\n </div>\n <div class=\"code-window-content\"${firstTab !== 'code' ? ' style=\"display:none;\"' : ''}>\n ${codeHtml}\n </div>\n </div>\n</div>`;\n return html;\n }\n\n // Add \"Try Live\" button for live code blocks\n const tryLiveButton = isLive \n ? `<button class=\"code-window-try-live\" data-live-code=\"${escapeHtml(encodeBase64(code))}\" data-lang=\"${effectiveLang}\" data-filename=\"${escapeHtml(filename)}\" title=\"Open in Live Playground\">β‘ Try Live</button>`\n : '';\n\n const html = `<div class=\"code-window${isLive ? ' code-window-live' : ''}\">\n <div class=\"code-window-header\">\n <div class=\"code-window-header-left\">\n <div class=\"code-window-dots\">\n <span class=\"code-window-dot dot-red\"></span>\n <span class=\"code-window-dot dot-yellow\"></span>\n <span class=\"code-window-dot dot-green\"></span>\n </div>\n ${filenameHtml}\n </div>\n ${tryLiveButton}\n </div>\n <div class=\"code-window-content\">\n ${codeHtml}\n </div>\n </div>`;\n\n return html;\n}\n\n/**\n * Encode string to base64 (works in both Node.js and browser)\n */\nfunction encodeBase64(str: string): string {\n // Use Buffer in Node.js\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf-8').toString('base64');\n }\n // Fallback for browser (shouldn't be needed during SSG build)\n return btoa(unescape(encodeURIComponent(str)));\n}\n\n/**\n * Get a display label for a language\n */\nfunction getLanguageLabel(lang: string): string {\n const labels: Record<string, string> = {\n 'tsx': 'TSX',\n 'jsx': 'JSX',\n 'ts': 'TypeScript',\n 'typescript': 'TypeScript',\n 'js': 'JavaScript',\n 'javascript': 'JavaScript',\n 'css': 'CSS',\n 'html': 'HTML',\n 'json': 'JSON',\n 'bash': 'Terminal',\n 'shell': 'Terminal',\n 'sh': 'Terminal',\n 'md': 'Markdown',\n 'markdown': 'Markdown',\n 'python': 'Python',\n 'py': 'Python',\n 'rust': 'Rust',\n 'go': 'Go',\n 'text': '',\n };\n return labels[lang.toLowerCase()] ?? lang.toUpperCase();\n}\n\n/**\n * Escape HTML special characters\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Create a rehype plugin for Shiki\n */\nexport function rehypeShiki(config?: ShikiConfig) {\n return async (tree: any) => {\n const { visit } = await import('unist-util-visit');\n const { fromHtml } = await import('hast-util-from-html');\n\n const nodesToProcess: Array<{ node: any; parent: any; index: number }> = [];\n\n visit(tree, 'element', (node: any, index: number | undefined, parent: any) => {\n // Look for <pre><code> elements\n if (\n node.tagName === 'pre' &&\n node.children?.[0]?.tagName === 'code'\n ) {\n nodesToProcess.push({ node, parent, index: index ?? 0 });\n }\n });\n\n // Process nodes in parallel\n await Promise.all(\n nodesToProcess.map(async ({ node, parent, index }) => {\n const codeNode = node.children[0];\n\n // Extract language from class (e.g., \"language-typescript\")\n const className = codeNode.properties?.className?.[0] || '';\n const lang = className.replace(/^language-/, '') || 'text';\n\n // Extract filename from meta string if present\n // Supports: ```tsx filename=\"Counter.tsx\" or ```tsx title=\"Counter.tsx\"\n const metaString = codeNode.data?.meta || codeNode.properties?.metastring || '';\n const filename = extractMeta(metaString, 'filename') || extractMeta(metaString, 'title') || '';\n \n // Check for \"live\" flag in meta string (e.g., ```tsx live)\n const isLive = /\\blive\\b/i.test(metaString);\n \n // Parse tabs from meta string - order determines tab order\n // Supported keywords: preview, code, console\n // Example: ```tsx code preview console live -> tabs: [code, preview, console], with live button\n const tabKeywords = ['preview', 'code', 'console'] as const;\n const tabs: TabType[] = [];\n \n // Find all tab keywords and their positions\n const tabPositions: Array<{ tab: TabType; index: number }> = [];\n for (const keyword of tabKeywords) {\n const regex = new RegExp(`\\\\b${keyword}\\\\b`, 'i');\n const match = metaString.match(regex);\n if (match && match.index !== undefined) {\n tabPositions.push({ tab: keyword, index: match.index });\n }\n }\n \n // Sort by position (order of appearance in meta string)\n tabPositions.sort((a, b) => a.index - b.index);\n \n // Extract just the tab names in order\n for (const { tab } of tabPositions) {\n tabs.push(tab);\n }\n\n // Get raw code content\n const code = getTextContent(codeNode);\n\n // Highlight with Shiki (with meta info)\n // Only pass tabs if at least one tab keyword was found\n const html = await highlightCode(code.trim(), lang, config, { \n filename, \n live: isLive, \n tabs: tabs.length > 0 ? tabs : undefined \n });\n\n // Parse the HTML string into HAST nodes\n const fragment = fromHtml(html, { fragment: true });\n \n // Replace node with the parsed HAST fragment's children\n if (parent && typeof index === 'number' && fragment.children.length > 0) {\n // Use the first element from the fragment (should be the code-window div)\n parent.children[index] = fragment.children[0];\n }\n })\n );\n };\n}\n\n/**\n * Extract a meta value from a meta string\n * Supports: filename=\"value\" or filename='value' or filename=value\n */\nfunction extractMeta(metaString: string, key: string): string | null {\n if (!metaString) return null;\n \n // Match: key=\"value\" or key='value' or key=value\n const regex = new RegExp(`${key}=[\"']?([^\"'\\\\s]+)[\"']?`, 'i');\n const match = metaString.match(regex);\n return match ? match[1] : null;\n}\n\n/**\n * Extract text content from an AST node\n */\nfunction getTextContent(node: any): string {\n if (node.type === 'text') {\n return node.value;\n }\n\n if (node.children) {\n return node.children.map(getTextContent).join('');\n }\n\n return '';\n}\n\n/**\n * Load additional language on demand\n */\nexport async function loadLanguage(lang: string): Promise<void> {\n const highlighter = await getHighlighter();\n const loadedLangs = highlighter.getLoadedLanguages();\n\n if (!loadedLangs.includes(lang as BundledLanguage)) {\n try {\n await highlighter.loadLanguage(lang as BundledLanguage);\n } catch {\n console.warn(`Shiki: Language \"${lang}\" not available, using plain text`);\n }\n }\n}\n","/**\n * Rehype plugin to extract headings from MDX/MD content\n *\n * Extracts headings (h2-h6 by default) with their IDs and text content\n * for use in table of contents generation.\n */\n\nimport { visit } from 'unist-util-visit';\nimport { toString } from 'hast-util-to-string';\nimport type { TocHeading } from '../types';\n\n/**\n * Options for the rehype headings plugin\n */\nexport interface RehypeHeadingsOptions {\n /**\n * Minimum heading level to include (1-6)\n * @default 2\n */\n minLevel?: number;\n\n /**\n * Maximum heading level to include (1-6)\n * @default 3\n */\n maxLevel?: number;\n}\n\n/**\n * Rehype plugin to extract headings from the document\n *\n * Stores extracted headings in `file.data.headings` for later use.\n *\n * @example\n * ```ts\n * import { rehypeExtractHeadings } from './rehype-headings';\n *\n * // Use with unified\n * unified()\n * .use(rehypeSlug) // First add IDs to headings\n * .use(rehypeExtractHeadings, { minLevel: 2, maxLevel: 3 })\n * ```\n */\nexport function rehypeExtractHeadings(options: RehypeHeadingsOptions = {}) {\n const { minLevel = 2, maxLevel = 3 } = options;\n\n return (tree: any, file: any) => {\n const headings: TocHeading[] = [];\n\n visit(tree, 'element', (node: any) => {\n // Check if this is a heading element (h1-h6)\n const match = /^h([1-6])$/.exec(node.tagName);\n if (!match) return;\n\n const level = parseInt(match[1], 10);\n\n // Skip headings outside configured range\n if (level < minLevel || level > maxLevel) return;\n\n // Get the heading ID (should be set by rehype-slug)\n const id = node.properties?.id;\n if (!id) return;\n\n // Extract text content from the heading\n const text = toString(node).trim();\n if (!text) return;\n\n headings.push({ id, text, level });\n });\n\n // Store headings in file data for later access\n file.data = file.data || {};\n file.data.headings = headings;\n };\n}\n\nexport default rehypeExtractHeadings;\n","/**\n * MDX Vite plugin\n *\n * Transforms MDX files into SignalX components with:\n * - Frontmatter extraction\n * - Shiki syntax highlighting\n * - SignalX JSX runtime integration\n */\n\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { SSGConfig, MarkdownConfig, PageMeta, TocHeading } from '../types';\nimport { parseFrontmatter, extractTitleFromContent } from './frontmatter';\nimport { rehypeShiki } from './shiki';\nimport { rehypeExtractHeadings } from './rehype-headings';\n\n/**\n * MDX plugin options\n */\nexport interface MDXPluginOptions {\n /**\n * Markdown configuration\n */\n markdown?: MarkdownConfig;\n\n /**\n * SSG configuration (for layout resolution)\n */\n ssgConfig?: SSGConfig;\n}\n\n/**\n * Create the MDX Vite plugin\n */\nexport function mdxPlugin(options: MDXPluginOptions = {}): Plugin {\n const { markdown = {} } = options;\n\n let mdxRollup: any;\n let viteConfig: ResolvedConfig;\n\n return {\n name: 'sigx-ssg-mdx',\n enforce: 'pre',\n\n async configResolved(config) {\n viteConfig = config;\n // Dynamically import @mdx-js/rollup\n const mdxModule = await import('@mdx-js/rollup');\n const remarkFrontmatter = (await import('remark-frontmatter')).default;\n const remarkMdxFrontmatter = (await import('remark-mdx-frontmatter')).default;\n const remarkGfm = (await import('remark-gfm')).default;\n const rehypeSlug = (await import('rehype-slug')).default;\n const rehypeAutolinkHeadings = (await import('rehype-autolink-headings')).default;\n\n // Get TOC config from SSG config\n const tocConfig = options.ssgConfig?.toc || { minLevel: 2, maxLevel: 3 };\n\n // Build rehype plugins array\n const rehypePlugins: any[] = [];\n\n // Add rehype-slug first to generate heading IDs\n rehypePlugins.push(rehypeSlug);\n\n // Add autolink headings (clickable anchor links)\n rehypePlugins.push([rehypeAutolinkHeadings, {\n behavior: 'append',\n properties: {\n class: 'heading-anchor',\n ariaHidden: true,\n tabIndex: -1,\n },\n content: {\n type: 'element',\n tagName: 'span',\n properties: { class: 'heading-anchor-icon' },\n children: [{ type: 'text', value: '#' }],\n },\n }]);\n\n // Add heading extraction for TOC\n rehypePlugins.push([rehypeExtractHeadings, tocConfig]);\n\n // Add Shiki if enabled\n if (markdown.shiki !== false) {\n const shikiConfig = typeof markdown.shiki === 'object' ? markdown.shiki : undefined;\n rehypePlugins.push([rehypeShiki, shikiConfig]);\n }\n\n // Add custom rehype plugins\n if (markdown.rehypePlugins) {\n rehypePlugins.push(...markdown.rehypePlugins);\n }\n\n // Build remark plugins array\n const remarkPlugins: any[] = [\n remarkFrontmatter,\n [remarkMdxFrontmatter, { name: 'frontmatter' }],\n remarkGfm,\n ];\n\n // Add custom remark plugins\n if (markdown.remarkPlugins) {\n remarkPlugins.push(...markdown.remarkPlugins);\n }\n\n // Create MDX plugin\n // Use jsx: false to output function calls instead of JSX syntax\n // This avoids needing esbuild to process .mdx files as JSX\n mdxRollup = mdxModule.default({\n jsx: false,\n jsxImportSource: 'sigx',\n remarkPlugins,\n rehypePlugins,\n providerImportSource: undefined,\n });\n },\n\n async transform(code, id) {\n // Only process MDX and MD files\n if (!/\\.mdx?$/.test(id)) {\n return null;\n }\n\n // Parse frontmatter first\n const { data: frontmatter, content } = parseFrontmatter(code);\n\n // Extract title from content if not in frontmatter\n if (!frontmatter.title) {\n const extractedTitle = extractTitleFromContent(content);\n if (extractedTitle) {\n frontmatter.title = extractedTitle;\n }\n }\n\n // Transform MDX content\n if (!mdxRollup?.transform) {\n throw new Error('MDX plugin not initialized');\n }\n\n const result = await mdxRollup.transform(code, id);\n\n if (!result) {\n return null;\n }\n\n // Extract headings from the file data (set by rehype-extract-headings)\n // Note: We need to process the content to get headings\n const headings = await extractHeadingsFromContent(content, options);\n\n // Create module ID for HMR tracking (normalize path separators)\n const moduleId = id.replace(/\\\\/g, '/');\n\n // Inject frontmatter export and wrap in SignalX component\n const transformedCode = wrapMDXComponent(\n result.code,\n frontmatter,\n headings,\n moduleId,\n viteConfig.command === 'serve'\n );\n\n return {\n code: transformedCode,\n map: result.map,\n };\n },\n };\n}\n\n/**\n * Wrap MDX output in a SignalX component\n * \n * Note: remark-mdx-frontmatter already exports `frontmatter`, so we only add the layout export\n * \n * In dev mode, we:\n * 1. Wrap MDXContent in a sigx component() for proper HMR tracking\n * 2. Inject HMR registration code so the component updates live\n */\nfunction wrapMDXComponent(\n code: string,\n frontmatter: PageMeta,\n headings: TocHeading[],\n moduleId: string,\n isDev: boolean\n): string {\n // The MDX output already includes frontmatter export from remark-mdx-frontmatter\n // We need to add the layout export for the SSG routing system\n \n // In dev mode, wrap in sigx component for HMR support\n if (isDev) {\n // Generate a component name from the file path for debugging\n const fileName = moduleId.split('/').pop()?.replace(/\\.mdx?$/, '') || 'MDXPage';\n const componentName = fileName.charAt(0).toUpperCase() + fileName.slice(1).replace(/[^a-zA-Z0-9]/g, '') + 'Page';\n \n // The MDX output has \"export default function MDXContent(...)\" \n // We need to:\n // 1. Remove the \"export default\" from MDXContent to avoid duplicate exports\n // 2. Wrap it in a sigx component for HMR\n // 3. Export the wrapped component as default\n const modifiedCode = code\n .replace(/export\\s+default\\s+function\\s+MDXContent/g, 'function _MDXContent')\n .replace(/export\\s+{\\s*MDXContent\\s+as\\s+default\\s*}/g, '');\n \n return `\nimport { registerHMRModule } from '@sigx/vite/hmr';\nimport { component as __component } from 'sigx';\nregisterHMRModule('${moduleId}');\n\n${modifiedCode}\n\n// Export layout from frontmatter for SSG routing\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\n\n// Export headings for table of contents\nexport const headings = ${JSON.stringify(headings)};\n\n// Wrap MDXContent in a sigx component for HMR support\nconst MDXPage = __component(() => {\n return () => _MDXContent({});\n}, { name: '${componentName}' });\n\nexport default MDXPage;\n\nif (import.meta.hot) {\n // Accept HMR updates with a callback to trigger re-render after module is updated\n import.meta.hot.accept((newModule) => {\n if (newModule) {\n // Notify LayoutRouter to clear its cache and re-render with new module\n window.dispatchEvent(new CustomEvent('sigx:mdx-hmr', { \n detail: { moduleId: '${moduleId}', newModule } \n }));\n }\n });\n}\n`;\n }\n \n // Production: just add exports without HMR wrapper\n return `\n${code}\n\n// Export layout from frontmatter for SSG routing\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\n\n// Export headings for table of contents\nexport const headings = ${JSON.stringify(headings)};\n`;\n}\n\n/**\n * Extract headings from markdown/MDX content\n */\nasync function extractHeadingsFromContent(\n content: string,\n options: MDXPluginOptions\n): Promise<TocHeading[]> {\n const { unified } = await import('unified');\n const remarkParse = (await import('remark-parse')).default;\n const remarkRehype = (await import('remark-rehype')).default;\n const rehypeSlug = (await import('rehype-slug')).default;\n const rehypeStringify = (await import('rehype-stringify')).default;\n\n // Get TOC config\n const tocConfig = options.ssgConfig?.toc || { minLevel: 2, maxLevel: 3 };\n\n // Process markdown to extract headings\n // Note: rehype-stringify is required for unified to have a compiler\n const processor = unified()\n .use(remarkParse)\n .use(remarkRehype)\n .use(rehypeSlug)\n .use(rehypeExtractHeadings, tocConfig)\n .use(rehypeStringify);\n\n const file = await processor.process(content);\n return (file.data as any).headings || [];\n}\n\n/**\n * Create a simple markdown-only plugin (no MDX features)\n */\nexport function markdownPlugin(options: MDXPluginOptions = {}): Plugin {\n return {\n name: 'sigx-ssg-markdown',\n enforce: 'pre',\n\n async transform(code, id) {\n // Only process .md files (not .mdx)\n if (!/\\.md$/.test(id) || /\\.mdx$/.test(id)) {\n return null;\n }\n\n // Parse frontmatter\n const { data: frontmatter, content } = parseFrontmatter(code);\n\n // Extract title if not in frontmatter\n if (!frontmatter.title) {\n const extractedTitle = extractTitleFromContent(content);\n if (extractedTitle) {\n frontmatter.title = extractedTitle;\n }\n }\n\n // Convert markdown to simple HTML using a lightweight parser\n // For full MD support, the MDX plugin should be used\n const html = await simpleMarkdownToHtml(content, options);\n \n // Extract headings for TOC\n const headings = await extractHeadingsFromContent(content, options);\n \n const frontmatterJSON = JSON.stringify(frontmatter);\n const headingsJSON = JSON.stringify(headings);\n\n return {\n code: `\nimport { jsx as _jsx } from 'sigx/jsx-runtime';\n\nexport const frontmatter = ${frontmatterJSON};\nexport const layout = ${frontmatter.layout ? JSON.stringify(frontmatter.layout) : 'undefined'};\nexport const headings = ${headingsJSON};\n\nexport default function MDContent(props) {\n return _jsx('div', {\n class: 'markdown-content',\n dangerouslySetInnerHTML: { __html: ${JSON.stringify(html)} }\n });\n}\n`,\n map: null,\n };\n },\n };\n}\n\n/**\n * Simple markdown to HTML conversion\n * For basic markdown without custom components\n */\nasync function simpleMarkdownToHtml(markdown: string, options: MDXPluginOptions = {}): Promise<string> {\n // Use unified for basic markdown processing\n const { unified } = await import('unified');\n const remarkParse = (await import('remark-parse')).default;\n const remarkRehype = (await import('remark-rehype')).default;\n const rehypeSlug = (await import('rehype-slug')).default;\n const rehypeStringify = (await import('rehype-stringify')).default;\n\n const result = await unified()\n .use(remarkParse)\n .use(remarkRehype)\n .use(rehypeSlug) // Add IDs to headings\n .use(rehypeStringify)\n .process(markdown);\n\n return String(result);\n}\n","/**\n * SSG Vite Plugin\n *\n * Main Vite plugin for @sigx/ssg that integrates:\n * - File-based routing with virtual modules\n * - Layout system\n * - MDX processing\n * - HMR for development\n * - Zero-config entry point generation\n */\n\nimport type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport type { SSGConfig } from '../types';\nimport { defineSSGConfig, loadConfig } from '../config';\nimport { scanPages } from '../routing/scanner';\nimport { generateRoutesModule, generateLazyRoutesModule, VIRTUAL_ROUTES_ID, RESOLVED_VIRTUAL_ROUTES_ID } from '../routing/virtual';\nimport { generateNavigationModule, VIRTUAL_NAVIGATION_ID, RESOLVED_VIRTUAL_NAVIGATION_ID } from '../routing/virtual-navigation';\nimport { discoverLayouts } from '../layouts/resolver';\nimport { generateLayoutsModule, VIRTUAL_LAYOUTS_ID, RESOLVED_VIRTUAL_LAYOUTS_ID } from '../layouts/virtual';\nimport { mdxPlugin } from '../mdx/plugin';\nimport { parseFrontmatter } from '../mdx/frontmatter';\nimport {\n detectCustomEntries,\n generateClientEntry,\n generateServerEntry,\n generateHtmlTemplate,\n VIRTUAL_CLIENT_ID,\n RESOLVED_VIRTUAL_CLIENT_ID,\n VIRTUAL_SERVER_ID,\n RESOLVED_VIRTUAL_SERVER_ID,\n SSG_CLIENT_ENTRY_PATH,\n type EntryDetectionResult,\n} from './virtual-entries';\n\n/**\n * SSG Plugin options\n */\nexport interface SSGPluginOptions extends Partial<SSGConfig> {\n /**\n * Path to ssg.config.ts\n */\n configPath?: string;\n \n /**\n * Enable built-in MDX processing. Set to false if using external MDX plugin.\n * @default true\n */\n enableMdx?: boolean;\n}\n\n/**\n * Virtual module for SSG config\n */\nconst VIRTUAL_CONFIG_ID = 'virtual:ssg-config';\nconst RESOLVED_VIRTUAL_CONFIG_ID = '\\0' + VIRTUAL_CONFIG_ID;\n\n/**\n * Create the SSG Vite plugin\n */\nexport function ssgPlugin(options: SSGPluginOptions = {}): Plugin[] {\n let config: ResolvedConfig;\n let ssgConfig: SSGConfig;\n let root: string;\n let server: ViteDevServer | undefined;\n let entryDetection: EntryDetectionResult;\n\n // Cache for virtual modules\n let routesCache: { routes: any[]; code: string } | null = null;\n let layoutsCache: { layouts: any[]; code: string } | null = null;\n let navigationCache: { code: string } | null = null;\n \n // Cache for frontmatter hashes to detect changes\n const frontmatterHashCache = new Map<string, string>();\n\n const mainPlugin: Plugin = {\n name: 'sigx-ssg',\n enforce: 'pre',\n\n async configResolved(resolvedConfig) {\n config = resolvedConfig;\n root = resolvedConfig.root;\n\n // Load SSG config - always try to load from file first\n const fileConfig = await loadConfig(options.configPath);\n \n // Merge file config with plugin options (plugin options take precedence)\n ssgConfig = defineSSGConfig({\n ...fileConfig,\n ...options,\n });\n\n // Detect custom entry points\n entryDetection = detectCustomEntries(root, ssgConfig);\n\n // Log zero-config mode status\n if (entryDetection.useVirtualClient || entryDetection.useVirtualServer) {\n console.log('π¦ @sigx/ssg: Using zero-config mode');\n if (entryDetection.useVirtualClient) {\n console.log(' β Virtual client entry');\n }\n if (entryDetection.useVirtualServer) {\n console.log(' β Virtual server entry');\n }\n if (entryDetection.globalCssPath) {\n console.log(` β Auto-importing ${entryDetection.globalCssPath}`);\n }\n }\n },\n\n configureServer(devServer) {\n server = devServer;\n\n // Watch pages and layouts directories for changes\n const pagesDir = path.resolve(root, ssgConfig.pages || 'src/pages');\n const layoutsDir = path.resolve(root, ssgConfig.layouts || 'src/layouts');\n const contentDir = path.resolve(root, ssgConfig.content || 'src/content');\n\n // Clear caches and trigger HMR on file changes\n devServer.watcher.on('add', (file) => {\n if (file.startsWith(pagesDir)) {\n routesCache = null;\n navigationCache = null;\n invalidateModule(RESOLVED_VIRTUAL_ROUTES_ID);\n invalidateModule(RESOLVED_VIRTUAL_NAVIGATION_ID);\n } else if (file.startsWith(layoutsDir)) {\n layoutsCache = null;\n invalidateModule(RESOLVED_VIRTUAL_LAYOUTS_ID);\n }\n });\n\n devServer.watcher.on('unlink', (file) => {\n if (file.startsWith(pagesDir)) {\n routesCache = null;\n navigationCache = null;\n // Clean up frontmatter hash cache\n frontmatterHashCache.delete(file);\n invalidateModule(RESOLVED_VIRTUAL_ROUTES_ID);\n invalidateModule(RESOLVED_VIRTUAL_NAVIGATION_ID);\n } else if (file.startsWith(layoutsDir)) {\n layoutsCache = null;\n invalidateModule(RESOLVED_VIRTUAL_LAYOUTS_ID);\n }\n });\n\n // Handle MDX/MD file content changes for frontmatter updates\n devServer.watcher.on('change', async (file) => {\n if (!file.startsWith(pagesDir)) return;\n if (!/\\.mdx?$/.test(file)) return;\n \n try {\n const content = await fs.promises.readFile(file, 'utf-8');\n const { data: newFrontmatter } = parseFrontmatter(content);\n const newHash = JSON.stringify(newFrontmatter);\n const oldHash = frontmatterHashCache.get(file);\n \n // Update the cache\n frontmatterHashCache.set(file, newHash);\n \n // If frontmatter changed, invalidate navigation (titles, categories may have changed)\n if (oldHash !== undefined && oldHash !== newHash) {\n navigationCache = null;\n routesCache = null;\n \n const navMod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_NAVIGATION_ID);\n if (navMod) {\n devServer.moduleGraph.invalidateModule(navMod);\n }\n \n const routesMod = devServer.moduleGraph.getModuleById(RESOLVED_VIRTUAL_ROUTES_ID);\n if (routesMod) {\n devServer.moduleGraph.invalidateModule(routesMod);\n }\n \n // Send HMR update for navigation changes\n devServer.ws.send({ type: 'full-reload' });\n }\n } catch (err) {\n // File read error, ignore\n }\n });\n\n function invalidateModule(id: string) {\n const mod = devServer.moduleGraph.getModuleById(id);\n if (mod) {\n devServer.moduleGraph.invalidateModule(mod);\n devServer.ws.send({ type: 'full-reload' });\n }\n }\n\n // Serve virtual HTML template if no index.html exists\n if (entryDetection.useVirtualHtml) {\n devServer.middlewares.use((req, res, next) => {\n // Skip virtual modules and special Vite paths\n if (req.url?.startsWith('/@') || \n req.url?.startsWith('/__') || \n req.url?.includes('virtual:') ||\n req.url?.includes('node_modules') ||\n req.url?.startsWith('/@vite') ||\n req.url?.startsWith('/@fs')) {\n return next();\n }\n \n // Only handle requests for HTML pages (not assets with extensions)\n if (req.url && (req.url === '/' || !req.url.includes('.'))) {\n const html = generateHtmlTemplate(ssgConfig);\n // Transform HTML through Vite for HMR injection\n devServer.transformIndexHtml(req.url, html).then((transformedHtml) => {\n res.setHeader('Content-Type', 'text/html');\n res.end(transformedHtml);\n }).catch(next);\n return;\n }\n next();\n });\n }\n },\n\n resolveId(id) {\n // Handle virtual modules\n if (id === VIRTUAL_ROUTES_ID) {\n return RESOLVED_VIRTUAL_ROUTES_ID;\n }\n if (id === VIRTUAL_LAYOUTS_ID) {\n return RESOLVED_VIRTUAL_LAYOUTS_ID;\n }\n if (id === VIRTUAL_CONFIG_ID) {\n return RESOLVED_VIRTUAL_CONFIG_ID;\n }\n if (id === VIRTUAL_NAVIGATION_ID) {\n return RESOLVED_VIRTUAL_NAVIGATION_ID;\n }\n // Handle virtual entry points (both formats)\n if (id === VIRTUAL_CLIENT_ID || id === SSG_CLIENT_ENTRY_PATH) {\n return RESOLVED_VIRTUAL_CLIENT_ID;\n }\n if (id === VIRTUAL_SERVER_ID) {\n return RESOLVED_VIRTUAL_SERVER_ID;\n }\n return null;\n },\n\n async load(id) {\n // Generate virtual routes module\n if (id === RESOLVED_VIRTUAL_ROUTES_ID) {\n if (!routesCache) {\n const routes = await scanPages(ssgConfig, root);\n // Use lazy loading in dev mode for proper HMR and MDX processing\n const code = config.command === 'serve'\n ? generateLazyRoutesModule(routes, ssgConfig)\n : generateRoutesModule(routes, ssgConfig);\n routesCache = { routes, code };\n }\n return routesCache.code;\n }\n\n // Generate virtual layouts module\n if (id === RESOLVED_VIRTUAL_LAYOUTS_ID) {\n if (!layoutsCache) {\n const layouts = await discoverLayouts(ssgConfig, root);\n const code = generateLayoutsModule(layouts, ssgConfig);\n layoutsCache = { layouts, code };\n }\n return layoutsCache.code;\n }\n\n // Generate virtual navigation module\n if (id === RESOLVED_VIRTUAL_NAVIGATION_ID) {\n if (!navigationCache) {\n // Ensure routes are loaded (reuse cache if available)\n if (!routesCache) {\n const routes = await scanPages(ssgConfig, root);\n const routesCode = config.command === 'serve'\n ? generateLazyRoutesModule(routes, ssgConfig)\n : generateRoutesModule(routes, ssgConfig);\n routesCache = { routes, code: routesCode };\n }\n const isDev = config.command === 'serve';\n const code = generateNavigationModule(routesCache.routes, ssgConfig, isDev);\n navigationCache = { code };\n }\n return navigationCache.code;\n }\n\n // Generate virtual config module\n if (id === RESOLVED_VIRTUAL_CONFIG_ID) {\n return `export default ${JSON.stringify(ssgConfig)};`;\n }\n\n // Generate virtual client entry (needs JSX transform)\n if (id === RESOLVED_VIRTUAL_CLIENT_ID) {\n const code = generateClientEntry(ssgConfig, entryDetection);\n const esbuild = await import('esbuild');\n const result = await esbuild.transform(code, {\n loader: 'tsx',\n jsx: 'automatic',\n jsxImportSource: 'sigx',\n });\n return result.code;\n }\n\n // Generate virtual server entry (needs JSX transform)\n if (id === RESOLVED_VIRTUAL_SERVER_ID) {\n const code = generateServerEntry(ssgConfig);\n const esbuild = await import('esbuild');\n const result = await esbuild.transform(code, {\n loader: 'tsx',\n jsx: 'automatic',\n jsxImportSource: 'sigx',\n });\n return result.code;\n }\n\n return null;\n },\n\n // Handle HMR for layouts and pages\n async handleHotUpdate({ file, server }) {\n const layoutsDir = path.resolve(root, ssgConfig.layouts || 'src/layouts');\n const pagesDir = path.resolve(root, ssgConfig.pages || 'src/pages');\n\n if (file.startsWith(layoutsDir)) {\n // Clear layout cache\n layoutsCache = null;\n\n // Invalidate the virtual layouts module\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_LAYOUTS_ID);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Also reload pages that use this layout\n return [];\n }\n\n // Handle MDX/MD file changes in pages directory\n if (file.startsWith(pagesDir) && /\\.mdx?$/.test(file)) {\n // The MDX plugin handles the transform and HMR code injection.\n // We just need to ensure the module is properly invalidated.\n // Vite will handle the rest via the injected import.meta.hot.accept()\n \n // Return undefined to let Vite handle the standard HMR flow\n // The MDX file already has import.meta.hot.accept() injected\n return undefined;\n }\n\n return undefined;\n },\n };\n\n // Combine with MDX plugin if enabled (default: true)\n const enableMdx = options.enableMdx !== false;\n \n if (enableMdx) {\n const mdx = mdxPlugin({\n markdown: options.markdown,\n ssgConfig: undefined as any, // Will be set by configResolved\n });\n return [mainPlugin, mdx];\n }\n \n return [mainPlugin];\n}\n\n/**\n * Export the plugin as default\n */\nexport default ssgPlugin;\n"],"mappings":";;;;;;;AAYA,IAAI,IAAkD,MAKhD,IAAwC;CAC1C,OAAO;CACP,MAAM;CACN,OAAO;EAAC;EAAc;EAAc;EAAO;EAAO;EAAQ;EAAO;EAAQ;EAAY;EAAQ;EAAQ;CACxG;AAKD,eAAsB,EAAe,GAA4C;CAC7E,IAAI,CAAC,GAAoB;EACrB,IAAM,IAAe;GAAE,GAAG;GAAgB,GAAG;GAAQ;EAErD,IAAqB,EAAkB;GACnC,QAAQ,CAAC,EAAa,OAAuB,EAAa,KAAqB;GAC/E,OAAO,EAAa;GACvB,CAAC;;CAGN,OAAO;;AAWX,eAAsB,EAClB,GACA,GACA,GACA,GACe;CACf,IAAM,IAAc,MAAM,EAAe,EAAO,EAC1C,IAAe;EAAE,GAAG;EAAgB,GAAG;EAAQ,EAI/C,IADc,EAAY,oBACV,CAAY,SAAS,EAAwB,GAAG,IAAO,QAGvE,IAAW,EAAY,WAAW,GAAM;EAC1C,MAAM;EACN,QAAQ;GACJ,OAAO,EAAa;GACpB,MAAM,EAAa;GACtB;EACJ,CAAC,EAGI,IAAW,GAAM,YAAY,IAC7B,IAAS,GAAM,QAAQ,IACvB,IAAO,GAAM,MACb,I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B,IAAI,MAAO,GACP,OAAO,kBAAkB,KAAK,UAAU,EAAU,CAAC;GAIvD,IAAI,MAAA,4BAAmC;IACnC,IAAM,IAAO,EAAoB,GAAW,EAAe;IAO3D,QAAO,OALc,MADC,OAAO,YACA,UAAU,GAAM;KACzC,QAAQ;KACR,KAAK;KACL,iBAAiB;KACpB,CAAC,EACY;;GAIlB,IAAI,MAAA,4BAAmC;IACnC,IAAM,IAAO,EAAoB,EAAU;IAO3C,QAAO,OALc,MADC,OAAO,YACA,UAAU,GAAM;KACzC,QAAQ;KACR,KAAK;KACL,iBAAiB;KACpB,CAAC,EACY;;GAGlB,OAAO;;EAIX,MAAM,gBAAgB,EAAE,SAAM,aAAU;GACpC,IAAM,IAAa,EAAK,QAAQ,GAAM,EAAU,WAAW,cAAc,EACnE,IAAW,EAAK,QAAQ,GAAM,EAAU,SAAS,YAAY;GAEnE,IAAI,EAAK,WAAW,EAAW,EAAE;IAE7B,IAAe;IAGf,IAAM,IAAM,EAAO,YAAY,cAAc,EAA4B;IAMzE,OALI,KACA,EAAO,YAAY,iBAAiB,EAAI,EAIrC,EAAE;;GAIT,EAAK,WAAW,EAAS,IAAI,UAAU,KAAK,EAAK;;EAY5D;CAaD,OAVkB,EAAQ,cAAc,KAUjC,CAAC,EAAW,GAHR,CAAC,GAJI,EAAU;EAClB,UAAU,EAAQ;EAClB,WAAW,KAAA;EACd,CACmB,CAAI"}
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @sigx/ssg CLI plugin
|
|
3
|
+
*
|
|
4
|
+
* Registers dev, build, and preview commands with the sigx CLI.
|
|
5
|
+
* Auto-detected when a project has ssg.config.ts.
|
|
6
|
+
*/
|
|
7
|
+
declare const _default: import("@sigx/cli/plugin").SigxPlugin;
|
|
8
|
+
export default _default;
|
|
9
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;AAMH,wBA4DG"}
|