@conloca/astro-cms 0.1.0

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/README.md ADDED
@@ -0,0 +1,305 @@
1
+ # @conloca/astro-cms
2
+
3
+ A developer-focused CMS for Astro that runs exclusively in development mode. This CMS provides a visual interface for
4
+ managing content using Puck's drag-and-drop editor, allowing developers to create and edit pages visually while
5
+ maintaining full control over their content structure. The CMS integrates seamlessly into your Astro development
6
+ workflow, accessible at `/__cms` routes without requiring authentication or complex setup.
7
+
8
+ ## How Astro Integrations Are Built
9
+
10
+ Based on research of official Astro integrations:
11
+
12
+ ### Build Tools Used
13
+
14
+ 1. **astro-scripts** - Official Astro integrations use `astro-scripts` for building:
15
+
16
+ ```json
17
+ {
18
+ "scripts": {
19
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc",
20
+ "build:ci": "astro-scripts build \"src/**/*.ts\""
21
+ }
22
+ }
23
+ ```
24
+
25
+ 2. **TypeScript Compilation** - Standard `tsc` for type definitions:
26
+ - Compiles `.ts` files to `.js`
27
+ - Generates `.d.ts` type definitions
28
+ - Does NOT compile `.astro` files
29
+
30
+ 3. **Package Exports** - Modern ESM exports in package.json:
31
+ ```json
32
+ {
33
+ "exports": {
34
+ ".": "./dist/index.js",
35
+ "./package.json": "./package.json"
36
+ }
37
+ }
38
+ ```
39
+
40
+ ### How Integrations Ship UI
41
+
42
+ Official integrations handle UI in several ways:
43
+
44
+ 1. **API Endpoints Only** (Most common)
45
+ - Example: `@astrojs/web-vitals` injects API routes
46
+ - No UI components shipped
47
+
48
+ 2. **Client-Side Scripts** (Common)
49
+ - Example: Dev toolbar integrations
50
+ - Ship JavaScript that runs on the client
51
+ - Injected via `injectScript()`
52
+
53
+ 3. **Middleware Approach** (Common)
54
+ - Example: `@astrojs/node` adds Express middleware
55
+ - Serves content programmatically
56
+
57
+ 4. **Virtual Modules** (Advanced)
58
+ - Example: `@astrojs/db` uses virtual modules
59
+ - Routes are generated at build time
60
+ - Uses Vite's virtual module system
61
+
62
+ ### Building Non-Standard Integrations
63
+
64
+ For integrations that need to ship actual UI:
65
+
66
+ 1. **Custom Build Process**
67
+ - Can use any build tool (Vite, Rollup, esbuild)
68
+ - Not limited to `tsc` only
69
+ - Example: Bundle React app and serve via middleware
70
+
71
+ 2. **Asset Handling**
72
+ - Static assets can be included in the package
73
+ - Served via middleware or virtual modules
74
+ - Example: CSS files, images, bundled JavaScript
75
+
76
+ 3. **Route Injection Patterns**
77
+
78
+ ```typescript
79
+ // Inject API routes (standard)
80
+ injectRoute({
81
+ pattern: '/api/[...path]',
82
+ entrypoint: '@my-pkg/api-handler',
83
+ });
84
+
85
+ // Inject catch-all for SPA (for client routing)
86
+ injectRoute({
87
+ pattern: '/__cms/[...path]',
88
+ entrypoint: '@my-pkg/spa-handler',
89
+ });
90
+ ```
91
+
92
+ ### Shipping .astro Files (Possible but Rare)
93
+
94
+ While uncommon, packages CAN ship .astro files:
95
+
96
+ ```json
97
+ {
98
+ "exports": {
99
+ "./pages/index.astro": "./src/pages/index.astro"
100
+ }
101
+ }
102
+ ```
103
+
104
+ However, this requires:
105
+
106
+ - Including source .astro files in npm package
107
+ - Proper export configuration
108
+ - User's Astro instance compiles them at build time
109
+
110
+ ### For This CMS
111
+
112
+ Given the requirements:
113
+
114
+ - React-based UI (Puck editor)
115
+ - Client-side routing needed
116
+ - Development-only usage
117
+
118
+ The optimal approach is:
119
+
120
+ 1. Build the CMS as a Vite-based React SPA
121
+ 2. Bundle it during package build
122
+ 3. Serve via middleware with catch-all routing
123
+ 4. Use Astro's API routes for data endpoints
124
+
125
+ This aligns with how tools like Vite's dev UI and other development tools integrate with build systems.
126
+
127
+ ## Research: Using .astro Components in React/Puck
128
+
129
+ Based on investigation of Astro's source code, here's what was discovered about rendering .astro components within
130
+ React:
131
+
132
+ ### How .astro Components Work
133
+
134
+ 1. **Compilation Process** ([astro/packages/astro/src/vite-plugin-astro/compile.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/vite-plugin-astro/compile.ts)):
135
+ - .astro files are transformed by `@astrojs/compiler` into TypeScript/JavaScript
136
+ - The output is an `AstroComponentFactory` function, not a React component
137
+ - Components include metadata for hydration, slots, and server-side rendering
138
+
139
+ 2. **Component Factory Structure** ([astro/packages/astro/src/runtime/server/render/astro/factory.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/runtime/server/render/astro/factory.ts)):
140
+
141
+ ```typescript
142
+ interface AstroComponentFactory {
143
+ (result: any, props: any, slots: any): AstroFactoryReturnValue;
144
+ isAstroComponentFactory?: boolean;
145
+ moduleId?: string;
146
+ propagation?: PropagationHint;
147
+ }
148
+ ```
149
+
150
+ 3. **Container API** ([astro/packages/astro/src/container/index.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/container/index.ts)):
151
+ - Provides `experimental_AstroContainer` for programmatic rendering
152
+ - Can render .astro components to HTML strings via `renderToString()`
153
+ - Server-side only - returns static HTML, not React components
154
+
155
+ ### Rendering .astro Components
156
+
157
+ The Container API allows server-side rendering of .astro components:
158
+
159
+ ```typescript
160
+ // Example from astro/examples/container-with-vitest/test/ReactWrapper.test.ts
161
+ import { experimental_AstroContainer as AstroContainer } from 'astro/container';
162
+ import { getContainerRenderer } from '@astrojs/react';
163
+ import Component from '../src/components/Component.astro';
164
+
165
+ const container = await AstroContainer.create({
166
+ renderers: [getContainerRenderer()],
167
+ });
168
+
169
+ const html = await container.renderToString(Component, {
170
+ props: {
171
+ /* component props */
172
+ },
173
+ slots: { default: 'Slot content' },
174
+ });
175
+ ```
176
+
177
+ ### Integration Approaches
178
+
179
+ #### 1. Server-Side HTML Rendering (Limited)
180
+
181
+ - Render .astro components to HTML strings server-side
182
+ - Display in React using `dangerouslySetInnerHTML`
183
+ - No client-side interactivity preserved
184
+ - Requires API endpoint to render components on demand
185
+
186
+ #### 2. Astro Islands Architecture ([astro/packages/astro/src/runtime/server/astro-island.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/runtime/server/astro-island.ts))
187
+
188
+ - Astro uses custom `<astro-island>` elements for hydration
189
+ - Complex hydration system with directives (`client:load`, `client:idle`, etc.)
190
+ - Not designed for embedding within React components
191
+ - Would require significant work to integrate with React's lifecycle
192
+
193
+ #### 3. Direct Component Usage (Not Possible)
194
+
195
+ - .astro components cannot be directly imported and used as React components
196
+ - Different component models: Astro uses server-first rendering with partial hydration
197
+ - React expects components that return React elements
198
+
199
+ ### Recommendation
200
+
201
+ **Use React components in Puck, not .astro components:**
202
+
203
+ 1. Create shared React components that can be used by both:
204
+ - Astro pages (via React integration)
205
+ - Puck editor (native React)
206
+
207
+ 2. Example structure:
208
+
209
+ ```
210
+ src/
211
+ components/
212
+ Hero.tsx # React component
213
+ Card.tsx # React component
214
+ pages/
215
+ index.astro # Uses React components
216
+ puck.config.ts # Also uses React components
217
+ ```
218
+
219
+ 3. Benefits:
220
+ - Full interactivity in the CMS
221
+ - Consistent behavior between CMS preview and production
222
+ - No complex wrapping or conversion needed
223
+ - Proper TypeScript support and props validation
224
+
225
+ ### Technical Constraints
226
+
227
+ Based on the source code analysis:
228
+
229
+ 1. **No React Wrapper Exists**: Astro doesn't provide a way to wrap .astro components for use in React
230
+ 2. **Different Rendering Models**: Astro's server-first, partial hydration model is incompatible with React's
231
+ client-side model
232
+ 3. **Container API Limitations**: Only provides server-side rendering to HTML strings, not interactive components
233
+
234
+ ### Conclusion
235
+
236
+ While .astro components excel at server-side rendering with selective hydration, they cannot be meaningfully wrapped as
237
+ React components for use in Puck. The recommended approach is to use React components throughout the Puck configuration,
238
+ which can also be used in Astro pages via the React integration.
239
+
240
+ ## Astro Development Mode and HMR
241
+
242
+ ### How Astro Handles Hot Module Replacement
243
+
244
+ Based on analysis of the Astro source code:
245
+
246
+ 1. **Compilation Pipeline** ([astro/packages/astro/src/vite-plugin-astro/index.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/vite-plugin-astro/index.ts)):
247
+ - `@astrojs/compiler` transforms .astro files into JavaScript
248
+ - `vite-plugin-astro` orchestrates this compilation
249
+ - The plugin integrates with Vite's module system
250
+
251
+ 2. **HMR Implementation** ([astro/packages/astro/src/vite-plugin-astro/hmr.ts](https://github.com/withastro/astro/blob/main/packages/astro/src/vite-plugin-astro/hmr.ts)):
252
+ - Vite watches for file changes and triggers `handleHotUpdate`
253
+ - Astro optimizes HMR for specific change types:
254
+ - Style-only changes: Only CSS virtual modules are invalidated
255
+ - CSS dependencies: Invalidates compile metadata when CSS imports change
256
+ - Full changes: Re-compiles the entire component
257
+ - Vite's HMR system propagates updates to the browser
258
+
259
+ 3. **Development Flow**:
260
+ ```
261
+ .astro file changes → Vite detects → vite-plugin-astro compiles →
262
+ @astrojs/compiler transforms → JavaScript output → Vite HMR update → Browser
263
+ ```
264
+
265
+ ### Implications for Puck Config Loading
266
+
267
+ Since Vite handles all module loading and HMR in Astro's dev mode:
268
+
269
+ 1. **Virtual Modules**: We can use Vite's virtual module system to serve the Puck config
270
+ 2. **Automatic HMR**: Changes to puck.config.ts will trigger HMR automatically
271
+ 3. **Component Bundling**: Vite will handle bundling React components in the config
272
+ 4. **No Custom Build**: We don't need a separate build process for the config
273
+
274
+ Example virtual module approach:
275
+
276
+ ```typescript
277
+ // In the Astro plugin
278
+ vite: {
279
+ plugins: [
280
+ {
281
+ name: 'conloca-cms-config',
282
+ resolveId(id) {
283
+ if (id === 'virtual:conloca-cms/puck-config') {
284
+ return '\0virtual:conloca-cms/puck-config';
285
+ }
286
+ },
287
+ load(id) {
288
+ if (id === '\0virtual:conloca-cms/puck-config') {
289
+ return `
290
+ import { puckConfig } from '${userPuckConfigPath}';
291
+ export default puckConfig;
292
+ `;
293
+ }
294
+ },
295
+ },
296
+ ];
297
+ }
298
+ ```
299
+
300
+ Benefits:
301
+
302
+ - Leverages existing Vite infrastructure
303
+ - HMR works out of the box
304
+ - No additional complexity for module loading
305
+ - React components are properly bundled
@@ -0,0 +1,23 @@
1
+ import { APIRoute } from "astro";
2
+
3
+ //#region src/cms-handler.d.ts
4
+
5
+ /**
6
+ * Unified CMS handler - single entry point for all CMS routes.
7
+ *
8
+ * This handler:
9
+ * 1. Validates CF Access authentication ONCE at the top
10
+ * 2. Routes to appropriate sub-handler based on path:
11
+ * - /api/data-context -> handleDataContext()
12
+ * - /api/* -> handleContentApi()
13
+ * - /* -> handleSpa()
14
+ *
15
+ * Benefits:
16
+ * - Single authentication check prevents security gaps
17
+ * - New routes automatically inherit auth protection
18
+ * - Easier to audit security
19
+ */
20
+ declare const ALL: APIRoute;
21
+ //#endregion
22
+ export { ALL };
23
+ //# sourceMappingURL=cms-handler.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cms-handler.d.mts","names":[],"sources":["../src/cms-handler.ts"],"sourcesContent":[],"mappings":";;;;;;AAmCA;;;;;;;;;;;;;cAAa,KAAK"}
@@ -0,0 +1,221 @@
1
+ import { createRequire } from "node:module";
2
+ import { FileSystemContentAPI, createContentAPI, createContentAPIRouter, validateCFAccessRequest } from "@conloca/content-api/node";
3
+ import { dirname, join } from "node:path";
4
+ import { readFile } from "node:fs/promises";
5
+ import spaConfig from "virtual:conloca-config";
6
+ import { contentOptions, getDataCollection, getPagesByPrefix } from "virtual:conloca-page-api";
7
+ import routingConfig from "virtual:conloca-routing-config";
8
+
9
+ //#region src/cms-handler.ts
10
+ const cmsSpaPath = dirname(createRequire(import.meta.url).resolve("@conloca/cms-spa/package.json"));
11
+ /**
12
+ * Unified CMS handler - single entry point for all CMS routes.
13
+ *
14
+ * This handler:
15
+ * 1. Validates CF Access authentication ONCE at the top
16
+ * 2. Routes to appropriate sub-handler based on path:
17
+ * - /api/data-context -> handleDataContext()
18
+ * - /api/* -> handleContentApi()
19
+ * - /* -> handleSpa()
20
+ *
21
+ * Benefits:
22
+ * - Single authentication check prevents security gaps
23
+ * - New routes automatically inherit auth protection
24
+ * - Easier to audit security
25
+ */
26
+ const ALL = async ({ params, request }) => {
27
+ const cfResult = await validateCFAccessRequest(request);
28
+ if (!cfResult.valid && cfResult.required) return new Response(JSON.stringify({ error: "Unauthorized" }), {
29
+ status: 401,
30
+ headers: { "Content-Type": "application/json" }
31
+ });
32
+ const pathArray = params.path;
33
+ const path = Array.isArray(pathArray) ? pathArray.join("/") : pathArray || "";
34
+ if (path.startsWith("api/data-context")) return handleDataContext(request);
35
+ if (path.startsWith("api/")) return handleContentApi(request, cfResult);
36
+ return handleSpa(params, request);
37
+ };
38
+ /**
39
+ * Generate HTML for dev mode that loads cms-spa source through Vite.
40
+ * This ensures React is resolved from Vite's pre-bundled deps, not from the cms-spa bundle.
41
+ */
42
+ function generateDevHtml(config) {
43
+ return `<!DOCTYPE html>
44
+ <html lang="en">
45
+ <head>
46
+ <meta charset="UTF-8" />
47
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
48
+ <title>Conloca CMS</title>
49
+ <link rel="stylesheet" href="${config.basename}/main.css" />
50
+ <script>
51
+ // Configure UI with plugin options
52
+ window.__UI_CONFIG__ = ${JSON.stringify(config)};
53
+ <\/script>
54
+ <script type="module" src="${config.basename}/schemas-entry.js"><\/script>
55
+ <script type="module" src="${config.basename}/puck-entry.js"><\/script>
56
+ <script type="module" src="${config.basename}/content-listener.js"><\/script>
57
+ </head>
58
+ <body>
59
+ <div id="root"></div>
60
+ <script type="module" src="${config.basename}/cms-spa-entry.js"><\/script>
61
+ </body>
62
+ </html>`;
63
+ }
64
+ /**
65
+ * Load the HTML at runtime (production only)
66
+ */
67
+ async function loadIndexHtml() {
68
+ const spaDir = join(cmsSpaPath, "dist/spa");
69
+ const { readdir } = await import("node:fs/promises");
70
+ const htmlFile = (await readdir(spaDir)).find((f) => f.startsWith("index.") && f.endsWith(".html"));
71
+ if (!htmlFile) throw new Error("No index.html found in @conloca/cms-spa dist/spa");
72
+ return await readFile(join(spaDir, htmlFile), "utf-8");
73
+ }
74
+ /**
75
+ * Handle SPA requests - serve CMS admin interface
76
+ */
77
+ async function handleSpa(params, request) {
78
+ const pathArray = params.path;
79
+ const path = Array.isArray(pathArray) ? pathArray.join("/") : pathArray || "";
80
+ console.log("[cms-handler] SPA request for path:", path, "params:", params, "URL:", request.url);
81
+ if (!path || !path.includes(".")) try {
82
+ let html;
83
+ if (import.meta.env.DEV) {
84
+ html = generateDevHtml(spaConfig);
85
+ console.log("[cms-handler] Dev mode: serving generated HTML with virtual module entry");
86
+ } else {
87
+ html = await loadIndexHtml();
88
+ const configScript = `
89
+ <script>
90
+ // Configure UI with plugin options
91
+ window.__UI_CONFIG__ = ${JSON.stringify(spaConfig)};
92
+ <\/script>
93
+ <script type="module" src="${spaConfig.basename}/schemas-entry.js"><\/script>
94
+ <script type="module" src="${spaConfig.basename}/puck-entry.js"><\/script>
95
+ <script type="module" src="${spaConfig.basename}/content-listener.js"><\/script>
96
+ `;
97
+ html = html.replace("<head>", `<head>${configScript}`);
98
+ }
99
+ const scriptMatches = html.match(/<script[^>]+src="([^"]+)"/g);
100
+ console.log("[cms-handler] Script tags in HTML:", scriptMatches);
101
+ return new Response(html, { headers: {
102
+ "Content-Type": "text/html",
103
+ "Cache-Control": "no-store, must-revalidate",
104
+ "X-HMR": "spa-page"
105
+ } });
106
+ } catch (error) {
107
+ console.error("Error loading CMS HTML:", error);
108
+ return new Response("CMS build not found. Run nx build @conloca/astro-cms", {
109
+ status: 500,
110
+ headers: { "Content-Type": "text/plain" }
111
+ });
112
+ }
113
+ try {
114
+ const content = await readFile(join(cmsSpaPath, "dist/spa", path));
115
+ let contentType = "application/octet-stream";
116
+ if (path.endsWith(".js")) contentType = "application/javascript";
117
+ else if (path.endsWith(".css")) contentType = "text/css";
118
+ else if (path.endsWith(".html")) contentType = "text/html";
119
+ else if (path.endsWith(".json")) contentType = "application/json";
120
+ return new Response(content, { headers: {
121
+ "Content-Type": contentType,
122
+ "Cache-Control": "public, max-age=31536000"
123
+ } });
124
+ } catch {
125
+ return new Response("Not found", { status: 404 });
126
+ }
127
+ }
128
+ /**
129
+ * Handle DataContext API requests - returns data bindings for CMS editor
130
+ */
131
+ async function handleDataContext(request) {
132
+ try {
133
+ const pageId = new URL(request.url).searchParams.get("pageId");
134
+ if (!pageId) return jsonResponse({});
135
+ const config = routingConfig;
136
+ if (!config.enabled) return jsonResponse({});
137
+ const contentApi = await createContentAPI({
138
+ contentRoot: contentOptions.contentRoot,
139
+ canvasDir: contentOptions.canvasDir
140
+ });
141
+ const locale = contentOptions.locale;
142
+ const content = await contentApi.getContent(pageId);
143
+ if (!content) return jsonResponse({});
144
+ const pageCollection = content.collection || "pages";
145
+ const routeEntry = Object.entries(config.routes).find(([, routeConfig$1]) => routeConfig$1.collection === pageCollection);
146
+ if (!routeEntry) return jsonResponse({});
147
+ const [, routeConfig] = routeEntry;
148
+ const hasCollections = routeConfig.dataBindings?.collections?.length;
149
+ const hasPages = routeConfig.dataBindings?.pages?.prefix;
150
+ if (!hasCollections && !hasPages) return jsonResponse({});
151
+ const collections = {};
152
+ let pages;
153
+ if (hasCollections && routeConfig.dataBindings?.collections) for (const collectionName of routeConfig.dataBindings.collections) try {
154
+ collections[collectionName] = await getDataCollection(collectionName, routeConfig.dataBindings.locale ?? locale);
155
+ } catch {
156
+ collections[collectionName] = [];
157
+ }
158
+ if (hasPages && routeConfig.dataBindings?.pages) try {
159
+ const pagesConfig = routeConfig.dataBindings.pages;
160
+ pages = await getPagesByPrefix(pagesConfig.prefix, {
161
+ sort: pagesConfig.sort,
162
+ limit: pagesConfig.limit
163
+ });
164
+ } catch {
165
+ pages = [];
166
+ }
167
+ return jsonResponse({ dataContext: {
168
+ collections,
169
+ pages,
170
+ locale: routeConfig.dataBindings.locale ?? locale,
171
+ siteName: contentOptions.siteName
172
+ } });
173
+ } catch {
174
+ return jsonResponse({});
175
+ }
176
+ }
177
+ function jsonResponse(data) {
178
+ return new Response(JSON.stringify(data), {
179
+ status: 200,
180
+ headers: { "Content-Type": "application/json" }
181
+ });
182
+ }
183
+ /**
184
+ * Handle Content API requests - delegates to Hono router
185
+ */
186
+ async function handleContentApi(request, cfResult) {
187
+ const contentRoot = import.meta.env.CONLOCA_CONTENT_ROOT || "./content";
188
+ const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || "./canvas";
189
+ const contentApi = await FileSystemContentAPI.create({
190
+ contentRoot,
191
+ canvasDir
192
+ });
193
+ const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || "";
194
+ const app = createContentAPIRouter(contentApi, assetsPath ? { assetsPath } : void 0);
195
+ const url = new URL(request.url);
196
+ const apiIndex = url.pathname.indexOf("/api/");
197
+ if (apiIndex === -1) return new Response("Invalid API path", { status: 400 });
198
+ const basePath = url.pathname.substring(0, apiIndex + 4);
199
+ const path = url.pathname.substring(basePath.length) || "/";
200
+ const headers = new Headers(request.headers);
201
+ if (cfResult.user) {
202
+ headers.set("X-CF-User-Email", cfResult.user.email);
203
+ headers.set("X-CF-User-Sub", cfResult.user.sub);
204
+ }
205
+ const honoRequest = new Request(new URL(path + url.search, "http://localhost").href, {
206
+ method: request.method,
207
+ headers,
208
+ body: request.body,
209
+ ...request.body && { duplex: "half" }
210
+ });
211
+ const response = await app.fetch(honoRequest);
212
+ return new Response(response.body, {
213
+ status: response.status,
214
+ statusText: response.statusText,
215
+ headers: response.headers
216
+ });
217
+ }
218
+
219
+ //#endregion
220
+ export { ALL };
221
+ //# sourceMappingURL=cms-handler.mjs.map
@@ -0,0 +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 optional assets support\n const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';\n const app = createContentAPIRouter(contentApi, assetsPath ? { assetsPath } : undefined);\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,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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,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"}
@@ -0,0 +1,36 @@
1
+ import { defineCollection } from "astro:content";
2
+
3
+ //#region src/collections.d.ts
4
+
5
+ /**
6
+ * Options for createConlocaCollections().
7
+ */
8
+ interface CreateConlocaCollectionsOptions {
9
+ /** Path to content root directory. @default './content' */
10
+ contentRoot?: string;
11
+ /** Site name for multi-site setups. @default 'default' */
12
+ site?: string;
13
+ }
14
+ /**
15
+ * Return type of createConlocaCollections().
16
+ */
17
+ interface ConlocaCollectionsResult {
18
+ /** Astro Content Collections definitions - export this as `collections` */
19
+ collections: Record<string, ReturnType<typeof defineCollection>>;
20
+ }
21
+ /**
22
+ * Creates Astro Content Collections by discovering from indexed content.
23
+ * Uses content-api to find collections that have content.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // src/content.config.ts
28
+ * import { createConlocaCollections } from '@conloca/astro-cms/collections';
29
+ *
30
+ * export const { collections } = await createConlocaCollections();
31
+ * ```
32
+ */
33
+ declare function createConlocaCollections(options?: CreateConlocaCollectionsOptions): Promise<ConlocaCollectionsResult>;
34
+ //#endregion
35
+ export { ConlocaCollectionsResult, CreateConlocaCollectionsOptions, createConlocaCollections };
36
+ //# sourceMappingURL=collections.d.mts.map
@@ -0,0 +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"}