@conloca/astro-cms 0.2.1 → 0.2.3

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 (101) hide show
  1. package/README.md +21 -19
  2. package/dist/internal/page-handler.astro +8 -2
  3. package/dist/ts/.build-inputs.json +88 -0
  4. package/dist/ts/node/content.d.ts +1 -2
  5. package/dist/ts/node/content.d.ts.map +1 -1
  6. package/dist/ts/node/content.js +1 -1
  7. package/dist/ts/node/content.js.map +1 -1
  8. package/dist/ts/node/index.d.ts +1 -1
  9. package/dist/ts/node/index.d.ts.map +1 -1
  10. package/dist/ts/node/index.js +3 -3
  11. package/dist/ts/node/index.js.map +1 -1
  12. package/dist/ts/src/collections.d.ts +31 -53
  13. package/dist/ts/src/collections.d.ts.map +1 -1
  14. package/dist/ts/src/collections.js +66 -71
  15. package/dist/ts/src/collections.js.map +1 -1
  16. package/dist/ts/src/editor-descriptors.d.ts +19 -5
  17. package/dist/ts/src/editor-descriptors.d.ts.map +1 -1
  18. package/dist/ts/src/editor-descriptors.js +26 -5
  19. package/dist/ts/src/editor-descriptors.js.map +1 -1
  20. package/dist/ts/src/entries.d.ts +44 -0
  21. package/dist/ts/src/entries.d.ts.map +1 -0
  22. package/dist/ts/src/entries.js +48 -0
  23. package/dist/ts/src/entries.js.map +1 -0
  24. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
  25. package/dist/ts/src/handlers/collection-content-api.js +7 -2
  26. package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
  27. package/dist/ts/src/handlers/collection-names.d.ts +9 -0
  28. package/dist/ts/src/handlers/collection-names.d.ts.map +1 -0
  29. package/dist/ts/src/handlers/collection-names.js +9 -0
  30. package/dist/ts/src/handlers/collection-names.js.map +1 -0
  31. package/dist/ts/src/handlers/page-render-core.d.ts +31 -12
  32. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
  33. package/dist/ts/src/handlers/page-render-core.js +38 -17
  34. package/dist/ts/src/handlers/page-render-core.js.map +1 -1
  35. package/dist/ts/src/index.d.ts +2 -2
  36. package/dist/ts/src/index.d.ts.map +1 -1
  37. package/dist/ts/src/index.js +1 -3
  38. package/dist/ts/src/index.js.map +1 -1
  39. package/dist/ts/src/internal/collection-parsers.d.ts +26 -0
  40. package/dist/ts/src/internal/collection-parsers.d.ts.map +1 -0
  41. package/dist/ts/src/internal/collection-parsers.js +34 -0
  42. package/dist/ts/src/internal/collection-parsers.js.map +1 -0
  43. package/dist/ts/src/internal/entry-issues.d.ts +8 -0
  44. package/dist/ts/src/internal/entry-issues.d.ts.map +1 -0
  45. package/dist/ts/src/internal/entry-issues.js +19 -0
  46. package/dist/ts/src/internal/entry-issues.js.map +1 -0
  47. package/dist/ts/src/internal/entry-validation.d.ts +93 -0
  48. package/dist/ts/src/internal/entry-validation.d.ts.map +1 -0
  49. package/dist/ts/src/internal/entry-validation.js +228 -0
  50. package/dist/ts/src/internal/entry-validation.js.map +1 -0
  51. package/dist/ts/src/lib/virtual-module-generators.d.ts +13 -0
  52. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
  53. package/dist/ts/src/lib/virtual-module-generators.js +18 -0
  54. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
  55. package/dist/ts/src/loader.d.ts +9 -12
  56. package/dist/ts/src/loader.d.ts.map +1 -1
  57. package/dist/ts/src/loader.js +19 -16
  58. package/dist/ts/src/loader.js.map +1 -1
  59. package/dist/ts/src/page-schemas.d.ts +1 -1
  60. package/dist/ts/src/page-schemas.d.ts.map +1 -1
  61. package/dist/ts/src/page-schemas.js +1 -1
  62. package/dist/ts/src/page-schemas.js.map +1 -1
  63. package/dist/ts/src/plugin-spa.d.ts +12 -0
  64. package/dist/ts/src/plugin-spa.d.ts.map +1 -1
  65. package/dist/ts/src/plugin-spa.js +39 -14
  66. package/dist/ts/src/plugin-spa.js.map +1 -1
  67. package/dist/ts/src/sandbox-frame-handler.d.ts +4 -1
  68. package/dist/ts/src/sandbox-frame-handler.d.ts.map +1 -1
  69. package/dist/ts/src/sandbox-frame-handler.js +22 -11
  70. package/dist/ts/src/sandbox-frame-handler.js.map +1 -1
  71. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts +3 -62
  72. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -1
  73. package/dist/ts/src/site-styles/content-wrapper-endpoint.js +12 -193
  74. package/dist/ts/src/site-styles/content-wrapper-endpoint.js.map +1 -1
  75. package/dist/virtual-modules.d.ts +14 -0
  76. package/node/content.ts +10 -1
  77. package/node/index.ts +7 -7
  78. package/package.json +12 -9
  79. package/src/collections.ts +107 -76
  80. package/src/editor-descriptors.ts +43 -5
  81. package/src/entries.ts +111 -0
  82. package/src/handlers/collection-content-api.ts +7 -2
  83. package/src/handlers/collection-names.ts +8 -0
  84. package/src/handlers/page-handler.astro +8 -2
  85. package/src/handlers/page-render-core.ts +65 -17
  86. package/src/index.ts +6 -7
  87. package/src/internal/collection-parsers.ts +51 -0
  88. package/src/internal/entry-issues.ts +23 -0
  89. package/src/internal/entry-validation.ts +305 -0
  90. package/src/lib/virtual-module-generators.ts +20 -0
  91. package/src/loader.ts +33 -17
  92. package/src/page-schemas.ts +4 -0
  93. package/src/plugin-spa.ts +58 -13
  94. package/src/sandbox-frame-handler.ts +16 -5
  95. package/src/site-styles/content-wrapper-endpoint.ts +4 -285
  96. package/src/virtual-modules.d.ts +14 -0
  97. package/dist/ts/src/internal/page-collection-schema.d.ts +0 -44
  98. package/dist/ts/src/internal/page-collection-schema.d.ts.map +0 -1
  99. package/dist/ts/src/internal/page-collection-schema.js +0 -152
  100. package/dist/ts/src/internal/page-collection-schema.js.map +0 -1
  101. package/src/internal/page-collection-schema.ts +0 -210
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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.1",
96
- "@conloca/content-api": "0.2.1",
97
- "@conloca/mdx": "0.2.1",
95
+ "@conloca/cms-spa": "0.2.3",
96
+ "@conloca/content-api": "0.2.3",
97
+ "@conloca/mdx": "0.2.3",
98
98
  "@puckeditor/core": "^0.23.0",
