@conloca/astro-cms 0.1.14 → 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.
- package/README.md +65 -5
- package/dist/collections-Bd7EME4b.mjs +129 -0
- package/dist/collections-Bd7EME4b.mjs.map +1 -0
- package/dist/collections.d.mts +3 -3
- package/dist/collections.d.mts.map +1 -1
- package/dist/collections.mjs +2 -56
- package/dist/components.d.mts +6 -31
- package/dist/components.d.mts.map +1 -1
- package/dist/components.mjs +100 -45
- package/dist/components.mjs.map +1 -1
- package/dist/hydration.d.mts +2 -2
- package/dist/hydration.mjs +2 -3
- package/dist/index.d.mts +12 -88
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +19 -797
- package/dist/index.mjs.map +1 -1
- package/dist/internal/acorn-default.mjs +29 -0
- package/dist/{cms-handler.d.mts → internal/cms-handler.d.mts} +0 -1
- package/dist/internal/cms-handler.d.mts.map +1 -0
- package/dist/{cms-handler.mjs → internal/cms-handler.mjs} +57 -8
- package/dist/internal/cms-handler.mjs.map +1 -0
- package/dist/internal/page-handler.astro +541 -0
- package/dist/lib/hydration-script.d.mts +1 -2
- package/dist/lib/hydration-script.d.mts.map +1 -1
- package/dist/lib/hydration-script.mjs +1 -2
- package/dist/lib/hydration-script.mjs.map +1 -1
- package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
- package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
- package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
- package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
- package/dist/node/content.d.mts +18 -0
- package/dist/node/content.d.mts.map +1 -0
- package/dist/node/content.d.ts +3 -0
- package/dist/node/content.d.ts.map +1 -0
- package/dist/node/content.js +2 -0
- package/dist/node/content.mjs +2 -0
- package/dist/node/index.d.mts +200 -0
- package/dist/node/index.d.mts.map +1 -0
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +3 -0
- package/dist/node/index.mjs +2513 -0
- package/dist/node/index.mjs.map +1 -0
- package/dist/{serialize-props-DqfDQeFl.mjs → serialize-props-BHoNpzH6.mjs} +4 -5
- package/dist/{serialize-props-DqfDQeFl.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
- package/dist/src/cms-handler.d.ts +19 -0
- package/dist/src/cms-handler.d.ts.map +1 -0
- package/dist/src/cms-handler.js +366 -0
- package/dist/src/collections.d.ts +32 -0
- package/dist/src/collections.d.ts.map +1 -0
- package/dist/src/collections.js +50 -0
- package/dist/src/components/HydrationWrapper.d.ts +18 -0
- package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
- package/dist/src/components/HydrationWrapper.js +21 -0
- package/dist/src/components/RenderWithBlocks.d.ts +23 -0
- package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
- package/dist/src/components/RenderWithBlocks.js +129 -0
- package/dist/src/components/RenderWithHydration.d.ts +17 -0
- package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
- package/dist/src/components/RenderWithHydration.js +36 -0
- package/dist/src/components.d.ts +4 -0
- package/dist/src/components.d.ts.map +1 -0
- package/dist/src/components.js +3 -0
- package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
- package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
- package/dist/src/discovery/astro-frontmatter.js +24 -0
- package/dist/src/discovery/extract-props-ts.d.ts +41 -0
- package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
- package/dist/src/discovery/extract-props-ts.js +231 -0
- package/dist/src/discovery/merge-registry.d.ts +58 -0
- package/dist/src/discovery/merge-registry.d.ts.map +1 -0
- package/dist/src/discovery/merge-registry.js +332 -0
- package/dist/src/discovery/registry-endpoint.d.ts +42 -0
- package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
- package/dist/src/discovery/registry-endpoint.js +81 -0
- package/dist/src/discovery/scan-components.d.ts +98 -0
- package/dist/src/discovery/scan-components.d.ts.map +1 -0
- package/dist/src/discovery/scan-components.js +399 -0
- package/dist/src/discovery/scan-mdx.d.ts +63 -0
- package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
- package/dist/src/discovery/scan-mdx.js +112 -0
- package/dist/src/discovery/scan-overrides.d.ts +71 -0
- package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
- package/dist/src/discovery/scan-overrides.js +33 -0
- package/dist/src/hydration.d.ts +4 -0
- package/dist/src/hydration.d.ts.map +1 -0
- package/dist/src/hydration.js +4 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +25 -0
- package/dist/src/lib/hydration-scanner.d.ts +47 -0
- package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
- package/dist/src/lib/hydration-scanner.js +135 -0
- package/dist/src/lib/hydration-script.d.ts +28 -0
- package/dist/src/lib/hydration-script.d.ts.map +1 -0
- package/dist/src/lib/hydration-script.js +88 -0
- package/dist/src/lib/hydration-utils.d.ts +51 -0
- package/dist/src/lib/hydration-utils.d.ts.map +1 -0
- package/dist/src/lib/hydration-utils.js +83 -0
- package/dist/src/lib/page-api.d.ts +77 -0
- package/dist/src/lib/page-api.d.ts.map +1 -0
- package/dist/src/lib/page-api.js +121 -0
- package/dist/src/lib/route-utils.d.ts +41 -0
- package/dist/src/lib/route-utils.d.ts.map +1 -0
- package/dist/src/lib/route-utils.js +78 -0
- package/dist/src/lib/routing-config.d.ts +32 -0
- package/dist/src/lib/routing-config.d.ts.map +1 -0
- package/dist/src/lib/routing-config.js +93 -0
- package/dist/src/lib/serialize-props.d.ts +6 -0
- package/dist/src/lib/serialize-props.d.ts.map +1 -0
- package/dist/src/lib/serialize-props.js +7 -0
- package/dist/src/lib/virtual-module-generators.d.ts +57 -0
- package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
- package/dist/src/lib/virtual-module-generators.js +263 -0
- package/dist/src/lib/withHydration.d.ts +51 -0
- package/dist/src/lib/withHydration.d.ts.map +1 -0
- package/dist/src/lib/withHydration.js +49 -0
- package/dist/src/loader.d.ts +14 -0
- package/dist/src/loader.d.ts.map +1 -0
- package/dist/src/loader.js +89 -0
- package/dist/src/locales-helpers.d.ts +61 -0
- package/dist/src/locales-helpers.d.ts.map +1 -0
- package/dist/src/locales-helpers.js +49 -0
- package/dist/src/mime-types.d.ts +3 -0
- package/dist/src/mime-types.d.ts.map +1 -0
- package/dist/src/mime-types.js +19 -0
- package/dist/src/path-validation.d.ts +8 -0
- package/dist/src/path-validation.d.ts.map +1 -0
- package/dist/src/path-validation.js +12 -0
- package/dist/src/plugin-spa.d.ts +164 -0
- package/dist/src/plugin-spa.d.ts.map +1 -0
- package/dist/src/plugin-spa.js +972 -0
- package/dist/src/safe-json-stringify.d.ts +13 -0
- package/dist/src/safe-json-stringify.d.ts.map +1 -0
- package/dist/src/safe-json-stringify.js +6 -0
- package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
- package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
- package/dist/src/site-styles/render-endpoint.d.ts +55 -0
- package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/render-endpoint.js +263 -0
- package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
- package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/styles-endpoint.js +158 -0
- package/dist/src/types.d.ts +627 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +1 -0
- package/dist/{types-Bsd_qENn.d.mts → types-CS9neadI.d.mts} +193 -3
- package/dist/types-CS9neadI.d.mts.map +1 -0
- package/dist/virtual-modules.d.ts +155 -0
- package/dist/{withHydration-692fMySA.mjs → withHydration-C256ox_6.mjs} +6 -2
- package/dist/withHydration-C256ox_6.mjs.map +1 -0
- package/dist/{withHydration-BGgQDE-H.d.mts → withHydration-DkKpkmzJ.d.mts} +5 -2
- package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
- package/package.json +106 -40
- package/dist/cms-handler.d.mts.map +0 -1
- package/dist/cms-handler.mjs.map +0 -1
- package/dist/collections.mjs.map +0 -1
- package/dist/handlers/page-handler.astro +0 -299
- package/dist/loader-W3i9kf3p.mjs +0 -61
- package/dist/loader-W3i9kf3p.mjs.map +0 -1
- package/dist/types-Bsd_qENn.d.mts.map +0 -1
- package/dist/withHydration-692fMySA.mjs.map +0 -1
- package/dist/withHydration-BGgQDE-H.d.mts.map +0 -1
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { readSitesConfig } from '@conloca/content-api/node';
|
|
5
|
+
import viteReact from '@vitejs/plugin-react';
|
|
6
|
+
import { searchForWorkspaceRoot } from 'vite';
|
|
7
|
+
import { createRegistryEndpoint } from './discovery/registry-endpoint.js';
|
|
8
|
+
import { deriveComponentPaths, scanForHydratableComponents } from './lib/hydration-scanner.js';
|
|
9
|
+
import { normalizeRoutingConfig, resolveRouteConfig } from './lib/routing-config.js';
|
|
10
|
+
import { createContentWrapperEndpoint } from './site-styles/content-wrapper-endpoint.js';
|
|
11
|
+
import { createRenderEndpoint } from './site-styles/render-endpoint.js';
|
|
12
|
+
import { createStylesEndpoint } from './site-styles/styles-endpoint.js';
|
|
13
|
+
// FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.
|
|
14
|
+
// It provides the React Fast Refresh preamble script needed for HMR in virtual modules.
|
|
15
|
+
// If @vitejs/plugin-react removes or renames this property, the assertion below will
|
|
16
|
+
// fail immediately at dev startup. Test after any @vitejs/plugin-react update.
|
|
17
|
+
if (typeof viteReact.preambleCode !== 'string') {
|
|
18
|
+
throw new Error('@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +
|
|
19
|
+
'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +
|
|
20
|
+
'Check @vitejs/plugin-react release notes and update the preamble injection logic.');
|
|
21
|
+
}
|
|
22
|
+
const reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');
|
|
23
|
+
// Get the directory of this module to resolve page-handler.astro
|
|
24
|
+
// Works from both src/ (dev) and dist/ (published) since build copies the file
|
|
25
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
26
|
+
const PAGE_HANDLER_PATH = join(__dirname, '..', 'internal', 'page-handler.astro');
|
|
27
|
+
const CMS_HANDLER_PATH = join(__dirname, '..', 'internal', 'cms-handler.mjs');
|
|
28
|
+
const ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', 'internal', 'acorn-default.mjs');
|
|
29
|
+
import { generateLayoutModule, generatePageApiModule, generatePuckConfigModule, generateRoutingConfigModule, } from './lib/virtual-module-generators.js';
|
|
30
|
+
// Virtual module for passing config from plugin to route handler
|
|
31
|
+
const VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';
|
|
32
|
+
const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
|
|
33
|
+
// Virtual module IDs for routing system
|
|
34
|
+
const VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';
|
|
35
|
+
const VIRTUAL_LAYOUT = 'virtual:conloca-layout';
|
|
36
|
+
const VIRTUAL_PAGE_API = 'virtual:conloca-page-api';
|
|
37
|
+
const VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';
|
|
38
|
+
// Resolved IDs (with \0 prefix to prevent file resolution)
|
|
39
|
+
const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
|
|
40
|
+
const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
|
|
41
|
+
const RESOLVED_PAGE_API = `\0${VIRTUAL_PAGE_API}`;
|
|
42
|
+
const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
|
|
43
|
+
// Virtual modules for hydration system
|
|
44
|
+
const VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';
|
|
45
|
+
const VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';
|
|
46
|
+
const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
|
|
47
|
+
const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
|
|
48
|
+
// Virtual module for CMS SPA source loading (dev only)
|
|
49
|
+
const VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';
|
|
50
|
+
const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
|
|
51
|
+
async function loadContentApiNode() {
|
|
52
|
+
return import('@conloca/content-api/node');
|
|
53
|
+
}
|
|
54
|
+
// Template for content change listener virtual module
|
|
55
|
+
const contentChangeListener = () => {
|
|
56
|
+
return `
|
|
57
|
+
// Content change listener that uses Vite HMR
|
|
58
|
+
if (import.meta.hot) {
|
|
59
|
+
import.meta.hot.on('conloca:content-update', (data) => {
|
|
60
|
+
console.log('[Conloca CMS] Content updated, invalidating cache:', data);
|
|
61
|
+
|
|
62
|
+
// Get the query client from the global scope and invalidate
|
|
63
|
+
if (window.__QUERY_CLIENT__) {
|
|
64
|
+
window.__QUERY_CLIENT__.invalidateQueries();
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export default {};
|
|
70
|
+
`;
|
|
71
|
+
};
|
|
72
|
+
// Template for the puck config loader virtual module
|
|
73
|
+
const puckConfigLoader = (absolutePuckPath, cmsSpaDistDir) => {
|
|
74
|
+
// We need to ensure the preamble executes before ANY module evaluation
|
|
75
|
+
// So we'll use a dynamic import after the preamble is set up
|
|
76
|
+
const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/puck-config.mjs` : '@conloca/cms-spa/puck-config';
|
|
77
|
+
return `
|
|
78
|
+
// Import and execute React refresh preamble first (from @vitejs/plugin-react)
|
|
79
|
+
${reactRefreshPreamble}
|
|
80
|
+
|
|
81
|
+
// Import the setPuckConfig function from cms-spa
|
|
82
|
+
import { setPuckConfig } from '${puckConfigImport}';
|
|
83
|
+
|
|
84
|
+
// Now dynamically import the config after preamble is ready
|
|
85
|
+
const puckConfigPromise = import('${absolutePuckPath}');
|
|
86
|
+
|
|
87
|
+
// Handle the initial load
|
|
88
|
+
puckConfigPromise.then(module => {
|
|
89
|
+
const puckConfig = module.default;
|
|
90
|
+
setPuckConfig(puckConfig);
|
|
91
|
+
|
|
92
|
+
// Hook into React Fast Refresh to detect component updates
|
|
93
|
+
if (window.__registerBeforePerformReactRefresh) {
|
|
94
|
+
window.__registerBeforePerformReactRefresh(async () => {
|
|
95
|
+
// Re-import the config module to get updated components
|
|
96
|
+
const newModule = await import('${absolutePuckPath}');
|
|
97
|
+
setPuckConfig(newModule.default);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// Accept HMR for this module itself
|
|
103
|
+
if (import.meta.hot) {
|
|
104
|
+
import.meta.hot.accept();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Export the promise so the module has a default export
|
|
108
|
+
export default puckConfigPromise.then(m => m.default);
|
|
109
|
+
`;
|
|
110
|
+
};
|
|
111
|
+
// Template for the schemas loader virtual module
|
|
112
|
+
const schemasLoader = (absoluteSchemasPath, cmsSpaDistDir) => {
|
|
113
|
+
const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/page-schemas.mjs` : '@conloca/cms-spa/page-schemas';
|
|
114
|
+
const mdxComponentsImport = cmsSpaDistDir ? `${cmsSpaDistDir}/mdx-components.mjs` : '@conloca/cms-spa/mdx-components';
|
|
115
|
+
// The host's schemas file may transitively import React components (the
|
|
116
|
+
// `Editor` field on an MdxComponentDescriptor can be a JSX/TSX
|
|
117
|
+
// component). Vite's React plugin requires the Fast Refresh preamble to
|
|
118
|
+
// run before any TSX module is evaluated, so we emit it here and then
|
|
119
|
+
// dynamically import the schemas file — matching the pattern used by
|
|
120
|
+
// the Puck config loader above.
|
|
121
|
+
return `
|
|
122
|
+
${reactRefreshPreamble}
|
|
123
|
+
|
|
124
|
+
import { setPageSchemas } from '${pageSchemasImport}';
|
|
125
|
+
import { setMdxComponents } from '${mdxComponentsImport}';
|
|
126
|
+
|
|
127
|
+
const schemasPromise = import('${absoluteSchemasPath}');
|
|
128
|
+
|
|
129
|
+
schemasPromise.then((schemas) => {
|
|
130
|
+
if (schemas.pageSchemas) {
|
|
131
|
+
setPageSchemas(schemas.pageSchemas);
|
|
132
|
+
}
|
|
133
|
+
if (schemas.mdxComponents) {
|
|
134
|
+
setMdxComponents(schemas.mdxComponents);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
if (import.meta.hot) {
|
|
139
|
+
import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
|
|
140
|
+
if (newModule?.pageSchemas) {
|
|
141
|
+
setPageSchemas(newModule.pageSchemas);
|
|
142
|
+
}
|
|
143
|
+
if (newModule?.mdxComponents) {
|
|
144
|
+
setMdxComponents(newModule.mdxComponents);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export default schemasPromise;
|
|
150
|
+
`;
|
|
151
|
+
};
|
|
152
|
+
// Template for the site styles loader virtual module.
|
|
153
|
+
//
|
|
154
|
+
// Each CSS file is imported with Vite's `?inline` query so the full CSS
|
|
155
|
+
// pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet
|
|
156
|
+
// as a string — no `<style>` tag is injected into the CMS admin's parent
|
|
157
|
+
// `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles
|
|
158
|
+
// registry; the editor's iframe bridge then injects them directly into
|
|
159
|
+
// Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS
|
|
160
|
+
// chrome and confines it to the intended consumer (the preview).
|
|
161
|
+
const siteStylesLoader = (cssPaths, cmsSpaDistDir) => {
|
|
162
|
+
const imports = cssPaths
|
|
163
|
+
.map((p, i) => {
|
|
164
|
+
const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
|
|
165
|
+
return `import css${i} from '${absolutePath}?inline';`;
|
|
166
|
+
})
|
|
167
|
+
.join('\n');
|
|
168
|
+
const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
|
|
169
|
+
const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : '@conloca/cms-spa/site-styles';
|
|
170
|
+
return `
|
|
171
|
+
${imports}
|
|
172
|
+
import { setSiteStyles } from '${siteStylesImport}';
|
|
173
|
+
|
|
174
|
+
setSiteStyles([${vars}]);
|
|
175
|
+
|
|
176
|
+
if (import.meta.hot) {
|
|
177
|
+
import.meta.hot.accept();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export default {};
|
|
181
|
+
`;
|
|
182
|
+
};
|
|
183
|
+
// Template for the editor styles loader virtual module — same shape as
|
|
184
|
+
// siteStylesLoader but feeds a different registry (`setEditorStyles`),
|
|
185
|
+
// consumed by the MDX editor's `useInjectHostStyles` call. Kept separate
|
|
186
|
+
// from `siteStyles` because the two surfaces have opposite cascade needs;
|
|
187
|
+
// see `packages/cms-spa/src/site-styles.ts` for the rationale.
|
|
188
|
+
const editorStylesLoader = (cssPaths, cmsSpaDistDir) => {
|
|
189
|
+
const imports = cssPaths
|
|
190
|
+
.map((p, i) => {
|
|
191
|
+
const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
|
|
192
|
+
return `import css${i} from '${absolutePath}?inline';`;
|
|
193
|
+
})
|
|
194
|
+
.join('\n');
|
|
195
|
+
const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
|
|
196
|
+
const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : '@conloca/cms-spa/site-styles';
|
|
197
|
+
return `
|
|
198
|
+
${imports}
|
|
199
|
+
import { setEditorStyles } from '${siteStylesImport}';
|
|
200
|
+
|
|
201
|
+
setEditorStyles([${vars}]);
|
|
202
|
+
|
|
203
|
+
if (import.meta.hot) {
|
|
204
|
+
import.meta.hot.accept();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export default {};
|
|
208
|
+
`;
|
|
209
|
+
};
|
|
210
|
+
export function conlocaCMS(options) {
|
|
211
|
+
const cmsRoute = options.route || '/__cms';
|
|
212
|
+
// Resolve @conloca/cms-spa package directory for absolute imports in virtual
|
|
213
|
+
// module templates. Bare specifiers like '@conloca/cms-spa/puck-config'
|
|
214
|
+
// resolve from the Vite project root, which works when deps are hoisted
|
|
215
|
+
// (npm consumers) but fails with isolated linkers (e.g. bun). Using the
|
|
216
|
+
// resolved absolute path bypasses the project-root lookup entirely.
|
|
217
|
+
let cmsSpaDir;
|
|
218
|
+
try {
|
|
219
|
+
const pkgUrl = import.meta.resolve('@conloca/cms-spa/package.json');
|
|
220
|
+
cmsSpaDir = dirname(pkgUrl.startsWith('file://') ? fileURLToPath(pkgUrl) : pkgUrl);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
// Package not resolvable — virtual modules will fall back to bare specifiers
|
|
224
|
+
}
|
|
225
|
+
const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, 'dist') : undefined;
|
|
226
|
+
// Normalize routing config and resolve defaults
|
|
227
|
+
// Pass top-level layout to enable routing when layout provided without explicit routing config
|
|
228
|
+
const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
|
|
229
|
+
// Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths
|
|
230
|
+
// Scanner handles missing directories gracefully (fast-glob returns empty array)
|
|
231
|
+
const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);
|
|
232
|
+
// Scan for hydratable components - this promise is awaited in the virtual module loader
|
|
233
|
+
const hydrationDiscoveriesPromise = scanForHydratableComponents(componentPaths, process.cwd()).then((discoveries) => {
|
|
234
|
+
if (discoveries.length > 0) {
|
|
235
|
+
console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
|
|
236
|
+
}
|
|
237
|
+
return discoveries;
|
|
238
|
+
});
|
|
239
|
+
// Build resolved routing config with all defaults applied
|
|
240
|
+
let resolvedRoutingConfig;
|
|
241
|
+
if (routingConfig?.enabled !== false && routingConfig) {
|
|
242
|
+
const resolvedRoutes = {};
|
|
243
|
+
for (const [name, config] of Object.entries(routingConfig.routes || {})) {
|
|
244
|
+
resolvedRoutes[name] = resolveRouteConfig(config);
|
|
245
|
+
}
|
|
246
|
+
resolvedRoutingConfig = {
|
|
247
|
+
enabled: routingConfig.enabled ?? true,
|
|
248
|
+
routes: resolvedRoutes,
|
|
249
|
+
fallback: routingConfig.fallback ?? '404',
|
|
250
|
+
onConflict: routingConfig.onConflict ?? 'warn',
|
|
251
|
+
siteName: routingConfig.siteName ?? 'default',
|
|
252
|
+
locale: routingConfig.locale ?? 'en',
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
// SPA config passed to route handler via virtual module
|
|
256
|
+
// This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true
|
|
257
|
+
// `mdxPagesEnabled` and `resolvedMdxPages` start uninitialized; the
|
|
258
|
+
// `astro:config:setup` hook reads sites.json (the canonical home for
|
|
259
|
+
// per-site `mdxPages` paths) and mutates them before any virtual
|
|
260
|
+
// module load fires — `load(id)` runs at request time, after the
|
|
261
|
+
// hook completes.
|
|
262
|
+
const spaConfig = {
|
|
263
|
+
basename: cmsRoute,
|
|
264
|
+
apiBaseUrl: `${cmsRoute}/api`,
|
|
265
|
+
siteBaseUrl: options.siteBaseUrl,
|
|
266
|
+
enableDevtools: options.enableDevtools ?? true,
|
|
267
|
+
queryClientOptions: options.queryClientOptions,
|
|
268
|
+
schemasPath: options.schemasPath,
|
|
269
|
+
projectRoot: process.cwd(),
|
|
270
|
+
templates: options.templates,
|
|
271
|
+
// True when at least one site in sites.json declares an `mdxPages`
|
|
272
|
+
// path. Drives the "Document page" option in the create-page dialog.
|
|
273
|
+
// Initialized in the `astro:config:setup` hook below.
|
|
274
|
+
mdxPagesEnabled: false,
|
|
275
|
+
// Forward the locale list so the SPA stops hardcoding en/nl/fr in
|
|
276
|
+
// the create-page dialog. The integration receives this from the
|
|
277
|
+
// top-level `locales` option, which can in turn be produced by
|
|
278
|
+
// `localesFromAstroI18n` / `localesFromStarlight`.
|
|
279
|
+
locales: options.locales ? { list: options.locales.list, defaultLocale: options.locales.defaultLocale } : undefined,
|
|
280
|
+
};
|
|
281
|
+
// Resolved mdxPages path, populated from sites.json in the
|
|
282
|
+
// config:setup hook. Used by the registry endpoint and content
|
|
283
|
+
// watcher. `null` means no site declares an `mdxPages` path — .mdx
|
|
284
|
+
// files (if any) fall back to living alongside Puck pages.
|
|
285
|
+
let resolvedMdxPages = null;
|
|
286
|
+
let refreshConlocaContent;
|
|
287
|
+
return {
|
|
288
|
+
name: '@conloca/astro-cms',
|
|
289
|
+
hooks: {
|
|
290
|
+
'astro:config:setup': async ({ updateConfig, injectRoute, command, logger }) => {
|
|
291
|
+
// Read sites.json — the canonical home for per-site config
|
|
292
|
+
// including the optional `mdxPages` field. Reading it here (once,
|
|
293
|
+
// at integration setup) gives us a single source of truth for
|
|
294
|
+
// the rest of the hook. `readSitesConfig` returns a safe default
|
|
295
|
+
// when the file is missing or malformed.
|
|
296
|
+
const sitesConfig = await readSitesConfig(options.contentRoot);
|
|
297
|
+
// Pick the first site that declares an `mdxPages` path. Today's
|
|
298
|
+
// integration supports a single `mdxPages` per project;
|
|
299
|
+
// multi-site `mdxPages` is a future expansion (would require
|
|
300
|
+
// fanning the watcher and registry scanner across all roots).
|
|
301
|
+
const firstSiteWithMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages);
|
|
302
|
+
resolvedMdxPages = firstSiteWithMdxPages?.mdxPages ?? null;
|
|
303
|
+
spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);
|
|
304
|
+
// Auto-inject fs.allow for external contentRoot (dev mode only)
|
|
305
|
+
const astroRoot = process.cwd();
|
|
306
|
+
const contentAbsolute = resolve(options.contentRoot);
|
|
307
|
+
if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {
|
|
308
|
+
logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
|
|
309
|
+
updateConfig({
|
|
310
|
+
vite: {
|
|
311
|
+
server: {
|
|
312
|
+
fs: {
|
|
313
|
+
allow: [
|
|
314
|
+
searchForWorkspaceRoot(process.cwd()), // Preserve Vite default
|
|
315
|
+
contentAbsolute,
|
|
316
|
+
],
|
|
317
|
+
},
|
|
318
|
+
},
|
|
319
|
+
},
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
// @puckeditor/core (and its zustand dependency) must always go through Vite's
|
|
323
|
+
// SSR resolver, in dev AND build. SSR-external modules are require()'d directly
|
|
324
|
+
// by Node, bypassing Vite's resolver — and `resolve.dedupe` below — entirely,
|
|
325
|
+
// which risks pulling in a stray React copy from outside the workspace.
|
|
326
|
+
const alwaysSsrNoExternal = ['@puckeditor/core'];
|
|
327
|
+
// In dev, linked workspace packages also need to be bundled so React resolves
|
|
328
|
+
// through Vite and HMR works from source (build mode uses their compiled dist output).
|
|
329
|
+
const devOnlySsrNoExternal = [/^@conloca\//];
|
|
330
|
+
const serverOnlyExternal = [
|
|
331
|
+
'@conloca/content-api',
|
|
332
|
+
'@conloca/content-api/node',
|
|
333
|
+
'@conloca/content-api/reader',
|
|
334
|
+
'@conloca/content-api/schemas',
|
|
335
|
+
'@conloca/mdx',
|
|
336
|
+
'@conloca/mdx/node',
|
|
337
|
+
];
|
|
338
|
+
updateConfig({
|
|
339
|
+
vite: {
|
|
340
|
+
ssr: {
|
|
341
|
+
noExternal: command === 'dev' ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,
|
|
342
|
+
// Keep Node-only content packages (content-api, mdx) external so SSR
|
|
343
|
+
// builds do not try to bundle their server-only surfaces.
|
|
344
|
+
external: serverOnlyExternal,
|
|
345
|
+
},
|
|
346
|
+
resolve: {
|
|
347
|
+
// Dedupe React to avoid multiple instances when CMS SPA source is
|
|
348
|
+
// loaded from a workspace sibling package. Only list packages the
|
|
349
|
+
// consumer project declares directly — with bun's isolated linker,
|
|
350
|
+
// transitive deps (e.g. @tanstack/react-query) live in the owning
|
|
351
|
+
// package's node_modules and must NOT be forced to resolve from the
|
|
352
|
+
// consumer root (which would fail).
|
|
353
|
+
dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
|
|
354
|
+
},
|
|
355
|
+
// Virtual modules for routing - needed in both dev and build
|
|
356
|
+
plugins: [
|
|
357
|
+
// Public page rendering should use Puck's server entry, not the full editor.
|
|
358
|
+
// The full editor pulls client-only store code into Astro prerendering.
|
|
359
|
+
{
|
|
360
|
+
name: 'conloca-puck-ssr-render-alias',
|
|
361
|
+
enforce: 'pre',
|
|
362
|
+
async resolveId(id, importer, options) {
|
|
363
|
+
if (id === '@puckeditor/core' && options?.ssr) {
|
|
364
|
+
return this.resolve('@puckeditor/core/rsc', importer, { ...options, skipSelf: true });
|
|
365
|
+
}
|
|
366
|
+
return null;
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
// Alias acorn to a CJS shim only during SSR (static page builds).
|
|
370
|
+
// Must NOT apply to the browser bundle — the shim uses createRequire
|
|
371
|
+
// which is Node.js-only and crashes in the browser.
|
|
372
|
+
{
|
|
373
|
+
name: 'conloca-acorn-ssr-alias',
|
|
374
|
+
enforce: 'pre',
|
|
375
|
+
resolveId(id, _importer, options) {
|
|
376
|
+
if (id === 'acorn' && options?.ssr) {
|
|
377
|
+
return ACORN_DEFAULT_SHIM_PATH;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
name: 'conloca-routing-virtual-modules',
|
|
384
|
+
resolveId(id) {
|
|
385
|
+
// Routing virtual modules (work in both dev and build)
|
|
386
|
+
if (id === VIRTUAL_ROUTING_CONFIG) {
|
|
387
|
+
return RESOLVED_ROUTING_CONFIG;
|
|
388
|
+
}
|
|
389
|
+
if (id === VIRTUAL_LAYOUT) {
|
|
390
|
+
return RESOLVED_LAYOUT;
|
|
391
|
+
}
|
|
392
|
+
if (id === VIRTUAL_PUCK_CONFIG) {
|
|
393
|
+
return RESOLVED_PUCK_CONFIG;
|
|
394
|
+
}
|
|
395
|
+
// Hydration virtual modules
|
|
396
|
+
if (id === VIRTUAL_HYDRATION_REGISTRY) {
|
|
397
|
+
return RESOLVED_HYDRATION_REGISTRY;
|
|
398
|
+
}
|
|
399
|
+
if (id === VIRTUAL_HYDRATION_ENTRY) {
|
|
400
|
+
return RESOLVED_HYDRATION_ENTRY;
|
|
401
|
+
}
|
|
402
|
+
return null;
|
|
403
|
+
},
|
|
404
|
+
async load(id) {
|
|
405
|
+
// Routing virtual modules
|
|
406
|
+
if (id === RESOLVED_ROUTING_CONFIG) {
|
|
407
|
+
if (resolvedRoutingConfig) {
|
|
408
|
+
return generateRoutingConfigModule(resolvedRoutingConfig);
|
|
409
|
+
}
|
|
410
|
+
// Return disabled config if routing not configured
|
|
411
|
+
return 'export default { enabled: false, routes: {}, fallback: "404", onConflict: "warn" };';
|
|
412
|
+
}
|
|
413
|
+
if (id === RESOLVED_LAYOUT) {
|
|
414
|
+
return generateLayoutModule(routingConfig);
|
|
415
|
+
}
|
|
416
|
+
if (id === RESOLVED_PUCK_CONFIG) {
|
|
417
|
+
return generatePuckConfigModule(options.puckConfigPath);
|
|
418
|
+
}
|
|
419
|
+
// Hydration virtual modules
|
|
420
|
+
if (id === RESOLVED_HYDRATION_REGISTRY) {
|
|
421
|
+
// Always scan - paths are auto-derived from puckConfigPath
|
|
422
|
+
const discoveries = await hydrationDiscoveriesPromise;
|
|
423
|
+
if (discoveries.length > 0) {
|
|
424
|
+
const entries = discoveries.map((d) => {
|
|
425
|
+
// Convert absolute path to Vite-friendly path
|
|
426
|
+
const relativePath = d.filePath.replace(process.cwd(), '');
|
|
427
|
+
return ` '${d.componentName}': {
|
|
428
|
+
loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
|
|
429
|
+
strategy: '${d.strategy}',
|
|
430
|
+
}`;
|
|
431
|
+
});
|
|
432
|
+
return `// Generated by @conloca/astro-cms scanner
|
|
433
|
+
export const componentRegistry = {
|
|
434
|
+
${entries.join(',\n')}
|
|
435
|
+
};`;
|
|
436
|
+
}
|
|
437
|
+
// No hydratable components found - return empty registry
|
|
438
|
+
return 'export const componentRegistry = {};';
|
|
439
|
+
}
|
|
440
|
+
if (id === RESOLVED_HYDRATION_ENTRY) {
|
|
441
|
+
// Generate entry point that imports registry and calls initHydration
|
|
442
|
+
return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
|
|
443
|
+
import { componentRegistry } from 'virtual:conloca-hydration-registry'
|
|
444
|
+
|
|
445
|
+
// Auto-initialize hydration when this module loads
|
|
446
|
+
initHydration(componentRegistry)
|
|
447
|
+
`;
|
|
448
|
+
}
|
|
449
|
+
return null;
|
|
450
|
+
},
|
|
451
|
+
},
|
|
452
|
+
],
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
// Content page routes - works in both dev and build
|
|
456
|
+
if (resolvedRoutingConfig?.enabled) {
|
|
457
|
+
for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
|
|
458
|
+
logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
|
|
459
|
+
injectRoute({
|
|
460
|
+
pattern: routeConfig.pattern,
|
|
461
|
+
entrypoint: PAGE_HANDLER_PATH,
|
|
462
|
+
prerender: routeConfig.prerender,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
// Only inject CMS admin routes and dev-specific config in dev mode
|
|
467
|
+
if (command !== 'dev')
|
|
468
|
+
return;
|
|
469
|
+
// Pass options via Vite define for API routes
|
|
470
|
+
updateConfig({
|
|
471
|
+
vite: {
|
|
472
|
+
define: {
|
|
473
|
+
'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),
|
|
474
|
+
'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),
|
|
475
|
+
'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),
|
|
476
|
+
'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),
|
|
477
|
+
// mdxPages / mdxPagesSite / mdxPagesDefaultLocale are no
|
|
478
|
+
// longer surfaced as env vars — the content-api reads them
|
|
479
|
+
// directly from sites.json under `contentRoot` at request
|
|
480
|
+
// time. See `readSitesConfig()` and `SitesConfig.sites[name].mdxPages`.
|
|
481
|
+
// Default route URL the block editor uses for style /
|
|
482
|
+
// wrapper discovery. See `blockPreviewRoute` option doc
|
|
483
|
+
// above. `/` is a sane fallback for most layouts.
|
|
484
|
+
'import.meta.env.CONLOCA_BLOCK_PREVIEW_ROUTE': JSON.stringify(options.blockPreviewRoute || '/'),
|
|
485
|
+
// Raw CSS the host wants injected into the editor's
|
|
486
|
+
// `conloca-host-preview` layer for visual overrides.
|
|
487
|
+
// See `editorCSS` option doc above for use cases.
|
|
488
|
+
'import.meta.env.CONLOCA_EDITOR_CSS': JSON.stringify(options.editorCSS || ''),
|
|
489
|
+
// Top-level locales. Vite `define` does literal text
|
|
490
|
+
// substitution, so this inlines as either a JS array or `null`.
|
|
491
|
+
// The runtime handler reads it as-is — no JSON.parse needed.
|
|
492
|
+
'import.meta.env.CONLOCA_LOCALES': JSON.stringify(options.locales?.list ?? null),
|
|
493
|
+
'import.meta.env.CONLOCA_DEFAULT_LOCALE': JSON.stringify(options.locales?.defaultLocale || ''),
|
|
494
|
+
},
|
|
495
|
+
optimizeDeps: {
|
|
496
|
+
// Exclude the puck config from optimization to avoid the outdated dep error
|
|
497
|
+
exclude: [options.puckConfigPath],
|
|
498
|
+
// Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization
|
|
499
|
+
// which causes React dual-instance issues when Vite discovers new deps dynamically
|
|
500
|
+
include: [
|
|
501
|
+
// React core - must be pre-bundled together
|
|
502
|
+
'react',
|
|
503
|
+
'react-dom',
|
|
504
|
+
'react-dom/client',
|
|
505
|
+
'react/jsx-runtime',
|
|
506
|
+
'react/jsx-dev-runtime',
|
|
507
|
+
// CMS dependencies
|
|
508
|
+
'@mdxeditor/editor',
|
|
509
|
+
'@puckeditor/core',
|
|
510
|
+
'@tanstack/react-query',
|
|
511
|
+
'@tanstack/react-query-devtools',
|
|
512
|
+
'react-router-dom',
|
|
513
|
+
'@radix-ui/react-dialog',
|
|
514
|
+
'@radix-ui/react-select',
|
|
515
|
+
'lucide-react',
|
|
516
|
+
'clsx',
|
|
517
|
+
'tailwind-merge',
|
|
518
|
+
// Content processing
|
|
519
|
+
'zod',
|
|
520
|
+
'yaml',
|
|
521
|
+
'nanoid',
|
|
522
|
+
'sort-keys',
|
|
523
|
+
// MDX processing
|
|
524
|
+
'@mdx-js/mdx',
|
|
525
|
+
'remark-frontmatter',
|
|
526
|
+
'remark-gfm',
|
|
527
|
+
'remark-mdx-frontmatter',
|
|
528
|
+
],
|
|
529
|
+
},
|
|
530
|
+
plugins: [
|
|
531
|
+
// Normalize @conloca/* imports from symlinked source files (bun link).
|
|
532
|
+
// When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports
|
|
533
|
+
// resolve relative to the real filesystem location, creating duplicate
|
|
534
|
+
// module instances. This plugin re-resolves them from the consumer
|
|
535
|
+
// project root so all @conloca packages use the same module identity.
|
|
536
|
+
{
|
|
537
|
+
name: 'conloca-resolve-normalizer',
|
|
538
|
+
enforce: 'pre',
|
|
539
|
+
async resolveId(source, importer) {
|
|
540
|
+
// Only normalize @conloca/* bare specifiers
|
|
541
|
+
if (!source.startsWith('@conloca/'))
|
|
542
|
+
return null;
|
|
543
|
+
// Only when imported from outside the project (symlinked source files)
|
|
544
|
+
if (!importer || importer.startsWith(astroRoot))
|
|
545
|
+
return null;
|
|
546
|
+
// Skip virtual modules (prefixed with \0)
|
|
547
|
+
if (importer.startsWith('\0'))
|
|
548
|
+
return null;
|
|
549
|
+
// Re-resolve from project root to ensure consumer's node_modules is used
|
|
550
|
+
const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });
|
|
551
|
+
return resolved;
|
|
552
|
+
},
|
|
553
|
+
},
|
|
554
|
+
{
|
|
555
|
+
name: 'conloca-dev-virtual-modules',
|
|
556
|
+
resolveId(id) {
|
|
557
|
+
// Dev-only config module for cms-handler.ts
|
|
558
|
+
if (id === VIRTUAL_CONFIG_MODULE) {
|
|
559
|
+
return RESOLVED_VIRTUAL_CONFIG;
|
|
560
|
+
}
|
|
561
|
+
if (id === `${cmsRoute}/puck-entry.js`) {
|
|
562
|
+
return id;
|
|
563
|
+
}
|
|
564
|
+
if (id === `${cmsRoute}/content-listener.js`) {
|
|
565
|
+
return id;
|
|
566
|
+
}
|
|
567
|
+
if (id === `${cmsRoute}/schemas-entry.js`) {
|
|
568
|
+
return id;
|
|
569
|
+
}
|
|
570
|
+
if (id === `${cmsRoute}/site-styles.js`) {
|
|
571
|
+
return id;
|
|
572
|
+
}
|
|
573
|
+
if (id === `${cmsRoute}/editor-styles.js`) {
|
|
574
|
+
return id;
|
|
575
|
+
}
|
|
576
|
+
if (id === VIRTUAL_PAGE_API) {
|
|
577
|
+
return RESOLVED_PAGE_API;
|
|
578
|
+
}
|
|
579
|
+
if (id === VIRTUAL_CMS_SPA_ENTRY) {
|
|
580
|
+
return RESOLVED_CMS_SPA_ENTRY;
|
|
581
|
+
}
|
|
582
|
+
if (id === `${cmsRoute}/cms-spa-entry.js`) {
|
|
583
|
+
return RESOLVED_CMS_SPA_ENTRY;
|
|
584
|
+
}
|
|
585
|
+
return null;
|
|
586
|
+
},
|
|
587
|
+
load(id) {
|
|
588
|
+
// Dev-only config module for cms-handler.ts
|
|
589
|
+
if (id === RESOLVED_VIRTUAL_CONFIG) {
|
|
590
|
+
return `export default ${JSON.stringify(spaConfig)};`;
|
|
591
|
+
}
|
|
592
|
+
if (id === `${cmsRoute}/puck-entry.js`) {
|
|
593
|
+
const absolutePuckPath = options.puckConfigPath.startsWith('.')
|
|
594
|
+
? `/${options.puckConfigPath.slice(2)}`
|
|
595
|
+
: options.puckConfigPath;
|
|
596
|
+
return puckConfigLoader(absolutePuckPath, cmsSpaDistDir);
|
|
597
|
+
}
|
|
598
|
+
if (id === `${cmsRoute}/content-listener.js`) {
|
|
599
|
+
return contentChangeListener();
|
|
600
|
+
}
|
|
601
|
+
if (id === `${cmsRoute}/schemas-entry.js`) {
|
|
602
|
+
if (options.schemasPath) {
|
|
603
|
+
const absoluteSchemasPath = options.schemasPath.startsWith('.')
|
|
604
|
+
? `/${options.schemasPath.slice(2)}`
|
|
605
|
+
: options.schemasPath;
|
|
606
|
+
return schemasLoader(absoluteSchemasPath, cmsSpaDistDir);
|
|
607
|
+
}
|
|
608
|
+
return 'export default {};';
|
|
609
|
+
}
|
|
610
|
+
if (id === `${cmsRoute}/site-styles.js`) {
|
|
611
|
+
if (options.siteStyles) {
|
|
612
|
+
const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];
|
|
613
|
+
return siteStylesLoader(paths, cmsSpaDistDir);
|
|
614
|
+
}
|
|
615
|
+
return 'export default {};';
|
|
616
|
+
}
|
|
617
|
+
if (id === `${cmsRoute}/editor-styles.js`) {
|
|
618
|
+
if (options.editorStyles) {
|
|
619
|
+
const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];
|
|
620
|
+
return editorStylesLoader(paths, cmsSpaDistDir);
|
|
621
|
+
}
|
|
622
|
+
return 'export default {};';
|
|
623
|
+
}
|
|
624
|
+
if (id === RESOLVED_PAGE_API) {
|
|
625
|
+
return generatePageApiModule({
|
|
626
|
+
contentRoot: options.contentRoot,
|
|
627
|
+
canvasDir: options.canvasDir || './canvas',
|
|
628
|
+
siteName: resolvedRoutingConfig?.siteName ?? 'default',
|
|
629
|
+
locale: resolvedRoutingConfig?.locale ?? 'en',
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (id === RESOLVED_CMS_SPA_ENTRY) {
|
|
633
|
+
// Detect whether cms-spa source is available (workspace mode)
|
|
634
|
+
// vs only dist/ (npm install). Reuses `cmsSpaDir` resolved
|
|
635
|
+
// at plugin setup time.
|
|
636
|
+
let cmsSpaImport;
|
|
637
|
+
if (cmsSpaDir) {
|
|
638
|
+
const realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');
|
|
639
|
+
// Prefer the consumer-side symlink path when @conloca/cms-spa is
|
|
640
|
+
// linked in from another workspace (e.g. cross-repo `bun link`).
|
|
641
|
+
// Importing via the symlink path keeps `react`/`react-dom`
|
|
642
|
+
// resolving through the consumer's node_modules walk, which
|
|
643
|
+
// prevents duplicate React instances inside the CMS SPA.
|
|
644
|
+
// Same-workspace installs either don't expose this path or
|
|
645
|
+
// point at the same underlying file, so behavior and HMR
|
|
646
|
+
// are preserved.
|
|
647
|
+
const linkedSrcMainPath = join(astroRoot, 'node_modules', '@conloca', 'cms-spa', 'src', 'main.tsx');
|
|
648
|
+
const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;
|
|
649
|
+
if (existsSync(srcMainPath)) {
|
|
650
|
+
// Workspace mode: import source for HMR
|
|
651
|
+
cmsSpaImport = `import '${srcMainPath}';`;
|
|
652
|
+
}
|
|
653
|
+
else {
|
|
654
|
+
// npm mode: import pre-built SPA mounting entry
|
|
655
|
+
cmsSpaImport = "import '@conloca/cms-spa/main';";
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
// Fallback: use package import
|
|
660
|
+
cmsSpaImport = "import '@conloca/cms-spa/main';";
|
|
661
|
+
}
|
|
662
|
+
return `
|
|
663
|
+
// Import and execute React refresh preamble first (from @vitejs/plugin-react)
|
|
664
|
+
${reactRefreshPreamble}
|
|
665
|
+
|
|
666
|
+
// Import cms-spa through Vite
|
|
667
|
+
// Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
|
|
668
|
+
${cmsSpaImport}
|
|
669
|
+
|
|
670
|
+
// Accept HMR
|
|
671
|
+
if (import.meta.hot) {
|
|
672
|
+
import.meta.hot.accept();
|
|
673
|
+
}
|
|
674
|
+
`;
|
|
675
|
+
}
|
|
676
|
+
return null;
|
|
677
|
+
},
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
// Per-page styles endpoint. Fetches the live HTML for the
|
|
681
|
+
// route and returns every `<style>` block and `<link
|
|
682
|
+
// rel="stylesheet">` it lists — the same set of stylesheets
|
|
683
|
+
// the browser paints with.
|
|
684
|
+
name: 'conloca-styles-endpoint',
|
|
685
|
+
apply: 'serve',
|
|
686
|
+
configureServer(server) {
|
|
687
|
+
server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());
|
|
688
|
+
},
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
// Per-route content-wrapper endpoint. Fetches the live page
|
|
692
|
+
// HTML and returns the host's content-root element shape
|
|
693
|
+
// (`{ tagName, className }`) so the editor can render its
|
|
694
|
+
// contenteditable inside a clone of that wrapper — letting
|
|
695
|
+
// the host's CSS (eg `article.card { background: … }`) paint
|
|
696
|
+
// the editor's content surface naturally, with no per-color
|
|
697
|
+
// bridging.
|
|
698
|
+
name: 'conloca-content-wrapper-endpoint',
|
|
699
|
+
apply: 'serve',
|
|
700
|
+
configureServer(server) {
|
|
701
|
+
server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());
|
|
702
|
+
},
|
|
703
|
+
},
|
|
704
|
+
{
|
|
705
|
+
// Registry + render endpoints are paired: the registry
|
|
706
|
+
// builds the list of legal component sources, and the
|
|
707
|
+
// render endpoint validates every incoming `source`
|
|
708
|
+
// against that list before passing it to ssrLoadModule.
|
|
709
|
+
// Constructing both in one configureServer hook means
|
|
710
|
+
// they share the same memoized scan — no cross-plugin
|
|
711
|
+
// state, no startup-order race.
|
|
712
|
+
//
|
|
713
|
+
// - Registry: scans MDX content for imports + usages and
|
|
714
|
+
// the configured local component folders for
|
|
715
|
+
// `interface Props { ... }`, merges into a single
|
|
716
|
+
// descriptor list, returns it as JSON. The SPA fetches
|
|
717
|
+
// this on mount and seeds `setMdxComponents`,
|
|
718
|
+
// replacing the hand-written `mdx-components.tsx` flow.
|
|
719
|
+
// - Render: renders a single MDX component (Aside,
|
|
720
|
+
// Card, …) via Astro's Container API so the CMS editor
|
|
721
|
+
// can display the real framework markup, paired with
|
|
722
|
+
// the per-page CSS from the styles endpoint above.
|
|
723
|
+
name: 'conloca-registry-and-render-endpoints',
|
|
724
|
+
apply: 'serve',
|
|
725
|
+
configureServer(server) {
|
|
726
|
+
const registry = createRegistryEndpoint({
|
|
727
|
+
contentRoot: resolvedMdxPages ?? options.contentRoot,
|
|
728
|
+
componentFolders: options.mdxComponentFolders ?? ['src/components/mdx'],
|
|
729
|
+
projectRoot: process.cwd(),
|
|
730
|
+
});
|
|
731
|
+
server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
|
|
732
|
+
server.middlewares.use(`${cmsRoute}/api/render`, createRenderEndpoint(server, registry.getAllowedSources));
|
|
733
|
+
// Invalidate the cached scan whenever an .mdx file or
|
|
734
|
+
// any component file changes. Coarse for now — every
|
|
735
|
+
// change re-scans everything; cheap enough for typical
|
|
736
|
+
// project sizes. `.cms.json` sidecars also trigger
|
|
737
|
+
// invalidation so host overrides apply live without a
|
|
738
|
+
// dev-server restart.
|
|
739
|
+
const onFsChange = (filepath) => {
|
|
740
|
+
if (/\.(mdx|astro|tsx|d\.ts|cms\.json)$/.test(filepath))
|
|
741
|
+
registry.invalidate();
|
|
742
|
+
};
|
|
743
|
+
server.watcher.on('add', onFsChange);
|
|
744
|
+
server.watcher.on('change', onFsChange);
|
|
745
|
+
server.watcher.on('unlink', onFsChange);
|
|
746
|
+
},
|
|
747
|
+
},
|
|
748
|
+
{
|
|
749
|
+
name: 'conloca-content-watcher',
|
|
750
|
+
async configureServer(server) {
|
|
751
|
+
const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();
|
|
752
|
+
// Initialize content API using the extracted function.
|
|
753
|
+
// mdxPages / mdxPagesSite / mdxPagesDefaultLocale are
|
|
754
|
+
// read from sites.json by the content-api itself; we
|
|
755
|
+
// don't pass them here.
|
|
756
|
+
const contentApi = await createContentAPI({
|
|
757
|
+
contentRoot: options.contentRoot,
|
|
758
|
+
canvasDir: options.canvasDir || './canvas',
|
|
759
|
+
...(options.locales && {
|
|
760
|
+
availableLocales: options.locales.list,
|
|
761
|
+
defaultLocale: options.locales.defaultLocale,
|
|
762
|
+
}),
|
|
763
|
+
});
|
|
764
|
+
// Only add explicit watchers if content is outside the Astro project
|
|
765
|
+
const { resolve } = await import('node:path');
|
|
766
|
+
const astroRoot = process.cwd();
|
|
767
|
+
const contentAbsolute = resolve(options.contentRoot);
|
|
768
|
+
const canvasAbsolute = resolve(options.canvasDir || './canvas');
|
|
769
|
+
const foldersToWatch = [];
|
|
770
|
+
if (!contentAbsolute.startsWith(astroRoot)) {
|
|
771
|
+
console.log(`[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`);
|
|
772
|
+
foldersToWatch.push(options.contentRoot);
|
|
773
|
+
}
|
|
774
|
+
else {
|
|
775
|
+
console.log(`[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`);
|
|
776
|
+
}
|
|
777
|
+
if (!canvasAbsolute.startsWith(astroRoot)) {
|
|
778
|
+
console.log(`[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`);
|
|
779
|
+
foldersToWatch.push(options.canvasDir || './canvas');
|
|
780
|
+
}
|
|
781
|
+
else {
|
|
782
|
+
console.log(`[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`);
|
|
783
|
+
}
|
|
784
|
+
if (foldersToWatch.length > 0) {
|
|
785
|
+
server.watcher.add(foldersToWatch);
|
|
786
|
+
}
|
|
787
|
+
// Set up HMR for content changes using extracted handlers.
|
|
788
|
+
// The watcher uses `mdxPagesRoot` to flag events under
|
|
789
|
+
// the mdx tree (so docs-loader can refresh). The value
|
|
790
|
+
// comes from sites.json via `resolvedMdxPages`.
|
|
791
|
+
const handlers = createContentWatchHandlers(contentApi, {
|
|
792
|
+
contentRoot: options.contentRoot,
|
|
793
|
+
canvasDir: options.canvasDir || './canvas',
|
|
794
|
+
...(resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }),
|
|
795
|
+
}, server.ws, async (event) => {
|
|
796
|
+
await refreshConlocaContent?.();
|
|
797
|
+
// Astro 6's content-virtual-mod plugin registers an explicit
|
|
798
|
+
// file watcher on `.astro/data-store.json` only (see
|
|
799
|
+
// dist/content/vite-plugin-content-virtual-mod.js: `devServer.watcher.add(dataStoreFile)`).
|
|
800
|
+
// It does NOT watch the sibling `content-modules.mjs` (file
|
|
801
|
+
// path → render function map). When Starlight's docsLoader
|
|
802
|
+
// adds a new MDX entry at runtime, that file IS rewritten on
|
|
803
|
+
// disk, but Vite's SSR moduleGraph keeps the stale module
|
|
804
|
+
// and `renderEntry` throws UnknownContentCollectionError.
|
|
805
|
+
// Force-reload the file ourselves; `reloadModule` is the
|
|
806
|
+
// Vite API that re-runs the load hook on next SSR import.
|
|
807
|
+
if (event.inMdxRoot) {
|
|
808
|
+
const dotAstroModulesFile = resolve(astroRoot, '.astro', 'content-modules.mjs');
|
|
809
|
+
const dotAstroAssetsFile = resolve(astroRoot, '.astro', 'content-assets.mjs');
|
|
810
|
+
for (const env of Object.values(server.environments ?? {})) {
|
|
811
|
+
if (!env?.moduleGraph)
|
|
812
|
+
continue;
|
|
813
|
+
for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {
|
|
814
|
+
const mod = env.moduleGraph.getModuleById(filePath);
|
|
815
|
+
if (!mod)
|
|
816
|
+
continue;
|
|
817
|
+
const envWithReload = env;
|
|
818
|
+
if (typeof envWithReload.reloadModule === 'function') {
|
|
819
|
+
void Promise.resolve(envWithReload.reloadModule(mod)).catch(() => undefined);
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
env.moduleGraph.invalidateModule(mod, undefined, Date.now(), true);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
env.hot?.send('astro:content-changed', {});
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
server.watcher.on('change', handlers.onChange);
|
|
830
|
+
server.watcher.on('add', handlers.onAdd);
|
|
831
|
+
server.watcher.on('unlink', handlers.onUnlink);
|
|
832
|
+
},
|
|
833
|
+
},
|
|
834
|
+
{
|
|
835
|
+
name: 'conloca-suppress-cms-save-reload',
|
|
836
|
+
apply: 'serve',
|
|
837
|
+
configureServer(server) {
|
|
838
|
+
let suppressUntil = 0;
|
|
839
|
+
const WINDOW_MS = 2000;
|
|
840
|
+
const cmsContentPrefix = `${cmsRoute}/api/content`;
|
|
841
|
+
server.middlewares.use((req, _res, next) => {
|
|
842
|
+
const isWrite = req.method === 'POST' ||
|
|
843
|
+
req.method === 'PUT' ||
|
|
844
|
+
req.method === 'PATCH' ||
|
|
845
|
+
req.method === 'DELETE';
|
|
846
|
+
if (isWrite && req.url?.startsWith(cmsContentPrefix)) {
|
|
847
|
+
suppressUntil = Date.now() + WINDOW_MS;
|
|
848
|
+
}
|
|
849
|
+
next();
|
|
850
|
+
});
|
|
851
|
+
// During a CMS save window, drop two server→client signals that
|
|
852
|
+
// would otherwise stomp on the CMS's own optimistic cache updates:
|
|
853
|
+
//
|
|
854
|
+
// 1. Vite `full-reload` — emitted by Astro 6.2.1's invalidateDataStore()
|
|
855
|
+
// in dist/content/vite-plugin-content-virtual-mod.js. The call site
|
|
856
|
+
// is in a configureServer watcher callback, outside the
|
|
857
|
+
// handleHotUpdate pipeline, so wrapping hot.send is the only intercept.
|
|
858
|
+
//
|
|
859
|
+
// 2. `conloca:content-update` custom event — emitted by
|
|
860
|
+
// conloca-content-watcher above. The client listener (template at
|
|
861
|
+
// `contentChangeListener` in this file) reacts by calling
|
|
862
|
+
// queryClient.invalidateQueries() with NO args, refetching every
|
|
863
|
+
// query and visibly blinking lists. CMS mutation hooks already do
|
|
864
|
+
// optimistic setQueryData, so this event is redundant for
|
|
865
|
+
// CMS-originated writes. External edits (outside the save window)
|
|
866
|
+
// still pass through normally.
|
|
867
|
+
const shouldDropDuringWindow = (payload) => {
|
|
868
|
+
if (!payload || typeof payload !== 'object')
|
|
869
|
+
return false;
|
|
870
|
+
const p = payload;
|
|
871
|
+
if (p.type === 'full-reload')
|
|
872
|
+
return true;
|
|
873
|
+
if (p.type === 'custom' && p.event === 'conloca:content-update')
|
|
874
|
+
return true;
|
|
875
|
+
return false;
|
|
876
|
+
};
|
|
877
|
+
const patchSend = (target) => {
|
|
878
|
+
if (!target)
|
|
879
|
+
return;
|
|
880
|
+
const marked = target;
|
|
881
|
+
if (marked.__conlocaPatched)
|
|
882
|
+
return;
|
|
883
|
+
const origSend = target.send.bind(target);
|
|
884
|
+
target.send = ((payload, ...rest) => {
|
|
885
|
+
if (shouldDropDuringWindow(payload) && Date.now() < suppressUntil) {
|
|
886
|
+
server.config.logger.info(`[conloca] suppressed ${payload.type} during CMS save window`, { timestamp: true });
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
return origSend(payload, ...rest);
|
|
890
|
+
});
|
|
891
|
+
marked.__conlocaPatched = true;
|
|
892
|
+
};
|
|
893
|
+
// Astro's content plugin sends `full-reload` via environments.client.hot.
|
|
894
|
+
// Conloca's content watcher sends custom events via server.ws (legacy API).
|
|
895
|
+
// Patch both; idempotent per-target via __conlocaPatched.
|
|
896
|
+
patchSend(server.environments?.client?.hot);
|
|
897
|
+
patchSend(server.ws);
|
|
898
|
+
},
|
|
899
|
+
},
|
|
900
|
+
],
|
|
901
|
+
},
|
|
902
|
+
});
|
|
903
|
+
// Inject unified CMS handler for all CMS routes
|
|
904
|
+
// Single handler validates auth once, then routes to appropriate sub-handler
|
|
905
|
+
injectRoute({
|
|
906
|
+
pattern: `${cmsRoute}/[...path]`,
|
|
907
|
+
entrypoint: CMS_HANDLER_PATH,
|
|
908
|
+
prerender: false,
|
|
909
|
+
});
|
|
910
|
+
// Also handle the root CMS route
|
|
911
|
+
injectRoute({
|
|
912
|
+
pattern: cmsRoute,
|
|
913
|
+
entrypoint: CMS_HANDLER_PATH,
|
|
914
|
+
prerender: false,
|
|
915
|
+
});
|
|
916
|
+
},
|
|
917
|
+
'astro:server:setup': ({ logger, refreshContent }) => {
|
|
918
|
+
logger.info(`Conloca CMS available at ${cmsRoute}`);
|
|
919
|
+
let refreshChain = Promise.resolve();
|
|
920
|
+
refreshConlocaContent = async () => {
|
|
921
|
+
if (!refreshContent) {
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
refreshChain = refreshChain
|
|
925
|
+
.catch(() => undefined)
|
|
926
|
+
.then(async () => {
|
|
927
|
+
await refreshContent({ loaders: ['conloca-loader'] });
|
|
928
|
+
});
|
|
929
|
+
await refreshChain;
|
|
930
|
+
};
|
|
931
|
+
// Register dev-time content refresh after the Vite server exists.
|
|
932
|
+
// This keeps Astro collections in sync with Conloca's own file watcher.
|
|
933
|
+
logger.debug('Registering Conloca content refresh handler');
|
|
934
|
+
},
|
|
935
|
+
'astro:routes:resolved': ({ routes, logger }) => {
|
|
936
|
+
// Check for route conflicts when routing is enabled
|
|
937
|
+
if (!resolvedRoutingConfig?.enabled)
|
|
938
|
+
return;
|
|
939
|
+
const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));
|
|
940
|
+
// Find file-based project routes that conflict with injected routes.
|
|
941
|
+
// Integration routes (origin: 'external') sharing the same catch-all pattern
|
|
942
|
+
// is expected — Astro's prerender fallthrough handles coexistence automatically.
|
|
943
|
+
const conflicts = [];
|
|
944
|
+
for (const route of routes) {
|
|
945
|
+
if (route.origin !== 'project')
|
|
946
|
+
continue;
|
|
947
|
+
const pattern = route.pattern;
|
|
948
|
+
if (injectedPatterns.has(pattern)) {
|
|
949
|
+
conflicts.push({
|
|
950
|
+
injected: pattern,
|
|
951
|
+
fileBased: route.entrypoint || pattern,
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (conflicts.length === 0)
|
|
956
|
+
return;
|
|
957
|
+
// Handle conflicts based on onConflict setting
|
|
958
|
+
const onConflict = resolvedRoutingConfig.onConflict;
|
|
959
|
+
for (const conflict of conflicts) {
|
|
960
|
+
const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;
|
|
961
|
+
if (onConflict === 'error') {
|
|
962
|
+
throw new Error(`[Conloca] ${message}`);
|
|
963
|
+
}
|
|
964
|
+
if (onConflict === 'warn') {
|
|
965
|
+
logger.warn(message);
|
|
966
|
+
}
|
|
967
|
+
// 'silent' - do nothing
|
|
968
|
+
}
|
|
969
|
+
},
|
|
970
|
+
},
|
|
971
|
+
};
|
|
972
|
+
}
|