@ecopages/react 0.2.1 → 0.3.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 (167) hide show
  1. package/README.md +179 -35
  2. package/package.json +78 -33
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  6. package/src/bundling/bootstrap-package-paths.js +5 -0
  7. package/src/bundling/bundle.d.ts +78 -0
  8. package/src/bundling/bundle.js +130 -0
  9. package/src/bundling/runtime-alias-map.d.ts +12 -0
  10. package/src/bundling/runtime-alias-map.js +110 -0
  11. package/src/bundling/runtime-bundle.d.ts +70 -0
  12. package/src/bundling/runtime-bundle.js +233 -0
  13. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  14. package/src/bundling/runtime-interop-plugin.js +32 -0
  15. package/src/bundling/runtime-mode.d.ts +1 -0
  16. package/src/bundling/runtime-mode.js +10 -0
  17. package/src/bundling/runtime-modules.d.ts +21 -0
  18. package/src/bundling/runtime-modules.js +28 -0
  19. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  20. package/src/client-graph/ast-transform-eco-page.js +71 -0
  21. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  22. package/src/client-graph/ast-transform-import-edits.js +75 -0
  23. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  24. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  25. package/src/client-graph/ast-transform.d.ts +12 -0
  26. package/src/client-graph/ast-transform.js +91 -0
  27. package/src/client-graph/ast-walk.d.ts +10 -0
  28. package/src/client-graph/ast-walk.js +26 -0
  29. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  31. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  32. package/src/client-graph/boundary-plugin-transform.js +31 -0
  33. package/src/client-graph/boundary-plugin.d.ts +23 -0
  34. package/src/client-graph/boundary-plugin.js +177 -0
  35. package/src/client-graph/component-config-traversal.d.ts +36 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/{utils → client-graph}/declared-modules.d.ts +1 -1
  38. package/src/client-graph/declared-modules.js +69 -0
  39. package/src/client-graph/module-classification.d.ts +3 -0
  40. package/src/client-graph/module-classification.js +43 -0
  41. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  42. package/src/client-graph/reachability-analyzer.js +55 -0
  43. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  44. package/src/client-graph/reachability-client-roots.js +59 -0
  45. package/src/client-graph/reachability-export-names.d.ts +5 -0
  46. package/src/client-graph/reachability-export-names.js +34 -0
  47. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  48. package/src/client-graph/reachability-fallback-roots.js +71 -0
  49. package/src/client-graph/reachability-preload.d.ts +10 -0
  50. package/src/client-graph/reachability-preload.js +30 -0
  51. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  52. package/src/client-graph/reachability-top-level-index.js +93 -0
  53. package/src/client-graph/reachability-traverse.d.ts +7 -0
  54. package/src/client-graph/reachability-traverse.js +201 -0
  55. package/src/client-graph/specifier-classification.d.ts +74 -0
  56. package/src/client-graph/specifier-classification.js +191 -0
  57. package/src/content/collection-component-cache.d.ts +25 -0
  58. package/src/content/collection-component-cache.js +62 -0
  59. package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +7 -14
  60. package/src/contracts/router-adapter.js +6 -0
  61. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  62. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  63. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  64. package/src/hmr/hmr-strategy-process.js +83 -0
  65. package/src/hmr/hmr-strategy.d.ts +67 -0
  66. package/src/hmr/hmr-strategy.js +306 -0
  67. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +6 -2
  68. package/src/hmr/page-metadata-cache.js +44 -0
  69. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  70. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +81 -0
  74. package/src/hydration/browser/island-hydration.js +247 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/compiled-page-hydration-options.js +1 -0
  83. package/src/hydration/hydration-asset.d.ts +128 -0
  84. package/src/hydration/hydration-asset.js +388 -0
  85. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  86. package/src/hydration/hydration-page-entry-source.js +87 -0
  87. package/src/hydration/hydration-script-compiler.d.ts +47 -0
  88. package/src/hydration/hydration-script-compiler.js +213 -0
  89. package/src/hydration/page-data-manifest.d.ts +58 -0
  90. package/src/hydration/page-data-manifest.js +97 -0
  91. package/src/hydration/page-data-reader.d.ts +17 -0
  92. package/src/hydration/page-data-reader.js +31 -0
  93. package/src/hydration/page-payload.d.ts +68 -0
  94. package/src/hydration/page-payload.js +106 -0
  95. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  96. package/src/hydration/serialize-page-data-script.js +30 -0
  97. package/src/mdx/mdx-config-dependency.d.ts +37 -0
  98. package/src/mdx/mdx-config-dependency.js +107 -0
  99. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  100. package/src/mdx/mdx-loader-plugin.js +11 -0
  101. package/src/page/page-module.d.ts +46 -0
  102. package/src/page/page-module.js +74 -0
  103. package/src/plugin/react.constants.d.ts +1 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/plugin/react.plugin.d.ts +71 -0
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.d.ts +11 -0
  114. package/src/render/eco-embed.js +9 -0
  115. package/src/render/errors.d.ts +16 -0
  116. package/src/render/errors.js +23 -0
  117. package/src/render/html-boundary.js +59 -0
  118. package/src/render/layout-compose.d.ts +66 -0
  119. package/src/render/layout-compose.js +134 -0
  120. package/src/render/react-renderer.d.ts +114 -0
  121. package/src/render/react-renderer.js +490 -0
  122. package/src/render/react-runtime.d.ts +13 -0
  123. package/src/render/react-runtime.js +26 -0
  124. package/src/render/unified-layout-composition.d.ts +22 -0
  125. package/src/render/unified-layout-composition.js +31 -0
  126. package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
  127. package/src/runtime/use-sync-external-store-with-selector.js +54 -0
  128. package/CHANGELOG.md +0 -29
  129. package/src/react-hmr-strategy.d.ts +0 -148
  130. package/src/react-hmr-strategy.js +0 -313
  131. package/src/react-renderer.d.ts +0 -213
  132. package/src/react-renderer.js +0 -654
  133. package/src/react.plugin.d.ts +0 -147
  134. package/src/react.plugin.js +0 -146
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/react-bundle.service.d.ts +0 -47
  137. package/src/services/react-bundle.service.js +0 -93
  138. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  139. package/src/services/react-hydration-asset.service.d.ts +0 -76
  140. package/src/services/react-hydration-asset.service.js +0 -210
  141. package/src/services/react-page-module.service.d.ts +0 -83
  142. package/src/services/react-page-module.service.js +0 -162
  143. package/src/services/react-runtime-bundle.service.d.ts +0 -40
  144. package/src/services/react-runtime-bundle.service.js +0 -130
  145. package/src/utils/client-graph-boundary-plugin.d.ts +0 -43
  146. package/src/utils/client-graph-boundary-plugin.js +0 -494
  147. package/src/utils/client-only.js +0 -19
  148. package/src/utils/declared-modules.js +0 -59
  149. package/src/utils/dynamic.js +0 -12
  150. package/src/utils/hmr-scripts.d.ts +0 -18
  151. package/src/utils/hmr-scripts.js +0 -31
  152. package/src/utils/html-boundary.js +0 -55
  153. package/src/utils/hydration-scripts.d.ts +0 -86
  154. package/src/utils/hydration-scripts.js +0 -285
  155. package/src/utils/reachability-analyzer.d.ts +0 -66
  156. package/src/utils/reachability-analyzer.js +0 -339
  157. package/src/utils/react-dom-runtime-interop-plugin.js +0 -29
  158. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  159. package/src/utils/react-mdx-loader-plugin.js +0 -45
  160. package/src/utils/react-runtime-specifier-map.d.ts +0 -6
  161. package/src/utils/react-runtime-specifier-map.js +0 -37
  162. package/src/utils/use-sync-external-store-shim-plugin.d.ts +0 -5
  163. package/src/utils/use-sync-external-store-shim-plugin.js +0 -41
  164. /package/src/{utils → app}/client-only.d.ts +0 -0
  165. /package/src/{utils → app}/dynamic.d.ts +0 -0
  166. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  167. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,37 @@