99
99
  "@tiptap/core": "^3.31.2",
100
100
  "@tiptap/pm": "^3.31.2",
@@ -114,13 +114,12 @@
114
114
  "astro": "^7.3.1",
115
115
  "react": "^19.0.0",
116
116
  "react-dom": "^19.0.0",
117
- "vite": "^7.0.0 || ^8.0.0",
118
- "zod": "^4.5.4"
117
+ "vite": "^7.0.0 || ^8.0.0"
119
118
  },
120
119
  "devDependencies": {
121
120
  "@astrojs/check": "^0.9.10",
122
121
  "@astrojs/sitemap": "^3.7.3",
123
- "@happy-dom/global-registrator": "20.13.2",
122
+ "@happy-dom/global-registrator": "21.0.4",
124
123
  "@tiptap/extension-blockquote": "3.31.2",
125
124
  "@tiptap/extension-bold": "3.31.2",
126
125
  "@tiptap/extension-code": "3.31.2",
@@ -138,8 +137,12 @@
138
137
  "@tiptap/extension-text-align": "3.31.2",
139
138
  "@tiptap/extension-underline": "3.31.2",
140
139
  "@tiptap/html": "3.31.2",
140
+ "@ttsc/unplugin": "^0.34.1",
141
141
  "@vitejs/plugin-react": "^5.2.0",
142
142
  "astro": "^7.3.1",
143
+ "fast-check": "^4.9.0",
144
+ "ttsc": "0.34.1",
145
+ "typia": "^14.0.4",
143
146
  "vite": "^7.3.6"
144
147
  },
145
148
  "nx": {
@@ -214,9 +217,9 @@
214
217
  "{workspaceRoot}/example/website-with-cms/src/**/*"
215
218
  ],
216
219
  "options": {
217
- "command": "bun --conditions=production test",
220
+ "command": "bun test --timeout=0 --conditions=production --preload=./test-native-preload.ts",
218
221
  "cwd": "{projectRoot}",
219
- "timeoutMs": 120000,
222
+ "idleTimeoutMs": 180000,
220
223
  "killAfterMs": 10000
221
224
  }
222
225
  },
@@ -1,15 +1,52 @@
1
1
  import { defineCollection } from 'astro:content';
2
- import type { DataSchemas, PageSchemas } from '@conloca/cms-spa/page-schema-define';
2
+ import type { DataSchemas, HostSchema, PageSchemas } from '@conloca/cms-spa/page-schema-define';
3
3
  import { createContentAPI } from '@conloca/content-api/reader';
