@conloca/astro-cms 0.2.4 → 0.2.6

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 CHANGED
@@ -19,6 +19,9 @@ The second line is the full peer set — the CMS expects the host site to own th
19
19
  optional: the editor is a React application, and this integration does not register Astro's React renderer for you. A
20
20
  site that omits it serves the editor route with no editor in it.
21
21
 
22
+ ttsc compiles with native TypeScript 7. A site that keeps TypeScript 5 or 6, as `@astrojs/check` requires, adds it under
23
+ an alias: `npm install -D typescript@^6.0.3 '@typescript/native@npm:typescript@^7.0.2'`.
24
+
22
25
  ### The four files a site needs
23
26
 
24
27
  A working site needs all four of these. Omitting any one of them breaks the site or the editor, in most cases without an
@@ -0,0 +1,326 @@
1
+ ---
2
+ /**
3
+ * Page Handler Component
4
+ *
5
+ * This Astro component is injected via injectRoute() to handle content pages.
6
+ * It implements getStaticPaths() for static page generation and renders
7
+ * content using the Puck Render component with an optional Layout wrapper.
8
+ *
9
+ * MDX fragments are evaluated at build time and rendered as React components.
10
+ */
11
+
12
+ import { getCollection } from 'astro:content';
13
+ import { loadContentSchemas } from 'virtual:conloca-content-schemas';
14
+ import Layout from 'virtual:conloca-layout';
15
+ import puckConfig from 'virtual:conloca-puck-config';
16
+ import routingConfig from 'virtual:conloca-routing-config';
17
+ import type { PageData, ResolvedRoutingConfig } from '@conloca/astro-cms';
18
+ import { hasHydratableComponents, staticPathParams } from '@conloca/astro-cms';
19
+ import { createPageRendererWithFragments, RenderWithHydration } from '@conloca/astro-cms/components';
20
+ import { type ContentAPI, isContentPublished, pageTimestampsOf } from '@conloca/content-api';
21
+ import { type Data, Render } from '@puckeditor/core';
22
+ import type { GetStaticPaths } from 'astro';
23
+ import type { ComponentType } from 'react';
24
+ // The astro-free render core is emitted by tsc to `dist/ts/src/handlers/`;
25
+ // this handler is copied to `dist/internal/`, so it reaches the core with a
26
+ // relative path and the extraction adds no public export.
27
+ import {
28
+ buildDataContext,
29
+ createCollectionContentSource,
30
+ createReaderContentSource,
31
+ findUnknownComponentTypes,
32
+ getPageEntries,
33
+ loadMdxComponents,
34
+ normalizePathname,
35
+ type PageContentSource,
36
+ type PageEntryData,
37
+ type PageEntryRecord,
38
+ pageNotFoundResponse,
39
+ resolvePuckData,
40
+ } from '../ts/src/handlers/page-render-core.js';
41
+ import { previewEntryParsers } from '../ts/src/internal/collection-parsers.js';
42
+
43
+ // prerender is controlled by injectRoute({ prerender }) in plugin-spa.ts
44
+ // Do not hardcode here — it overrides the route-level config
45
+
46
+ type AstroCollectionEntry = Awaited<ReturnType<typeof getCollection>>[number];
47
+
48
+ let evaluateMDXToComponentPromise: Promise<typeof import('@conloca/mdx/node').evaluateMDXToComponent> | undefined;
49
+
50
+ async function loadEvaluateMDXToComponent() {
51
+ evaluateMDXToComponentPromise ??= import('@conloca/mdx/node').then((module) => module.evaluateMDXToComponent);
52
+
53
+ return evaluateMDXToComponentPromise;
54
+ }
55
+
56
+ export const getStaticPaths: GetStaticPaths = async () => {
57
+ const config = routingConfig as ResolvedRoutingConfig;
58
+ const paths: {
59
+ params: Record<string, string | undefined>;
60
+ props: { routeName: string; collection: string; pathname: string };
61
+ }[] = [];
62
+
63
+ if (!config.enabled) {
64
+ return paths;
65
+ }
66
+
67
+ for (const [routeName, routeConfig] of Object.entries(config.routes)) {
68
+ try {
69
+ const pages = ((await getCollection(routeConfig.collection as never)) as AstroCollectionEntry[])
70
+ .map((entry) => entry.data as Partial<PageEntryData>)
71
+ .filter((data) => {
72
+ if (data.locale !== config.locale || typeof data.pathname !== 'string') {
73
+ return false;
74
+ }
75
+
76
+ return isContentPublished(data);
77
+ });
78
+
79
+ for (const data of pages) {
80
+ const pathname = data.pathname || '/';
81
+
82
+ paths.push({
83
+ params: staticPathParams(pathname, routeConfig.pattern),
84
+ props: {
85
+ routeName,
86
+ collection: routeConfig.collection,
87
+ pathname,
88
+ },
89
+ });
90
+ }
91
+ } catch (error) {
92
+ console.error(`[Conloca] Error loading pages for route '${routeName}':`, error);
93
+ }
94
+ }
95
+
96
+ if (import.meta.env.DEV) {
97
+ if (paths.length === 0) {
98
+ console.warn(
99
+ '[Conloca] getStaticPaths returned 0 pages. ' +
100
+ 'Check that content collections are populated and pages have locale/pathname fields.',
101
+ );
102
+ } else {
103
+ console.debug(`[Conloca] getStaticPaths: ${paths.length} page(s)`);
104
+ }
105
+ }
106
+
107
+ return paths;
108
+ };
109
+
110
+ interface Props {
111
+ routeName: string;
112
+ collection: string;
113
+ pathname: string;
114
+ }
115
+
116
+ const config = routingConfig as ResolvedRoutingConfig;
117
+
118
+ // In prerender mode, props come from getStaticPaths().
119
+ // In SSR mode (prerender: false), derive from the request URL.
120
+ const propsFromStaticPaths = Astro.props as Partial<Props>;
121
+ let routeName = propsFromStaticPaths.routeName;
122
+ let collection = propsFromStaticPaths.collection;
123
+ let pathname = propsFromStaticPaths.pathname;
124
+
125
+ if (!routeName || !collection || !pathname) {
126
+ // SSR fallback: match URL against configured routes. Normalized because
127
+ // browser-facing URLs carry trailing slashes the canonical entry pathnames
128
+ // don't ('/faq/' vs '/faq'), and the page match below is exact equality.
129
+ const requestPath = normalizePathname(Astro.url.pathname);
130
+ for (const [name, routeConfig] of Object.entries(config.routes)) {
131
+ const prefix = routeConfig.pattern.replace(/\[.*$/, '').replace(/\/$/, '');
132
+ if (requestPath === prefix || requestPath.startsWith(`${prefix}/`) || prefix === '') {
133
+ routeName = name;
134
+ collection = routeConfig.collection;
135
+ pathname = requestPath;
136
+ break;
137
+ }
138
+ }
139
+
140
+ if (!routeName || !collection || !pathname) {
141
+ // No configured route claims this URL, so there is no collection to look
142
+ // a page up in. Answer exactly as a matched route with no content does.
143
+ // Bound instead of returned directly: TypeScript skips the expression of a
144
+ // `return` outside a function body, so every top-level return in this file
145
+ // names the type it produces to get the call checked.
146
+ const notFound: Response = pageNotFoundResponse(config.fallback);
147
+ return notFound;
148
+ }
149
+ }
150
+
151
+ // Content-access seam. A caller can install a ContentAPI on
152
+ // `Astro.locals.contentApi`; when present we read through it, so the page shows
153
+ // what that reader serves, parsed with each collection's entry parser as the build
154
+ // parses its entries. Absent — the normal render — we read Astro content
155
+ // collections, byte-for-byte identically to before the extraction.
156
+ const previewContentApi = (Astro.locals as { contentApi?: ContentAPI }).contentApi;
157
+ const source: PageContentSource = previewContentApi
158
+ ? createReaderContentSource(previewContentApi, {
159
+ renderLocale: config.locale,
160
+ parsers: previewEntryParsers(config, await loadContentSchemas()),
161
+ })
162
+ : createCollectionContentSource({
163
+ getCollection: (name) => getCollection(name as never) as Promise<{ data: unknown }[]>,
164
+ isDev: import.meta.env.DEV,
165
+ });
166
+
167
+ let page: PageData | undefined;
168
+ let matchedPage: (PageEntryRecord & { pathname: string }) | undefined;
169
+ let loadError: Error | undefined;
170
+
171
+ try {
172
+ const entries = await getPageEntries(source, collection, config.locale);
173
+ matchedPage = entries.find((data) => normalizePathname(data.pathname) === pathname);
174
+
175
+ if (!matchedPage) {
176
+ const error = new Error(`Page not found: ${pathname}`) as Error & { code?: string };
177
+ error.code = 'PAGE_NOT_FOUND';
178
+ throw error;
179
+ }
180
+
181
+ const data = matchedPage;
182
+ const routeConfig = config.routes[routeName];
183
+
184
+ page = {
185
+ id: data.id,
186
+ title: data.title || data.id,
187
+ description: data.description,
188
+ pathname,
189
+ puckData: data.puckData as Data,
190
+ collection,
191
+ route: {
192
+ name: routeName,
193
+ pattern: routeConfig.pattern,
194
+ meta: routeConfig.meta,
195
+ },
196
+ meta: {
197
+ title: data.title,
198
+ description: data.description,
199
+ },
200
+ timestamps: pageTimestampsOf(data),
201
+ };
202
+ } catch (error) {
203
+ loadError = error as Error;
204
+
205
+ if ((error as { code?: string }).code === 'PAGE_NOT_FOUND') {
206
+ const notFound: Response = pageNotFoundResponse(config.fallback);
207
+ return notFound;
208
+ }
209
+
210
+ throw error;
211
+ }
212
+
213
+ const dataContext = await buildDataContext(source, config.routes[routeName], config, matchedPage);
214
+
215
+ const hasPuckData = !!page?.puckData && Object.keys(page.puckData).length > 0;
216
+ let resolvedPuckData = page?.puckData;
217
+
218
+ if (hasPuckData && page) {
219
+ resolvedPuckData = await resolvePuckData(page.puckData, puckConfig, dataContext);
220
+ }
221
+
222
+ if (hasPuckData && resolvedPuckData) {
223
+ const unknown = findUnknownComponentTypes(resolvedPuckData, puckConfig);
224
+ if (unknown.length > 0) {
225
+ console.error(
226
+ `[Conloca] Page references ${unknown.length} component type(s) missing from your Puck config: ` +
227
+ `${unknown.join(', ')}. Puck renders unknown components as nothing, so these will be blank. ` +
228
+ 'Register them in the file named by puckConfigPath.',
229
+ );
230
+ }
231
+ }
232
+
233
+ const needsHydration = hasPuckData && resolvedPuckData && hasHydratableComponents(resolvedPuckData, puckConfig);
234
+
235
+ let PageRenderer: ComponentType | undefined;
236
+
237
+ if (hasPuckData && page && resolvedPuckData) {
238
+ try {
239
+ const mdxComponents = await loadMdxComponents(
240
+ source,
241
+ config.locale,
242
+ await loadEvaluateMDXToComponent(),
243
+ import.meta.env.DEV,
244
+ );
245
+ PageRenderer = createPageRendererWithFragments(puckConfig, resolvedPuckData, mdxComponents, dataContext);
246
+ } catch (error) {
247
+ console.error('[Conloca] MDX evaluation failed, falling back to plain render:', error);
248
+ PageRenderer = undefined;
249
+ }
250
+ }
251
+ ---
252
+
253
+ {Layout && page ? (
254
+ <Layout title={page.title ?? 'Page'} description={page.description} page={dataContext.page}>
255
+ {hasPuckData && PageRenderer ? (
256
+ <PageRenderer />
257
+ ) : hasPuckData && resolvedPuckData ? (
258
+ needsHydration ? (
259
+ <RenderWithHydration config={puckConfig} data={resolvedPuckData} metadata={dataContext} />
260
+ ) : (
261
+ <Render config={puckConfig} data={resolvedPuckData} metadata={dataContext} />
262
+ )
263
+ ) : (
264
+ <div class="conloca-empty-page">
265
+ <p>This page has no content yet.</p>
266
+ </div>
267
+ )}
268
+ </Layout>
269
+ ) : page ? (
270
+ <html lang={config.locale || 'en'}>
271
+ <head>
272
+ <meta charset="UTF-8" />
273
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
274
+ <title>{page.title || 'Untitled'}</title>
275
+ {page.description && <meta name="description" content={page.description} />}
276
+ {needsHydration && <script>import 'virtual:conloca-hydration-entry'</script>}
277
+ </head>
278
+ <body>
279
+ {hasPuckData && PageRenderer ? (
280
+ <PageRenderer />
281
+ ) : hasPuckData && resolvedPuckData ? (
282
+ needsHydration ? (
283
+ <RenderWithHydration config={puckConfig} data={resolvedPuckData} metadata={dataContext} />
284
+ ) : (
285
+ <Render config={puckConfig} data={resolvedPuckData} metadata={dataContext} />
286
+ )
287
+ ) : (
288
+ <div class="conloca-empty-page">
289
+ <p>This page has no content yet.</p>
290
+ </div>
291
+ )}
292
+ </body>
293
+ </html>
294
+ ) : (
295
+ <html lang="en">
296
+ <head>
297
+ <meta charset="UTF-8" />
298
+ <title>Error</title>
299
+ </head>
300
+ <body>
301
+ <div class="conloca-error">
302
+ <h1>Error Loading Page</h1>
303
+ <p>{import.meta.env.DEV ? (loadError?.message || 'An unknown error occurred.') : 'An error occurred while loading this page.'}</p>
304
+ </div>
305
+ </body>
306
+ </html>
307
+ )}
308
+
309
+ {Layout && needsHydration && <script>import 'virtual:conloca-hydration-entry'</script>}
310
+
311
+ <style>
312
+ .conloca-empty-page {
313
+ padding: 2rem;
314
+ text-align: center;
315
+ color: #666;
316
+ }
317
+
318
+ .conloca-error {
319
+ padding: 2rem;
320
+ text-align: center;
321
+ }
322
+
323
+ .conloca-error h1 {
324
+ color: #c00;
325
+ }
326
+ </style>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -92,9 +92,9 @@
92
92
  "!**/*.tsbuildinfo"
93
93
  ],
94
94
  "dependencies": {
95
- "@conloca/cms-spa": "0.2.4",
96
- "@conloca/content-api": "0.2.4",
97
- "@conloca/mdx": "0.2.4",
95
+ "@conloca/cms-spa": "0.2.6",
96
+ "@conloca/content-api": "0.2.6",
97
+ "@conloca/mdx": "0.2.6",
98
98
  "@puckeditor/core": "^0.23.0",
99
99
  "@tiptap/core": "^3.31.2",
100
100
  "@tiptap/pm": "^3.31.2",
@@ -142,8 +142,8 @@
142
142
  "astro": "^7.3.1",
143
143
  "fast-check": "^4.9.0",
144
144
  "ttsc": "0.34.1",
145
- "typia": "^14.0.4",
146
- "vite": "^7.3.6"
145
+ "typia": "^14.0.6",
146
+ "vite": "^8.2.2"
147
147
  },
148
148
  "nx": {
149
149
  "targets": {