@ecopages/react 0.2.0-alpha.1

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 (59) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/LICENSE +21 -0
  3. package/README.md +65 -0
  4. package/package.json +76 -0
  5. package/src/declarations.d.ts +6 -0
  6. package/src/react-hmr-strategy.d.ts +143 -0
  7. package/src/react-hmr-strategy.js +332 -0
  8. package/src/react-hmr-strategy.ts +444 -0
  9. package/src/react-renderer.d.ts +106 -0
  10. package/src/react-renderer.js +302 -0
  11. package/src/react-renderer.ts +403 -0
  12. package/src/react.plugin.d.ts +147 -0
  13. package/src/react.plugin.js +126 -0
  14. package/src/react.plugin.ts +241 -0
  15. package/src/router-adapter.d.ts +87 -0
  16. package/src/router-adapter.js +0 -0
  17. package/src/router-adapter.ts +95 -0
  18. package/src/services/react-bundle.service.d.ts +68 -0
  19. package/src/services/react-bundle.service.js +145 -0
  20. package/src/services/react-bundle.service.ts +212 -0
  21. package/src/services/react-hmr-page-metadata-cache.d.ts +17 -0
  22. package/src/services/react-hmr-page-metadata-cache.js +19 -0
  23. package/src/services/react-hmr-page-metadata-cache.ts +24 -0
  24. package/src/services/react-hydration-asset.service.d.ts +75 -0
  25. package/src/services/react-hydration-asset.service.js +198 -0
  26. package/src/services/react-hydration-asset.service.ts +260 -0
  27. package/src/services/react-page-module.service.d.ts +80 -0
  28. package/src/services/react-page-module.service.js +155 -0
  29. package/src/services/react-page-module.service.ts +214 -0
  30. package/src/services/react-runtime-bundle.service.d.ts +38 -0
  31. package/src/services/react-runtime-bundle.service.js +207 -0
  32. package/src/services/react-runtime-bundle.service.ts +271 -0
  33. package/src/utils/client-graph-boundary-plugin.d.ts +43 -0
  34. package/src/utils/client-graph-boundary-plugin.js +356 -0
  35. package/src/utils/client-graph-boundary-plugin.ts +590 -0
  36. package/src/utils/client-only.d.ts +8 -0
  37. package/src/utils/client-only.js +19 -0
  38. package/src/utils/client-only.ts +27 -0
  39. package/src/utils/declared-modules.d.ts +42 -0
  40. package/src/utils/declared-modules.js +56 -0
  41. package/src/utils/declared-modules.ts +99 -0
  42. package/src/utils/dynamic.d.ts +15 -0
  43. package/src/utils/dynamic.js +12 -0
  44. package/src/utils/dynamic.ts +27 -0
  45. package/src/utils/hmr-scripts.d.ts +18 -0
  46. package/src/utils/hmr-scripts.js +31 -0
  47. package/src/utils/hmr-scripts.ts +47 -0
  48. package/src/utils/html-boundary.d.ts +7 -0
  49. package/src/utils/html-boundary.js +55 -0
  50. package/src/utils/html-boundary.ts +66 -0
  51. package/src/utils/hydration-scripts.d.ts +71 -0
  52. package/src/utils/hydration-scripts.js +222 -0
  53. package/src/utils/hydration-scripts.ts +338 -0
  54. package/src/utils/reachability-analyzer.d.ts +55 -0
  55. package/src/utils/reachability-analyzer.js +243 -0
  56. package/src/utils/reachability-analyzer.ts +440 -0
  57. package/src/utils/react-mdx-loader-plugin.d.ts +3 -0
  58. package/src/utils/react-mdx-loader-plugin.js +37 -0
  59. package/src/utils/react-mdx-loader-plugin.ts +40 -0
