@conloca/astro-cms 0.1.16 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/README.md +250 -298
  2. package/dist/internal/acorn-default.mjs +11 -3
  3. package/dist/internal/page-handler.astro +137 -358
  4. package/dist/ts/node/content.d.ts +4 -0
  5. package/dist/ts/node/content.d.ts.map +1 -0
  6. package/dist/ts/node/content.js +3 -0
  7. package/dist/ts/node/content.js.map +1 -0
  8. package/dist/ts/node/index.d.ts +9 -0
  9. package/dist/ts/node/index.d.ts.map +1 -0
  10. package/dist/ts/node/index.js +14 -0
  11. package/dist/ts/node/index.js.map +1 -0
  12. package/dist/ts/src/asset-ref-base.d.ts +3 -0
  13. package/dist/ts/src/asset-ref-base.d.ts.map +1 -0
  14. package/dist/ts/src/asset-ref-base.js +48 -0
  15. package/dist/ts/src/asset-ref-base.js.map +1 -0
  16. package/dist/ts/src/checks.d.ts +7 -0
  17. package/dist/ts/src/checks.d.ts.map +1 -0
  18. package/dist/ts/src/checks.js +7 -0
  19. package/dist/ts/src/checks.js.map +1 -0
  20. package/dist/{src → ts/src}/cms-handler.d.ts +0 -1
  21. package/dist/ts/src/cms-handler.d.ts.map +1 -0
  22. package/dist/{src → ts/src}/cms-handler.js +9 -130
  23. package/dist/ts/src/cms-handler.js.map +1 -0
  24. package/dist/ts/src/collections.d.ts +160 -0
  25. package/dist/ts/src/collections.d.ts.map +1 -0
  26. package/dist/ts/src/collections.js +170 -0
  27. package/dist/ts/src/collections.js.map +1 -0
  28. package/dist/{src → ts/src}/components/HydrationWrapper.d.ts +1 -1
  29. package/dist/ts/src/components/HydrationWrapper.d.ts.map +1 -0
  30. package/dist/{src → ts/src}/components/HydrationWrapper.js +1 -0
  31. package/dist/ts/src/components/HydrationWrapper.js.map +1 -0
  32. package/dist/{src/components/RenderWithBlocks.d.ts → ts/src/components/RenderWithFragments.d.ts} +8 -4
  33. package/dist/ts/src/components/RenderWithFragments.d.ts.map +1 -0
  34. package/dist/ts/src/components/RenderWithFragments.js +133 -0
  35. package/dist/ts/src/components/RenderWithFragments.js.map +1 -0
  36. package/dist/{src → ts/src}/components/RenderWithHydration.d.ts +6 -2
  37. package/dist/ts/src/components/RenderWithHydration.d.ts.map +1 -0
  38. package/dist/{src → ts/src}/components/RenderWithHydration.js +6 -3
  39. package/dist/ts/src/components/RenderWithHydration.js.map +1 -0
  40. package/dist/ts/src/components.d.ts +4 -0
  41. package/dist/ts/src/components.d.ts.map +1 -0
  42. package/dist/ts/src/components.js +4 -0
  43. package/dist/ts/src/components.js.map +1 -0
  44. package/dist/ts/src/discovery/astro-frontmatter.d.ts.map +1 -0
  45. package/dist/{src → ts/src}/discovery/astro-frontmatter.js +1 -0
  46. package/dist/ts/src/discovery/astro-frontmatter.js.map +1 -0
  47. package/dist/ts/src/discovery/discover.d.ts +43 -0
  48. package/dist/ts/src/discovery/discover.d.ts.map +1 -0
  49. package/dist/ts/src/discovery/discover.js +87 -0
  50. package/dist/ts/src/discovery/discover.js.map +1 -0
  51. package/dist/ts/src/discovery/extract-props-ts.d.ts.map +1 -0
  52. package/dist/{src → ts/src}/discovery/extract-props-ts.js +1 -0
  53. package/dist/ts/src/discovery/extract-props-ts.js.map +1 -0
  54. package/dist/{src → ts/src}/discovery/merge-registry.d.ts +3 -3
  55. package/dist/ts/src/discovery/merge-registry.d.ts.map +1 -0
  56. package/dist/{src → ts/src}/discovery/merge-registry.js +1 -0
  57. package/dist/ts/src/discovery/merge-registry.js.map +1 -0
  58. package/dist/ts/src/discovery/registry-endpoint.d.ts +27 -0
  59. package/dist/ts/src/discovery/registry-endpoint.d.ts.map +1 -0
  60. package/dist/ts/src/discovery/registry-endpoint.js +76 -0
  61. package/dist/ts/src/discovery/registry-endpoint.js.map +1 -0
  62. package/dist/{src → ts/src}/discovery/scan-components.d.ts +3 -7
  63. package/dist/ts/src/discovery/scan-components.d.ts.map +1 -0
  64. package/dist/{src → ts/src}/discovery/scan-components.js +4 -6
  65. package/dist/ts/src/discovery/scan-components.js.map +1 -0
  66. package/dist/ts/src/discovery/scan-mdx.d.ts.map +1 -0
  67. package/dist/{src → ts/src}/discovery/scan-mdx.js +1 -0
  68. package/dist/ts/src/discovery/scan-mdx.js.map +1 -0
  69. package/dist/ts/src/discovery/scan-overrides.d.ts.map +1 -0
  70. package/dist/{src → ts/src}/discovery/scan-overrides.js +1 -0
  71. package/dist/ts/src/discovery/scan-overrides.js.map +1 -0
  72. package/dist/ts/src/editor-descriptors.d.ts +31 -0
  73. package/dist/ts/src/editor-descriptors.d.ts.map +1 -0
  74. package/dist/ts/src/editor-descriptors.js +84 -0
  75. package/dist/ts/src/editor-descriptors.js.map +1 -0
  76. package/dist/ts/src/handlers/collection-content-api.d.ts +32 -0
  77. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -0
  78. package/dist/ts/src/handlers/collection-content-api.js +166 -0
  79. package/dist/ts/src/handlers/collection-content-api.js.map +1 -0
  80. package/dist/ts/src/handlers/page-render-core.d.ts +137 -0
  81. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -0
  82. package/dist/ts/src/handlers/page-render-core.js +315 -0
  83. package/dist/ts/src/handlers/page-render-core.js.map +1 -0
  84. package/dist/ts/src/hydration.d.ts.map +1 -0
  85. package/dist/{src → ts/src}/hydration.js +1 -0
  86. package/dist/ts/src/hydration.js.map +1 -0
  87. package/dist/ts/src/index.d.ts +21 -0
  88. package/dist/ts/src/index.d.ts.map +1 -0
  89. package/dist/ts/src/index.js +45 -0
  90. package/dist/ts/src/index.js.map +1 -0
  91. package/dist/ts/src/internal/declared-collections.d.ts +30 -0
  92. package/dist/ts/src/internal/declared-collections.d.ts.map +1 -0
  93. package/dist/ts/src/internal/declared-collections.js +84 -0
  94. package/dist/ts/src/internal/declared-collections.js.map +1 -0
  95. package/dist/ts/src/internal/page-collection-schema.d.ts +44 -0
  96. package/dist/ts/src/internal/page-collection-schema.d.ts.map +1 -0
  97. package/dist/ts/src/internal/page-collection-schema.js +152 -0
  98. package/dist/ts/src/internal/page-collection-schema.js.map +1 -0
  99. package/dist/ts/src/lib/content-config-guard.d.ts +11 -0
  100. package/dist/ts/src/lib/content-config-guard.d.ts.map +1 -0
  101. package/dist/ts/src/lib/content-config-guard.js +41 -0
  102. package/dist/ts/src/lib/content-config-guard.js.map +1 -0
  103. package/dist/ts/src/lib/hydration-scanner.d.ts.map +1 -0
  104. package/dist/{src → ts/src}/lib/hydration-scanner.js +1 -0
  105. package/dist/ts/src/lib/hydration-scanner.js.map +1 -0
  106. package/dist/ts/src/lib/hydration-script.d.ts.map +1 -0
  107. package/dist/{src → ts/src}/lib/hydration-script.js +1 -0
  108. package/dist/ts/src/lib/hydration-script.js.map +1 -0
  109. package/dist/ts/src/lib/hydration-utils.d.ts.map +1 -0
  110. package/dist/{src → ts/src}/lib/hydration-utils.js +1 -0
  111. package/dist/ts/src/lib/hydration-utils.js.map +1 -0
  112. package/dist/ts/src/lib/resolve-locale.d.ts +15 -0
  113. package/dist/ts/src/lib/resolve-locale.d.ts.map +1 -0
  114. package/dist/ts/src/lib/resolve-locale.js +16 -0
  115. package/dist/ts/src/lib/resolve-locale.js.map +1 -0
  116. package/dist/ts/src/lib/resolve-site-name.d.ts +8 -0
  117. package/dist/ts/src/lib/resolve-site-name.d.ts.map +1 -0
  118. package/dist/ts/src/lib/resolve-site-name.js +12 -0
  119. package/dist/ts/src/lib/resolve-site-name.js.map +1 -0
  120. package/dist/{src → ts/src}/lib/route-utils.d.ts +26 -6
  121. package/dist/ts/src/lib/route-utils.d.ts.map +1 -0
  122. package/dist/{src → ts/src}/lib/route-utils.js +33 -15
  123. package/dist/ts/src/lib/route-utils.js.map +1 -0
  124. package/dist/{src → ts/src}/lib/routing-config.d.ts +7 -1
  125. package/dist/ts/src/lib/routing-config.d.ts.map +1 -0
  126. package/dist/{src → ts/src}/lib/routing-config.js +13 -0
  127. package/dist/ts/src/lib/routing-config.js.map +1 -0
  128. package/dist/ts/src/lib/serialize-props.d.ts.map +1 -0
  129. package/dist/{src → ts/src}/lib/serialize-props.js +1 -0
  130. package/dist/ts/src/lib/serialize-props.js.map +1 -0
  131. package/dist/ts/src/lib/unknown-components.d.ts +21 -0
  132. package/dist/ts/src/lib/unknown-components.d.ts.map +1 -0
  133. package/dist/ts/src/lib/unknown-components.js +49 -0
  134. package/dist/ts/src/lib/unknown-components.js.map +1 -0
  135. package/dist/{src → ts/src}/lib/virtual-module-generators.d.ts +0 -24
  136. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -0
  137. package/dist/ts/src/lib/virtual-module-generators.js +51 -0
  138. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -0
  139. package/dist/ts/src/lib/withHydration.d.ts.map +1 -0
  140. package/dist/{src → ts/src}/lib/withHydration.js +1 -0
  141. package/dist/ts/src/lib/withHydration.js.map +1 -0
  142. package/dist/ts/src/loader.d.ts +27 -0
  143. package/dist/ts/src/loader.d.ts.map +1 -0
  144. package/dist/{src → ts/src}/loader.js +33 -4
  145. package/dist/ts/src/loader.js.map +1 -0
  146. package/dist/ts/src/locales-helpers.d.ts.map +1 -0
  147. package/dist/{src → ts/src}/locales-helpers.js +1 -0
  148. package/dist/ts/src/locales-helpers.js.map +1 -0
  149. package/dist/ts/src/mime-types.d.ts.map +1 -0
  150. package/dist/{src → ts/src}/mime-types.js +1 -0
  151. package/dist/ts/src/mime-types.js.map +1 -0
  152. package/dist/ts/src/page-feed.d.ts +13 -0
  153. package/dist/ts/src/page-feed.d.ts.map +1 -0
  154. package/dist/ts/src/page-feed.js +20 -0
  155. package/dist/ts/src/page-feed.js.map +1 -0
  156. package/dist/ts/src/page-schemas.d.ts +6 -0
  157. package/dist/ts/src/page-schemas.d.ts.map +1 -0
  158. package/dist/ts/src/page-schemas.js +6 -0
  159. package/dist/ts/src/page-schemas.js.map +1 -0
  160. package/dist/ts/src/path-validation.d.ts.map +1 -0
  161. package/dist/{src → ts/src}/path-validation.js +1 -0
  162. package/dist/ts/src/path-validation.js.map +1 -0
  163. package/dist/{src → ts/src}/plugin-spa.d.ts +28 -10
  164. package/dist/ts/src/plugin-spa.d.ts.map +1 -0
  165. package/dist/{src → ts/src}/plugin-spa.js +280 -87
  166. package/dist/ts/src/plugin-spa.js.map +1 -0
  167. package/dist/ts/src/puck-manifest/components-endpoint.d.ts +30 -0
  168. package/dist/ts/src/puck-manifest/components-endpoint.d.ts.map +1 -0
  169. package/dist/ts/src/puck-manifest/components-endpoint.js +54 -0
  170. package/dist/ts/src/puck-manifest/components-endpoint.js.map +1 -0
  171. package/dist/ts/src/puck-manifest/field-projection.d.ts +91 -0
  172. package/dist/ts/src/puck-manifest/field-projection.d.ts.map +1 -0
  173. package/dist/ts/src/puck-manifest/field-projection.js +422 -0
  174. package/dist/ts/src/puck-manifest/field-projection.js.map +1 -0
  175. package/dist/ts/src/puck-manifest/index.d.ts +4 -0
  176. package/dist/ts/src/puck-manifest/index.d.ts.map +1 -0
  177. package/dist/ts/src/puck-manifest/index.js +3 -0
  178. package/dist/ts/src/puck-manifest/index.js.map +1 -0
  179. package/dist/ts/src/puck-manifest/literal.d.ts +163 -0
  180. package/dist/ts/src/puck-manifest/literal.d.ts.map +1 -0
  181. package/dist/ts/src/puck-manifest/literal.js +354 -0
  182. package/dist/ts/src/puck-manifest/literal.js.map +1 -0
  183. package/dist/ts/src/puck-manifest/read-config.d.ts +42 -0
  184. package/dist/ts/src/puck-manifest/read-config.d.ts.map +1 -0
  185. package/dist/ts/src/puck-manifest/read-config.js +517 -0
  186. package/dist/ts/src/puck-manifest/read-config.js.map +1 -0
  187. package/dist/ts/src/puck-manifest/read-field.d.ts +7 -0
  188. package/dist/ts/src/puck-manifest/read-field.d.ts.map +1 -0
  189. package/dist/ts/src/puck-manifest/read-field.js +11 -0
  190. package/dist/ts/src/puck-manifest/read-field.js.map +1 -0
  191. package/dist/ts/src/puck-manifest/read-wrapper.d.ts +147 -0
  192. package/dist/ts/src/puck-manifest/read-wrapper.d.ts.map +1 -0
  193. package/dist/ts/src/puck-manifest/read-wrapper.js +889 -0
  194. package/dist/ts/src/puck-manifest/read-wrapper.js.map +1 -0
  195. package/dist/ts/src/puck-manifest/reading-budget.d.ts +50 -0
  196. package/dist/ts/src/puck-manifest/reading-budget.d.ts.map +1 -0
  197. package/dist/ts/src/puck-manifest/reading-budget.js +113 -0
  198. package/dist/ts/src/puck-manifest/reading-budget.js.map +1 -0
  199. package/dist/ts/src/puck-manifest/resolve-reference.d.ts +4 -0
  200. package/dist/ts/src/puck-manifest/resolve-reference.d.ts.map +1 -0
  201. package/dist/ts/src/puck-manifest/resolve-reference.js +4 -0
  202. package/dist/ts/src/puck-manifest/resolve-reference.js.map +1 -0
  203. package/dist/ts/src/puck-manifest/source-reference.d.ts +96 -0
  204. package/dist/ts/src/puck-manifest/source-reference.d.ts.map +1 -0
  205. package/dist/ts/src/puck-manifest/source-reference.js +424 -0
  206. package/dist/ts/src/puck-manifest/source-reference.js.map +1 -0
  207. package/dist/ts/src/puck-manifest/syntax.d.ts +29 -0
  208. package/dist/ts/src/puck-manifest/syntax.d.ts.map +1 -0
  209. package/dist/ts/src/puck-manifest/syntax.js +79 -0
  210. package/dist/ts/src/puck-manifest/syntax.js.map +1 -0
  211. package/dist/ts/src/puck-manifest/types.d.ts +145 -0
  212. package/dist/ts/src/puck-manifest/types.d.ts.map +1 -0
  213. package/dist/ts/src/puck-manifest/types.js +2 -0
  214. package/dist/ts/src/puck-manifest/types.js.map +1 -0
  215. package/dist/ts/src/safe-json-stringify.d.ts.map +1 -0
  216. package/dist/{src → ts/src}/safe-json-stringify.js +1 -0
  217. package/dist/ts/src/safe-json-stringify.js.map +1 -0
  218. package/dist/ts/src/sandbox-frame-handler.d.ts +19 -0
  219. package/dist/ts/src/sandbox-frame-handler.d.ts.map +1 -0
  220. package/dist/ts/src/sandbox-frame-handler.js +27 -0
  221. package/dist/ts/src/sandbox-frame-handler.js.map +1 -0
  222. package/dist/{src → ts/src}/site-styles/content-wrapper-endpoint.d.ts +2 -5
  223. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  224. package/dist/{src → ts/src}/site-styles/content-wrapper-endpoint.js +5 -8
  225. package/dist/ts/src/site-styles/content-wrapper-endpoint.js.map +1 -0
  226. package/dist/{src → ts/src}/site-styles/render-endpoint.d.ts +4 -9
  227. package/dist/ts/src/site-styles/render-endpoint.d.ts.map +1 -0
  228. package/dist/{src → ts/src}/site-styles/render-endpoint.js +1 -0
  229. package/dist/ts/src/site-styles/render-endpoint.js.map +1 -0
  230. package/dist/{src → ts/src}/site-styles/styles-endpoint.d.ts +2 -4
  231. package/dist/ts/src/site-styles/styles-endpoint.d.ts.map +1 -0
  232. package/dist/{src → ts/src}/site-styles/styles-endpoint.js +3 -5
  233. package/dist/ts/src/site-styles/styles-endpoint.js.map +1 -0
  234. package/dist/ts/src/sitemap-options.d.ts +21 -0
  235. package/dist/ts/src/sitemap-options.d.ts.map +1 -0
  236. package/dist/ts/src/sitemap-options.js +92 -0
  237. package/dist/ts/src/sitemap-options.js.map +1 -0
  238. package/dist/ts/src/tiptap-html-static.d.ts +15 -0
  239. package/dist/ts/src/tiptap-html-static.d.ts.map +1 -0
  240. package/dist/ts/src/tiptap-html-static.js +67 -0
  241. package/dist/ts/src/tiptap-html-static.js.map +1 -0
  242. package/dist/{src → ts/src}/types.d.ts +26 -110
  243. package/dist/ts/src/types.d.ts.map +1 -0
  244. package/dist/ts/src/types.js +2 -0
  245. package/dist/ts/src/types.js.map +1 -0
  246. package/dist/virtual-modules.d.ts +12 -93
  247. package/node/content.ts +14 -0
  248. package/node/index.ts +22 -0
  249. package/package.json +159 -73
  250. package/src/asset-ref-base.ts +48 -0
  251. package/src/checks.ts +10 -0
  252. package/src/cms-handler.ts +280 -0
  253. package/src/collections.ts +262 -0
  254. package/src/components/HydrationWrapper.tsx +41 -0
  255. package/src/components/RenderWithFragments.tsx +204 -0
  256. package/src/components/RenderWithHydration.tsx +55 -0
  257. package/src/components.ts +3 -0
  258. package/src/discovery/astro-frontmatter.ts +24 -0
  259. package/src/discovery/discover.ts +108 -0
  260. package/src/discovery/extract-props-ts.ts +255 -0
  261. package/src/discovery/merge-registry.ts +411 -0
  262. package/src/discovery/registry-endpoint.ts +80 -0
  263. package/src/discovery/scan-components.ts +458 -0
  264. package/src/discovery/scan-mdx.ts +190 -0
  265. package/src/discovery/scan-overrides.ts +92 -0
  266. package/src/editor-descriptors.ts +96 -0
  267. package/src/env.d.ts +31 -0
  268. package/src/handlers/collection-content-api.ts +196 -0
  269. package/src/handlers/page-handler.astro +320 -0
  270. package/src/handlers/page-render-core.ts +456 -0
  271. package/src/hydration.ts +7 -0
  272. package/src/index.ts +111 -0
  273. package/src/internal/acorn-default.mjs +37 -0
  274. package/src/internal/declared-collections.ts +98 -0
  275. package/src/internal/page-collection-schema.ts +210 -0
  276. package/src/lib/content-config-guard.ts +48 -0
  277. package/src/lib/hydration-scanner.ts +176 -0
  278. package/src/lib/hydration-script.ts +126 -0
  279. package/src/lib/hydration-utils.ts +120 -0
  280. package/src/lib/resolve-locale.ts +22 -0
  281. package/src/lib/resolve-site-name.ts +10 -0
  282. package/src/lib/route-utils.ts +106 -0
  283. package/src/lib/routing-config.ts +126 -0
  284. package/src/lib/serialize-props.ts +7 -0
  285. package/src/lib/unknown-components.ts +64 -0
  286. package/src/lib/virtual-module-generators.ts +58 -0
  287. package/{dist/withHydration-DkKpkmzJ.d.mts → src/lib/withHydration.ts} +25 -8
  288. package/src/loader.ts +145 -0
  289. package/{dist/locales-helpers-BvYYqnJ5.d.mts → src/locales-helpers.ts} +21 -17
  290. package/src/mime-types.ts +19 -0
  291. package/src/page-feed.ts +26 -0
  292. package/src/page-schemas.ts +19 -0
  293. package/src/path-validation.ts +13 -0
  294. package/src/plugin-spa.ts +1480 -0
  295. package/src/puck-manifest/components-endpoint.ts +55 -0
  296. package/src/puck-manifest/field-projection.ts +510 -0
  297. package/src/puck-manifest/index.ts +3 -0
  298. package/src/puck-manifest/literal.ts +459 -0
  299. package/src/puck-manifest/read-config.ts +577 -0
  300. package/src/puck-manifest/read-field.ts +19 -0
  301. package/src/puck-manifest/read-wrapper.ts +1056 -0
  302. package/src/puck-manifest/reading-budget.ts +127 -0
  303. package/src/puck-manifest/resolve-reference.ts +9 -0
  304. package/src/puck-manifest/source-reference.ts +484 -0
  305. package/src/puck-manifest/syntax.ts +104 -0
  306. package/src/puck-manifest/types.ts +139 -0
  307. package/src/safe-json-stringify.ts +17 -0
  308. package/src/sandbox-frame-handler.ts +31 -0
  309. package/src/site-styles/content-wrapper-endpoint.ts +327 -0
  310. package/src/site-styles/render-endpoint.ts +331 -0
  311. package/src/site-styles/styles-endpoint.ts +184 -0
  312. package/src/sitemap-options.ts +115 -0
  313. package/src/tiptap-html-static.ts +84 -0
  314. package/{dist/types-CS9neadI.d.mts → src/types.ts} +87 -124
  315. package/src/virtual-modules.d.ts +74 -0
  316. package/dist/collections-Bd7EME4b.mjs +0 -129
  317. package/dist/collections-Bd7EME4b.mjs.map +0 -1
  318. package/dist/collections.d.mts +0 -35
  319. package/dist/collections.d.mts.map +0 -1
  320. package/dist/collections.mjs +0 -2
  321. package/dist/components.d.mts +0 -41
  322. package/dist/components.d.mts.map +0 -1
  323. package/dist/components.mjs +0 -223
  324. package/dist/components.mjs.map +0 -1
  325. package/dist/hydration.d.mts +0 -4
  326. package/dist/hydration.mjs +0 -2
  327. package/dist/index.d.mts +0 -108
  328. package/dist/index.d.mts.map +0 -1
  329. package/dist/index.mjs +0 -67
  330. package/dist/index.mjs.map +0 -1
  331. package/dist/internal/cms-handler.d.mts +0 -25
  332. package/dist/internal/cms-handler.d.mts.map +0 -1
  333. package/dist/internal/cms-handler.mjs +0 -314
  334. package/dist/internal/cms-handler.mjs.map +0 -1
  335. package/dist/lib/hydration-script.d.mts +0 -30
  336. package/dist/lib/hydration-script.d.mts.map +0 -1
  337. package/dist/lib/hydration-script.mjs +0 -84
  338. package/dist/lib/hydration-script.mjs.map +0 -1
  339. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +0 -1
  340. package/dist/locales-helpers-qiwh7nxS.mjs +0 -54
  341. package/dist/locales-helpers-qiwh7nxS.mjs.map +0 -1
  342. package/dist/node/content.d.mts +0 -18
  343. package/dist/node/content.d.mts.map +0 -1
  344. package/dist/node/content.d.ts +0 -3
  345. package/dist/node/content.d.ts.map +0 -1
  346. package/dist/node/content.js +0 -2
  347. package/dist/node/content.mjs +0 -2
  348. package/dist/node/index.d.mts +0 -200
  349. package/dist/node/index.d.mts.map +0 -1
  350. package/dist/node/index.d.ts +0 -4
  351. package/dist/node/index.d.ts.map +0 -1
  352. package/dist/node/index.js +0 -3
  353. package/dist/node/index.mjs +0 -2513
  354. package/dist/node/index.mjs.map +0 -1
  355. package/dist/serialize-props-BHoNpzH6.mjs +0 -72
  356. package/dist/serialize-props-BHoNpzH6.mjs.map +0 -1
  357. package/dist/src/cms-handler.d.ts.map +0 -1
  358. package/dist/src/collections.d.ts +0 -32
  359. package/dist/src/collections.d.ts.map +0 -1
  360. package/dist/src/collections.js +0 -50
  361. package/dist/src/components/HydrationWrapper.d.ts.map +0 -1
  362. package/dist/src/components/RenderWithBlocks.d.ts.map +0 -1
  363. package/dist/src/components/RenderWithBlocks.js +0 -129
  364. package/dist/src/components/RenderWithHydration.d.ts.map +0 -1
  365. package/dist/src/components.d.ts +0 -4
  366. package/dist/src/components.d.ts.map +0 -1
  367. package/dist/src/components.js +0 -3
  368. package/dist/src/discovery/astro-frontmatter.d.ts.map +0 -1
  369. package/dist/src/discovery/extract-props-ts.d.ts.map +0 -1
  370. package/dist/src/discovery/merge-registry.d.ts.map +0 -1
  371. package/dist/src/discovery/registry-endpoint.d.ts +0 -42
  372. package/dist/src/discovery/registry-endpoint.d.ts.map +0 -1
  373. package/dist/src/discovery/registry-endpoint.js +0 -81
  374. package/dist/src/discovery/scan-components.d.ts.map +0 -1
  375. package/dist/src/discovery/scan-mdx.d.ts.map +0 -1
  376. package/dist/src/discovery/scan-overrides.d.ts.map +0 -1
  377. package/dist/src/hydration.d.ts.map +0 -1
  378. package/dist/src/index.d.ts +0 -11
  379. package/dist/src/index.d.ts.map +0 -1
  380. package/dist/src/index.js +0 -25
  381. package/dist/src/lib/hydration-scanner.d.ts.map +0 -1
  382. package/dist/src/lib/hydration-script.d.ts.map +0 -1
  383. package/dist/src/lib/hydration-utils.d.ts.map +0 -1
  384. package/dist/src/lib/page-api.d.ts +0 -77
  385. package/dist/src/lib/page-api.d.ts.map +0 -1
  386. package/dist/src/lib/page-api.js +0 -121
  387. package/dist/src/lib/route-utils.d.ts.map +0 -1
  388. package/dist/src/lib/routing-config.d.ts.map +0 -1
  389. package/dist/src/lib/serialize-props.d.ts.map +0 -1
  390. package/dist/src/lib/virtual-module-generators.d.ts.map +0 -1
  391. package/dist/src/lib/virtual-module-generators.js +0 -263
  392. package/dist/src/lib/withHydration.d.ts.map +0 -1
  393. package/dist/src/loader.d.ts +0 -14
  394. package/dist/src/loader.d.ts.map +0 -1
  395. package/dist/src/locales-helpers.d.ts.map +0 -1
  396. package/dist/src/mime-types.d.ts.map +0 -1
  397. package/dist/src/path-validation.d.ts.map +0 -1
  398. package/dist/src/plugin-spa.d.ts.map +0 -1
  399. package/dist/src/safe-json-stringify.d.ts.map +0 -1
  400. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +0 -1
  401. package/dist/src/site-styles/render-endpoint.d.ts.map +0 -1
  402. package/dist/src/site-styles/styles-endpoint.d.ts.map +0 -1
  403. package/dist/src/types.d.ts.map +0 -1
  404. package/dist/src/types.js +0 -1
  405. package/dist/types-CS9neadI.d.mts.map +0 -1
  406. package/dist/withHydration-C256ox_6.mjs +0 -49
  407. package/dist/withHydration-C256ox_6.mjs.map +0 -1
  408. package/dist/withHydration-DkKpkmzJ.d.mts.map +0 -1
  409. /package/dist/{src → ts/src}/discovery/astro-frontmatter.d.ts +0 -0
  410. /package/dist/{src → ts/src}/discovery/extract-props-ts.d.ts +0 -0
  411. /package/dist/{src → ts/src}/discovery/scan-mdx.d.ts +0 -0
  412. /package/dist/{src → ts/src}/discovery/scan-overrides.d.ts +0 -0
  413. /package/dist/{src → ts/src}/hydration.d.ts +0 -0
  414. /package/dist/{src → ts/src}/lib/hydration-scanner.d.ts +0 -0
  415. /package/dist/{src → ts/src}/lib/hydration-script.d.ts +0 -0
  416. /package/dist/{src → ts/src}/lib/hydration-utils.d.ts +0 -0
  417. /package/dist/{src → ts/src}/lib/serialize-props.d.ts +0 -0
  418. /package/dist/{src → ts/src}/lib/withHydration.d.ts +0 -0
  419. /package/dist/{src → ts/src}/locales-helpers.d.ts +0 -0
  420. /package/dist/{src → ts/src}/mime-types.d.ts +0 -0
  421. /package/dist/{src → ts/src}/path-validation.d.ts +0 -0
  422. /package/dist/{src → ts/src}/safe-json-stringify.d.ts +0 -0
