@conloca/astro-cms 0.2.1 → 0.2.2
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 +21 -19
- package/dist/internal/page-handler.astro +8 -2
- package/dist/ts/node/content.d.ts +1 -2
- package/dist/ts/node/content.d.ts.map +1 -1
- package/dist/ts/node/content.js +1 -1
- package/dist/ts/node/content.js.map +1 -1
- package/dist/ts/src/collections.d.ts +31 -53
- package/dist/ts/src/collections.d.ts.map +1 -1
- package/dist/ts/src/collections.js +66 -71
- package/dist/ts/src/collections.js.map +1 -1
- package/dist/ts/src/entries.d.ts +44 -0
- package/dist/ts/src/entries.d.ts.map +1 -0
- package/dist/ts/src/entries.js +48 -0
- package/dist/ts/src/entries.js.map +1 -0
- package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
- package/dist/ts/src/handlers/collection-content-api.js +7 -2
- package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
- package/dist/ts/src/handlers/collection-names.d.ts +9 -0
- package/dist/ts/src/handlers/collection-names.d.ts.map +1 -0
- package/dist/ts/src/handlers/collection-names.js +9 -0
- package/dist/ts/src/handlers/collection-names.js.map +1 -0
- package/dist/ts/src/handlers/page-render-core.d.ts +31 -12
- package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
- package/dist/ts/src/handlers/page-render-core.js +38 -17
- package/dist/ts/src/handlers/page-render-core.js.map +1 -1
- package/dist/ts/src/index.d.ts +2 -2
- package/dist/ts/src/index.d.ts.map +1 -1
- package/dist/ts/src/index.js +1 -3
- package/dist/ts/src/index.js.map +1 -1
- package/dist/ts/src/internal/collection-parsers.d.ts +26 -0
- package/dist/ts/src/internal/collection-parsers.d.ts.map +1 -0
- package/dist/ts/src/internal/collection-parsers.js +34 -0
- package/dist/ts/src/internal/collection-parsers.js.map +1 -0
- package/dist/ts/src/internal/entry-issues.d.ts +8 -0
- package/dist/ts/src/internal/entry-issues.d.ts.map +1 -0
- package/dist/ts/src/internal/entry-issues.js +19 -0
- package/dist/ts/src/internal/entry-issues.js.map +1 -0
- package/dist/ts/src/internal/entry-validation.d.ts +93 -0
- package/dist/ts/src/internal/entry-validation.d.ts.map +1 -0
- package/dist/ts/src/internal/entry-validation.js +228 -0
- package/dist/ts/src/internal/entry-validation.js.map +1 -0
- package/dist/ts/src/lib/virtual-module-generators.d.ts +13 -0
- package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
- package/dist/ts/src/lib/virtual-module-generators.js +18 -0
- package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
- package/dist/ts/src/loader.d.ts +9 -12
- package/dist/ts/src/loader.d.ts.map +1 -1
- package/dist/ts/src/loader.js +19 -16
- package/dist/ts/src/loader.js.map +1 -1
- package/dist/ts/src/page-schemas.d.ts +1 -1
- package/dist/ts/src/page-schemas.d.ts.map +1 -1
- package/dist/ts/src/page-schemas.js +1 -1
- package/dist/ts/src/page-schemas.js.map +1 -1
- package/dist/ts/src/plugin-spa.d.ts +12 -0
- package/dist/ts/src/plugin-spa.d.ts.map +1 -1
- package/dist/ts/src/plugin-spa.js +9 -2
- package/dist/ts/src/plugin-spa.js.map +1 -1
- package/dist/virtual-modules.d.ts +14 -0
- package/node/content.ts +10 -1
- package/package.json +12 -9
- package/src/collections.ts +107 -76
- package/src/entries.ts +111 -0
- package/src/handlers/collection-content-api.ts +7 -2
- package/src/handlers/collection-names.ts +8 -0
- package/src/handlers/page-handler.astro +8 -2
- package/src/handlers/page-render-core.ts +65 -17
- package/src/index.ts +6 -7
- package/src/internal/collection-parsers.ts +51 -0
- package/src/internal/entry-issues.ts +23 -0
- package/src/internal/entry-validation.ts +305 -0
- package/src/lib/virtual-module-generators.ts +20 -0
- package/src/loader.ts +33 -17
- package/src/page-schemas.ts +4 -0
- package/src/plugin-spa.ts +24 -1
- package/src/virtual-modules.d.ts +14 -0
- package/dist/ts/src/internal/page-collection-schema.d.ts +0 -44
- package/dist/ts/src/internal/page-collection-schema.d.ts.map +0 -1
- package/dist/ts/src/internal/page-collection-schema.js +0 -152
- package/dist/ts/src/internal/page-collection-schema.js.map +0 -1
- package/src/internal/page-collection-schema.ts +0 -210
|
@@ -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 './
|
|
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
|
-
|
|
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
|
|
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,
|
|
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,
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
type ContentManifest,
|
|
18
18
|
type ContentMeta,
|
|
19
19
|
isContentPublished,
|
|
20
|
+
type LocalizedEntry,
|
|
20
21
|
type MDXHeading,
|
|
21
22
|
pageTimestampsOf,
|
|
22
23
|
selectPagesByPrefix,
|
|
@@ -25,19 +26,16 @@ import type { Config } from '@puckeditor/core';
|
|
|
25
26
|
import { type Data, resolveAllData } from '@puckeditor/core';
|
|
26
27
|
import type { ComponentType } from 'react';
|
|
27
28
|
import React from 'react';
|
|
29
|
+
import { describeEntryIssues } from '../internal/entry-issues.js';
|
|
30
|
+
import type { EntryParser } from '../internal/entry-validation.js';
|
|
28
31
|
import type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from '../types.js';
|
|
32
|
+
import { ALL_FRAGMENTS_COLLECTION } from './collection-names.js';
|
|
29
33
|
|
|
30
34
|
// Re-exported so the copied `dist/internal/page-handler.astro` reaches
|
|
31
35
|
// everything it renders with through this one module.
|
|
32
36
|
export { findUnknownComponentTypes } from '../lib/unknown-components.js';
|
|
33
37
|
|
|
34
|
-
|
|
35
|
-
* Synthetic collection every discovered fragment lands in (the loader flattens
|
|
36
|
-
* all fragment collections into one). Owned here — rather than imported from
|
|
37
|
-
* `collections.ts` — so this core stays free of the `astro:content` that module
|
|
38
|
-
* pulls in; `collections.ts` re-exports it to keep the public name stable.
|
|
39
|
-
*/
|
|
40
|
-
export const ALL_FRAGMENTS_COLLECTION = '__conloca_fragments';
|
|
38
|
+
export { ALL_FRAGMENTS_COLLECTION };
|
|
41
39
|
|
|
42
40
|
/**
|
|
43
41
|
* The single content-access seam the render core depends on: give me the raw
|
|
@@ -395,27 +393,80 @@ export async function resolvePuckData(puckData: Data, puckConfig: Config, dataCo
|
|
|
395
393
|
}
|
|
396
394
|
}
|
|
397
395
|
|
|
396
|
+
export interface ReaderContentSourceOptions {
|
|
397
|
+
/**
|
|
398
|
+
* Every consumer filters records to one locale, and each shaped locale is
|
|
399
|
+
* one getLocalized read, so with a render locale known, shaping the others
|
|
400
|
+
* is wasted work.
|
|
401
|
+
*/
|
|
402
|
+
renderLocale?: string;
|
|
403
|
+
/**
|
|
404
|
+
* The entry parser of each collection, keyed by collection name — the ones
|
|
405
|
+
* the collection factories hand the loader (see `previewEntryParsers`). The
|
|
406
|
+
* build runs every loader record through its parser before storing it, so a
|
|
407
|
+
* preview record must go through it too: otherwise a page gets ISO strings
|
|
408
|
+
* where the published one gets Dates. A collection absent here has no
|
|
409
|
+
* parser to run; its records pass through.
|
|
410
|
+
* An entry the reader serves from the build's own parsed collections (see
|
|
411
|
+
* {@link rememberBuiltRecord}) is not parsed again: it already is what the
|
|
412
|
+
* build made of it.
|
|
413
|
+
*/
|
|
414
|
+
parsers: Readonly<Record<string, EntryParser<Record<string, unknown>>>>;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* The build's parsed record behind each entry a collection-backed ContentAPI
|
|
419
|
+
* hands out. A preview reader serves unchanged entries from that API, and
|
|
420
|
+
* the reader source uses the record the build already made instead of
|
|
421
|
+
* reshaping and parsing it again.
|
|
422
|
+
*/
|
|
423
|
+
const builtRecords = new WeakMap<LocalizedEntry, Record<string, unknown>>();
|
|
424
|
+
|
|
425
|
+
/** Mark `entry` as projected from the build's parsed collection record `record`. */
|
|
426
|
+
export function rememberBuiltRecord(entry: LocalizedEntry, record: Record<string, unknown>): void {
|
|
427
|
+
builtRecords.set(entry, record);
|
|
428
|
+
}
|
|
429
|
+
|
|
398
430
|
/**
|
|
399
431
|
* Reader-backed {@link PageContentSource} over a {@link ContentAPI}, the one a
|
|
400
432
|
* caller installs on `Astro.locals.contentApi`. It projects the reader's
|
|
401
433
|
* manifest listing + per-locale content into the SAME record shape the
|
|
402
|
-
* collection-backed source (and the Astro loader) produce,
|
|
403
|
-
*
|
|
404
|
-
*
|
|
434
|
+
* collection-backed source (and the Astro loader) produce, then parses each
|
|
435
|
+
* record with its collection's entry parser as the build does, so the render
|
|
436
|
+
* core is oblivious to which backend served it: the page shows whatever that
|
|
437
|
+
* reader returns, with the values the published page would get.
|
|
405
438
|
*
|
|
406
439
|
* The synthetic `__conloca_fragments` collection is not a real ContentAPI
|
|
407
440
|
* collection (the loader flattens every fragment collection into it), so it maps
|
|
408
441
|
* to a `kind: 'fragment'` query; `type: 'mdx'` PAGES are skipped exactly as the
|
|
409
442
|
* loader skips them (they belong to an external renderer).
|
|
410
443
|
*/
|
|
411
|
-
export function createReaderContentSource(api: ContentAPI,
|
|
444
|
+
export function createReaderContentSource(api: ContentAPI, options: ReaderContentSourceOptions): PageContentSource {
|
|
445
|
+
const { renderLocale, parsers } = options;
|
|
412
446
|
const filtersFor = (collection: string) =>
|
|
413
447
|
collection === ALL_FRAGMENTS_COLLECTION ? ({ kind: 'fragment' } as const) : { collection };
|
|
414
448
|
|
|
415
|
-
const
|
|
449
|
+
const parseRecord = (collection: string, record: Record<string, unknown>) => {
|
|
450
|
+
const parse = parsers[collection];
|
|
451
|
+
if (parse === undefined) return record;
|
|
452
|
+
const parsed = parse(record);
|
|
453
|
+
// The same error the loader fails the build with for this entry.
|
|
454
|
+
if (!parsed.success) throw new Error(describeEntryIssues(parsed.issues, { collection, id: String(record.id) }));
|
|
455
|
+
// The loader stores this same parse output as the entry's `data` record,
|
|
456
|
+
// which is what the collection source hands out.
|
|
457
|
+
return parsed.data;
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
const shapeEntry = async (
|
|
461
|
+
collection: string,
|
|
462
|
+
manifest: ContentManifest,
|
|
463
|
+
locale: string,
|
|
464
|
+
): Promise<Record<string, unknown> | null> => {
|
|
416
465
|
const localeVersion = manifest.locales[locale];
|
|
417
466
|
if (!localeVersion) return null;
|
|
418
467
|
const localized = await api.getLocalized(manifest.id, locale);
|
|
468
|
+
const built = localized ? builtRecords.get(localized) : undefined;
|
|
469
|
+
if (built) return built;
|
|
419
470
|
const content = localized?.localized.content;
|
|
420
471
|
const record: Record<string, unknown> = {
|
|
421
472
|
id: manifest.id,
|
|
@@ -431,7 +482,7 @@ export function createReaderContentSource(api: ContentAPI, renderLocale?: string
|
|
|
431
482
|
};
|
|
432
483
|
if (content?.mdx !== undefined) record.mdx = content.mdx;
|
|
433
484
|
if (content?.puckData !== undefined) record.puckData = content.puckData;
|
|
434
|
-
return record;
|
|
485
|
+
return parseRecord(collection, record);
|
|
435
486
|
};
|
|
436
487
|
|
|
437
488
|
return {
|
|
@@ -441,12 +492,9 @@ export function createReaderContentSource(api: ContentAPI, renderLocale?: string
|
|
|
441
492
|
// Mirror the loader's skip: `type: 'mdx'` pages are owned by an
|
|
442
493
|
// external renderer, not this puck-page handler.
|
|
443
494
|
if (manifest.kind === 'page' && manifest.type === 'mdx') continue;
|
|
444
|
-
// Every consumer filters records to one locale, and each shaped
|
|
445
|
-
// locale is one getLocalized read, so with a render locale known,
|
|
446
|
-
// shaping the others is wasted work.
|
|
447
495
|
for (const locale of Object.keys(manifest.locales)) {
|
|
448
496
|
if (renderLocale !== undefined && locale !== renderLocale) continue;
|
|
449
|
-
const record = await shapeEntry(manifest, locale);
|
|
497
|
+
const record = await shapeEntry(collection, manifest, locale);
|
|
450
498
|
if (record) records.push(record);
|
|
451
499
|
}
|
|
452
500
|
}
|
package/src/index.ts
CHANGED
|
@@ -25,11 +25,15 @@ export {
|
|
|
25
25
|
// and is wired by the schemasPath option (see ConlocaCMSOptions).
|
|
26
26
|
export {
|
|
27
27
|
type CoreFieldsMode,
|
|
28
|
+
type DataSchemas,
|
|
29
|
+
defineHostSchema,
|
|
28
30
|
definePageSchema,
|
|
29
31
|
type FieldHint,
|
|
30
32
|
type FieldHintCommon,
|
|
31
33
|
type FieldHints,
|
|
32
34
|
type FieldHintVariant,
|
|
35
|
+
type HostSchema,
|
|
36
|
+
type HostSchemaType,
|
|
33
37
|
type PageSchemaDescriptor,
|
|
34
38
|
type PageSchemaEntry,
|
|
35
39
|
type PageSchemaGroup,
|
|
@@ -42,13 +46,8 @@ export {
|
|
|
42
46
|
type PageSettingName,
|
|
43
47
|
pageSettingAttributes,
|
|
44
48
|
} from '@conloca/cms-spa/page-setting-attributes';
|
|
45
|
-
//
|
|
46
|
-
export {
|
|
47
|
-
type FragmentMeta,
|
|
48
|
-
fragmentMetaSchema,
|
|
49
|
-
type PageMeta,
|
|
50
|
-
pageMetaSchema,
|
|
51
|
-
} from '@conloca/content-api/schemas';
|
|
49
|
+
// Content metadata types; their generated validators live on `@conloca/content-api/schemas`.
|
|
50
|
+
export type { DataMeta, FragmentMeta, PageMeta } from '@conloca/content-api/schemas';
|
|
52
51
|
// Read-only ContentAPI over the build's content collections.
|
|
53
52
|
export {
|
|
54
53
|
type CollectionBackedContentAPIOptions,
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The entry parsers a draft preview runs, built from the same inputs and the
|
|
3
|
+
* same builders conlocaPages, conlocaData and conlocaFragments hand their
|
|
4
|
+
* loaders, so a preview record gets the values the build stores. Free of
|
|
5
|
+
* Astro's content layer and of the loader's filesystem reader: a preview
|
|
6
|
+
* builds these in a server runtime, where the site's content config itself
|
|
7
|
+
* cannot be evaluated.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { DataSchemas, PageSchemas } from '@conloca/cms-spa/page-schema-define';
|
|
11
|
+
import { parseLooseDataMeta } from '@conloca/content-api/schemas';
|
|
12
|
+
import { ALL_FRAGMENTS_COLLECTION } from '../handlers/collection-names.js';
|
|
13
|
+
import type { ResolvedRoutingConfig } from '../types.js';
|
|
14
|
+
import {
|
|
15
|
+
createDataEntryParser,
|
|
16
|
+
createPageEntryParser,
|
|
17
|
+
type EntryParser,
|
|
18
|
+
parseFragmentEntry,
|
|
19
|
+
} from './entry-validation.js';
|
|
20
|
+
|
|
21
|
+
/** What the site's `contentSchemasPath` module exports: the inputs its content config hands the factories. */
|
|
22
|
+
export interface ContentSchemas {
|
|
23
|
+
pageSchemas?: PageSchemas;
|
|
24
|
+
dataSchemas?: DataSchemas;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The entry parser of each collection a page render reads — its routes' page
|
|
29
|
+
* collections, their bound data collections and the fragments aggregate. A
|
|
30
|
+
* site without `contentSchemasPath` gets the parsers those factories build
|
|
31
|
+
* with no host input: Conloca's own fields are parsed (publish dates become
|
|
32
|
+
* Dates), host page fields are not validated and data payloads pass as they
|
|
33
|
+
* are.
|
|
34
|
+
*/
|
|
35
|
+
export function previewEntryParsers(
|
|
36
|
+
routing: ResolvedRoutingConfig,
|
|
37
|
+
{ pageSchemas, dataSchemas }: ContentSchemas,
|
|
38
|
+
): Record<string, EntryParser<Record<string, unknown>>> {
|
|
39
|
+
const parsers: Record<string, EntryParser<Record<string, unknown>>> = {
|
|
40
|
+
[ALL_FRAGMENTS_COLLECTION]: parseFragmentEntry,
|
|
41
|
+
};
|
|
42
|
+
const parsePage = createPageEntryParser(pageSchemas);
|
|
43
|
+
for (const route of Object.values(routing.routes)) {
|
|
44
|
+
parsers[route.collection] = parsePage;
|
|
45
|
+
for (const name of route.dataBindings.collections ?? []) {
|
|
46
|
+
const payload = dataSchemas?.[name];
|
|
47
|
+
parsers[name] = payload ? createDataEntryParser(payload) : parseLooseDataMeta;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return parsers;
|
|
51
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { SchemaIssue } from '@conloca/content-api/schemas';
|
|
2
|
+
|
|
3
|
+
/** Renders a failed parse as the build error the loader throws. */
|
|
4
|
+
export function describeEntryIssues(
|
|
5
|
+
issues: readonly SchemaIssue[],
|
|
6
|
+
where: { collection: string; id: string; filePath?: string },
|
|
7
|
+
): string {
|
|
8
|
+
const lines = issues.map(
|
|
9
|
+
(issue) => ` - ${issue.path}: expected ${issue.expected}, received ${describeValue(issue.value)}`,
|
|
10
|
+
);
|
|
11
|
+
const file = where.filePath ? ` (${where.filePath})` : '';
|
|
12
|
+
return `[conloca] ${where.collection} entry "${where.id}"${file} does not match its schema:\n${lines.join('\n')}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function describeValue(value: unknown): string {
|
|
16
|
+
if (value === undefined) return 'undefined';
|
|
17
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
|
|
18
|
+
try {
|
|
19
|
+
return JSON.stringify(value) ?? String(value);
|
|
20
|
+
} catch {
|
|
21
|
+
return String(value);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type HostSchema,
|
|
3
|
+
type HostSchemaMetadata,
|
|
4
|
+
type PageSchemas,
|
|
5
|
+
resolveHostJsonSchema,
|
|
6
|
+
rootObjectOf,
|
|
7
|
+
toPageSchemaDescriptor,
|
|
8
|
+
} from '@conloca/cms-spa/page-schema-define';
|
|
9
|
+
import type { ContentMeta } from '@conloca/content-api';
|
|
10
|
+
import {
|
|
11
|
+
type DataMeta,
|
|
12
|
+
type LooseFragmentMeta,
|
|
13
|
+
type LoosePageMeta,
|
|
14
|
+
PAGE_META_KEYS,
|
|
15
|
+
type PageMeta,
|
|
16
|
+
parseLooseDataMeta,
|
|
17
|
+
parseLooseFragmentMeta,
|
|
18
|
+
parseLoosePageMeta,
|
|
19
|
+
type SchemaIssue,
|
|
20
|
+
type SchemaParseResult,
|
|
21
|
+
} from '@conloca/content-api/schemas';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Validation of Conloca collection entries, at build time and in a draft preview.
|
|
25
|
+
*
|
|
26
|
+
* Astro's `defineCollection({ schema })` only takes a Zod schema, and a schema
|
|
27
|
+
* is optional: without one, `parseData` hands the entry through unchanged
|
|
28
|
+
* (astro/dist/content/utils.js `getEntryData`). So the factories declare their
|
|
29
|
+
* collections schema-less and the loader validates every entry with the parsers
|
|
30
|
+
* below BEFORE `store.set` — the generated Typia validators from
|
|
31
|
+
* `@conloca/content-api/schemas` for Conloca's own fields, and the host's
|
|
32
|
+
* generated validators for its `pageSchemas` / `dataSchemas`. A draft preview
|
|
33
|
+
* parses its records with the same parsers, in a server runtime, so this
|
|
34
|
+
* module stays free of the loader's filesystem reader.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Entry fields the content loader owns, written into every entry's data in
|
|
39
|
+
* its load().
|
|
40
|
+
*
|
|
41
|
+
* None of them belong to `PageMeta`, so page validation keeps them only as
|
|
42
|
+
* undeclared top-level fields. A host page-meta field of the same name would
|
|
43
|
+
* replace the loader's value — a host `puckData` shape would empty the page
|
|
44
|
+
* tree of every page in the built site. `hostFieldsFromPageSchemas` refuses
|
|
45
|
+
* those names with an error.
|
|
46
|
+
*
|
|
47
|
+
* Adding a field to the record the loader builds also means reserving it here.
|
|
48
|
+
*/
|
|
49
|
+
export const LOADER_RESERVED_FIELDS = ['created', 'modified', 'name', 'data', 'mdx', 'puckData'] as const;
|
|
50
|
+
|
|
51
|
+
/** Validates (and normalizes) one entry's data as the loader built it. */
|
|
52
|
+
export type EntryParser<T> = (data: Record<string, unknown>) => SchemaParseResult<T>;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A page collection entry as the loader delivers it: the validated `PageMeta`
|
|
56
|
+
* fields, the loader-written record fields (`created`, `modified`, `name`,
|
|
57
|
+
* `puckData`), and the host's meta fields through `ContentMeta`/`HostPageMeta`.
|
|
58
|
+
*/
|
|
59
|
+
export type ConlocaPageEntry = ContentMeta &
|
|
60
|
+
PageMeta & {
|
|
61
|
+
created?: string | Date;
|
|
62
|
+
modified?: string | Date;
|
|
63
|
+
name?: string;
|
|
64
|
+
puckData?: unknown;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** A data collection entry: the validated `DataMeta` fields with `data` typed by the collection's host schema. */
|
|
68
|
+
export interface ConlocaDataEntry<T> extends Omit<DataMeta, 'data'> {
|
|
69
|
+
data?: T;
|
|
70
|
+
[key: string]: unknown;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A fragment collection entry: validated `FragmentMeta` fields plus the loader-written `mdx`. */
|
|
74
|
+
export type ConlocaFragmentEntry = LooseFragmentMeta & { mdx?: string };
|
|
75
|
+
|
|
76
|
+
const CORE_FIELD_NAMES = new Set<string>(PAGE_META_KEYS);
|
|
77
|
+
// `Object.hasOwn` is ES2022, past this package's `lib`.
|
|
78
|
+
const hasOwn = (record: object, key: string) => Object.getOwnPropertyDescriptor(record, key) !== undefined;
|
|
79
|
+
const RESERVED_FIELD_NAMES = new Set<string>(LOADER_RESERVED_FIELDS);
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The generated JSON Schema of one field, `$ref`s inlined, as a comparable
|
|
83
|
+
* string. The `title`/`description` annotations are dropped — help text may
|
|
84
|
+
* differ between descriptors — but never a field that happens to be named
|
|
85
|
+
* `title` or `description` inside a `properties` map.
|
|
86
|
+
*/
|
|
87
|
+
function canonicalFieldSchema(metadata: HostSchemaMetadata, node: unknown, depth = 0, isNameMap = false): unknown {
|
|
88
|
+
if (depth > 32 || typeof node !== 'object' || node === null) return node;
|
|
89
|
+
if (Array.isArray(node)) return node.map((item) => canonicalFieldSchema(metadata, item, depth + 1));
|
|
90
|
+
const resolved: object | null =
|
|
91
|
+
!isNameMap && '$ref' in node && typeof node.$ref === 'string'
|
|
92
|
+
? resolveHostJsonSchema(metadata, { $ref: node.$ref })
|
|
93
|
+
: node;
|
|
94
|
+
if (resolved === null) return null;
|
|
95
|
+
return Object.fromEntries(
|
|
96
|
+
Object.entries(resolved)
|
|
97
|
+
.filter(([key]) => isNameMap || (key !== 'description' && key !== 'title'))
|
|
98
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
99
|
+
.map(([key, value]) => [
|
|
100
|
+
key,
|
|
101
|
+
canonicalFieldSchema(
|
|
102
|
+
metadata,
|
|
103
|
+
value,
|
|
104
|
+
depth + 1,
|
|
105
|
+
// These keywords map field names to schemas; their keys are names, not annotations.
|
|
106
|
+
!isNameMap && (key === 'properties' || key === 'patternProperties'),
|
|
107
|
+
),
|
|
108
|
+
]),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** One page-schema descriptor's contribution to page validation. */
|
|
113
|
+
export interface HostFieldSet {
|
|
114
|
+
/** The `pageSchemas` key the fields came from, for error messages. */
|
|
115
|
+
key: string;
|
|
116
|
+
schema: HostSchema;
|
|
117
|
+
/** Top-level fields this descriptor validates on every page (core names owned by 'minimal'/'none' removed). */
|
|
118
|
+
fields: readonly string[];
|
|
119
|
+
/**
|
|
120
|
+
* Core field names a 'minimal'/'none' descriptor declares for its form. Conloca
|
|
121
|
+
* validates them; the host validator only sees the page's core values so that a
|
|
122
|
+
* required declaration (Starlight's `title`) does not fail the whole validation
|
|
123
|
+
* and skip the pruning of the host's own fields.
|
|
124
|
+
*/
|
|
125
|
+
coreOwned: readonly string[];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function assertHostFieldIsSafe(name: string): void {
|
|
129
|
+
if (CORE_FIELD_NAMES.has(name)) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`[conloca] pageSchemas cannot redeclare Conloca field "${name}". ` +
|
|
132
|
+
'Title, pathname, locale, and the other core fields come from the CMS — put constraints on them in the editor schema, not here.',
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
if (RESERVED_FIELD_NAMES.has(name)) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
`[conloca] pageSchemas cannot declare "${name}". ` +
|
|
138
|
+
'That field is owned by the content loader; a host schema of the same name would replace page content on every page.',
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Fold every page-schema descriptor into the host fields page validation checks.
|
|
145
|
+
*
|
|
146
|
+
* Every page is checked against every descriptor's fields — Astro builds the
|
|
147
|
+
* whole `pages` pile while the editor scopes a descriptor to a prefix — so a
|
|
148
|
+
* field name may only be declared twice with the same generated schema:
|
|
149
|
+
* otherwise one prefix's pages would be validated against the other's type,
|
|
150
|
+
* failing with an error that names neither descriptor.
|
|
151
|
+
*/
|
|
152
|
+
export function hostFieldsFromPageSchemas(pageSchemas: PageSchemas): HostFieldSet[] {
|
|
153
|
+
const owners = new Map<string, { key: string; canonical: string }>();
|
|
154
|
+
return Object.entries(pageSchemas).map(([key, entry]) => {
|
|
155
|
+
const descriptor = toPageSchemaDescriptor(entry);
|
|
156
|
+
// 'minimal'/'none' descriptors declare title for the form; those names stay Conloca's.
|
|
157
|
+
const mode = descriptor.coreFields?.mode;
|
|
158
|
+
const ownsCore = mode === 'minimal' || mode === 'none';
|
|
159
|
+
const { metadata } = descriptor.schema;
|
|
160
|
+
const root = rootObjectOf(metadata);
|
|
161
|
+
if (root === null) {
|
|
162
|
+
// Without an object root there are no fields to check, and every page
|
|
163
|
+
// would pass unvalidated instead of failing the build.
|
|
164
|
+
throw new Error(
|
|
165
|
+
`[conloca] pageSchemas "${key}" metadata is not generated for an object type. ` +
|
|
166
|
+
'Declare it with defineHostSchema<T>({ validate, metadata: typia.json.schema<T>() }) for an object type T.',
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
const fields: string[] = [];
|
|
170
|
+
const coreOwned: string[] = [];
|
|
171
|
+
for (const [name, node] of Object.entries(root.properties ?? {})) {
|
|
172
|
+
if (ownsCore && CORE_FIELD_NAMES.has(name)) {
|
|
173
|
+
coreOwned.push(name);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
assertHostFieldIsSafe(name);
|
|
177
|
+
const canonical = JSON.stringify(canonicalFieldSchema(metadata, node));
|
|
178
|
+
const owner = owners.get(name);
|
|
179
|
+
if (owner !== undefined && owner.canonical !== canonical) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
`[conloca] pageSchemas "${owner.key}" and "${key}" both declare field "${name}" with different schemas. ` +
|
|
182
|
+
'Every page is validated against every declared field — declare the field with one type in both ' +
|
|
183
|
+
'schemas, or rename one of the fields.',
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (owner === undefined) owners.set(name, { key, canonical });
|
|
187
|
+
fields.push(name);
|
|
188
|
+
}
|
|
189
|
+
return { key, schema: descriptor.schema, fields, coreOwned };
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The top-level key a Typia error path (`$input.name`, `$input["a-b"]`, …) starts with. */
|
|
194
|
+
export function topLevelKeyOf(path: string): string | undefined {
|
|
195
|
+
const rest = path.startsWith('$input') ? path.slice('$input'.length) : undefined;
|
|
196
|
+
if (rest === undefined) return undefined;
|
|
197
|
+
const dotted = /^\.([A-Za-z_$][\w$]*)/.exec(rest);
|
|
198
|
+
if (dotted) return dotted[1];
|
|
199
|
+
const bracketed = /^\[("(?:[^"\\]|\\.)*")\]/.exec(rest);
|
|
200
|
+
return bracketed?.[1] === undefined ? undefined : (JSON.parse(bracketed[1]) as string);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Re-roots a generated validator's error under `prefix` (`$input` → `$input.data`). */
|
|
204
|
+
function toIssue(error: { path: string; expected: string; value: unknown }, prefix = ''): SchemaIssue {
|
|
205
|
+
return {
|
|
206
|
+
path: prefix ? `$input${prefix}${error.path.slice('$input'.length)}` : error.path,
|
|
207
|
+
expected: error.expected,
|
|
208
|
+
value: error.value,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Validate one descriptor's fields on a page. The fields are copied out first, so
|
|
214
|
+
* a pruning validator never mutates the loader's data, and a field the page
|
|
215
|
+
* does not carry is not an error: host fields are optional collection-wide.
|
|
216
|
+
* Requiredness is shallow, as `.partial()` was — a nested required field still
|
|
217
|
+
* has to be present when its parent is.
|
|
218
|
+
*
|
|
219
|
+
* A generated validator prunes only on success, so the core fields a
|
|
220
|
+
* 'minimal'/'none' descriptor redeclares are passed in with the page's own
|
|
221
|
+
* values: otherwise its required `title` would fail every page and leave the
|
|
222
|
+
* host's nested fields unpruned. Errors on them are Conloca's to report, not the
|
|
223
|
+
* host's, and they never reach the returned values.
|
|
224
|
+
*
|
|
225
|
+
* When the only failures are on ignored fields — those core fields, or a host
|
|
226
|
+
* field the page does not carry that `T` declares required — the validator's
|
|
227
|
+
* prune does not run, so nested undeclared keys are kept, as with a non-pruning
|
|
228
|
+
* `createValidate`, where `.partial()` would still have stripped them. A host
|
|
229
|
+
* schema carries no marker telling a pruning validator from a plain one, so
|
|
230
|
+
* there is nothing to re-run; a host that wants every page pruned declares its
|
|
231
|
+
* page fields optional (`?`), which they are collection-wide anyway.
|
|
232
|
+
*/
|
|
233
|
+
function validateHostFields(
|
|
234
|
+
set: HostFieldSet,
|
|
235
|
+
entry: Record<string, unknown>,
|
|
236
|
+
): { issues: SchemaIssue[]; values: Record<string, unknown> } {
|
|
237
|
+
const picked: Record<string, unknown> = {};
|
|
238
|
+
for (const name of set.fields) {
|
|
239
|
+
if (hasOwn(entry, name)) picked[name] = structuredClone(entry[name]);
|
|
240
|
+
}
|
|
241
|
+
const input: Record<string, unknown> = { ...picked };
|
|
242
|
+
for (const name of set.coreOwned) {
|
|
243
|
+
if (hasOwn(entry, name)) input[name] = structuredClone(entry[name]);
|
|
244
|
+
}
|
|
245
|
+
// Pruning rewrites `input`'s nested values in place, which `picked` shares.
|
|
246
|
+
const result = set.schema.validate(input);
|
|
247
|
+
if (result.success) return { issues: [], values: picked };
|
|
248
|
+
const issues = result.errors
|
|
249
|
+
.filter((error) => {
|
|
250
|
+
const key = topLevelKeyOf(error.path);
|
|
251
|
+
return key === undefined || hasOwn(picked, key);
|
|
252
|
+
})
|
|
253
|
+
.map((error) => toIssue(error));
|
|
254
|
+
return { issues, values: picked };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The parser a page collection validates entries with: Conloca's page fields
|
|
259
|
+
* (dates coerced, unknown keys kept) plus every host field from `pageSchemas`.
|
|
260
|
+
*/
|
|
261
|
+
export function createPageEntryParser(pageSchemas?: PageSchemas): EntryParser<ConlocaPageEntry> {
|
|
262
|
+
const hostFieldSets = pageSchemas ? hostFieldsFromPageSchemas(pageSchemas) : [];
|
|
263
|
+
return (data) => {
|
|
264
|
+
const core = parseLoosePageMeta(data);
|
|
265
|
+
const issues: SchemaIssue[] = core.success ? [] : [...core.issues];
|
|
266
|
+
let entry: LoosePageMeta | Record<string, unknown> = core.success ? core.data : data;
|
|
267
|
+
for (const set of hostFieldSets) {
|
|
268
|
+
const host = validateHostFields(set, entry);
|
|
269
|
+
issues.push(...host.issues);
|
|
270
|
+
if (host.issues.length === 0 && Object.keys(host.values).length > 0) entry = { ...entry, ...host.values };
|
|
271
|
+
}
|
|
272
|
+
if (!core.success || issues.length > 0) return { success: false, issues };
|
|
273
|
+
// The one declared seam: the runtime value is core fields validated by
|
|
274
|
+
// content-api's generated validator plus host fields validated by the host's,
|
|
275
|
+
// but the host's declared field TYPES reach TypeScript only through the
|
|
276
|
+
// `HostPageMeta` augmentation a site writes next to its pageSchemas. A host
|
|
277
|
+
// declaring `HostPageMeta` promises it matches them, as listings always have.
|
|
278
|
+
return { success: true, data: entry as ConlocaPageEntry };
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The parser a fragment collection validates entries with. */
|
|
283
|
+
export const parseFragmentEntry: EntryParser<ConlocaFragmentEntry> = parseLooseFragmentMeta;
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The parser a `conlocaData` collection validates entries with: Conloca's data
|
|
287
|
+
* fields, then the collection's payload under `data` against its host schema.
|
|
288
|
+
* `data` stays optional — an entry saved before any payload exists is not an
|
|
289
|
+
* error. The payload is validated as given: requiredness preserved.
|
|
290
|
+
*/
|
|
291
|
+
export function createDataEntryParser<T extends object>(payload: HostSchema<T>): EntryParser<ConlocaDataEntry<T>> {
|
|
292
|
+
return (data) => {
|
|
293
|
+
const base = parseLooseDataMeta(data);
|
|
294
|
+
if (!base.success) return base;
|
|
295
|
+
if (base.data.data === undefined) {
|
|
296
|
+
const { data: _absent, ...rest } = base.data;
|
|
297
|
+
return { success: true, data: rest };
|
|
298
|
+
}
|
|
299
|
+
const result = payload.validate(structuredClone(base.data.data));
|
|
300
|
+
if (!result.success) {
|
|
301
|
+
return { success: false, issues: result.errors.map((error) => toIssue(error, '.data')) };
|
|
302
|
+
}
|
|
303
|
+
return { success: true, data: { ...base.data, data: result.data } };
|
|
304
|
+
};
|
|
305
|
+
}
|
|
@@ -56,3 +56,23 @@ export function generatePuckConfigModule(puckConfigPath: string): string {
|
|
|
56
56
|
|
|
57
57
|
return `export { default } from '${absolutePath}';`;
|
|
58
58
|
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Generate the virtual:conloca-content-schemas module: the site's
|
|
62
|
+
* `contentSchemasPath` module — the `pageSchemas` / `dataSchemas` its content
|
|
63
|
+
* config hands the collection factories — for a draft preview to build the
|
|
64
|
+
* same collection schemas from. Not the content config itself: that imports
|
|
65
|
+
* build-time loaders, which cannot be evaluated in a server runtime.
|
|
66
|
+
*
|
|
67
|
+
* Imported lazily, on the first call, so only a preview render evaluates it.
|
|
68
|
+
*
|
|
69
|
+
* @param contentSchemasPath - Absolute path of the module, or undefined when the site names none
|
|
70
|
+
* @returns JavaScript module code as a string
|
|
71
|
+
*/
|
|
72
|
+
export function generateContentSchemasModule(contentSchemasPath: string | undefined): string {
|
|
73
|
+
if (contentSchemasPath === undefined) {
|
|
74
|
+
return 'export function loadContentSchemas() { return Promise.resolve({}); }';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return `export function loadContentSchemas() { return import(${JSON.stringify(contentSchemasPath)}); }`;
|
|
78
|
+
}
|