@conloca/astro-cms 0.1.9 → 0.1.11

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.
Files changed (36) hide show
  1. package/dist/cms-handler.d.mts +0 -1
  2. package/dist/cms-handler.d.mts.map +1 -1
  3. package/dist/cms-handler.mjs +2 -2
  4. package/dist/cms-handler.mjs.map +1 -1
  5. package/dist/collections.d.mts +0 -1
  6. package/dist/collections.d.mts.map +1 -1
  7. package/dist/collections.mjs +1 -1
  8. package/dist/collections.mjs.map +1 -1
  9. package/dist/components.d.mts +1 -1
  10. package/dist/components.d.mts.map +1 -1
  11. package/dist/components.mjs +2 -2
  12. package/dist/components.mjs.map +1 -1
  13. package/dist/handlers/page-handler.astro +1 -1
  14. package/dist/hydration.d.mts +3 -2
  15. package/dist/hydration.mjs +1 -1
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +11 -11
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/lib/hydration-script.d.mts +31 -2
  21. package/dist/lib/hydration-script.d.mts.map +1 -0
  22. package/dist/{loader-BYmsavWc.mjs → loader-W3i9kf3p.mjs} +1 -1
  23. package/dist/loader-W3i9kf3p.mjs.map +1 -0
  24. package/dist/{serialize-props-CQDv661k.mjs → serialize-props-DqfDQeFl.mjs} +1 -1
  25. package/dist/serialize-props-DqfDQeFl.mjs.map +1 -0
  26. package/dist/{hydration-script-CKamSyIx.d.mts → types-Bsd_qENn.d.mts} +3 -31
  27. package/dist/types-Bsd_qENn.d.mts.map +1 -0
  28. package/dist/{withHydration-DfAwNHmI.mjs → withHydration-692fMySA.mjs} +1 -1
  29. package/dist/{withHydration-DfAwNHmI.mjs.map → withHydration-692fMySA.mjs.map} +1 -1
  30. package/dist/{withHydration-C6l6XnF2.d.mts → withHydration-BGgQDE-H.d.mts} +1 -2
  31. package/dist/withHydration-BGgQDE-H.d.mts.map +1 -0
  32. package/package.json +23 -18
  33. package/dist/hydration-script-CKamSyIx.d.mts.map +0 -1
  34. package/dist/loader-BYmsavWc.mjs.map +0 -1
  35. package/dist/serialize-props-CQDv661k.mjs.map +0 -1
  36. package/dist/withHydration-C6l6XnF2.d.mts.map +0 -1
@@ -1,7 +1,6 @@
1
1
  import { APIRoute } from "astro";
2
2
 
3
3
  //#region src/cms-handler.d.ts
4
-
5
4
  /**
6
5
  * Unified CMS handler - single entry point for all CMS routes.
7
6
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cms-handler.d.mts","names":[],"sources":["../src/cms-handler.ts"],"sourcesContent":[],"mappings":";;;;;;AAmCA;;;;;;;;;;;;;cAAa,KAAK"}
1
+ {"version":3,"file":"cms-handler.d.mts","names":[],"sources":["../src/cms-handler.ts"],"mappings":";;;;;AAmCA;;;;;;;;;;;;;cAAa,GAAA,EAAK,QAAA"}
@@ -119,7 +119,7 @@ async function handleSpa(params, request) {
119
119
  else if (path.endsWith(".json")) contentType = "application/json";
120
120
  return new Response(content, { headers: {
121
121
  "Content-Type": contentType,
122
- "Cache-Control": "public, max-age=31536000"
122
+ "Cache-Control": import.meta.env.DEV ? "no-cache" : "public, max-age=31536000"
123
123
  } });
124
124
  } catch {
125
125
  return new Response("Not found", { status: 404 });
@@ -142,7 +142,7 @@ async function handleDataContext(request) {
142
142
  const content = await contentApi.getContent(pageId);
143
143
  if (!content) return jsonResponse({});
144
144
  const pageCollection = content.collection || "pages";
145
- const routeEntry = Object.entries(config.routes).find(([, routeConfig$1]) => routeConfig$1.collection === pageCollection);
145
+ const routeEntry = Object.entries(config.routes).find(([, routeConfig]) => routeConfig.collection === pageCollection);
146
146
  if (!routeEntry) return jsonResponse({});
147
147
  const [, routeConfig] = routeEntry;
148
148
  const hasCollections = routeConfig.dataBindings?.collections?.length;
@@ -1 +1 @@
1
- {"version":3,"file":"cms-handler.mjs","names":["ALL: APIRoute","html: string","routeConfig","collections: Record<string, DataCollectionEntry[]>","pages: PageReference[] | undefined"],"sources":["../src/cms-handler.ts"],"sourcesContent":["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 type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from './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__ = ${JSON.stringify(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 console.log('[cms-handler] SPA request for path:', path, 'params:', params, 'URL:', request.url);\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 console.log('[cms-handler] Dev mode: serving generated HTML with virtual module entry');\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__ = ${JSON.stringify(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 // Log what JS files are referenced in the HTML\n const scriptMatches = html.match(/<script[^>]+src=\"([^\"]+)\"/g);\n console.log('[cms-handler] Script tags in HTML:', scriptMatches);\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 assetPath = join(cmsSpaPath, 'dist/spa', path);\n const content = await readFile(assetPath);\n\n // Determine content type\n let contentType = 'application/octet-stream';\n if (path.endsWith('.js')) contentType = 'application/javascript';\n else if (path.endsWith('.css')) contentType = 'text/css';\n else if (path.endsWith('.html')) contentType = 'text/html';\n else if (path.endsWith('.json')) contentType = 'application/json';\n\n return new Response(content as BodyInit, {\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': '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 headers.set('X-CF-User-Email', cfResult.user.email);\n headers.set('X-CF-User-Sub', cfResult.user.sub);\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":";;;;;;;;;AAkBA,MAAM,aAAa,QADH,cAAc,OAAO,KAAK,IAAI,CACX,QAAQ,gCAAgC,CAAC;;;;;;;;;;;;;;;;AAiB5E,MAAaA,MAAgB,OAAO,EAAE,QAAQ,cAAc;CAE1D,MAAM,WAAW,MAAM,wBAAwB,QAAQ;AACvD,KAAI,CAAC,SAAS,SAAS,SAAS,SAC9B,QAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,gBAAgB,CAAC,EAAE;EAC7D,QAAQ;EACR,SAAS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B,OAAO;EAAE;EAAa;EAAW,CAAC;CAGhF,MAAM,aAAa,OAAO,KAAK,IAAI,uBAAuB;CAC1D,MAAM,MAAM,uBAAuB,YAAY;EAAE,GAAI,cAAc,EAAE,YAAY;EAAG;EAAa,CAAC;CAGlG,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;CAEhC,MAAM,WAAW,IAAI,SAAS,QAAQ,QAAQ;AAC9C,KAAI,aAAa,GACf,QAAO,IAAI,SAAS,oBAAoB,EAAE,QAAQ,KAAK,CAAC;CAE1D,MAAM,WAAW,IAAI,SAAS,UAAU,GAAG,WAAW,EAAE;CACxD,MAAM,OAAO,IAAI,SAAS,UAAU,SAAS,OAAO,IAAI;CAGxD,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,KAAI,SAAS,MAAM;AACjB,UAAQ,IAAI,mBAAmB,SAAS,KAAK,MAAM;AACnD,UAAQ,IAAI,iBAAiB,SAAS,KAAK,IAAI;;CAMjD,MAAM,cAAc,IAAI,QAAQ,IAAI,IAAI,OAAO,IAAI,QAAQ,mBAAmB,CAAC,MAAM;EACnF,QAAQ,QAAQ;EAChB;EACA,MAAM,QAAQ;EACd,GAAI,QAAQ,QAAQ,EAAE,QAAQ,QAAQ;EACvC,CAAgB;CAGjB,MAAM,WAAW,MAAM,IAAI,MAAM,YAAY;AAG7C,QAAO,IAAI,SAAS,SAAS,MAAM;EACjC,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,SAAS,SAAS;EACnB,CAAC"}
1
+ {"version":3,"file":"cms-handler.mjs","names":[],"sources":["../src/cms-handler.ts"],"sourcesContent":["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 type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from './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__ = ${JSON.stringify(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 console.log('[cms-handler] SPA request for path:', path, 'params:', params, 'URL:', request.url);\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 console.log('[cms-handler] Dev mode: serving generated HTML with virtual module entry');\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__ = ${JSON.stringify(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 // Log what JS files are referenced in the HTML\n const scriptMatches = html.match(/<script[^>]+src=\"([^\"]+)\"/g);\n console.log('[cms-handler] Script tags in HTML:', scriptMatches);\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 assetPath = join(cmsSpaPath, 'dist/spa', path);\n const content = await readFile(assetPath);\n\n // Determine content type\n let contentType = 'application/octet-stream';\n if (path.endsWith('.js')) contentType = 'application/javascript';\n else if (path.endsWith('.css')) contentType = 'text/css';\n else if (path.endsWith('.html')) contentType = 'text/html';\n else if (path.endsWith('.json')) contentType = 'application/json';\n\n return new Response(content as BodyInit, {\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': import.meta.env.DEV ? 'no-cache' : '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 headers.set('X-CF-User-Email', cfResult.user.email);\n headers.set('X-CF-User-Sub', cfResult.user.sub);\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":";;;;;;;;;AAkBA,MAAM,aAAa,QADH,cAAc,OAAO,KAAK,IAAI,CACX,QAAQ,gCAAgC,CAAC;;;;;;;;;;;;;;;;AAiB5E,MAAa,MAAgB,OAAO,EAAE,QAAQ,cAAc;CAE1D,MAAM,WAAW,MAAM,wBAAwB,QAAQ;AACvD,KAAI,CAAC,SAAS,SAAS,SAAS,SAC9B,QAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,gBAAgB,CAAC,EAAE;EAC7D,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CAAC;CAIJ,MAAM,YAAY,OAAO;CACzB,MAAM,OAAO,MAAM,QAAQ,UAAU,GAAG,UAAU,KAAK,IAAI,GAAG,aAAa;AAG3E,KAAI,KAAK,WAAW,mBAAmB,CACrC,QAAO,kBAAkB,QAAQ;AAGnC,KAAI,KAAK,WAAW,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,IAAI;CAEhC,MAAM,WAAW,IAAI,SAAS,QAAQ,QAAQ;AAC9C,KAAI,aAAa,GACf,QAAO,IAAI,SAAS,oBAAoB,EAAE,QAAQ,KAAK,CAAC;CAE1D,MAAM,WAAW,IAAI,SAAS,UAAU,GAAG,WAAW,EAAE;CACxD,MAAM,OAAO,IAAI,SAAS,UAAU,SAAS,OAAO,IAAI;CAGxD,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,KAAI,SAAS,MAAM;AACjB,UAAQ,IAAI,mBAAmB,SAAS,KAAK,MAAM;AACnD,UAAQ,IAAI,iBAAiB,SAAS,KAAK,IAAI;;CAMjD,MAAM,cAAc,IAAI,QAAQ,IAAI,IAAI,OAAO,IAAI,QAAQ,mBAAmB,CAAC,MAAM;EACnF,QAAQ,QAAQ;EAChB;EACA,MAAM,QAAQ;EACd,GAAI,QAAQ,QAAQ,EAAE,QAAQ,QAAQ;EACvC,CAAgB;CAGjB,MAAM,WAAW,MAAM,IAAI,MAAM,YAAY;AAG7C,QAAO,IAAI,SAAS,SAAS,MAAM;EACjC,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,SAAS,SAAS;EACnB,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { defineCollection } from "astro:content";
2
2
 
3
3
  //#region src/collections.d.ts
4
-
5
4
  /**
6
5
  * Options for createConlocaCollections().
7
6
  */
