@conloca/astro-cms 0.1.15 → 0.1.16

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 (160) hide show
  1. package/README.md +65 -5
  2. package/dist/collections-Bd7EME4b.mjs +129 -0
  3. package/dist/collections-Bd7EME4b.mjs.map +1 -0
  4. package/dist/collections.d.mts +0 -1
  5. package/dist/collections.d.mts.map +1 -1
  6. package/dist/collections.mjs +1 -64
  7. package/dist/components.d.mts +2 -7
  8. package/dist/components.d.mts.map +1 -1
  9. package/dist/components.mjs +3 -6
  10. package/dist/components.mjs.map +1 -1
  11. package/dist/hydration.d.mts +2 -2
  12. package/dist/hydration.mjs +2 -3
  13. package/dist/index.d.mts +6 -37
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +7 -6
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/internal/cms-handler.d.mts +0 -1
  18. package/dist/internal/cms-handler.d.mts.map +1 -1
  19. package/dist/internal/cms-handler.mjs +55 -8
  20. package/dist/internal/cms-handler.mjs.map +1 -1
  21. package/dist/lib/hydration-script.d.mts +1 -2
  22. package/dist/lib/hydration-script.d.mts.map +1 -1
  23. package/dist/lib/hydration-script.mjs +1 -2
  24. package/dist/lib/hydration-script.mjs.map +1 -1
  25. package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
  26. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
  27. package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
  28. package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
  29. package/dist/node/content.d.mts +0 -1
  30. package/dist/node/content.d.mts.map +1 -1
  31. package/dist/node/content.d.ts +3 -0
  32. package/dist/node/content.d.ts.map +1 -0
  33. package/dist/node/content.js +2 -0
  34. package/dist/node/content.mjs +2 -4
  35. package/dist/node/index.d.mts +151 -3
  36. package/dist/node/index.d.mts.map +1 -1
  37. package/dist/node/index.d.ts +4 -0
  38. package/dist/node/index.d.ts.map +1 -0
  39. package/dist/node/index.js +3 -0
  40. package/dist/node/index.mjs +1857 -97
  41. package/dist/node/index.mjs.map +1 -1
  42. package/dist/{serialize-props-Dhv_MnkY.mjs → serialize-props-BHoNpzH6.mjs} +2 -3
  43. package/dist/{serialize-props-Dhv_MnkY.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
  44. package/dist/src/cms-handler.d.ts +19 -0
  45. package/dist/src/cms-handler.d.ts.map +1 -0
  46. package/dist/src/cms-handler.js +366 -0
  47. package/dist/src/collections.d.ts +32 -0
  48. package/dist/src/collections.d.ts.map +1 -0
  49. package/dist/src/collections.js +50 -0
  50. package/dist/src/components/HydrationWrapper.d.ts +18 -0
  51. package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
  52. package/dist/src/components/HydrationWrapper.js +21 -0
  53. package/dist/src/components/RenderWithBlocks.d.ts +23 -0
  54. package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
  55. package/dist/src/components/RenderWithBlocks.js +129 -0
  56. package/dist/src/components/RenderWithHydration.d.ts +17 -0
  57. package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
  58. package/dist/src/components/RenderWithHydration.js +36 -0
  59. package/dist/src/components.d.ts +4 -0
  60. package/dist/src/components.d.ts.map +1 -0
  61. package/dist/src/components.js +3 -0
  62. package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
  63. package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
  64. package/dist/src/discovery/astro-frontmatter.js +24 -0
  65. package/dist/src/discovery/extract-props-ts.d.ts +41 -0
  66. package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
  67. package/dist/src/discovery/extract-props-ts.js +231 -0
  68. package/dist/src/discovery/merge-registry.d.ts +58 -0
  69. package/dist/src/discovery/merge-registry.d.ts.map +1 -0
  70. package/dist/src/discovery/merge-registry.js +332 -0
  71. package/dist/src/discovery/registry-endpoint.d.ts +42 -0
  72. package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
  73. package/dist/src/discovery/registry-endpoint.js +81 -0
  74. package/dist/src/discovery/scan-components.d.ts +98 -0
  75. package/dist/src/discovery/scan-components.d.ts.map +1 -0
  76. package/dist/src/discovery/scan-components.js +399 -0
  77. package/dist/src/discovery/scan-mdx.d.ts +63 -0
  78. package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
  79. package/dist/src/discovery/scan-mdx.js +112 -0
  80. package/dist/src/discovery/scan-overrides.d.ts +71 -0
  81. package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
  82. package/dist/src/discovery/scan-overrides.js +33 -0
  83. package/dist/src/hydration.d.ts +4 -0
  84. package/dist/src/hydration.d.ts.map +1 -0
  85. package/dist/src/hydration.js +4 -0
  86. package/dist/src/index.d.ts +11 -0
  87. package/dist/src/index.d.ts.map +1 -0
  88. package/dist/src/index.js +25 -0
  89. package/dist/src/lib/hydration-scanner.d.ts +47 -0
  90. package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
  91. package/dist/src/lib/hydration-scanner.js +135 -0
  92. package/dist/src/lib/hydration-script.d.ts +28 -0
  93. package/dist/src/lib/hydration-script.d.ts.map +1 -0
  94. package/dist/src/lib/hydration-script.js +88 -0
  95. package/dist/src/lib/hydration-utils.d.ts +51 -0
  96. package/dist/src/lib/hydration-utils.d.ts.map +1 -0
  97. package/dist/src/lib/hydration-utils.js +83 -0
  98. package/dist/src/lib/page-api.d.ts +77 -0
  99. package/dist/src/lib/page-api.d.ts.map +1 -0
  100. package/dist/src/lib/page-api.js +121 -0
  101. package/dist/src/lib/route-utils.d.ts +41 -0
  102. package/dist/src/lib/route-utils.d.ts.map +1 -0
  103. package/dist/src/lib/route-utils.js +78 -0
  104. package/dist/src/lib/routing-config.d.ts +32 -0
  105. package/dist/src/lib/routing-config.d.ts.map +1 -0
  106. package/dist/src/lib/routing-config.js +93 -0
  107. package/dist/src/lib/serialize-props.d.ts +6 -0
  108. package/dist/src/lib/serialize-props.d.ts.map +1 -0
  109. package/dist/src/lib/serialize-props.js +7 -0
  110. package/dist/src/lib/virtual-module-generators.d.ts +57 -0
  111. package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
  112. package/dist/src/lib/virtual-module-generators.js +263 -0
  113. package/dist/src/lib/withHydration.d.ts +51 -0
  114. package/dist/src/lib/withHydration.d.ts.map +1 -0
  115. package/dist/src/lib/withHydration.js +49 -0
  116. package/dist/src/loader.d.ts +14 -0
  117. package/dist/src/loader.d.ts.map +1 -0
  118. package/dist/src/loader.js +89 -0
  119. package/dist/src/locales-helpers.d.ts +61 -0
  120. package/dist/src/locales-helpers.d.ts.map +1 -0
  121. package/dist/src/locales-helpers.js +49 -0
  122. package/dist/src/mime-types.d.ts +3 -0
  123. package/dist/src/mime-types.d.ts.map +1 -0
  124. package/dist/src/mime-types.js +19 -0
  125. package/dist/src/path-validation.d.ts +8 -0
  126. package/dist/src/path-validation.d.ts.map +1 -0
  127. package/dist/src/path-validation.js +12 -0
  128. package/dist/src/plugin-spa.d.ts +164 -0
  129. package/dist/src/plugin-spa.d.ts.map +1 -0
  130. package/dist/src/plugin-spa.js +972 -0
  131. package/dist/src/safe-json-stringify.d.ts +13 -0
  132. package/dist/src/safe-json-stringify.d.ts.map +1 -0
  133. package/dist/src/safe-json-stringify.js +6 -0
  134. package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
  135. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  136. package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
  137. package/dist/src/site-styles/render-endpoint.d.ts +55 -0
  138. package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
  139. package/dist/src/site-styles/render-endpoint.js +263 -0
  140. package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
  141. package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
  142. package/dist/src/site-styles/styles-endpoint.js +158 -0
  143. package/dist/src/types.d.ts +627 -0
  144. package/dist/src/types.d.ts.map +1 -0
  145. package/dist/src/types.js +1 -0
  146. package/dist/{types-CVQNmPxF.d.mts → types-CS9neadI.d.mts} +193 -3
  147. package/dist/types-CS9neadI.d.mts.map +1 -0
  148. package/dist/virtual-modules.d.ts +155 -0
  149. package/dist/{withHydration-EzyzBQ-Y.mjs → withHydration-C256ox_6.mjs} +2 -2
  150. package/dist/{withHydration-EzyzBQ-Y.mjs.map → withHydration-C256ox_6.mjs.map} +1 -1
  151. package/dist/{withHydration-HIvO9ysY.d.mts → withHydration-DkKpkmzJ.d.mts} +1 -2
  152. package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
  153. package/package.json +82 -26
  154. package/dist/collections.mjs.map +0 -1
  155. package/dist/hydration-scanner-B0NjYkZ_.mjs +0 -109
  156. package/dist/hydration-scanner-B0NjYkZ_.mjs.map +0 -1
  157. package/dist/loader-By-AQWHc.mjs +0 -68
  158. package/dist/loader-By-AQWHc.mjs.map +0 -1
  159. package/dist/types-CVQNmPxF.d.mts.map +0 -1
  160. package/dist/withHydration-HIvO9ysY.d.mts.map +0 -1
@@ -1,10 +1,1070 @@
1
- import { n as scanForHydratableComponents, t as deriveComponentPaths } from "../hydration-scanner-B0NjYkZ_.mjs";
2
- import { dirname, join, resolve } from "node:path";
1
+ import { n as localesFromStarlight, t as localesFromAstroI18n } from "../locales-helpers-qiwh7nxS.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
5
+ import fg from "fast-glob";
3
6
  import { existsSync } from "node:fs";
4
7
  import { fileURLToPath } from "node:url";
8
+ import { readSitesConfig } from "@conloca/content-api/node";
5
9
  import viteReact from "@vitejs/plugin-react";
6
10
  import { searchForWorkspaceRoot } from "vite";
7
-
11
+ import { ModuleKind, ModuleResolutionKind, Project, ScriptTarget } from "ts-morph";
12
+ import { fromMarkdown } from "mdast-util-from-markdown";
13
+ import { mdxFromMarkdown } from "mdast-util-mdx";
14
+ import { mdxjs } from "micromark-extension-mdxjs";
15
+ import { experimental_AstroContainer } from "astro/container";
16
+ //#region src/lib/hydration-scanner.ts
17
+ const HYDRATION_IMPORT_PATTERN = /import\s+\{[^}]*withHydration[^}]*\}\s+from\s+['"]@conloca\/astro-cms(?:\/hydration)?['"]/;
18
+ const HYDRATION_PATTERN = /withHydration\s*\(\s*\w+\s*,\s*['"](\w+)['"]\s*\)/g;
19
+ const VALID_STRATEGIES = /* @__PURE__ */ new Set([
20
+ "load",
21
+ "visible",
22
+ "idle"
23
+ ]);
24
+ /**
25
+ * Derives component scan paths from puckConfigPath.
26
+ *
27
+ * Convention: puckConfigPath directory + '/components/puck'
28
+ * Example: './src/puck.config.tsx' -> './src/components/puck'
29
+ *
30
+ * If explicitPaths provided, they extend (not replace) the auto-discovered path.
31
+ *
32
+ * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')
33
+ * @param explicitPaths - Optional additional paths to scan
34
+ * @returns Array of paths to scan for hydratable components
35
+ */
36
+ function deriveComponentPaths(puckConfigPath, explicitPaths) {
37
+ const defaultScanPath = join(dirname(puckConfigPath), "components", "puck");
38
+ if (explicitPaths && explicitPaths.length > 0) return [defaultScanPath, ...explicitPaths];
39
+ return [defaultScanPath];
40
+ }
41
+ /**
42
+ * Derives a PascalCase component name from a file path.
43
+ *
44
+ * @param filePath - Absolute path to the component file
45
+ * @returns Component name in PascalCase
46
+ *
47
+ * @example
48
+ * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')
49
+ * // => 'TestimonialGrid'
50
+ *
51
+ * deriveComponentName('/src/components/puck/blog-post-grid.tsx')
52
+ * // => 'BlogPostGrid'
53
+ */
54
+ function deriveComponentName(filePath) {
55
+ const filename = basename(filePath, extname(filePath));
56
+ if (filename.includes("-")) return filename.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
57
+ return filename.charAt(0).toUpperCase() + filename.slice(1);
58
+ }
59
+ /**
60
+ * Scans component directories for files using withHydration wrapper.
61
+ *
62
+ * This function performs static analysis to discover components marked
63
+ * for hydration, without executing any component code.
64
+ *
65
+ * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])
66
+ * @param projectRoot - Absolute path to the project root
67
+ * @returns Array of discovered hydratable components with their strategies
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const discoveries = await scanForHydratableComponents(
72
+ * ['src/components/puck'],
73
+ * '/path/to/project'
74
+ * )
75
+ * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]
76
+ * ```
77
+ */
78
+ async function scanForHydratableComponents(componentPaths, projectRoot) {
79
+ const discoveries = [];
80
+ const seenNames = /* @__PURE__ */ new Map();
81
+ for (const scanPath of componentPaths) {
82
+ const files = await fg("**/*.tsx", {
83
+ cwd: resolve(projectRoot, scanPath),
84
+ absolute: true,
85
+ onlyFiles: true
86
+ });
87
+ for (const filePath of files) try {
88
+ const content = await readFile(filePath, "utf-8");
89
+ if (!HYDRATION_IMPORT_PATTERN.test(content)) continue;
90
+ const matches = [...content.matchAll(HYDRATION_PATTERN)];
91
+ if (matches.length === 0) continue;
92
+ if (matches.length > 1) console.warn(`[Conloca Hydration] Multiple withHydration calls in ${filePath}. Consider splitting into separate component files. Using first call.`);
93
+ const rawStrategy = matches[0][1];
94
+ if (!VALID_STRATEGIES.has(rawStrategy)) {
95
+ console.warn(`[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. Valid options: ${[...VALID_STRATEGIES].join(", ")}. Skipping component.`);
96
+ continue;
97
+ }
98
+ const strategy = rawStrategy;
99
+ const componentName = deriveComponentName(filePath);
100
+ const existingPath = seenNames.get(componentName);
101
+ if (existingPath) {
102
+ console.warn(`[Conloca Hydration] Duplicate component name '${componentName}'. Found in: ${existingPath} and ${filePath}. Using first occurrence.`);
103
+ continue;
104
+ }
105
+ seenNames.set(componentName, filePath);
106
+ discoveries.push({
107
+ componentName,
108
+ filePath,
109
+ strategy
110
+ });
111
+ } catch (err) {
112
+ console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err);
113
+ }
114
+ }
115
+ return discoveries;
116
+ }
117
+ //#endregion
118
+ //#region src/discovery/merge-registry.ts
119
+ function mergeRegistry(mdxScans, localComponents, overrides) {
120
+ const byKey = /* @__PURE__ */ new Map();
121
+ for (const comp of localComponents) {
122
+ const key = `${comp.source}::${comp.name}`;
123
+ byKey.set(key, new DescriptorBuilder({
124
+ name: comp.name,
125
+ source: comp.source,
126
+ defaultExport: false,
127
+ kind: comp.kind,
128
+ propsFromInterface: comp.props
129
+ }));
130
+ }
131
+ for (const scan of mdxScans) for (const usage of scan.usages) {
132
+ const imp = scan.imports[usage.name];
133
+ if (!imp) continue;
134
+ const canonicalName = imp.exportName === "default" ? usage.name : imp.exportName;
135
+ const key = `${imp.source}::${canonicalName}`;
136
+ let builder = byKey.get(key);
137
+ if (!builder) {
138
+ builder = new DescriptorBuilder({
139
+ name: canonicalName,
140
+ source: imp.source,
141
+ defaultExport: imp.defaultExport,
142
+ kind: usage.kind
143
+ });
144
+ byKey.set(key, builder);
145
+ }
146
+ builder.observeUsage(usage.attrs, scan.filepath, usage.name, imp, usage.kind);
147
+ }
148
+ const grouped = /* @__PURE__ */ new Map();
149
+ for (const builder of byKey.values()) {
150
+ const arr = grouped.get(builder.name) ?? [];
151
+ arr.push(builder);
152
+ grouped.set(builder.name, arr);
153
+ }
154
+ const winners = [];
155
+ for (const candidates of grouped.values()) {
156
+ candidates.sort((a, b) => {
157
+ if (a.usageCount !== b.usageCount) return b.usageCount - a.usageCount;
158
+ const aHasSchema = a.hasInterfaceSchema();
159
+ if (aHasSchema !== b.hasInterfaceSchema()) return aHasSchema ? -1 : 1;
160
+ return 0;
161
+ });
162
+ let descriptor = candidates[0].toDescriptor();
163
+ const override = overrides?.get(descriptor.name);
164
+ if (override) descriptor = applyOverride(descriptor, override);
165
+ winners.push(descriptor);
166
+ }
167
+ return winners;
168
+ }
169
+ /**
170
+ * Apply a host-provided override to an auto-discovered descriptor.
171
+ *
172
+ * Three kinds of merges happen:
173
+ *
174
+ * 1. **Shallow object merges** for `insert` and `defaults` — host
175
+ * fields overwrite inferred fields one key at a time, so a host
176
+ * can tweak only the label without losing the inferred category.
177
+ *
178
+ * 2. **Per-prop merges** for the `props` array — match by `name`,
179
+ * override individual fields (`required`, `label`, `help`,
180
+ * `options`) while keeping the rest of the prop's inferred
181
+ * schema (type, defaultValue). Props the override doesn't mention
182
+ * stay untouched.
183
+ *
184
+ * 3. **Scalar overrides** for `hasChildren` and `kind` — host value
185
+ * replaces inferred value directly.
186
+ *
187
+ * The override is INTENTIONALLY a subset of `MdxJsxComponentDescriptor`
188
+ * — fields the host can sensibly customize. Things like `name` and
189
+ * `import` come from the actual file system / MDX scan and can't be
190
+ * meaningfully overridden by a sidecar JSON.
191
+ */
192
+ function applyOverride(descriptor, override) {
193
+ const next = { ...descriptor };
194
+ if (override.insert) next.insert = {
195
+ ...descriptor.insert ?? { label: descriptor.name },
196
+ ...override.insert
197
+ };
198
+ if (override.defaults) next.defaults = {
199
+ ...descriptor.defaults ?? {},
200
+ ...override.defaults,
201
+ ...override.defaults.attributes ? { attributes: {
202
+ ...descriptor.defaults?.attributes ?? {},
203
+ ...override.defaults.attributes
204
+ } } : {}
205
+ };
206
+ if (override.hasChildren !== void 0) next.hasChildren = override.hasChildren;
207
+ if (override.kind) next.kind = override.kind;
208
+ if (override.props && descriptor.props) {
209
+ const overridesByName = override.props;
210
+ next.props = descriptor.props.map((p) => {
211
+ const o = overridesByName[p.name];
212
+ if (!o) return p;
213
+ const merged = { ...p };
214
+ if (o.required !== void 0) merged.required = o.required;
215
+ if (o.label !== void 0) merged.label = o.label;
216
+ if (o.help !== void 0) merged.help = o.help;
217
+ if (o.options && merged.type === "string") merged.options = o.options;
218
+ return merged;
219
+ });
220
+ }
221
+ return next;
222
+ }
223
+ /** Internal accumulator. Combines interface-derived schema with
224
+ * usage-derived observations as scans arrive. */
225
+ var DescriptorBuilder = class {
226
+ name;
227
+ source;
228
+ defaultExport;
229
+ /**
230
+ * Component flow/text kind. Mutable across `observeUsage` calls
231
+ * because mdast classifies the SAME component differently based on
232
+ * how each instance is authored in source: `<Steps>...</Steps>` on
233
+ * one line parses as `mdxJsxTextElement` (inline), but the same
234
+ * component with blank-line-separated children parses as
235
+ * `mdxJsxFlowElement` (block). The component's intrinsic nature is
236
+ * "block" — so any single flow observation must promote the kind
237
+ * from text to flow. Without this, one stray inline usage in a
238
+ * fixture poisons the registry, MDXEditor mounts the JSX as inline,
239
+ * and saves serialize block components as single-line MDX — which
240
+ * Starlight's strict-slot validators (Steps wants `<ol>`, FileTree
241
+ * wants `<ul>`) then reject at render time.
242
+ *
243
+ * Demotion in the other direction never happens: a component seen
244
+ * as flow even once is intrinsically flow-capable, regardless of
245
+ * other inline observations.
246
+ */
247
+ kind;
248
+ propsFromInterface;
249
+ /** propName → set of distinct string values observed in MDX. */
250
+ observedValues = /* @__PURE__ */ new Map();
251
+ /** filepath → local alias used in that file (when ≠ canonical). */
252
+ aliases = {};
253
+ /** Names of props we've seen in usage but that aren't in the
254
+ * interface (or for npm components where there's no interface). */
255
+ observedPropNames = /* @__PURE__ */ new Set();
256
+ /** How many `<Foo>` usages of this component were seen across all
257
+ * MDX files. Used to pick a winner on name collisions. */
258
+ usageCount = 0;
259
+ constructor(init) {
260
+ this.name = init.name;
261
+ this.source = init.source;
262
+ this.defaultExport = init.defaultExport;
263
+ this.kind = init.kind;
264
+ this.propsFromInterface = init.propsFromInterface ?? [];
265
+ }
266
+ observeUsage(attrs, filepath, localName, imp, observedKind) {
267
+ this.usageCount++;
268
+ if (observedKind === "flow") this.kind = "flow";
269
+ if (imp.aliasedFrom && localName !== this.name) this.aliases[filepath] = localName;
270
+ for (const [propName, value] of Object.entries(attrs)) {
271
+ this.observedPropNames.add(propName);
272
+ if (!this.observedValues.has(propName)) this.observedValues.set(propName, /* @__PURE__ */ new Set());
273
+ this.observedValues.get(propName).add(value);
274
+ }
275
+ }
276
+ hasInterfaceSchema() {
277
+ return this.propsFromInterface.length > 0;
278
+ }
279
+ toDescriptor() {
280
+ const interfacePropNames = new Set(this.propsFromInterface.map((p) => p.name));
281
+ const props = [];
282
+ for (const ip of this.propsFromInterface) props.push(toMdxComponentProp(ip, this.observedValues.get(ip.name)));
283
+ for (const name of this.observedPropNames) {
284
+ if (interfacePropNames.has(name)) continue;
285
+ props.push({
286
+ name,
287
+ type: "string"
288
+ });
289
+ }
290
+ const requiredAttributes = {};
291
+ for (const p of props) {
292
+ if (!p.required) continue;
293
+ requiredAttributes[p.name] = placeholderForProp(p, this.observedValues.get(p.name));
294
+ }
295
+ const descriptor = {
296
+ name: this.name,
297
+ kind: this.kind,
298
+ hasChildren: true,
299
+ props,
300
+ import: {
301
+ from: this.source,
302
+ ...this.defaultExport ? { default: true } : {}
303
+ },
304
+ insert: {
305
+ label: this.name,
306
+ category: "Components"
307
+ },
308
+ ...Object.keys(requiredAttributes).length > 0 ? { defaults: { attributes: requiredAttributes } } : {}
309
+ };
310
+ if (Object.keys(this.aliases).length > 0) descriptor.aliases = this.aliases;
311
+ return descriptor;
312
+ }
313
+ };
314
+ /**
315
+ * Pick a sensible starter value for a required prop so the insert flow
316
+ * has something to put on the attribute. See the call site in
317
+ * `DescriptorBuilder.toDescriptor` for the priority rationale; this
318
+ * function just executes it.
319
+ *
320
+ * Number and boolean placeholders are intentionally trivial — `0` and
321
+ * `true` — because numeric/boolean props are rare in MDX components and
322
+ * any concrete value beats `undefined`. The interesting work is on the
323
+ * string path, where union options and observed usage give us real
324
+ * authored values to reuse.
325
+ */
326
+ function placeholderForProp(prop, observed) {
327
+ if (prop.type === "number") return 0;
328
+ if (prop.type === "boolean") return true;
329
+ if (prop.options && prop.options.length > 0) return prop.options[0].value;
330
+ if (observed && observed.size > 0) {
331
+ const first = observed.values().next();
332
+ if (!first.done) return first.value;
333
+ }
334
+ return prop.name.charAt(0).toUpperCase() + prop.name.slice(1);
335
+ }
336
+ function toMdxComponentProp(parsed, observed) {
337
+ let optionStrings = parsed.options;
338
+ if (optionStrings && observed && observed.size > 0) {
339
+ const combined = new Set(optionStrings);
340
+ for (const v of observed) combined.add(v);
341
+ if (combined.size <= 5) optionStrings = Array.from(combined);
342
+ }
343
+ if (parsed.type === "number") return {
344
+ name: parsed.name,
345
+ type: "number",
346
+ required: parsed.required
347
+ };
348
+ if (parsed.type === "boolean") return {
349
+ name: parsed.name,
350
+ type: "boolean",
351
+ required: parsed.required
352
+ };
353
+ return {
354
+ name: parsed.name,
355
+ type: "string",
356
+ required: parsed.required,
357
+ ...optionStrings && optionStrings.length > 0 ? { options: optionStrings.map((v) => ({
358
+ value: v,
359
+ label: v
360
+ })) } : {}
361
+ };
362
+ }
363
+ //#endregion
364
+ //#region src/discovery/astro-frontmatter.ts
365
+ /**
366
+ * Extract the frontmatter (the `---`-fenced TypeScript block) from
367
+ * an `.astro` source file. Returns the inner text, or `null` if no
368
+ * frontmatter is present (a valid Astro file shape — props-less
369
+ * components without `<script>` of any kind).
370
+ *
371
+ * Astro's official compiler (`@astrojs/compiler`) exposes a full
372
+ * parser, but for the props-extraction use case all we need is the
373
+ * text between the opening and closing fences. A regex is sufficient
374
+ * and keeps this synchronous (no WASM init cost, no async).
375
+ *
376
+ * The fence rule is simple: the file must start with `---\n` and
377
+ * close with `\n---` followed by either a newline or end-of-file.
378
+ * Whitespace before the opening fence is rejected — Astro itself
379
+ * requires the fence at column 0.
380
+ */
381
+ function extractAstroFrontmatter(content) {
382
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/.exec(content);
383
+ return match ? match[1] : null;
384
+ }
385
+ //#endregion
386
+ //#region src/discovery/extract-props-ts.ts
387
+ /**
388
+ * TypeScript-aware extraction of a component's `Props` interface,
389
+ * replacing the regex-based path in `scan-components.ts`. Uses
390
+ * `ts-morph` (a thin wrapper over the TypeScript compiler API) so
391
+ * derived types — `(typeof asideVariants)[number]`, mapped types,
392
+ * imported aliases, conditional types — resolve to their concrete
393
+ * literal-union values. The regex scanner couldn't follow any
394
+ * indirection and silently dropped options for those props (Aside's
395
+ * `type` being the canonical example).
396
+ *
397
+ * The output shape is identical to the regex path (`ParsedProp[]`)
398
+ * so the rest of the discovery pipeline doesn't change.
399
+ *
400
+ * Astro files are handled by extracting the frontmatter block and
401
+ * feeding it to the Project as a virtual `.ts` source — see
402
+ * `extractAstroFrontmatter` in `astro-frontmatter.ts`.
403
+ */
404
+ /**
405
+ * One Project per scan run, reused across `extractPropsViaTs` calls
406
+ * within the same scan. Building the Project loads `lib.dom.d.ts`
407
+ * etc. which dominates cold-start cost (~500ms-2s); sharing across
408
+ * files in a scan amortises that. A fresh Project is built per scan
409
+ * run so file changes are picked up — ts-morph's `addSourceFile`
410
+ * caches by path and wouldn't see external edits otherwise.
411
+ */
412
+ function createScanProject(tsConfigFilePath) {
413
+ if (tsConfigFilePath) try {
414
+ return new Project({
415
+ tsConfigFilePath,
416
+ skipAddingFilesFromTsConfig: true
417
+ });
418
+ } catch {}
419
+ return new Project({
420
+ compilerOptions: {
421
+ target: ScriptTarget.ES2022,
422
+ module: ModuleKind.ESNext,
423
+ moduleResolution: ModuleResolutionKind.Bundler,
424
+ allowJs: true,
425
+ esModuleInterop: true,
426
+ skipLibCheck: true,
427
+ strict: false
428
+ },
429
+ skipAddingFilesFromTsConfig: true
430
+ });
431
+ }
432
+ /**
433
+ * Extract the Props interface from a source string and return the
434
+ * parsed prop list. `filepath` is used as the virtual file's path
435
+ * inside the Project so error messages and source-map debugging
436
+ * point back at the right file; the actual content comes from
437
+ * `sourceText`. `.astro` callers pass the extracted frontmatter as
438
+ * `sourceText` and `${filepath}.virtual.ts` as `filepath`.
439
+ *
440
+ * Returns `[]` when no Props interface is found — same contract as
441
+ * the regex path so callers don't need a special-case branch.
442
+ */
443
+ function extractPropsViaTs(project, filepath, sourceText, componentName) {
444
+ let sf;
445
+ try {
446
+ sf = project.createSourceFile(filepath, sourceText, { overwrite: true });
447
+ } catch (err) {
448
+ console.warn(`[conloca:ts-morph] parse failed for ${filepath}:`, err instanceof Error ? err.message : err);
449
+ return [];
450
+ }
451
+ const candidates = [];
452
+ if (componentName) candidates.push(`${componentName}Props`);
453
+ candidates.push("Props");
454
+ let propertySignatures = [];
455
+ for (const name of candidates) {
456
+ const iface = sf.getInterface(name);
457
+ if (iface) {
458
+ propertySignatures = collectLocalProperties(iface);
459
+ break;
460
+ }
461
+ const alias = sf.getTypeAlias(name);
462
+ if (alias) {
463
+ propertySignatures = collectAliasProperties(alias);
464
+ break;
465
+ }
466
+ }
467
+ if (propertySignatures.length === 0) {
468
+ project.removeSourceFile(sf);
469
+ return [];
470
+ }
471
+ const props = [];
472
+ for (const prop of propertySignatures) {
473
+ const name = prop.getName();
474
+ const type = prop.getType();
475
+ const required = !prop.hasQuestionToken();
476
+ props.push(parseType(name, type, required));
477
+ }
478
+ project.removeSourceFile(sf);
479
+ return props;
480
+ }
481
+ /**
482
+ * Get ONLY the locally-declared properties on an interface, NOT
483
+ * properties inherited from `extends` clauses. This is the key choice
484
+ * that keeps the side panel sane for components like Starlight's
485
+ * `LinkCard` which declares `extends Omit<HTMLAttributes<'a'>, 'title'>`:
486
+ * the type-level `Type.getProperties()` would include every HTML
487
+ * attribute (~200 entries — `accesskey`, `aria-*`, `on*`, etc), making
488
+ * the panel useless. The declaration-level `iface.getProperties()`
489
+ * returns just the props the author explicitly wrote inside the
490
+ * braces, which is the editor's intent.
491
+ *
492
+ * Trade-off: a property the author "overrides" via re-declaration
493
+ * (eg LinkCard's local `title: string` overriding the inherited
494
+ * `title?: string`) appears — good. A property the author NEVER
495
+ * declared locally but the inherited interface defines (eg `href`
496
+ * inherited from HTMLAttributes) does NOT appear — also good, the
497
+ * panel stays focused on what the author wanted to expose. Hosts
498
+ * who want a specific inherited prop surfaced can re-declare it
499
+ * locally or use the sidecar `cmsConfig.props` override.
500
+ */
501
+ function collectLocalProperties(iface) {
502
+ return iface.getProperties();
503
+ }
504
+ /**
505
+ * Type-alias variant. For `type Props = { ... }`, the declaration
506
+ * node is a TypeLiteralNode and we read its own member list. For
507
+ * intersections (`type Props = A & { ... }`) or imported aliases,
508
+ * we get an empty list rather than walking into the constituent
509
+ * types — same author-intent rationale as the interface case.
510
+ */
511
+ function collectAliasProperties(alias) {
512
+ const members = alias.getTypeNode()?.getMembers?.();
513
+ if (!members) return [];
514
+ return members.filter((m) => m.getKindName() === "PropertySignature");
515
+ }
516
+ /**
517
+ * Map a resolved `Type` to a `ParsedProp`. Mirrors the kind of
518
+ * branching the old regex did, but on real type information.
519
+ */
520
+ function parseType(name, type, required) {
521
+ if (type.isString()) return {
522
+ name,
523
+ type: "string",
524
+ required
525
+ };
526
+ if (type.isNumber()) return {
527
+ name,
528
+ type: "number",
529
+ required
530
+ };
531
+ if (type.isBoolean()) return {
532
+ name,
533
+ type: "boolean",
534
+ required
535
+ };
536
+ if (type.isUnion()) {
537
+ const nonUndefined = type.getUnionTypes().filter((m) => !m.isUndefined());
538
+ if (nonUndefined.length > 0 && nonUndefined.every((m) => m.isBooleanLiteral() || m.isBoolean())) return {
539
+ name,
540
+ type: "boolean",
541
+ required
542
+ };
543
+ const stringLiterals = nonUndefined.filter((m) => m.isStringLiteral()).map((m) => m.getLiteralValue()).filter((v) => typeof v === "string");
544
+ if (stringLiterals.length > 0) return {
545
+ name,
546
+ type: "string",
547
+ required,
548
+ options: stringLiterals
549
+ };
550
+ if (nonUndefined.length === 1) {
551
+ const only = nonUndefined[0];
552
+ if (only.isString()) return {
553
+ name,
554
+ type: "string",
555
+ required
556
+ };
557
+ if (only.isNumber()) return {
558
+ name,
559
+ type: "number",
560
+ required
561
+ };
562
+ if (only.isBoolean()) return {
563
+ name,
564
+ type: "boolean",
565
+ required
566
+ };
567
+ if (only.isStringLiteral()) {
568
+ const v = only.getLiteralValue();
569
+ return {
570
+ name,
571
+ type: "string",
572
+ required,
573
+ options: typeof v === "string" ? [v] : void 0
574
+ };
575
+ }
576
+ }
577
+ }
578
+ if (type.isStringLiteral()) {
579
+ const v = type.getLiteralValue();
580
+ return {
581
+ name,
582
+ type: "string",
583
+ required,
584
+ options: typeof v === "string" ? [v] : void 0
585
+ };
586
+ }
587
+ if (type.isBooleanLiteral()) return {
588
+ name,
589
+ type: "boolean",
590
+ required
591
+ };
592
+ return {
593
+ name,
594
+ type: "expression",
595
+ required
596
+ };
597
+ }
598
+ //#endregion
599
+ //#region src/discovery/scan-components.ts
600
+ /**
601
+ * Scan every `.astro` / `.tsx` file under each configured folder.
602
+ * Folder globs are resolved relative to `projectRoot`.
603
+ */
604
+ async function scanLocalComponents(folders, projectRoot) {
605
+ if (folders.length === 0) return [];
606
+ const sourcePatterns = folders.map((f) => `${f.replace(/\/+$/, "")}/**/*.{astro,tsx}`);
607
+ const dtsPatterns = folders.map((f) => `${f.replace(/\/+$/, "")}/**/*.d.ts`);
608
+ const sourceFiles = await fg(sourcePatterns, {
609
+ cwd: projectRoot,
610
+ absolute: true,
611
+ dot: false
612
+ });
613
+ const dtsFiles = await fg(dtsPatterns, {
614
+ cwd: projectRoot,
615
+ absolute: true,
616
+ dot: false
617
+ });
618
+ const seen = /* @__PURE__ */ new Set();
619
+ const allFiles = [];
620
+ for (const file of sourceFiles) {
621
+ const name = componentNameFromPath(file);
622
+ if (seen.has(name)) continue;
623
+ seen.add(name);
624
+ allFiles.push(file);
625
+ }
626
+ for (const file of dtsFiles) {
627
+ const name = componentNameFromPath(file);
628
+ if (seen.has(name)) continue;
629
+ seen.add(name);
630
+ allFiles.push(file);
631
+ }
632
+ const project = createScanProject(findTsConfig(projectRoot));
633
+ const results = [];
634
+ for (const file of allFiles) try {
635
+ const r = await scanFile$1(file, projectRoot, project);
636
+ if (r) results.push(r);
637
+ } catch (err) {
638
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
639
+ }
640
+ return results;
641
+ }
642
+ async function scanFile$1(filepath, projectRoot, project) {
643
+ const content = await readFile(filepath, "utf8");
644
+ const name = componentNameFromPath(filepath);
645
+ if (!/^[A-Z]/.test(name)) return null;
646
+ const props = extractPropsForFile(project, filepath, content, name);
647
+ return {
648
+ filepath,
649
+ name,
650
+ source: filepath,
651
+ importSpecifier: `/${relative(projectRoot, filepath).replace(/\\/g, "/")}`,
652
+ kind: "flow",
653
+ props
654
+ };
655
+ }
656
+ /**
657
+ * Bridge between the file-level scanner and the ts-morph extractor.
658
+ * Handles the three file types we accept:
659
+ * - `.astro` — extract the `---`-fenced frontmatter, feed it as
660
+ * a virtual `.ts` source.
661
+ * - `.tsx` / `.d.ts` — feed the whole file content directly.
662
+ *
663
+ * The virtual source path is the real filepath suffixed with
664
+ * `.virtual.ts` for `.astro` files, so ts-morph's diagnostics still
665
+ * point back at the right author file. For `.tsx` / `.d.ts` we use
666
+ * the real path verbatim — ts-morph parses TS extensions natively.
667
+ */
668
+ function extractPropsForFile(project, filepath, content, componentName) {
669
+ if (filepath.endsWith(".astro")) {
670
+ const frontmatter = extractAstroFrontmatter(content);
671
+ if (!frontmatter) return [];
672
+ return extractPropsViaTs(project, `${filepath}.virtual.ts`, frontmatter, componentName);
673
+ }
674
+ return extractPropsViaTs(project, filepath, content, componentName);
675
+ }
676
+ /**
677
+ * Locate the host's `tsconfig.json` so the ts-morph Project can
678
+ * resolve cross-file `typeof` refs, path aliases, and node_modules
679
+ * declarations the same way the author's IDE does. Walks up from
680
+ * `projectRoot` looking for the closest tsconfig; returns `undefined`
681
+ * if none found (the Project then uses permissive defaults).
682
+ */
683
+ function findTsConfig(projectRoot) {
684
+ const candidate = resolve(projectRoot, "tsconfig.json");
685
+ return existsSync(candidate) ? candidate : void 0;
686
+ }
687
+ /**
688
+ * Derive the canonical component name from a file path.
689
+ *
690
+ * Two extension shapes:
691
+ * - Single (`.astro`, `.tsx`) → strip with `extname`/`basename`.
692
+ * - Compound (`.d.ts`) → strip `.d.ts` explicitly, since `extname`
693
+ * would return only `.ts` and leave a trailing `.d` (`Card.d`).
694
+ *
695
+ * Keeps the rule simple and consistent: file basename === component
696
+ * name. Multi-component files (a `.d.ts` exporting many React
697
+ * components from one barrel) are NOT supported through this path —
698
+ * the sidecar `cmsConfig` mechanism (future task) covers those.
699
+ */
700
+ function componentNameFromPath(filepath) {
701
+ const base = basename(filepath);
702
+ if (base.endsWith(".d.ts")) return base.slice(0, -5);
703
+ return base.slice(0, -extname(base).length);
704
+ }
705
+ /**
706
+ * Scan every npm-style import source referenced in the MDX usage scan
707
+ * and treat any `.astro` / `.tsx` file inside the resolved package as a
708
+ * candidate component. Resolves each unique specifier via Node's
709
+ * `require.resolve` (run from `projectRoot` so packages are looked up
710
+ * in the consumer's `node_modules`, not ours), walks up to the package
711
+ * root, then globs the package for component-shaped files.
712
+ *
713
+ * The returned `source` on each result is the ORIGINAL specifier from
714
+ * the MDX import (e.g. `@astrojs/starlight/components`) — not the
715
+ * resolved file path. That's what makes the merge work: `scan-mdx`
716
+ * records imports by their literal source string, so for the merge
717
+ * registry to dedupe local-folder scan ⨯ MDX-usage scan we need both
718
+ * sides to key on the same specifier. Vite's `ssrLoadModule` handles
719
+ * the specifier itself at render time, so we don't need an absolute
720
+ * file path on the descriptor.
721
+ *
722
+ * Caveats:
723
+ * - Specifiers that look like local paths (`./foo`, `/abs/path`) are
724
+ * intentionally skipped here — those are local components, already
725
+ * covered by `scanLocalComponents`.
726
+ * - One specifier per package: if a package is imported via two
727
+ * different specifiers (`@pkg/components` and `@pkg`), we'll scan
728
+ * it twice and emit two descriptor sets keyed on each specifier.
729
+ * The merge layer's collision resolution picks the one with more
730
+ * real usage, so this is self-correcting in practice.
731
+ * - We cap glob depth at 4 to avoid walking into deeply-nested
732
+ * library internals (most component packages put their exports
733
+ * near the root). Components nested deeper won't surface; hosts
734
+ * can either re-export them at a shallower path or add a sidecar
735
+ * `cmsConfig` (when sidecar support lands).
736
+ */
737
+ async function scanExternalComponents(mdxScans, projectRoot) {
738
+ const specifiers = collectExternalSpecifiers(mdxScans);
739
+ if (specifiers.size === 0) return [];
740
+ const project = createScanProject(findTsConfig(projectRoot));
741
+ const results = [];
742
+ const requireFromProject = createRequire(`${projectRoot.replace(/\/$/, "")}/package.json`);
743
+ for (const specifier of specifiers) try {
744
+ const resolved = requireFromProject.resolve(specifier);
745
+ const packageRoot = findPackageRoot(resolved);
746
+ if (!packageRoot) continue;
747
+ const barrelFiles = await collectBarrelExports(resolved, packageRoot);
748
+ let scanFiles;
749
+ if (barrelFiles.length > 0) scanFiles = barrelFiles;
750
+ else {
751
+ const sourceFiles = await fg("**/*.{astro,tsx}", {
752
+ cwd: packageRoot,
753
+ absolute: true,
754
+ dot: false,
755
+ deep: 4
756
+ });
757
+ const dtsFiles = await fg("**/*.d.ts", {
758
+ cwd: packageRoot,
759
+ absolute: true,
760
+ dot: false,
761
+ deep: 4
762
+ });
763
+ const seen = /* @__PURE__ */ new Set();
764
+ scanFiles = [];
765
+ for (const file of [...sourceFiles, ...dtsFiles]) {
766
+ const name = componentNameFromPath(file);
767
+ if (seen.has(name)) continue;
768
+ seen.add(name);
769
+ scanFiles.push(file);
770
+ }
771
+ }
772
+ for (const file of scanFiles) try {
773
+ const r = await scanExternalFile(file, specifier, project);
774
+ if (r) results.push(r);
775
+ } catch (err) {
776
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
777
+ }
778
+ } catch (err) {
779
+ console.warn(`[conloca:discovery] could not resolve '${specifier}' from ${projectRoot}:`, err instanceof Error ? err.message : err);
780
+ }
781
+ return results;
782
+ }
783
+ /**
784
+ * Same parsing as `scanFile`, but with `source` set to the original
785
+ * npm specifier instead of the absolute file path. See the function
786
+ * doc on `scanExternalComponents` for why.
787
+ */
788
+ async function scanExternalFile(filepath, specifier, project) {
789
+ const content = await readFile(filepath, "utf8");
790
+ const name = componentNameFromPath(filepath);
791
+ if (!/^[A-Z]/.test(name)) return null;
792
+ return {
793
+ filepath,
794
+ name,
795
+ source: specifier,
796
+ importSpecifier: specifier,
797
+ kind: "flow",
798
+ props: extractPropsForFile(project, filepath, content, name)
799
+ };
800
+ }
801
+ /**
802
+ * Pick out unique npm-style specifiers from every import seen in the
803
+ * MDX scan. Local paths (`./foo`, `/abs`) are dropped — `scanLocalComponents`
804
+ * covers those via its folder glob.
805
+ */
806
+ function collectExternalSpecifiers(mdxScans) {
807
+ const out = /* @__PURE__ */ new Set();
808
+ for (const scan of mdxScans) for (const imp of Object.values(scan.imports)) {
809
+ const src = imp.source;
810
+ if (!src) continue;
811
+ if (src.startsWith(".") || src.startsWith("/")) continue;
812
+ out.add(src);
813
+ }
814
+ return out;
815
+ }
816
+ /**
817
+ * If `resolvedFile` is a barrel (re-export aggregator), return the
818
+ * absolute paths of every re-exported component file. Otherwise
819
+ * return an empty array.
820
+ *
821
+ * Patterns recognized:
822
+ * - `export { default as Foo } from './path/to/Foo.astro'`
823
+ * - `export { Foo } from './path/to/Foo'`
824
+ * - `export { Foo, Bar } from './path/to/m'`
825
+ * - `export * from './path/to/m'` (treated as opaque — we
826
+ * can't enumerate the
827
+ * names without a real
828
+ * parser, so we skip and
829
+ * fall back to glob-all)
830
+ *
831
+ * The barrel must resolve to a real file we can re-resolve to one of
832
+ * the supported extensions (`.astro`, `.tsx`, `.d.ts`). Missing or
833
+ * unsupported targets are dropped quietly. Comments are stripped
834
+ * first to avoid matching commented-out exports.
835
+ *
836
+ * Why this matters: Starlight's `@astrojs/starlight/components`
837
+ * barrel lists exactly the 12 MDX-friendly components. Globbing the
838
+ * whole package would also pull in ~30 internal layout components
839
+ * (Banner, Hero, Pagination, ...) — they'd litter the slash menu
840
+ * even though they're not meant for author use.
841
+ */
842
+ async function collectBarrelExports(resolvedFile, packageRoot) {
843
+ if (!/\.(?:m?[jt]s)$/.test(resolvedFile)) return [];
844
+ let content;
845
+ try {
846
+ content = await readFile(resolvedFile, "utf8");
847
+ } catch {
848
+ return [];
849
+ }
850
+ const cleaned = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
851
+ const pathRe = /export\s*(?:\{[^}]*\}|\*)\s*from\s*['"]([^'"]+)['"]/g;
852
+ const relPaths = /* @__PURE__ */ new Set();
853
+ for (const m of cleaned.matchAll(pathRe)) {
854
+ const rel = m[1];
855
+ if (!rel) continue;
856
+ relPaths.add(rel);
857
+ }
858
+ if (relPaths.size === 0) return [];
859
+ const requireFromBarrel = createRequire(`${dirname(resolvedFile)}/_.js`);
860
+ const resolved = [];
861
+ for (const rel of relPaths) try {
862
+ const target = requireFromBarrel.resolve(rel);
863
+ if (!/\.(?:astro|tsx|d\.ts)$/.test(target)) continue;
864
+ if (!target.startsWith(packageRoot)) continue;
865
+ resolved.push(target);
866
+ } catch {}
867
+ return resolved;
868
+ }
869
+ /**
870
+ * Walk up from a resolved file path until we find the directory that
871
+ * contains the closest `package.json`. That's the package root we'll
872
+ * glob for component files. Returns `null` if no package.json is found
873
+ * within a reasonable depth (defensive — shouldn't happen for a real
874
+ * resolution).
875
+ */
876
+ function findPackageRoot(resolvedPath) {
877
+ let dir = dirname(resolvedPath);
878
+ for (let i = 0; i < 10; i++) {
879
+ if (existsSync(`${dir}/package.json`)) return dir;
880
+ const parent = dirname(dir);
881
+ if (parent === dir) return null;
882
+ dir = parent;
883
+ }
884
+ return null;
885
+ }
886
+ //#endregion
887
+ //#region src/discovery/scan-mdx.ts
888
+ /**
889
+ * Scan every `.mdx` file under `rootDir` (recursive). Returns one
890
+ * result per file. Files that fail to parse are skipped with a
891
+ * warning rather than throwing — the discovery flow shouldn't take
892
+ * down the dev server on a single broken file.
893
+ */
894
+ async function scanMdxFiles(rootDir) {
895
+ const files = await fg("**/*.mdx", {
896
+ cwd: rootDir,
897
+ absolute: true,
898
+ dot: false
899
+ });
900
+ const results = [];
901
+ for (const file of files) try {
902
+ results.push(await scanFile(file));
903
+ } catch (err) {
904
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
905
+ }
906
+ return results;
907
+ }
908
+ async function scanFile(filepath) {
909
+ const tree = fromMarkdown(await readFile(filepath, "utf8"), {
910
+ extensions: [mdxjs()],
911
+ mdastExtensions: [mdxFromMarkdown()]
912
+ });
913
+ const imports = {};
914
+ const usages = [];
915
+ walk(tree, (node) => {
916
+ if (isEsmNode(node)) collectImports(node, imports);
917
+ else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
918
+ const name = typeof node.name === "string" ? node.name : "";
919
+ if (!name) return;
920
+ const attrs = {};
921
+ const rawAttrs = node.attributes ?? [];
922
+ for (const a of rawAttrs) {
923
+ if (a.type !== "mdxJsxAttribute" || typeof a.name !== "string") continue;
924
+ if (typeof a.value === "string") attrs[a.name] = a.value;
925
+ }
926
+ usages.push({
927
+ name,
928
+ attrs,
929
+ kind: node.type === "mdxJsxFlowElement" ? "flow" : "text"
930
+ });
931
+ }
932
+ });
933
+ return {
934
+ filepath,
935
+ imports,
936
+ usages
937
+ };
938
+ }
939
+ function isEsmNode(node) {
940
+ return node.type === "mdxjsEsm";
941
+ }
942
+ function collectImports(esmNode, out) {
943
+ const estree = esmNode.data?.estree;
944
+ if (!estree?.body) return;
945
+ for (const stmt of estree.body) {
946
+ if (stmt.type !== "ImportDeclaration") continue;
947
+ const source = stmt.source?.value;
948
+ if (typeof source !== "string") continue;
949
+ for (const spec of stmt.specifiers ?? []) {
950
+ const local = spec.local?.name;
951
+ if (typeof local !== "string") continue;
952
+ if (spec.type === "ImportDefaultSpecifier") out[local] = {
953
+ source,
954
+ defaultExport: true,
955
+ exportName: "default"
956
+ };
957
+ else if (spec.type === "ImportSpecifier") {
958
+ const exportName = spec.imported?.type === "Identifier" ? spec.imported.name : typeof spec.imported?.value === "string" ? spec.imported.value : local;
959
+ out[local] = {
960
+ source,
961
+ defaultExport: false,
962
+ exportName: exportName ?? local,
963
+ ...exportName && exportName !== local ? { aliasedFrom: exportName } : {}
964
+ };
965
+ }
966
+ }
967
+ }
968
+ }
969
+ /** Depth-first walk; visits every node including the root. */
970
+ function walk(node, fn) {
971
+ fn(node);
972
+ if (Array.isArray(node.children)) {
973
+ for (const child of node.children) if (child && typeof child === "object") walk(child, fn);
974
+ }
975
+ }
976
+ //#endregion
977
+ //#region src/discovery/scan-overrides.ts
978
+ /**
979
+ * Read every `*.cms.json` file under `folder` (recursive) and return
980
+ * the parsed overrides keyed by basename (`Card.cms.json` → `Card`).
981
+ *
982
+ * Failures are skipped with a warning — a broken JSON file shouldn't
983
+ * take down the rest of the registry build. The folder being empty
984
+ * (or not existing) returns an empty map silently; that's the
985
+ * common zero-config case where the host hasn't added any
986
+ * overrides yet.
987
+ */
988
+ async function loadCmsOverrides(folder, projectRoot) {
989
+ const out = /* @__PURE__ */ new Map();
990
+ if (!folder) return out;
991
+ const files = await fg(`${folder.replace(/\/+$/, "")}/**/*.cms.json`, {
992
+ cwd: projectRoot,
993
+ absolute: true,
994
+ dot: false
995
+ });
996
+ for (const file of files) try {
997
+ const content = await readFile(file, "utf8");
998
+ const parsed = JSON.parse(content);
999
+ const name = basename(file).slice(0, -9);
1000
+ out.set(name, parsed);
1001
+ } catch (err) {
1002
+ console.warn(`[conloca:discovery] failed to load override ${file}:`, err instanceof Error ? err.message : err);
1003
+ }
1004
+ return out;
1005
+ }
1006
+ //#endregion
1007
+ //#region src/discovery/registry-endpoint.ts
1008
+ function createRegistryEndpoint(options) {
1009
+ const projectRoot = options.projectRoot ?? process.cwd();
1010
+ const contentRoot = resolve(projectRoot, options.contentRoot);
1011
+ let cached = null;
1012
+ const compute = () => {
1013
+ if (cached) return cached;
1014
+ cached = (async () => {
1015
+ const mdxScans = await scanMdxFiles(contentRoot);
1016
+ const overridesFolder = options.overridesFolder ?? "src/cms-overrides";
1017
+ const [localComponents, externalComponents, overrides] = await Promise.all([
1018
+ scanLocalComponents(options.componentFolders, projectRoot),
1019
+ scanExternalComponents(mdxScans, projectRoot),
1020
+ loadCmsOverrides(overridesFolder, projectRoot)
1021
+ ]);
1022
+ return mergeRegistry(mdxScans, [...externalComponents, ...localComponents], overrides);
1023
+ })();
1024
+ return cached;
1025
+ };
1026
+ const handler = async (req, res, _next) => {
1027
+ try {
1028
+ const components = await compute();
1029
+ res.statusCode = 200;
1030
+ res.setHeader("content-type", "application/json; charset=utf-8");
1031
+ res.setHeader("cache-control", "no-store");
1032
+ res.end(JSON.stringify({ components }));
1033
+ } catch (err) {
1034
+ const message = err instanceof Error ? err.message : String(err);
1035
+ console.warn("[conloca:discovery] registry endpoint failed:", message);
1036
+ res.statusCode = 500;
1037
+ res.setHeader("content-type", "application/json; charset=utf-8");
1038
+ res.end(JSON.stringify({ error: message }));
1039
+ }
1040
+ };
1041
+ return {
1042
+ handler,
1043
+ invalidate: () => {
1044
+ cached = null;
1045
+ },
1046
+ /**
1047
+ * Set of import sources the render endpoint is allowed to load.
1048
+ *
1049
+ * Reuses the same memoized scan as `handler`, so the allowlist stays
1050
+ * in sync with the registry the SPA sees — invalidation in one place
1051
+ * invalidates both. Failing closed (returning an empty set) on scan
1052
+ * error is intentional: better to refuse all renders than to fall
1053
+ * back to "trust the request body".
1054
+ */
1055
+ getAllowedSources: async () => {
1056
+ try {
1057
+ const components = await compute();
1058
+ const sources = /* @__PURE__ */ new Set();
1059
+ for (const c of components) if (c.import?.from) sources.add(c.import.from);
1060
+ return sources;
1061
+ } catch {
1062
+ return /* @__PURE__ */ new Set();
1063
+ }
1064
+ }
1065
+ };
1066
+ }
1067
+ //#endregion
8
1068
  //#region src/lib/routing-config.ts