1
+ import { type EcoComponent, type EcoComponentConfig } from '@ecopages/core';
2
+ import { type AssetProcessingIntegration, type AssetProcessingService, type ProcessedAsset } from '@ecopages/core/integration';
3
+ import type { PageModuleService } from '../page/page-module.js';
4
+ type MdxConfigDependencyProcessor = (components: Partial<EcoComponent>[]) => Promise<ProcessedAsset[]>;
5
+ export interface MdxConfigDependencyServiceConfig {
6
+ integrationName: string;
7
+ pageModuleService: Pick<PageModuleService, 'ensureConfigFileMetadata'>;
8
+ assetProcessingService: Pick<AssetProcessingService, 'processDependencies'>;
9
+ assetProcessingIntegration?: AssetProcessingIntegration;
10
+ }
11
+ /**
12
+ * Resolves MDX-owned config dependencies that live outside the normal React component tree.
13
+ *
14
+ * React MDX pages can declare dependencies on the page config itself or on a
15
+ * resolved layout config. Those roots need to be materialized as synthetic
16
+ * component configs so the shared dependency pipeline can process them without
17
+ * growing more MDX-specific logic inside the renderer.
18
+ */
19
+ export declare class MdxConfigDependencyService {
20
+ private readonly config;
21
+ constructor(config: MdxConfigDependencyServiceConfig);
22
+ /**
23
+ * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
24
+ */
25
+ processMdxConfigDependencies(options: {
26
+ pagePath: string;
27
+ config?: EcoComponentConfig;
28
+ processComponentDependencies: MdxConfigDependencyProcessor;
29
+ }): Promise<ProcessedAsset[]>;
30
+ private createOwnedConfigComponents;
31
+ private processDeclaredSsrLazyDependencies;
32
+ /**
33
+ * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
34
+ */
35
+ private collectDeclaredSsrLazyDependencies;
36
+ }
37
+ export {};
@@ -0,0 +1,107 @@
1
+ import path from 'node:path';
2
+ import { getComponentIdentity, } from '@ecopages/core';
3
+ import { attachEcoFileMetadataToConfig } from '@ecopages/core/integration';
4
+ import { AssetFactory, } from '@ecopages/core/integration';
5
+ import { collectFromConfigForest, getComponentConfigs } from '../client-graph/component-config-traversal.js';
6
+ /**
7
+ * Resolves MDX-owned config dependencies that live outside the normal React component tree.
8
+ *
9
+ * React MDX pages can declare dependencies on the page config itself or on a
10
+ * resolved layout config. Those roots need to be materialized as synthetic
11
+ * component configs so the shared dependency pipeline can process them without
12
+ * growing more MDX-specific logic inside the renderer.
13
+ */
14
+ export class MdxConfigDependencyService {
15
+ config;
16
+ constructor(config) {
17
+ this.config = config;
18
+ }
19
+ /**
20
+ * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
21
+ */
22
+ async processMdxConfigDependencies(options) {
23
+ const components = this.createOwnedConfigComponents(options.pagePath, options.config);
24
+ if (components.length === 0) {
25
+ return [];
26
+ }
27
+ const processedDependencies = await options.processComponentDependencies(components);
28
+ const eagerSsrLazyDependencies = await this.processDeclaredSsrLazyDependencies(components);
29
+ return [...processedDependencies, ...eagerSsrLazyDependencies];
30
+ }
31
+ createOwnedConfigComponents(pagePath, config) {
32
+ const components = [];
33
+ for (const layout of config?.layouts ?? []) {
34
+ if (layout?.config?.dependencies) {
35
+ const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(layout.config, pagePath);
36
+ components.push({ config: layoutConfig });
37
+ }
38
+ }
39
+ if (config?.dependencies) {
40
+ components.push({
41
+ config: attachEcoFileMetadataToConfig(config, pagePath, this.config.integrationName),
42
+ });
43
+ }
44
+ return components;
45
+ }
46
+ async processDeclaredSsrLazyDependencies(components) {
47
+ const dependencies = this.collectDeclaredSsrLazyDependencies(components);
48
+ if (dependencies.length === 0) {
49
+ return [];
50
+ }
51
+ return this.config.assetProcessingService.processDependencies(dependencies, this.config.assetProcessingIntegration);
52
+ }
53
+ /**
54
+ * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
55
+ */
56
+ collectDeclaredSsrLazyDependencies(components) {
57
+ const dependencies = [];
58
+ const seenKeys = new Set();
59
+ const normalizeAttributes = (attributes) => ({
60
+ type: 'module',
61
+ defer: '',
62
+ ...(attributes ?? {}),
63
+ });
64
+ collectFromConfigForest(getComponentConfigs(components), (config) => {
65
+ const componentFile = getComponentIdentity(config)?.file;
66
+ if (!componentFile) {
67
+ return [];
68
+ }
69
+ const componentDir = path.dirname(componentFile);
70
+ for (const script of config.dependencies?.scripts ?? []) {
71
+ if (typeof script === 'string' || !script.lazy || script.ssr !== true) {
72
+ continue;
73
+ }
74
+ const attributes = normalizeAttributes(script.attributes);
75
+ if (script.content) {
76
+ const key = `content:${script.content}:${JSON.stringify(attributes)}`;
77
+ if (seenKeys.has(key)) {
78
+ continue;
79
+ }
80
+ seenKeys.add(key);
81
+ dependencies.push(AssetFactory.createContentScript({
82
+ position: 'head',
83
+ content: script.content,
84
+ attributes,
85
+ }));
86
+ continue;
87
+ }
88
+ if (!script.src) {
89
+ continue;
90
+ }
91
+ const resolvedPath = path.resolve(componentDir, script.src);
92
+ const key = `file:${resolvedPath}:${JSON.stringify(attributes)}`;
93
+ if (seenKeys.has(key)) {
94
+ continue;
95
+ }
96
+ seenKeys.add(key);
97
+ dependencies.push(AssetFactory.createFileScript({
98
+ filepath: resolvedPath,
99
+ position: 'head',
100
+ attributes,
101
+ }));
102
+ }
103
+ return [];
104
+ });
105
+ return dependencies;
106
+ }
107
+ }
@@ -0,0 +1,8 @@
1
+ import type { CompileOptions } from '@mdx-js/mdx';
2
+ import type { RequestPipelineMetricsState } from '@ecopages/core/build';
3
+ export interface CreateReactMdxLoaderPluginOptions {
4
+ compilerOptions?: CompileOptions;
5
+ projectRoot: string;
6
+ requestPipelineMetrics: RequestPipelineMetricsState;
7
+ }
8
+ export declare function createReactMdxLoaderPlugin(options: CreateReactMdxLoaderPluginOptions): import("@ecopages/core/integration").EcoBuildPlugin;
@@ -0,0 +1,11 @@
1
+ import { createMdxLoaderPlugin as createMdxLoaderPluginCore } from '@ecopages/mdx/core';
2
+ export function createReactMdxLoaderPlugin(options) {
3
+ return createMdxLoaderPluginCore({
4
+ name: 'react-mdx-loader',
5
+ integrationName: 'react',
6
+ compilerOptions: options.compilerOptions,
7
+ defaultMdExtensions: [],
8
+ projectRoot: options.projectRoot,
9
+ requestPipelineMetrics: options.requestPipelineMetrics,
10
+ });
11
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Page module loading and configuration resolution service for React integration.
3
+ *
4
+ * Handles component identity resolution and module hydration analysis.
5
+ * MDX page modules load through the core {@link PageModuleImportService} path
6
+ * using the React plugin's server build contributions.
7
+ *
8
+ * @module
9
+ */
10
+ import { type EcoComponentConfig, type EcoPageFile } from '@ecopages/core';
11
+ /**
12
+ * Configuration for the PageModuleService.
13
+ */
14
+ export interface PageModuleServiceConfig {
15
+ layoutsDir?: string;
16
+ componentsDir?: string;
17
+ mdxExtensions: string[];
18
+ integrationName: string;
19
+ hasRouterAdapter: boolean;
20
+ }
21
+ /**
22
+ * Manages page module metadata resolution and hydration analysis for React pages.
23
+ */
24
+ export declare class PageModuleService {
25
+ private readonly config;
26
+ constructor(config: PageModuleServiceConfig);
27
+ /**
28
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
29
+ */
30
+ isMdxFile(filePath: string): boolean;
31
+ /**
32
+ * Ensures that an EcoComponentConfig has canonical identity attached.
33
+ */
34
+ ensureConfigFileMetadata(config: EcoComponentConfig, pagePath: string): EcoComponentConfig;
35
+ hasModulesInConfig(config: EcoComponentConfig | undefined): boolean;
36
+ shouldHydratePage(pageModule: EcoPageFile<{
37
+ config?: EcoComponentConfig;
38
+ }> & {
39
+ config?: EcoComponentConfig;
40
+ }): boolean;
41
+ collectPageDeclaredModules(pageModule: EcoPageFile<{
42
+ config?: EcoComponentConfig;
43
+ }> & {
44
+ config?: EcoComponentConfig;
45
+ }): string[];
46
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Page module loading and configuration resolution service for React integration.
3
+ *
4
+ * Handles component identity resolution and module hydration analysis.
5
+ * MDX page modules load through the core {@link PageModuleImportService} path
6
+ * using the React plugin's server build contributions.
7
+ *
8
+ * @module
9
+ */
10
+ import path from 'node:path';
11
+ import { bindComponentIdentity, getComponentIdentity, getComponentOwner, } from '@ecopages/core';
12
+ import { contentHash } from '@ecopages/core/build';
13
+ import { fileSystem } from '@ecopages/file-system';
14
+ import { someInConfigTree } from '../client-graph/component-config-traversal.js';
15
+ import { collectPageDeclaredModulesFromModule } from '../client-graph/declared-modules.js';
16
+ /**
17
+ * Manages page module metadata resolution and hydration analysis for React pages.
18
+ */
19
+ export class PageModuleService {
20
+ config;
21
+ constructor(config) {
22
+ this.config = config;
23
+ }
24
+ /**
25
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
26
+ */
27
+ isMdxFile(filePath) {
28
+ return this.config.mdxExtensions.some((ext) => filePath.endsWith(ext));
29
+ }
30
+ /**
31
+ * Ensures that an EcoComponentConfig has canonical identity attached.
32
+ */
33
+ ensureConfigFileMetadata(config, pagePath) {
34
+ const identity = getComponentIdentity(config);
35
+ if (identity?.file) {
36
+ return config;
37
+ }
38
+ const buildIdentity = (file) => ({
39
+ id: identity?.id ?? BigInt(`0x${contentHash(file, 16)}`).toString(36),
40
+ integration: getComponentOwner(config, this.config.integrationName),
41
+ file,
42
+ });
43
+ const resolveDependencyValue = (value) => typeof value === 'string' ? value : value.src;
44
+ const dependencyPaths = [
45
+ ...(config.dependencies?.stylesheets ?? []).map(resolveDependencyValue),
46
+ ...(config.dependencies?.scripts ?? []).map(resolveDependencyValue),
47
+ ]
48
+ .filter((value) => Boolean(value))
49
+ .filter((value) => value.startsWith('./') || value.startsWith('../'));
50
+ const candidateDirs = [this.config.layoutsDir, this.config.componentsDir, path.dirname(pagePath)].filter((value) => typeof value === 'string' && value.length > 0);
51
+ for (const dependencyPath of dependencyPaths) {
52
+ for (const candidateDir of candidateDirs) {
53
+ const resolvedDependency = path.resolve(candidateDir, dependencyPath);
54
+ if (fileSystem.exists(resolvedDependency)) {
55
+ return bindComponentIdentity(buildIdentity(path.join(candidateDir, path.basename(pagePath))), config);
56
+ }
57
+ }
58
+ }
59
+ return bindComponentIdentity(buildIdentity(pagePath), config);
60
+ }
61
+ hasModulesInConfig(config) {
62
+ return someInConfigTree(config, (node) => node.dependencies?.modules?.some((entry) => entry.trim().length > 0) ?? false);
63
+ }
64
+ shouldHydratePage(pageModule) {
65
+ if (this.config.hasRouterAdapter) {
66
+ return true;
67
+ }
68
+ const pageConfig = pageModule.default?.config;
69
+ return this.hasModulesInConfig(pageConfig) || this.hasModulesInConfig(pageModule.config);
70
+ }
71
+ collectPageDeclaredModules(pageModule) {
72
+ return collectPageDeclaredModulesFromModule(pageModule);
73
+ }
74
+ }
@@ -0,0 +1 @@
1
+ export declare const REACT_PLUGIN_NAME = "react";
@@ -0,0 +1 @@
1
+ export const REACT_PLUGIN_NAME = 'react';
@@ -0,0 +1,71 @@
1
+ import { IntegrationPlugin, type IntegrationRendererBase, type IntegrationRuntimeContext, type EcoBuildPlugin } from '@ecopages/core/integration';
2
+ import type React from 'react';
3
+ import { ReactRenderer } from '../render/react-renderer.js';
4
+ import type { ReactPluginOptions } from './react.types.js';
5
+ export type { ReactMdxOptions, ReactPluginOptions, ReactRendererConfig } from './react.types.js';
6
+ /**
7
+ * The name of the React plugin
8
+ */
9
+ export declare const PLUGIN_NAME = "react";
10
+ /**
11
+ * The React plugin class
12
+ * This plugin provides support for React components in Ecopages
13
+ */
14
+ export declare class ReactPlugin extends IntegrationPlugin<React.ReactNode> {
15
+ renderer: typeof ReactRenderer;
16
+ readonly bundlesPageDependencies = true;
17
+ private readonly routerAdapter;
18
+ private readonly mdxExtensions;
19
+ private readonly mdxCompilerOptions;
20
+ private readonly getMdxLoaderPlugin?;
21
+ private readonly runtimeBundleService;
22
+ private readonly hmrPageMetadataCache;
23
+ private runtimeDependenciesInitialized;
24
+ /**
25
+ * When true, always emit page browser graph / hydration assets.
26
+ *
27
+ * @remarks
28
+ * Mapped from public `explicitGraph`. Does not skip client-graph AST stripping.
29
+ */
30
+ private readonly forceBrowserGraph;
31
+ private readonly rendererConfig;
32
+ constructor(options?: ReactPluginOptions);
33
+ /**
34
+ * Creates a React renderer with instance-owned runtime configuration.
35
+ *
36
+ * React renderers depend on plugin-owned router, MDX, and HMR metadata state.
37
+ * Keeping that state on the instance avoids cross-plugin static mutation while
38
+ * preserving the same runtime services the base initializer wires up.
39
+ */
40
+ createRenderer(base: IntegrationRendererBase): ReactRenderer;
41
+ private ensureRuntimeDependencies;
42
+ /**
43
+ * Returns the MDX loader when MDX is enabled.
44
+ *
45
+ * @remarks
46
+ * The loader is created on the first read for an app runtime and kept, because the renderer and the HMR
47
+ * strategy reuse the instance the build manifest holds.
48
+ */
49
+ plugins(app: IntegrationRuntimeContext['appConfig']): EcoBuildPlugin[];
50
+ private resolveMdxLoaderPlugin;
51
+ /**
52
+ * Adds the React runtime vendor assets to the global dependencies, then processes them.
53
+ */
54
+ setup(context: IntegrationRuntimeContext): Promise<void>;
55
+ /**
56
+ * Provides React-specific HMR strategy with Fast Refresh support.
57
+ *
58
+ * The strategy shares a React-only page metadata cache with the renderer so
59
+ * save-time rebuilds can reuse declared-module analysis without expanding the
60
+ * core HMR interfaces.
61
+ *
62
+ * @returns ReactHmrStrategy instance for handling React component updates
63
+ */
64
+ hmr(context: IntegrationRuntimeContext): void;
65
+ }
66
+ /**
67
+ * Factory function to create a React plugin instance
68
+ * @param options Configuration options for the React plugin
69
+ * @returns A new ReactPlugin instance
70
+ */
71
+ export declare function reactPlugin(options?: ReactPluginOptions): ReactPlugin;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * This module contains the react plugin for Ecopages
3
+ * @module
4
+ */
5
+ import { requireAppRuntime } from '@ecopages/core/integration';
6
+ import { IntegrationPlugin, } from '@ecopages/core/integration';
7
+ import { Logger } from '@ecopages/logger';
8
+ import path from 'node:path';
9
+ import { REACT_PLUGIN_NAME } from './react.constants.js';
10
+ import { ReactRenderer } from '../render/react-renderer.js';
11
+ import { ReactHmrStrategy } from '../hmr/hmr-strategy.js';
12
+ import { ReactDevTransformContributor } from '../dev-transform/react-dev-transform-contributor.js';
13
+ import { RuntimeBundleService } from '../bundling/runtime-bundle.js';
14
+ import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
15
+ import { createReactMdxLoaderPlugin } from '../mdx/mdx-loader-plugin.js';
16
+ import { appendMdxExtensions, resolveMdxCompilerOptions } from '@ecopages/mdx/core';
17
+ import { resolveReactPluginRuntimeModules } from '../bundling/runtime-modules.js';
18
+ const appLogger = new Logger('[ReactPlugin]');
19
+ /**
20
+ * The name of the React plugin
21
+ */
22
+ export const PLUGIN_NAME = REACT_PLUGIN_NAME;
23
+ const resolveReactMdxCompilerOptions = (mdxOptions) => resolveMdxCompilerOptions(mdxOptions, { jsxImportSource: 'react' });
24
+ /**
25
+ * Resolves user-facing React plugin options into the internal plugin config.
26
+ *
27
+ * Defaults:
28
+ * - `extensions`: `['.tsx']`
29
+ * - `explicitGraph`: `false`
30
+ * - MDX is disabled when `mdx` is omitted
31
+ * - `mdx.extensions`: `['.mdx']`
32
+ */
33
+ const resolveReactPluginOptions = (options) => {
34
+ const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, runtimeModules, ...baseConfig } = options ?? {};
35
+ const extensions = [...(userExtensions ?? ['.tsx'])];
36
+ const mdxEnabled = mdx !== undefined;
37
+ const mdxExtensions = mdx?.extensions ?? ['.mdx'];
38
+ const resolvedRuntimeModules = resolveReactPluginRuntimeModules(runtimeModules);
39
+ if (mdxEnabled) {
40
+ appendMdxExtensions(extensions, mdxExtensions);
41
+ }
42
+ const rendererConfig = {
43
+ routerAdapter: router,
44
+ runtimeModules: resolvedRuntimeModules,
45
+ mdxExtensions,
46
+ hmrPageMetadataCache: new HmrPageMetadataCache(),
47
+ forceBrowserGraph: explicitGraph ?? false,
48
+ };
49
+ return {
50
+ ...baseConfig,
51
+ extensions,
52
+ integrationDependencies: dependencies,
53
+ mdxCompilerOptions: mdxEnabled && mdx ? resolveReactMdxCompilerOptions(mdx) : undefined,
54
+ rendererConfig,
55
+ };
56
+ };
57
+ /**
58
+ * The React plugin class
59
+ * This plugin provides support for React components in Ecopages
60
+ */
61
+ export class ReactPlugin extends IntegrationPlugin {
62
+ renderer = ReactRenderer;
63
+ bundlesPageDependencies = true;
64
+ routerAdapter;
65
+ mdxExtensions;
66
+ mdxCompilerOptions;
67
+ getMdxLoaderPlugin;
68
+ runtimeBundleService;
69
+ hmrPageMetadataCache;
70
+ runtimeDependenciesInitialized = false;
71
+ /**
72
+ * When true, always emit page browser graph / hydration assets.
73
+ *
74
+ * @remarks
75
+ * Mapped from public `explicitGraph`. Does not skip client-graph AST stripping.
76
+ */
77
+ forceBrowserGraph;
78
+ rendererConfig;
79
+ constructor(options) {
80
+ const config = resolveReactPluginOptions(options);
81
+ const { extensions, rendererConfig, integrationDependencies, mdxCompilerOptions, ...baseConfig } = config;
82
+ const runtimeBundleService = new RuntimeBundleService({
83
+ routerAdapter: rendererConfig.routerAdapter,
84
+ runtimeModules: rendererConfig.runtimeModules,
85
+ });
86
+ super({
87
+ name: PLUGIN_NAME,
88
+ extensions,
89
+ jsxImportSource: 'react',
90
+ integrationDependencies,
91
+ browserRuntimeManifest: runtimeBundleService.getRuntimeManifest(),
92
+ ...baseConfig,
93
+ });
94
+ this.routerAdapter = rendererConfig.routerAdapter;
95
+ this.mdxCompilerOptions = mdxCompilerOptions;
96
+ this.getMdxLoaderPlugin = mdxCompilerOptions
97
+ ? () => {
98
+ if (!this.appConfig?.rootDir) {
99
+ throw new Error('[ReactPlugin] Cannot create MDX loader: appConfig.rootDir is required.');
100
+ }
101
+ const plugin = this.runtime?.buildManifest.server.find((item) => item.name === 'react-mdx-loader');
102
+ if (!plugin) {
103
+ throw new Error('[ReactPlugin] The app build manifest does not contain the React MDX loader.');
104
+ }
105
+ return plugin;
106
+ }
107
+ : undefined;
108
+ this.mdxExtensions = rendererConfig.mdxExtensions ?? ['.mdx'];
109
+ this.hmrPageMetadataCache = rendererConfig.hmrPageMetadataCache ?? new HmrPageMetadataCache();
110
+ this.forceBrowserGraph = rendererConfig.forceBrowserGraph ?? false;
111
+ this.rendererConfig = {
112
+ ...rendererConfig,
113
+ getMdxLoaderPlugin: this.getMdxLoaderPlugin,
114
+ mdxExtensions: this.mdxExtensions,
115
+ hmrPageMetadataCache: this.hmrPageMetadataCache,
116
+ forceBrowserGraph: this.forceBrowserGraph,
117
+ };
118
+ if (mdxCompilerOptions) {
119
+ appLogger.debug('MDX mode enabled with React jsx runtime');
120
+ }
121
+ this.runtimeBundleService = runtimeBundleService;
122
+ }
123
+ /**
124
+ * Creates a React renderer with instance-owned runtime configuration.
125
+ *
126
+ * React renderers depend on plugin-owned router, MDX, and HMR metadata state.
127
+ * Keeping that state on the instance avoids cross-plugin static mutation while
128
+ * preserving the same runtime services the base initializer wires up.
129
+ */
130
+ createRenderer(base) {
131
+ const renderer = new this.renderer({
132
+ ...base,
133
+ reactConfig: this.rendererConfig,
134
+ });
135
+ renderer.name ||= this.name;
136
+ return renderer;
137
+ }
138
+ ensureRuntimeDependencies(appConfig) {
139
+ if (this.runtimeDependenciesInitialized) {
140
+ return;
141
+ }
142
+ this.runtimeBundleService.setRootDir(appConfig.rootDir);
143
+ this.runtimeBundleService.setWorkDir(appConfig.absolutePaths.workDir ?? path.join(appConfig.rootDir, appConfig.workDir ?? '.eco'));
144
+ this.runtimeBundleService.setRuntimeModules(this.rendererConfig.runtimeModules ?? []);
145
+ this.integrationDependencies.unshift(...this.runtimeBundleService.getDependencies());
146
+ this.runtimeDependenciesInitialized = true;
147
+ }
148
+ /**
149
+ * Returns the MDX loader when MDX is enabled.
150
+ *
151
+ * @remarks
152
+ * The loader is created on the first read for an app runtime and kept, because the renderer and the HMR
153
+ * strategy reuse the instance the build manifest holds.
154
+ */
155
+ plugins(app) {
156
+ const loader = this.mdxCompilerOptions ? this.resolveMdxLoaderPlugin(this.mdxCompilerOptions, app) : undefined;
157
+ return loader ? [loader] : [];
158
+ }
159
+ resolveMdxLoaderPlugin(compilerOptions, appConfig) {
160
+ const requestPipelineMetrics = requireAppRuntime(appConfig).requestPipelineMetrics;
161
+ return createReactMdxLoaderPlugin({
162
+ compilerOptions,
163
+ projectRoot: appConfig.rootDir,
164
+ requestPipelineMetrics,
165
+ });
166
+ }
167
+ /**
168
+ * Adds the React runtime vendor assets to the global dependencies, then processes them.
169
+ */
170
+ async setup(context) {
171
+ this.ensureRuntimeDependencies(context.appConfig);
172
+ await super.setup(context);
173
+ }
174
+ /**
175
+ * Provides React-specific HMR strategy with Fast Refresh support.
176
+ *
177
+ * The strategy shares a React-only page metadata cache with the renderer so
178
+ * save-time rebuilds can reuse declared-module analysis without expanding the
179
+ * core HMR interfaces.
180
+ *
181
+ * @returns ReactHmrStrategy instance for handling React component updates
182
+ */
183
+ hmr(context) {
184
+ super.hmr(context);
185
+ const manager = context.runtime.hmr;
186
+ if (!manager)
187
+ return;
188
+ const strategy = new ReactHmrStrategy({
189
+ context: manager.getDefaultContext(),
190
+ projectRoot: context.appConfig.rootDir,
191
+ pageMetadataCache: this.hmrPageMetadataCache,
192
+ runtimeManifest: this.runtimeBundleService.getRuntimeManifest('development'),
193
+ getMdxLoaderPlugin: this.getMdxLoaderPlugin,
194
+ ownedTemplateExtensions: this.extensions,
195
+ allTemplateExtensions: context.appConfig.templatesExt,
196
+ });
197
+ manager.registerStrategy(strategy);
198
+ manager.registerDevTransformContributor(new ReactDevTransformContributor({
199
+ strategy: strategy,
200
+ }));
201
+ }
202
+ }
203
+ /**
204
+ * Factory function to create a React plugin instance
205
+ * @param options Configuration options for the React plugin
206
+ * @returns A new ReactPlugin instance
207
+ */
208
+ export function reactPlugin(options) {
209
+ return new ReactPlugin(options);
210
+ }
@@ -0,0 +1,106 @@
1
+ import type { AssetDefinition } from '@ecopages/core/integration';
2
+ import type { EcoBuildPlugin } from '@ecopages/core/integration';
3
+ import type { MdxCompilerOptionsInput } from '@ecopages/mdx/core';
4
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
5
+ import type { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
6
+ import type { ReactPluginRuntimeModule, ResolvedReactPluginRuntimeModule } from '../bundling/runtime-modules.js';
7
+ export type ReactMdxOptions = MdxCompilerOptionsInput;
8
+ /**
9
+ * Options for the React plugin.
10
+ */
11
+ export type ReactPluginOptions = {
12
+ extensions?: string[];
13
+ dependencies?: AssetDefinition[];
14
+ /**
15
+ * When true, always emit the page browser graph / hydration assets for React
16
+ * page entries, even when the page does not declare `dependencies.modules`
17
+ * and no router adapter is configured.
18
+ *
19
+ * @remarks
20
+ * This does not skip the client-graph AST boundary. Server-only
21
+ * `eco.page(...)` options such as `middleware` and `requires` are still
22
+ * stripped from browser bundles.
23
+ *
24
+ * With a router adapter, page hydration is already always enabled, so this
25
+ * option is redundant for SPA apps.
26
+ *
27
+ * @default false
28
+ */
29
+ explicitGraph?: boolean;
30
+ /**
31
+ * Router adapter for SPA navigation.
32
+ * When provided, pages with layouts will be wrapped in the router for client-side navigation.
33
+ * @example
34
+ * ```ts
35
+ * import { ecoRouter } from '@ecopages/react-router';
36
+ * reactPlugin({ router: ecoRouter() })
37
+ * ```
38
+ */
39
+ router?: ReactRouterAdapter;
40
+ /**
41
+ * Optional shared browser runtime vendors.
42
+ *
43
+ * @remarks
44
+ * Packages listed here use one vendor URL across page browser graphs. Add
45
+ * singleton packages such as TanStack Query or MobX when pages and layouts
46
+ * need to share the same module instance; layouts do not infer these entries.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * reactPlugin({
51
+ * router: ecoRouter(),
52
+ * runtimeModules: ['@tanstack/react-query'],
53
+ * });
54
+ * ```
55
+ *
56
+ * Register the exact specifier imported by the page or layout. Package
57
+ * subpaths are separate module contracts and need separate entries.
58
+ *
59
+ * @example Advanced vendor config
60
+ * ```ts
61
+ * runtimeModules: [
62
+ * { specifier: '@acme/ui', outputName: 'acme-ui' },
63
+ * ]
64
+ * ```
65
+ */
66
+ runtimeModules?: ReactPluginRuntimeModule[];
67
+ /**
68
+ * MDX configuration for handling .mdx files within the React plugin.
69
+ * When configured, MDX files are treated as React pages with full router support.
70
+ * @example
71
+ * ```ts
72
+ * reactPlugin({
73
+ * router: ecoRouter(),
74
+ * mdx: {
75
+ * extensions: ['.mdx', '.md'],
76
+ * remarkPlugins: [remarkGfm],
77
+ * rehypePlugins: [[rehypePrettyCode, { theme: '...' }]],
78
+ * }
79
+ * })
80
+ * ```
81
+ */
82
+ mdx?: ReactMdxOptions;
83
+ };
84
+ export type ReactRendererConfig = {
85
+ routerAdapter?: ReactRouterAdapter;
86
+ runtimeModules?: ResolvedReactPluginRuntimeModule[];
87
+ /**
88
+ * Returns the plugin-owned MDX loader, creating it on first call. Set only
89
+ * when MDX is enabled.
90
+ *
91
+ * @remarks
92
+ * Server builds, browser bundles and HMR rebuilds all use this one loader, so
93
+ * they share its compile cache.
94
+ */
95
+ getMdxLoaderPlugin?: () => EcoBuildPlugin;
96
+ mdxExtensions?: string[];
97
+ hmrPageMetadataCache?: HmrPageMetadataCache;
98
+ /**
99
+ * When true, always emit page browser graph / hydration assets for React pages.
100
+ *
101
+ * @remarks
102
+ * Mapped from the public `explicitGraph` plugin option. Does not skip the
103
+ * client-graph AST strip of server-only `eco.page(...)` options.
104
+ */
105
+ forceBrowserGraph?: boolean;
106
+ };