@conloca/astro-cms 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cms-handler.mjs +1 -1
- package/dist/cms-handler.mjs.map +1 -1
- package/package.json +3 -3
package/dist/cms-handler.mjs
CHANGED
|
@@ -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": import.meta.env.DEV ? "no-
|
|
122
|
+
"Cache-Control": import.meta.env.DEV ? "no-store, must-revalidate" : "public, max-age=31536000"
|
|
123
123
|
} });
|
|
124
124
|
} catch {
|
|
125
125
|
return new Response("Not found", { status: 404 });
|
package/dist/cms-handler.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,OAAO,CACzB,QAAO,iBAAiB,SAAS,SAAS;AAG5C,QAAO,UAAU,QAAQ,QAAQ;;;;;;AAWnC,SAAS,gBAAgB,QAAkC;AACzD,QAAO;;;;;;iCAMwB,OAAO,SAAS;;;6BAGpB,KAAK,UAAU,OAAO,CAAC;;+BAErB,OAAO,SAAS;+BAChB,OAAO,SAAS;+BAChB,OAAO,SAAS;;;;+BAIhB,OAAO,SAAS;;;;;;;AAQ/C,eAAe,gBAAiC;CAC9C,MAAM,SAAS,KAAK,YAAY,WAAW;CAC3C,MAAM,EAAE,YAAY,MAAM,OAAO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,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-store, must-revalidate' : 'public, max-age=31536000',\n },\n });\n } catch {\n return new Response('Not found', { status: 404 });\n }\n}\n\n// ============================================================================\n// Data Context Handler (from data-context-handler.ts)\n// ============================================================================\n\n/**\n * Handle DataContext API requests - returns data bindings for CMS editor\n */\nasync function handleDataContext(request: Request): Promise<Response> {\n try {\n const url = new URL(request.url);\n const pageId = url.searchParams.get('pageId');\n\n if (!pageId) {\n return jsonResponse({});\n }\n\n const config = routingConfig as ResolvedRoutingConfig;\n if (!config.enabled) {\n return jsonResponse({});\n }\n\n // Find which route this page belongs to by loading the page manifest\n // and matching its collection against route configs\n const contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n });\n\n const locale = contentOptions.locale;\n\n // Get the page manifest to determine its collection\n const content = await contentApi.getContent(pageId);\n if (!content) {\n return jsonResponse({});\n }\n const pageCollection = content.collection || 'pages';\n\n // Find the route whose collection matches this page\n const routeEntry = Object.entries(config.routes).find(\n ([, routeConfig]) => routeConfig.collection === pageCollection,\n );\n\n if (!routeEntry) {\n return jsonResponse({});\n }\n\n const [, routeConfig] = routeEntry;\n const hasCollections = routeConfig.dataBindings?.collections?.length;\n const hasPages = routeConfig.dataBindings?.pages?.prefix;\n\n if (!hasCollections && !hasPages) {\n return jsonResponse({});\n }\n\n // Build DataContext using the same logic as page-handler.astro\n const collections: Record<string, DataCollectionEntry[]> = {};\n let pages: PageReference[] | undefined;\n\n if (hasCollections && routeConfig.dataBindings?.collections) {\n for (const collectionName of routeConfig.dataBindings.collections) {\n try {\n const bindingLocale = routeConfig.dataBindings.locale ?? locale;\n collections[collectionName] = await getDataCollection(collectionName, bindingLocale);\n } catch {\n collections[collectionName] = [];\n }\n }\n }\n\n if (hasPages && routeConfig.dataBindings?.pages) {\n try {\n const pagesConfig = routeConfig.dataBindings.pages;\n pages = await getPagesByPrefix(pagesConfig.prefix, {\n sort: pagesConfig.sort,\n limit: pagesConfig.limit,\n });\n } catch {\n pages = [];\n }\n }\n\n const dataContext: DataContext = {\n collections,\n pages,\n locale: routeConfig.dataBindings.locale ?? locale,\n siteName: contentOptions.siteName,\n };\n\n return jsonResponse({ dataContext });\n } catch {\n return jsonResponse({});\n }\n}\n\nfunction jsonResponse(data: object): Response {\n return new Response(JSON.stringify(data), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n// ============================================================================\n// Content API Handler (from content-api-handler.ts)\n// ============================================================================\n\n/**\n * Handle Content API requests - delegates to Hono router\n */\nasync function handleContentApi(request: Request, cfResult: CFAccessResult): Promise<Response> {\n const contentRoot = import.meta.env.CONLOCA_CONTENT_ROOT || './content';\n const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || './canvas';\n\n // FileSystemContentAPI.create() handles caching internally\n const contentApi = await FileSystemContentAPI.create({ contentRoot, canvasDir });\n\n // Create the Hono router with assets and content root for git operations\n const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';\n const app = createContentAPIRouter(contentApi, { ...(assetsPath && { assetsPath }), contentRoot });\n\n // Extract the path after the API base\n const url = new URL(request.url);\n // Find where /api/ appears in the pathname\n const apiIndex = url.pathname.indexOf('/api/');\n if (apiIndex === -1) {\n return new Response('Invalid API path', { status: 400 });\n }\n const basePath = url.pathname.substring(0, apiIndex + 4); // Include '/api'\n const path = url.pathname.substring(basePath.length) || '/';\n\n // Pass user to Hono via headers for downstream use (needed for git commit attribution)\n const headers = new Headers(request.headers);\n if (cfResult.user) {\n 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,OAAO,CACzB,QAAO,iBAAiB,SAAS,SAAS;AAG5C,QAAO,UAAU,QAAQ,QAAQ;;;;;;AAWnC,SAAS,gBAAgB,QAAkC;AACzD,QAAO;;;;;;iCAMwB,OAAO,SAAS;;;6BAGpB,KAAK,UAAU,OAAO,CAAC;;+BAErB,OAAO,SAAS;+BAChB,OAAO,SAAS;+BAChB,OAAO,SAAS;;;;+BAIhB,OAAO,SAAS;;;;;;;AAQ/C,eAAe,gBAAiC;CAC9C,MAAM,SAAS,KAAK,YAAY,WAAW;CAC3C,MAAM,EAAE,YAAY,MAAM,OAAO;CAEjC,MAAM,YADQ,MAAM,QAAQ,OAAO,EACZ,MAAM,MAAM,EAAE,WAAW,SAAS,IAAI,EAAE,SAAS,QAAQ,CAAC;AAEjF,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,mDAAmD;AAMrE,QAFa,MAAM,SADF,K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,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"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@conloca/astro-cms",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
|
-
"url": "https://github.com/conloca/
|
|
10
|
-
"directory": "
|
|
9
|
+
"url": "git+https://github.com/conloca/conloca.git",
|
|
10
|
+
"directory": "astro-cms"
|
|
11
11
|
},
|
|
12
12
|
"type": "module",
|
|
13
13
|
"main": "./dist/index.mjs",
|