@@ -0,0 +1,198 @@
1
+ import path from "node:path";
2
+ import { rapidhash } from "@ecopages/core/hash";
3
+ import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
+ import {
5
+ AssetFactory
6
+ } from "@ecopages/core/services/asset-processing-service";
7
+ import { createHydrationScript } from "../utils/hydration-scripts.js";
8
+ import { createIslandHydrationScript } from "../utils/hydration-scripts.js";
9
+ import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
10
+ class ReactHydrationAssetService {
11
+ constructor(config) {
12
+ this.config = config;
13
+ }
14
+ /**
15
+ * Resolves the import path for the bundled page component.
16
+ * Uses HMR manager for development or constructs static path for production.
17
+ *
18
+ * @param pagePath - Absolute path to the page source file
19
+ * @param componentName - Generated unique component name
20
+ * @returns The resolved import path for the bundled component
21
+ */
22
+ async resolveAssetImportPath(pagePath, componentName) {
23
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
24
+ if (hmrManager?.isEnabled()) {
25
+ return hmrManager.registerEntrypoint(pagePath);
26
+ }
27
+ return `/${path.join(RESOLVED_ASSETS_DIR, path.relative(this.config.srcDir, pagePath)).replace(path.basename(pagePath), `${componentName}.js`).replace(/\\/g, "/")}`;
28
+ }
29
+ /**
30
+ * Creates the asset dependencies for a page: the bundled component and hydration script.
31
+ *
32
+ * @param pagePath - Absolute path to the page source file
33
+ * @param componentName - Generated unique component name
34
+ * @param importPath - Resolved import path for the bundled component
35
+ * @param bundleOptions - Bundle configuration options
36
+ * @param isDevelopment - Whether running in development mode with HMR
37
+ * @param isMdx - Whether the source file is an MDX file
38
+ * @param props - Optional page props for client serialization
39
+ * @returns Array of asset definitions for processing
40
+ */
41
+ createPageDependencies(pagePath, componentName, importPath, bundleOptions, isDevelopment, isMdx, props) {
42
+ const runtimeImports = this.config.bundleService.getRuntimeImports();
43
+ const dependencies = [
44
+ AssetFactory.createFileScript({
45
+ position: "head",
46
+ filepath: pagePath,
47
+ name: componentName,
48
+ excludeFromHtml: true,
49
+ bundle: true,
50
+ bundleOptions,
51
+ attributes: {
52
+ type: "module",
53
+ defer: "",
54
+ "data-eco-persist": "true"
55
+ }
56
+ })
57
+ ];
58
+ if (props && Object.keys(props).length > 0) {
59
+ dependencies.push(
60
+ AssetFactory.createContentScript({
61
+ position: "head",
62
+ content: `window.__ECO_PAGE__={module:"${importPath}",props:${JSON.stringify(props)}};`,
63
+ name: `${componentName}-props`,
64
+ bundle: false,
65
+ attributes: {
66
+ type: "module"
67
+ }
68
+ })
69
+ );
70
+ }
71
+ dependencies.push(
72
+ AssetFactory.createContentScript({
73
+ position: "head",
74
+ content: createHydrationScript({
75
+ importPath,
76
+ reactImportPath: runtimeImports.react,
77
+ reactDomClientImportPath: runtimeImports.reactDomClient,
78
+ routerImportPath: runtimeImports.router,
79
+ isDevelopment,
80
+ isMdx,
81
+ router: this.config.routerAdapter
82
+ }),
83
+ name: `${componentName}-hydration`,
84
+ bundle: false,
85
+ attributes: {
86
+ type: "module",
87
+ defer: "",
88
+ "data-eco-rerun": "true",
89
+ "data-eco-script-id": `${componentName}-hydration`,
90
+ "data-eco-persist": "true"
91
+ }
92
+ })
93
+ );
94
+ return dependencies;
95
+ }
96
+ /**
97
+ * Builds client-side assets for a React component island.
98
+ *
99
+ * Includes the bundled component entry and an inline hydration bootstrap script.
100
+ *
101
+ * @param componentFile - Absolute path to the component source file
102
+ * @param componentInstanceId - Unique instance ID for DOM targeting
103
+ * @param props - Serialized props for client-side hydration
104
+ * @param config - Optional component config with `__eco` metadata
105
+ * @returns Processed assets ready for injection
106
+ */
107
+ async buildComponentRenderAssets(componentFile, componentInstanceId, props, config) {
108
+ const componentName = `ecopages-react-island-${rapidhash(`${componentFile}:${componentInstanceId}`)}`;
109
+ const importPath = await this.resolveAssetImportPath(componentFile, componentName);
110
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
111
+ const isDevelopment = hmrManager?.isEnabled() ?? false;
112
+ const declaredModules = collectDeclaredModulesInConfig(config);
113
+ const bundleOptions = await this.config.bundleService.createBundleOptions(
114
+ componentName,
115
+ false,
116
+ declaredModules
117
+ );
118
+ const runtimeImports = this.config.bundleService.getRuntimeImports();
119
+ const dependencies = [
120
+ AssetFactory.createFileScript({
121
+ position: "head",
122
+ filepath: componentFile,
123
+ name: componentName,
124
+ excludeFromHtml: true,
125
+ bundle: true,
126
+ bundleOptions,
127
+ attributes: {
128
+ type: "module",
129
+ defer: "",
130
+ "data-eco-persist": "true"
131
+ }
132
+ }),
133
+ AssetFactory.createContentScript({
134
+ position: "head",
135
+ content: createIslandHydrationScript({
136
+ importPath,
137
+ reactImportPath: runtimeImports.react,
138
+ reactDomClientImportPath: runtimeImports.reactDomClient,
139
+ targetSelector: `[data-eco-component-id="${componentInstanceId}"]`,
140
+ props,
141
+ componentRef: config?.__eco?.id,
142
+ componentFile,
143
+ isDevelopment
144
+ }),
145
+ name: `${componentName}-hydration`,
146
+ bundle: false,
147
+ attributes: {
148
+ type: "module",
149
+ defer: "",
150
+ "data-eco-rerun": "true",
151
+ "data-eco-script-id": `${componentName}-hydration`,
152
+ "data-eco-persist": "true"
153
+ }
154
+ })
155
+ ];
156
+ if (!this.config.assetProcessingService) {
157
+ return [];
158
+ }
159
+ return this.config.assetProcessingService.processDependencies(dependencies, componentName);
160
+ }
161
+ /**
162
+ * Builds all client-side route assets for a page.
163
+ *
164
+ * @param pagePath - Absolute file path of the page
165
+ * @param isMdx - Whether the page is an MDX file
166
+ * @param declaredModules - Explicitly declared browser module specifiers
167
+ * @returns Processed assets for the route
168
+ */
169
+ async buildRouteRenderAssets(pagePath, isMdx, declaredModules) {
170
+ const componentName = `ecopages-react-${rapidhash(pagePath)}`;
171
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
172
+ const isDevelopment = hmrManager?.isEnabled() ?? false;
173
+ if (isDevelopment) {
174
+ this.config.hmrPageMetadataCache?.setDeclaredModules(pagePath, declaredModules);
175
+ }
176
+ const importPath = await this.resolveAssetImportPath(pagePath, componentName);
177
+ const bundleOptions = await this.config.bundleService.createBundleOptions(
178
+ componentName,
179
+ isMdx,
180
+ declaredModules
181
+ );
182
+ const dependencies = this.createPageDependencies(
183
+ pagePath,
184
+ componentName,
185
+ importPath,
186
+ bundleOptions,
187
+ isDevelopment,
188
+ isMdx
189
+ );
190
+ if (!this.config.assetProcessingService) {
191
+ throw new Error("AssetProcessingService is not set");
192
+ }
193
+ return this.config.assetProcessingService.processDependencies(dependencies, componentName);
194
+ }
195
+ }
196
+ export {
197
+ ReactHydrationAssetService
198
+ };
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Hydration asset creation service for React integration.
3
+ *
4
+ * Builds the asset definitions (bundled component scripts + hydration bootstrap scripts)
5
+ * required for client-side React rendering — both at the page level and the component
6
+ * island level.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import path from 'node:path';
12
+ import type { EcoComponentConfig } from '@ecopages/core';
13
+ import { rapidhash } from '@ecopages/core/hash';
14
+ import { RESOLVED_ASSETS_DIR } from '@ecopages/core/constants';
15
+ import {
16
+ AssetFactory,
17
+ type AssetDefinition,
18
+ type ProcessedAsset,
19
+ } from '@ecopages/core/services/asset-processing-service';
20
+ import type { AssetProcessingService } from '@ecopages/core/services/asset-processing-service';
21
+ import { createHydrationScript } from '../utils/hydration-scripts.ts';
22
+ import { createIslandHydrationScript } from '../utils/hydration-scripts.ts';
23
+ import { collectDeclaredModulesInConfig } from '../utils/declared-modules.ts';
24
+ import type { ReactBundleService } from './react-bundle.service.ts';
25
+ import type { ReactHmrPageMetadataCache } from './react-hmr-page-metadata-cache.ts';
26
+ import type { ReactRouterAdapter } from '../router-adapter.ts';
27
+
28
+ /**
29
+ * Configuration for the ReactHydrationAssetService.
30
+ */
31
+ export interface ReactHydrationAssetServiceConfig {
32
+ srcDir: string;
33
+ routerAdapter?: ReactRouterAdapter;
34
+ assetProcessingService: AssetProcessingService;
35
+ bundleService: ReactBundleService;
36
+ hmrPageMetadataCache?: ReactHmrPageMetadataCache;
37
+ }
38
+
39
+ /**
40
+ * Manages the creation of client-side hydration assets for React pages and component islands.
41
+ */
42
+ export class ReactHydrationAssetService {
43
+ constructor(private readonly config: ReactHydrationAssetServiceConfig) {}
44
+
45
+ /**
46
+ * Resolves the import path for the bundled page component.
47
+ * Uses HMR manager for development or constructs static path for production.
48
+ *
49
+ * @param pagePath - Absolute path to the page source file
50
+ * @param componentName - Generated unique component name
51
+ * @returns The resolved import path for the bundled component
52
+ */
53
+ async resolveAssetImportPath(pagePath: string, componentName: string): Promise<string> {
54
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
55
+
56
+ if (hmrManager?.isEnabled()) {
57
+ return hmrManager.registerEntrypoint(pagePath);
58
+ }
59
+
60
+ return `/${path
61
+ .join(RESOLVED_ASSETS_DIR, path.relative(this.config.srcDir, pagePath))
62
+ .replace(path.basename(pagePath), `${componentName}.js`)
63
+ .replace(/\\/g, '/')}`;
64
+ }
65
+
66
+ /**
67
+ * Creates the asset dependencies for a page: the bundled component and hydration script.
68
+ *
69
+ * @param pagePath - Absolute path to the page source file
70
+ * @param componentName - Generated unique component name
71
+ * @param importPath - Resolved import path for the bundled component
72
+ * @param bundleOptions - Bundle configuration options
73
+ * @param isDevelopment - Whether running in development mode with HMR
74
+ * @param isMdx - Whether the source file is an MDX file
75
+ * @param props - Optional page props for client serialization
76
+ * @returns Array of asset definitions for processing
77
+ */
78
+ createPageDependencies(
79
+ pagePath: string,
80
+ componentName: string,
81
+ importPath: string,
82
+ bundleOptions: Record<string, unknown>,
83
+ isDevelopment: boolean,
84
+ isMdx: boolean,
85
+ props?: Record<string, unknown>,
86
+ ): AssetDefinition[] {
87
+ const runtimeImports = this.config.bundleService.getRuntimeImports();
88
+ const dependencies: AssetDefinition[] = [
89
+ AssetFactory.createFileScript({
90
+ position: 'head',
91
+ filepath: pagePath,
92
+ name: componentName,
93
+ excludeFromHtml: true,
94
+ bundle: true,
95
+ bundleOptions,
96
+ attributes: {
97
+ type: 'module',
98
+ defer: '',
99
+ 'data-eco-persist': 'true',
100
+ },
101
+ }),
102
+ ];
103
+
104
+ if (props && Object.keys(props).length > 0) {
105
+ dependencies.push(
106
+ AssetFactory.createContentScript({
107
+ position: 'head',
108
+ content: `window.__ECO_PAGE__={module:"${importPath}",props:${JSON.stringify(props)}};`,
109
+ name: `${componentName}-props`,
110
+ bundle: false,
111
+ attributes: {
112
+ type: 'module',
113
+ },
114
+ }),
115
+ );
116
+ }
117
+
118
+ dependencies.push(
119
+ AssetFactory.createContentScript({
120
+ position: 'head',
121
+ content: createHydrationScript({
122
+ importPath,
123
+ reactImportPath: runtimeImports.react,
124
+ reactDomClientImportPath: runtimeImports.reactDomClient,
125
+ routerImportPath: runtimeImports.router,
126
+ isDevelopment,
127
+ isMdx,
128
+ router: this.config.routerAdapter,
129
+ }),
130
+ name: `${componentName}-hydration`,
131
+ bundle: false,
132
+ attributes: {
133
+ type: 'module',
134
+ defer: '',
135
+ 'data-eco-rerun': 'true',
136
+ 'data-eco-script-id': `${componentName}-hydration`,
137
+ 'data-eco-persist': 'true',
138
+ },
139
+ }),
140
+ );
141
+
142
+ return dependencies;
143
+ }
144
+
145
+ /**
146
+ * Builds client-side assets for a React component island.
147
+ *
148
+ * Includes the bundled component entry and an inline hydration bootstrap script.
149
+ *
150
+ * @param componentFile - Absolute path to the component source file
151
+ * @param componentInstanceId - Unique instance ID for DOM targeting
152
+ * @param props - Serialized props for client-side hydration
153
+ * @param config - Optional component config with `__eco` metadata
154
+ * @returns Processed assets ready for injection
155
+ */
156
+ async buildComponentRenderAssets(
157
+ componentFile: string,
158
+ componentInstanceId: string,
159
+ props: Record<string, unknown>,
160
+ config?: EcoComponentConfig,
161
+ ): Promise<ProcessedAsset[]> {
162
+ const componentName = `ecopages-react-island-${rapidhash(`${componentFile}:${componentInstanceId}`)}`;
163
+ const importPath = await this.resolveAssetImportPath(componentFile, componentName);
164
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
165
+ const isDevelopment = hmrManager?.isEnabled() ?? false;
166
+ const declaredModules = collectDeclaredModulesInConfig(config);
167
+ const bundleOptions = await this.config.bundleService.createBundleOptions(
168
+ componentName,
169
+ false,
170
+ declaredModules,
171
+ );
172
+ const runtimeImports = this.config.bundleService.getRuntimeImports();
173
+
174
+ const dependencies: AssetDefinition[] = [
175
+ AssetFactory.createFileScript({
176
+ position: 'head',
177
+ filepath: componentFile,
178
+ name: componentName,
179
+ excludeFromHtml: true,
180
+ bundle: true,
181
+ bundleOptions,
182
+ attributes: {
183
+ type: 'module',
184
+ defer: '',
185
+ 'data-eco-persist': 'true',
186
+ },
187
+ }),
188
+ AssetFactory.createContentScript({
189
+ position: 'head',
190
+ content: createIslandHydrationScript({
191
+ importPath,
192
+ reactImportPath: runtimeImports.react,
193
+ reactDomClientImportPath: runtimeImports.reactDomClient,
194
+ targetSelector: `[data-eco-component-id="${componentInstanceId}"]`,
195
+ props,
196
+ componentRef: config?.__eco?.id,
197
+ componentFile,
198
+ isDevelopment,
199
+ }),
200
+ name: `${componentName}-hydration`,
201
+ bundle: false,
202
+ attributes: {
203
+ type: 'module',
204
+ defer: '',
205
+ 'data-eco-rerun': 'true',
206
+ 'data-eco-script-id': `${componentName}-hydration`,
207
+ 'data-eco-persist': 'true',
208
+ },
209
+ }),
210
+ ];
211
+
212
+ if (!this.config.assetProcessingService) {
213
+ return [];
214
+ }
215
+
216
+ return this.config.assetProcessingService.processDependencies(dependencies, componentName);
217
+ }
218
+
219
+ /**
220
+ * Builds all client-side route assets for a page.
221
+ *
222
+ * @param pagePath - Absolute file path of the page
223
+ * @param isMdx - Whether the page is an MDX file
224
+ * @param declaredModules - Explicitly declared browser module specifiers
225
+ * @returns Processed assets for the route
226
+ */
227
+ async buildRouteRenderAssets(
228
+ pagePath: string,
229
+ isMdx: boolean,
230
+ declaredModules: string[],
231
+ ): Promise<ProcessedAsset[]> {
232
+ const componentName = `ecopages-react-${rapidhash(pagePath)}`;
233
+ const hmrManager = this.config.assetProcessingService?.getHmrManager();
234
+ const isDevelopment = hmrManager?.isEnabled() ?? false;
235
+ if (isDevelopment) {
236
+ this.config.hmrPageMetadataCache?.setDeclaredModules(pagePath, declaredModules);
237
+ }
238
+
239
+ const importPath = await this.resolveAssetImportPath(pagePath, componentName);
240
+ const bundleOptions = await this.config.bundleService.createBundleOptions(
241
+ componentName,
242
+ isMdx,
243
+ declaredModules,
244
+ );
245
+ const dependencies = this.createPageDependencies(
246
+ pagePath,
247
+ componentName,
248
+ importPath,
249
+ bundleOptions,
250
+ isDevelopment,
251
+ isMdx,
252
+ );
253
+
254
+ if (!this.config.assetProcessingService) {
255
+ throw new Error('AssetProcessingService is not set');
256
+ }
257
+
258
+ return this.config.assetProcessingService.processDependencies(dependencies, componentName);
259
+ }
260
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Page module loading and configuration resolution service for React integration.
3
+ *
4
+ * Handles MDX compilation, component config metadata resolution,
5
+ * and module hydration analysis.
6
+ *
7
+ * @module
8
+ */
9
+ import type { EcoComponentConfig, EcoPageFile } from '@ecopages/core';
10
+ import type { CompileOptions } from '@mdx-js/mdx';
11
+ /**
12
+ * Configuration for the ReactPageModuleService.
13
+ */
14
+ export interface ReactPageModuleServiceConfig {
15
+ rootDir: string;
16
+ distDir: string;
17
+ layoutsDir?: string;
18
+ componentsDir?: string;
19
+ mdxCompilerOptions?: CompileOptions;
20
+ mdxExtensions: string[];
21
+ integrationName: string;
22
+ hasRouterAdapter: boolean;
23
+ }
24
+ /**
25
+ * Manages page module loading (including MDX compilation), config metadata
26
+ * resolution, and hydration analysis for React pages.
27
+ */
28
+ export declare class ReactPageModuleService {
29
+ private readonly config;
30
+ constructor(config: ReactPageModuleServiceConfig);
31
+ /**
32
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
33
+ * @param filePath - The file path to check
34
+ * @returns True if the file is an MDX file
35
+ */
36
+ isMdxFile(filePath: string): boolean;
37
+ /**
38
+ * Compiles and imports an MDX file as a page module.
39
+ *
40
+ * @param filePath - Absolute path to the MDX file
41
+ * @returns The imported module
42
+ */
43
+ importMdxPageFile(filePath: string): Promise<unknown>;
44
+ /**
45
+ * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
46
+ * Resolves the file path from dependency declarations when not already set.
47
+ *
48
+ * @param config - The component config to augment
49
+ * @param pagePath - Fallback file path if dependency resolution fails
50
+ * @returns Config with `__eco` metadata populated
51
+ */
52
+ ensureConfigFileMetadata(config: EcoComponentConfig, pagePath: string): EcoComponentConfig;
53
+ /**
54
+ * Recursively checks whether a component config tree declares any browser modules.
55
+ * Used to determine if a page needs hydration.
56
+ */
57
+ hasModulesInConfig(config: EcoComponentConfig | undefined, visited?: Set<EcoComponentConfig>): boolean;
58
+ /**
59
+ * Determines whether a page needs client-side hydration.
60
+ *
61
+ * @param pageModule - The imported page module
62
+ * @returns True if the page should be hydrated
63
+ */
64
+ shouldHydratePage(pageModule: EcoPageFile<{
65
+ config?: EcoComponentConfig;
66
+ }> & {
67
+ config?: EcoComponentConfig;
68
+ }): boolean;
69
+ /**
70
+ * Collects all explicitly declared browser module specifiers from a page module.
71
+ *
72
+ * @param pageModule - The imported page module
73
+ * @returns Deduplicated list of declared module specifiers
74
+ */
75
+ collectPageDeclaredModules(pageModule: EcoPageFile<{
76
+ config?: EcoComponentConfig;
77
+ }> & {
78
+ config?: EcoComponentConfig;
79
+ }): string[];
80
+ }
@@ -0,0 +1,155 @@
1
+ import path from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { rapidhash } from "@ecopages/core/hash";
4
+ import { defaultBuildAdapter } from "@ecopages/core/build/build-adapter";
5
+ import { fileSystem } from "@ecopages/file-system";
6
+ import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
7
+ class ReactPageModuleService {
8
+ constructor(config) {
9
+ this.config = config;
10
+ }
11
+ /**
12
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
13
+ * @param filePath - The file path to check
14
+ * @returns True if the file is an MDX file
15
+ */
16
+ isMdxFile(filePath) {
17
+ return this.config.mdxExtensions.some((ext) => filePath.endsWith(ext));
18
+ }
19
+ /**
20
+ * Compiles and imports an MDX file as a page module.
21
+ *
22
+ * @param filePath - Absolute path to the MDX file
23
+ * @returns The imported module
24
+ */
25
+ async importMdxPageFile(filePath) {
26
+ const { createReactMdxLoaderPlugin } = await import("../utils/react-mdx-loader-plugin.js");
27
+ const mdxPlugin = createReactMdxLoaderPlugin(
28
+ this.config.mdxCompilerOptions ?? {
29
+ jsxImportSource: "react",
30
+ jsxRuntime: "automatic",
31
+ development: process?.env?.NODE_ENV === "development"
32
+ }
33
+ );
34
+ const outdir = path.join(this.config.distDir, ".server-modules-react-mdx");
35
+ const fileBaseName = path.basename(filePath, path.extname(filePath));
36
+ const fileHash = fileSystem.hash(filePath);
37
+ const cacheBuster = process?.env?.NODE_ENV === "development" ? `-${Date.now()}` : "";
38
+ const outputFileName = `${fileBaseName}-${fileHash}${cacheBuster}.js`;
39
+ const buildResult = await defaultBuildAdapter.build({
40
+ entrypoints: [filePath],
41
+ root: this.config.rootDir,
42
+ outdir,
43
+ target: "node",
44
+ format: "esm",
45
+ sourcemap: "none",
46
+ splitting: false,
47
+ minify: false,
48
+ treeshaking: false,
49
+ naming: outputFileName,
50
+ plugins: [mdxPlugin]
51
+ });
52
+ if (!buildResult.success) {
53
+ const details = buildResult.logs.map((log) => log.message).join(" | ");
54
+ throw new Error(`Failed to compile MDX page module: ${details}`);
55
+ }
56
+ const preferredOutputPath = path.join(outdir, outputFileName);
57
+ const compiledOutput = buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ?? buildResult.outputs.find((output) => output.path.endsWith(".js"))?.path;
58
+ if (!compiledOutput) {
59
+ throw new Error(`No compiled MDX output generated for page: ${filePath}`);
60
+ }
61
+ return await import(pathToFileURL(compiledOutput).href);
62
+ }
63
+ /**
64
+ * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
65
+ * Resolves the file path from dependency declarations when not already set.
66
+ *
67
+ * @param config - The component config to augment
68
+ * @param pagePath - Fallback file path if dependency resolution fails
69
+ * @returns Config with `__eco` metadata populated
70
+ */
71
+ ensureConfigFileMetadata(config, pagePath) {
72
+ if (config.__eco?.file) {
73
+ return config;
74
+ }
75
+ const buildEcoMeta = (file) => ({
76
+ id: config.__eco?.id ?? rapidhash(file).toString(36),
77
+ integration: config.__eco?.integration ?? this.config.integrationName,
78
+ file
79
+ });
80
+ const resolveDependencyValue = (value) => typeof value === "string" ? value : value.src;
81
+ const dependencyPaths = [
82
+ ...(config.dependencies?.stylesheets ?? []).map(resolveDependencyValue),
83
+ ...(config.dependencies?.scripts ?? []).map(resolveDependencyValue)
84
+ ].filter((value) => Boolean(value)).filter((value) => value.startsWith("./") || value.startsWith("../"));
85
+ const candidateDirs = [this.config.layoutsDir, this.config.componentsDir, path.dirname(pagePath)].filter(
86
+ (value) => typeof value === "string" && value.length > 0
87
+ );
88
+ for (const dependencyPath of dependencyPaths) {
89
+ for (const candidateDir of candidateDirs) {
90
+ const resolvedDependency = path.resolve(candidateDir, dependencyPath);
91
+ if (fileSystem.exists(resolvedDependency)) {
92
+ return {
93
+ ...config,
94
+ __eco: buildEcoMeta(resolvedDependency)
95
+ };
96
+ }
97
+ }
98
+ }
99
+ return {
100
+ ...config,
101
+ __eco: buildEcoMeta(pagePath)
102
+ };
103
+ }
104
+ /**
105
+ * Recursively checks whether a component config tree declares any browser modules.
106
+ * Used to determine if a page needs hydration.
107
+ */
108
+ hasModulesInConfig(config, visited = /* @__PURE__ */ new Set()) {
109
+ if (!config || visited.has(config)) {
110
+ return false;
111
+ }
112
+ visited.add(config);
113
+ if (config.dependencies?.modules?.some((entry) => entry.trim().length > 0)) {
114
+ return true;
115
+ }
116
+ if (config.layout?.config && this.hasModulesInConfig(config.layout.config, visited)) {
117
+ return true;
118
+ }
119
+ for (const component of config.dependencies?.components ?? []) {
120
+ if (this.hasModulesInConfig(component.config, visited)) {
121
+ return true;
122
+ }
123
+ }
124
+ return false;
125
+ }
126
+ /**
127
+ * Determines whether a page needs client-side hydration.
128
+ *
129
+ * @param pageModule - The imported page module
130
+ * @returns True if the page should be hydrated
131
+ */
132
+ shouldHydratePage(pageModule) {
133
+ if (this.config.hasRouterAdapter) {
134
+ return true;
135
+ }
136
+ const pageConfig = pageModule.default?.config;
137
+ return this.hasModulesInConfig(pageConfig) || this.hasModulesInConfig(pageModule.config);
138
+ }
139
+ /**
140
+ * Collects all explicitly declared browser module specifiers from a page module.
141
+ *
142
+ * @param pageModule - The imported page module
143
+ * @returns Deduplicated list of declared module specifiers
144
+ */
145
+ collectPageDeclaredModules(pageModule) {
146
+ const declarations = [
147
+ ...collectDeclaredModulesInConfig(pageModule.default?.config),
148
+ ...collectDeclaredModulesInConfig(pageModule.config)
149
+ ];
150
+ return Array.from(new Set(declarations));
151
+ }
152
+ }
153
+ export {
154
+ ReactPageModuleService
155
+ };