4
- import { dataMetaSchema, fragmentMetaSchema, pageMetaSchema } from '@conloca/content-api/schemas';
5
- import { z } from 'zod';
6
- import { ALL_FRAGMENTS_COLLECTION } from './handlers/page-render-core.js';
4
+ import { parseLooseDataMeta } from '@conloca/content-api/schemas';
5
+ import type { Loader } from 'astro/loaders';
6
+ import { ALL_FRAGMENTS_COLLECTION } from './handlers/collection-names.js';
7
7
  import { declareConlocaCollection, withDeclarationCheck } from './internal/declared-collections.js';
8
- import { buildPageCollectionSchema, hostFieldsFromPageSchemas } from './internal/page-collection-schema.js';
8
+ import {
9
+ createDataEntryParser,
10
+ createPageEntryParser,
11
+ type EntryParser,
12
+ parseFragmentEntry,
13
+ } from './internal/entry-validation.js';
9
14
  import { conlocaLoader } from './loader.js';
10
15
 
16
+ export {
17
+ type CollectionEntryLike,
18
+ type ConlocaDataEntry,
19
+ type ConlocaFragmentEntry,
20
+ type ConlocaPageEntry,
21
+ conlocaDataEntries,
22
+ conlocaFragmentEntries,
23
+ conlocaPageEntries,
24
+ type TypedCollectionEntry,
25
+ } from './entries.js';
26
+ export type { EntryParser };
11
27
  export { ALL_FRAGMENTS_COLLECTION };
12
28
 
29
+ /**
30
+ * How every collection below is declared: a loader and NO `schema`.
31
+ *
32
+ * Astro's `schema` option only accepts Zod; it is optional, and without it
33
+ * `parseData` stores the loader's data unchanged. Validation therefore runs in
34
+ * the loader, before `store.set`, with the generated Typia validators for the
35
+ * collection (see `internal/entry-validation.ts`) — a stored entry that fails
36
+ * them still fails the build. Entry typing comes from the typed accessors
37
+ * (`conlocaPageEntries` / `conlocaDataEntries` / `conlocaFragmentEntries`),
38
+ * because Astro infers `getCollection` types from a Zod schema only.
39
+ */
40
+ function conlocaCollection(loader: Loader, parseEntry: EntryParser<Record<string, unknown>>) {
41
+ const defined = defineCollection({ loader });
42
+ entryParsersByCollection.set(defined, parseEntry);
43
+ return defined;
44
+ }
45
+
46
+ // The entry parser each Conloca-built collection's loader validates with, so a
47
+ // test (or a host) can run exactly the build's validation without a content root.
48
+ const entryParsersByCollection = new WeakMap<object, EntryParser<Record<string, unknown>>>();
49
+
13
50
  /**
14
51
  * Options for createConlocaCollections().
15
52
  */
