@conloca/astro-cms 0.1.14 → 0.1.15
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/dist/collections.d.mts +3 -2
- package/dist/collections.d.mts.map +1 -1
- package/dist/collections.mjs +15 -6
- package/dist/collections.mjs.map +1 -1
- package/dist/components.d.mts +4 -24
- package/dist/components.d.mts.map +1 -1
- package/dist/components.mjs +98 -40
- package/dist/components.mjs.map +1 -1
- package/dist/hydration-scanner-B0NjYkZ_.mjs +109 -0
- package/dist/hydration-scanner-B0NjYkZ_.mjs.map +1 -0
- package/dist/hydration.d.mts +2 -2
- package/dist/hydration.mjs +1 -1
- package/dist/index.d.mts +9 -54
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +17 -796
- package/dist/index.mjs.map +1 -1
- package/dist/internal/acorn-default.mjs +29 -0
- package/dist/internal/cms-handler.d.mts.map +1 -0
- package/dist/{cms-handler.mjs → internal/cms-handler.mjs} +3 -1
- package/dist/internal/cms-handler.mjs.map +1 -0
- package/dist/internal/page-handler.astro +541 -0
- package/dist/lib/hydration-script.d.mts +1 -1
- package/dist/{loader-W3i9kf3p.mjs → loader-By-AQWHc.mjs} +10 -3
- package/dist/loader-By-AQWHc.mjs.map +1 -0
- package/dist/node/content.d.mts +19 -0
- package/dist/node/content.d.mts.map +1 -0
- package/dist/node/content.mjs +4 -0
- package/dist/node/index.d.mts +52 -0
- package/dist/node/index.d.mts.map +1 -0
- package/dist/node/index.mjs +753 -0
- package/dist/node/index.mjs.map +1 -0
- package/dist/{serialize-props-DqfDQeFl.mjs → serialize-props-Dhv_MnkY.mjs} +3 -3
- package/dist/{serialize-props-DqfDQeFl.mjs.map → serialize-props-Dhv_MnkY.mjs.map} +1 -1
- package/dist/{types-Bsd_qENn.d.mts → types-CVQNmPxF.d.mts} +1 -1
- package/dist/{types-Bsd_qENn.d.mts.map → types-CVQNmPxF.d.mts.map} +1 -1
- package/dist/{withHydration-692fMySA.mjs → withHydration-EzyzBQ-Y.mjs} +5 -1
- package/dist/withHydration-EzyzBQ-Y.mjs.map +1 -0
- package/dist/{withHydration-BGgQDE-H.d.mts → withHydration-HIvO9ysY.d.mts} +5 -1
- package/dist/withHydration-HIvO9ysY.d.mts.map +1 -0
- package/package.json +35 -25
- package/dist/cms-handler.d.mts.map +0 -1
- package/dist/cms-handler.mjs.map +0 -1
- package/dist/handlers/page-handler.astro +0 -299
- package/dist/loader-W3i9kf3p.mjs.map +0 -1
- package/dist/withHydration-692fMySA.mjs.map +0 -1
- package/dist/withHydration-BGgQDE-H.d.mts.map +0 -1
- /package/dist/{cms-handler.d.mts → internal/cms-handler.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/lib/routing-config.ts","../../src/lib/virtual-module-generators.ts","../../src/plugin-spa.ts"],"sourcesContent":["import type { RouteConfig, RoutingConfig, RoutingConfigInput } from '../types.js';\n\n/**\n * Normalize routing config input to full RoutingConfig.\n *\n * Handles the `routing: true` shorthand, boolean values, and top-level layout option.\n *\n * @param input - The routing config input (boolean, object, or undefined)\n * @param topLevelLayout - Optional top-level layout path (enables routing when provided)\n * @returns Normalized RoutingConfig or undefined if not enabled\n */\nexport function normalizeRoutingConfig(\n input: RoutingConfigInput | undefined,\n topLevelLayout?: string\n): RoutingConfig | undefined {\n // If no routing config but layout provided, enable with defaults\n if (input === undefined && topLevelLayout) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n layout: topLevelLayout,\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === undefined) {\n return undefined;\n }\n\n if (input === true) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === false) {\n return { enabled: false };\n }\n\n return input;\n}\n\n/**\n * Apply defaults to a RouteConfig.\n *\n * Fills in missing optional fields with their default values.\n *\n * @param config - Partial route configuration\n * @returns Complete route configuration with all fields\n */\nexport function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {\n return {\n pattern: config.pattern,\n collection: config.collection ?? 'pages',\n layout: config.layout ?? '',\n prerender: config.prerender ?? true,\n meta: config.meta ?? {},\n dataBindings: config.dataBindings ?? { collections: [] },\n };\n}\n\n/**\n * Validate a route pattern.\n *\n * Ensures the pattern is a valid Astro route pattern.\n * Throws descriptive error if invalid.\n *\n * @param pattern - The route pattern to validate\n * @param routeName - Name of the route (for error messages)\n * @throws Error if pattern is invalid\n */\nexport function validateRoutePattern(pattern: string, routeName: string): void {\n if (!pattern.startsWith('/')) {\n throw new Error(`Route '${routeName}': pattern must start with '/', got '${pattern}'`);\n }\n\n // Check for valid Astro route syntax\n // Allow: a-zA-Z0-9, hyphen, underscore, slash, brackets, dots\n const invalidChars = pattern.match(/[^a-zA-Z0-9\\-_/[\\].]/g);\n if (invalidChars) {\n throw new Error(`Route '${routeName}': pattern contains invalid characters: ${invalidChars.join(', ')}`);\n }\n\n // Check for balanced brackets\n const openBrackets = (pattern.match(/\\[/g) || []).length;\n const closeBrackets = (pattern.match(/\\]/g) || []).length;\n if (openBrackets !== closeBrackets) {\n throw new Error(`Route '${routeName}': pattern has unbalanced brackets: '${pattern}'`);\n }\n}\n","import type { ResolvedRoutingConfig, RoutingConfig } from '../types.js';\n\n/**\n * Generate the virtual:conloca-routing-config module.\n *\n * Returns a module that exports the resolved routing configuration as default.\n *\n * @param config - Resolved routing configuration with all defaults applied\n * @returns JavaScript module code as a string\n */\nexport function generateRoutingConfigModule(config: ResolvedRoutingConfig): string {\n return `export default ${JSON.stringify(config, null, 2)};`;\n}\n\n/**\n * Generate the virtual:conloca-layout module.\n *\n * Returns a module that re-exports the layout component or exports undefined\n * if no layout is configured.\n *\n * Currently uses the first route's layout. Multi-layout support is future work.\n *\n * @param routing - Routing configuration (may be undefined if routing disabled)\n * @returns JavaScript module code as a string\n */\nexport function generateLayoutModule(routing: RoutingConfig | undefined): string {\n // Get layout from first route (for now - multi-layout is future work)\n const routes = routing?.routes || {};\n const firstRoute = Object.values(routes)[0];\n const layoutPath = firstRoute?.layout;\n\n if (layoutPath) {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = layoutPath.startsWith('.') ? `/${layoutPath.slice(2)}` : layoutPath;\n\n return `export { default } from '${absolutePath}';`;\n }\n\n return 'export default undefined;';\n}\n\n/**\n * Options for generating the page API module.\n */\nexport interface PageApiModuleOptions {\n contentRoot: string;\n canvasDir: string;\n /** Site name for content resolution. @default 'default' */\n siteName: string;\n /** Default locale for content resolution. @default 'en' */\n locale: string;\n}\n\n/**\n * Generate the virtual:conloca-page-api module.\n *\n * Returns a module that provides page loading functions wrapping ContentAPI:\n * - getAllPages(collection?) - For getStaticPaths()\n * - getPage(pathname, collection?) - For page data loading\n * - pageExists(pathname, collection?) - For 404 checks\n * - contentOptions - Configuration for ContentAPI (for MDX evaluation)\n *\n * @param options - Configuration for ContentAPI initialization\n * @returns JavaScript module code as a string\n */\nexport function generatePageApiModule(options: PageApiModuleOptions): string {\n return `\nimport { createContentAPI } from '@conloca/content-api/reader';\n\n// Export content options for MDX evaluation and other ContentAPI uses\nexport const contentOptions = {\n contentRoot: '${options.contentRoot}',\n canvasDir: '${options.canvasDir}',\n siteName: '${options.siteName}',\n locale: '${options.locale}',\n};\n\n// Initialize ContentAPI with configured paths\nconst contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n});\n\n// Get site instance for page operations (configured via routing.siteName)\nconst site = contentApi.getSite(contentOptions.siteName);\nconst locale = contentOptions.locale; // Configured via routing.locale\n\n/**\n * Get all pages for static path generation.\n * @param collection - Optional collection filter\n */\nexport async function getAllPages(collection) {\n const pages = [];\n\n // listPages is a generator that yields ContentManifest objects\n for (const manifest of site.listPages(locale)) {\n // Get the localized data for pathname/title\n const localeData = manifest.locales[locale];\n if (!localeData) continue;\n\n const pathname = localeData.pathname || '/' + manifest.id.replace(/^index$/, '');\n\n // Collection resolution: explicit collection in manifest, or default 'pages'\n const resolvedCollection = manifest.collection || 'pages';\n\n // Filter by requested collection\n if (collection && resolvedCollection !== collection) continue;\n\n pages.push({\n id: manifest.id,\n pathname: pathname,\n title: localeData.meta?.title || manifest.id,\n collection: resolvedCollection,\n meta: localeData.meta || {},\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n });\n }\n\n return pages;\n}\n\n/**\n * Get pages matching a path prefix.\n * @param prefix - Path prefix to match (e.g., '/blog/')\n * @param options - Optional sort and limit settings\n * @returns Array of PageReference objects\n */\nexport async function getPagesByPrefix(prefix, options = {}) {\n const allPages = await getAllPages();\n\n let filtered = allPages.filter(page =>\n page.pathname.startsWith(prefix) &&\n page.pathname !== prefix && // Exclude the listing page itself\n page.pathname !== prefix.slice(0, -1) // Exclude without trailing slash\n );\n\n // Sort by date (newest first by default)\n if (options.sort === 'date-desc' || !options.sort) {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateB).getTime() - new Date(dateA).getTime();\n });\n } else if (options.sort === 'date-asc') {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateA).getTime() - new Date(dateB).getTime();\n });\n } else if (options.sort === 'title') {\n filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));\n }\n\n if (options.limit && options.limit > 0) {\n filtered = filtered.slice(0, options.limit);\n }\n\n return filtered;\n}\n\n/**\n * Load full page data for rendering.\n * @param pathname - URL pathname (e.g., '/about')\n * @param collection - Optional collection to search in\n */\nexport async function getPage(pathname, collection) {\n // Use site.getByPathname which returns ContentManifest (metadata only)\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Optionally filter by collection\n if (collection && manifest.collection !== collection) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Get the full content with locale data\n const content = await contentApi.getLocalized(manifest.id, locale);\n\n if (!content) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n const localeData = content.localized;\n const meta = localeData.meta || {};\n\n return {\n id: manifest.id,\n title: meta.title || manifest.id,\n description: meta.description,\n pathname: pathname,\n puckData: localeData.content?.puckData,\n collection: manifest.collection || collection || 'pages',\n route: {\n name: 'pages', // Will be set by caller\n pattern: '/[...slug]',\n meta: {},\n },\n meta: meta,\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n };\n}\n\n/**\n * Check if a page exists without loading full data.\n * @param pathname - URL pathname\n * @param collection - Optional collection filter\n */\nexport function pageExists(pathname, collection) {\n // getByPathname is synchronous - returns ContentManifest | null\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n return false;\n }\n\n // If collection filter specified, verify it matches\n if (collection && manifest.collection !== collection) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get all entries from a data collection.\n * @param collection - Data collection name\n * @param localeOverride - Optional locale override (defaults to configured locale)\n * @returns Array of DataCollectionEntry objects\n */\nexport async function getDataCollection(collection, localeOverride) {\n const targetLocale = localeOverride || locale;\n const entries = [];\n\n // List all manifests in the collection\n for (const manifest of contentApi.data.listContent({ collection })) {\n // Get localized data for each entry\n const localized = await contentApi.getLocalized(manifest.id, targetLocale);\n if (localized) {\n entries.push({\n id: manifest.id,\n name: manifest.name,\n data: localized.content?.data || {},\n meta: manifest.meta || {},\n });\n }\n }\n\n return entries;\n}\n`;\n}\n\n/**\n * Generate the virtual:conloca-puck-config module.\n *\n * Returns a module that re-exports the Puck configuration.\n * This is separate from the HMR-enabled puck-entry.js used by the CMS SPA.\n *\n * @param puckConfigPath - Path to the puck config module\n * @returns JavaScript module code as a string\n */\nexport function generatePuckConfigModule(puckConfigPath: string): string {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = puckConfigPath.startsWith('.') ? `/${puckConfigPath.slice(2)}` : puckConfigPath;\n\n return `export { default } from '${absolutePath}';`;\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { UIConfig } from '@conloca/cms-spa';\nimport viteReact from '@vitejs/plugin-react';\nimport type { AstroIntegration } from 'astro';\nimport { searchForWorkspaceRoot } from 'vite';\n\nimport { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';\nimport { normalizeRoutingConfig, resolveRouteConfig } from './lib/routing-config.js';\n\n// FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.\n// It provides the React Fast Refresh preamble script needed for HMR in virtual modules.\n// If @vitejs/plugin-react removes or renames this property, the assertion below will\n// fail immediately at dev startup. Test after any @vitejs/plugin-react update.\nif (typeof viteReact.preambleCode !== 'string') {\n throw new Error(\n '@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +\n 'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +\n 'Check @vitejs/plugin-react release notes and update the preamble injection logic.',\n );\n}\n\nconst reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');\n\n// Get the directory of this module to resolve page-handler.astro\n// Works from both src/ (dev) and dist/ (published) since build copies the file\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst PAGE_HANDLER_PATH = join(__dirname, '..', 'internal', 'page-handler.astro');\nconst CMS_HANDLER_PATH = join(__dirname, '..', 'internal', 'cms-handler.mjs');\nconst ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', 'internal', 'acorn-default.mjs');\n\nimport {\n generateLayoutModule,\n generatePageApiModule,\n generatePuckConfigModule,\n generateRoutingConfigModule,\n} from './lib/virtual-module-generators.js';\nimport type { ResolvedRoutingConfig, RoutingConfigInput, TemplateConfig } from './types.js';\n\n// Virtual module for passing config from plugin to route handler\nconst VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';\nconst RESOLVED_VIRTUAL_CONFIG = `\\0${VIRTUAL_CONFIG_MODULE}`;\n\n// Virtual module IDs for routing system\nconst VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';\nconst VIRTUAL_LAYOUT = 'virtual:conloca-layout';\nconst VIRTUAL_PAGE_API = 'virtual:conloca-page-api';\nconst VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';\n\n// Resolved IDs (with \\0 prefix to prevent file resolution)\nconst RESOLVED_ROUTING_CONFIG = `\\0${VIRTUAL_ROUTING_CONFIG}`;\nconst RESOLVED_LAYOUT = `\\0${VIRTUAL_LAYOUT}`;\nconst RESOLVED_PAGE_API = `\\0${VIRTUAL_PAGE_API}`;\nconst RESOLVED_PUCK_CONFIG = `\\0${VIRTUAL_PUCK_CONFIG}`;\n\n// Virtual modules for hydration system\nconst VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';\nconst VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';\nconst RESOLVED_HYDRATION_REGISTRY = `\\0${VIRTUAL_HYDRATION_REGISTRY}`;\nconst RESOLVED_HYDRATION_ENTRY = `\\0${VIRTUAL_HYDRATION_ENTRY}`;\n\n// Virtual module for CMS SPA source loading (dev only)\nconst VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';\nconst RESOLVED_CMS_SPA_ENTRY = `\\0${VIRTUAL_CMS_SPA_ENTRY}`;\n\nasync function loadContentApiNode() {\n return import('@conloca/content-api/node');\n}\n\nexport interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {\n contentRoot: string;\n canvasDir?: string;\n route?: string; // Default: /__cms\n puckConfigPath: string; // Path to the puck config module (should be .tsx file with React components)\n schemasPath?: string; // Path to the schemas module (exports { dataSchemas, pageSchemas })\n\n /**\n * Default layout for content pages.\n * When provided without routing config, enables routing with catch-all pattern.\n * For multi-route setups, use routing.routes.{name}.layout instead.\n *\n * @example './src/layouts/Layout.astro'\n */\n layout?: string;\n\n routing?: RoutingConfigInput; // Content page routing configuration\n templates?: Record<string, TemplateConfig>; // Page creation templates\n\n /**\n * Paths to scan for hydratable components.\n * Components using withHydration() in these directories are auto-discovered.\n *\n * @example ['src/components/puck']\n */\n componentPaths?: string[];\n\n /**\n * Path to the assets directory for image uploads.\n * When provided, enables the Media Library and asset upload API routes.\n *\n * @example 'src/assets/uploads'\n */\n assetsPath?: string;\n\n /**\n * CSS files to load in the CMS editor for component preview styling.\n *\n * Each file is processed by Vite (Tailwind, PostCSS, etc.) and injected\n * directly into Puck's preview iframe `<head>`. Site CSS never enters the\n * CMS admin's parent document, so host-site styles cannot bleed into the\n * CMS chrome (drawer, sidebar, etc.).\n *\n * @example './src/styles/global.css'\n * @example ['./src/styles/global.css', './src/styles/theme.css']\n */\n siteStyles?: string | string[];\n}\n\n// Template for content change listener virtual module\nconst contentChangeListener = () => {\n return `\n// Content change listener that uses Vite HMR\nif (import.meta.hot) {\n import.meta.hot.on('conloca:content-update', (data) => {\n console.log('[Conloca CMS] Content updated, invalidating cache:', data);\n \n // Get the query client from the global scope and invalidate\n if (window.__QUERY_CLIENT__) {\n window.__QUERY_CLIENT__.invalidateQueries();\n }\n });\n}\n\nexport default {};\n`;\n};\n\n// Template for the puck config loader virtual module\nconst puckConfigLoader = (absolutePuckPath: string) => {\n // We need to ensure the preamble executes before ANY module evaluation\n // So we'll use a dynamic import after the preamble is set up\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${reactRefreshPreamble}\n\n// Import the setPuckConfig function from cms-spa\nimport { setPuckConfig } from '@conloca/cms-spa/puck-config';\n\n// Now dynamically import the config after preamble is ready\nconst puckConfigPromise = import('${absolutePuckPath}');\n\n// Handle the initial load\npuckConfigPromise.then(module => {\n const puckConfig = module.default;\n setPuckConfig(puckConfig);\n\n // Hook into React Fast Refresh to detect component updates\n if (window.__registerBeforePerformReactRefresh) {\n window.__registerBeforePerformReactRefresh(async () => {\n // Re-import the config module to get updated components\n const newModule = await import('${absolutePuckPath}');\n setPuckConfig(newModule.default);\n });\n }\n});\n\n// Accept HMR for this module itself\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\n// Export the promise so the module has a default export\nexport default puckConfigPromise.then(m => m.default);\n`;\n};\n\n// Template for the schemas loader virtual module\nconst schemasLoader = (absoluteSchemasPath: string) => {\n return `\nimport { setPageSchemas } from '@conloca/cms-spa/page-schemas';\nimport * as schemas from '${absoluteSchemasPath}';\n\nif (schemas.pageSchemas) {\n setPageSchemas(schemas.pageSchemas);\n}\n\nif (import.meta.hot) {\n import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {\n if (newModule?.pageSchemas) {\n setPageSchemas(newModule.pageSchemas);\n }\n });\n}\n\nexport default schemas;\n`;\n};\n\n// Template for the site styles loader virtual module.\n//\n// Each CSS file is imported with Vite's `?inline` query so the full CSS\n// pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet\n// as a string — no `<style>` tag is injected into the CMS admin's parent\n// `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles\n// registry; the editor's iframe bridge then injects them directly into\n// Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS\n// chrome and confines it to the intended consumer (the preview).\nconst siteStylesLoader = (cssPaths: string[]) => {\n const imports = cssPaths\n .map((p, i) => {\n const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;\n return `import css${i} from '${absolutePath}?inline';`;\n })\n .join('\\n');\n const vars = cssPaths.map((_, i) => `css${i}`).join(', ');\n\n return `\n${imports}\nimport { setSiteStyles } from '@conloca/cms-spa/site-styles';\n\nsetSiteStyles([${vars}]);\n\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\nexport default {};\n`;\n};\n\nexport function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {\n const cmsRoute = options.route || '/__cms';\n\n // Normalize routing config and resolve defaults\n // Pass top-level layout to enable routing when layout provided without explicit routing config\n const routingConfig = normalizeRoutingConfig(options.routing, options.layout);\n\n // Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths\n // Scanner handles missing directories gracefully (fast-glob returns empty array)\n const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);\n\n // Scan for hydratable components - this promise is awaited in the virtual module loader\n const hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]> = scanForHydratableComponents(\n componentPaths,\n process.cwd(),\n ).then((discoveries) => {\n if (discoveries.length > 0) {\n console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);\n }\n return discoveries;\n });\n\n // Build resolved routing config with all defaults applied\n let resolvedRoutingConfig: ResolvedRoutingConfig | undefined;\n if (routingConfig?.enabled !== false && routingConfig) {\n const resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>> = {};\n for (const [name, config] of Object.entries(routingConfig.routes || {})) {\n resolvedRoutes[name] = resolveRouteConfig(config);\n }\n resolvedRoutingConfig = {\n enabled: routingConfig.enabled ?? true,\n routes: resolvedRoutes,\n fallback: routingConfig.fallback ?? '404',\n onConflict: routingConfig.onConflict ?? 'warn',\n siteName: routingConfig.siteName ?? 'default',\n locale: routingConfig.locale ?? 'en',\n };\n }\n\n // SPA config passed to route handler via virtual module\n // This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true\n const spaConfig = {\n basename: cmsRoute,\n apiBaseUrl: `${cmsRoute}/api`,\n siteBaseUrl: options.siteBaseUrl,\n enableDevtools: options.enableDevtools ?? true,\n queryClientOptions: options.queryClientOptions,\n schemasPath: options.schemasPath,\n projectRoot: process.cwd(),\n templates: options.templates,\n };\n\n let refreshConlocaContent: (() => Promise<void>) | undefined;\n\n return {\n name: '@conloca/astro-cms',\n hooks: {\n 'astro:config:setup': ({ updateConfig, injectRoute, command, logger }) => {\n // Auto-inject fs.allow for external contentRoot (dev mode only)\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n\n if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {\n logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);\n\n updateConfig({\n vite: {\n server: {\n fs: {\n allow: [\n searchForWorkspaceRoot(process.cwd()), // Preserve Vite default\n contentAbsolute,\n ],\n },\n },\n },\n });\n }\n\n const devSsrNoExternal = [/^@conloca\\//, '@puckeditor/core'];\n const serverOnlyExternal = [\n '@conloca/content-api',\n '@conloca/content-api/node',\n '@conloca/content-api/reader',\n '@conloca/content-api/schemas',\n '@conloca/mdx',\n '@conloca/mdx/node',\n '@node-rs/xxhash',\n '@node-rs/xxhash-linux-x64-gnu',\n '@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node',\n ];\n updateConfig({\n vite: {\n ssr: {\n // In dev, linked workspace packages need to be bundled so React resolves\n // through Vite and HMR works from source.\n noExternal: command === 'dev' ? devSsrNoExternal : [],\n // Keep Node-only content processing packages external so SSR builds do not\n // try to bundle native dependencies like xxhash.\n external: serverOnlyExternal,\n },\n build: {\n rollupOptions: {\n external: [\n '@node-rs/xxhash',\n '@node-rs/xxhash-linux-x64-gnu',\n '@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node',\n ],\n },\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\n // Alias acorn to a CJS shim only during SSR (static page builds).\n // Must NOT apply to the browser bundle — the shim uses createRequire\n // which is Node.js-only and crashes in the browser.\n {\n name: 'conloca-acorn-ssr-alias',\n enforce: 'pre' as const,\n resolveId(id, _importer, options) {\n if (id === 'acorn' && options?.ssr) {\n return ACORN_DEFAULT_SHIM_PATH;\n }\n return null;\n },\n },\n {\n name: 'conloca-routing-virtual-modules',\n resolveId(id) {\n // Routing virtual modules (work in both dev and build)\n if (id === VIRTUAL_ROUTING_CONFIG) {\n return RESOLVED_ROUTING_CONFIG;\n }\n if (id === VIRTUAL_LAYOUT) {\n return RESOLVED_LAYOUT;\n }\n if (id === VIRTUAL_PUCK_CONFIG) {\n return RESOLVED_PUCK_CONFIG;\n }\n // Hydration virtual modules\n if (id === VIRTUAL_HYDRATION_REGISTRY) {\n return RESOLVED_HYDRATION_REGISTRY;\n }\n if (id === VIRTUAL_HYDRATION_ENTRY) {\n return RESOLVED_HYDRATION_ENTRY;\n }\n return null;\n },\n async load(id) {\n // Routing virtual modules\n if (id === RESOLVED_ROUTING_CONFIG) {\n if (resolvedRoutingConfig) {\n return generateRoutingConfigModule(resolvedRoutingConfig);\n }\n // Return disabled config if routing not configured\n return 'export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };';\n }\n if (id === RESOLVED_LAYOUT) {\n return generateLayoutModule(routingConfig);\n }\n if (id === RESOLVED_PUCK_CONFIG) {\n return generatePuckConfigModule(options.puckConfigPath);\n }\n // Hydration virtual modules\n if (id === RESOLVED_HYDRATION_REGISTRY) {\n // Always scan - paths are auto-derived from puckConfigPath\n const discoveries = await hydrationDiscoveriesPromise;\n if (discoveries.length > 0) {\n const entries = discoveries.map((d) => {\n // Convert absolute path to Vite-friendly path\n const relativePath = d.filePath.replace(process.cwd(), '');\n return ` '${d.componentName}': {\n loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),\n strategy: '${d.strategy}',\n }`;\n });\n return `// Generated by @conloca/astro-cms scanner\nexport const componentRegistry = {\n${entries.join(',\\n')}\n};`;\n }\n\n // No hydratable components found - return empty registry\n return 'export const componentRegistry = {};';\n }\n if (id === RESOLVED_HYDRATION_ENTRY) {\n // Generate entry point that imports registry and calls initHydration\n return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'\nimport { componentRegistry } from 'virtual:conloca-hydration-registry'\n\n// Auto-initialize hydration when this module loads\ninitHydration(componentRegistry)\n`;\n }\n return null;\n },\n },\n ],\n },\n });\n\n // Content page routes - works in both dev and build\n if (resolvedRoutingConfig?.enabled) {\n for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {\n logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);\n injectRoute({\n pattern: routeConfig.pattern,\n entrypoint: PAGE_HANDLER_PATH,\n prerender: routeConfig.prerender,\n });\n }\n }\n\n // Only inject CMS admin routes and dev-specific config in dev mode\n if (command !== 'dev') return;\n\n // Pass options via Vite define for API routes\n updateConfig({\n vite: {\n define: {\n 'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),\n 'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),\n 'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),\n 'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),\n },\n resolve: {\n // Dedupe React and React Query to avoid multiple instances when using symlinked packages.\n // Without this, bun link causes esbuild to find nested copies in the symlink target's\n // node_modules, creating separate React.createContext() calls = broken context sharing.\n dedupe: [\n 'react',\n 'react-dom',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n '@puckeditor/core',\n '@tanstack/react-query',\n ],\n // Prevent symlinked packages (via bun link) from resolving dependencies\n // from their real path. Ensures @conloca packages find React from the\n // consumer project's node_modules, not from their source repo.\n preserveSymlinks: true,\n },\n optimizeDeps: {\n // Exclude the puck config from optimization to avoid the outdated dep error\n exclude: [options.puckConfigPath],\n // Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization\n // which causes React dual-instance issues when Vite discovers new deps dynamically\n include: [\n // React core - must be pre-bundled together\n 'react',\n 'react-dom',\n 'react-dom/client',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n // CMS dependencies\n '@mdxeditor/editor',\n '@puckeditor/core',\n '@tanstack/react-query',\n '@tanstack/react-query-devtools',\n 'react-router-dom',\n '@radix-ui/react-dialog',\n '@radix-ui/react-select',\n 'lucide-react',\n 'clsx',\n 'tailwind-merge',\n // Content processing\n 'zod',\n 'yaml',\n 'nanoid',\n 'sort-keys',\n // MDX processing\n '@mdx-js/mdx',\n 'remark-frontmatter',\n 'remark-gfm',\n 'remark-mdx-frontmatter',\n ],\n },\n plugins: [\n // Normalize @conloca/* imports from symlinked source files (bun link).\n // When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports\n // resolve relative to the real filesystem location, creating duplicate\n // module instances. This plugin re-resolves them from the consumer\n // project root so all @conloca packages use the same module identity.\n {\n name: 'conloca-resolve-normalizer',\n enforce: 'pre' as const,\n async resolveId(source, importer) {\n // Only normalize @conloca/* bare specifiers\n if (!source.startsWith('@conloca/')) return null;\n // Only when imported from outside the project (symlinked source files)\n if (!importer || importer.startsWith(astroRoot)) return null;\n // Skip virtual modules (prefixed with \\0)\n if (importer.startsWith('\\0')) return null;\n // Re-resolve from project root to ensure consumer's node_modules is used\n const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });\n return resolved;\n },\n },\n {\n name: 'conloca-dev-virtual-modules',\n resolveId(id) {\n // Dev-only config module for cms-handler.ts\n if (id === VIRTUAL_CONFIG_MODULE) {\n return RESOLVED_VIRTUAL_CONFIG;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n return id;\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return id;\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n return id;\n }\n if (id === `${cmsRoute}/site-styles.js`) {\n return id;\n }\n if (id === VIRTUAL_PAGE_API) {\n return RESOLVED_PAGE_API;\n }\n if (id === VIRTUAL_CMS_SPA_ENTRY) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n if (id === `${cmsRoute}/cms-spa-entry.js`) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n return null;\n },\n load(id) {\n // Dev-only config module for cms-handler.ts\n if (id === RESOLVED_VIRTUAL_CONFIG) {\n return `export default ${JSON.stringify(spaConfig)};`;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n const absolutePuckPath = options.puckConfigPath.startsWith('.')\n ? `/${options.puckConfigPath.slice(2)}`\n : options.puckConfigPath;\n\n return puckConfigLoader(absolutePuckPath);\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return contentChangeListener();\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n if (options.schemasPath) {\n const absoluteSchemasPath = options.schemasPath.startsWith('.')\n ? `/${options.schemasPath.slice(2)}`\n : options.schemasPath;\n return schemasLoader(absoluteSchemasPath);\n }\n return 'export default {};';\n }\n if (id === `${cmsRoute}/site-styles.js`) {\n if (options.siteStyles) {\n const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];\n return siteStylesLoader(paths);\n }\n return 'export default {};';\n }\n if (id === RESOLVED_PAGE_API) {\n return generatePageApiModule({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n siteName: resolvedRoutingConfig?.siteName ?? 'default',\n locale: resolvedRoutingConfig?.locale ?? 'en',\n });\n }\n if (id === RESOLVED_CMS_SPA_ENTRY) {\n // Detect whether cms-spa source is available (workspace mode)\n // vs only dist/ (npm install)\n let cmsSpaImport: string;\n try {\n const cmsSpaPackageJsonPath = import.meta.resolve('@conloca/cms-spa/package.json');\n const cmsSpaDir = dirname(\n cmsSpaPackageJsonPath.startsWith('file://')\n ? fileURLToPath(cmsSpaPackageJsonPath)\n : cmsSpaPackageJsonPath,\n );\n const realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\n // Prefer the consumer-side symlink path when @conloca/cms-spa is\n // linked in from another workspace (e.g. cross-repo `bun link`).\n // Importing via the symlink path keeps `react`/`react-dom`\n // resolving through the consumer's node_modules walk under\n // `preserveSymlinks: true`, which prevents duplicate React\n // instances inside the CMS SPA. Same-workspace installs either\n // don't expose this path or point at the same underlying file,\n // so behavior and HMR are preserved.\n const linkedSrcMainPath = join(\n astroRoot,\n 'node_modules',\n '@conloca',\n 'cms-spa',\n 'src',\n 'main.tsx',\n );\n const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;\n\n if (existsSync(srcMainPath)) {\n // Workspace mode: import source for HMR\n cmsSpaImport = `import '${srcMainPath}';`;\n } else {\n // npm mode: import pre-built SPA mounting entry\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n } catch {\n // Fallback: use package import\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${reactRefreshPreamble}\n\n// Import cms-spa through Vite\n// Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)\n${cmsSpaImport}\n\n// Accept HMR\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n`;\n }\n return null;\n },\n },\n {\n name: 'conloca-content-watcher',\n async configureServer(server) {\n const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();\n\n // Initialize content API using the extracted function\n const contentApi = await createContentAPI({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n });\n\n // Only add explicit watchers if content is outside the Astro project\n const { resolve } = await import('node:path');\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n const canvasAbsolute = resolve(options.canvasDir || './canvas');\n\n const foldersToWatch = [];\n\n if (!contentAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`,\n );\n foldersToWatch.push(options.contentRoot);\n } else {\n console.log(\n `[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`,\n );\n }\n\n if (!canvasAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`,\n );\n foldersToWatch.push(options.canvasDir || './canvas');\n } else {\n console.log(\n `[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`,\n );\n }\n\n if (foldersToWatch.length > 0) {\n server.watcher.add(foldersToWatch);\n }\n\n // Set up HMR for content changes using extracted handlers\n const handlers = createContentWatchHandlers(\n contentApi,\n {\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n },\n server.ws,\n async () => {\n await refreshConlocaContent?.();\n },\n );\n\n server.watcher.on('change', handlers.onChange);\n server.watcher.on('add', handlers.onAdd);\n server.watcher.on('unlink', handlers.onUnlink);\n },\n },\n ],\n },\n });\n\n // Inject unified CMS handler for all CMS routes\n // Single handler validates auth once, then routes to appropriate sub-handler\n injectRoute({\n pattern: `${cmsRoute}/[...path]`,\n entrypoint: CMS_HANDLER_PATH,\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: CMS_HANDLER_PATH,\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger, refreshContent }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\n\n let refreshChain = Promise.resolve();\n\n refreshConlocaContent = async () => {\n if (!refreshContent) {\n return;\n }\n\n refreshChain = refreshChain\n .catch(() => undefined)\n .then(async () => {\n await refreshContent({ loaders: ['conloca-loader'] });\n });\n\n await refreshChain;\n };\n\n // Register dev-time content refresh after the Vite server exists.\n // This keeps Astro collections in sync with Conloca's own file watcher.\n logger.debug('Registering Conloca content refresh handler');\n },\n\n 'astro:routes:resolved': ({ routes, logger }) => {\n // Check for route conflicts when routing is enabled\n if (!resolvedRoutingConfig?.enabled) return;\n\n const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));\n\n // Find file-based project routes that conflict with injected routes.\n // Integration routes (origin: 'external') sharing the same catch-all pattern\n // is expected — Astro's prerender fallthrough handles coexistence automatically.\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n if (route.origin !== 'project') continue;\n\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: route.entrypoint || pattern,\n });\n }\n }\n\n if (conflicts.length === 0) return;\n\n // Handle conflicts based on onConflict setting\n const onConflict = resolvedRoutingConfig.onConflict;\n\n for (const conflict of conflicts) {\n const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;\n\n if (onConflict === 'error') {\n throw new Error(`[Conloca] ${message}`);\n }\n if (onConflict === 'warn') {\n logger.warn(message);\n }\n // 'silent' - do nothing\n }\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAWA,SAAgB,uBACd,OACA,gBAC2B;AAE3B,KAAI,UAAU,UAAa,eACzB,QAAO;EACL,SAAS;EACT,QAAQ,EACN,OAAO;GACL,SAAS;GACT,YAAY;GACZ,QAAQ;GACR,WAAW;GACZ,EACF;EACD,UAAU;EACV,YAAY;EACb;AAGH,KAAI,UAAU,OACZ;AAGF,KAAI,UAAU,KACZ,QAAO;EACL,SAAS;EACT,QAAQ,EACN,OAAO;GACL,SAAS;GACT,YAAY;GACZ,WAAW;GACZ,EACF;EACD,UAAU;EACV,YAAY;EACb;AAGH,KAAI,UAAU,MACZ,QAAO,EAAE,SAAS,OAAO;AAG3B,QAAO;;;;;;;;;;AAWT,SAAgB,mBAAmB,QAA4C;AAC7E,QAAO;EACL,SAAS,OAAO;EAChB,YAAY,OAAO,cAAc;EACjC,QAAQ,OAAO,UAAU;EACzB,WAAW,OAAO,aAAa;EAC/B,MAAM,OAAO,QAAQ,EAAE;EACvB,cAAc,OAAO,gBAAgB,EAAE,aAAa,EAAE,EAAE;EACzD;;;;;;;;;;;;;AChEH,SAAgB,4BAA4B,QAAuC;AACjF,QAAO,kBAAkB,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;;;;;;;;;;;;;AAc3D,SAAgB,qBAAqB,SAA4C;CAE/E,MAAM,SAAS,SAAS,UAAU,EAAE;CAEpC,MAAM,aADa,OAAO,OAAO,OAAO,CAAC,IACV;AAE/B,KAAI,WAKF,QAAO,4BAFc,WAAW,WAAW,IAAI,GAAG,IAAI,WAAW,MAAM,EAAE,KAAK,WAE9B;AAGlD,QAAO;;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,WAAW,MAAM,cAAc;MAChC,CAAC;;AAIN,QAAI,UAAU,WAAW,EAAG;IAG5B,MAAM,aAAa,sBAAsB;AAEzC,SAAK,MAAM,YAAY,WAAW;KAChC,MAAM,UAAU,oBAAoB,SAAS,SAAS,uBAAuB,SAAS,UAAU;AAEhG,SAAI,eAAe,QACjB,OAAM,IAAI,MAAM,aAAa,UAAU;AAEzC,SAAI,eAAe,OACjB,QAAO,KAAK,QAAQ;;;GAK3B;EACF"}
|
|
@@ -32,7 +32,7 @@ function findHydratableComponents(data, config) {
|
|
|
32
32
|
type: item.type,
|
|
33
33
|
props: item.props ?? {},
|
|
34
34
|
strategy,
|
|
35
|
-
id: item.props?.
|
|
35
|
+
id: item.props?.id ?? item.type
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
if (data.zones) for (const [zoneName, zoneContent] of Object.entries(data.zones)) for (const item of zoneContent) {
|
|
@@ -41,7 +41,7 @@ function findHydratableComponents(data, config) {
|
|
|
41
41
|
type: item.type,
|
|
42
42
|
props: item.props ?? {},
|
|
43
43
|
strategy,
|
|
44
|
-
id: item.props?.
|
|
44
|
+
id: item.props?.id ?? `${zoneName}-${item.type}`
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
47
|
return hydratable;
|
|
@@ -70,4 +70,4 @@ function serializeProps(props) {
|
|
|
70
70
|
|
|
71
71
|
//#endregion
|
|
72
72
|
export { isHydratable as i, findHydratableComponents as n, hasHydratableComponents as r, serializeProps as t };
|
|
73
|
-
//# sourceMappingURL=serialize-props-
|
|
73
|
+
//# sourceMappingURL=serialize-props-Dhv_MnkY.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serialize-props-
|
|
1
|
+
{"version":3,"file":"serialize-props-Dhv_MnkY.mjs","names":[],"sources":["../src/lib/hydration-utils.ts","../src/lib/serialize-props.ts"],"sourcesContent":["import type { Config, Data } from '@puckeditor/core';\nimport type { HydrationStrategy } from '../types.js';\nimport type { HydrationMeta } from './withHydration.js';\n\n/**\n * Extended ComponentConfig with hydration support.\n * @deprecated Use withHydration() wrapper instead of hydration property.\n */\nexport interface HydratableComponentConfig {\n /** @deprecated Use withHydration() wrapper on render function instead */\n hydration?: HydrationStrategy;\n render?: (props: unknown) => unknown;\n}\n\n/**\n * Component instance requiring hydration.\n * Contains the component name, props, and hydration strategy.\n */\nexport interface HydratableComponent {\n /** Component type name from Puck config */\n type: string;\n /** Props to pass to the component */\n props: Record<string, unknown>;\n /** Hydration strategy from ComponentConfig */\n strategy: Exclude<HydrationStrategy, 'none'>;\n /** Unique ID from Puck data (for keying) */\n id: string;\n}\n\n/**\n * Check if a component type has hydration enabled.\n *\n * First checks for __hydration metadata on the render function (new withHydration API),\n * then falls back to hydration property on ComponentConfig (deprecated).\n *\n * @param componentType - The component type name from Puck data\n * @param config - The Puck config with component definitions\n * @returns The hydration strategy ('none', 'load', 'visible', 'idle')\n */\nexport function isHydratable(componentType: string, config: Config): HydrationStrategy {\n const componentConfig = config.components[componentType] as HydratableComponentConfig | undefined;\n if (!componentConfig?.render) return 'none';\n\n // New API: Check for __hydration metadata attached by withHydration()\n const render = componentConfig.render as { __hydration?: HydrationMeta };\n if (render.__hydration?.__isHydratable) {\n return render.__hydration.strategy;\n }\n\n // Deprecated: Check hydration property on ComponentConfig\n return componentConfig?.hydration ?? 'none';\n}\n\n/**\n * Find all components in a Puck data tree that require hydration.\n * Walks the content array and zones recursively.\n *\n * @param data - Puck data object containing content tree\n * @param config - Puck config with component definitions\n * @returns Array of components that need hydration\n */\nexport function findHydratableComponents(data: Data, config: Config): HydratableComponent[] {\n const hydratable: HydratableComponent[] = [];\n\n // Walk content array\n if (data.content) {\n for (const item of data.content) {\n const strategy = isHydratable(item.type, config);\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?.id ?? item.type,\n });\n }\n }\n }\n\n // Walk zones (named drop zones with nested content)\n if (data.zones) {\n for (const [zoneName, zoneContent] of Object.entries(data.zones)) {\n for (const item of zoneContent) {\n const strategy = isHydratable(item.type, config);\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?.id ?? `${zoneName}-${item.type}`,\n });\n }\n }\n }\n }\n\n return hydratable;\n}\n\n/**\n * Check if Puck data contains any hydratable components.\n * Quick check before more expensive operations.\n */\nexport function hasHydratableComponents(data: Data, config: Config): boolean {\n // Check content\n if (data.content?.some((item) => isHydratable(item.type, config) !== 'none')) {\n return true;\n }\n\n // Check zones\n if (data.zones) {\n for (const zoneContent of Object.values(data.zones)) {\n if (zoneContent.some((item) => isHydratable(item.type, config) !== 'none')) {\n return true;\n }\n }\n }\n\n return false;\n}\n","/**\n * Safely serialize props for embedding in HTML data attributes.\n * Escapes < to prevent XSS when JSON is parsed in browser.\n */\nexport function serializeProps(props: Record<string, unknown>): string {\n return JSON.stringify(props).replace(/</g, '\\\\u003c')\n}\n"],"mappings":";;;;;;;;;;;AAuCA,SAAgB,aAAa,eAAuB,QAAmC;CACrF,MAAM,kBAAkB,OAAO,WAAW;AAC1C,KAAI,CAAC,iBAAiB,OAAQ,QAAO;CAGrC,MAAM,SAAS,gBAAgB;AAC/B,KAAI,OAAO,aAAa,eACtB,QAAO,OAAO,YAAY;AAI5B,QAAO,iBAAiB,aAAa;;;;;;;;;;AAWvC,SAAgB,yBAAyB,MAAY,QAAuC;CAC1F,MAAM,aAAoC,EAAE;AAG5C,KAAI,KAAK,QACP,MAAK,MAAM,QAAQ,KAAK,SAAS;EAC/B,MAAM,WAAW,aAAa,KAAK,MAAM,OAAO;AAChD,MAAI,aAAa,OACf,YAAW,KAAK;GACd,MAAM,KAAK;GACX,OAAO,KAAK,SAAS,EAAE;GACvB;GACA,IAAI,KAAK,OAAO,MAAM,KAAK;GAC5B,CAAC;;AAMR,KAAI,KAAK,MACP,MAAK,MAAM,CAAC,UAAU,gBAAgB,OAAO,QAAQ,KAAK,MAAM,CAC9D,MAAK,MAAM,QAAQ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;;;EAkBA,MAAA;;;;;;;;;;;;;;;;;;;EAoBA,SAAA;;;;;;;;;EAUA,IAAA,GAAO,MAAA;;;;;;;;;;;;;;;;;EAkBP,YAAA,GAAe,iBAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;UAoPA,iBAAA;;;;;;;;;;EAUf,WAAA;;;;;;;EAQA,MAAA;;;;;;;;;;;;;;;;;;;;;EAsBA,KAAA;;;;;;;;;IASE,MAAA;;;;;;IAOA,KAAA;;;;;;;;;;IAWA,IAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;UA0Ba,cAAA;;;;;EAKf,KAAA;;;;;;EAOA,SAAA;;;;;;EAOA,UAAA;;;;EAKA,WAAA;AAAA"}
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
* The wrapper does NOT create a new component or add runtime overhead.
|
|
10
10
|
* It simply attaches a `__hydration` property to the existing function.
|
|
11
11
|
*
|
|
12
|
+
* **Constraint:** Hydratable components must not use `puck.renderDropZone`,
|
|
13
|
+
* `puck.isEditing`, or `puck.metadata` — the `puck` prop is stripped during
|
|
14
|
+
* serialization and not available at hydration time.
|
|
15
|
+
*
|
|
12
16
|
* @param Component - The React component to mark for hydration
|
|
13
17
|
* @param strategy - When to hydrate: 'load', 'visible', or 'idle'
|
|
14
18
|
* @returns The same component with hydration metadata attached
|
|
@@ -42,4 +46,4 @@ function withHydration(Component, strategy) {
|
|
|
42
46
|
|
|
43
47
|
//#endregion
|
|
44
48
|
export { withHydration as t };
|
|
45
|
-
//# sourceMappingURL=withHydration-
|
|
49
|
+
//# sourceMappingURL=withHydration-EzyzBQ-Y.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"withHydration-EzyzBQ-Y.mjs","names":[],"sources":["../src/lib/withHydration.ts"],"sourcesContent":["import type React from 'react';\n\n/**\n * Metadata attached to components marked for hydration.\n * Used by the build-time scanner and runtime hydration system.\n */\nexport interface HydrationMeta {\n strategy: 'load' | 'visible' | 'idle';\n __isHydratable: true;\n}\n\n/**\n * Hydration strategy for the withHydration wrapper.\n * Does not include 'none' since wrapping implies hydration is desired.\n */\nexport type WithHydrationStrategy = 'load' | 'visible' | 'idle';\n\n/**\n * Marks a component's render function for client-side hydration.\n *\n * This wrapper attaches metadata to the component function, enabling:\n * 1. Build-time discovery via static analysis of source files\n * 2. Runtime hydration strategy determination\n *\n * The wrapper does NOT create a new component or add runtime overhead.\n * It simply attaches a `__hydration` property to the existing function.\n *\n * **Constraint:** Hydratable components must not use `puck.renderDropZone`,\n * `puck.isEditing`, or `puck.metadata` — the `puck` prop is stripped during\n * serialization and not available at hydration time.\n *\n * @param Component - The React component to mark for hydration\n * @param strategy - When to hydrate: 'load', 'visible', or 'idle'\n * @returns The same component with hydration metadata attached\n *\n * @example\n * ```tsx\n * // In a Puck component file (e.g., TestimonialGrid.tsx)\n * import { withHydration } from '@conloca/astro-cms'\n *\n * const TestimonialGridComponent = ({ title, testimonials }) => {\n * const [currentPage, setCurrentPage] = useState(0)\n * // ... interactive logic\n * }\n *\n * export const TestimonialGrid: ComponentConfig<Props> = {\n * fields: { ... },\n * defaultProps: { ... },\n * render: withHydration(TestimonialGridComponent, 'visible'),\n * }\n * ```\n */\nexport function withHydration<T extends (props: any) => React.ReactNode>(\n Component: T,\n strategy: WithHydrationStrategy,\n): T {\n // Environment variable escape hatch for debugging\n if (typeof process !== 'undefined' && process.env?.CONLOCA_DISABLE_HYDRATION === 'true') {\n return Component;\n }\n\n // Attach metadata directly to the function object\n // This avoids creating a wrapper component and keeps bundle size minimal\n const HydratableComponent = Component as T & { __hydration: HydrationMeta };\n HydratableComponent.__hydration = {\n strategy,\n __isHydratable: true,\n };\n\n return HydratableComponent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,cACd,WACA,UACG;AAEH,KAAI,OAAO,YAAY,eAAe,QAAQ,KAAK,8BAA8B,OAC/E,QAAO;CAKT,MAAM,sBAAsB;AAC5B,qBAAoB,cAAc;EAChC;EACA,gBAAgB;EACjB;AAED,QAAO"}
|
|
@@ -24,6 +24,10 @@ type WithHydrationStrategy = 'load' | 'visible' | 'idle';
|
|
|
24
24
|
* The wrapper does NOT create a new component or add runtime overhead.
|
|
25
25
|
* It simply attaches a `__hydration` property to the existing function.
|
|
26
26
|
*
|
|
27
|
+
* **Constraint:** Hydratable components must not use `puck.renderDropZone`,
|
|
28
|
+
* `puck.isEditing`, or `puck.metadata` — the `puck` prop is stripped during
|
|
29
|
+
* serialization and not available at hydration time.
|
|
30
|
+
*
|
|
27
31
|
* @param Component - The React component to mark for hydration
|
|
28
32
|
* @param strategy - When to hydrate: 'load', 'visible', or 'idle'
|
|
29
33
|
* @returns The same component with hydration metadata attached
|
|
@@ -48,4 +52,4 @@ type WithHydrationStrategy = 'load' | 'visible' | 'idle';
|
|
|
48
52
|
declare function withHydration<T extends (props: any) => React.ReactNode>(Component: T, strategy: WithHydrationStrategy): T;
|
|
49
53
|
//#endregion
|
|
50
54
|
export { WithHydrationStrategy as n, withHydration as r, HydrationMeta as t };
|
|
51
|
-
//# sourceMappingURL=withHydration-
|
|
55
|
+
//# sourceMappingURL=withHydration-HIvO9ysY.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"withHydration-HIvO9ysY.d.mts","names":[],"sources":["../src/lib/withHydration.ts"],"mappings":";;;;;AAMA;;UAAiB,aAAA;EACf,QAAA;EACA,cAAA;AAAA;;;;;KAOU,qBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCI,aAAA,YAAyB,KAAA,UAAe,KAAA,CAAM,SAAA,CAAA,CAC5D,SAAA,EAAW,CAAA,EACX,QAAA,EAAU,qBAAA,GACT,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@conloca/astro-cms",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -12,49 +12,59 @@
|
|
|
12
12
|
"type": "module",
|
|
13
13
|
"main": "./dist/index.mjs",
|
|
14
14
|
"module": "./dist/index.mjs",
|
|
15
|
-
"types": "./dist/index.d.
|
|
15
|
+
"types": "./dist/index.d.mts",
|
|
16
16
|
"exports": {
|
|
17
17
|
"./package.json": "./package.json",
|
|
18
18
|
".": {
|
|
19
|
-
"types": "./dist/index.d.
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
20
|
"import": "./dist/index.mjs",
|
|
21
21
|
"default": "./dist/index.mjs"
|
|
22
22
|
},
|
|
23
|
-
"./
|
|
24
|
-
"types": "./dist/
|
|
25
|
-
"import": "./dist/
|
|
26
|
-
"default": "./dist/
|
|
23
|
+
"./node": {
|
|
24
|
+
"types": "./dist/node/index.d.mts",
|
|
25
|
+
"import": "./dist/node/index.mjs",
|
|
26
|
+
"default": "./dist/node/index.mjs"
|
|
27
|
+
},
|
|
28
|
+
"./node/content": {
|
|
29
|
+
"types": "./dist/node/content.d.mts",
|
|
30
|
+
"import": "./dist/node/content.mjs",
|
|
31
|
+
"default": "./dist/node/content.mjs"
|
|
27
32
|
},
|
|
28
33
|
"./cms-handler": {
|
|
29
|
-
"types": "./dist/cms-handler.d.
|
|
30
|
-
"import": "./dist/cms-handler.mjs",
|
|
31
|
-
"default": "./dist/cms-handler.mjs"
|
|
34
|
+
"types": "./dist/internal/cms-handler.d.mts",
|
|
35
|
+
"import": "./dist/internal/cms-handler.mjs",
|
|
36
|
+
"default": "./dist/internal/cms-handler.mjs"
|
|
32
37
|
},
|
|
33
38
|
"./collections": {
|
|
34
|
-
"types": "./dist/collections.d.
|
|
39
|
+
"types": "./dist/collections.d.mts",
|
|
35
40
|
"import": "./dist/collections.mjs",
|
|
36
41
|
"default": "./dist/collections.mjs"
|
|
37
42
|
},
|
|
38
|
-
"./
|
|
39
|
-
"types": "./
|
|
43
|
+
"./components": {
|
|
44
|
+
"types": "./dist/components.d.mts",
|
|
45
|
+
"import": "./dist/components.mjs",
|
|
46
|
+
"default": "./dist/components.mjs"
|
|
40
47
|
},
|
|
41
48
|
"./page-handler": {
|
|
42
|
-
"import": "./dist/
|
|
43
|
-
"default": "./dist/
|
|
49
|
+
"import": "./dist/internal/page-handler.astro",
|
|
50
|
+
"default": "./dist/internal/page-handler.astro"
|
|
51
|
+
},
|
|
52
|
+
"./virtual-modules": {
|
|
53
|
+
"types": "./src/virtual-modules.d.ts"
|
|
44
54
|
},
|
|
45
55
|
"./lib/hydration-script": {
|
|
46
|
-
"types": "./dist/lib/hydration-script.d.
|
|
56
|
+
"types": "./dist/lib/hydration-script.d.mts",
|
|
47
57
|
"import": "./dist/lib/hydration-script.mjs",
|
|
48
58
|
"default": "./dist/lib/hydration-script.mjs"
|
|
49
59
|
},
|
|
50
60
|
"./hydration": {
|
|
51
|
-
"types": "./dist/hydration.d.
|
|
61
|
+
"types": "./dist/hydration.d.mts",
|
|
52
62
|
"import": "./dist/hydration.mjs",
|
|
53
63
|
"default": "./dist/hydration.mjs"
|
|
54
64
|
}
|
|
55
65
|
},
|
|
56
66
|
"scripts": {
|
|
57
|
-
"build": "tsdown && mkdir -p dist/
|
|
67
|
+
"build": "tsdown && mkdir -p dist/internal && cp src/handlers/page-handler.astro dist/internal/page-handler.astro && cp src/internal/acorn-default.mjs dist/internal/acorn-default.mjs",
|
|
58
68
|
"test": "tsc-bun-test",
|
|
59
69
|
"test:watch": "bun test --watch"
|
|
60
70
|
},
|
|
@@ -63,24 +73,24 @@
|
|
|
63
73
|
"!**/*.tsbuildinfo"
|
|
64
74
|
],
|
|
65
75
|
"dependencies": {
|
|
66
|
-
"@conloca/cms-spa": "^0.1.
|
|
67
|
-
"@conloca/content-api": "^0.1.
|
|
68
|
-
"@conloca/
|
|
69
|
-
"@conloca/mdx": "^0.1.13",
|
|
76
|
+
"@conloca/cms-spa": "^0.1.15",
|
|
77
|
+
"@conloca/content-api": "^0.1.15",
|
|
78
|
+
"@conloca/mdx": "^0.1.15",
|
|
70
79
|
"@puckeditor/core": "^0.21.1",
|
|
80
|
+
"clsx": "^2.1.1",
|
|
71
81
|
"fast-glob": "^3.3.2",
|
|
72
82
|
"tslib": "^2.8.1"
|
|
73
83
|
},
|
|
74
84
|
"peerDependencies": {
|
|
75
|
-
"astro": "^5.0.0",
|
|
76
|
-
"vite": "^6.0.0",
|
|
85
|
+
"astro": "^5.0.0 || ^6.0.0",
|
|
86
|
+
"vite": "^6.0.0 || ^7.0.0",
|
|
77
87
|
"@vitejs/plugin-react": "^4.0.0",
|
|
78
88
|
"react": "^19.0.0",
|
|
79
89
|
"react-dom": "^19.0.0",
|
|
80
90
|
"zod": "^4.3.6"
|
|
81
91
|
},
|
|
82
92
|
"devDependencies": {
|
|
83
|
-
"@happy-dom/global-registrator": "
|
|
93
|
+
"@happy-dom/global-registrator": "20.6.1",
|
|
84
94
|
"@testing-library/jest-dom": "^6.9.1",
|
|
85
95
|
"@vitejs/plugin-react": "^4.5.2",
|
|
86
96
|
"astro": "5.17.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cms-handler.d.mts","names":[],"sources":["../src/mime-types.ts","../src/cms-handler.ts"],"mappings":";;;;cACa,cAAA,EAAgB,MAAA;;;;AAA7B;;;;;;;;ACuCA;;;;;;cAAa,GAAA,EAAK,QAAA"}
|
package/dist/cms-handler.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cms-handler.mjs","names":[],"sources":["../src/mime-types.ts","../src/path-validation.ts","../src/safe-json-stringify.ts","../src/cms-handler.ts"],"sourcesContent":["/** MIME types for SPA static asset serving. Covers all file types produced by the cms-spa build. */\nexport const SPA_MIME_TYPES: Record<string, string> = {\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.html': 'text/html',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.map': 'application/json',\n '.ico': 'image/x-icon',\n};\n","import { resolve, sep } from 'node:path';\n\n/**\n * Validates that a target path resolves within a base directory.\n * Prevents path traversal attacks by canonicalizing both paths\n * and checking that the target starts with the base path + separator\n * (or is exactly the base path).\n */\nexport function isPathWithinBase(basePath: string, targetPath: string): boolean {\n const resolvedBase = resolve(basePath);\n const resolvedTarget = resolve(targetPath);\n return resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + sep);\n}\n","/**\n * JSON.stringify replacement that escapes characters dangerous in HTML script contexts.\n *\n * When embedding JSON in `<script>` tags, characters like `<`, `>`, `&`, and `'` can break\n * out of the script context (e.g., `</script>` closes the tag prematurely). This function\n * replaces those characters with their Unicode escape equivalents, which are valid in both\n * JSON and JavaScript string contexts.\n *\n * @see https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n */\nexport function safeJsonStringify(data: Record<string, unknown> | unknown[] | string | number | boolean | null): string;\nexport function safeJsonStringify(data: unknown): string | undefined;\nexport function safeJsonStringify(data: unknown): string | undefined {\n const json = JSON.stringify(data);\n if (json === undefined) return undefined;\n return json.replace(/[<>&']/g, (ch) => `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport spaConfig from 'virtual:conloca-config';\nimport { contentOptions, getDataCollection, getPagesByPrefix } from 'virtual:conloca-page-api';\nimport routingConfig from 'virtual:conloca-routing-config';\nimport {\n type CFAccessResult,\n createContentAPI,\n createContentAPIRouter,\n FileSystemContentAPI,\n validateCFAccessRequest,\n} from '@conloca/content-api/node';\nimport type { APIRoute } from 'astro';\nimport { SPA_MIME_TYPES } from './mime-types.js';\nimport { isPathWithinBase } from './path-validation.js';\nimport { safeJsonStringify } from './safe-json-stringify.js';\nimport type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from './types.js';\n\nexport { SPA_MIME_TYPES } from './mime-types.js';\n\n// Get the path to the cms-spa package by resolving its package.json\nconst require = createRequire(import.meta.url);\nconst cmsSpaPath = dirname(require.resolve('@conloca/cms-spa/package.json'));\n\n/**\n * Unified CMS handler - single entry point for all CMS routes.\n *\n * This handler:\n * 1. Validates CF Access authentication ONCE at the top\n * 2. Routes to appropriate sub-handler based on path:\n * - /api/data-context -> handleDataContext()\n * - /api/* -> handleContentApi()\n * - /* -> handleSpa()\n *\n * Benefits:\n * - Single authentication check prevents security gaps\n * - New routes automatically inherit auth protection\n * - Easier to audit security\n */\nexport const ALL: APIRoute = async ({ params, request }) => {\n // Step 1: Validate CF Access ONCE\n const cfResult = await validateCFAccessRequest(request);\n if (!cfResult.valid && cfResult.required) {\n return new Response(JSON.stringify({ error: 'Unauthorized' }), {\n status: 401,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Step 2: Route based on path\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // Route to appropriate handler\n if (path.startsWith('api/data-context')) {\n return handleDataContext(request);\n }\n\n if (path.startsWith('api/')) {\n return handleContentApi(request, cfResult);\n }\n\n return handleSpa(params, request);\n};\n\n// ============================================================================\n// SPA Handler (from spa-handler.ts)\n// ============================================================================\n\n/**\n * Generate HTML for dev mode that loads cms-spa source through Vite.\n * This ensures React is resolved from Vite's pre-bundled deps, not from the cms-spa bundle.\n */\nfunction generateDevHtml(config: typeof spaConfig): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Conloca CMS</title>\n <link rel=\"stylesheet\" href=\"${config.basename}/main.css\" />\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(config)};\n </script>\n <script type=\"module\" src=\"${config.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/content-listener.js\"></script>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"${config.basename}/cms-spa-entry.js\"></script>\n</body>\n</html>`;\n}\n\n/**\n * Load the HTML at runtime (production only)\n */\nasync function loadIndexHtml(): Promise<string> {\n const spaDir = join(cmsSpaPath, 'dist/spa');\n const { readdir } = await import('node:fs/promises');\n const files = await readdir(spaDir);\n const htmlFile = files.find((f) => f.startsWith('index.') && f.endsWith('.html'));\n\n if (!htmlFile) {\n throw new Error('No index.html found in @conloca/cms-spa dist/spa');\n }\n\n const htmlPath = join(spaDir, htmlFile);\n const html = await readFile(htmlPath, 'utf-8');\n\n return html;\n}\n\n/**\n * Handle SPA requests - serve CMS admin interface\n */\nasync function handleSpa(params: { path?: string | string[] }, request: Request): Promise<Response> {\n // The path parameter is an array for [...path] routes\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // For the root path or any path without an extension, serve the HTML\n if (!path || !path.includes('.')) {\n try {\n let html: string;\n\n // In dev mode, generate HTML that loads source through Vite\n // In production, load the pre-built HTML from cms-spa dist\n if (import.meta.env.DEV) {\n html = generateDevHtml(spaConfig);\n } else {\n html = await loadIndexHtml();\n // Inject CMS configuration and load virtual modules\n const configScript = `\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(spaConfig)};\n </script>\n <script type=\"module\" src=\"${spaConfig.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/content-listener.js\"></script>\n `;\n // Inject the script at the top to ensure config is available first\n html = html.replace('<head>', `<head>${configScript}`);\n }\n\n return new Response(html, {\n headers: {\n 'Content-Type': 'text/html',\n 'Cache-Control': 'no-store, must-revalidate',\n 'X-HMR': 'spa-page',\n },\n });\n } catch (error) {\n console.error('Error loading CMS HTML:', error);\n return new Response('CMS build not found. Run nx build @conloca/astro-cms', {\n status: 500,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n }\n\n // For asset requests, serve them from the cms-spa dist/spa directory\n try {\n const spaBase = join(cmsSpaPath, 'dist/spa');\n const assetPath = join(spaBase, path);\n\n if (!isPathWithinBase(spaBase, assetPath)) {\n console.warn('[security] Path traversal attempt blocked:', path);\n return new Response('Forbidden', { status: 403 });\n }\n\n const content = await readFile(assetPath);\n\n // Determine content type from extension map with octet-stream fallback\n const ext = path.substring(path.lastIndexOf('.'));\n const contentType = SPA_MIME_TYPES[ext] ?? 'application/octet-stream';\n\n return new Response(content as BodyInit, {\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': import.meta.env.DEV ? 'no-store, must-revalidate' : 'public, max-age=31536000',\n },\n });\n } catch {\n return new Response('Not found', { status: 404 });\n }\n}\n\n// ============================================================================\n// Data Context Handler (from data-context-handler.ts)\n// ============================================================================\n\n/**\n * Handle DataContext API requests - returns data bindings for CMS editor\n */\nasync function handleDataContext(request: Request): Promise<Response> {\n try {\n const url = new URL(request.url);\n const pageId = url.searchParams.get('pageId');\n\n if (!pageId) {\n return jsonResponse({});\n }\n\n const config = routingConfig as ResolvedRoutingConfig;\n if (!config.enabled) {\n return jsonResponse({});\n }\n\n // Find which route this page belongs to by loading the page manifest\n // and matching its collection against route configs\n const contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n });\n\n const locale = contentOptions.locale;\n\n // Get the page manifest to determine its collection\n const content = await contentApi.getContent(pageId);\n if (!content) {\n return jsonResponse({});\n }\n const pageCollection = content.collection || 'pages';\n\n // Find the route whose collection matches this page\n const routeEntry = Object.entries(config.routes).find(\n ([, routeConfig]) => routeConfig.collection === pageCollection,\n );\n\n if (!routeEntry) {\n return jsonResponse({});\n }\n\n const [, routeConfig] = routeEntry;\n const hasCollections = routeConfig.dataBindings?.collections?.length;\n const hasPages = routeConfig.dataBindings?.pages?.prefix;\n\n if (!hasCollections && !hasPages) {\n return jsonResponse({});\n }\n\n // Build DataContext using the same logic as page-handler.astro\n const collections: Record<string, DataCollectionEntry[]> = {};\n let pages: PageReference[] | undefined;\n\n if (hasCollections && routeConfig.dataBindings?.collections) {\n for (const collectionName of routeConfig.dataBindings.collections) {\n try {\n const bindingLocale = routeConfig.dataBindings.locale ?? locale;\n collections[collectionName] = await getDataCollection(collectionName, bindingLocale);\n } catch {\n collections[collectionName] = [];\n }\n }\n }\n\n if (hasPages && routeConfig.dataBindings?.pages) {\n try {\n const pagesConfig = routeConfig.dataBindings.pages;\n pages = await getPagesByPrefix(pagesConfig.prefix, {\n sort: pagesConfig.sort,\n limit: pagesConfig.limit,\n });\n } catch {\n pages = [];\n }\n }\n\n const dataContext: DataContext = {\n collections,\n pages,\n locale: routeConfig.dataBindings.locale ?? locale,\n siteName: contentOptions.siteName,\n };\n\n return jsonResponse({ dataContext });\n } catch {\n return jsonResponse({});\n }\n}\n\nfunction jsonResponse(data: object): Response {\n return new Response(JSON.stringify(data), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n// ============================================================================\n// Content API Handler (from content-api-handler.ts)\n// ============================================================================\n\n/**\n * Handle Content API requests - delegates to Hono router\n */\nasync function handleContentApi(request: Request, cfResult: CFAccessResult): Promise<Response> {\n const contentRoot = import.meta.env.CONLOCA_CONTENT_ROOT || './content';\n const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || './canvas';\n\n // FileSystemContentAPI.create() handles caching internally\n const contentApi = await FileSystemContentAPI.create({ contentRoot, canvasDir });\n\n // Create the Hono router with assets and content root for git operations\n const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';\n const app = createContentAPIRouter(contentApi, { ...(assetsPath && { assetsPath }), contentRoot });\n\n // Extract the path after the API base\n const url = new URL(request.url);\n // Find where /api/ appears in the pathname\n const apiIndex = url.pathname.indexOf('/api/');\n if (apiIndex === -1) {\n return new Response('Invalid API path', { status: 400 });\n }\n const basePath = url.pathname.substring(0, apiIndex + 4); // Include '/api'\n const path = url.pathname.substring(basePath.length) || '/';\n\n // Pass user to Hono via headers for downstream use (needed for git commit attribution)\n const headers = new Headers(request.headers);\n if (cfResult.user) {\n if (cfResult.user.email) {\n headers.set('X-CF-User-Email', cfResult.user.email);\n }\n if (cfResult.user.sub) {\n headers.set('X-CF-User-Sub', cfResult.user.sub);\n }\n }\n\n // Create a new request with the correct path for Hono\n // Note: duplex option is required for Node.js fetch when sending a body\n // but not in the TypeScript RequestInit type\n const honoRequest = new Request(new URL(path + url.search, 'http://localhost').href, {\n method: request.method,\n headers,\n body: request.body,\n ...(request.body && { duplex: 'half' }),\n } as RequestInit);\n\n // Let Hono handle the request\n const response = await app.fetch(honoRequest);\n\n // Return the Hono response\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n"],"mappings":";;;;;;;;;;AACA,MAAa,iBAAyC;CACpD,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,QAAQ;CACT;;;;;;;;;;ACVD,SAAgB,iBAAiB,UAAkB,YAA6B;CAC9E,MAAM,eAAe,QAAQ,SAAS;CACtC,MAAM,iBAAiB,QAAQ,WAAW;AAC1C,QAAO,mBAAmB,gBAAgB,eAAe,WAAW,eAAe,IAAI;;;;;ACCzF,SAAgB,kBAAkB,MAAmC;CACnE,MAAM,OAAO,KAAK,UAAU,KAAK;AACjC,KAAI,SAAS,OAAW,QAAO;AAC/B,QAAO,KAAK,QAAQ,YAAY,OAAO,MAAM,GAAG,WAAW,EAAE,CAAC,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI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