@conloca/astro-cms 0.2.6 → 0.3.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.
Files changed (97) hide show
  1. package/README.md +169 -22
  2. package/dist/internal/PageRoot.astro +10 -0
  3. package/dist/internal/page-handler.astro +46 -13
  4. package/dist/internal/preview-page-handler.astro +46 -13
  5. package/dist/ts/.build-inputs.json +20 -15
  6. package/dist/ts/src/build/check-fragment-components.d.ts +18 -0
  7. package/dist/ts/src/build/check-fragment-components.d.ts.map +1 -0
  8. package/dist/ts/src/build/check-fragment-components.js +70 -0
  9. package/dist/ts/src/build/check-fragment-components.js.map +1 -0
  10. package/dist/ts/src/build/fragment-manifest.d.ts +35 -0
  11. package/dist/ts/src/build/fragment-manifest.d.ts.map +1 -0
  12. package/dist/ts/src/build/fragment-manifest.js +138 -0
  13. package/dist/ts/src/build/fragment-manifest.js.map +1 -0
  14. package/dist/ts/src/build/fragment-render-load.d.ts +17 -0
  15. package/dist/ts/src/build/fragment-render-load.d.ts.map +1 -0
  16. package/dist/ts/src/build/fragment-render-load.js +51 -0
  17. package/dist/ts/src/build/fragment-render-load.js.map +1 -0
  18. package/dist/ts/src/cms-handler.d.ts +6 -0
  19. package/dist/ts/src/cms-handler.d.ts.map +1 -1
  20. package/dist/ts/src/cms-handler.js +3 -5
  21. package/dist/ts/src/cms-handler.js.map +1 -1
  22. package/dist/ts/src/components/FragmentIsland.d.ts +17 -0
  23. package/dist/ts/src/components/FragmentIsland.d.ts.map +1 -0
  24. package/dist/ts/src/components/FragmentIsland.js +78 -0
  25. package/dist/ts/src/components/FragmentIsland.js.map +1 -0
  26. package/dist/ts/src/components/IslandSlot.d.ts +14 -0
  27. package/dist/ts/src/components/IslandSlot.d.ts.map +1 -0
  28. package/dist/ts/src/components/IslandSlot.js +19 -0
  29. package/dist/ts/src/components/IslandSlot.js.map +1 -0
  30. package/dist/ts/src/components/RenderWithFragments.d.ts +3 -1
  31. package/dist/ts/src/components/RenderWithFragments.d.ts.map +1 -1
  32. package/dist/ts/src/components/RenderWithFragments.js +1 -1
  33. package/dist/ts/src/components/RenderWithFragments.js.map +1 -1
  34. package/dist/ts/src/discovery/merge-registry.js +6 -2
  35. package/dist/ts/src/discovery/merge-registry.js.map +1 -1
  36. package/dist/ts/src/editor-descriptors.d.ts +4 -0
  37. package/dist/ts/src/editor-descriptors.d.ts.map +1 -1
  38. package/dist/ts/src/editor-descriptors.js +11 -0
  39. package/dist/ts/src/editor-descriptors.js.map +1 -1
  40. package/dist/ts/src/handlers/collection-content-api.d.ts +3 -1
  41. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
  42. package/dist/ts/src/handlers/collection-content-api.js +13 -2
  43. package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
  44. package/dist/ts/src/handlers/page-render-core.d.ts +36 -7
  45. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
  46. package/dist/ts/src/handlers/page-render-core.js +97 -18
  47. package/dist/ts/src/handlers/page-render-core.js.map +1 -1
  48. package/dist/ts/src/lib/hydration-scanner.d.ts +21 -0
  49. package/dist/ts/src/lib/hydration-scanner.d.ts.map +1 -1
  50. package/dist/ts/src/lib/hydration-scanner.js +50 -0
  51. package/dist/ts/src/lib/hydration-scanner.js.map +1 -1
  52. package/dist/ts/src/lib/hydration-script.d.ts +13 -5
  53. package/dist/ts/src/lib/hydration-script.d.ts.map +1 -1
  54. package/dist/ts/src/lib/hydration-script.js +74 -36
  55. package/dist/ts/src/lib/hydration-script.js.map +1 -1
  56. package/dist/ts/src/lib/routing-config.d.ts +1 -1
  57. package/dist/ts/src/lib/routing-config.d.ts.map +1 -1
  58. package/dist/ts/src/lib/routing-config.js +5 -2
  59. package/dist/ts/src/lib/routing-config.js.map +1 -1
  60. package/dist/ts/src/lib/unknown-components.d.ts +1 -2
  61. package/dist/ts/src/lib/unknown-components.d.ts.map +1 -1
  62. package/dist/ts/src/lib/virtual-module-generators.d.ts +37 -0
  63. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
  64. package/dist/ts/src/lib/virtual-module-generators.js +86 -0
  65. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
  66. package/dist/ts/src/plugin-spa.d.ts +24 -0
  67. package/dist/ts/src/plugin-spa.d.ts.map +1 -1
  68. package/dist/ts/src/plugin-spa.js +136 -69
  69. package/dist/ts/src/plugin-spa.js.map +1 -1
  70. package/dist/ts/src/puck-manifest/types.d.ts +4 -0
  71. package/dist/ts/src/puck-manifest/types.d.ts.map +1 -1
  72. package/dist/ts/src/types.d.ts +14 -2
  73. package/dist/ts/src/types.d.ts.map +1 -1
  74. package/dist/virtual-modules.d.ts +26 -0
  75. package/package.json +10 -4
  76. package/src/build/check-fragment-components.ts +82 -0
  77. package/src/build/fragment-manifest.ts +163 -0
  78. package/src/build/fragment-render-load.ts +64 -0
  79. package/src/cms-handler.ts +3 -6
  80. package/src/components/FragmentIsland.tsx +97 -0
  81. package/src/components/IslandSlot.tsx +28 -0
  82. package/src/components/PageRoot.astro +10 -0
  83. package/src/components/RenderWithFragments.tsx +4 -1
  84. package/src/discovery/merge-registry.ts +8 -3
  85. package/src/editor-descriptors.ts +17 -0
  86. package/src/handlers/collection-content-api.ts +15 -2
  87. package/src/handlers/page-handler.astro +46 -13
  88. package/src/handlers/page-render-core.ts +132 -21
  89. package/src/lib/hydration-scanner.ts +65 -0
  90. package/src/lib/hydration-script.ts +83 -40
  91. package/src/lib/routing-config.ts +7 -3
  92. package/src/lib/unknown-components.ts +1 -1
  93. package/src/lib/virtual-module-generators.ts +106 -0
  94. package/src/plugin-spa.ts +182 -76
  95. package/src/puck-manifest/types.ts +8 -0
  96. package/src/types.ts +15 -1
  97. package/src/virtual-modules.d.ts +26 -0