@@ -23,8 +60,8 @@ export interface CreateConlocaCollectionsOptions {
23
60
  site?: string;
24
61
  /**
25
62
  * The same `pageSchemas` object the editor loads. Host meta fields are
26
- * validated on every page collection at build time (made optional, because
27
- * the editor scopes a descriptor to a prefix while Astro validates the
63
+ * validated on every page collection at build time (optional, because
64
+ * the editor scopes a descriptor to a prefix while Astro builds the
28
65
  * whole pile). Pass the object itself — not a hand-copied field list — so
29
66
  * the form and the build cannot drift. Listing types come from augmenting
30
67
  * `HostPageMeta`, not from Astro `entry.data`.
@@ -44,10 +81,8 @@ export interface ConlocaCollectionsResult {
44
81
 
45
82
  /**
46
83
  * @deprecated Declare collections explicitly with {@link conlocaPages},
47
- * {@link conlocaData} and {@link conlocaFragments} — they keep the entry
48
- * types Astro's generated `getCollection` needs, and undeclared content
49
- * fails the build instead of silently not building. This wrapper still
50
- * works but returns untyped entries.
84
+ * {@link conlocaData} and {@link conlocaFragments} — undeclared content fails
85
+ * the build instead of silently not building. This wrapper still works.
51
86
  *
52
87
  * Creates Astro Content Collections by discovering from indexed content.
53
88
  * Uses content-api to find collections that have content.
@@ -56,7 +91,7 @@ export interface ConlocaCollectionsResult {
56
91
  * ```typescript
57
92
  * // src/content.config.ts
58
93
  * import { createConlocaCollections } from '@conloca/astro-cms/node/content';
59
- * import { pageSchemas } from './page-schemas';
94
+ * import { pageSchemas } from './page-schemas.js';
60
95
  *
61
96
  * export const { collections } = await createConlocaCollections({ pageSchemas });
62
97
  * ```
@@ -73,37 +108,32 @@ export async function createConlocaCollections(
73
108
  const api = await createContentAPI({ contentRoot });
74
109
  const collections: Record<string, ReturnType<typeof defineCollection>> = {};
75
110
 
76
- collections[ALL_FRAGMENTS_COLLECTION] = defineCollection({
77
- loader: conlocaLoader({ contentRoot, site, kind: 'fragment' }),
78
- schema: fragmentMetaSchema.loose(),
79
- });
111
+ collections[ALL_FRAGMENTS_COLLECTION] = conlocaCollection(
112
+ conlocaLoader({ contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
113
+ parseFragmentEntry,
114
+ );
80
115
 
81
116
  for (const name of api.fragments.collections) {
82
- collections[name] = defineCollection({
83
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'fragment' }),
84
- schema: fragmentMetaSchema.loose(),
85
- });
117
+ collections[name] = conlocaCollection(
118
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
119
+ parseFragmentEntry,
120
+ );
86
121
  }
87
122
 
88
123
  for (const name of api.data.collections) {
89
- collections[name] = defineCollection({
90
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }),
91
- schema: dataMetaSchema.loose(),
92
- });
124
+ collections[name] = conlocaCollection(
125
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'data', parseEntry: parseLooseDataMeta }),
126
+ parseLooseDataMeta,
127
+ );
93
128
  }
94
129
 
95
- const hostFields = pageSchemas ? hostFieldsFromPageSchemas(pageSchemas) : undefined;
96
- const pageSchema =
97
- hostFields && Object.keys(hostFields.shape).length > 0
98
- ? buildPageCollectionSchema(hostFields)
99
- : pageMetaSchema.loose();
100
-
130
+ const parsePage = createPageEntryParser(pageSchemas);
101
131
  const siteCollections = api.getSite(site)?.collections ?? new Set<string>();
102
132
  for (const name of siteCollections) {
103
- collections[name] = defineCollection({
104
- loader: conlocaLoader({ collection: name, contentRoot, site, kind: 'page' }),
105
- schema: pageSchema,
106
- });
133
+ collections[name] = conlocaCollection(
134
+ conlocaLoader({ collection: name, contentRoot, site, kind: 'page', parseEntry: parsePage }),
135
+ parsePage,
136
+ );
107
137
  }
108
138
 
109
139
  return { collections };
@@ -144,26 +174,35 @@ export function pageSchemasOf(collection: object): PageSchemas | undefined {
144
174
  }
145
175
 
146
176
  /**
147
- * One typed Astro collection for Conloca pages — the explicit,
148
- * Starlight-shaped declaration:
177
+ * The entry parser a Conloca-built collection's loader validates every entry
178
+ * with before storing it, or undefined for any other collection.
179
+ */
180
+ export function entryParserOf(collection: object): EntryParser<Record<string, unknown>> | undefined {
181
+ return entryParsersByCollection.get(collection);
182
+ }
183
+
184
+ /**
185
+ * One Astro collection for Conloca pages — the explicit, Starlight-shaped
186
+ * declaration:
149
187
  *
150
188
  * ```ts
151
189
  * export const collections = { pages: conlocaPages({ pageSchemas }) };
152
190
  * ```
153
191
  *
154
- * Entry data is typed as {@link ConlocaPageEntry}; `getCollection('pages')`
155
- * carries pathname/title/dates and the host's declared meta fields.
192
+ * Every page is validated as {@link ConlocaPageEntry} while it loads; read it
193
+ * typed with `conlocaPageEntries(await getCollection('pages'), pageSchemas)`.
156
194
  */
157
195
  export function conlocaPages(options: ConlocaPagesOptions = {}) {
158
196
  const { contentRoot = defaultContentRoot(), site = 'default', collection = 'pages', pageSchemas } = options;
159
197
  declareConlocaCollection('page', collection);
160
- const defined = defineCollection({
161
- loader: withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'page' }), {
198
+ const parseEntry = createPageEntryParser(pageSchemas);
199
+ const defined = conlocaCollection(
200
+ withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'page', parseEntry }), {
162
201
  contentRoot,
163
202
  site,
164
203
  }),
165
- schema: buildPageCollectionSchema(pageSchemas ? hostFieldsFromPageSchemas(pageSchemas) : z.object({})),
166
- });
204
+ parseEntry,
205
+ );
167
206
  if (pageSchemas) pageSchemasByCollection.set(defined, pageSchemas);
168
207
  return defined;
169
208
  }