@@ -1 +1 @@
1
- {"version":3,"file":"collections.d.mts","names":[],"sources":["../src/collections.ts"],"sourcesContent":[],"mappings":";;;;;;AAQA;AAUiB,UAVA,+BAAA,CAUwB;EAEO;EAAlB,WAAA,CAAA,EAAA,MAAA;EAAf;EAAM,IAAA,CAAA,EAAA,MAAA;AAerB;;;;AAEU,UAnBO,wBAAA,CAmBP;;eAjBK,eAAe,kBAAkB;;;;;;;;;;;;;;iBAe1B,wBAAA,WACX,kCACR,QAAQ"}
1
+ {"version":3,"file":"collections.d.mts","names":[],"sources":["../src/collections.ts"],"mappings":";;;;;AAQA;UAAiB,+BAAA;;EAEf,WAAA;EAEI;EAAJ,IAAA;AAAA;;;;UAMe,wBAAA;EAEI;EAAnB,WAAA,EAAa,MAAA,SAAe,UAAA,QAAkB,gBAAA;AAAA;;;;;;AAehD;;;;;;;iBAAsB,wBAAA,CACpB,OAAA,GAAS,+BAAA,GACR,OAAA,CAAQ,wBAAA"}
@@ -1,4 +1,4 @@
1
- import { t as conlocaLoader } from "./loader-BYmsavWc.mjs";
1
+ import { t as conlocaLoader } from "./loader-W3i9kf3p.mjs";
2
2
  import { blockMetaSchema, dataMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
3
3
  import { createContentAPI } from "@conloca/content-api/node";
4
4
  import { defineCollection } from "astro:content";
@@ -1 +1 @@
1
- {"version":3,"file":"collections.mjs","names":["collections: Record<string, ReturnType<typeof defineCollection>>"],"sources":["../src/collections.ts"],"sourcesContent":["import { defineCollection } from 'astro:content';\nimport { createContentAPI } from '@conloca/content-api/node';\nimport { blockMetaSchema, dataMetaSchema, pageMetaSchema } from '@conloca/content-api/schemas';\nimport { conlocaLoader } from './loader';\n\n/**\n * Options for createConlocaCollections().\n */\nexport interface CreateConlocaCollectionsOptions {\n /** Path to content root directory. @default './content' */\n contentRoot?: string;\n /** Site name for multi-site setups. @default 'default' */\n site?: string;\n}\n\n/**\n * Return type of createConlocaCollections().\n */\nexport interface ConlocaCollectionsResult {\n /** Astro Content Collections definitions - export this as `collections` */\n collections: Record<string, ReturnType<typeof defineCollection>>;\n}\n\n/**\n * Creates Astro Content Collections by discovering from indexed content.\n * Uses content-api to find collections that have content.\n *\n * @example\n * ```typescript\n * // src/content.config.ts\n * import { createConlocaCollections } from '@conloca/astro-cms/collections';\n *\n * export const { collections } = await createConlocaCollections();\n * ```\n */\nexport async function createConlocaCollections(\n options: CreateConlocaCollectionsOptions = {},\n): Promise<ConlocaCollectionsResult> {\n const { contentRoot = './content', site = 'default' } = options;\n\n const api = await createContentAPI({ contentRoot });\n const collections: Record<string, ReturnType<typeof defineCollection>> = {};\n\n // Add block collections\n for (const name of api.blocks.collections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'block' }),\n schema: blockMetaSchema,\n });\n }\n\n // Add data collections\n for (const name of api.data.collections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }),\n schema: dataMetaSchema,\n });\n }\n\n // Add page collections for this site\n const siteCollections = api.getSite(site)?.collections ?? new Set<string>();\n for (const name of siteCollections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'page' }),\n schema: pageMetaSchema.passthrough(),\n });\n }\n\n return { collections };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,eAAsB,yBACpB,UAA2C,EAAE,EACV;CACnC,MAAM,EAAE,cAAc,aAAa,OAAO,cAAc;CAExD,MAAM,MAAM,MAAM,iBAAiB,EAAE,aAAa,CAAC;CACnD,MAAMA,cAAmE,EAAE;AAG3E,MAAK,MAAM,QAAQ,IAAI,OAAO,YAC5B,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAS,CAAC;EAC7E,QAAQ;EACT,CAAC;AAIJ,MAAK,MAAM,QAAQ,IAAI,KAAK,YAC1B,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAQ,CAAC;EAC5E,QAAQ;EACT,CAAC;CAIJ,MAAM,kBAAkB,IAAI,QAAQ,KAAK,EAAE,+BAAe,IAAI,KAAa;AAC3E,MAAK,MAAM,QAAQ,gBACjB,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAQ,CAAC;EAC5E,QAAQ,eAAe,aAAa;EACrC,CAAC;AAGJ,QAAO,EAAE,aAAa"}
1
+ {"version":3,"file":"collections.mjs","names":[],"sources":["../src/collections.ts"],"sourcesContent":["import { defineCollection } from 'astro:content';\nimport { createContentAPI } from '@conloca/content-api/node';\nimport { blockMetaSchema, dataMetaSchema, pageMetaSchema } from '@conloca/content-api/schemas';\nimport { conlocaLoader } from './loader';\n\n/**\n * Options for createConlocaCollections().\n */\nexport interface CreateConlocaCollectionsOptions {\n /** Path to content root directory. @default './content' */\n contentRoot?: string;\n /** Site name for multi-site setups. @default 'default' */\n site?: string;\n}\n\n/**\n * Return type of createConlocaCollections().\n */\nexport interface ConlocaCollectionsResult {\n /** Astro Content Collections definitions - export this as `collections` */\n collections: Record<string, ReturnType<typeof defineCollection>>;\n}\n\n/**\n * Creates Astro Content Collections by discovering from indexed content.\n * Uses content-api to find collections that have content.\n *\n * @example\n * ```typescript\n * // src/content.config.ts\n * import { createConlocaCollections } from '@conloca/astro-cms/collections';\n *\n * export const { collections } = await createConlocaCollections();\n * ```\n */\nexport async function createConlocaCollections(\n options: CreateConlocaCollectionsOptions = {},\n): Promise<ConlocaCollectionsResult> {\n const { contentRoot = './content', site = 'default' } = options;\n\n const api = await createContentAPI({ contentRoot });\n const collections: Record<string, ReturnType<typeof defineCollection>> = {};\n\n // Add block collections\n for (const name of api.blocks.collections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'block' }),\n // Cast needed: Astro uses Zod v3 BaseSchema types, our schemas are Zod v4\n schema: blockMetaSchema as never,\n });\n }\n\n // Add data collections\n for (const name of api.data.collections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }),\n schema: dataMetaSchema as never,\n });\n }\n\n // Add page collections for this site\n const siteCollections = api.getSite(site)?.collections ?? new Set<string>();\n for (const name of siteCollections) {\n collections[name] = defineCollection({\n loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'page' }),\n schema: pageMetaSchema.passthrough() as never,\n });\n }\n\n return { collections };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,eAAsB,yBACpB,UAA2C,EAAE,EACV;CACnC,MAAM,EAAE,cAAc,aAAa,OAAO,cAAc;CAExD,MAAM,MAAM,MAAM,iBAAiB,EAAE,aAAa,CAAC;CACnD,MAAM,cAAmE,EAAE;AAG3E,MAAK,MAAM,QAAQ,IAAI,OAAO,YAC5B,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAS,CAAC;EAE7E,QAAQ;EACT,CAAC;AAIJ,MAAK,MAAM,QAAQ,IAAI,KAAK,YAC1B,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAQ,CAAC;EAC5E,QAAQ;EACT,CAAC;CAIJ,MAAM,kBAAkB,IAAI,QAAQ,KAAK,EAAE,+BAAe,IAAI,KAAa;AAC3E,MAAK,MAAM,QAAQ,gBACjB,aAAY,QAAQ,iBAAiB;EACnC,QAAQ,cAAc;GAAE,YAAY;GAAM;GAAa;GAAM,MAAM;GAAQ,CAAC;EAC5E,QAAQ,eAAe,aAAa;EACrC,CAAC;AAGJ,QAAO,EAAE,aAAa"}
@@ -1,4 +1,4 @@
1
- import { Config, Data } from "@measured/puck";
1
+ import { Config, Data } from "@puckeditor/core";
2
2
  import * as react_jsx_runtime0 from "react/jsx-runtime";
3
3
  import { ComponentType } from "react";
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"components.d.mts","names":[],"sources":["../src/components/RenderWithBlocks.tsx","../src/components/RenderWithHydration.tsx"],"sourcesContent":[],"mappings":";;;;;UAMU,YAAA;;;EAAA,SAAA,EAGG,aAHS;AA8HtB;;;;;;;;;ACnIkD;AAkBlD;;;;;;;;;;;;;;;;;;;;;;;;iBDiHgB,4BAAA,SAAqC,cAAc,qBAAqB,iBAAiB;;;UC/H/F,wBAAA;UACA;QACF;;ADLmC;AAkI3C;;;;;;;;iBCjHgB,mBAAA;;;GAAsC,2BAAwB,kBAAA,CAAA,GAAA,CAAA"}
1
+ {"version":3,"file":"components.d.mts","names":[],"sources":["../src/components/RenderWithBlocks.tsx","../src/components/RenderWithHydration.tsx"],"mappings":";;;;;UAMU,YAAA;EACR,EAAA;EACA,KAAA;EACA,SAAA,EAAW,aAAA;AAAA;;;;;;;;;AA2Hb;;;;;;;;;;;;;;;;;;;;;ACpIqD;;;;iBDoIrC,4BAAA,CAA6B,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,aAAA,EAAe,YAAA,KAAiB,aAAA;;;UC/H/F,wBAAA;EACR,MAAA,EAAQ,MAAA;EACR,IAAA,EAAM,IAAA;AAAA;ADLmC;;;;;;;;;AAAA,iBCiB3B,mBAAA,CAAA;EAAsB,MAAA;EAAQ;AAAA,GAAQ,wBAAA,GAAwB,kBAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -1,5 +1,5 @@
1
- import { i as isHydratable, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-CQDv661k.mjs";
2
- import { Render } from "@measured/puck";
1
+ import { i as isHydratable, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-DqfDQeFl.mjs";
2
+ import { Render } from "@puckeditor/core";
3
3
  import { Fragment, jsx } from "react/jsx-runtime";
4
4
 
5
5
  //#region src/components/HydrationWrapper.tsx
@@ -1 +1 @@
1
- {"version":3,"file":"components.mjs","names":["blockComponents: Record<string, ComponentConfig>","blockCategoryList: string[]","enhancedConfig: Config"],"sources":["../src/components/HydrationWrapper.tsx","../src/components/RenderWithHydration.tsx","../src/components/RenderWithBlocks.tsx"],"sourcesContent":["import type { ReactNode } from 'react'\nimport type { HydrationStrategy } from '../types.js'\nimport { serializeProps } from '../lib/serialize-props.js'\n\ninterface HydrationWrapperProps {\n componentName: string\n strategy: HydrationStrategy\n props: Record<string, unknown>\n children: ReactNode\n}\n\n/**\n * Wraps hydratable components with data attributes for browser hydration.\n *\n * When strategy is 'none', renders children directly without wrapper overhead.\n * Otherwise, wraps in a div with data-hydrate attributes that the browser\n * hydration script uses to find and hydrate components.\n */\nexport function HydrationWrapper({\n componentName,\n strategy,\n props,\n children,\n}: HydrationWrapperProps) {\n // No hydration needed - render children directly without wrapper\n if (strategy === 'none') {\n return <>{children}</>\n }\n\n // Wrap with hydration markers for the browser script to find\n return (\n <div\n data-hydrate={componentName}\n data-hydrate-strategy={strategy}\n data-props={serializeProps(props)}\n >\n {children}\n </div>\n )\n}\n","import { Render } from '@measured/puck'\nimport type { Config, Data } from '@measured/puck'\nimport { HydrationWrapper } from './HydrationWrapper.js'\nimport { isHydratable } from '../lib/hydration-utils.js'\n\ninterface RenderWithHydrationProps {\n config: Config\n data: Data\n}\n\n/**\n * Wrapper around Puck's Render component that adds hydration support.\n *\n * For each component with a hydration strategy configured, wraps the\n * component's render output with HydrationWrapper to add data-hydrate\n * attributes for browser-side hydration.\n *\n * Non-hydratable components render without any wrapper overhead.\n */\nexport function RenderWithHydration({ config, data }: RenderWithHydrationProps) {\n // Create wrapped config with hydration-aware render functions\n const wrappedConfig: Config = {\n ...config,\n components: Object.fromEntries(\n Object.entries(config.components).map(([name, componentConfig]) => {\n const strategy = isHydratable(name, config)\n\n if (strategy === 'none') {\n // No wrapping needed - component stays static\n return [name, componentConfig]\n }\n\n // Wrap the render function so its output becomes HydrationWrapper children\n const originalRender = componentConfig.render\n return [\n name,\n {\n ...componentConfig,\n render: (props) => (\n <HydrationWrapper\n componentName={name}\n strategy={strategy}\n props={props}\n >\n {originalRender(props)}\n </HydrationWrapper>\n ),\n },\n ]\n })\n ),\n }\n\n return <Render config={wrappedConfig} data={data} />\n}\n","import type { ComponentConfig, Config, Data } from '@measured/puck';\nimport { Render } from '@measured/puck';\nimport type { ComponentType } from 'react';\nimport { RenderWithHydration } from './RenderWithHydration.js';\nimport { hasHydratableComponents } from '../lib/hydration-utils.js';\n\ninterface MDXComponent {\n id: string;\n title: string;\n Component: ComponentType;\n}\n\ninterface RenderWithBlocksProps {\n config: Config;\n data: Data;\n mdxComponents: MDXComponent[];\n}\n\n/**\n * Internal component for rendering Puck pages with MDX blocks.\n *\n * Uses Puck's Render component for static rendering in Astro.\n * All content is pre-rendered at build time with no client-side JavaScript.\n *\n * MDX blocks are passed as React components (not HTML strings), which:\n * - Avoids dangerouslySetInnerHTML security risks\n * - More efficient (no HTML conversion round-trip)\n * - Type-safe with proper React component types\n *\n * **Note:** This function is internal. Use `createPageRendererWithBlocks` instead,\n * which provides a factory pattern to handle the closure correctly.\n *\n * @internal\n * @param props - Component props\n * @param props.config - Base Puck configuration\n * @param props.data - Puck page data containing component tree\n * @param props.mdxComponents - Array of evaluated MDX React components\n */\nfunction RenderWithBlocks({ config, data, mdxComponents }: RenderWithBlocksProps) {\n // Build enhanced config with MDX blocks\n const blockComponents: Record<string, ComponentConfig> = {};\n const blockCategoryList: string[] = [];\n\n // Create component configs for each block\n mdxComponents.forEach((block) => {\n const componentKey = `Block_${block.id}`;\n\n // Capture component in closure - Puck doesn't persist defaultProps reliably\n const BlockComponent = block.Component;\n\n blockComponents[componentKey] = {\n label: block.title,\n fields: {},\n defaultProps: {},\n render: () => {\n // Use blockId and BlockComponent from closure - no prop dependency\n return (\n <div className=\"mdx-content prose prose-sm max-w-none\">\n <BlockComponent />\n </div>\n );\n },\n };\n blockCategoryList.push(componentKey);\n });\n\n // Merge with existing config\n const existingCategories = config.categories || {};\n const existingComponents = config.components || {};\n\n // Merge block components with existing config components\n const mergedComponents = {\n ...existingComponents,\n ...blockComponents,\n } as Config['components'];\n\n const enhancedConfig: Config = {\n ...config,\n categories: {\n ...existingCategories,\n blocks: {\n title: 'Content Blocks',\n components: blockCategoryList,\n },\n },\n components: mergedComponents,\n };\n\n // Check if page has hydratable components\n const needsHydration = hasHydratableComponents(data, enhancedConfig);\n\n // Render with hydration support if needed, otherwise static\n return needsHydration ? (\n <RenderWithHydration config={enhancedConfig} data={data} />\n ) : (\n <Render config={enhancedConfig} data={data} />\n );\n}\n\n/**\n * Factory function to create a PageRenderer with MDX components baked in via closure.\n *\n * This approach avoids dangerouslySetInnerHTML by keeping React components as components\n * throughout the rendering pipeline. Components are captured in the closure and don't\n * need to be passed as props (which Astro can't serialize).\n *\n * @param config - The Puck configuration with component definitions\n * @param data - Puck page data containing component tree\n * @param mdxComponents - Array of evaluated MDX components\n * @returns A PageRenderer component with no props needed (components in closure)\n *\n * @example\n * ```astro\n * ---\n * import { createPageRendererWithBlocks } from '@conloca/astro-cms/components';\n * import { evaluateMDXBlocks } from '@conloca/mdx/node';\n * import { createContentAPI } from '@conloca/content-api/node';\n * import config from '../puck.config';\n *\n * const api = await createContentAPI({ contentRoot: './content' });\n * const mdxComponents = await evaluateMDXBlocks(api, 'en');\n * const PageRenderer = createPageRendererWithBlocks(config, puckData, mdxComponents);\n * ---\n * <PageRenderer />\n * ```\n *\n * Benefits:\n * - No dangerouslySetInnerHTML (safer, no XSS risk from HTML strings)\n * - No string conversion round-trip (more efficient)\n * - Type safe React components throughout\n * - Normal React rendering with proper escaping\n */\nexport function createPageRendererWithBlocks(config: Config, data: Data, mdxComponents: MDXComponent[]): ComponentType {\n // Capture components in closure - no need to pass as props\n return function PageRendererWithBlocks() {\n return <RenderWithBlocks config={config} data={data} mdxComponents={mdxComponents} />;\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,iBAAiB,EAC/B,eACA,UACA,OACA,YACwB;AAExB,KAAI,aAAa,OACf,QAAO,gCAAG,WAAY;AAIxB,QACE,oBAAC;EACC,gBAAc;EACd,yBAAuB;EACvB,cAAY,eAAe,MAAM;EAEhC;GACG;;;;;;;;;;;;;;AClBV,SAAgB,oBAAoB,EAAE,QAAQ,QAAkC;AAkC9E,QAAO,oBAAC;EAAO,QAhCe;GAC5B,GAAG;GACH,YAAY,OAAO,YACjB,OAAO,QAAQ,OAAO,WAAW,CAAC,KAAK,CAAC,MAAM,qBAAqB;IACjE,MAAM,WAAW,aAAa,MAAM,OAAO;AAE3C,QAAI,aAAa,OAEf,QAAO,CAAC,MAAM,gBAAgB;IAIhC,MAAM,iBAAiB,gBAAgB;AACvC,WAAO,CACL,MACA;KACE,GAAG;KACH,SAAS,UACP,oBAAC;MACC,eAAe;MACL;MACH;gBAEN,eAAe,MAAM;OACL;KAEtB,CACF;KACD,CACH;GACF;EAE2C;GAAQ;;;;;;;;;;;;;;;;;;;;;;;;;ACftD,SAAS,iBAAiB,EAAE,QAAQ,MAAM,iBAAwC;CAEhF,MAAMA,kBAAmD,EAAE;CAC3D,MAAMC,oBAA8B,EAAE;AAGtC,eAAc,SAAS,UAAU;EAC/B,MAAM,eAAe,SAAS,MAAM;EAGpC,MAAM,iBAAiB,MAAM;AAE7B,kBAAgB,gBAAgB;GAC9B,OAAO,MAAM;GACb,QAAQ,EAAE;GACV,cAAc,EAAE;GAChB,cAAc;AAEZ,WACE,oBAAC;KAAI,WAAU;eACb,oBAAC,mBAAiB;MACd;;GAGX;AACD,oBAAkB,KAAK,aAAa;GACpC;CAGF,MAAM,qBAAqB,OAAO,cAAc,EAAE;CAIlD,MAAM,mBAAmB;EACvB,GAJyB,OAAO,cAAc,EAAE;EAKhD,GAAG;EACJ;CAED,MAAMC,iBAAyB;EAC7B,GAAG;EACH,YAAY;GACV,GAAG;GACH,QAAQ;IACN,OAAO;IACP,YAAY;IACb;GACF;EACD,YAAY;EACb;AAMD,QAHuB,wBAAwB,MAAM,eAAe,GAIlE,oBAAC;EAAoB,QAAQ;EAAsB;GAAQ,GAE3D,oBAAC;EAAO,QAAQ;EAAsB;GAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqClD,SAAgB,6BAA6B,QAAgB,MAAY,eAA8C;AAErH,QAAO,SAAS,yBAAyB;AACvC,SAAO,oBAAC;GAAyB;GAAc;GAAqB;IAAiB"}
1
+ {"version":3,"file":"components.mjs","names":[],"sources":["../src/components/HydrationWrapper.tsx","../src/components/RenderWithHydration.tsx","../src/components/RenderWithBlocks.tsx"],"sourcesContent":["import type { ReactNode } from 'react'\nimport type { HydrationStrategy } from '../types.js'\nimport { serializeProps } from '../lib/serialize-props.js'\n\ninterface HydrationWrapperProps {\n componentName: string\n strategy: HydrationStrategy\n props: Record<string, unknown>\n children: ReactNode\n}\n\n/**\n * Wraps hydratable components with data attributes for browser hydration.\n *\n * When strategy is 'none', renders children directly without wrapper overhead.\n * Otherwise, wraps in a div with data-hydrate attributes that the browser\n * hydration script uses to find and hydrate components.\n */\nexport function HydrationWrapper({\n componentName,\n strategy,\n props,\n children,\n}: HydrationWrapperProps) {\n // No hydration needed - render children directly without wrapper\n if (strategy === 'none') {\n return <>{children}</>\n }\n\n // Wrap with hydration markers for the browser script to find\n return (\n <div\n data-hydrate={componentName}\n data-hydrate-strategy={strategy}\n data-props={serializeProps(props)}\n >\n {children}\n </div>\n )\n}\n","import type { Config, Data } from '@puckeditor/core';\nimport { Render } from '@puckeditor/core';\nimport { isHydratable } from '../lib/hydration-utils.js';\nimport { HydrationWrapper } from './HydrationWrapper.js';\n\ninterface RenderWithHydrationProps {\n config: Config;\n data: Data;\n}\n\n/**\n * Wrapper around Puck's Render component that adds hydration support.\n *\n * For each component with a hydration strategy configured, wraps the\n * component's render output with HydrationWrapper to add data-hydrate\n * attributes for browser-side hydration.\n *\n * Non-hydratable components render without any wrapper overhead.\n */\nexport function RenderWithHydration({ config, data }: RenderWithHydrationProps) {\n // Create wrapped config with hydration-aware render functions\n const wrappedConfig: Config = {\n ...config,\n components: Object.fromEntries(\n Object.entries(config.components).map(([name, componentConfig]) => {\n const strategy = isHydratable(name, config);\n\n if (strategy === 'none') {\n // No wrapping needed - component stays static\n return [name, componentConfig];\n }\n\n // Wrap the render function so its output becomes HydrationWrapper children\n const originalRender = componentConfig.render;\n return [\n name,\n {\n ...componentConfig,\n render: (props) => (\n <HydrationWrapper componentName={name} strategy={strategy} props={props}>\n {originalRender(props)}\n </HydrationWrapper>\n ),\n },\n ];\n }),\n ),\n };\n\n return <Render config={wrappedConfig} data={data} />;\n}\n","import type { ComponentConfig, Config, Data } from '@puckeditor/core';\nimport { Render } from '@puckeditor/core';\nimport type { ComponentType } from 'react';\nimport { hasHydratableComponents } from '../lib/hydration-utils.js';\nimport { RenderWithHydration } from './RenderWithHydration.js';\n\ninterface MDXComponent {\n id: string;\n title: string;\n Component: ComponentType;\n}\n\ninterface RenderWithBlocksProps {\n config: Config;\n data: Data;\n mdxComponents: MDXComponent[];\n}\n\n/**\n * Internal component for rendering Puck pages with MDX blocks.\n *\n * Uses Puck's Render component for static rendering in Astro.\n * All content is pre-rendered at build time with no client-side JavaScript.\n *\n * MDX blocks are passed as React components (not HTML strings), which:\n * - Avoids dangerouslySetInnerHTML security risks\n * - More efficient (no HTML conversion round-trip)\n * - Type-safe with proper React component types\n *\n * **Note:** This function is internal. Use `createPageRendererWithBlocks` instead,\n * which provides a factory pattern to handle the closure correctly.\n *\n * @internal\n * @param props - Component props\n * @param props.config - Base Puck configuration\n * @param props.data - Puck page data containing component tree\n * @param props.mdxComponents - Array of evaluated MDX React components\n */\nfunction RenderWithBlocks({ config, data, mdxComponents }: RenderWithBlocksProps) {\n // Build enhanced config with MDX blocks\n const blockComponents: Record<string, ComponentConfig> = {};\n const blockCategoryList: string[] = [];\n\n // Create component configs for each block\n mdxComponents.forEach((block) => {\n const componentKey = `Block_${block.id}`;\n\n // Capture component in closure - Puck doesn't persist defaultProps reliably\n const BlockComponent = block.Component;\n\n blockComponents[componentKey] = {\n label: block.title,\n fields: {},\n defaultProps: {},\n render: () => {\n // Use blockId and BlockComponent from closure - no prop dependency\n return (\n <div className=\"mdx-content prose prose-sm max-w-none\">\n <BlockComponent />\n </div>\n );\n },\n };\n blockCategoryList.push(componentKey);\n });\n\n // Merge with existing config\n const existingCategories = config.categories || {};\n const existingComponents = config.components || {};\n\n // Merge block components with existing config components\n const mergedComponents = {\n ...existingComponents,\n ...blockComponents,\n } as Config['components'];\n\n const enhancedConfig: Config = {\n ...config,\n categories: {\n ...existingCategories,\n blocks: {\n title: 'Content Blocks',\n components: blockCategoryList,\n },\n },\n components: mergedComponents,\n };\n\n // Check if page has hydratable components\n const needsHydration = hasHydratableComponents(data, enhancedConfig);\n\n // Render with hydration support if needed, otherwise static\n return needsHydration ? (\n <RenderWithHydration config={enhancedConfig} data={data} />\n ) : (\n <Render config={enhancedConfig} data={data} />\n );\n}\n\n/**\n * Factory function to create a PageRenderer with MDX components baked in via closure.\n *\n * This approach avoids dangerouslySetInnerHTML by keeping React components as components\n * throughout the rendering pipeline. Components are captured in the closure and don't\n * need to be passed as props (which Astro can't serialize).\n *\n * @param config - The Puck configuration with component definitions\n * @param data - Puck page data containing component tree\n * @param mdxComponents - Array of evaluated MDX components\n * @returns A PageRenderer component with no props needed (components in closure)\n *\n * @example\n * ```astro\n * ---\n * import { createPageRendererWithBlocks } from '@conloca/astro-cms/components';\n * import { evaluateMDXBlocks } from '@conloca/mdx/node';\n * import { createContentAPI } from '@conloca/content-api/node';\n * import config from '../puck.config';\n *\n * const api = await createContentAPI({ contentRoot: './content' });\n * const mdxComponents = await evaluateMDXBlocks(api, 'en');\n * const PageRenderer = createPageRendererWithBlocks(config, puckData, mdxComponents);\n * ---\n * <PageRenderer />\n * ```\n *\n * Benefits:\n * - No dangerouslySetInnerHTML (safer, no XSS risk from HTML strings)\n * - No string conversion round-trip (more efficient)\n * - Type safe React components throughout\n * - Normal React rendering with proper escaping\n */\nexport function createPageRendererWithBlocks(config: Config, data: Data, mdxComponents: MDXComponent[]): ComponentType {\n // Capture components in closure - no need to pass as props\n return function PageRendererWithBlocks() {\n return <RenderWithBlocks config={config} data={data} mdxComponents={mdxComponents} />;\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,iBAAiB,EAC/B,eACA,UACA,OACA,YACwB;AAExB,KAAI,aAAa,OACf,QAAO,gCAAG,WAAY;AAIxB,QACE,oBAAC;EACC,gBAAc;EACd,yBAAuB;EACvB,cAAY,eAAe,MAAM;EAEhC;GACG;;;;;;;;;;;;;;AClBV,SAAgB,oBAAoB,EAAE,QAAQ,QAAkC;AA8B9E,QAAO,oBAAC;EAAO,QA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O,oBAAC;GAAyB;GAAc;GAAqB;IAAiB"}
@@ -9,7 +9,7 @@
9
9
  * MDX blocks are evaluated at build time and rendered as React components.
10
10
  */
11
11
 
12
- import { Render, resolveAllData } from '@measured/puck';
12
+ import { Render, resolveAllData } from '@puckeditor/core';
13
13
  import type { ComponentType } from 'react';
14
14
 
15
15
  // MDX evaluation imports
@@ -1,3 +1,4 @@
1
- import { r as HydrationStrategy, t as ComponentRegistry } from "./hydration-script-CKamSyIx.mjs";
2
- import { n as WithHydrationStrategy, r as withHydration, t as HydrationMeta } from "./withHydration-C6l6XnF2.mjs";
1
+ import { t as HydrationStrategy } from "./types-Bsd_qENn.mjs";
2
+ import { n as WithHydrationStrategy, r as withHydration, t as HydrationMeta } from "./withHydration-BGgQDE-H.mjs";
3
+ import { ComponentRegistry } from "./lib/hydration-script.mjs";
3
4
  export { type ComponentRegistry, type HydrationMeta, type HydrationStrategy, type WithHydrationStrategy, withHydration };
@@ -1,3 +1,3 @@
1
- import { t as withHydration } from "./withHydration-DfAwNHmI.mjs";
1
+ import { t as withHydration } from "./withHydration-692fMySA.mjs";
2
2
 
3
3
  export { withHydration };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,8 @@
1
- import { a as TemplateConfig, i as RoutingConfigInput, r as HydrationStrategy, t as ComponentRegistry } from "./hydration-script-CKamSyIx.mjs";
2
- import { n as WithHydrationStrategy, r as withHydration, t as HydrationMeta } from "./withHydration-C6l6XnF2.mjs";
1
+ import { n as RoutingConfigInput, r as TemplateConfig, t as HydrationStrategy } from "./types-Bsd_qENn.mjs";
2
+ import { n as WithHydrationStrategy, r as withHydration, t as HydrationMeta } from "./withHydration-BGgQDE-H.mjs";
3
+ import { ComponentRegistry } from "./lib/hydration-script.mjs";
3
4
  import { BlockMeta, PageMeta, blockMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
4
- import { Config, Data } from "@measured/puck";
5
+ import { Config, Data } from "@puckeditor/core";
5
6
  import { AstroIntegration } from "astro";
6
7
  import { Loader } from "astro/loaders";
7
8
  import { UIConfig } from "@conloca/cms-spa";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/hydration-scanner.ts","../src/lib/hydration-utils.ts","../src/lib/route-utils.ts","../src/lib/serialize-props.ts","../src/loader.ts","../src/plugin-spa.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;UAOiB,kBAAA;;;;;;EAAA,QAAA,EAAA,MAAA,GAAA,SAAkB,GAAA,MAAA;AA0FnC;;;ACYA;;;;AC7FA;AAkCA;;;;AC9CA;;;;ACDA;AAYA;;;iBJkFsB,2BAAA,iDAGnB,QAAQ;;;;;;;UC5FM,yBAAA;;cAEH;EDHG,MAAA,CAAA,EAAA,CAAA,KAAA,EAAA,OAAkB,EAAA,GAAA,OAAA;AA0FnC;;;;ACzFA;AAUiB,UAAA,mBAAA,CAAmB;EAI3B;EAEW,IAAA,EAAA,MAAA;EAAR;EAAO,KAAA,EAFV,MAEU,CAAA,MAAA,EAAA,OAAA,CAAA;EAeH;EAyBA,QAAA,EAxCJ,OAwCI,CAxCI,iBAwCoB,EAAA,MAAA,CAAA;EAChC;EACE,EAAA,EAAA,MAAA;;;AA2CV;;;;AC7FA;AAkCA;;;;AC9CgB,iBFmCA,YAAA,CEnCsB,aAAM,EAAA,MAAA,EAAA,MAAA,EFqClC,MErCkC,CAAA,EFsCzC,iBEtCyC;;;;ACD5C;AAYA;;;;ACoCiB,iBJaD,wBAAA,CIbmB,IAAA,EJc3B,IId2B,EAAA,MAAA,EJezB,MIfyB,CAAA,EJgBhC,mBIhBgC,EAAA;;;;;AAAQ,iBJ0D3B,uBAAA,CI1D2B,IAAA,EJ0DG,II1DH,EAAA,MAAA,EJ0DiB,MI1DjB,CAAA,EAAA,OAAA;;;;;;;;;;;;AL5C3C;AA0FA;;;;ACzFA;AAUA;AAIS,iBCNO,uBAAA,CDMP,QAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;;;AAiBT;AAyBA;;;;;AA6CA;;;;AC7FA;AAkCA;iBAAgB,gBAAA;;;;;;;iBC9CA,cAAA,QAAsB;;;UCDrB,oBAAA;;;;;;;;AJIjB;AA0FA;;iBIlFgB,aAAA,UAAuB,uBAAuB;;;UCoC7C,iBAAA,SAA0B,KAAK;;;;;;EL5C/B;AA0FjB;;;;ACzFA;AAUA;EAIS,MAAA,CAAA,EAAA,MAAA;EAEW,OAAA,CAAA,EI2CR,kBJ3CQ;EAAR,SAAA,CAAA,EI4CE,MJ5CF,CAAA,MAAA,EI4CiB,cJ5CjB,CAAA;EAAO;AAenB;AAyBA;;;;EAGsB,cAAA,CAAA,EAAA,MAAA,EAAA;EA0CN;;;;AC7FhB;AAkCA;;;iBGyHgB,UAAA,UAAoB,oBAAoB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/hydration-scanner.ts","../src/lib/hydration-utils.ts","../src/lib/route-utils.ts","../src/lib/serialize-props.ts","../src/loader.ts","../src/plugin-spa.ts"],"mappings":";;;;;;;;;;;;;UAOiB,kBAAA;;EAEf,aAAA;;EAEA,QAAA;;EAEA,QAAA;AAAA;;;;;;;;;ACLF;;;;;;;;;;AAUA;iBD+EsB,2BAAA,CACpB,cAAA,YACA,WAAA,WACC,OAAA,CAAQ,kBAAA;;;;;;;UC5FM,yBAAA;;EAEf,SAAA,GAAY,iBAAA;EACZ,MAAA,IAAU,KAAA;AAAA;;;;;UAOK,mBAAA;EDLf;ECOA,IAAA;EDPQ;ECSR,KAAA,EAAO,MAAA;ED2EwC;ECzE/C,QAAA,EAAU,OAAA,CAAQ,iBAAA;ED4EV;EC1ER,EAAA;AAAA;;;;;;;;AAlBF;;;iBA+BgB,YAAA,CAAa,aAAA,UAAuB,MAAA,EAAQ,MAAA,GAAS,iBAAA;;;;;;;AArBrE;;iBA2CgB,wBAAA,CAAyB,IAAA,EAAM,IAAA,EAAM,MAAA,EAAQ,MAAA,GAAS,mBAAA;;;;;iBA0CtD,uBAAA,CAAwB,IAAA,EAAM,IAAA,EAAM,MAAA,EAAQ,MAAA;;;;;;;;;;;;;ADhG5D;;;;;;iBESgB,uBAAA,CAAwB,QAAA,UAAkB,OAAA;;;AFiF1D;;;;;;;;;;;;;iBE/CgB,gBAAA,CAAiB,IAAA,sBAA0B,OAAA;;;;;;;iBC9C3C,cAAA,CAAe,KAAA,EAAO,MAAA;;;UCDrB,oBAAA;EACf,UAAA;EACA,WAAA;EACA,IAAA;;EAEA,IAAA;AAAA;;;AJDF;;iBIQgB,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,MAAA;;;UCoC7C,iBAAA,SAA0B,IAAA,CAAK,QAAA;EAC9C,WAAA;EACA,SAAA;EACA,KAAA;EACA,cAAA;EACA,WAAA;;ALjDF;;;;;;EK0DE,MAAA;EAEA,OAAA,GAAU,kBAAA;EACV,SAAA,GAAY,MAAA,SAAe,cAAA;EL6BP;;;;;;EKrBpB,cAAA;ELwBS;;;;;;EKhBT,UAAA;AAAA;AAAA,iBAuFc,UAAA,CAAW,OAAA,EAAS,iBAAA,GAAoB,gBAAA"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { i as isHydratable, n as findHydratableComponents, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-CQDv661k.mjs";
2
- import { t as withHydration } from "./withHydration-DfAwNHmI.mjs";
3
- import { t as conlocaLoader } from "./loader-BYmsavWc.mjs";
1
+ import { i as isHydratable, n as findHydratableComponents, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-DqfDQeFl.mjs";
2
+ import { t as withHydration } from "./withHydration-692fMySA.mjs";
3
+ import { t as conlocaLoader } from "./loader-W3i9kf3p.mjs";
4
4
  import { blockMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { basename, dirname, extname, join, resolve } from "node:path";
@@ -675,7 +675,7 @@ initHydration(componentRegistry)
675
675
  "react-dom",
676
676
  "react/jsx-runtime",
677
677
  "react/jsx-dev-runtime",
678
- "@measured/puck"
678
+ "@puckeditor/core"
679
679
  ] },
680
680
  optimizeDeps: {
681
681
  exclude: [options.puckConfigPath],
@@ -686,7 +686,7 @@ initHydration(componentRegistry)
686
686
  "react/jsx-runtime",
687
687
  "react/jsx-dev-runtime",
688
688
  "@mdxeditor/editor",
689
- "@measured/puck",
689
+ "@puckeditor/core",
690
690
  "@tanstack/react-query",
691
691
  "@tanstack/react-query-devtools",
692
692
  "react-router-dom",
@@ -758,16 +758,16 @@ if (import.meta.hot) {
758
758
  contentRoot: options.contentRoot,
759
759
  canvasDir: options.canvasDir || "./canvas"
760
760
  });
761
- const { resolve: resolve$1 } = await import("node:path");
762
- const astroRoot$1 = process.cwd();
763
- const contentAbsolute$1 = resolve$1(options.contentRoot);
764
- const canvasAbsolute = resolve$1(options.canvasDir || "./canvas");
761
+ const { resolve } = await import("node:path");
762
+ const astroRoot = process.cwd();
763
+ const contentAbsolute = resolve(options.contentRoot);
764
+ const canvasAbsolute = resolve(options.canvasDir || "./canvas");
765
765
  const foldersToWatch = [];
766
- if (!contentAbsolute$1.startsWith(astroRoot$1)) {
766
+ if (!contentAbsolute.startsWith(astroRoot)) {
767
767
  console.log(`[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`);
768
768
  foldersToWatch.push(options.contentRoot);
769
769
  } else console.log(`[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`);
770
- if (!canvasAbsolute.startsWith(astroRoot$1)) {
770
+ if (!canvasAbsolute.startsWith(astroRoot)) {
771
771
  console.log(`[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || "./canvas"}`);
772
772
  foldersToWatch.push(options.canvasDir || "./canvas");
773
773
  } else console.log(`[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || "./canvas"}`);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["discoveries: HydrationDiscovery[]","hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]>","resolvedRoutingConfig: ResolvedRoutingConfig | undefined","resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>>","cmsSpaImport: string","astroRoot","contentAbsolute","resolve","conflicts: { injected: string; fileBased: string }[]"],"sources":["../src/lib/hydration-scanner.ts","../src/lib/route-utils.ts","../src/lib/routing-config.ts","../src/lib/virtual-module-generators.ts","../src/plugin-spa.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport fg from 'fast-glob'\n\n/**\n * Result of scanning a component file for withHydration usage.\n */\nexport interface HydrationDiscovery {\n /** Component name derived from filename (PascalCase) */\n componentName: string\n /** Absolute path to the component file */\n filePath: string\n /** Hydration strategy extracted from withHydration call */\n strategy: 'load' | 'visible' | 'idle'\n}\n\n// Regex to check if file imports withHydration from @conloca/astro-cms or @conloca/astro-cms/hydration\n// This is faster than es-module-lexer for JSX files and avoids parse errors\nconst HYDRATION_IMPORT_PATTERN = /import\\s+\\{[^}]*withHydration[^}]*\\}\\s+from\\s+['\"]@conloca\\/astro-cms(?:\\/hydration)?['\"]/\n\n// Regex to find withHydration calls and extract strategy\n// Matches: withHydration(ComponentName, 'strategy') or withHydration(ComponentName, \"strategy\")\nconst HYDRATION_PATTERN = /withHydration\\s*\\(\\s*\\w+\\s*,\\s*['\"](\\w+)['\"]\\s*\\)/g\n\n// Valid hydration strategies\nconst VALID_STRATEGIES = new Set(['load', 'visible', 'idle'])\n\n/**\n * Derives component scan paths from puckConfigPath.\n *\n * Convention: puckConfigPath directory + '/components/puck'\n * Example: './src/puck.config.tsx' -> './src/components/puck'\n *\n * If explicitPaths provided, they extend (not replace) the auto-discovered path.\n *\n * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')\n * @param explicitPaths - Optional additional paths to scan\n * @returns Array of paths to scan for hydratable components\n */\nexport function deriveComponentPaths(\n puckConfigPath: string,\n explicitPaths?: string[]\n): string[] {\n const puckDir = dirname(puckConfigPath)\n const defaultScanPath = join(puckDir, 'components', 'puck')\n\n if (explicitPaths && explicitPaths.length > 0) {\n return [defaultScanPath, ...explicitPaths]\n }\n return [defaultScanPath]\n}\n\n/**\n * Derives a PascalCase component name from a file path.\n *\n * @param filePath - Absolute path to the component file\n * @returns Component name in PascalCase\n *\n * @example\n * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')\n * // => 'TestimonialGrid'\n *\n * deriveComponentName('/src/components/puck/blog-post-grid.tsx')\n * // => 'BlogPostGrid'\n */\nfunction deriveComponentName(filePath: string): string {\n const filename = basename(filePath, extname(filePath))\n // Convert kebab-case to PascalCase if needed\n if (filename.includes('-')) {\n return filename\n .split('-')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n }\n // Ensure first letter is uppercase\n return filename.charAt(0).toUpperCase() + filename.slice(1)\n}\n\n/**\n * Scans component directories for files using withHydration wrapper.\n *\n * This function performs static analysis to discover components marked\n * for hydration, without executing any component code.\n *\n * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])\n * @param projectRoot - Absolute path to the project root\n * @returns Array of discovered hydratable components with their strategies\n *\n * @example\n * ```typescript\n * const discoveries = await scanForHydratableComponents(\n * ['src/components/puck'],\n * '/path/to/project'\n * )\n * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]\n * ```\n */\nexport async function scanForHydratableComponents(\n componentPaths: string[],\n projectRoot: string\n): Promise<HydrationDiscovery[]> {\n const discoveries: HydrationDiscovery[] = []\n const seenNames = new Map<string, string>() // componentName -> first filePath\n\n for (const scanPath of componentPaths) {\n const absolutePath = resolve(projectRoot, scanPath)\n\n // Find all .tsx files in the directory and subdirectories\n const files = await fg('**/*.tsx', {\n cwd: absolutePath,\n absolute: true,\n onlyFiles: true,\n })\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8')\n\n // Fast path: check if file imports withHydration from @conloca/astro-cms\n // Using simple regex instead of es-module-lexer to avoid JSX parse errors\n if (!HYDRATION_IMPORT_PATTERN.test(content)) {\n continue\n }\n\n // Find withHydration calls with regex\n const matches = [...content.matchAll(HYDRATION_PATTERN)]\n\n if (matches.length === 0) {\n continue\n }\n\n if (matches.length > 1) {\n console.warn(\n `[Conloca Hydration] Multiple withHydration calls in ${filePath}. ` +\n 'Consider splitting into separate component files. Using first call.'\n )\n }\n\n const match = matches[0]\n const rawStrategy = match[1]\n\n // Validate strategy\n if (!VALID_STRATEGIES.has(rawStrategy)) {\n console.warn(\n `[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. ` +\n `Valid options: ${[...VALID_STRATEGIES].join(', ')}. Skipping component.`\n )\n continue\n }\n\n const strategy = rawStrategy as 'load' | 'visible' | 'idle'\n const componentName = deriveComponentName(filePath)\n\n // Check for naming conflicts\n const existingPath = seenNames.get(componentName)\n if (existingPath) {\n console.warn(\n `[Conloca Hydration] Duplicate component name '${componentName}'. ` +\n `Found in: ${existingPath} and ${filePath}. Using first occurrence.`\n )\n continue\n }\n\n seenNames.set(componentName, filePath)\n discoveries.push({\n componentName,\n filePath,\n strategy,\n })\n } catch (err) {\n // Log error but continue scanning other files\n console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err)\n }\n }\n }\n\n return discoveries\n}\n","/**\n * Extract slug from pathname given a route pattern.\n *\n * The slug is the portion of the pathname that comes after the\n * static prefix of the pattern.\n *\n * @param pathname - URL pathname (e.g., '/about', '/blog/post-1')\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns The extracted slug, or undefined for root paths\n *\n * @example\n * extractSlugFromPathname('/about', '/[...slug]') // 'about'\n * extractSlugFromPathname('/blog/post-1', '/blog/[...slug]') // 'post-1'\n * extractSlugFromPathname('/', '/[...slug]') // undefined\n * extractSlugFromPathname('/blog', '/blog/[...slug]') // undefined\n */\nexport function extractSlugFromPathname(pathname: string, pattern: string): string | undefined {\n // Pattern: /[...slug] -> prefix: ''\n // Pattern: /blog/[...slug] -> prefix: '/blog'\n // Pattern: /docs/[...path] -> prefix: '/docs'\n\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n // Remove prefix from pathname\n const slugPart = pathname.slice(prefix.length);\n\n // Remove leading slash\n const slug = slugPart.replace(/^\\//, '');\n\n // Empty string means root page (e.g., /blog for /blog/[...slug])\n // Return undefined for root to match [...slug] behavior\n return slug || undefined;\n}\n\n/**\n * Convert a slug back to a pathname given a route pattern.\n *\n * The inverse of extractSlugFromPathname.\n *\n * @param slug - The page slug (e.g., 'about', 'post-1'), or undefined for root\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns Full URL pathname\n *\n * @example\n * pathnameFromSlug('about', '/[...slug]') // '/about'\n * pathnameFromSlug('post-1', '/blog/[...slug]') // '/blog/post-1'\n * pathnameFromSlug(undefined, '/[...slug]') // '/'\n * pathnameFromSlug(undefined, '/blog/[...slug]') // '/blog'\n */\nexport function pathnameFromSlug(slug: string | undefined, pattern: string): string {\n // Extract the static prefix before the dynamic segment\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n if (!slug) {\n // No slug means root of this pattern\n return prefix || '/';\n }\n\n // Combine prefix and slug\n return `${prefix}/${slug}`;\n}\n","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/node';\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 { createContentAPI, createContentWatchHandlers } from '@conloca/content-api/node';\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// 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, 'handlers', 'page-handler.astro');\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\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// 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 // Get the exact preamble code from the React plugin\n // The base needs to be '/' so the import becomes '/@react-refresh'\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\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${preambleCode}\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\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 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 // Always apply SSR externalization for native modules (needed for both dev and build)\n // This must be outside the dev-only block to fix build errors\n updateConfig({\n vite: {\n ssr: {\n // Force these packages through Vite's resolver during SSR\n // This ensures symlinked packages use the consumer's React, not their own\n // Without this, symlinked packages resolve React from their node_modules\n noExternal: ['@conloca/astro-cms', '@conloca/cms-spa'],\n // Externalize native Node modules for SSR builds\n // These cannot be bundled and must be available at runtime\n external: ['@node-rs/xxhash'],\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\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_PAGE_API) {\n return RESOLVED_PAGE_API;\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_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_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 to avoid multiple instances when using symlinked packages\n // This prevents \"Cannot read properties of null (reading 'useMemo')\" errors\n dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', '@measured/puck'],\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 '@measured/puck',\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 {\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 === 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 === RESOLVED_CMS_SPA_ENTRY) {\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\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 srcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\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${preambleCode}\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 // 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 );\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: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\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 routes that may conflict with injected routes\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n // Skip routes from integrations (including our own)\n if (route.origin === 'internal') continue;\n\n // Skip our own injected page handler route\n const entrypoint = route.entrypoint || '';\n if (entrypoint.includes('page-handler.astro')) continue;\n\n // Check if this file-based route pattern matches any injected pattern\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: 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":";;;;;;;;;;;;;;AAkBA,MAAM,2BAA2B;AAIjC,MAAM,oBAAoB;AAG1B,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAO,CAAC;;;;;;;;;;;;;AAc7D,SAAgB,qBACd,gBACA,eACU;CAEV,MAAM,kBAAkB,KADR,QAAQ,eAAe,EACD,cAAc,OAAO;AAE3D,KAAI,iBAAiB,cAAc,SAAS,EAC1C,QAAO,CAAC,iBAA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I,QAAQ,CAC/B,WAAU,KAAK;MACb,UAAU;MACV,WAAW,cAAc;MAC1B,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"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/lib/hydration-scanner.ts","../src/lib/route-utils.ts","../src/lib/routing-config.ts","../src/lib/virtual-module-generators.ts","../src/plugin-spa.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport fg from 'fast-glob'\n\n/**\n * Result of scanning a component file for withHydration usage.\n */\nexport interface HydrationDiscovery {\n /** Component name derived from filename (PascalCase) */\n componentName: string\n /** Absolute path to the component file */\n filePath: string\n /** Hydration strategy extracted from withHydration call */\n strategy: 'load' | 'visible' | 'idle'\n}\n\n// Regex to check if file imports withHydration from @conloca/astro-cms or @conloca/astro-cms/hydration\n// This is faster than es-module-lexer for JSX files and avoids parse errors\nconst HYDRATION_IMPORT_PATTERN = /import\\s+\\{[^}]*withHydration[^}]*\\}\\s+from\\s+['\"]@conloca\\/astro-cms(?:\\/hydration)?['\"]/\n\n// Regex to find withHydration calls and extract strategy\n// Matches: withHydration(ComponentName, 'strategy') or withHydration(ComponentName, \"strategy\")\nconst HYDRATION_PATTERN = /withHydration\\s*\\(\\s*\\w+\\s*,\\s*['\"](\\w+)['\"]\\s*\\)/g\n\n// Valid hydration strategies\nconst VALID_STRATEGIES = new Set(['load', 'visible', 'idle'])\n\n/**\n * Derives component scan paths from puckConfigPath.\n *\n * Convention: puckConfigPath directory + '/components/puck'\n * Example: './src/puck.config.tsx' -> './src/components/puck'\n *\n * If explicitPaths provided, they extend (not replace) the auto-discovered path.\n *\n * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')\n * @param explicitPaths - Optional additional paths to scan\n * @returns Array of paths to scan for hydratable components\n */\nexport function deriveComponentPaths(\n puckConfigPath: string,\n explicitPaths?: string[]\n): string[] {\n const puckDir = dirname(puckConfigPath)\n const defaultScanPath = join(puckDir, 'components', 'puck')\n\n if (explicitPaths && explicitPaths.length > 0) {\n return [defaultScanPath, ...explicitPaths]\n }\n return [defaultScanPath]\n}\n\n/**\n * Derives a PascalCase component name from a file path.\n *\n * @param filePath - Absolute path to the component file\n * @returns Component name in PascalCase\n *\n * @example\n * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')\n * // => 'TestimonialGrid'\n *\n * deriveComponentName('/src/components/puck/blog-post-grid.tsx')\n * // => 'BlogPostGrid'\n */\nfunction deriveComponentName(filePath: string): string {\n const filename = basename(filePath, extname(filePath))\n // Convert kebab-case to PascalCase if needed\n if (filename.includes('-')) {\n return filename\n .split('-')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n }\n // Ensure first letter is uppercase\n return filename.charAt(0).toUpperCase() + filename.slice(1)\n}\n\n/**\n * Scans component directories for files using withHydration wrapper.\n *\n * This function performs static analysis to discover components marked\n * for hydration, without executing any component code.\n *\n * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])\n * @param projectRoot - Absolute path to the project root\n * @returns Array of discovered hydratable components with their strategies\n *\n * @example\n * ```typescript\n * const discoveries = await scanForHydratableComponents(\n * ['src/components/puck'],\n * '/path/to/project'\n * )\n * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]\n * ```\n */\nexport async function scanForHydratableComponents(\n componentPaths: string[],\n projectRoot: string\n): Promise<HydrationDiscovery[]> {\n const discoveries: HydrationDiscovery[] = []\n const seenNames = new Map<string, string>() // componentName -> first filePath\n\n for (const scanPath of componentPaths) {\n const absolutePath = resolve(projectRoot, scanPath)\n\n // Find all .tsx files in the directory and subdirectories\n const files = await fg('**/*.tsx', {\n cwd: absolutePath,\n absolute: true,\n onlyFiles: true,\n })\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8')\n\n // Fast path: check if file imports withHydration from @conloca/astro-cms\n // Using simple regex instead of es-module-lexer to avoid JSX parse errors\n if (!HYDRATION_IMPORT_PATTERN.test(content)) {\n continue\n }\n\n // Find withHydration calls with regex\n const matches = [...content.matchAll(HYDRATION_PATTERN)]\n\n if (matches.length === 0) {\n continue\n }\n\n if (matches.length > 1) {\n console.warn(\n `[Conloca Hydration] Multiple withHydration calls in ${filePath}. ` +\n 'Consider splitting into separate component files. Using first call.'\n )\n }\n\n const match = matches[0]\n const rawStrategy = match[1]\n\n // Validate strategy\n if (!VALID_STRATEGIES.has(rawStrategy)) {\n console.warn(\n `[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. ` +\n `Valid options: ${[...VALID_STRATEGIES].join(', ')}. Skipping component.`\n )\n continue\n }\n\n const strategy = rawStrategy as 'load' | 'visible' | 'idle'\n const componentName = deriveComponentName(filePath)\n\n // Check for naming conflicts\n const existingPath = seenNames.get(componentName)\n if (existingPath) {\n console.warn(\n `[Conloca Hydration] Duplicate component name '${componentName}'. ` +\n `Found in: ${existingPath} and ${filePath}. Using first occurrence.`\n )\n continue\n }\n\n seenNames.set(componentName, filePath)\n discoveries.push({\n componentName,\n filePath,\n strategy,\n })\n } catch (err) {\n // Log error but continue scanning other files\n console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err)\n }\n }\n }\n\n return discoveries\n}\n","/**\n * Extract slug from pathname given a route pattern.\n *\n * The slug is the portion of the pathname that comes after the\n * static prefix of the pattern.\n *\n * @param pathname - URL pathname (e.g., '/about', '/blog/post-1')\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns The extracted slug, or undefined for root paths\n *\n * @example\n * extractSlugFromPathname('/about', '/[...slug]') // 'about'\n * extractSlugFromPathname('/blog/post-1', '/blog/[...slug]') // 'post-1'\n * extractSlugFromPathname('/', '/[...slug]') // undefined\n * extractSlugFromPathname('/blog', '/blog/[...slug]') // undefined\n */\nexport function extractSlugFromPathname(pathname: string, pattern: string): string | undefined {\n // Pattern: /[...slug] -> prefix: ''\n // Pattern: /blog/[...slug] -> prefix: '/blog'\n // Pattern: /docs/[...path] -> prefix: '/docs'\n\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n // Remove prefix from pathname\n const slugPart = pathname.slice(prefix.length);\n\n // Remove leading slash\n const slug = slugPart.replace(/^\\//, '');\n\n // Empty string means root page (e.g., /blog for /blog/[...slug])\n // Return undefined for root to match [...slug] behavior\n return slug || undefined;\n}\n\n/**\n * Convert a slug back to a pathname given a route pattern.\n *\n * The inverse of extractSlugFromPathname.\n *\n * @param slug - The page slug (e.g., 'about', 'post-1'), or undefined for root\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns Full URL pathname\n *\n * @example\n * pathnameFromSlug('about', '/[...slug]') // '/about'\n * pathnameFromSlug('post-1', '/blog/[...slug]') // '/blog/post-1'\n * pathnameFromSlug(undefined, '/[...slug]') // '/'\n * pathnameFromSlug(undefined, '/blog/[...slug]') // '/blog'\n */\nexport function pathnameFromSlug(slug: string | undefined, pattern: string): string {\n // Extract the static prefix before the dynamic segment\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n if (!slug) {\n // No slug means root of this pattern\n return prefix || '/';\n }\n\n // Combine prefix and slug\n return `${prefix}/${slug}`;\n}\n","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/node';\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 { createContentAPI, createContentWatchHandlers } from '@conloca/content-api/node';\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// 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, 'handlers', 'page-handler.astro');\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\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// 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 // Get the exact preamble code from the React plugin\n // The base needs to be '/' so the import becomes '/@react-refresh'\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\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${preambleCode}\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\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 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 // Always apply SSR externalization for native modules (needed for both dev and build)\n // This must be outside the dev-only block to fix build errors\n updateConfig({\n vite: {\n ssr: {\n // Force these packages through Vite's resolver during SSR\n // This ensures symlinked packages use the consumer's React, not their own\n // Without this, symlinked packages resolve React from their node_modules\n noExternal: ['@conloca/astro-cms', '@conloca/cms-spa'],\n // Externalize native Node modules for SSR builds\n // These cannot be bundled and must be available at runtime\n external: ['@node-rs/xxhash'],\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\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_PAGE_API) {\n return RESOLVED_PAGE_API;\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_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_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 to avoid multiple instances when using symlinked packages\n // This prevents \"Cannot read properties of null (reading 'useMemo')\" errors\n dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', '@puckeditor/core'],\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 {\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 === 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 === RESOLVED_CMS_SPA_ENTRY) {\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\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 srcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\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${preambleCode}\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 // 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 );\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: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\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 routes that may conflict with injected routes\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n // Skip routes from integrations (including our own)\n if (route.origin === 'internal') continue;\n\n // Skip our own injected page handler route\n const entrypoint = route.entrypoint || '';\n if (entrypoint.includes('page-handler.astro')) continue;\n\n // Check if this file-based route pattern matches any injected pattern\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: 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":";;;;;;;;;;;;;;AAkBA,MAAM,2BAA2B;AAIjC,MAAM,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CAAC;IAGnG,MAAM,YAAuD,EAAE;AAE/D,SAAK,MAAM,SAAS,QAAQ;AAE1B,SAAI,MAAM,WAAW,WAAY;KAGjC,MAAM,aAAa,MAAM,cAAc;AACvC,SAAI,WAAW,SAAS,qBAAqB,CAAE;KAG/C,MAAM,UAAU,MAAM;AACtB,SAAI,iBAAiB,IAAI,QAAQ,CAC/B,WAAU,KAAK;MACb,UAAU;MACV,WAAW,cAAc;MAC1B,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"}
@@ -1,2 +1,31 @@
1
- import { n as initHydration, t as ComponentRegistry } from "../hydration-script-CKamSyIx.mjs";
2
- export { ComponentRegistry, initHydration };
1
+ import { t as HydrationStrategy } from "../types-Bsd_qENn.mjs";
2
+
3
+ //#region src/lib/hydration-script.d.ts
4
+ /**
5
+ * Async loader that returns a React component.
6
+ * The registry generator handles extraction from ComponentConfig at build time.
7
+ */
8
+ type ComponentLoader = () => Promise<React.ComponentType<unknown>>;
9
+ /**
10
+ * Registry entry with loader and strategy.
11
+ * Generated by the scanner from withHydration metadata.
12
+ */
13
+ interface ComponentRegistryEntry {
14
+ loader: ComponentLoader;
15
+ strategy: HydrationStrategy;
16
+ }
17
+ /**
18
+ * Registry mapping component names to their loaders and strategies.
19
+ * Generated by virtual:conloca-hydration-registry at build time.
20
+ */
21
+ type ComponentRegistry = Record<string, ComponentRegistryEntry>;
22
+ /**
23
+ * Initialize hydration for all marked components on the page.
24
+ *
25
+ * Finds all elements with [data-hydrate] attribute and hydrates them
26
+ * according to their strategy from the registry.
27
+ */
28
+ declare function initHydration(registry: ComponentRegistry): void;
29
+ //#endregion
30
+ export { ComponentRegistry, initHydration };
31
+ //# sourceMappingURL=hydration-script.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-script.d.mts","names":[],"sources":["../../src/lib/hydration-script.ts"],"mappings":";;;;;AAGoD;;KAM/C,eAAA,SAAwB,OAAA,CAAQ,KAAA,CAAM,aAAA;;;;;UAMjC,sBAAA;EACR,MAAA,EAAQ,eAAA;EACR,QAAA,EAAU,iBAAA;AAAA;;;;;KAOA,iBAAA,GAAoB,MAAA,SAAe,sBAAA;;;;AAA/C;;;iBA0EgB,aAAA,CAAc,QAAA,EAAU,iBAAA"}
@@ -58,4 +58,4 @@ function conlocaLoader(options) {
58
58
 
59
59
  //#endregion
60
60
  export { conlocaLoader as t };
61
- //# sourceMappingURL=loader-BYmsavWc.mjs.map
61
+ //# sourceMappingURL=loader-W3i9kf3p.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-W3i9kf3p.mjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["import { createContentAPI } from '@conloca/content-api/node';\nimport type { Loader, LoaderContext } from 'astro/loaders';\n\nexport interface ConlocaLoaderOptions {\n collection: string;\n contentRoot: string;\n site?: string;\n /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */\n kind?: 'page' | 'block' | 'data';\n}\n\n/**\n * Custom Astro content loader for Conloca CMS.\n * Loads content from the Conloca content directory into Astro collections.\n */\nexport function conlocaLoader(options: ConlocaLoaderOptions): Loader {\n return {\n name: 'conloca-loader',\n async load(context: LoaderContext): Promise<void> {\n const { store, parseData, generateDigest, logger } = context;\n\n // Create content API instance\n const api = await createContentAPI({ contentRoot: options.contentRoot });\n\n // Use provided kind, or fall back to inferring from collection name\n const kind = options.kind ?? (options.collection === 'blocks' ? 'block' : 'page');\n\n // List all content for this collection\n // Note: blocks and data don't have a site, so only pass site for pages\n const content = Array.from(\n api.listAllContent({\n collection: options.collection,\n kind,\n site: kind === 'page' ? options.site : undefined,\n }),\n );\n\n store.clear();\n\n for (const manifest of content) {\n for (const [locale, localeVersion] of Object.entries(manifest.locales)) {\n if (!localeVersion) continue;\n\n const entryId = `${manifest.id}/${locale}`;\n\n // For data and page collections, fetch full content to get the actual content fields\n let dataContent: Record<string, unknown> | undefined;\n let puckData: unknown | undefined;\n\n if (kind === 'data') {\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.data) {\n dataContent = fullContent.localized.content.data;\n }\n } else if (kind === 'page') {\n // For page collections, fetch full content to get puckData\n // This enables getCollection('pages') to return entries with puckData included\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.puckData) {\n puckData = fullContent.localized.content.puckData;\n }\n }\n\n const data: Record<string, unknown> = {\n id: manifest.id,\n locale,\n ...(localeVersion.pathname && { pathname: localeVersion.pathname }),\n ...(localeVersion.name && { name: localeVersion.name }),\n ...localeVersion.meta,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n // Include the data content for data collections\n ...(dataContent && { data: dataContent }),\n };\n\n // Include puckData for page collections (added separately to avoid spread type issues)\n if (puckData !== undefined) {\n data.puckData = puckData;\n }\n\n const parsedData = await parseData({ id: entryId, data });\n\n store.set({\n id: entryId,\n data: parsedData,\n digest: generateDigest(localeVersion.etag),\n });\n }\n }\n\n logger.info(`Loaded ${store.keys().length} entries from ${options.collection}`);\n },\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,cAAc,SAAuC;AACnE,QAAO;EACL,MAAM;EACN,MAAM,KAAK,SAAuC;GAChD,MAAM,EAAE,OAAO,WAAW,gBAAgB,WAAW;GAGrD,MAAM,MAAM,MAAM,iBAAiB,EAAE,aAAa,QAAQ,aAAa,CAAC;GAGxE,MAAM,OAAO,QAAQ,SAAS,QAAQ,eAAe,WAAW,UAAU;GAI1E,MAAM,UAAU,MAAM,KACpB,IAAI,eAAe;IACjB,YAAY,QAAQ;IACpB;IACA,MAAM,SAAS,SAAS,QAAQ,OAAO;IACxC,CAAC,CACH;AAED,SAAM,OAAO;AAEb,QAAK,MAAM,YAAY,QACrB,MAAK,MAAM,CAAC,QAAQ,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,EAAE;AACtE,QAAI,CAAC,cAAe;IAEpB,MAAM,UAAU,GAAG,SAAS,GAAG,GAAG;IAGlC,IAAI;IACJ,IAAI;AAEJ,QAAI,SAAS,QAAQ;KACnB,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,KAClC,eAAc,YAAY,UAAU,QAAQ;eAErC,SAAS,QAAQ;KAG1B,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,SAClC,YAAW,YAAY,UAAU,QAAQ;;IAI7C,MAAM,OAAgC;KACpC,IAAI,SAAS;KACb;KACA,GAAI,cAAc,YAAY,EAAE,UAAU,cAAc,UAAU;KAClE,GAAI,cAAc,QAAQ,EAAE,MAAM,cAAc,MAAM;KACtD,GAAG,cAAc;KACjB,WAAW,cAAc;KACzB,aAAa,cAAc;KAE3B,GAAI,eAAe,EAAE,MAAM,aAAa;KACzC;AAGD,QAAI,aAAa,OACf,MAAK,WAAW;IAGlB,MAAM,aAAa,MAAM,UAAU;KAAE,IAAI;KAAS;KAAM,CAAC;AAEzD,UAAM,IAAI;KACR,IAAI;KACJ,MAAM;KACN,QAAQ,eAAe,cAAc,KAAK;KAC3C,CAAC;;AAIN,UAAO,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,gBAAgB,QAAQ,aAAa;;EAElF"}
@@ -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-CQDv661k.mjs.map
73
+ //# sourceMappingURL=serialize-props-DqfDQeFl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialize-props-DqfDQeFl.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,OAAO,KAAK;GAC7B,CAAC;;AAMR,KAAI,KAAK,MACP,MAAK,MAAM,CAAC,UAAU,gBAAgB,OAAO,QAAQ,KAAK,MAAM,CAC9D,MAAK,MAAM,QAAQ,aAAa;EAC9B,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,OAAO,GAAG,SAAS,GAAG,KAAK;GAC5C,CAAC;;AAMV,QAAO;;;;;;AAOT,SAAgB,wBAAwB,MAAY,QAAyB;AAE3E,KAAI,KAAK,SAAS,MAAM,SAAS,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CAC1E,QAAO;AAIT,KAAI,KAAK,OACP;OAAK,MAAM,eAAe,OAAO,OAAO,KAAK,MAAM,CACjD,KAAI,YAAY,MAAM,SAAS,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CACxE,QAAO;;AAKb,QAAO;;;;;;;;;AClHT,SAAgB,eAAe,OAAwC;AACrE,QAAO,KAAK,UAAU,MAAM,CAAC,QAAQ,MAAM,UAAU"}
@@ -1,7 +1,6 @@
1
- import { Data } from "@measured/puck";
1
+ import { Data } from "@puckeditor/core";
2
2
 
3
3
  //#region src/types.d.ts
4
-
5
4
  /**
6
5
  * Hydration strategy for Puck components in production.
7
6
  *
@@ -430,32 +429,5 @@ interface TemplateConfig {
430
429
  description?: string;
431
430
  }
432
431
  //#endregion
433
- //#region src/lib/hydration-script.d.ts
434
- /**
435
- * Async loader that returns a React component.
436
- * The registry generator handles extraction from ComponentConfig at build time.
437
- */
438
- type ComponentLoader = () => Promise<React.ComponentType<unknown>>;
439
- /**
440
- * Registry entry with loader and strategy.
441
- * Generated by the scanner from withHydration metadata.
442
- */
443
- interface ComponentRegistryEntry {
444
- loader: ComponentLoader;
445
- strategy: HydrationStrategy;
446
- }
447
- /**
448
- * Registry mapping component names to their loaders and strategies.
449
- * Generated by virtual:conloca-hydration-registry at build time.
450
- */
451
- type ComponentRegistry = Record<string, ComponentRegistryEntry>;
452
- /**
453
- * Initialize hydration for all marked components on the page.
454
- *
455
- * Finds all elements with [data-hydrate] attribute and hydrates them
456
- * according to their strategy from the registry.
457
- */
458
- declare function initHydration(registry: ComponentRegistry): void;
459
- //#endregion
460
- export { TemplateConfig as a, RoutingConfigInput as i, initHydration as n, HydrationStrategy as r, ComponentRegistry as t };
461
- //# sourceMappingURL=hydration-script-CKamSyIx.d.mts.map
432
+ export { RoutingConfigInput as n, TemplateConfig as r, HydrationStrategy as t };
433
+ //# sourceMappingURL=types-Bsd_qENn.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-Bsd_qENn.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;AAuBA;;;;;AA2CA;;;;;;;;;;;;;;KA3CY,iBAAA;;;;;AA6LZ;;;;;;;;;;;;;;AA6YA;;;;;;;;;;;;AAgLA;;;;;;;;;;;UA/sBiB,aAAA;;;;;;;;;EASf,OAAA;;;;;;;;;;;;;;;EAgBA,MAAA,GAAS,MAAA,SAAe,WAAA;;;;;;;;;;;;EAaxB,QAAA;;;;;;;;;;;;EAaA,UAAA;;;;;;;;;;;;;;;;;;;;EAqBA,QAAA;;;;;;;;;;;;;;;;;;;;EAqBA,MAAA;AAAA;;;;;;;;;;;;;;KAgBU,kBAAA,aAA+B,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqC1B,WAAA;;;;;;;;;;;;;;;EAef,OAAA;;;;;;;;;;;;;;;;EAiBA,UAAA;;;;;;;;;;;;;;;;;EAkBA,MAAA;;;;;;;;;;;;;;;;;;;EAoBA,SAAA;;;;;;;;;EAUA,IAAA,GAAO,MAAA;;;;;;;;;;;;;;;;;EAkBP,YAAA,GAAe,iBAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;UA2SA,iBAAA;;;;;;;;;;EAUf,WAAA;;;;;;;EAQA,MAAA;;;;;;;;;;;;;;;;;;;;;EAsBA,KAAA;;;;;;;;;IASE,MAAA;;;;;;IAOA,KAAA;;;;;;;;;;IAWA,IAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;UA6Ga,cAAA;;;;;EAKf,KAAA;;;;;;EAOA,SAAA;;;;;;EAOA,UAAA;;;;EAKA,WAAA;AAAA"}
@@ -42,4 +42,4 @@ function withHydration(Component, strategy) {
42
42
 
43
43
  //#endregion
44
44
  export { withHydration as t };
45
- //# sourceMappingURL=withHydration-DfAwNHmI.mjs.map
45
+ //# sourceMappingURL=withHydration-692fMySA.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"withHydration-DfAwNHmI.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 * @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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,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"}
1
+ {"version":3,"file":"withHydration-692fMySA.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 * @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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,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"}
@@ -1,7 +1,6 @@
1
1
  import React from "react";
2
2
 
3
3
  //#region src/lib/withHydration.d.ts
4
-
5
4
  /**
6
5
  * Metadata attached to components marked for hydration.
7
6
  * Used by the build-time scanner and runtime hydration system.
@@ -49,4 +48,4 @@ type WithHydrationStrategy = 'load' | 'visible' | 'idle';
49
48
  declare function withHydration<T extends (props: any) => React.ReactNode>(Component: T, strategy: WithHydrationStrategy): T;
50
49
  //#endregion
51
50
  export { WithHydrationStrategy as n, withHydration as r, HydrationMeta as t };
52
- //# sourceMappingURL=withHydration-C6l6XnF2.d.mts.map
51
+ //# sourceMappingURL=withHydration-BGgQDE-H.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withHydration-BGgQDE-H.d.mts","names":[],"sources":["../src/lib/withHydration.ts"],"mappings":";;;;;AAMA;;UAAiB,aAAA;EACf,QAAA;EACA,cAAA;AAAA;;;;;KAOU,qBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCI,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.9",
3
+ "version": "0.1.11",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -12,26 +12,26 @@
12
12
  "type": "module",
13
13
  "main": "./dist/index.mjs",
14
14
  "module": "./dist/index.mjs",
15
- "types": "./dist/index.d.mts",
15
+ "types": "./dist/index.d.ts",
16
16
  "exports": {
17
17
  "./package.json": "./package.json",
18
18
  ".": {
19
- "types": "./dist/index.d.mts",
19
+ "types": "./dist/index.d.ts",
20
20
  "import": "./dist/index.mjs",
21
21
  "default": "./dist/index.mjs"
22
22
  },
23
23
  "./components": {
24
- "types": "./dist/components.d.mts",
24
+ "types": "./dist/components.d.ts",
25
25
  "import": "./dist/components.mjs",
26
26
  "default": "./dist/components.mjs"
27
27
  },
28
28
  "./cms-handler": {
29
- "types": "./dist/cms-handler.d.mts",
29
+ "types": "./dist/cms-handler.d.ts",
30
30
  "import": "./dist/cms-handler.mjs",
31
31
  "default": "./dist/cms-handler.mjs"
32
32
  },
33
33
  "./collections": {
34
- "types": "./dist/collections.d.mts",
34
+ "types": "./dist/collections.d.ts",
35
35
  "import": "./dist/collections.mjs",
36
36
  "default": "./dist/collections.mjs"
37
37
  },
@@ -43,12 +43,12 @@
43
43
  "default": "./dist/handlers/page-handler.astro"
44
44
  },
45
45
  "./lib/hydration-script": {
46
- "types": "./dist/lib/hydration-script.d.mts",
46
+ "types": "./dist/lib/hydration-script.d.ts",
47
47
  "import": "./dist/lib/hydration-script.mjs",
48
48
  "default": "./dist/lib/hydration-script.mjs"
49
49
  },
50
50
  "./hydration": {
51
- "types": "./dist/hydration.d.mts",
51
+ "types": "./dist/hydration.d.ts",
52
52
  "import": "./dist/hydration.mjs",
53
53
  "default": "./dist/hydration.mjs"
54
54
  }
@@ -63,23 +63,28 @@
63
63
  "!**/*.tsbuildinfo"
64
64
  ],
65
65
  "dependencies": {
66
- "@conloca/cms-spa": "0.1.9",
67
- "@conloca/content-api": "0.1.9",
68
- "@conloca/content-api-client": "0.1.9",
69
- "@conloca/mdx": "0.1.9",
70
- "@measured/puck": "^0.20.2",
66
+ "@conloca/cms-spa": "^0.1.11",
67
+ "@conloca/content-api": "^0.1.11",
68
+ "@conloca/content-api-client": "^0.1.11",
69
+ "@conloca/mdx": "^0.1.11",
70
+ "@puckeditor/core": "^0.21.1",
71
71
  "fast-glob": "^3.3.2",
72
72
  "tslib": "^2.8.1"
73
73
  },
74
74
  "peerDependencies": {
75
- "react": "^19.0.0",
76
- "react-dom": "^19.0.0",
77
- "zod": "^3.0.0"
75
+ "astro": "^5.0.0",
76
+ "vite": "^6.0.0",
77
+ "@vitejs/plugin-react": "^4.0.0",
78
+ "react": "19.2.4",
79
+ "react-dom": "19.2.4",
80
+ "zod": "^4.3.6"
78
81
  },
79
82
  "devDependencies": {
80
- "@happy-dom/global-registrator": "^20.0.10",
83
+ "@happy-dom/global-registrator": "^20.6.1",
81
84
  "@testing-library/jest-dom": "^6.9.1",
82
- "astro": "5.15.3"
85
+ "@vitejs/plugin-react": "^4.5.2",
86
+ "astro": "5.17.2",
87
+ "vite": "^6.3.5"
83
88
  },
84
89
  "nx": {
85
90
  "targets": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"hydration-script-CKamSyIx.d.mts","names":[],"sources":["../src/types.ts","../src/lib/hydration-script.ts"],"sourcesContent":[],"mappings":";;;;;;AAuBA;AA2CA;AA6GA;AAqCA;AA6YA;AAgLA;;;;AC9wBoD;AAMhB;AAepC;AA0EA;;;;;;;KD3EY,iBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA2CK,aAAA;;;;;;;;;;;;;;;;;;;;;;;;WAyBN,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoFd,kBAAA,aAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqC1B,WAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAgFR;;;;;;;;;;;;;;;;;iBAkBQ;;;;;;;;;;;;;;;;;;;;;;;;UA2SA,iBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAgLA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AA1vBjB;AA2CA;AA6GA,KCtKK,eAAA,GDsKO,GAAkB,GCtKD,ODsKC,CCtKO,KAAA,CAAM,aDsKa,CAAA,OAAA,CAAA,CAAA;AAqCxD;AA6YA;AAgLA;;UClwBU,sBAAA;UACA;EAPL,QAAA,EAQO,iBARQ;AAAgB;AAepC;AA0EA;;;KA1EY,iBAAA,GAAoB,eAAe;;;;;;;iBA0E/B,aAAA,WAAwB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-BYmsavWc.mjs","names":["dataContent: Record<string, unknown> | undefined","puckData: unknown | undefined","data: Record<string, unknown>"],"sources":["../src/loader.ts"],"sourcesContent":["import { createContentAPI } from '@conloca/content-api/node';\nimport type { Loader, LoaderContext } from 'astro/loaders';\n\nexport interface ConlocaLoaderOptions {\n collection: string;\n contentRoot: string;\n site?: string;\n /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */\n kind?: 'page' | 'block' | 'data';\n}\n\n/**\n * Custom Astro content loader for Conloca CMS.\n * Loads content from the Conloca content directory into Astro collections.\n */\nexport function conlocaLoader(options: ConlocaLoaderOptions): Loader {\n return {\n name: 'conloca-loader',\n async load(context: LoaderContext): Promise<void> {\n const { store, parseData, generateDigest, logger } = context;\n\n // Create content API instance\n const api = await createContentAPI({ contentRoot: options.contentRoot });\n\n // Use provided kind, or fall back to inferring from collection name\n const kind = options.kind ?? (options.collection === 'blocks' ? 'block' : 'page');\n\n // List all content for this collection\n // Note: blocks and data don't have a site, so only pass site for pages\n const content = Array.from(\n api.listAllContent({\n collection: options.collection,\n kind,\n site: kind === 'page' ? options.site : undefined,\n }),\n );\n\n store.clear();\n\n for (const manifest of content) {\n for (const [locale, localeVersion] of Object.entries(manifest.locales)) {\n if (!localeVersion) continue;\n\n const entryId = `${manifest.id}/${locale}`;\n\n // For data and page collections, fetch full content to get the actual content fields\n let dataContent: Record<string, unknown> | undefined;\n let puckData: unknown | undefined;\n\n if (kind === 'data') {\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.data) {\n dataContent = fullContent.localized.content.data;\n }\n } else if (kind === 'page') {\n // For page collections, fetch full content to get puckData\n // This enables getCollection('pages') to return entries with puckData included\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.puckData) {\n puckData = fullContent.localized.content.puckData;\n }\n }\n\n const data: Record<string, unknown> = {\n id: manifest.id,\n locale,\n ...(localeVersion.pathname && { pathname: localeVersion.pathname }),\n ...(localeVersion.name && { name: localeVersion.name }),\n ...localeVersion.meta,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n // Include the data content for data collections\n ...(dataContent && { data: dataContent }),\n };\n\n // Include puckData for page collections (added separately to avoid spread type issues)\n if (puckData !== undefined) {\n data.puckData = puckData;\n }\n\n const parsedData = await parseData({ id: entryId, data });\n\n store.set({\n id: entryId,\n data: parsedData,\n digest: generateDigest(localeVersion.etag),\n });\n }\n }\n\n logger.info(`Loaded ${store.keys().length} entries from ${options.collection}`);\n },\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,cAAc,SAAuC;AACnE,QAAO;EACL,MA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,UAAO,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,gBAAgB,QAAQ,aAAa;;EAElF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"serialize-props-CQDv661k.mjs","names":["hydratable: HydratableComponent[]"],"sources":["../src/lib/hydration-utils.ts","../src/lib/serialize-props.ts"],"sourcesContent":["import type { Config, Data } from '@measured/puck'\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(\n componentType: string,\n config: Config\n): 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(\n data: Data,\n config: Config\n): 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,aACd,eACA,QACmB;CACnB,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,yBACd,MACA,QACuB;CACvB,MAAMA,aAAoC,EAAE;AAG5C,KAAI,KAAK,QACP,MAAK,MAAM,QAAQ,KAAK,SAAS;EAC/B,MAAM,WAAW,aAAa,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