@@ -71,6 +71,32 @@ declare module 'virtual:conloca-content-schemas' {
71
71
  export function loadContentSchemas(): Promise<{ pageSchemas?: PageSchemas; dataSchemas?: DataSchemas }>;
72
72
  }
73
73
 
74
+ /**
75
+ * Virtual module: virtual:conloca-fragment-components
76
+ *
77
+ * The site's `fragmentComponentsPath` module, imported on the first call only;
78
+ * an empty object when the site names none.
79
+ */
80
+ declare module 'virtual:conloca-fragment-components' {
81
+ export function loadFragmentComponents(): Promise<{ fragmentComponents?: unknown }>;
82
+ /** The resolved absolute path of that module, or `undefined` when the site names none. */
83
+ export const fragmentComponentsPath: string | undefined;
84
+ /** Registry key → loader of each hydrated fragment component the render module imports. */
85
+ export const fragmentIslandLoaders: Readonly<Record<string, () => Promise<object | undefined>>>;
86
+ }
87
+
88
+ /**
89
+ * Virtual module: virtual:conloca-site-render (dev only)
90
+ *
91
+ * The site's fragment vocabulary, its editor frames (route name → frame) and
92
+ * the fragment renderer, handed to cms-spa's `setSiteRender`.
93
+ */
94
+ declare module 'virtual:conloca-site-render' {
95
+ export const fragmentComponents: unknown;
96
+ export const editorFrames: unknown;
97
+ export { evaluateMDXToComponent } from '@conloca/mdx/render';
98
+ }
99
+
74
100
  /**
75
101
  * Virtual module: virtual:conloca-hydration-entry
76
102
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -60,6 +60,11 @@
60
60
  "import": "./dist/ts/src/puck-manifest/index.js",
61
61
  "default": "./dist/ts/src/puck-manifest/index.js"
62
62
  },
63
+ "./fragment-manifest": {
64
+ "types": "./dist/ts/src/build/fragment-manifest.d.ts",
65
+ "import": "./dist/ts/src/build/fragment-manifest.js",
66
+ "default": "./dist/ts/src/build/fragment-manifest.js"
67
+ },
63
68
  "./components": {
64
69
  "types": "./dist/ts/src/components.d.ts",
65
70
  "import": "./dist/ts/src/components.js",
@@ -92,9 +97,9 @@
92
97
  "!**/*.tsbuildinfo"
93
98
  ],