@@ -184,49 +223,41 @@ export interface ConlocaDataOptions<DS extends DataSchemas> {
184
223
 
185
224
  /**
186
225
  * Deliberate asymmetry with pages: a data schema is validated AS GIVEN —
187
- * requiredness preserved, no rewrite guard — because the site owns it whole
188
- * for exactly one collection, unlike host page fields folded into the shared
189
- * pages schema. The flip side, accepted for now: a .transform or .default in
190
- * a dataSchema runs at build time but not in the editor form, so the two can
191
- * diverge.
226
+ * requiredness preserved — because the site owns it whole for exactly one
227
+ * collection, unlike host page fields checked across the shared pages pile.
192
228
  */
193
- function conlocaDataCollection<T extends z.ZodObject<z.ZodRawShape>>(
194
- name: string,
195
- payload: T,
196
- contentRoot: string,
197
- site: string,
198
- ) {
199
- return defineCollection({
200
- loader: withDeclarationCheck(conlocaLoader({ collection: name, contentRoot, site, kind: 'data' }), {
229
+ function conlocaDataCollection(name: string, payload: HostSchema, contentRoot: string, site: string) {
230
+ const parseEntry = createDataEntryParser(payload);
231
+ return conlocaCollection(
232
+ withDeclarationCheck(conlocaLoader({ collection: name, contentRoot, site, kind: 'data', parseEntry }), {
201
233
  contentRoot,
202
234
  site,
203
235
  }),
204
- // Base meta plus this collection's payload under `data`. `data` stays
205
- // optional: an entry saved before any payload exists is not an error.
206
- schema: z.looseObject({ ...dataMetaSchema.shape, data: payload.optional() }),
207
- });
236
+ parseEntry,
237
+ );
208
238
  }
209
239
 
210
240
  /**
211
- * Typed Astro collections for Conloca data, one per `dataSchemas` key:
241
+ * Astro collections for Conloca data, one per `dataSchemas` key:
212
242
  *
213
243
  * ```ts
214
244
  * export const collections = { ...conlocaData({ dataSchemas }) };
215
245
  * ```
216
246
  *
217
- * `getCollection('testimonials')` entries carry `data` typed by that key's
218
- * schema, and a stored entry that fails its schema fails the build instead
219
- * of rendering blank.
247
+ * A stored entry whose payload fails its schema fails the build instead of
248
+ * rendering blank. Read entries typed by that key's schema with
249
+ * `conlocaDataEntries(dataSchemas, 'testimonials', await getCollection('testimonials'))`.
220
250
  */
221
251
  export function conlocaData<DS extends DataSchemas>(options: ConlocaDataOptions<DS>) {
222
252
  const { dataSchemas, contentRoot = defaultContentRoot(), site = 'default' } = options;
223
- const entries = Object.entries(dataSchemas).map(([name, payload]) => {
253
+ const collections: Record<string, ReturnType<typeof conlocaDataCollection>> = {};
254
+ for (const [name, payload] of Object.entries(dataSchemas)) {
224
255
  declareConlocaCollection('data', name);
225
- return [name, conlocaDataCollection(name, payload, contentRoot, site)] as const;
226
- });
227
- // Object.fromEntries erases per-key types; the assertion restores exactly
228
- // what the loop built — one collection per dataSchemas key.
229
- return Object.fromEntries(entries) as { [K in keyof DS]: ReturnType<typeof conlocaDataCollection<DS[K]>> };
256
+ collections[name] = conlocaDataCollection(name, payload, contentRoot, site);
257
+ }
258
+ // The loop built exactly one collection per dataSchemas key; the record type
259
+ // keeps those keys for the content.config `collections` export.
260
+ return collections as { [K in keyof DS]: ReturnType<typeof conlocaDataCollection> };
230
261
  }
231
262
 
232
263
  /**
@@ -249,13 +280,13 @@ export function conlocaFragments<const N extends readonly string[]>(...names: N)
249
280
  const site = 'default';
250
281
  declareConlocaCollection('fragment', EDITOR_FRAGMENT_FOLDER);
251
282
  const fragmentCollection = (collection?: string) =>
252
- defineCollection({
253
- loader: withDeclarationCheck(conlocaLoader({ collection, contentRoot, site, kind: 'fragment' }), {
254
- contentRoot,
255
- site,
256
- }),
257
- schema: fragmentMetaSchema.loose(),
258
- });
283
+ conlocaCollection(
284
+ withDeclarationCheck(
285
+ conlocaLoader({ collection, contentRoot, site, kind: 'fragment', parseEntry: parseFragmentEntry }),
286
+ { contentRoot, site },
287
+ ),
288
+ parseFragmentEntry,
289
+ );
259
290
  const named = Object.fromEntries(
260
291
  names.map((name) => {
261
292
  declareConlocaCollection('fragment', name);
@@ -1,3 +1,4 @@
1
+ import { isAbsolute } from 'node:path';
1
2
  import { readEditorDataBindings } from '@conloca/content-api';
2
3
  import type { MdxRegistryScanOptions } from './discovery/discover.js';
3
4
  import type { EditorDataBindings, TemplateConfig } from './types.js';
@@ -6,23 +7,37 @@ import type { EditorDataBindings, TemplateConfig } from './types.js';
6
7
  * Env var through which `conlocaCMS` publishes the editor descriptors it
7
8
  * resolved during an Astro build, alongside `CONLOCA_CONTENT_ROOT`.
8
9
  *
9
- * The CMS resolves them once — the site's schemas module, the MDX registry
10
- * scan inputs, the page templates and the routing data bindings — so another
11
- * integration in the same build reads the SAME descriptors dev serves from
12
- * `schemasPath`, `/api/registry` and its UI config instead of taking those
13
- * options a second time.
10
+ * The CMS resolves them once — the site's schemas module, its editor-build
11
+ * options, the MDX registry scan inputs, the page templates and the routing
12
+ * data bindings — so another integration in the same build reads the SAME
13
+ * descriptors dev serves from `schemasPath`, `/api/registry` and its UI config
14
+ * instead of taking those options a second time.
14
15
  */
15
16
  export const EDITOR_DESCRIPTORS_ENV_VAR = 'CONLOCA_EDITOR_DESCRIPTORS';
16
17
 
17
18
  export interface EditorDescriptorChannel {
18
19
  /** Absolute path of the host's schemas module (the `schemasPath` option), when configured. */
19
20
  schemasPath?: string;
21
+ /**
22
+ * Absolute path of the puck config module (the `puckConfigPath` option).
23
+ * Optional only because an older `@conloca/astro-cms` wrote no such field;
24
+ * this version always publishes it.
25
+ */
26
+ puckConfigPath?: string;
27
+ /** Absolute paths of the `siteStyles` option, resolved against the Astro root, one entry per stylesheet. */
28
+ siteStyles?: string[];
29
+ /** Absolute paths of `editorStyles`, each resolved against the Astro root. */
30
+ editorStyles?: string[];
31
+ /** The `editorCSS` option, verbatim. */
32
+ editorCSS?: string;
20
33
  /** Resolved inputs for the MDX component registry scan (`mdxComponentFolders` + the MDX content root). */
21
34
  registry: MdxRegistryScanOptions;
22
35
  /** Page-creation templates (the `templates` option), when configured. */
23
36
  templates?: Record<string, TemplateConfig>;
24
37
  /** The routing data bindings each page's data context is built from, when the site has content routes. */
25
38
  dataBindings?: EditorDataBindings;
39
+ /** Absolute paths of every folder the content API writes to: the content root, the MDX pages root, the media folder. */
40
+ contentPaths?: string[];
26
41
  }
27
42
 
28
43
  /**
@@ -44,9 +59,14 @@ export function readEditorDescriptors(
44
59
  }
45
60
  if (typeof parsed !== 'object' || parsed === null) return undefined;
46
61
  const schemasPath = 'schemasPath' in parsed ? parsed.schemasPath : undefined;
62
+ const puckConfigPath = 'puckConfigPath' in parsed ? parsed.puckConfigPath : undefined;
63
+ const styleValue = 'siteStyles' in parsed ? parsed.siteStyles : undefined;
64
+ const editorStyleValue = 'editorStyles' in parsed ? parsed.editorStyles : undefined;
65
+ const editorCSS = 'editorCSS' in parsed ? parsed.editorCSS : undefined;
47
66
  const registry = 'registry' in parsed ? parsed.registry : undefined;
48
67
  const templateValue = 'templates' in parsed ? parsed.templates : undefined;
49
68
  const dataBindingValue = 'dataBindings' in parsed ? parsed.dataBindings : undefined;
69
+ const contentPathValue = 'contentPaths' in parsed ? parsed.contentPaths : undefined;
50
70
  if (typeof registry !== 'object' || registry === null) return undefined;
51
71
  const contentRoot = 'contentRoot' in registry ? registry.contentRoot : undefined;
52
72
  const componentFolders = 'componentFolders' in registry ? registry.componentFolders : undefined;
@@ -61,8 +81,25 @@ export function readEditorDescriptors(
61
81
  }
62
82
  const templates = readTemplates(templateValue);
63
83
  const dataBindings = readEditorDataBindings(dataBindingValue);
84
+ const siteStyles =
85
+ Array.isArray(styleValue) && styleValue.every((path): path is string => typeof path === 'string')
86
+ ? styleValue
87
+ : undefined;
88
+ const editorStyles =
89
+ Array.isArray(editorStyleValue) && editorStyleValue.every((path): path is string => typeof path === 'string')
90
+ ? editorStyleValue
91
+ : undefined;
92
+ const contentPaths =
93
+ Array.isArray(contentPathValue) &&
94
+ contentPathValue.every((path): path is string => typeof path === 'string' && isAbsolute(path))
95
+ ? contentPathValue
96
+ : undefined;
64
97
  return {
65
98
  ...(typeof schemasPath === 'string' ? { schemasPath } : {}),
99
+ ...(typeof puckConfigPath === 'string' ? { puckConfigPath } : {}),
100
+ ...(siteStyles === undefined ? {} : { siteStyles }),
101
+ ...(editorStyles === undefined ? {} : { editorStyles }),
102
+ ...(typeof editorCSS === 'string' ? { editorCSS } : {}),
66
103
  registry: {
67
104
  contentRoot,
68
105
  componentFolders,
@@ -71,6 +108,7 @@ export function readEditorDescriptors(
71
108
  },
72
109
  ...(templates === undefined ? {} : { templates }),
73
110
  ...(dataBindings === undefined ? {} : { dataBindings }),
111
+ ...(contentPaths === undefined ? {} : { contentPaths }),
74
112
  };
75
113
  }
76
114
 
package/src/entries.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { DataSchemas, HostSchemaType, PageSchemas } from '@conloca/cms-spa/page-schema-define';
2
+ import { describeEntryIssues } from './internal/entry-issues.js';
3
+ import {
4
+ type ConlocaDataEntry,
5
+ type ConlocaFragmentEntry,
6
+ type ConlocaPageEntry,
7
+ createDataEntryParser,
8
+ createPageEntryParser,
9
+ type EntryParser,
10
+ parseFragmentEntry,
11
+ } from './internal/entry-validation.js';
12
+
13
+ /**
14
+ * Typed reads of Conloca collections.
15
+ *
16
+ * Astro types `getCollection()` entries from a collection's Zod `schema`; the
17
+ * Conloca factories declare none (the loader validates with generated Typia
18
+ * validators instead), so Astro's own entry type for them is `any`. These
19
+ * accessors take what `getCollection()` returned and hand back entries typed
20
+ * by the same declarations the build validated with — re-running those
21
+ * validators, so the type is earned at runtime rather than asserted:
22
+ *
23
+ * ```ts
24
+ * import { getCollection } from 'astro:content';
25
+ * import { conlocaPageEntries } from '@conloca/astro-cms/collections';
26
+ * import { pageSchemas } from '../page-schemas';
27
+ *
28
+ * const pages = conlocaPageEntries(await getCollection('pages'), pageSchemas);
29
+ * pages[0].data.title; // string
30
+ * ```
31
+ *
32
+ * They take the entries rather than calling `getCollection` themselves so they
33
+ * stay importable (and testable) outside Astro's virtual modules.
34
+ *
35
+ * Each call re-validates every entry it is given; call once per collection
36
+ * read (e.g. in `getStaticPaths` or once per page) rather than per access.
37
+ */
38
+
39
+ /** The fields every Astro collection entry carries besides `data`. */
40
+ export interface CollectionEntryLike {
41
+ id: string;
42
+ data: unknown;
43
+ }
44
+
45
+ /** An Astro collection entry with `data` replaced by its validated, typed form. */
46
+ export type TypedCollectionEntry<E extends CollectionEntryLike, T> = Omit<E, 'data'> & { data: T };
47
+
48
+ // Parsers fold descriptors and compare generated schemas once per registry, not
49
+ // once per read: the registries are module constants in a site's config.
50
+ const pageParsers = new WeakMap<PageSchemas, EntryParser<ConlocaPageEntry>>();
51
+ const dataParsers = new WeakMap<object, EntryParser<ConlocaDataEntry<object>>>();
52
+ const corePageParser = createPageEntryParser();
53
+
54
+ function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
56
+ }
57
+
58
+ function typedEntries<E extends CollectionEntryLike, T>(
59
+ entries: readonly E[],
60
+ parse: EntryParser<T>,
61
+ collection: string,
62
+ ): TypedCollectionEntry<E, T>[] {
63
+ return entries.map((entry) => {
64
+ if (!isRecord(entry.data)) {
65
+ throw new Error(`[conloca] ${collection} entry "${entry.id}" has no data record`);
66
+ }
67
+ const result = parse(entry.data);
68
+ if (!result.success) {
69
+ throw new Error(describeEntryIssues(result.issues, { collection, id: entry.id }));
70
+ }
71
+ return { ...entry, data: result.data };
72
+ });
73
+ }
74
+
75
+ /** `getCollection('pages')` entries, validated and typed as {@link ConlocaPageEntry}. */
76
+ export function conlocaPageEntries<E extends CollectionEntryLike>(
77
+ entries: readonly E[],
78
+ pageSchemas?: PageSchemas,
79
+ ): TypedCollectionEntry<E, ConlocaPageEntry>[] {
80
+ let parse = corePageParser;
81
+ if (pageSchemas) {
82
+ parse = pageParsers.get(pageSchemas) ?? createPageEntryParser(pageSchemas);
83
+ pageParsers.set(pageSchemas, parse);
84
+ }
85
+ return typedEntries(entries, parse, 'pages');
86
+ }
87
+
88
+ /** A `conlocaData` collection's entries, with `data` validated and typed by that key's host schema. */
89
+ export function conlocaDataEntries<E extends CollectionEntryLike, DS extends DataSchemas, K extends keyof DS & string>(
90
+ dataSchemas: DS,
91
+ collection: K,
92
+ entries: readonly E[],
93
+ ): TypedCollectionEntry<E, ConlocaDataEntry<HostSchemaType<DS[K]>>>[] {
94
+ const payload: DataSchemas[string] | undefined = dataSchemas[collection];
95
+ if (!payload) throw new Error(`[conloca] dataSchemas declares no collection "${collection}"`);
96
+ const parse = dataParsers.get(payload) ?? createDataEntryParser(payload);
97
+ dataParsers.set(payload, parse);
98
+ // `payload` is `dataSchemas[collection]`, so its generated validator checks
99
+ // exactly `HostSchemaType<DS[K]>`; TypeScript cannot follow an indexed
100
+ // generic through the registry lookup, so the parser is re-typed here.
101
+ return typedEntries(entries, parse as EntryParser<ConlocaDataEntry<HostSchemaType<DS[K]>>>, collection);
102
+ }
103
+
104
+ /** Fragment collection entries, validated and typed as {@link ConlocaFragmentEntry}. */
105
+ export function conlocaFragmentEntries<E extends CollectionEntryLike>(
106
+ entries: readonly E[],
107
+ ): TypedCollectionEntry<E, ConlocaFragmentEntry>[] {
108
+ return typedEntries(entries, parseFragmentEntry, 'fragments');
109
+ }
110
+
111
+ export type { ConlocaDataEntry, ConlocaFragmentEntry, ConlocaPageEntry };
@@ -35,7 +35,8 @@ import type {
35
35
  UpdateResult,
36
36
  } from '@conloca/content-api';
37
37
  import type { ResolvedRoutingConfig } from '../types.js';
38
- import { ALL_FRAGMENTS_COLLECTION } from './page-render-core.js';
38
+ import { ALL_FRAGMENTS_COLLECTION } from './collection-names.js';
39
+ import { rememberBuiltRecord } from './page-render-core.js';
39
40
 
40
41
  interface CollectionEntry {
41
42
  data: Record<string, unknown>;
@@ -126,7 +127,11 @@ export async function createCollectionBackedContentAPI(opts: CollectionBackedCon
126
127
  if (locale === undefined) continue;
127
128
  const { version, content } = splitRecord(record);
128
129
  locales[locale] = version;
129
- entries.set(`${id} ${locale}`, { ...identity, localized: { ...version, content } });
130
+ const entry: LocalizedEntry = { ...identity, localized: { ...version, content } };
131
+ // The record is the build's parse output; a reader source hands it
132
+ // out as is instead of parsing what was reconstructed from it.
133
+ rememberBuiltRecord(entry, record);
134
+ entries.set(`${id} ${locale}`, entry);
130
135
  }
131
136
  manifests.push({ ...identity, locales });
132
137
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Synthetic collection every discovered fragment lands in (the loader flattens
3
+ * all fragment collections into one). A leaf module on purpose: the render core
4
+ * must stay free of the `astro:content` that `collections.ts` pulls in, and the
5
+ * content config that `collections.ts` runs in must not load the render core's
6
+ * Puck and React graph just to name a collection. Both re-export it.
7
+ */
8
+ export const ALL_FRAGMENTS_COLLECTION = '__conloca_fragments';
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { getCollection } from 'astro:content';
13
+ import { loadContentSchemas } from 'virtual:conloca-content-schemas';
13
14
  import Layout from 'virtual:conloca-layout';
14
15
  import puckConfig from 'virtual:conloca-puck-config';
15
16
  import routingConfig from 'virtual:conloca-routing-config';
@@ -37,6 +38,7 @@ import {
37
38
  pageNotFoundResponse,
38
39
  resolvePuckData,
39
40
  } from '../ts/src/handlers/page-render-core.js';
41
+ import { previewEntryParsers } from '../ts/src/internal/collection-parsers.js';
40
42
 
41
43
  // prerender is controlled by injectRoute({ prerender }) in plugin-spa.ts
42
44
  // Do not hardcode here — it overrides the route-level config
@@ -148,11 +150,15 @@ if (!routeName || !collection || !pathname) {
148
150
 
149
151
  // Content-access seam. A caller can install a ContentAPI on
150
152
  // `Astro.locals.contentApi`; when present we read through it, so the page shows
151
- // what that reader serves. Absent — the normal render — we read Astro content
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
152
155
  // collections, byte-for-byte identically to before the extraction.
153
156
  const previewContentApi = (Astro.locals as { contentApi?: ContentAPI }).contentApi;
154
157
  const source: PageContentSource = previewContentApi
155
- ? createReaderContentSource(previewContentApi, config.locale)
158
+ ? createReaderContentSource(previewContentApi, {
159
+ renderLocale: config.locale,
160
+ parsers: previewEntryParsers(config, await loadContentSchemas()),
161
+ })
156
162
  : createCollectionContentSource({
157
163
  getCollection: (name) => getCollection(name as never) as Promise<{ data: unknown }[]>,
158
164
  isDev: import.meta.env.DEV,