9
1069
  /**
10
1070
  * Normalize routing config input to full RoutingConfig.
@@ -59,7 +1119,547 @@ function resolveRouteConfig(config) {
59
1119
  dataBindings: config.dataBindings ?? { collections: [] }
60
1120
  };
61
1121
  }
62
-
1122
+ //#endregion
1123
+ //#region src/site-styles/content-wrapper-endpoint.ts
1124
+ function createContentWrapperEndpoint() {
1125
+ return async (req, res, _next) => {
1126
+ try {
1127
+ const routeUrl = new URL(req.url ?? "", "http://localhost").searchParams.get("url");
1128
+ if (!routeUrl) {
1129
+ res.statusCode = 400;
1130
+ res.setHeader("content-type", "text/plain");
1131
+ res.end("Missing required query parameter: url");
1132
+ return;
1133
+ }
1134
+ const host = req.headers.host ?? "localhost:4321";
1135
+ const liveUrl = `${req.headers["x-forwarded-proto"] ?? "http"}://${host}${routeUrl}`;
1136
+ const wrappers = findContentWrapper(await fetch(liveUrl, { headers: req.headers.cookie ? { cookie: req.headers.cookie } : void 0 }).then((r) => r.text()));
1137
+ res.statusCode = 200;
1138
+ res.setHeader("content-type", "application/json; charset=utf-8");
1139
+ res.setHeader("cache-control", "no-store");
1140
+ res.end(JSON.stringify(wrappers));
1141
+ } catch (err) {
1142
+ res.statusCode = 500;
1143
+ res.setHeader("content-type", "text/plain");
1144
+ res.end(`Content-wrapper discovery failed: ${err instanceof Error ? err.message : String(err)}`);
1145
+ }
1146
+ };
1147
+ }
1148
+ /** Tags whose presence signals "this element holds prose content."
1149
+ * We walk up from the first such element we find inside `<main>` to
1150
+ * locate the wrapper. Headings + paragraphs cover every prose-styling
1151
+ * convention we've seen — every CSS framework scopes typography
1152
+ * through descendant selectors on `h1`–`h6` and `p`. */
1153
+ const PROSE_TAGS = /* @__PURE__ */ new Set([
1154
+ "h1",
1155
+ "h2",
1156
+ "h3",
1157
+ "h4",
1158
+ "h5",
1159
+ "h6",
1160
+ "p"
1161
+ ]);
1162
+ /** Tag that anchors code-block wrapper discovery. The host's code-
1163
+ * block library (Starlight's expressive-code, Tailwind's `pre`
1164
+ * styling, etc.) always renders a `<pre>` containing the code,
1165
+ * often wrapped in additional classed elements. */
1166
+ const CODE_BLOCK_ANCHOR = "pre";
1167
+ /** HTML5 void elements — never push onto the open-tag stack since they
1168
+ * have no closing tag. */
1169
+ const VOID_TAGS = /* @__PURE__ */ new Set([
1170
+ "area",
1171
+ "base",
1172
+ "br",
1173
+ "col",
1174
+ "embed",
1175
+ "hr",
1176
+ "img",
1177
+ "input",
1178
+ "link",
1179
+ "meta",
1180
+ "source",
1181
+ "track",
1182
+ "wbr"
1183
+ ]);
1184
+ /**
1185
+ * Locate the host's content + code-block wrappers in raw HTML. Single-
1186
+ * pass regex walk with a stack so we can recover ancestor chains for
1187
+ * both prose tags and `<pre>` tags without a full DOM parser dep.
1188
+ *
1189
+ * Exported for unit testing.
1190
+ */
1191
+ function findContentWrapper(html) {
1192
+ const cleaned = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "");
1193
+ const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*)?)\s*(\/?)>/g;
1194
+ const stack = [];
1195
+ let explicit = null;
1196
+ let mainEl = null;
1197
+ const proseAncestorChains = [];
1198
+ const preAncestorChains = [];
1199
+ let match;
1200
+ while ((match = tagRe.exec(cleaned)) !== null) {
1201
+ const isClose = match[1] === "/";
1202
+ const tagName = match[2].toLowerCase();
1203
+ const attrBlob = match[3] ?? "";
1204
+ const explicitlySelfClosing = match[4] === "/";
1205
+ if (isClose) {
1206
+ for (let i = stack.length - 1; i >= 0; i--) if (stack[i].tag === tagName) {
1207
+ stack.length = i;
1208
+ break;
1209
+ }
1210
+ continue;
1211
+ }
1212
+ const attrs = parseAttributes(attrBlob);
1213
+ const className = attrs.class ?? "";
1214
+ const el = {
1215
+ tag: tagName,
1216
+ className,
1217
+ attrs
1218
+ };
1219
+ if (!explicit && "data-conloca-content-root" in attrs) explicit = {
1220
+ tagName,
1221
+ className
1222
+ };
1223
+ if (!mainEl && tagName === "main") mainEl = el;
1224
+ if (mainEl && PROSE_TAGS.has(tagName)) {
1225
+ const mainIdx = stack.indexOf(mainEl);
1226
+ if (mainIdx >= 0) proseAncestorChains.push(stack.slice(mainIdx + 1));
1227
+ }
1228
+ if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
1229
+ const mainIdx = stack.indexOf(mainEl);
1230
+ if (mainIdx >= 0) preAncestorChains.push(stack.slice(mainIdx + 1));
1231
+ }
1232
+ if (!VOID_TAGS.has(tagName) && !explicitlySelfClosing) stack.push(el);
1233
+ }
1234
+ const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
1235
+ return {
1236
+ content,
1237
+ codeBlock: resolveCodeBlockWrapper(content, preAncestorChains)
1238
+ };
1239
+ }
1240
+ /**
1241
+ * Pick the content wrapper from the walk's collected data.
1242
+ *
1243
+ * Priority: explicit opt-in > majority-prose-wrapper-inside-main >
1244
+ * `<main>` fallback > null.
1245
+ */
1246
+ function resolveContentWrapper(explicit, mainEl, proseAncestorChains) {
1247
+ if (explicit) return explicit;
1248
+ if (!mainEl) return null;
1249
+ if (proseAncestorChains.length === 0) return {
1250
+ tagName: "main",
1251
+ className: mainEl.className
1252
+ };
1253
+ const scores = /* @__PURE__ */ new Map();
1254
+ for (const chain of proseAncestorChains) for (const ancestor of chain) {
1255
+ if (!ancestor.className) continue;
1256
+ scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
1257
+ }
1258
+ const threshold = proseAncestorChains.length / 2;
1259
+ const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
1260
+ if (candidates.length === 0) return {
1261
+ tagName: "main",
1262
+ className: mainEl.className
1263
+ };
1264
+ const maxChainIndex = (el) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
1265
+ candidates.sort((a, b) => {
1266
+ if (b[1] !== a[1]) return b[1] - a[1];
1267
+ return maxChainIndex(b[0]) - maxChainIndex(a[0]);
1268
+ });
1269
+ const winner = candidates[0][0];
1270
+ return {
1271
+ tagName: winner.tag,
1272
+ className: winner.className
1273
+ };
1274
+ }
1275
+ /**
1276
+ * Derive the code-block wrapper chain from a representative `<pre>`'s
1277
+ * ancestor chain. We strip everything at or above the content wrapper
1278
+ * (its styles are already handled by the content-wrapper mirror) and
1279
+ * return the remaining classed elements in nesting order, outermost
1280
+ * first.
1281
+ *
1282
+ * Returning a chain (instead of one collapsed element) preserves the
1283
+ * shape host CSS expects:
1284
+ *
1285
+ * - Single-class selectors (`.frame { ... }`) hit on whichever link
1286
+ * carries that class.
1287
+ * - Descendant selectors (`.expressive-code .frame { ... }`,
1288
+ * `.frame .header > .title`) hit because the editor's renderer
1289
+ * materialises the chain as nested elements with the host's
1290
+ * expected tag names.
1291
+ *
1292
+ * The editor's code-block frame component (`code-block-frame.tsx` in
1293
+ * `@conloca/mdx`) treats the LAST link as the "frame" element (where
1294
+ * figcaption/pre/copy children render) and wraps it with the earlier
1295
+ * links from inside out. This matches the host's authoring shape for
1296
+ * libraries like ExpressiveCode (`.expressive-code > figure.frame >
1297
+ * figcaption + pre + .copy`).
1298
+ */
1299
+ function resolveCodeBlockWrapper(content, preAncestorChains) {
1300
+ if (preAncestorChains.length === 0) return null;
1301
+ const chain = preAncestorChains[0];
1302
+ const contentIdx = content ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className) : -1;
1303
+ const classedAncestors = chain.slice(contentIdx + 1).filter((el) => el.className);
1304
+ if (classedAncestors.length === 0) return null;
1305
+ return classedAncestors.map((el) => ({
1306
+ tagName: el.tag,
1307
+ className: el.className
1308
+ }));
1309
+ }
1310
+ /**
1311
+ * Parse the attribute blob inside an opening tag. Handles `name="v"`,
1312
+ * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
1313
+ * handle entity decoding (`&amp;` → `&`) since the values we read
1314
+ * (tag name, class list, the marker attribute) don't carry entities
1315
+ * in practice.
1316
+ */
1317
+ function parseAttributes(s) {
1318
+ const out = {};
1319
+ const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
1320
+ let m;
1321
+ while ((m = re.exec(s)) !== null) {
1322
+ const name = m[1];
1323
+ out[name] = m[2] ?? m[3] ?? m[4] ?? "";
1324
+ }
1325
+ return out;
1326
+ }
1327
+ //#endregion
1328
+ //#region src/site-styles/render-endpoint.ts
1329
+ /**
1330
+ * Vite middleware that renders an MDX JSX subtree to HTML on demand.
1331
+ *
1332
+ * Container components (CardGrid, Tabs, …) have JSX children that on
1333
+ * the published page render as direct DOM children of the parent —
1334
+ * positional CSS (`:nth-child` colour cycling on Card grids, CSS-grid
1335
+ * placement) depends on that DOM shape. Per-block isolated rendering
1336
+ * breaks both: each child gets its own wrapper, and the parent's only
1337
+ * direct child is a slot marker.
1338
+ *
1339
+ * This endpoint renders a recursive tree: each node provides its
1340
+ * component name + source + props, optionally with its own `children`
1341
+ * tree. The server renders leaves first and assembles parents by
1342
+ * passing rendered children HTML as the parent's default slot, so the
1343
+ * final markup matches what Astro would emit for the same MDX
1344
+ * source — same DOM, same CSS context.
1345
+ *
1346
+ * Request shape (JSON body):
1347
+ * {
1348
+ * tree: {
1349
+ * component: string,
1350
+ * source: string,
1351
+ * defaultExport?: boolean,
1352
+ * props?: Record<string, unknown>,
1353
+ * slotId: string,
1354
+ * children?: RenderTreeNode[]
1355
+ * },
1356
+ * documentIndex?: number // wraps top-level output to fix
1357
+ * // sibling-position CSS for root-level
1358
+ * // blocks (see phantom-sibling fix).
1359
+ * }
1360
+ *
1361
+ * Legacy shape (kept for backward compatibility):
1362
+ * { component, source, defaultExport?, props?, documentIndex? }
1363
+ *
1364
+ * For each node, the rendered slot content is either:
1365
+ * - The concatenated HTML of recursively-rendered children, if any.
1366
+ * - `<conloca-slot data-slot-id="<id>"></conloca-slot>` placeholder
1367
+ * otherwise (the SPA portals a Lexical editor into it).
1368
+ *
1369
+ * Returns 200 with `Content-Type: text/html` on success; 4xx with a
1370
+ * plain-text error otherwise.
1371
+ */
1372
+ function createRenderEndpoint(server, getAllowedSources) {
1373
+ let containerPromise = null;
1374
+ const getContainer = () => {
1375
+ if (!containerPromise) containerPromise = experimental_AstroContainer.create();
1376
+ return containerPromise;
1377
+ };
1378
+ return async (req, res, _next) => {
1379
+ if (req.method !== "POST") {
1380
+ res.statusCode = 405;
1381
+ res.setHeader("content-type", "text/plain");
1382
+ res.end("Method not allowed");
1383
+ return;
1384
+ }
1385
+ try {
1386
+ const body = await readJson(req);
1387
+ const tree = body.tree ?? {
1388
+ component: body.component ?? "",
1389
+ source: body.source ?? "",
1390
+ defaultExport: body.defaultExport,
1391
+ props: body.props,
1392
+ slotId: "root"
1393
+ };
1394
+ if (!tree.component || !tree.source) {
1395
+ res.statusCode = 400;
1396
+ res.setHeader("content-type", "text/plain");
1397
+ res.end("Missing required fields: tree.component, tree.source");
1398
+ return;
1399
+ }
1400
+ const disallowed = collectDisallowedSources(tree, await getAllowedSources());
1401
+ if (disallowed.length > 0) {
1402
+ res.statusCode = 400;
1403
+ res.setHeader("content-type", "text/plain");
1404
+ res.end(`source not in registry: ${disallowed.join(", ")}`);
1405
+ return;
1406
+ }
1407
+ const container = await getContainer();
1408
+ let rendered;
1409
+ try {
1410
+ rendered = await renderTree(tree, container, server);
1411
+ } catch (err) {
1412
+ console.warn(`[conloca:render] <${tree.component}> failed:`, err instanceof Error ? err.message : err);
1413
+ rendered = renderErrorStub(tree, err);
1414
+ }
1415
+ let html;
1416
+ if (body.inline) html = rendered;
1417
+ else {
1418
+ const documentIndex = body.documentIndex;
1419
+ const phantomCount = typeof documentIndex === "number" && documentIndex > 0 ? documentIndex - 1 : 0;
1420
+ html = `<div class="sl-markdown-content">${phantomCount > 0 ? "<span hidden aria-hidden=\"true\"></span>".repeat(phantomCount) : ""}${rendered}</div>`;
1421
+ }
1422
+ res.statusCode = 200;
1423
+ res.setHeader("content-type", "text/html; charset=utf-8");
1424
+ res.setHeader("cache-control", "no-store");
1425
+ res.end(html);
1426
+ } catch (err) {
1427
+ res.statusCode = 500;
1428
+ res.setHeader("content-type", "text/plain");
1429
+ res.end(`Render failed: ${err instanceof Error ? err.message : String(err)}`);
1430
+ }
1431
+ };
1432
+ }
1433
+ async function renderTree(node, container, server) {
1434
+ const module = await server.ssrLoadModule(node.source);
1435
+ const exportKey = node.defaultExport ? "default" : node.component;
1436
+ const factory = module[exportKey];
1437
+ if (typeof factory !== "function") throw new Error(`Component '${node.component}' not found at '${node.source}' (export '${exportKey}')`);
1438
+ let slotContent;
1439
+ if (node.children && node.children.length > 0) slotContent = (await Promise.all(node.children.map(async (child) => {
1440
+ try {
1441
+ return await renderTree(child, container, server);
1442
+ } catch (err) {
1443
+ console.warn(`[conloca:render] <${child.component}> failed:`, err instanceof Error ? err.message : err);
1444
+ return renderErrorStub(child, err);
1445
+ }
1446
+ }))).join("");
1447
+ else if (node.bodyHtml) slotContent = node.bodyHtml;
1448
+ else {
1449
+ const fallback = node.body ?? "";
1450
+ slotContent = `<conloca-slot data-slot-id="${escapeHtml(node.slotId)}">${fallback}</conloca-slot>`;
1451
+ }
1452
+ const slots = {
1453
+ default: slotContent,
1454
+ ...node.namedSlots ?? {}
1455
+ };
1456
+ return container.renderToString(factory, {
1457
+ props: node.props,
1458
+ slots,
1459
+ locals: { t: defaultI18nFallback }
1460
+ });
1461
+ }
1462
+ /**
1463
+ * Build a self-contained, editable error stub for one render failure.
1464
+ *
1465
+ * Three jobs:
1466
+ * 1. Surface the error inline so the author sees *exactly* which
1467
+ * component blew up and why, right where it sits in the document.
1468
+ * No console-spelunking required.
1469
+ * 2. Keep the slot id intact so GenericBlock's portal-discovery loop
1470
+ * (`querySelectorAll('conloca-slot[data-slot-id]')`) still finds a
1471
+ * mount point inside the stub. The body editor mounts as normal;
1472
+ * the author can edit the children even though the parent
1473
+ * component's own render failed — typically that's enough to fix
1474
+ * whatever the validator was upset about.
1475
+ * 3. Stay structurally innocuous. A `<div>` wrapper renders cleanly
1476
+ * inside any parent slot that accepts arbitrary HTML, and a
1477
+ * data-attribute on the wrapper lets host CSS style it however
1478
+ * they like (yellow background, red border, whatever).
1479
+ *
1480
+ * Note: if the parent component itself has a strict-slot validator
1481
+ * (eg `<Tabs>` rejects non-TabItem children), the stub will fail the
1482
+ * parent's render too — but the recursion at the parent level then
1483
+ * catches THAT failure and emits its own stub one level up. The
1484
+ * worst case bubbles all the way to the top-level wrap in the
1485
+ * endpoint handler. Errors never escape as 500s.
1486
+ */
1487
+ function renderErrorStub(node, err) {
1488
+ const message = err instanceof Error ? err.message : String(err);
1489
+ const name = node.component || "unknown";
1490
+ return `<div class="conloca-render-error" data-component="${escapeHtml(name)}" data-slot-id="${escapeHtml(node.slotId)}" role="alert"><div class="conloca-render-error__label">&lt;${escapeHtml(name)}&gt; failed to render: ${escapeHtml(message)}</div><conloca-slot data-slot-id="${escapeHtml(node.slotId)}"></conloca-slot></div>`;
1491
+ }
1492
+ function collectDisallowedSources(node, allowed) {
1493
+ const bad = [];
1494
+ if (!allowed.has(node.source)) bad.push(node.source);
1495
+ if (node.children) for (const child of node.children) bad.push(...collectDisallowedSources(child, allowed));
1496
+ return bad;
1497
+ }
1498
+ function escapeHtml(s) {
1499
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1500
+ }
1501
+ function defaultI18nFallback(key) {
1502
+ const leaf = key.split(".").pop() ?? key;
1503
+ return leaf.charAt(0).toUpperCase() + leaf.slice(1);
1504
+ }
1505
+ async function readJson(req) {
1506
+ return new Promise((resolve, reject) => {
1507
+ let raw = "";
1508
+ req.setEncoding("utf8");
1509
+ req.on("data", (chunk) => {
1510
+ raw += chunk;
1511
+ });
1512
+ req.on("end", () => {
1513
+ try {
1514
+ resolve(raw ? JSON.parse(raw) : {});
1515
+ } catch (err) {
1516
+ reject(err instanceof Error ? err : /* @__PURE__ */ new Error("Invalid JSON"));
1517
+ }
1518
+ });
1519
+ req.on("error", reject);
1520
+ });
1521
+ }
1522
+ //#endregion
1523
+ //#region src/site-styles/styles-endpoint.ts
1524
+ /**
1525
+ * Vite middleware that returns the concatenated CSS for a route URL.
1526
+ *
1527
+ * Used by the CMS editor SPA to fetch the styles that apply to the page
1528
+ * being edited so the editor renders content with the same CSS as the
1529
+ * published page.
1530
+ *
1531
+ * Mechanism (host-agnostic):
1532
+ *
1533
+ * 1. HTTP-fetch the live HTML at the route URL from the running dev
1534
+ * server. This is the same HTML a browser would receive — it lists
1535
+ * every stylesheet the page actually loads.
1536
+ * 2. Pull the content of every `<style>...</style>` block (where dev-
1537
+ * mode Astro inlines its component / Tailwind / user CSS).
1538
+ * 3. Pull every `<link rel="stylesheet" href="…">` (excluding
1539
+ * `media="print"`) and fetch each one with `?direct` so the dev
1540
+ * server returns the raw CSS instead of the HMR JS wrapper.
1541
+ * 4. Concatenate in source order and return as `text/css`.
1542
+ *
1543
+ * Why this instead of Astro's `devCSSMap`:
1544
+ *
1545
+ * - `devCSSMap` is an Astro-internal virtual module. It only surfaces
1546
+ * CSS that flows through Astro's `.astro` component graph. Anything
1547
+ * emitted by an Astro integration as a STANDALONE asset (the
1548
+ * canonical example is expressive-code's `/_astro/ec.*.css`) sits
1549
+ * outside that graph and never reaches the editor through devCSSMap.
1550
+ * - Scraping the live HTML reads what the published page actually
1551
+ * paints with — the same stylesheets the user will see in the
1552
+ * browser. No dependency on a specific framework's internal API.
1553
+ *
1554
+ * Known limitations (rare on Astro sites):
1555
+ *
1556
+ * - CSS injected by JavaScript at runtime (`document.head.appendChild`)
1557
+ * isn't in the initial HTML, so we don't see it. Affects view-
1558
+ * transition handlers and third-party widget snippets.
1559
+ * - CSS-in-JS libraries (styled-components, emotion) generate styles
1560
+ * during client render and have the same blind spot.
1561
+ * - Cross-origin stylesheets the dev server can't reach get logged
1562
+ * and skipped (graceful degradation, not silent failure).
1563
+ */
1564
+ function createStylesEndpoint() {
1565
+ return async (req, res, _next) => {
1566
+ try {
1567
+ const routeUrl = new URL(req.url ?? "", "http://localhost").searchParams.get("url");
1568
+ if (!routeUrl) {
1569
+ res.statusCode = 400;
1570
+ res.setHeader("content-type", "text/plain");
1571
+ res.end("Missing required query parameter: url");
1572
+ return;
1573
+ }
1574
+ const host = req.headers.host ?? "localhost:4321";
1575
+ const origin = `${req.headers["x-forwarded-proto"] ?? "http"}://${host}`;
1576
+ const cookie = req.headers.cookie;
1577
+ const liveResponse = await fetch(`${origin}${routeUrl}`, { headers: cookie ? { cookie } : void 0 });
1578
+ if (!liveResponse.ok) {
1579
+ res.statusCode = liveResponse.status;
1580
+ res.setHeader("content-type", "text/plain");
1581
+ res.end(`Upstream route returned ${liveResponse.status}: ${routeUrl}`);
1582
+ return;
1583
+ }
1584
+ const body = (await collectStylesFromHtml(await liveResponse.text(), origin, cookie)).map((s) => `/* ${s.url} */\n${s.css}`).join("\n\n");
1585
+ res.statusCode = 200;
1586
+ res.setHeader("content-type", "text/css; charset=utf-8");
1587
+ res.setHeader("cache-control", "no-store");
1588
+ res.end(body);
1589
+ } catch (err) {
1590
+ res.statusCode = 500;
1591
+ res.setHeader("content-type", "text/plain");
1592
+ res.end(`Styles discovery failed: ${err instanceof Error ? err.message : String(err)}`);
1593
+ }
1594
+ };
1595
+ }
1596
+ /**
1597
+ * Read every `<style>` block and `<link rel="stylesheet">` from the
1598
+ * HTML in their original source order. Inline `<style>` blocks are
1599
+ * captured verbatim; link tags are fetched separately (raw CSS via
1600
+ * `?direct`). Print-media stylesheets are skipped.
1601
+ *
1602
+ * Exported for unit testing.
1603
+ */
1604
+ async function collectStylesFromHtml(html, origin, cookie) {
1605
+ const cleaned = html.replace(/<!--[\s\S]*?-->/g, "");
1606
+ const entries = [];
1607
+ const styleRe = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
1608
+ let match;
1609
+ while ((match = styleRe.exec(cleaned)) !== null) {
1610
+ const attrs = match[1];
1611
+ if (/media\s*=\s*["']?print/i.test(attrs)) continue;
1612
+ const css = match[2];
1613
+ const idAttr = attrs.match(/data-vite-dev-id="([^"]+)"/);
1614
+ const captured = {
1615
+ url: idAttr ? idAttr[1] : `<style#${match.index}>`,
1616
+ css
1617
+ };
1618
+ entries.push({
1619
+ index: match.index,
1620
+ fetch: () => Promise.resolve(captured)
1621
+ });
1622
+ }
1623
+ const linkRe = /<link\b([^>]*)\/?>/gi;
1624
+ while ((match = linkRe.exec(cleaned)) !== null) {
1625
+ const attrs = match[1];
1626
+ if (!/rel\s*=\s*["']?stylesheet["']?/i.test(attrs)) continue;
1627
+ if (/media\s*=\s*["']?print/i.test(attrs)) continue;
1628
+ const hrefMatch = attrs.match(/href\s*=\s*"([^"]+)"|href\s*=\s*'([^']+)'/);
1629
+ if (!hrefMatch) continue;
1630
+ const href = hrefMatch[1] ?? hrefMatch[2];
1631
+ const index = match.index;
1632
+ entries.push({
1633
+ index,
1634
+ fetch: () => fetchStylesheet(href, origin, cookie)
1635
+ });
1636
+ }
1637
+ entries.sort((a, b) => a.index - b.index);
1638
+ return (await Promise.all(entries.map((e) => e.fetch()))).filter((r) => r !== null);
1639
+ }
1640
+ /**
1641
+ * Fetch a stylesheet by href and return its raw CSS. Vite serves CSS
1642
+ * files as JS HMR wrappers by default; `?direct` flips that to raw CSS
1643
+ * output. Absolute URLs are fetched as-is; root-relative paths are
1644
+ * resolved against the dev server origin so cross-page link tags work.
1645
+ */
1646
+ async function fetchStylesheet(href, origin, cookie) {
1647
+ const target = !/^https?:\/\//i.test(href) || href.startsWith(origin) ? `${origin}${href.startsWith("/") ? href : `/${href}`}${href.includes("?") ? "&direct" : "?direct"}` : href;
1648
+ try {
1649
+ const res = await fetch(target, { headers: cookie ? { cookie } : void 0 });
1650
+ if (!res.ok) {
1651
+ console.warn(`[conloca:css] link fetch returned ${res.status} for ${href}`);
1652
+ return null;
1653
+ }
1654
+ return {
1655
+ url: href,
1656
+ css: await res.text()
1657
+ };
1658
+ } catch (err) {
1659
+ console.warn(`[conloca:css] link fetch failed for ${href}:`, err);
1660
+ return null;
1661
+ }
1662
+ }
63
1663
  //#endregion
64
1664
  //#region src/lib/virtual-module-generators.ts
65
1665
  /**
@@ -315,7 +1915,6 @@ export async function getDataCollection(collection, localeOverride) {
315
1915
  function generatePuckConfigModule(puckConfigPath) {
316
1916
  return `export { default } from '${puckConfigPath.startsWith(".") ? `/${puckConfigPath.slice(2)}` : puckConfigPath}';`;
317
1917
  }
318
-
319
1918
  //#endregion
320
1919
  //#region src/plugin-spa.ts
321
1920
  if (typeof viteReact.preambleCode !== "string") throw new Error("@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. Check @vitejs/plugin-react release notes and update the preamble injection logic.");
@@ -360,13 +1959,14 @@ if (import.meta.hot) {
360
1959
  export default {};
361
1960
  `;
362
1961
  };
363
- const puckConfigLoader = (absolutePuckPath) => {
1962
+ const puckConfigLoader = (absolutePuckPath, cmsSpaDistDir) => {
1963
+ const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/puck-config.mjs` : "@conloca/cms-spa/puck-config";
364
1964
  return `
365
1965
  // Import and execute React refresh preamble first (from @vitejs/plugin-react)
366
1966
  ${reactRefreshPreamble}
367
1967
 
368
1968
  // Import the setPuckConfig function from cms-spa
369
- import { setPuckConfig } from '@conloca/cms-spa/puck-config';
1969
+ import { setPuckConfig } from '${puckConfigImport}';
370
1970
 
371
1971
  // Now dynamically import the config after preamble is ready
372
1972
  const puckConfigPromise = import('${absolutePuckPath}');
@@ -395,34 +1995,68 @@ if (import.meta.hot) {
395
1995
  export default puckConfigPromise.then(m => m.default);
396
1996
  `;
397
1997
  };
398
- const schemasLoader = (absoluteSchemasPath) => {
1998
+ const schemasLoader = (absoluteSchemasPath, cmsSpaDistDir) => {
1999
+ const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/page-schemas.mjs` : "@conloca/cms-spa/page-schemas";
2000
+ const mdxComponentsImport = cmsSpaDistDir ? `${cmsSpaDistDir}/mdx-components.mjs` : "@conloca/cms-spa/mdx-components";
399
2001
  return `
400
- import { setPageSchemas } from '@conloca/cms-spa/page-schemas';
401
- import * as schemas from '${absoluteSchemasPath}';
2002
+ ${reactRefreshPreamble}
402
2003
 
403
- if (schemas.pageSchemas) {
404
- setPageSchemas(schemas.pageSchemas);
405
- }
2004
+ import { setPageSchemas } from '${pageSchemasImport}';
2005
+ import { setMdxComponents } from '${mdxComponentsImport}';
2006
+
2007
+ const schemasPromise = import('${absoluteSchemasPath}');
2008
+
2009
+ schemasPromise.then((schemas) => {
2010
+ if (schemas.pageSchemas) {
2011
+ setPageSchemas(schemas.pageSchemas);
2012
+ }
2013
+ if (schemas.mdxComponents) {
2014
+ setMdxComponents(schemas.mdxComponents);
2015
+ }
2016
+ });
406
2017
 
407
2018
  if (import.meta.hot) {
408
2019
  import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
409
2020
  if (newModule?.pageSchemas) {
410
2021
  setPageSchemas(newModule.pageSchemas);
411
2022
  }
2023
+ if (newModule?.mdxComponents) {
2024
+ setMdxComponents(newModule.mdxComponents);
2025
+ }
412
2026
  });
413
2027
  }
414
2028
 
415
- export default schemas;
2029
+ export default schemasPromise;
416
2030
  `;
417
2031
  };
418
- const siteStylesLoader = (cssPaths) => {
2032
+ const siteStylesLoader = (cssPaths, cmsSpaDistDir) => {
2033
+ const imports = cssPaths.map((p, i) => {
2034
+ return `import css${i} from '${p.startsWith("./") ? `/${p.slice(2)}` : p}?inline';`;
2035
+ }).join("\n");
2036
+ const vars = cssPaths.map((_, i) => `css${i}`).join(", ");
419
2037
  return `
420
- ${cssPaths.map((p, i) => {
2038
+ ${imports}
2039
+ import { setSiteStyles } from '${cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : "@conloca/cms-spa/site-styles"}';
2040
+
2041
+ setSiteStyles([${vars}]);
2042
+
2043
+ if (import.meta.hot) {
2044
+ import.meta.hot.accept();
2045
+ }
2046
+
2047
+ export default {};
2048
+ `;
2049
+ };
2050
+ const editorStylesLoader = (cssPaths, cmsSpaDistDir) => {
2051
+ const imports = cssPaths.map((p, i) => {
421
2052
  return `import css${i} from '${p.startsWith("./") ? `/${p.slice(2)}` : p}?inline';`;
422
- }).join("\n")}
423
- import { setSiteStyles } from '@conloca/cms-spa/site-styles';
2053
+ }).join("\n");
2054
+ const vars = cssPaths.map((_, i) => `css${i}`).join(", ");
2055
+ return `
2056
+ ${imports}
2057
+ import { setEditorStyles } from '${cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : "@conloca/cms-spa/site-styles"}';
424
2058
 
425
- setSiteStyles([${cssPaths.map((_, i) => `css${i}`).join(", ")}]);
2059
+ setEditorStyles([${vars}]);
426
2060
 
427
2061
  if (import.meta.hot) {
428
2062
  import.meta.hot.accept();
@@ -433,6 +2067,12 @@ export default {};
433
2067
  };
434
2068
  function conlocaCMS(options) {
435
2069
  const cmsRoute = options.route || "/__cms";
2070
+ let cmsSpaDir;
2071
+ try {
2072
+ const pkgUrl = import.meta.resolve("@conloca/cms-spa/package.json");
2073
+ cmsSpaDir = dirname(pkgUrl.startsWith("file://") ? fileURLToPath(pkgUrl) : pkgUrl);
2074
+ } catch {}
2075
+ const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, "dist") : void 0;
436
2076
  const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
437
2077
  const hydrationDiscoveriesPromise = scanForHydratableComponents(deriveComponentPaths(options.puckConfigPath, options.componentPaths), process.cwd()).then((discoveries) => {
438
2078
  if (discoveries.length > 0) console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
@@ -459,86 +2099,110 @@ function conlocaCMS(options) {
459
2099
  queryClientOptions: options.queryClientOptions,
460
2100
  schemasPath: options.schemasPath,
461
2101
  projectRoot: process.cwd(),
462
- templates: options.templates
2102
+ templates: options.templates,
2103
+ mdxPagesEnabled: false,
2104
+ locales: options.locales ? {
2105
+ list: options.locales.list,
2106
+ defaultLocale: options.locales.defaultLocale
2107
+ } : void 0
463
2108
  };
2109
+ let resolvedMdxPages = null;
464
2110
  let refreshConlocaContent;
465
2111
  return {
466
2112
  name: "@conloca/astro-cms",
467
2113
  hooks: {
468
- "astro:config:setup": ({ updateConfig, injectRoute, command, logger }) => {
2114
+ "astro:config:setup": async ({ updateConfig, injectRoute, command, logger }) => {
2115
+ const sitesConfig = await readSitesConfig(options.contentRoot);
2116
+ resolvedMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages)?.mdxPages ?? null;
2117
+ spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);
469
2118
  const astroRoot = process.cwd();
470
2119
  const contentAbsolute = resolve(options.contentRoot);
471
2120
  if (command === "dev" && !contentAbsolute.startsWith(astroRoot)) {
472
2121
  logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
473
2122
  updateConfig({ vite: { server: { fs: { allow: [searchForWorkspaceRoot(process.cwd()), contentAbsolute] } } } });
474
2123
  }
2124
+ const alwaysSsrNoExternal = ["@puckeditor/core"];
2125
+ const devOnlySsrNoExternal = [/^@conloca\//];
2126
+ const serverOnlyExternal = [
2127
+ "@conloca/content-api",
2128
+ "@conloca/content-api/node",
2129
+ "@conloca/content-api/reader",
2130
+ "@conloca/content-api/schemas",
2131
+ "@conloca/mdx",
2132
+ "@conloca/mdx/node"
2133
+ ];
475
2134
  updateConfig({ vite: {
476
2135
  ssr: {
477
- noExternal: command === "dev" ? [/^@conloca\//, "@puckeditor/core"] : [],
478
- external: [
479
- "@conloca/content-api",
480
- "@conloca/content-api/node",
481
- "@conloca/content-api/reader",
482
- "@conloca/content-api/schemas",
483
- "@conloca/mdx",
484
- "@conloca/mdx/node",
485
- "@node-rs/xxhash",
486
- "@node-rs/xxhash-linux-x64-gnu",
487
- "@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node"
488
- ]
2136
+ noExternal: command === "dev" ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,
2137
+ external: serverOnlyExternal
489
2138
  },
490
- build: { rollupOptions: { external: [
491
- "@node-rs/xxhash",
492
- "@node-rs/xxhash-linux-x64-gnu",
493
- "@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node"
494
- ] } },
495
- plugins: [{
496
- name: "conloca-acorn-ssr-alias",
497
- enforce: "pre",
498
- resolveId(id, _importer, options) {
499
- if (id === "acorn" && options?.ssr) return ACORN_DEFAULT_SHIM_PATH;
500
- return null;
501
- }
502
- }, {
503
- name: "conloca-routing-virtual-modules",
504
- resolveId(id) {
505
- if (id === VIRTUAL_ROUTING_CONFIG) return RESOLVED_ROUTING_CONFIG;
506
- if (id === VIRTUAL_LAYOUT) return RESOLVED_LAYOUT;
507
- if (id === VIRTUAL_PUCK_CONFIG) return RESOLVED_PUCK_CONFIG;
508
- if (id === VIRTUAL_HYDRATION_REGISTRY) return RESOLVED_HYDRATION_REGISTRY;
509
- if (id === VIRTUAL_HYDRATION_ENTRY) return RESOLVED_HYDRATION_ENTRY;
510
- return null;
2139
+ resolve: { dedupe: [
2140
+ "react",
2141
+ "react-dom",
2142
+ "react/jsx-runtime",
2143
+ "react/jsx-dev-runtime"
2144
+ ] },
2145
+ plugins: [
2146
+ {
2147
+ name: "conloca-puck-ssr-render-alias",
2148
+ enforce: "pre",
2149
+ async resolveId(id, importer, options) {
2150
+ if (id === "@puckeditor/core" && options?.ssr) return this.resolve("@puckeditor/core/rsc", importer, {
2151
+ ...options,
2152
+ skipSelf: true
2153
+ });
2154
+ return null;
2155
+ }
511
2156
  },
512
- async load(id) {
513
- if (id === RESOLVED_ROUTING_CONFIG) {
514
- if (resolvedRoutingConfig) return generateRoutingConfigModule(resolvedRoutingConfig);
515
- return "export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };";
2157
+ {
2158
+ name: "conloca-acorn-ssr-alias",
2159
+ enforce: "pre",
2160
+ resolveId(id, _importer, options) {
2161
+ if (id === "acorn" && options?.ssr) return ACORN_DEFAULT_SHIM_PATH;
2162
+ return null;
516
2163
  }
517
- if (id === RESOLVED_LAYOUT) return generateLayoutModule(routingConfig);
518
- if (id === RESOLVED_PUCK_CONFIG) return generatePuckConfigModule(options.puckConfigPath);
519
- if (id === RESOLVED_HYDRATION_REGISTRY) {
520
- const discoveries = await hydrationDiscoveriesPromise;
521
- if (discoveries.length > 0) return `// Generated by @conloca/astro-cms scanner
2164
+ },
2165
+ {
2166
+ name: "conloca-routing-virtual-modules",
2167
+ resolveId(id) {
2168
+ if (id === VIRTUAL_ROUTING_CONFIG) return RESOLVED_ROUTING_CONFIG;
2169
+ if (id === VIRTUAL_LAYOUT) return RESOLVED_LAYOUT;
2170
+ if (id === VIRTUAL_PUCK_CONFIG) return RESOLVED_PUCK_CONFIG;
2171
+ if (id === VIRTUAL_HYDRATION_REGISTRY) return RESOLVED_HYDRATION_REGISTRY;
2172
+ if (id === VIRTUAL_HYDRATION_ENTRY) return RESOLVED_HYDRATION_ENTRY;
2173
+ return null;
2174
+ },
2175
+ async load(id) {
2176
+ if (id === RESOLVED_ROUTING_CONFIG) {
2177
+ if (resolvedRoutingConfig) return generateRoutingConfigModule(resolvedRoutingConfig);
2178
+ return "export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };";
2179
+ }
2180
+ if (id === RESOLVED_LAYOUT) return generateLayoutModule(routingConfig);
2181
+ if (id === RESOLVED_PUCK_CONFIG) return generatePuckConfigModule(options.puckConfigPath);
2182
+ if (id === RESOLVED_HYDRATION_REGISTRY) {
2183
+ const discoveries = await hydrationDiscoveriesPromise;
2184
+ if (discoveries.length > 0) return `// Generated by @conloca/astro-cms scanner
522
2185
  export const componentRegistry = {
523
2186
  ${discoveries.map((d) => {
524
- const relativePath = d.filePath.replace(process.cwd(), "");
525
- return ` '${d.componentName}': {
2187
+ const relativePath = d.filePath.replace(process.cwd(), "");
2188
+ return ` '${d.componentName}': {
526
2189
  loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
527
2190
  strategy: '${d.strategy}',
528
2191
  }`;
529
- }).join(",\n")}
2192
+ }).join(",\n")}
530
2193
  };`;
531
- return "export const componentRegistry = {};";
532
- }
533
- if (id === RESOLVED_HYDRATION_ENTRY) return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
2194
+ return "export const componentRegistry = {};";
2195
+ }
2196
+ if (id === RESOLVED_HYDRATION_ENTRY) return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
534
2197
  import { componentRegistry } from 'virtual:conloca-hydration-registry'
535
2198
 
536
2199
  // Auto-initialize hydration when this module loads
537
2200
  initHydration(componentRegistry)
538
2201
  `;
539
- return null;
2202
+ return null;
2203
+ }
540
2204
  }
541
- }]
2205
+ ]
542
2206
  } });
543
2207
  if (resolvedRoutingConfig?.enabled) for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
544
2208
  logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
@@ -554,18 +2218,11 @@ initHydration(componentRegistry)
554
2218
  "import.meta.env.CONLOCA_CONTENT_ROOT": JSON.stringify(options.contentRoot),
555
2219
  "import.meta.env.CONLOCA_CANVAS_DIR": JSON.stringify(options.canvasDir || "./canvas"),
556
2220
  "import.meta.env.CONLOCA_PUCK_CONFIG_PATH": JSON.stringify(options.puckConfigPath),
557
- "import.meta.env.CONLOCA_ASSETS_PATH": JSON.stringify(options.assetsPath || "")
558
- },
559
- resolve: {
560
- dedupe: [
561
- "react",
562
- "react-dom",
563
- "react/jsx-runtime",
564
- "react/jsx-dev-runtime",
565
- "@puckeditor/core",
566
- "@tanstack/react-query"
567
- ],
568
- preserveSymlinks: true
2221
+ "import.meta.env.CONLOCA_ASSETS_PATH": JSON.stringify(options.assetsPath || ""),
2222
+ "import.meta.env.CONLOCA_BLOCK_PREVIEW_ROUTE": JSON.stringify(options.blockPreviewRoute || "/"),
2223
+ "import.meta.env.CONLOCA_EDITOR_CSS": JSON.stringify(options.editorCSS || ""),
2224
+ "import.meta.env.CONLOCA_LOCALES": JSON.stringify(options.locales?.list ?? null),
2225
+ "import.meta.env.CONLOCA_DEFAULT_LOCALE": JSON.stringify(options.locales?.defaultLocale || "")
569
2226
  },
570
2227
  optimizeDeps: {
571
2228
  exclude: [options.puckConfigPath],
@@ -614,6 +2271,7 @@ initHydration(componentRegistry)
614
2271
  if (id === `${cmsRoute}/content-listener.js`) return id;
615
2272
  if (id === `${cmsRoute}/schemas-entry.js`) return id;
616
2273
  if (id === `${cmsRoute}/site-styles.js`) return id;
2274
+ if (id === `${cmsRoute}/editor-styles.js`) return id;
617
2275
  if (id === VIRTUAL_PAGE_API) return RESOLVED_PAGE_API;
618
2276
  if (id === VIRTUAL_CMS_SPA_ENTRY) return RESOLVED_CMS_SPA_ENTRY;
619
2277
  if (id === `${cmsRoute}/cms-spa-entry.js`) return RESOLVED_CMS_SPA_ENTRY;
@@ -621,14 +2279,30 @@ initHydration(componentRegistry)
621
2279
  },
622
2280
  load(id) {
623
2281
  if (id === RESOLVED_VIRTUAL_CONFIG) return `export default ${JSON.stringify(spaConfig)};`;
624
- if (id === `${cmsRoute}/puck-entry.js`) return puckConfigLoader(options.puckConfigPath.startsWith(".") ? `/${options.puckConfigPath.slice(2)}` : options.puckConfigPath);
2282
+ if (id === `${cmsRoute}/puck-entry.js`) {
2283
+ const absolutePuckPath = options.puckConfigPath.startsWith(".") ? `/${options.puckConfigPath.slice(2)}` : options.puckConfigPath;
2284
+ return puckConfigLoader(absolutePuckPath, cmsSpaDistDir);
2285
+ }
625
2286
  if (id === `${cmsRoute}/content-listener.js`) return contentChangeListener();
626
2287
  if (id === `${cmsRoute}/schemas-entry.js`) {
627
- if (options.schemasPath) return schemasLoader(options.schemasPath.startsWith(".") ? `/${options.schemasPath.slice(2)}` : options.schemasPath);
2288
+ if (options.schemasPath) {
2289
+ const absoluteSchemasPath = options.schemasPath.startsWith(".") ? `/${options.schemasPath.slice(2)}` : options.schemasPath;
2290
+ return schemasLoader(absoluteSchemasPath, cmsSpaDistDir);
2291
+ }
628
2292
  return "export default {};";
629
2293
  }
630
2294
  if (id === `${cmsRoute}/site-styles.js`) {
631
- if (options.siteStyles) return siteStylesLoader(Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles]);
2295
+ if (options.siteStyles) {
2296
+ const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];
2297
+ return siteStylesLoader(paths, cmsSpaDistDir);
2298
+ }
2299
+ return "export default {};";
2300
+ }
2301
+ if (id === `${cmsRoute}/editor-styles.js`) {
2302
+ if (options.editorStyles) {
2303
+ const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];
2304
+ return editorStylesLoader(paths, cmsSpaDistDir);
2305
+ }
632
2306
  return "export default {};";
633
2307
  }
634
2308
  if (id === RESOLVED_PAGE_API) return generatePageApiModule({
@@ -639,16 +2313,13 @@ initHydration(componentRegistry)
639
2313
  });
640
2314
  if (id === RESOLVED_CMS_SPA_ENTRY) {
641
2315
  let cmsSpaImport;
642
- try {
643
- const cmsSpaPackageJsonPath = import.meta.resolve("@conloca/cms-spa/package.json");
644
- const realSrcMainPath = join(dirname(cmsSpaPackageJsonPath.startsWith("file://") ? fileURLToPath(cmsSpaPackageJsonPath) : cmsSpaPackageJsonPath), "src", "main.tsx");
2316
+ if (cmsSpaDir) {
2317
+ const realSrcMainPath = join(cmsSpaDir, "src", "main.tsx");
645
2318
  const linkedSrcMainPath = join(astroRoot, "node_modules", "@conloca", "cms-spa", "src", "main.tsx");
646
2319
  const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;
647
2320
  if (existsSync(srcMainPath)) cmsSpaImport = `import '${srcMainPath}';`;
648
2321
  else cmsSpaImport = "import '@conloca/cms-spa/main';";
649
- } catch {
650
- cmsSpaImport = "import '@conloca/cms-spa/main';";
651
- }
2322
+ } else cmsSpaImport = "import '@conloca/cms-spa/main';";
652
2323
  return `
653
2324
  // Import and execute React refresh preamble first (from @vitejs/plugin-react)
654
2325
  ${reactRefreshPreamble}
@@ -666,13 +2337,50 @@ if (import.meta.hot) {
666
2337
  return null;
667
2338
  }
668
2339
  },
2340
+ {
2341
+ name: "conloca-styles-endpoint",
2342
+ apply: "serve",
2343
+ configureServer(server) {
2344
+ server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());
2345
+ }
2346
+ },
2347
+ {
2348
+ name: "conloca-content-wrapper-endpoint",
2349
+ apply: "serve",
2350
+ configureServer(server) {
2351
+ server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());
2352
+ }
2353
+ },
2354
+ {
2355
+ name: "conloca-registry-and-render-endpoints",
2356
+ apply: "serve",
2357
+ configureServer(server) {
2358
+ const registry = createRegistryEndpoint({
2359
+ contentRoot: resolvedMdxPages ?? options.contentRoot,
2360
+ componentFolders: options.mdxComponentFolders ?? ["src/components/mdx"],
2361
+ projectRoot: process.cwd()
2362
+ });
2363
+ server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
2364
+ server.middlewares.use(`${cmsRoute}/api/render`, createRenderEndpoint(server, registry.getAllowedSources));
2365
+ const onFsChange = (filepath) => {
2366
+ if (/\.(mdx|astro|tsx|d\.ts|cms\.json)$/.test(filepath)) registry.invalidate();
2367
+ };
2368
+ server.watcher.on("add", onFsChange);
2369
+ server.watcher.on("change", onFsChange);
2370
+ server.watcher.on("unlink", onFsChange);
2371
+ }
2372
+ },
669
2373
  {
670
2374
  name: "conloca-content-watcher",
671
2375
  async configureServer(server) {
672
2376
  const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();
673
2377
  const contentApi = await createContentAPI({
674
2378
  contentRoot: options.contentRoot,
675
- canvasDir: options.canvasDir || "./canvas"
2379
+ canvasDir: options.canvasDir || "./canvas",
2380
+ ...options.locales && {
2381
+ availableLocales: options.locales.list,
2382
+ defaultLocale: options.locales.defaultLocale
2383
+ }
676
2384
  });
677
2385
  const { resolve } = await import("node:path");
678
2386
  const astroRoot = process.cwd();
@@ -690,14 +2398,66 @@ if (import.meta.hot) {
690
2398
  if (foldersToWatch.length > 0) server.watcher.add(foldersToWatch);
691
2399
  const handlers = createContentWatchHandlers(contentApi, {
692
2400
  contentRoot: options.contentRoot,
693
- canvasDir: options.canvasDir || "./canvas"
694
- }, server.ws, async () => {
2401
+ canvasDir: options.canvasDir || "./canvas",
2402
+ ...resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }
2403
+ }, server.ws, async (event) => {
695
2404
  await refreshConlocaContent?.();
2405
+ if (event.inMdxRoot) {
2406
+ const dotAstroModulesFile = resolve(astroRoot, ".astro", "content-modules.mjs");
2407
+ const dotAstroAssetsFile = resolve(astroRoot, ".astro", "content-assets.mjs");
2408
+ for (const env of Object.values(server.environments ?? {})) {
2409
+ if (!env?.moduleGraph) continue;
2410
+ for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {
2411
+ const mod = env.moduleGraph.getModuleById(filePath);
2412
+ if (!mod) continue;
2413
+ const envWithReload = env;
2414
+ if (typeof envWithReload.reloadModule === "function") Promise.resolve(envWithReload.reloadModule(mod)).catch(() => void 0);
2415
+ else env.moduleGraph.invalidateModule(mod, void 0, Date.now(), true);
2416
+ }
2417
+ env.hot?.send("astro:content-changed", {});
2418
+ }
2419
+ }
696
2420
  });
697
2421
  server.watcher.on("change", handlers.onChange);
698
2422
  server.watcher.on("add", handlers.onAdd);
699
2423
  server.watcher.on("unlink", handlers.onUnlink);
700
2424
  }
2425
+ },
2426
+ {
2427
+ name: "conloca-suppress-cms-save-reload",
2428
+ apply: "serve",
2429
+ configureServer(server) {
2430
+ let suppressUntil = 0;
2431
+ const WINDOW_MS = 2e3;
2432
+ const cmsContentPrefix = `${cmsRoute}/api/content`;
2433
+ server.middlewares.use((req, _res, next) => {
2434
+ if ((req.method === "POST" || req.method === "PUT" || req.method === "PATCH" || req.method === "DELETE") && req.url?.startsWith(cmsContentPrefix)) suppressUntil = Date.now() + WINDOW_MS;
2435
+ next();
2436
+ });
2437
+ const shouldDropDuringWindow = (payload) => {
2438
+ if (!payload || typeof payload !== "object") return false;
2439
+ const p = payload;
2440
+ if (p.type === "full-reload") return true;
2441
+ if (p.type === "custom" && p.event === "conloca:content-update") return true;
2442
+ return false;
2443
+ };
2444
+ const patchSend = (target) => {
2445
+ if (!target) return;
2446
+ const marked = target;
2447
+ if (marked.__conlocaPatched) return;
2448
+ const origSend = target.send.bind(target);
2449
+ target.send = ((payload, ...rest) => {
2450
+ if (shouldDropDuringWindow(payload) && Date.now() < suppressUntil) {
2451
+ server.config.logger.info(`[conloca] suppressed ${payload.type} during CMS save window`, { timestamp: true });
2452
+ return;
2453
+ }
2454
+ return origSend(payload, ...rest);
2455
+ });
2456
+ marked.__conlocaPatched = true;
2457
+ };
2458
+ patchSend(server.environments?.client?.hot);
2459
+ patchSend(server.ws);
2460
+ }
701
2461
  }
702
2462
  ]
703
2463
  } });
@@ -747,7 +2507,7 @@ if (import.meta.hot) {
747
2507
  }
748
2508
  };
749
2509
  }
750
-
751
2510
  //#endregion
752
- export { conlocaCMS };
2511
+ export { conlocaCMS, localesFromAstroI18n, localesFromStarlight, scanForHydratableComponents };
2512
+
753
2513
  //# sourceMappingURL=index.mjs.map