@@ -0,0 +1,1480 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import type { UIConfig } from '@conloca/cms-spa';
5
+ import { readSitesConfig } from '@conloca/content-api/node';
6
+ import viteReact from '@vitejs/plugin-react';
7
+ import type { AstroIntegration } from 'astro';
8
+ import { type HotPayload, type InferCustomEventPayload, type NormalizedHotChannel, searchForWorkspaceRoot } from 'vite';
9
+ import { deriveAssetRefBase } from './asset-ref-base.js';
10
+ import type { MdxRegistryScanOptions } from './discovery/discover.js';
11
+ import { createRegistryEndpoint } from './discovery/registry-endpoint.js';
12
+ import { EDITOR_DESCRIPTORS_ENV_VAR, type EditorDescriptorChannel } from './editor-descriptors.js';
13
+ import { CONTENT_CONFIG_SNIPPET, findContentConfigProblem } from './lib/content-config-guard.js';
14
+ import { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';
15
+ import { resolveLocale } from './lib/resolve-locale.js';
16
+ import { resolveSiteName } from './lib/resolve-site-name.js';
17
+ import { normalizeRoutingConfig, resolveRouteConfig, toEditorDataBindings } from './lib/routing-config.js';
18
+ import type { ConlocaLocales } from './locales-helpers.js';
19
+ import { createComponentsEndpoint, endpointReaderOptions } from './puck-manifest/components-endpoint.js';
20
+ import { createContentWrapperEndpoint } from './site-styles/content-wrapper-endpoint.js';
21
+ import { createRenderEndpoint } from './site-styles/render-endpoint.js';
22
+ import { createStylesEndpoint } from './site-styles/styles-endpoint.js';
23
+
24
+ // FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.
25
+ // It provides the React Fast Refresh preamble script needed for HMR in virtual modules.
26
+ // If @vitejs/plugin-react removes or renames this property, the assertion below will
27
+ // fail immediately at dev startup. Test after any @vitejs/plugin-react update.
28
+ if (typeof viteReact.preambleCode !== 'string') {
29
+ throw new Error(
30
+ '@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +
31
+ 'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +
32
+ 'Check @vitejs/plugin-react release notes and update the preamble injection logic.',
33
+ );
34
+ }
35
+
36
+ const reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');
37
+
38
+ // The preamble is served as a module of its own rather than pasted into each
39
+ // dev virtual module below. A module's static imports all evaluate before its
40
+ // own body runs, so inlined preamble statements always lose to the cms-spa
41
+ // import underneath them — and cms-spa's built entries are plain `.js`, which
42
+ // Vite's React plugin rewrites with Fast Refresh, throwing on evaluation while
43
+ // `window.$RefreshReg$` is still unset. Imported first, the preamble wins.
44
+ const VIRTUAL_REFRESH_PREAMBLE = 'virtual:conloca-react-refresh-preamble';
45
+ const RESOLVED_REFRESH_PREAMBLE = `\0${VIRTUAL_REFRESH_PREAMBLE}`;
46
+
47
+ // Get the directory of this module to resolve the copied handler assets.
48
+ // Compiled, this file sits in dist/ts/src/, the copied Astro handler in
49
+ // dist/internal/, and the emitted handler modules right next to this file.
50
+ const __dirname = dirname(fileURLToPath(import.meta.url));
51
+ const PAGE_HANDLER_PATH = join(__dirname, '..', '..', 'internal', 'page-handler.astro');
52
+ const CMS_HANDLER_PATH = join(__dirname, 'cms-handler.js');
53
+ const SANDBOX_FRAME_HANDLER_PATH = join(__dirname, 'sandbox-frame-handler.js');
54
+ const ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', '..', 'internal', 'acorn-default.mjs');
55
+ const TIPTAP_HTML_SHIM_PATH = join(__dirname, 'tiptap-html-static.js');
56
+
57
+ import {
58
+ generateLayoutModule,
59
+ generatePuckConfigModule,
60
+ generateRoutingConfigModule,
61
+ } from './lib/virtual-module-generators.js';
62
+ import type { EditorDataBindings, ResolvedRoutingConfig, RoutingConfigInput, TemplateConfig } from './types.js';
63
+
64
+ // Virtual module for passing config from plugin to route handler
65
+ const VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';
66
+ const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
67
+
68
+ // Virtual module IDs for routing system
69
+ const VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';
70
+ const VIRTUAL_LAYOUT = 'virtual:conloca-layout';
71
+ const VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';
72
+
73
+ // Resolved IDs (with \0 prefix to prevent file resolution)
74
+ const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
75
+ const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
76
+ const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
77
+
78
+ // Virtual modules for hydration system
79
+ const VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';
80
+ const VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';
81
+ const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
82
+ const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
83
+
84
+ /** Vite payloads whose browser-side effects would overwrite the editor's own save update. */
85
+ function dropsEditorSaveUpdate(payload: HotPayload): boolean {
86
+ if (payload.type === 'full-reload') return true;
87
+ return payload.type === 'custom' && payload.event === 'conloca:content-update';
88
+ }
89
+
90
+ // Virtual module for CMS SPA source loading (dev only)
91
+ const VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';
92
+ const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
93
+
94
+ async function loadContentApiNode() {
95
+ return import('@conloca/content-api/node');
96
+ }
97
+
98
+ export interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {
99
+ /**
100
+ * Path to the content root directory. The single source of truth: the
101
+ * integration publishes it (via process.env.CONLOCA_CONTENT_ROOT) to
102
+ * createConlocaCollections(), so the content config needs no copy.
103
+ */
104
+ contentRoot: string;
105
+ canvasDir?: string;
106
+ route?: string; // Default: /__cms
107
+ puckConfigPath: string; // Path to the puck config module (should be .tsx file with React components)
108
+ schemasPath?: string; // Path to the schemas module (exports { dataSchemas, pageSchemas, mdxComponents })
109
+
110
+ /**
111
+ * Default layout for content pages.
112
+ * When provided without routing config, enables routing with catch-all pattern.
113
+ * For multi-route setups, use routing.routes.{name}.layout instead.
114
+ *
115
+ * @example './src/layouts/Layout.astro'
116
+ */
117
+ layout?: string;
118
+
119
+ routing?: RoutingConfigInput; // Content page routing configuration
120
+ templates?: Record<string, TemplateConfig>; // Page creation templates
121
+
122
+ /**
123
+ * Paths to scan for hydratable components.
124
+ * Components using withHydration() in these directories are auto-discovered.
125
+ *
126
+ * @example ['src/components/puck']
127
+ */
128
+ componentPaths?: string[];
129
+
130
+ /**
131
+ * Folders to scan for locally-authored MDX components. Their
132
+ * `interface Props { ... }` is parsed into the editor's prop
133
+ * panel automatically — no hand-written descriptors needed.
134
+ *
135
+ * Combined with the MDX usage scan (which picks up imports from
136
+ * npm packages like `@astrojs/starlight/components`), this powers
137
+ * the auto-discover registry served at `/__cms/api/registry`.
138
+ *
139
+ * Paths are project-relative. Defaults to `['src/components/mdx']`.
140
+ *
141
+ * @example ['src/components/mdx', 'src/components/prose']
142
+ */
143
+ mdxComponentFolders?: string[];
144
+
145
+ /**
146
+ * Path to the assets directory for image uploads.
147
+ * When provided, enables the Media Library and asset upload API routes.
148
+ * The editor stores links under the public URL derived from this folder.
149
+ * The site must serve the folder from its publicDir, directly or through a link, or dev and build fail.
150
+
151
+ *
152
+ * @example './public/assets'
153
+ */
154
+ assetsPath?: string;
155
+
156
+ /**
157
+ * CSS files to load in the CMS editor for component preview styling.
158
+ *
159
+ * Each file is processed by Vite (Tailwind, PostCSS, etc.) and injected
160
+ * directly into Puck's preview iframe `<head>`. Site CSS never enters the
161
+ * CMS admin's parent document, so host-site styles cannot bleed into the
162
+ * CMS chrome (drawer, sidebar, etc.).
163
+ *
164
+ * @example './src/styles/global.css'
165
+ * @example ['./src/styles/global.css', './src/styles/theme.css']
166
+ */
167
+ siteStyles?: string | string[];
168
+
169
+ /**
170
+ * Narrow CSS path injected into the MDX editor's admin document while the
171
+ * editor is mounted. Use this to ship host-component styling
172
+ * (`.conloca-aside`, `.conloca-card`, etc.) so the editor preview matches
173
+ * the published surface, WITHOUT pulling in host Tailwind utilities or
174
+ * `:root` token overrides that would collide with admin chrome.
175
+ *
176
+ * What belongs here: stylesheets that target only host-component class
177
+ * selectors. Examples: `./src/styles/asides.css`,
178
+ * `./src/styles/starlight-components.css`, `./src/styles/code-blocks.css`.
179
+ *
180
+ * What does NOT belong: the host's `global.css` (Tailwind base, theme,
181
+ * utilities) or any
182
+ * stylesheet with `body`, `:root`, or `*` rules that would override
183
+ * admin chrome. Those go in `siteStyles` instead — that path is only
184
+ * injected into the Puck iframe, never the admin shell.
185
+ *
186
+ * @example ['./src/styles/asides.css', './src/styles/starlight-components.css']
187
+ */
188
+ editorStyles?: string | string[];
189
+
190
+ /**
191
+ * Route URL whose styles + content-wrapper shape get applied when
192
+ * editing a standalone FRAGMENT (not a page). Fragments aren't tied to a
193
+ * specific route, but they're consumed inside pages — so the
194
+ * authoring experience should look like the user's actual site. The
195
+ * editor fetches this route's CSS (via `/api/styles?url=…`) and its
196
+ * content-root wrapper (via `/api/content-wrapper?url=…`) the same
197
+ * way it does for pages, then renders the fragment inside that frame.
198
+ *
199
+ * Pick a representative content page on your site — typically the
200
+ * site root or a docs landing page. Hosts that ship rich typography
201
+ * benefit most; for hosts whose body bg matches the editor chrome,
202
+ * the value barely matters. Defaults to `/` (site root).
203
+ *
204
+ * Per-fragment overrides via fragment frontmatter remain on the roadmap
205
+ * for cases where one fragment ships only inside a specific layout.
206
+ *
207
+ * @example '/getting-started/'
208
+ */
209
+ fragmentPreviewRoute?: string;
210
+
211
+ /**
212
+ * Inline CSS to inject into the editor's `conloca-host-preview`
213
+ * layer, applied AFTER auto-discovered host stylesheets. The
214
+ * editor's content surround, prose card, and individual MDX
215
+ * components all surface here; anything you write at this layer
216
+ * wins on cascade order against the auto-discovery output (same
217
+ * specificity, later layer position).
218
+ *
219
+ * Use for one-off overrides when:
220
+ * - Your host body bg doesn't read well behind the editor chrome
221
+ * and you want a specific color regardless.
222
+ * - You want a different prose surface only inside the editor
223
+ * (eg lighter for accessibility while authoring).
224
+ * - A component renders correctly on the published page but
225
+ * needs a small visual tweak in the editor — toolbar gutter,
226
+ * focus ring, etc.
227
+ *
228
+ * Pure raw CSS. Conloca does no scoping or transformation, so any
229
+ * selector you write needs to be specific enough not to leak into
230
+ * the admin chrome (the chrome's selectors live in the `cms-admin`
231
+ * layer, which sits LOWER in the cascade — so without explicitly
232
+ * naming admin selectors, your CSS only reaches host components
233
+ * and the content surround).
234
+ *
235
+ * @example `
236
+ * /* Force a darker editor body even though the live page is light. *\/
237
+ * body { background-color: #0a0a0f; }
238
+ * /* Custom focus ring for the prose surface. *\/
239
+ * .conloca-prose--editor:focus-within { outline: 2px solid hotpink; }
240
+ * `
241
+ */
242
+ editorCSS?: string;
243
+
244
+ /**
245
+ * The site's supported locales and default locale.
246
+ *
247
+ * When set, Conloca uses this list as the single source of truth for
248
+ * locale detection — folders or filename suffixes that don't match
249
+ * one of these locales are left in the slug rather than silently
250
+ * classified as a language. When omitted, falls back to the
251
+ * `globalLocales` field in `<contentRoot>/sites.json` (the existing
252
+ * behavior; preserved for backwards compatibility).
253
+ *
254
+ * Use one of the framework-bridge helpers exported from
255
+ * `@conloca/astro-cms/node` to keep the declaration in a single spot:
256
+ *
257
+ * @example Pass Astro's i18n config directly:
258
+ * ```ts
259
+ * import { conlocaCMS, localesFromAstroI18n } from '@conloca/astro-cms/node';
260
+ * const i18n = { defaultLocale: 'en', locales: ['en', 'de'] };
261
+ * defineConfig({
262
+ * i18n,
263
+ * integrations: [conlocaCMS({ locales: localesFromAstroI18n(i18n) })],
264
+ * });
265
+ * ```
266
+ *
267
+ * @example Pass a literal list:
268
+ * ```ts
269
+ * conlocaCMS({ locales: { list: ['en', 'de'], defaultLocale: 'en' } });
270
+ * ```
271
+ */
272
+ locales?: ConlocaLocales;
273
+ }
274
+
275
+ // Template for content change listener virtual module
276
+ const contentChangeListener = () => {
277
+ return `
278
+ // Content change listener that uses Vite HMR
279
+ if (import.meta.hot) {
280
+ import.meta.hot.on('conloca:content-update', (data) => {
281
+ console.log('[Conloca CMS] Content updated, invalidating cache:', data);
282
+
283
+ // Get the query client from the global scope and invalidate
284
+ if (window.__QUERY_CLIENT__) {
285
+ window.__QUERY_CLIENT__.invalidateQueries();
286
+ }
287
+ });
288
+ }
289
+
290
+ export default {};
291
+ `;
292
+ };
293
+
294
+ // Template for the puck config loader virtual module
295
+ const puckConfigLoader = (absolutePuckPath: string, cmsSpaDistDir?: string) => {
296
+ // We need to ensure the preamble executes before ANY module evaluation
297
+ // So we'll use a dynamic import after the preamble is set up
298
+ const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/puck-config.js` : '@conloca/cms-spa/puck-config';
299
+ return `
300
+ // React refresh preamble first — it must be the first import, see its module
301
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
302
+
303
+ // Import the setPuckConfig function from cms-spa
304
+ import { setPuckConfig } from '${puckConfigImport}';
305
+
306
+ // Now dynamically import the config after preamble is ready
307
+ const puckConfigPromise = import('${absolutePuckPath}');
308
+
309
+ // Handle the initial load
310
+ puckConfigPromise.then(module => {
311
+ const puckConfig = module.default;
312
+ setPuckConfig(puckConfig);
313
+
314
+ // Hook into React Fast Refresh to detect component updates
315
+ if (window.__registerBeforePerformReactRefresh) {
316
+ window.__registerBeforePerformReactRefresh(async () => {
317
+ // Re-import the config module to get updated components
318
+ const newModule = await import('${absolutePuckPath}');
319
+ setPuckConfig(newModule.default);
320
+ });
321
+ }
322
+ });
323
+
324
+ // Accept HMR for this module itself
325
+ if (import.meta.hot) {
326
+ import.meta.hot.accept();
327
+ }
328
+
329
+ // Export the promise so the module has a default export
330
+ export default puckConfigPromise.then(m => m.default);
331
+ `;
332
+ };
333
+
334
+ // Template for the schemas loader virtual module
335
+ const schemasLoader = (absoluteSchemasPath: string, cmsSpaDistDir?: string) => {
336
+ const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/page-schemas.js` : '@conloca/cms-spa/page-schemas';
337
+ const mdxComponentsImport = cmsSpaDistDir
338
+ ? `${cmsSpaDistDir}/ts/mdx-components.js`
339
+ : '@conloca/cms-spa/mdx-components';
340
+ const dataSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/data-schemas.js` : '@conloca/cms-spa/data-schemas';
341
+ // The host's schemas file may transitively import React components (the
342
+ // `Editor` field on an MdxComponentDescriptor can be a JSX/TSX
343
+ // component), and so does cms-spa's own mdx-components entry. Vite's React
344
+ // plugin requires the Fast Refresh preamble to run before any such module
345
+ // is evaluated, so we import it first and then dynamically import the
346
+ // schemas file — matching the pattern used by the Puck config loader above.
347
+ return `
348
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
349
+
350
+ import { setPageSchemas } from '${pageSchemasImport}';
351
+ import { installHostAuthoredMdxComponents } from '${mdxComponentsImport}';
352
+ import { setDataSchemas } from '${dataSchemasImport}';
353
+
354
+ const schemasPromise = import('${absoluteSchemasPath}');
355
+
356
+ schemasPromise.then((schemas) => {
357
+ if (schemas.pageSchemas) {
358
+ setPageSchemas(schemas.pageSchemas);
359
+ }
360
+ if (schemas.mdxComponents) {
361
+ // Slotted installer, not setMdxComponents: this module and the SPA's
362
+ // /api/registry fetch settle in either order, and a bare set from the
363
+ // late one would overwrite the other's components.
364
+ installHostAuthoredMdxComponents(schemas.mdxComponents);
365
+ }
366
+ if (schemas.dataSchemas) {
367
+ setDataSchemas(schemas.dataSchemas);
368
+ }
369
+ });
370
+
371
+ if (import.meta.hot) {
372
+ import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
373
+ if (newModule?.pageSchemas) {
374
+ setPageSchemas(newModule.pageSchemas);
375
+ }
376
+ if (newModule?.mdxComponents) {
377
+ installHostAuthoredMdxComponents(newModule.mdxComponents);
378
+ }
379
+ if (newModule?.dataSchemas) {
380
+ setDataSchemas(newModule.dataSchemas);
381
+ }
382
+ });
383
+ }
384
+
385
+ export default schemasPromise;
386
+ `;
387
+ };
388
+
389
+ // Template for the site styles loader virtual module.
390
+ //
391
+ // Each CSS file is imported with Vite's `?inline` query so the full CSS
392
+ // pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet
393
+ // as a string — no `<style>` tag is injected into the CMS admin's parent
394
+ // `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles
395
+ // registry; the editor's iframe bridge then injects them directly into
396
+ // Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS
397
+ // chrome and confines it to the intended consumer (the preview).
398
+ const siteStylesLoader = (cssPaths: string[], cmsSpaDistDir?: string) => {
399
+ const imports = cssPaths
400
+ .map((p, i) => {
401
+ const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
402
+ return `import css${i} from '${absolutePath}?inline';`;
403
+ })
404
+ .join('\n');
405
+ const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
406
+ const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/site-styles.js` : '@conloca/cms-spa/site-styles';
407
+
408
+ return `
409
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
410
+ ${imports}
411
+ import { setSiteStyles } from '${siteStylesImport}';
412
+
413
+ setSiteStyles([${vars}]);
414
+
415
+ if (import.meta.hot) {
416
+ import.meta.hot.accept();
417
+ }
418
+
419
+ export default {};
420
+ `;
421
+ };
422
+
423
+ // Template for the editor styles loader virtual module — same shape as
424
+ // siteStylesLoader but feeds a different registry (`setEditorStyles`),
425
+ // consumed by the MDX editor's `useInjectHostStyles` call. Kept separate
426
+ // from `siteStyles` because the two surfaces have opposite cascade needs;
427
+ // see `packages/cms-spa/src/site-styles.ts` for the rationale.
428
+ const editorStylesLoader = (cssPaths: string[], cmsSpaDistDir?: string) => {
429
+ const imports = cssPaths
430
+ .map((p, i) => {
431
+ const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
432
+ return `import css${i} from '${absolutePath}?inline';`;
433
+ })
434
+ .join('\n');
435
+ const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
436
+ const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/site-styles.js` : '@conloca/cms-spa/site-styles';
437
+
438
+ return `
439
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
440
+ ${imports}
441
+ import { setEditorStyles } from '${siteStylesImport}';
442
+
443
+ setEditorStyles([${vars}]);
444
+
445
+ if (import.meta.hot) {
446
+ import.meta.hot.accept();
447
+ }
448
+
449
+ export default {};
450
+ `;
451
+ };
452
+
453
+ /**
454
+ * Whether a resolved package directory came from the registry rather than from
455
+ * a workspace. @conloca/cms-spa ships its sources so source maps resolve, so
456
+ * the files on disk no longer tell the two apart — the location does. Node
457
+ * resolves symlinks, so a registry install always sits under a node_modules
458
+ * directory (hoisted `<consumer>/node_modules/@conloca/cms-spa`, or isolated
459
+ * `…/node_modules/.bun/…/node_modules/@conloca/cms-spa`), while a workspace
460
+ * package or a cross-repo `bun link` resolves to its own checkout.
461
+ */
462
+ export function isRegistryInstall(packageDir: string): boolean {
463
+ return packageDir.split(/[\\/]/).includes('node_modules');
464
+ }
465
+
466
+ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
467
+ const cmsRoute = options.route || '/__cms';
468
+
469
+ // Resolve @conloca/cms-spa package directory for absolute imports in virtual
470
+ // module templates. Bare specifiers like '@conloca/cms-spa/puck-config'
471
+ // resolve from the Vite project root, which works when deps are hoisted
472
+ // (npm consumers) but fails with isolated linkers (e.g. bun). Using the
473
+ // resolved absolute path bypasses the project-root lookup entirely.
474
+ let cmsSpaDir: string | undefined;
475
+ try {
476
+ const pkgUrl = import.meta.resolve('@conloca/cms-spa/package.json');
477
+ cmsSpaDir = dirname(pkgUrl.startsWith('file://') ? fileURLToPath(pkgUrl) : pkgUrl);
478
+ } catch {
479
+ // Package not resolvable — virtual modules will fall back to bare specifiers
480
+ }
481
+ const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, 'dist') : undefined;
482
+
483
+ // Normalize routing config and resolve defaults
484
+ // Pass top-level layout to enable routing when layout provided without explicit routing config
485
+ const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
486
+
487
+ // Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths
488
+ // Scanner handles missing directories gracefully (fast-glob returns empty array)
489
+ const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);
490
+
491
+ // Scan for hydratable components - this promise is awaited in the virtual module loader
492
+ const hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]> = scanForHydratableComponents(
493
+ componentPaths,
494
+ process.cwd(),
495
+ ).then((discoveries) => {
496
+ if (discoveries.length > 0) {
497
+ console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
498
+ }
499
+ return discoveries;
500
+ });
501
+
502
+ // Build resolved routing config with all defaults applied
503
+ let resolvedRoutingConfig: ResolvedRoutingConfig | undefined;
504
+ // The site's final output mode, read at config:done because integrations
505
+ // that run after this one may still switch it. The duplicate-route-name check
506
+ // below keys on it.
507
+ let outputMode: 'static' | 'server' | undefined;
508
+ if (routingConfig?.enabled !== false && routingConfig) {
509
+ const resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>> = {};
510
+ for (const [name, config] of Object.entries(routingConfig.routes || {})) {
511
+ resolvedRoutes[name] = resolveRouteConfig(config);
512
+ }
513
+ resolvedRoutingConfig = {
514
+ enabled: routingConfig.enabled ?? true,
515
+ routes: resolvedRoutes,
516
+ fallback: routingConfig.fallback ?? '404',
517
+ onConflict: routingConfig.onConflict ?? 'warn',
518
+ // Both provisional. sites.json cannot be read here — integration
519
+ // construction is synchronous — so `astro:config:setup` below
520
+ // re-resolves them against the declared sites before any consumer
521
+ // loads. See `resolveSiteName` and `resolveLocale`.
522
+ siteName: routingConfig.siteName ?? 'default',
523
+ locale: routingConfig.locale ?? 'en',
524
+ };
525
+ }
526
+
527
+ // SPA config passed to route handler via virtual module
528
+ // This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true
529
+ // `mdxPagesEnabled` and `resolvedMdxPages` start uninitialized; the
530
+ // `astro:config:setup` hook reads sites.json (the canonical home for
531
+ // per-site `mdxPages` paths) and mutates them before any virtual
532
+ // module load fires — `load(id)` runs at request time, after the
533
+ // hook completes.
534
+ const spaConfig: {
535
+ basename: string;
536
+ apiBaseUrl: string;
537
+ siteBaseUrl?: string;
538
+ enableDevtools: boolean;
539
+ queryClientOptions: unknown;
540
+ schemasPath?: string;
541
+ projectRoot: string;
542
+ templates?: unknown;
543
+ mdxPagesEnabled: boolean;
544
+ locales?: { list: string[]; defaultLocale: string };
545
+ assetRefBase?: string;
546
+ dataBindings?: EditorDataBindings;
547
+ } = {
548
+ basename: cmsRoute,
549
+ apiBaseUrl: `${cmsRoute}/api`,
550
+ siteBaseUrl: options.siteBaseUrl,
551
+ enableDevtools: options.enableDevtools ?? true,
552
+ queryClientOptions: options.queryClientOptions,
553
+ schemasPath: options.schemasPath,
554
+ projectRoot: process.cwd(),
555
+ templates: options.templates,
556
+ // True when at least one site in sites.json declares an `mdxPages`
557
+ // path. Drives the "Document page" option in the create-page dialog.
558
+ // Initialized in the `astro:config:setup` hook below.
559
+ mdxPagesEnabled: false,
560
+ // Forward the locale list so the SPA stops hardcoding en/nl/fr in
561
+ // the create-page dialog. The integration receives this from the
562
+ // top-level `locales` option, which can in turn be produced by
563
+ // `localesFromAstroI18n` / `localesFromStarlight`.
564
+ locales: options.locales ? { list: options.locales.list, defaultLocale: options.locales.defaultLocale } : undefined,
565
+ };
566
+
567
+ // Resolved mdxPages path, populated from sites.json in the
568
+ // config:setup hook. Used by the registry endpoint and content
569
+ // watcher. `null` means no site declares an `mdxPages` path — .mdx
570
+ // files (if any) fall back to living alongside Puck pages.
571
+ let resolvedMdxPages: string | null = null;
572
+
573
+ // One root for every path this plugin resolves against, so a scan and an
574
+ // endpoint can never disagree about where the project is.
575
+ const projectRoot = process.cwd();
576
+
577
+ // Registry scan inputs, resolved ONCE: the dev endpoint below and anything
578
+ // that reads them off the descriptor channel must never disagree about which
579
+ // folders and content root were scanned.
580
+ // `contentRoot` is re-pointed at sites.json's `mdxPages` in config:setup,
581
+ // once that file has been read.
582
+ let registryScan: MdxRegistryScanOptions = {
583
+ contentRoot: options.contentRoot,
584
+ componentFolders: options.mdxComponentFolders ?? ['src/components/mdx'],
585
+ projectRoot,
586
+ };
587
+
588
+ let refreshConlocaContent: (() => Promise<void>) | undefined;
589
+
590
+ return {
591
+ name: '@conloca/astro-cms',
592
+ hooks: {
593
+ 'astro:config:setup': async ({ config, updateConfig, injectRoute, command, logger }) => {
594
+ // Publish the content root for createConlocaCollections(): the
595
+ // content config loads later in this same process, so the contentRoot
596
+ // configured here is the single source of truth. Raw on purpose —
597
+ // FileSystemContentAPI keys its process-wide index cache on the
598
+ // string as-passed, and the dev content watcher uses the raw option;
599
+ // resolving here would split one cache into two and dev refreshes
600
+ // would read stale content.
601
+ process.env.CONLOCA_CONTENT_ROOT = options.contentRoot;
602
+ // Read sites.json — the canonical home for per-site config
603
+ // including the optional `mdxPages` field. Reading it here (once,
604
+ // at integration setup) gives us a single source of truth for
605
+ // the rest of the hook. `readSitesConfig` returns a safe default
606
+ // when the file is missing or malformed.
607
+ const sitesConfig = await readSitesConfig(options.contentRoot);
608
+ // Now that sites.json is known, replace the provisional site name and
609
+ // locale built at construction time. Resolving from the raw options
610
+ // (not the already-defaulted resolved config) is what makes the
611
+ // sites.json fallbacks reachable. Every consumer — the routing
612
+ // virtual module, the editor's data bindings below, and
613
+ // `astro:routes:resolved` — reads them after this, so they all
614
+ // observe the resolved values.
615
+ if (resolvedRoutingConfig) {
616
+ resolvedRoutingConfig.siteName = resolveSiteName(routingConfig?.siteName, sitesConfig.sites);
617
+ resolvedRoutingConfig.locale = resolveLocale(
618
+ routingConfig?.locale,
619
+ options.locales?.defaultLocale,
620
+ resolvedRoutingConfig.siteName,
621
+ sitesConfig,
622
+ );
623
+ }
624
+ // Pick the first site that declares an `mdxPages` path. Today's
625
+ // integration supports a single `mdxPages` per project;
626
+ // multi-site `mdxPages` is a future expansion (would require
627
+ // fanning the watcher and registry scanner across all roots).
628
+ const firstSiteWithMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages);
629
+ resolvedMdxPages = firstSiteWithMdxPages?.mdxPages ?? null;
630
+ spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);
631
+ // The editor builds each page's data context in the browser from
632
+ // these, the same bindings the published page resolves with.
633
+ spaConfig.dataBindings = resolvedRoutingConfig?.enabled
634
+ ? toEditorDataBindings(resolvedRoutingConfig)
635
+ : undefined;
636
+
637
+ registryScan = { ...registryScan, contentRoot: resolvedMdxPages ?? options.contentRoot };
638
+ // Publish the resolved editor descriptors for other integrations in
639
+ // this build (see EDITOR_DESCRIPTORS_ENV_VAR): they read the same
640
+ // descriptors dev loads from `schemasPath`, `/api/registry` and
641
+ // `virtual:conloca-config` instead of taking these options again.
642
+ // schemasPath is absolutized because a reader may use it as an import
643
+ // specifier.
644
+ const editorDescriptors: EditorDescriptorChannel = {
645
+ ...(options.schemasPath ? { schemasPath: resolve(options.schemasPath) } : {}),
646
+ registry: registryScan,
647
+ ...(options.templates ? { templates: options.templates } : {}),
648
+ ...(spaConfig.dataBindings ? { dataBindings: spaConfig.dataBindings } : {}),
649
+ };
650
+ process.env[EDITOR_DESCRIPTORS_ENV_VAR] = JSON.stringify(editorDescriptors);
651
+
652
+ // Auto-inject fs.allow for external contentRoot (dev mode only)
653
+ const astroRoot = process.cwd();
654
+ const contentAbsolute = resolve(options.contentRoot);
655
+
656
+ // A missing content root used to produce an empty site that 404'd
657
+ // every page with no hint. Fail the build loudly; in dev (and sync)
658
+ // only warn — a brand-new project boots with an empty site and the
659
+ // CMS creates the directory on first save.
660
+ if (!existsSync(contentAbsolute)) {
661
+ const hint =
662
+ `Content root not found: ${contentAbsolute}. Create the directory ` +
663
+ '(git cannot track empty folders — add a .gitkeep) or fix contentRoot in conlocaCMS().';
664
+ if (command === 'build') {
665
+ throw new Error(`[Conloca] ${hint}`);
666
+ }
667
+ logger.warn(`${hint} Starting with an empty site.`);
668
+ }
669
+
670
+ // A content config that never declares Conloca collections yields
671
+ // an empty Astro collection, so the injected route resolves nothing
672
+ // and every page 404s with no other symptom. Astro exposes no hook
673
+ // that reveals resolved collections, so check the file itself.
674
+ const contentConfigProblem = findContentConfigProblem(astroRoot);
675
+ if (contentConfigProblem) {
676
+ const cause =
677
+ contentConfigProblem === 'missing'
678
+ ? 'No content config found.'
679
+ : 'Your content config does not declare Conloca collections.';
680
+ const hint = `${cause} Conloca pages will 404 until it does. Add this:\n\n${CONTENT_CONFIG_SNIPPET}\n`;
681
+ if (command === 'build') {
682
+ throw new Error(`[Conloca] ${hint}`);
683
+ }
684
+ logger.warn(hint);
685
+ }
686
+
687
+ // Every image the editor picks is stored under this base and served
688
+ // as-is by the published site. Derived in build too, so a media
689
+ // folder the site cannot serve fails there as well as in dev.
690
+ if (options.assetsPath) {
691
+ spaConfig.assetRefBase = deriveAssetRefBase(options.assetsPath, config.publicDir, config.base);
692
+ }
693
+
694
+ if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {
695
+ logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
696
+
697
+ updateConfig({
698
+ vite: {
699
+ server: {
700
+ fs: {
701
+ allow: [
702
+ searchForWorkspaceRoot(process.cwd()), // Preserve Vite default
703
+ contentAbsolute,
704
+ ],
705
+ },
706
+ },
707
+ },
708
+ });
709
+ }
710
+
711
+ // @puckeditor/core (and its zustand dependency) must always go through Vite's
712
+ // SSR resolver, in dev AND build. SSR-external modules are require()'d directly
713
+ // by Node, bypassing Vite's resolver — and `resolve.dedupe` below — entirely,
714
+ // which risks pulling in a stray React copy from outside the workspace.
715
+ const alwaysSsrNoExternal = ['@puckeditor/core'];
716
+ // In dev, linked workspace packages also need to be bundled so React resolves
717
+ // through Vite and HMR works from source (build mode uses their compiled dist output).
718
+ const devOnlySsrNoExternal = [/^@conloca\//];
719
+ const serverOnlyExternal = [
720
+ '@conloca/content-api',
721
+ '@conloca/content-api/node',
722
+ '@conloca/content-api/reader',
723
+ '@conloca/content-api/schemas',
724
+ '@conloca/mdx',
725
+ '@conloca/mdx/node',
726
+ ];
727
+ updateConfig({
728
+ vite: {
729
+ ssr: {
730
+ noExternal: command === 'dev' ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,
731
+ // Keep Node-only content packages (content-api, mdx) external so SSR
732
+ // builds do not try to bundle their server-only surfaces.
733
+ external: serverOnlyExternal,
734
+ },
735
+ resolve: {
736
+ // Dedupe React to avoid multiple instances when CMS SPA source is
737
+ // loaded from a workspace sibling package. Only list packages the
738
+ // consumer project declares directly — with bun's isolated linker,
739
+ // transitive deps (e.g. @tanstack/react-query) live in the owning
740
+ // package's node_modules and must NOT be forced to resolve from the
741
+ // consumer root (which would fail).
742
+ dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
743
+ alias: [
744
+ // Puck's richtext field render imports @tiptap/html. Its browser
745
+ // build throws off-browser ("generateHTML can only be used in a
746
+ // browser environment"), and its /server build fakes a browser
747
+ // with happy-dom — whose Window constructor reaches for
748
+ // node:vm's Script.runInContext, a stub on workerd, so every
749
+ // richtext section died there with "The 'contextifiedObject'
750
+ // argument must be an vm.Context". Both specifiers resolve to a
751
+ // shim that writes the markup as a string, with no DOM and no
752
+ // vm, so the same output comes out on every engine.
753
+ { find: /^@tiptap\/html(\/server)?$/, replacement: TIPTAP_HTML_SHIM_PATH },
754
+ ],
755
+ },
756
+ // react-dom@19 ships ./server as CJS under the workerd exports
757
+ // condition; without pre-bundling, the Cloudflare adapter's type-gen
758
+ // phase evaluates it raw in workerd ("require is not defined").
759
+ // Inert for Node builds.
760
+ optimizeDeps: { include: ['react-dom/server'] },
761
+ // Virtual modules for routing - needed in both dev and build
762
+ plugins: [
763
+ // Public page rendering should use Puck's server entry, not the full editor.
764
+ // The full editor pulls client-only store code into Astro prerendering.
765
+ {
766
+ name: 'conloca-puck-ssr-render-alias',
767
+ enforce: 'pre' as const,
768
+ async resolveId(id, importer, options) {
769
+ if (id === '@puckeditor/core' && options?.ssr) {
770
+ return this.resolve('@puckeditor/core/rsc', importer, { ...options, skipSelf: true });
771
+ }
772
+ return null;
773
+ },
774
+ },
775
+ // Alias acorn to a default+named shim only during SSR (page
776
+ // builds). Must NOT apply to the browser bundle, and must NOT
777
+ // apply to the shim's own `import ... from 'acorn'` — that
778
+ // static import has to reach the real package, not recurse.
779
+ {
780
+ name: 'conloca-acorn-ssr-alias',
781
+ enforce: 'pre' as const,
782
+ resolveId(id, importer, options) {
783
+ if (id === 'acorn' && options?.ssr && !importer?.endsWith('acorn-default.mjs')) {
784
+ return ACORN_DEFAULT_SHIM_PATH;
785
+ }
786
+ return null;
787
+ },
788
+ },
789
+ {
790
+ name: 'conloca-routing-virtual-modules',
791
+ resolveId(id) {
792
+ // Routing virtual modules (work in both dev and build)
793
+ if (id === VIRTUAL_ROUTING_CONFIG) {
794
+ return RESOLVED_ROUTING_CONFIG;
795
+ }
796
+ if (id === VIRTUAL_LAYOUT) {
797
+ return RESOLVED_LAYOUT;
798
+ }
799
+ if (id === VIRTUAL_PUCK_CONFIG) {
800
+ return RESOLVED_PUCK_CONFIG;
801
+ }
802
+ // Hydration virtual modules
803
+ if (id === VIRTUAL_HYDRATION_REGISTRY) {
804
+ return RESOLVED_HYDRATION_REGISTRY;
805
+ }
806
+ if (id === VIRTUAL_HYDRATION_ENTRY) {
807
+ return RESOLVED_HYDRATION_ENTRY;
808
+ }
809
+ return null;
810
+ },
811
+ async load(id) {
812
+ // Routing virtual modules
813
+ if (id === RESOLVED_ROUTING_CONFIG) {
814
+ if (resolvedRoutingConfig) {
815
+ return generateRoutingConfigModule(resolvedRoutingConfig);
816
+ }
817
+ // Return disabled config if routing not configured
818
+ return 'export default { enabled: false, routes: {}, fallback: "404", onConflict: "warn" };';
819
+ }
820
+ if (id === RESOLVED_LAYOUT) {
821
+ return generateLayoutModule(routingConfig);
822
+ }
823
+ if (id === RESOLVED_PUCK_CONFIG) {
824
+ return generatePuckConfigModule(options.puckConfigPath);
825
+ }
826
+ // Hydration virtual modules
827
+ if (id === RESOLVED_HYDRATION_REGISTRY) {
828
+ // Always scan - paths are auto-derived from puckConfigPath
829
+ const discoveries = await hydrationDiscoveriesPromise;
830
+ if (discoveries.length > 0) {
831
+ const entries = discoveries.map((d) => {
832
+ // Convert absolute path to Vite-friendly path
833
+ const relativePath = d.filePath.replace(process.cwd(), '');
834
+ return ` '${d.componentName}': {
835
+ loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
836
+ strategy: '${d.strategy}',
837
+ }`;
838
+ });
839
+ return `// Generated by @conloca/astro-cms scanner
840
+ export const componentRegistry = {
841
+ ${entries.join(',\n')}
842
+ };`;
843
+ }
844
+
845
+ // No hydratable components found - return empty registry
846
+ return 'export const componentRegistry = {};';
847
+ }
848
+ if (id === RESOLVED_HYDRATION_ENTRY) {
849
+ // Generate entry point that imports registry and calls initHydration
850
+ return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
851
+ import { componentRegistry } from 'virtual:conloca-hydration-registry'
852
+
853
+ // Auto-initialize hydration when this module loads
854
+ initHydration(componentRegistry)
855
+ `;
856
+ }
857
+ return null;
858
+ },
859
+ },
860
+ ],
861
+ },
862
+ });
863
+
864
+ // Content page routes - works in both dev and build
865
+ if (resolvedRoutingConfig?.enabled) {
866
+ for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
867
+ logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
868
+ injectRoute({
869
+ pattern: routeConfig.pattern,
870
+ entrypoint: PAGE_HANDLER_PATH,
871
+ prerender: routeConfig.prerender,
872
+ });
873
+ }
874
+ }
875
+
876
+ // The sandbox frame document ContentSandbox loads for MDX previews.
877
+ // Root-absolute by contract (SANDBOX_FRAME_PATH in @conloca/mdx) and
878
+ // needed wherever the editor runs — anything that serves the editor
879
+ // serves the same path. Injected outside the dev-only block: a
880
+ // production editor build needs the frame too.
881
+ //
882
+ // On-demand by necessity — the response carries the sandbox CSP, which
883
+ // a prerendered file cannot — so injecting it into a fully static site
884
+ // fails that build with NoAdapterInstalled. Such a site has no runtime
885
+ // editor to serve it to; dev serves it whatever the output mode.
886
+ if (command === 'dev' || config.output !== 'static') {
887
+ injectRoute({
888
+ pattern: '/api/v1/mdx/sandbox-frame',
889
+ entrypoint: SANDBOX_FRAME_HANDLER_PATH,
890
+ prerender: false,
891
+ });
892
+ }
893
+
894
+ // Only inject CMS admin routes and dev-specific config in dev mode
895
+ if (command !== 'dev') return;
896
+
897
+ // Pass options via Vite define for API routes
898
+ updateConfig({
899
+ vite: {
900
+ define: {
901
+ 'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),
902
+ 'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),
903
+ 'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),
904
+ 'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),
905
+ // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are no
906
+ // longer surfaced as env vars — the content-api reads them
907
+ // directly from sites.json under `contentRoot` at request
908
+ // time. See `readSitesConfig()` and `SitesConfig.sites[name].mdxPages`.
909
+ // Default route URL the fragment editor uses for style /
910
+ // wrapper discovery. See `fragmentPreviewRoute` option doc
911
+ // above. `/` is a sane fallback for most layouts.
912
+ 'import.meta.env.CONLOCA_FRAGMENT_PREVIEW_ROUTE': JSON.stringify(options.fragmentPreviewRoute || '/'),
913
+ // Raw CSS the host wants injected into the editor's
914
+ // `conloca-host-preview` layer for visual overrides.
915
+ // See `editorCSS` option doc above for use cases.
916
+ 'import.meta.env.CONLOCA_EDITOR_CSS': JSON.stringify(options.editorCSS || ''),
917
+ // Top-level locales. Vite `define` does literal text
918
+ // substitution, so this inlines as either a JS array or `null`.
919
+ // The runtime handler reads it as-is — no JSON.parse needed.
920
+ 'import.meta.env.CONLOCA_LOCALES': JSON.stringify(options.locales?.list ?? null),
921
+ 'import.meta.env.CONLOCA_DEFAULT_LOCALE': JSON.stringify(options.locales?.defaultLocale || ''),
922
+ },
923
+ optimizeDeps: {
924
+ // Exclude the puck config from optimization to avoid the outdated dep error
925
+ exclude: [options.puckConfigPath],
926
+ // Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization
927
+ // which causes React dual-instance issues when Vite discovers new deps dynamically
928
+ include: [
929
+ // React core - must be pre-bundled together
930
+ 'react',
931
+ 'react-dom',
932
+ 'react-dom/client',
933
+ 'react/jsx-runtime',
934
+ 'react/jsx-dev-runtime',
935
+ // CMS dependencies
936
+ '@mdxeditor/editor',
937
+ '@puckeditor/core',
938
+ '@tanstack/react-query',
939
+ '@tanstack/react-query-devtools',
940
+ 'react-router-dom',
941
+ '@radix-ui/react-dialog',
942
+ '@radix-ui/react-select',
943
+ 'lucide-react',
944
+ 'clsx',
945
+ 'tailwind-merge',
946
+ // Content processing
947
+ 'zod',
948
+ 'yaml',
949
+ 'nanoid',
950
+ 'sort-keys',
951
+ // MDX processing
952
+ '@mdx-js/mdx',
953
+ 'remark-frontmatter',
954
+ 'remark-gfm',
955
+ 'remark-mdx-frontmatter',
956
+ ],
957
+ },
958
+ plugins: [
959
+ // Normalize @conloca/* imports from symlinked source files (bun link).
960
+ // When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports
961
+ // resolve relative to the real filesystem location, creating duplicate
962
+ // module instances. This plugin re-resolves them from the consumer
963
+ // project root so all @conloca packages use the same module identity.
964
+ {
965
+ name: 'conloca-resolve-normalizer',
966
+ enforce: 'pre' as const,
967
+ async resolveId(source, importer) {
968
+ // Only normalize @conloca/* bare specifiers
969
+ if (!source.startsWith('@conloca/')) return null;
970
+ // Only when imported from outside the project (symlinked source files)
971
+ if (!importer || importer.startsWith(astroRoot)) return null;
972
+ // Skip virtual modules (prefixed with \0)
973
+ if (importer.startsWith('\0')) return null;
974
+ // Re-resolve from project root to ensure consumer's node_modules is used
975
+ const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });
976
+ return resolved;
977
+ },
978
+ },
979
+ {
980
+ name: 'conloca-dev-virtual-modules',
981
+ resolveId(id) {
982
+ // Dev-only config module for cms-handler.ts
983
+ if (id === VIRTUAL_CONFIG_MODULE) {
984
+ return RESOLVED_VIRTUAL_CONFIG;
985
+ }
986
+ if (id === VIRTUAL_REFRESH_PREAMBLE) {
987
+ return RESOLVED_REFRESH_PREAMBLE;
988
+ }
989
+ if (id === `${cmsRoute}/puck-entry.js`) {
990
+ return id;
991
+ }
992
+ if (id === `${cmsRoute}/content-listener.js`) {
993
+ return id;
994
+ }
995
+ if (id === `${cmsRoute}/schemas-entry.js`) {
996
+ return id;
997
+ }
998
+ if (id === `${cmsRoute}/site-styles.js`) {
999
+ return id;
1000
+ }
1001
+ if (id === `${cmsRoute}/editor-styles.js`) {
1002
+ return id;
1003
+ }
1004
+ if (id === VIRTUAL_CMS_SPA_ENTRY) {
1005
+ return RESOLVED_CMS_SPA_ENTRY;
1006
+ }
1007
+ if (id === `${cmsRoute}/cms-spa-entry.js`) {
1008
+ return RESOLVED_CMS_SPA_ENTRY;
1009
+ }
1010
+ return null;
1011
+ },
1012
+ load(id) {
1013
+ // Dev-only config module for cms-handler.ts
1014
+ if (id === RESOLVED_VIRTUAL_CONFIG) {
1015
+ return `export default ${JSON.stringify(spaConfig)};`;
1016
+ }
1017
+ if (id === RESOLVED_REFRESH_PREAMBLE) {
1018
+ return reactRefreshPreamble;
1019
+ }
1020
+ if (id === `${cmsRoute}/puck-entry.js`) {
1021
+ const absolutePuckPath = options.puckConfigPath.startsWith('.')
1022
+ ? `/${options.puckConfigPath.slice(2)}`
1023
+ : options.puckConfigPath;
1024
+
1025
+ return puckConfigLoader(absolutePuckPath, cmsSpaDistDir);
1026
+ }
1027
+ if (id === `${cmsRoute}/content-listener.js`) {
1028
+ return contentChangeListener();
1029
+ }
1030
+ if (id === `${cmsRoute}/schemas-entry.js`) {
1031
+ if (options.schemasPath) {
1032
+ const absoluteSchemasPath = options.schemasPath.startsWith('.')
1033
+ ? `/${options.schemasPath.slice(2)}`
1034
+ : options.schemasPath;
1035
+ return schemasLoader(absoluteSchemasPath, cmsSpaDistDir);
1036
+ }
1037
+ return 'export default {};';
1038
+ }
1039
+ if (id === `${cmsRoute}/site-styles.js`) {
1040
+ if (options.siteStyles) {
1041
+ const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];
1042
+ return siteStylesLoader(paths, cmsSpaDistDir);
1043
+ }
1044
+ return 'export default {};';
1045
+ }
1046
+ if (id === `${cmsRoute}/editor-styles.js`) {
1047
+ if (options.editorStyles) {
1048
+ const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];
1049
+ return editorStylesLoader(paths, cmsSpaDistDir);
1050
+ }
1051
+ return 'export default {};';
1052
+ }
1053
+ if (id === RESOLVED_CMS_SPA_ENTRY) {
1054
+ // Detect whether cms-spa is a workspace checkout (import its
1055
+ // source for HMR) or a registry install (import its built
1056
+ // entry). Reuses `cmsSpaDir` resolved at plugin setup time.
1057
+ let cmsSpaImport: string;
1058
+ if (cmsSpaDir && !isRegistryInstall(cmsSpaDir)) {
1059
+ const realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');
1060
+ // Prefer the consumer-side symlink path when @conloca/cms-spa is
1061
+ // linked in from another workspace (e.g. cross-repo `bun link`).
1062
+ // Importing via the symlink path keeps `react`/`react-dom`
1063
+ // resolving through the consumer's node_modules walk, which
1064
+ // prevents duplicate React instances inside the CMS SPA.
1065
+ // Same-workspace installs either don't expose this path or
1066
+ // point at the same underlying file, so behavior and HMR
1067
+ // are preserved.
1068
+ const linkedSrcMainPath = join(
1069
+ astroRoot,
1070
+ 'node_modules',
1071
+ '@conloca',
1072
+ 'cms-spa',
1073
+ 'src',
1074
+ 'main.tsx',
1075
+ );
1076
+
1077
+ // Workspace mode: import source for HMR
1078
+ cmsSpaImport = `import '${existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath}';`;
1079
+ } else {
1080
+ // npm mode, and the fallback when the package cannot be
1081
+ // resolved: import the pre-built SPA mounting entry
1082
+ cmsSpaImport = "import '@conloca/cms-spa/main';";
1083
+ }
1084
+
1085
+ return `
1086
+ // React refresh preamble first — it must be the first import, see its module
1087
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
1088
+
1089
+ // Import cms-spa through Vite
1090
+ // Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
1091
+ ${cmsSpaImport}
1092
+
1093
+ // Accept HMR
1094
+ if (import.meta.hot) {
1095
+ import.meta.hot.accept();
1096
+ }
1097
+ `;
1098
+ }
1099
+ return null;
1100
+ },
1101
+ },
1102
+ {
1103
+ // Per-page styles endpoint. Fetches the live HTML for the
1104
+ // route and returns every `<style>` block and `<link
1105
+ // rel="stylesheet">` it lists — the same set of stylesheets
1106
+ // the browser paints with.
1107
+ name: 'conloca-styles-endpoint',
1108
+ apply: 'serve' as const,
1109
+ configureServer(server) {
1110
+ server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());
1111
+ },
1112
+ },
1113
+ {
1114
+ // Per-route content-wrapper endpoint. Fetches the live page
1115
+ // HTML and returns the host's content-root element shape
1116
+ // (`{ tagName, className }`) so the editor can render its
1117
+ // contenteditable inside a clone of that wrapper — letting
1118
+ // the host's CSS (eg `article.card { background: … }`) paint
1119
+ // the editor's content surface naturally, with no per-color
1120
+ // bridging.
1121
+ name: 'conloca-content-wrapper-endpoint',
1122
+ apply: 'serve' as const,
1123
+ configureServer(server) {
1124
+ server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());
1125
+ },
1126
+ },
1127
+ {
1128
+ // Registry + render endpoints are paired: the registry
1129
+ // builds the list of legal component sources, and the
1130
+ // render endpoint validates every incoming `source`
1131
+ // against that list before passing it to ssrLoadModule.
1132
+ // Constructing both in one configureServer hook means
1133
+ // they share the same memoized scan — no cross-plugin
1134
+ // state, no startup-order race.
1135
+ //
1136
+ // - Registry: scans MDX content for imports + usages and
1137
+ // the configured local component folders for
1138
+ // `interface Props { ... }`, merges into a single
1139
+ // descriptor list, returns it as JSON. The SPA fetches
1140
+ // this on mount and seeds `setMdxComponents`,
1141
+ // replacing the hand-written `mdx-components.tsx` flow.
1142
+ // - Render: renders a single MDX component (Aside,
1143
+ // Card, …) via Astro's Container API so the CMS editor
1144
+ // can display the real framework markup, paired with
1145
+ // the per-page CSS from the styles endpoint above.
1146
+ name: 'conloca-registry-and-render-endpoints',
1147
+ apply: 'serve' as const,
1148
+ configureServer(server) {
1149
+ const registry = createRegistryEndpoint(registryScan);
1150
+ server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
1151
+ server.middlewares.use(
1152
+ `${cmsRoute}/api/render`,
1153
+ createRenderEndpoint(server, registry.getAllowedSources),
1154
+ );
1155
+
1156
+ // Invalidate the cached scan whenever an .mdx file or
1157
+ // any component file changes. Coarse for now — every
1158
+ // change re-scans everything; cheap enough for typical
1159
+ // project sizes. `.cms.json` sidecars also trigger
1160
+ // invalidation so host overrides apply live without a
1161
+ // dev-server restart.
1162
+ const onFsChange = (filepath: string) => {
1163
+ if (/\.(mdx|astro|tsx|d\.ts|cms\.json)$/.test(filepath)) registry.invalidate();
1164
+ };
1165
+ server.watcher.on('add', onFsChange);
1166
+ server.watcher.on('change', onFsChange);
1167
+ server.watcher.on('unlink', onFsChange);
1168
+ },
1169
+ },
1170
+ {
1171
+ // The Puck component vocabulary: every component the config
1172
+ // declares, with its fields, read from source and never
1173
+ // executed — so an agent editing a page can find out what it
1174
+ // may compose with. A build that publishes the vocabulary
1175
+ // reads the same config through the same entry
1176
+ // (`./puck-manifest`), never describing components a second
1177
+ // way.
1178
+ name: 'conloca-components-endpoint',
1179
+ apply: 'serve' as const,
1180
+ configureServer(server) {
1181
+ server.middlewares.use(
1182
+ `${cmsRoute}/api/components`,
1183
+ createComponentsEndpoint(
1184
+ endpointReaderOptions({ puckConfigPath: options.puckConfigPath, projectRoot }),
1185
+ ),
1186
+ );
1187
+ },
1188
+ },
1189
+ {
1190
+ name: 'conloca-content-watcher',
1191
+ async configureServer(server) {
1192
+ const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();
1193
+
1194
+ // Initialize content API using the extracted function.
1195
+ // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are
1196
+ // read from sites.json by the content-api itself; we
1197
+ // don't pass them here.
1198
+ const contentApi = await createContentAPI({
1199
+ contentRoot: options.contentRoot,
1200
+ canvasDir: options.canvasDir || './canvas',
1201
+ ...(options.locales && {
1202
+ availableLocales: options.locales.list,
1203
+ defaultLocale: options.locales.defaultLocale,
1204
+ }),
1205
+ });
1206
+
1207
+ // Only add explicit watchers if content is outside the Astro project
1208
+ const { resolve } = await import('node:path');
1209
+ const astroRoot = process.cwd();
1210
+ const contentAbsolute = resolve(options.contentRoot);
1211
+ const canvasAbsolute = resolve(options.canvasDir || './canvas');
1212
+
1213
+ const foldersToWatch = [];
1214
+
1215
+ if (!contentAbsolute.startsWith(astroRoot)) {
1216
+ console.log(
1217
+ `[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`,
1218
+ );
1219
+ foldersToWatch.push(options.contentRoot);
1220
+ } else {
1221
+ console.log(
1222
+ `[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`,
1223
+ );
1224
+ }
1225
+
1226
+ if (!canvasAbsolute.startsWith(astroRoot)) {
1227
+ console.log(
1228
+ `[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`,
1229
+ );
1230
+ foldersToWatch.push(options.canvasDir || './canvas');
1231
+ } else {
1232
+ console.log(
1233
+ `[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`,
1234
+ );
1235
+ }
1236
+
1237
+ if (foldersToWatch.length > 0) {
1238
+ server.watcher.add(foldersToWatch);
1239
+ }
1240
+
1241
+ // Set up HMR for content changes using extracted handlers.
1242
+ // The watcher uses `mdxPagesRoot` to flag events under
1243
+ // the mdx tree (so docs-loader can refresh). The value
1244
+ // comes from sites.json via `resolvedMdxPages`.
1245
+ const handlers = createContentWatchHandlers(
1246
+ contentApi,
1247
+ {
1248
+ contentRoot: options.contentRoot,
1249
+ canvasDir: options.canvasDir || './canvas',
1250
+ ...(resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }),
1251
+ },
1252
+ server.ws,
1253
+ async (event) => {
1254
+ await refreshConlocaContent?.();
1255
+
1256
+ // Astro 6's content-virtual-mod plugin registers an explicit
1257
+ // file watcher on `.astro/data-store.json` only (see
1258
+ // dist/content/vite-plugin-content-virtual-mod.js: `devServer.watcher.add(dataStoreFile)`).
1259
+ // It does NOT watch the sibling `content-modules.mjs` (file
1260
+ // path → render function map). When Starlight's docsLoader
1261
+ // adds a new MDX entry at runtime, that file IS rewritten on
1262
+ // disk, but Vite's SSR moduleGraph keeps the stale module
1263
+ // and `renderEntry` throws UnknownContentCollectionError.
1264
+ // Force-reload the file ourselves; `reloadModule` is the
1265
+ // Vite API that re-runs the load hook on next SSR import.
1266
+ if (event.inMdxRoot) {
1267
+ const dotAstroModulesFile = resolve(astroRoot, '.astro', 'content-modules.mjs');
1268
+ const dotAstroAssetsFile = resolve(astroRoot, '.astro', 'content-assets.mjs');
1269
+ for (const env of Object.values(server.environments ?? {})) {
1270
+ if (!env?.moduleGraph) continue;
1271
+ for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {
1272
+ const mod = env.moduleGraph.getModuleById(filePath);
1273
+ if (!mod) continue;
1274
+ const envWithReload = env as unknown as {
1275
+ reloadModule?: (m: unknown) => void | Promise<void>;
1276
+ };
1277
+ if (typeof envWithReload.reloadModule === 'function') {
1278
+ void Promise.resolve(envWithReload.reloadModule(mod)).catch(() => undefined);
1279
+ } else {
1280
+ env.moduleGraph.invalidateModule(mod, undefined, Date.now(), true);
1281
+ }
1282
+ }
1283
+ env.hot?.send('astro:content-changed', {});
1284
+ }
1285
+ }
1286
+ },
1287
+ );
1288
+
1289
+ server.watcher.on('change', handlers.onChange);
1290
+ server.watcher.on('add', handlers.onAdd);
1291
+ server.watcher.on('unlink', handlers.onUnlink);
1292
+ },
1293
+ },
1294
+ {
1295
+ name: 'conloca-suppress-cms-save-reload',
1296
+ apply: 'serve' as const,
1297
+ configureServer(server) {
1298
+ let suppressUntil = 0;
1299
+ const WINDOW_MS = 2000;
1300
+ const cmsContentPrefix = `${cmsRoute}/api/content`;
1301
+
1302
+ server.middlewares.use((req, _res, next) => {
1303
+ const isWrite =
1304
+ req.method === 'POST' ||
1305
+ req.method === 'PUT' ||
1306
+ req.method === 'PATCH' ||
1307
+ req.method === 'DELETE';
1308
+ if (isWrite && req.url?.startsWith(cmsContentPrefix)) {
1309
+ suppressUntil = Date.now() + WINDOW_MS;
1310
+ }
1311
+ next();
1312
+ });
1313
+
1314
+ // During a CMS save window, drop two server→client signals that
1315
+ // would otherwise stomp on the CMS's own optimistic cache updates:
1316
+ //
1317
+ // 1. Vite `full-reload` — emitted by Astro 6.2.1's invalidateDataStore()
1318
+ // in dist/content/vite-plugin-content-virtual-mod.js. The call site
1319
+ // is in a configureServer watcher callback, outside the
1320
+ // handleHotUpdate pipeline, so wrapping hot.send is the only intercept.
1321
+ //
1322
+ // 2. `conloca:content-update` custom event — emitted by
1323
+ // conloca-content-watcher above. The client listener (template at
1324
+ // `contentChangeListener` in this file) reacts by calling
1325
+ // queryClient.invalidateQueries() with NO args, refetching every
1326
+ // query and visibly blinking lists. CMS mutation hooks already do
1327
+ // optimistic setQueryData, so this event is redundant for
1328
+ // CMS-originated writes. External edits (outside the save window)
1329
+ // still pass through normally.
1330
+ const patchedChannels = new WeakSet();
1331
+ const patchSend = (target: NormalizedHotChannel | undefined) => {
1332
+ if (!target || patchedChannels.has(target)) return;
1333
+ const origSend = target.send.bind(target);
1334
+
1335
+ function send(payload: HotPayload): void;
1336
+ function send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1337
+ function send(
1338
+ payloadOrEvent: HotPayload | string,
1339
+ payload?: InferCustomEventPayload<string>,
1340
+ ): void {
1341
+ if (typeof payloadOrEvent === 'string') {
1342
+ origSend(payloadOrEvent, payload);
1343
+ return;
1344
+ }
1345
+ if (dropsEditorSaveUpdate(payloadOrEvent) && Date.now() < suppressUntil) {
1346
+ server.config.logger.info(
1347
+ `[conloca] suppressed ${payloadOrEvent.type} during CMS save window`,
1348
+ { timestamp: true },
1349
+ );
1350
+ return;
1351
+ }
1352
+ origSend(payloadOrEvent);
1353
+ }
1354
+
1355
+ target.send = send;
1356
+ patchedChannels.add(target);
1357
+ };
1358
+
1359
+ // Astro's content plugin sends `full-reload` via environments.client.hot.
1360
+ // Conloca's content watcher sends custom events via server.ws (legacy API).
1361
+ // Patch both; idempotent per-target via __conlocaPatched.
1362
+ patchSend(server.environments?.client?.hot);
1363
+ patchSend(server.ws);
1364
+ },
1365
+ },
1366
+ ],
1367
+ },
1368
+ });
1369
+
1370
+ // Inject unified CMS handler for all CMS routes
1371
+ // Single handler validates auth once, then routes to appropriate sub-handler
1372
+ injectRoute({
1373
+ pattern: `${cmsRoute}/[...path]`,
1374
+ entrypoint: CMS_HANDLER_PATH,
1375
+ prerender: false,
1376
+ });
1377
+
1378
+ // Also handle the root CMS route
1379
+ injectRoute({
1380
+ pattern: cmsRoute,
1381
+ entrypoint: CMS_HANDLER_PATH,
1382
+ prerender: false,
1383
+ });
1384
+ },
1385
+
1386
+ 'astro:config:done': ({ config }) => {
1387
+ outputMode = config.output;
1388
+ },
1389
+
1390
+ 'astro:server:setup': ({ logger, refreshContent }) => {
1391
+ logger.info(`Conloca CMS available at ${cmsRoute}`);
1392
+
1393
+ let refreshChain = Promise.resolve();
1394
+
1395
+ refreshConlocaContent = async () => {
1396
+ if (!refreshContent) {
1397
+ return;
1398
+ }
1399
+
1400
+ refreshChain = refreshChain
1401
+ .catch(() => undefined)
1402
+ .then(async () => {
1403
+ await refreshContent({ loaders: ['conloca-loader'] });
1404
+ });
1405
+
1406
+ await refreshChain;
1407
+ };
1408
+
1409
+ // Register dev-time content refresh after the Vite server exists.
1410
+ // This keeps Astro collections in sync with Conloca's own file watcher.
1411
+ logger.debug('Registering Conloca content refresh handler');
1412
+ },
1413
+
1414
+ 'astro:routes:resolved': ({ routes, logger }) => {
1415
+ // Check for route conflicts when routing is enabled
1416
+ if (!resolvedRoutingConfig?.enabled) return;
1417
+
1418
+ const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));
1419
+
1420
+ // Another integration's route with the SAME NAME as a Conloca route is
1421
+ // fatal, whatever `onConflict` says: routing copes (Astro falls through
1422
+ // a prerendered match to the on-demand twin), but Astro's runtime app
1423
+ // resolves a page's stylesheets by route name and takes the first
1424
+ // match, so the twins swap or lose their styles — silently, and only
1425
+ // in the built site. That app renders every page of a server-output
1426
+ // build (prerendering included) and the on-demand pages of a static
1427
+ // one; fully static generation resolves by route and component, where
1428
+ // twins are harmless, so such a site is left alone. Starlight's docs
1429
+ // route is the usual twin: it is named /[...slug] too. The fix is a
1430
+ // different parameter name.
1431
+ const isConlocaHandler = (route: { entrypoint?: string }) =>
1432
+ route.entrypoint?.endsWith('/internal/page-handler.astro') ?? false;
1433
+ const ownRoutes = routes.filter(isConlocaHandler);
1434
+ for (const route of routes) {
1435
+ if (route.origin !== 'external' || !injectedPatterns.has(route.pattern) || isConlocaHandler(route)) continue;
1436
+ const own = ownRoutes.find((candidate) => candidate.pattern === route.pattern);
1437
+ const stylesResolvedByName = outputMode === 'server' || !route.isPrerendered || own?.isPrerendered === false;
1438
+ if (!stylesResolvedByName) continue;
1439
+ throw new Error(
1440
+ `[Conloca] Route '${route.pattern}' is registered by Conloca routing and by ${route.entrypoint}. ` +
1441
+ 'Astro resolves stylesheets by route name, so two routes with the same name lose their styles. ' +
1442
+ "Give the Conloca route a parameter name of its own, e.g. '/[...page]'.",
1443
+ );
1444
+ }
1445
+
1446
+ // Find file-based project routes that conflict with injected routes.
1447
+ const conflicts: { injected: string; fileBased: string }[] = [];
1448
+
1449
+ for (const route of routes) {
1450
+ if (route.origin !== 'project') continue;
1451
+
1452
+ const pattern = route.pattern;
1453
+ if (injectedPatterns.has(pattern)) {
1454
+ conflicts.push({
1455
+ injected: pattern,
1456
+ fileBased: route.entrypoint || pattern,
1457
+ });
1458
+ }
1459
+ }
1460
+
1461
+ if (conflicts.length === 0) return;
1462
+
1463
+ // Handle conflicts based on onConflict setting
1464
+ const onConflict = resolvedRoutingConfig.onConflict;
1465
+
1466
+ for (const conflict of conflicts) {
1467
+ const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;
1468
+
1469
+ if (onConflict === 'error') {
1470
+ throw new Error(`[Conloca] ${message}`);
1471
+ }
1472
+ if (onConflict === 'warn') {
1473
+ logger.warn(message);
1474
+ }
1475
+ // 'silent' - do nothing
1476
+ }
1477
+ },
1478
+ },
1479
+ };
1480
+ }