94
99
  "dependencies": {
95
- "@conloca/cms-spa": "0.2.6",
96
- "@conloca/content-api": "0.2.6",
97
- "@conloca/mdx": "0.2.6",
100
+ "@conloca/cms-spa": "0.3.0",
101
+ "@conloca/content-api": "0.3.0",
102
+ "@conloca/mdx": "0.3.0",
98
103
  "@puckeditor/core": "^0.23.0",
99
104
  "@tiptap/core": "^3.31.2",
100
105
  "@tiptap/pm": "^3.31.2",
@@ -152,6 +157,7 @@
152
157
  "cache": true,
153
158
  "inputs": [
154
159
  "{projectRoot}/src/handlers/page-handler.astro",
160
+ "{projectRoot}/src/components/PageRoot.astro",
155
161
  "{projectRoot}/src/internal/acorn-default.mjs",
156
162
  "{projectRoot}/src/virtual-modules.d.ts",
157
163
  "{projectRoot}/copy-assets.ts"
@@ -0,0 +1,82 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import { isContentPublished } from '@conloca/content-api';
4
+ import { FileSystemContentAPI } from '@conloca/content-api/node';
5
+ import { findUnknownFragmentComponents } from '@conloca/mdx/render';
6
+ import type { UserConfig } from 'vite';
7
+ import { islandVocabulary } from '../components/FragmentIsland.js';
8
+ import { fragmentVocabularyOf } from '../handlers/page-render-core.js';
9
+ import { loadFragmentRender } from './fragment-render-load.js';
10
+
11
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
12
+
13
+ /**
14
+ * Problem lines for every fragment the site may serve (live or scheduled, not expired) that fails to parse or uses a
15
+ * component `fragmentComponentsPath` does not declare, and for a `withHydration()` component the build cannot map to
16
+ * a module: that one fails every page with fragments, so the build fails here whatever the output mode. A module that
17
+ * cannot load here only warns and skips the name check, because a module Astro builds may not load outside Astro's own
18
+ * pipeline.
19
+ */
20
+ export async function checkFragmentComponents(input: {
21
+ contentRoot: string;
22
+ root: string;
23
+ vite: UserConfig;
24
+ fragmentComponentsPath: string | undefined;
25
+ logger: { warn(message: string): void };
26
+ }): Promise<string[]> {
27
+ const { root, fragmentComponentsPath } = input;
28
+ const problems: string[] = [];
29
+ let names: ReadonlySet<string> | undefined = new Set();
30
+ if (fragmentComponentsPath) {
31
+ try {
32
+ const module = await loadFragmentRender({ root, vite: input.vite, fragmentComponentsPath });
33
+ let declared: ReadonlySet<string> | undefined;
34
+ try {
35
+ const vocabulary = fragmentVocabularyOf(module.render, fragmentComponentsPath);
36
+ declared = new Set(Object.keys(vocabulary.components));
37
+ // The mapping a published page renders with; it throws for a hydrated component the build cannot map.
38
+ islandVocabulary(vocabulary, new Map(module.islands.map(([key, component]) => [component, key])));
39
+ } catch (error) {
40
+ problems.push(messageOf(error));
41
+ }
42
+ names = declared;
43
+ } catch (error) {
44
+ input.logger.warn(
45
+ `@conloca/astro-cms: ${fragmentComponentsPath} failed to load, so neither fragment component names nor the hydration mapping are checked: ${messageOf(error)}`,
46
+ );
47
+ names = undefined;
48
+ }
49
+ }
50
+ const declaredIn = fragmentComponentsPath ?? 'fragmentComponentsPath (not set)';
51
+
52
+ const api = await FileSystemContentAPI.create({ contentRoot: resolve(root, input.contentRoot) });
53
+ // Only MDX fragments render through the fragment vocabulary; Puck (.vxjson) fragments are not MDX.
54
+ const fragments = [...api.listAllContent()]
55
+ .filter((manifest) => manifest.kind === 'fragment' && manifest.type === 'mdx')
56
+ .flatMap((manifest) =>
57
+ Object.entries(manifest.locales).flatMap(([locale, version]) =>
58
+ // Scheduled fragments go live without a rebuild, so only expired ones are skipped.
59
+ version?.sourcePath && isContentPublished({ unpublishAt: version.unpublishAt })
60
+ ? [{ id: manifest.id, locale, file: resolve(version.sourcePath) }]
61
+ : [],
62
+ ),
63
+ );
64
+ const found = await Promise.all(
65
+ fragments.map(async ({ id, locale, file }) => {
66
+ const text = await readFile(file, 'utf8');
67
+ const fence = /^---\r?\n[\s\S]*?\r?\n---[^\n]*(\n|$)/.exec(text)?.[0] ?? '';
68
+ const offset = fence.split('\n').length - 1;
69
+ const prefix = `${id} (${locale}) ${relative(root, file)}`;
70
+ try {
71
+ const unknown = findUnknownFragmentComponents(text.slice(fence.length), names ?? new Set());
72
+ if (!names) return [];
73
+ return unknown.map(({ name, line }) => `${prefix}:${offset + line}: <${name}> is not in ${declaredIn}`);
74
+ } catch (error) {
75
+ return [`${prefix}: ${messageOf(error)}`];
76
+ }
77
+ }),
78
+ );
79
+ problems.push(...found.flat());
80
+ // oxlint-disable-next-line unicorn/no-array-sort -- the target lib predates toSorted; this sorts a fresh local array.
81
+ return problems.sort();
82
+ }
@@ -0,0 +1,163 @@
1
+ import {
2
+ type MdxComponentDescriptor,
3
+ type MdxJsxComponentDescriptor,
4
+ mergeDiscoveredMdxComponents,
5
+ } from '@conloca/cms-spa/mdx-components-define';
6
+ import {
7
+ type FragmentManifest,
8
+ type FragmentManifestComponent,
9
+ type FragmentManifestProp,
10
+ isRecord,
11
+ } from '@conloca/content-api/component-vocabulary';
12
+ import type { FragmentVocabulary } from '@conloca/mdx/render';
13
+ import type { UserConfig } from 'vite';
14
+ import { strategyOf } from '../components/FragmentIsland.js';
15
+ import { fragmentVocabularyOf } from '../handlers/page-render-core.js';
16
+ import { loadFragmentRender } from './fragment-render-load.js';
17
+
18
+ export { type CheckEntry, loadFragmentRender } from './fragment-render-load.js';
19
+
20
+ /** A built fragment manifest, and a warning for each descriptor prop it left out. */
21
+ export interface FragmentManifestResult {
22
+ manifest: FragmentManifest;
23
+ warnings: string[];
24
+ }
25
+
26
+ // A JSX descriptor by shape; its props are parsed one by one below, since they come from site code.
27
+ const isJsxDescriptor = (value: unknown): value is MdxJsxComponentDescriptor =>
28
+ isRecord(value) && typeof value.name === 'string' && (value.kind === 'flow' || value.kind === 'text');
29
+
30
+ // Any descriptor by its name alone, for the merge; the JSX filter after it reads the rest.
31
+ const isNamedDescriptor = (value: unknown): value is MdxComponentDescriptor =>
32
+ isRecord(value) && typeof value.name === 'string';
33
+
34
+ const optionalString = (value: unknown) => (typeof value === 'string' ? value : undefined);
35
+
36
+ /** A descriptor prop or field as a manifest prop; `undefined` when its shape is not one the manifest describes. */
37
+ function manifestProp(value: unknown): FragmentManifestProp | undefined {
38
+ if (!isRecord(value)) return undefined;
39
+ const common = {
40
+ ...(typeof value.label === 'string' ? { label: value.label } : {}),
41
+ ...(typeof value.help === 'string' ? { help: value.help } : {}),
42
+ ...(value.required === true ? { required: true as const } : {}),
43
+ };
44
+ const fallback = value.defaultValue;
45
+ switch (value.type) {
46
+ case 'string': {
47
+ const options = value.options;
48
+ if (options !== undefined) {
49
+ if (!Array.isArray(options)) return undefined;
50
+ if (!options.every((o) => isRecord(o) && typeof o.value === 'string' && typeof o.label === 'string')) {
51
+ return undefined;
52
+ }
53
+ }
54
+ return {
55
+ type: 'string',
56
+ ...common,
57
+ ...(typeof fallback === 'string' ? { default: fallback } : {}),
58
+ ...(options ? { options: options.map((o) => ({ value: String(o.value), label: String(o.label) })) } : {}),
59
+ };
60
+ }
61
+ case 'number':
62
+ return { type: 'number', ...common, ...(typeof fallback === 'number' ? { default: fallback } : {}) };
63
+ case 'boolean':
64
+ return { type: 'boolean', ...common, ...(typeof fallback === 'boolean' ? { default: fallback } : {}) };
65
+ case 'list': {
66
+ const of = manifestProp(value.of);
67
+ return of ? { type: 'list', ...common, of } : undefined;
68
+ }
69
+ case 'object': {
70
+ if (!isRecord(value.fields)) return undefined;
71
+ const fields: Record<string, FragmentManifestProp> = {};
72
+ for (const [name, field] of Object.entries(value.fields)) {
73
+ const prop = manifestProp(field);
74
+ if (!prop) return undefined;
75
+ fields[name] = prop;
76
+ }
77
+ return { type: 'object', ...common, fields };
78
+ }
79
+ default:
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The manifest of a loaded vocabulary: every component it declares with the descriptor the editor uses for it
86
+ * (host-authored wins over discovered for these names), its hydration and its outline entry, and its element overrides.
87
+ */
88
+ export function fragmentManifestOf(input: {
89
+ vocabulary: FragmentVocabulary;
90
+ mdxComponents: unknown;
91
+ discovered: readonly unknown[];
92
+ }): FragmentManifestResult {
93
+ const { vocabulary } = input;
94
+ const names = Object.keys(vocabulary.components);
95
+ // Merge every descriptor kind first, as the editor does, so a host snippet of a vocabulary name still wins.
96
+ const host = (Array.isArray(input.mdxComponents) ? input.mdxComponents : []).filter(isNamedDescriptor);
97
+ const merged = mergeDiscoveredMdxComponents(host, input.discovered.filter(isNamedDescriptor), new Set(names));
98
+ const descriptors = new Map(merged.filter(isJsxDescriptor).map((d) => [d.name, d]));
99
+ const warnings: string[] = [];
100
+ const components: Record<string, FragmentManifestComponent> = {};
101
+ for (const name of names) {
102
+ const entry: FragmentManifestComponent = {};
103
+ const outline = vocabulary.outline?.[name];
104
+ if (outline) entry.outline = { id: outline.id, text: outline.text };
105
+ const hydrate = strategyOf(vocabulary.components[name]);
106
+ if (hydrate) entry.hydrate = hydrate;
107
+ const descriptor = descriptors.get(name);
108
+ if (descriptor) {
109
+ entry.kind = descriptor.kind;
110
+ const label = optionalString(descriptor.insert?.label);
111
+ if (label !== undefined) entry.label = label;
112
+ const description = optionalString(descriptor.insert?.description);
113
+ if (description !== undefined) entry.description = description;
114
+ if (descriptor.hasChildren === true) entry.children = true;
115
+ const props: Record<string, FragmentManifestProp> = {};
116
+ for (const prop of Array.isArray(descriptor.props) ? descriptor.props : []) {
117
+ if (!isRecord(prop) || typeof prop.name !== 'string') continue;
118
+ const parsed = manifestProp(prop);
119
+ if (parsed) props[prop.name] = parsed;
120
+ else {
121
+ warnings.push(
122
+ `fragment component ${name}: prop ${prop.name} has a type the component manifest cannot describe, so agent writes do not check it`,
123
+ );
124
+ }
125
+ }
126
+ entry.props = props;
127
+ }
128
+ components[name] = entry;
129
+ }
130
+ return { manifest: { components, elements: Object.keys(vocabulary.elements) }, warnings };
131
+ }
132
+
133
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
134
+
135
+ const unreadable = (unreadableReason: string): FragmentManifestResult => ({
136
+ manifest: { components: {}, elements: [], unreadable: true, unreadableReason },
137
+ warnings: [],
138
+ });
139
+
140
+ /**
141
+ * The fragment manifest of a build. Never throws: a site without `fragmentComponentsPath` lists nothing, and a render
142
+ * or schemas module that failed to load lists nothing and says why. `schemas: undefined` means the site sets no
143
+ * `schemasPath`, so no host-authored descriptors.
144
+ */
145
+ export async function readFragmentManifest(input: {
146
+ root: string;
147
+ vite: UserConfig;
148
+ fragmentComponentsPath?: string;
149
+ schemas: { mdxComponents: unknown } | { error: string } | undefined;
150
+ discovered: readonly unknown[];
151
+ }): Promise<FragmentManifestResult> {
152
+ const { fragmentComponentsPath, schemas } = input;
153
+ if (!fragmentComponentsPath) return { manifest: { components: {}, elements: [] }, warnings: [] };
154
+ let vocabulary: FragmentVocabulary;
155
+ try {
156
+ const { render } = await loadFragmentRender({ root: input.root, vite: input.vite, fragmentComponentsPath });
157
+ vocabulary = fragmentVocabularyOf(render, fragmentComponentsPath);
158
+ } catch (error) {
159
+ return unreadable(`${fragmentComponentsPath} failed to load: ${messageOf(error)}`);
160
+ }
161
+ if (schemas && 'error' in schemas) return unreadable(`the schemas module failed to load: ${schemas.error}`);
162
+ return fragmentManifestOf({ vocabulary, mdxComponents: schemas?.mdxComponents, discovered: input.discovered });
163
+ }
@@ -0,0 +1,64 @@
1
+ import { resolve } from 'node:path';
2
+ import { type Plugin, runnerImport, type UserConfig } from 'vite';
3
+ import type { FragmentComponentsModule } from '../handlers/page-render-core.js';
4
+ import { discoverFragmentIslands } from '../lib/hydration-scanner.js';
5
+
6
+ const CHECK_ENTRY = 'virtual:conloca-fragment-check';
7
+
8
+ /** The render module, and each island the build discovers in its imports as `[key, component]`, from one module graph. */
9
+ export interface CheckEntry {
10
+ render: FragmentComponentsModule;
11
+ islands: [string, object | undefined][];
12
+ }
13
+
14
+ /**
15
+ * Serves an entry that imports the render module and every module the island discovery maps, so their components are
16
+ * the same function objects the render module holds: the published render maps islands by identity.
17
+ */
18
+ function checkEntryPlugin(renderModulePath: string): Plugin {
19
+ return {
20
+ name: 'conloca:fragment-check-entry',
21
+ resolveId: (id) => (id === CHECK_ENTRY ? `\0${CHECK_ENTRY}` : undefined),
22
+ async load(id) {
23
+ if (id !== `\0${CHECK_ENTRY}`) return undefined;
24
+ const islands = await discoverFragmentIslands(renderModulePath, (s, i) => this.resolve(s, i));
25
+ return [
26
+ `import * as render from ${JSON.stringify(renderModulePath)};`,
27
+ ...islands.map(({ filePath }, i) => `import * as island${i} from ${JSON.stringify(filePath)};`),
28
+ 'export { render };',
29
+ `export const islands = [${islands.map(({ key, exportName }, i) => `[${JSON.stringify(key)}, island${i}[${JSON.stringify(exportName)}]]`).join(', ')}];`,
30
+ ].join('\n');
31
+ },
32
+ };
33
+ }
34
+
35
+ // shortcut: shared only when the site and its integrations resolve the same copy of this module; another copy loads
36
+ // again, which is correct but slower. Upgrade by passing the loaded module along if a site needs it.
37
+ const loads = new Map<string, Promise<CheckEntry>>();
38
+
39
+ /**
40
+ * Load the site's `fragmentComponentsPath` module once per process for its root and resolved path, so the build's
41
+ * component check and the component manifest share one load. A rejected load stays cached: both see the same error.
42
+ */
43
+ export function loadFragmentRender(input: {
44
+ root: string;
45
+ vite: UserConfig;
46
+ fragmentComponentsPath: string;
47
+ }): Promise<CheckEntry> {
48
+ // One spelling per directory: callers pass `process.cwd()` or a root URL path with a trailing slash.
49
+ const root = resolve(input.root);
50
+ const renderModulePath = resolve(root, input.fragmentComponentsPath);
51
+ const key = `${root}\0${renderModulePath}`;
52
+ let load = loads.get(key);
53
+ if (!load) {
54
+ load = runnerImport<CheckEntry>(CHECK_ENTRY, {
55
+ ...input.vite,
56
+ plugins: [...(input.vite.plugins ?? []), checkEntryPlugin(renderModulePath)],
57
+ configFile: false,
58
+ root,
59
+ logLevel: 'warn',
60
+ }).then(({ module }) => module);
61
+ loads.set(key, load);
62
+ }
63
+ return load;
64
+ }
@@ -8,7 +8,6 @@ import {
8
8
  FileSystemContentAPI,
9
9
  validateCFAccessRequest,
10
10
  } from '@conloca/content-api/node';
11
- import { handleMDXCompileRequest } from '@conloca/mdx/node';
12
11
  import type { APIRoute } from 'astro';
13
12
  import { SPA_MIME_TYPES } from './mime-types.js';
14
13
  import { isPathWithinBase } from './path-validation.js';
@@ -85,7 +84,7 @@ export const ALL: APIRoute = async ({ params, request }) => {
85
84
  * Generate HTML for dev mode that loads cms-spa source through Vite.
86
85
  * This ensures React is resolved from Vite's pre-bundled deps, not from the cms-spa bundle.
87
86
  */
88
- function generateDevHtml(config: typeof spaConfig): string {
87
+ export function generateDevHtml(config: typeof spaConfig): string {
89
88
  return `<!DOCTYPE html>
90
89
  <html lang="en">
91
90
  <head>
@@ -100,6 +99,7 @@ function generateDevHtml(config: typeof spaConfig): string {
100
99
  window.__UI_CONFIG__ = ${safeJsonStringify(config)};
101
100
  </script>
102
101
  <script type="module" src="${config.basename}/schemas-entry.js"></script>
102
+ <script type="module" src="${config.basename}/site-render-entry.js"></script>
103
103
  <script type="module" src="${config.basename}/puck-entry.js"></script>
104
104
  <script type="module" src="${config.basename}/content-listener.js"></script>
105
105
  </head>
@@ -157,6 +157,7 @@ async function handleSpa(params: { path?: string | string[] }): Promise<Response
157
157
  <script type="module" src="${spaConfig.basename}/site-styles.js"></script>
158
158
  <script type="module" src="${spaConfig.basename}/editor-styles.js"></script>
159
159
  <script type="module" src="${spaConfig.basename}/schemas-entry.js"></script>
160
+ <script type="module" src="${spaConfig.basename}/site-render-entry.js"></script>
160
161
  <script type="module" src="${spaConfig.basename}/puck-entry.js"></script>
161
162
  <script type="module" src="${spaConfig.basename}/content-listener.js"></script>
162
163
  `;
@@ -234,10 +235,6 @@ async function handleContentApi(request: Request, cfResult: CFAccessResult): Pro
234
235
  contentRoot,
235
236
  });
236
237
 
237
- // Mounted here rather than in @conloca/content-api because compiling MDX is a
238
- // renderer concern; content-api is purely storage.
239
- app.post('/mdx/compile', (c) => handleMDXCompileRequest(c.req.raw));
240
-
241
238
  // Extract the path after the API base
242
239
  const url = new URL(request.url);
243
240
  // Find where /api/ appears in the pathname
@@ -0,0 +1,97 @@
1
+ import { defineFragmentComponents, type FragmentVocabulary, type JsonValue } from '@conloca/mdx/render';
2
+ import { type ComponentType, createElement, Fragment, type ReactNode, useId } from 'react';
3
+ import { renderToString } from 'react-dom/server';
4
+ import { serializeProps } from '../lib/serialize-props.js';
5
+ import type { HydrationMeta } from '../lib/withHydration.js';
6
+ import { IslandSlot } from './IslandSlot.js';
7
+
8
+ // biome-ignore lint/suspicious/noExplicitAny: site components take arbitrary props
9
+ type AnyComponent = ComponentType<any>;
10
+
11
+ const islands = new WeakSet();
12
+ const memo = new WeakMap<FragmentVocabulary, FragmentVocabulary>();
13
+ const staticMemo = new WeakMap<FragmentVocabulary, FragmentVocabulary>();
14
+
15
+ // The strategy withHydration() attached, read without trusting the shape of the function's own properties.
16
+ export function strategyOf(component: AnyComponent | undefined): HydrationMeta['strategy'] | undefined {
17
+ const meta: unknown = component === undefined ? undefined : Reflect.get(component, '__hydration');
18
+ if (typeof meta !== 'object' || meta === null || Reflect.get(meta, '__isHydratable') !== true) return undefined;
19
+ const strategy: unknown = Reflect.get(meta, 'strategy');
20
+ return strategy === 'load' || strategy === 'visible' || strategy === 'idle' ? strategy : undefined;
21
+ }
22
+
23
+ function island(key: string, Component: AnyComponent, strategy: HydrationMeta['strategy']): AnyComponent {
24
+ // Fragment props are the JSON values the renderer read from the attributes, plus the rendered children.
25
+ function FragmentIsland({ children, ...props }: { children?: ReactNode; [prop: string]: JsonValue | ReactNode }) {
26
+ const id = useId();
27
+ const seen = { slot: false };
28
+ const slot = children === undefined ? undefined : createElement(IslandSlot, { id, seen }, children);
29
+ // Its own root, so the component's useId values carry the island id and the client root reproduces them.
30
+ const html = renderToString(createElement(Component, slot === undefined ? props : { ...props, children: slot }), {
31
+ identifierPrefix: id,
32
+ });
33
+ return createElement(
34
+ Fragment,
35
+ null,
36
+ createElement('conloca-island', {
37
+ 'data-conloca-island': id,
38
+ 'data-conloca-component': key,
39
+ 'data-hydrate-strategy': strategy,
40
+ 'data-props': serializeProps(props),
41
+ style: { display: 'contents' },
42
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: React's own server render of the component, not user input
43
+ dangerouslySetInnerHTML: { __html: html },
44
+ }),
45
+ slot !== undefined && !seen.slot ? createElement('template', { 'data-conloca-island-slot': id }, children) : null,
46
+ );
47
+ }
48
+ islands.add(FragmentIsland);
49
+ return FragmentIsland;
50
+ }
51
+
52
+ /**
53
+ * The vocabulary a published page renders fragments with: every `withHydration()` component becomes an island under
54
+ * its registry key from `islandKeys`; everything else keeps its reference.
55
+ *
56
+ * @param unmapped - `'throw'` (default): a hydrated element override, or a hydrated component missing from
57
+ * `islandKeys`, throws. `'static'`: each such value keeps its reference, so it renders without hydration.
58
+ */
59
+ export function islandVocabulary(
60
+ vocabulary: FragmentVocabulary,
61
+ islandKeys: ReadonlyMap<unknown, string>,
62
+ unmapped: 'throw' | 'static' = 'throw',
63
+ ): FragmentVocabulary {
64
+ const cache = unmapped === 'throw' ? memo : staticMemo;
65
+ const cached = cache.get(vocabulary);
66
+ if (cached) return cached;
67
+ for (const [name, element] of Object.entries(vocabulary.elements)) {
68
+ if (strategyOf(element) && unmapped === 'throw') {
69
+ throw new TypeError(
70
+ `Element override <${name}> is wrapped in withHydration(); only fragment components can hydrate.`,
71
+ );
72
+ }
73
+ }
74
+ const components: Record<string, AnyComponent> = {};
75
+ for (const [name, component] of Object.entries(vocabulary.components)) {
76
+ const strategy = strategyOf(component);
77
+ const key = strategy && islandKeys.get(component);
78
+ if (strategy && key === undefined && unmapped === 'throw') {
79
+ throw new TypeError(
80
+ `Fragment component <${name}> is wrapped in withHydration(), but the build found no module for it. Import it into the render module by name from the file that calls withHydration().`,
81
+ );
82
+ }
83
+ components[name] = strategy && key !== undefined ? island(key, component, strategy) : component;
84
+ }
85
+ const result = defineFragmentComponents({
86
+ components,
87
+ elements: { ...vocabulary.elements },
88
+ outline: { ...vocabulary.outline },
89
+ });
90
+ cache.set(vocabulary, result);
91
+ return result;
92
+ }
93
+
94
+ /** True only for the island wrappers `islandVocabulary` made. */
95
+ export function isFragmentIsland(component: unknown): boolean {
96
+ return typeof component === 'function' && islands.has(component);
97
+ }
@@ -0,0 +1,28 @@
1
+ import { createElement, type ReactElement, type ReactNode } from 'react';
2
+
3
+ /**
4
+ * The element an island's children sit in. On the server it renders the children and records that the component
5
+ * rendered them; in the browser it replays the HTML already on the page, so React keeps those DOM nodes.
6
+ */
7
+ export function IslandSlot({
8
+ id,
9
+ html,
10
+ seen,
11
+ children,
12
+ }: {
13
+ id: string;
14
+ html?: string;
15
+ seen?: { slot: boolean };
16
+ children?: ReactNode;
17
+ }): ReactElement {
18
+ const attributes = { 'data-conloca-island-slot': id, style: { display: 'contents' } };
19
+ if (html !== undefined) {
20
+ return createElement('conloca-island-slot', {
21
+ ...attributes,
22
+ dangerouslySetInnerHTML: { __html: html },
23
+ suppressHydrationWarning: true,
24
+ });
25
+ }
26
+ if (seen) seen.slot = true;
27
+ return createElement('conloca-island-slot', attributes, children);
28
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ /** Wraps page content in the marker the editor frame's drift check stops at, on routes that declare an `editorFrame`. */
3
+ interface Props {
4
+ framed: boolean;
5
+ }
6
+
7
+ const { framed } = Astro.props;
8
+ ---
9
+
10
+ {framed ? <div data-conloca-page-root=""><slot /></div> : <slot />}
@@ -1,5 +1,5 @@
1
1
  import type { MDXHeading } from '@conloca/content-api';
2
- import type { MDXFragmentEvaluationResult } from '@conloca/mdx/node';
2
+ import type { FragmentOutlineComponent, MDXFragmentEvaluationResult } from '@conloca/mdx/node';
3
3
  import type { ComponentConfig, Config, Data, PuckComponent } from '@puckeditor/core';
4
4
  import { Render } from '@puckeditor/core/rsc';
5
5
  import type { ComponentType } from 'react';
@@ -12,6 +12,8 @@ interface MDXComponent {
12
12
  title: string;
13
13
  Component: ComponentType;
14
14
  outline: readonly MDXHeading[];
15
+ /** Absent from a fragment a caller built by hand; it then lists no components. */
16
+ componentOutline?: readonly FragmentOutlineComponent[];
15
17
  }
16
18
 
17
19
  function isRenderableFragment(fragment: MDXFragmentEvaluationResult | MDXComponent): fragment is MDXComponent {
@@ -78,6 +80,7 @@ function withResolvedFragment(
78
80
  <HostBlock
79
81
  {...props}
80
82
  fragmentOutline={selected?.outline ?? []}
83
+ fragmentComponentOutline={selected?.componentOutline ?? []}
81
84
  fragment={
82
85
  SelectedFragmentComponent ? (
83
86
  <div className="mdx-content conloca-prose" data-conloca-content-root="">
@@ -321,7 +321,8 @@ class DescriptorBuilder {
321
321
  const requiredAttributes: Record<string, string | number | boolean> = {};
322
322
  for (const p of props) {
323
323
  if (!p.required) continue;
324
- requiredAttributes[p.name] = placeholderForProp(p, this.observedValues.get(p.name));
324
+ const placeholder = placeholderForProp(p, this.observedValues.get(p.name));
325
+ if (placeholder !== null) requiredAttributes[p.name] = placeholder;
325
326
  }
326
327
 
327
328
  const descriptor: DiscoveredComponent = {
@@ -358,10 +359,14 @@ class DescriptorBuilder {
358
359
  * string path, where union options and observed usage give us real
359
360
  * authored values to reuse.
360
361
  */
361
- function placeholderForProp(prop: MdxComponentProp, observed: Set<string> | undefined): string | number | boolean {
362
+ function placeholderForProp(
363
+ prop: MdxComponentProp,
364
+ observed: Set<string> | undefined,
365
+ ): string | number | boolean | null {
362
366
  if (prop.type === 'number') return 0;
363
367
  if (prop.type === 'boolean') return true;
364
- // string
368
+ // Discovery never produces list or object props.
369
+ if (prop.type !== 'string') return null;
365
370
  if (prop.options && prop.options.length > 0) return prop.options[0].value;
366
371
  if (observed && observed.size > 0) {
367
372
  const first = observed.values().next();
@@ -18,6 +18,10 @@ export const EDITOR_DESCRIPTORS_ENV_VAR = 'CONLOCA_EDITOR_DESCRIPTORS';
18
18
  export interface EditorDescriptorChannel {
19
19
  /** Absolute path of the host's schemas module (the `schemasPath` option), when configured. */
20
20
  schemasPath?: string;
21
+ /** Absolute path of the fragment components render module (the `fragmentComponentsPath` option), when configured. */
22
+ fragmentComponentsPath?: string;
23
+ /** Route name → absolute path of that route's `editorFrame` module, for each route that declares one. */
24
+ editorFrames?: Record<string, string>;
21
25
  /**
22
26
  * Absolute path of the puck config module (the `puckConfigPath` option).
23
27
  * Optional only because an older `@conloca/astro-cms` wrote no such field;
@@ -73,6 +77,8 @@ export function readEditorDescriptors(
73
77
  const contentPathValue = 'contentPaths' in parsed ? parsed.contentPaths : undefined;
74
78
  const assetsPath = 'assetsPath' in parsed ? parsed.assetsPath : undefined;
75
79
  const assetRefBase = 'assetRefBase' in parsed ? parsed.assetRefBase : undefined;
80
+ const fragmentComponentsPath = 'fragmentComponentsPath' in parsed ? parsed.fragmentComponentsPath : undefined;
81
+ const editorFrames = readEditorFrames('editorFrames' in parsed ? parsed.editorFrames : undefined);
76
82
  if (typeof registry !== 'object' || registry === null) return undefined;
77
83
  const contentRoot = 'contentRoot' in registry ? registry.contentRoot : undefined;
78
84
  const componentFolders = 'componentFolders' in registry ? registry.componentFolders : undefined;
@@ -113,6 +119,8 @@ export function readEditorDescriptors(
113
119
  ...(typeof overridesFolder === 'string' ? { overridesFolder } : {}),
114
120
  },
115
121
  ...(templates === undefined ? {} : { templates }),
122
+ ...(typeof fragmentComponentsPath === 'string' ? { fragmentComponentsPath } : {}),
123
+ ...(editorFrames === undefined ? {} : { editorFrames }),
116
124
  ...(dataBindings === undefined ? {} : { dataBindings }),
117
125
  ...(contentPaths === undefined ? {} : { contentPaths }),
118
126
  ...(typeof assetsPath === 'string' && isAbsolute(assetsPath) ? { assetsPath } : {}),
@@ -140,3 +148,12 @@ function readTemplates(raw: unknown): Record<string, TemplateConfig> | undefined
140
148
  }
141
149
  return Object.keys(templates).length > 0 ? templates : undefined;
142
150
  }
151
+
152
+ /** Per-entry, like `readTemplates`: a route whose frame is not a string is dropped, the rest survive. */
153
+ function readEditorFrames(raw: unknown): Record<string, string> | undefined {
154
+ if (typeof raw !== 'object' || raw === null) return undefined;
155
+ const frames = Object.fromEntries(
156
+ Object.entries(raw).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
157
+ );
158
+ return Object.keys(frames).length > 0 ? frames : undefined;
159
+ }