@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,490 @@
1
+ /**
2
+ * React IntegrationRenderer orchestrator.
3
+ *
4
+ * @remarks
5
+ * Wires services and delegates SSR / layout composition / ownership details to
6
+ * focused modules under `render/`. Prefer changing those modules for
7
+ * implementation work; keep this file as the IntegrationRenderer seam.
8
+ *
9
+ * @module
10
+ */
11
+ import { HttpError } from '@ecopages/core/errors';
12
+ import { buildIslandHostAttributes, getComponentIdentity } from '@ecopages/core';
13
+ import { createIntegrationRenderer, selectHydrationIslandEntries, } from '@ecopages/core/integration';
14
+ import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from '@ecopages/core/client';
15
+ import { resolveQueuedTokens } from '@ecopages/core/integration';
16
+ import { ensurePageConfigLayouts } from '@ecopages/core/integration';
17
+ import { hasSingleRootElement } from './html-boundary.js';
18
+ import { getIslandComponentKey } from '../hydration/hydration-asset.js';
19
+ import { REACT_PLUGIN_NAME } from '../plugin/react.constants.js';
20
+ import { BundleService } from '../bundling/bundle.js';
21
+ import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
22
+ import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
23
+ import { PageModuleService } from '../page/page-module.js';
24
+ import { PagePayloadService } from '../hydration/page-payload.js';
25
+ import { HydrationAssetService } from '../hydration/hydration-asset.js';
26
+ import {} from '@ecopages/core/integration';
27
+ import { asNonReactShellComponent, getComponentRequires, isReactManagedComponent } from './component-ownership.js';
28
+ import { buildHydrationProps, renderComponentHtml, renderNonReactShellComponent, restoreRuntimeChildHtml, toReactNode, } from './component-ssr.js';
29
+ import { BundleError, ReactRenderError } from './errors.js';
30
+ import { resolveReactRuntimeModules } from './react-runtime.js';
31
+ import { composeReactLayoutPageTree, shouldUseUnifiedReactLayoutComposition } from './unified-layout-composition.js';
32
+ import { assertComposablePage, resolveLayoutContextFromShell } from './layout-compose.js';
33
+ export { BundleError, ReactRenderError } from './errors.js';
34
+ const ReactIntegrationRenderer = createIntegrationRenderer(REACT_PLUGIN_NAME);
35
+ /** Renderer adapter that contributes React-specific behavior through core hooks. */
36
+ export class ReactRenderer extends ReactIntegrationRenderer {
37
+ reactRuntimeModules;
38
+ runtimeStateRef;
39
+ hookTargets;
40
+ constructor(options) {
41
+ const { reactConfig, ...rendererOptions } = options;
42
+ const runtimeStateRef = {};
43
+ const hookTargets = {};
44
+ const configuredHooks = createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTargets);
45
+ const additionalHooks = rendererOptions.hooks;
46
+ const hooks = (factoryOptions) => {
47
+ const reactHooks = configuredHooks(factoryOptions);
48
+ const customHooks = typeof additionalHooks === 'function'
49
+ ? additionalHooks({ ...factoryOptions, hooks: reactHooks })
50
+ : additionalHooks;
51
+ return { ...reactHooks, ...customHooks };
52
+ };
53
+ super({ ...rendererOptions, hooks });
54
+ this.runtimeStateRef = runtimeStateRef;
55
+ this.hookTargets = hookTargets;
56
+ this.hookTargets.buildIslandClientAssets = (plan) => this.buildPageClientBrowserAssetsHook(plan);
57
+ this.hookTargets.collectAppBrowserClientBuildEntries = (plan) => this.collectAppBrowserClientBuildEntriesHook(plan);
58
+ this.hookTargets.renderComponent = (input) => this.renderComponentHook(input);
59
+ this.hookTargets.renderQueuedChildren = (children, runtimeContext, queuedResolutionsByToken, resolveToken) => this.renderQueuedChildrenHook(children, runtimeContext, queuedResolutionsByToken, resolveToken);
60
+ this.hookTargets.normalizePageModule = (file, module) => this.normalizeImportedPageFileHook(file, module);
61
+ this.hookTargets.collectPageBrowserGraphContribution = (context) => this.collectPageBrowserGraphContributionHook(context);
62
+ this.hookTargets.composeChildren = ({ page, layouts, foreignChildRoots }) => this.resolveComposeChildren({ page, shellLayouts: layouts, foreignChildRoots });
63
+ this.hookTargets.documentShellProps = (renderOptions) => this.buildDocumentShellProps(renderOptions);
64
+ this.hookTargets.documentContributions = (context) => this.getHtmlDocumentContributionsHook(context);
65
+ this.hookTargets.documentAttributes = (renderOptions) => this.getDocumentAttributesHook(renderOptions);
66
+ }
67
+ get routerAdapter() {
68
+ return this.getRuntimeState().routerAdapter;
69
+ }
70
+ get mdxExtensions() {
71
+ return this.getRuntimeState().mdxExtensions;
72
+ }
73
+ get hmrPageMetadataCache() {
74
+ return this.getRuntimeState().hmrPageMetadataCache;
75
+ }
76
+ get forceBrowserGraph() {
77
+ return this.getRuntimeState().forceBrowserGraph;
78
+ }
79
+ get bundleService() {
80
+ return this.getRuntimeState().bundleService;
81
+ }
82
+ get pageModuleService() {
83
+ return this.getRuntimeState().pageModuleService;
84
+ }
85
+ get hydrationAssetService() {
86
+ return this.getRuntimeState().hydrationAssetService;
87
+ }
88
+ get pagePayloadService() {
89
+ return this.getRuntimeState().pagePayloadService;
90
+ }
91
+ get mdxConfigDependencyService() {
92
+ return this.getRuntimeState().mdxConfigDependencyService;
93
+ }
94
+ getRuntimeState() {
95
+ if (!this.runtimeStateRef.current) {
96
+ throw new Error('React renderer services were used before hook initialization.');
97
+ }
98
+ return this.runtimeStateRef.current;
99
+ }
100
+ /**
101
+ * Builds React island and lazy-entry modules in one grouped browser build.
102
+ */
103
+ async buildPageClientBrowserAssetsHook(plan) {
104
+ const result = await this.hydrationAssetService.buildPageClientRenderAssets({
105
+ islands: selectHydrationIslandEntries(plan, this.name).map((entry) => ({
106
+ file: entry.file,
107
+ config: entry.component.config,
108
+ })),
109
+ lazyEntries: plan.lazyClientEntries,
110
+ });
111
+ const lazyTriggers = this.getRuntimeState().applyPendingLazyTriggers(result.processedAssets, plan.lazyConfigs ?? []);
112
+ return {
113
+ processedAssets: result.processedAssets,
114
+ islandRenderAssetsByFile: result.assetsByFile,
115
+ lazyTriggers,
116
+ };
117
+ }
118
+ async collectAppBrowserClientBuildEntriesHook(plan) {
119
+ return this.hydrationAssetService.collectAppBrowserClientBuildEntries(selectHydrationIslandEntries(plan, this.name).map((entry) => ({
120
+ file: entry.file,
121
+ config: entry.component.config,
122
+ })));
123
+ }
124
+ getRouterDocumentAttributes() {
125
+ if (!this.routerAdapter) {
126
+ return undefined;
127
+ }
128
+ return {
129
+ [ECO_DOCUMENT_OWNER_ATTRIBUTE]: 'react-router',
130
+ };
131
+ }
132
+ resolveReactRuntimeModules() {
133
+ return resolveReactRuntimeModules(this.appConfig.rootDir);
134
+ }
135
+ getReactRuntimeModules() {
136
+ this.reactRuntimeModules ??= this.resolveReactRuntimeModules();
137
+ return this.reactRuntimeModules;
138
+ }
139
+ resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) {
140
+ return this.resolveQueuedForeignSubtrees(html, runtimeContext, async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => ({
141
+ html: await this.renderQueuedChildrenToHtml({
142
+ children,
143
+ runtimeContext: currentRuntimeContext,
144
+ queuedResolutionsByToken,
145
+ resolveToken,
146
+ }),
147
+ }));
148
+ }
149
+ async renderQueuedChildrenToHtml(options) {
150
+ const { children, runtimeContext, queuedResolutionsByToken, resolveToken } = options;
151
+ if (children === undefined) {
152
+ return undefined;
153
+ }
154
+ const { react, reactDomServer } = this.getReactRuntimeModules();
155
+ let html = this.normalizeUnresolvedMarkerArtifactHtml(reactDomServer.renderToString(react.createElement(react.Fragment, null, toReactNode(children, this.name))));
156
+ html = restoreRuntimeChildHtml(html, runtimeContext);
157
+ return await resolveQueuedTokens(html, queuedResolutionsByToken, resolveToken);
158
+ }
159
+ buildPagePayload(options) {
160
+ const safeLocals = this.pagePayloadService.getSerializableLocals(options.locals, getComponentRequires(options.Page));
161
+ return {
162
+ pageModuleUrl: this.pagePayloadService.resolvePageModuleUrl(options.pagePackage, {
163
+ routerEnabled: Boolean(this.routerAdapter),
164
+ }),
165
+ pageProps: this.pagePayloadService.buildSerializedPageProps({
166
+ pageProps: options.pageProps,
167
+ params: options.params,
168
+ query: options.query,
169
+ safeLocals,
170
+ }),
171
+ };
172
+ }
173
+ /**
174
+ * Renders a React component for component-level orchestration.
175
+ *
176
+ * Behavior:
177
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
178
+ * - When an explicit component instance id is provided, a stable
179
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
180
+ * - Without an explicit instance id, component renders remain plain SSR output.
181
+ * - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
182
+ * composition step and does not emit hydration assets for the parent wrapper.
183
+ *
184
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
185
+ * deterministic mount target per component instance.
186
+ */
187
+ async renderComponentHook(input) {
188
+ if (!isReactManagedComponent(input.component, this.name)) {
189
+ return await this.renderForeignComponentWithSerializedHtml(input);
190
+ }
191
+ const runtimeContext = this.getQueuedForeignSubtreeContext(input);
192
+ return await this.renderReactManagedComponent(input, runtimeContext);
193
+ }
194
+ async renderForeignComponentWithSerializedHtml(input) {
195
+ let props = input.props;
196
+ if (input.children !== undefined) {
197
+ props = {
198
+ ...input.props,
199
+ children: typeof input.children === 'string' ? input.children : String(input.children ?? ''),
200
+ };
201
+ }
202
+ const html = await renderNonReactShellComponent(asNonReactShellComponent(input.component), props, 'Component');
203
+ const assets = input.component.config?.dependencies
204
+ ? await this.processComponentDependencies([input.component])
205
+ : undefined;
206
+ return {
207
+ html,
208
+ canAttachAttributes: true,
209
+ integrationName: this.name,
210
+ assets,
211
+ };
212
+ }
213
+ /**
214
+ * Emits a server island host only for eligible, single-root component renders.
215
+ *
216
+ * @remarks
217
+ * Renderer-owned services stay on this class so SSR helpers do not receive
218
+ * wrappers around the renderer's own methods.
219
+ */
220
+ async renderReactManagedComponent(input, runtimeContext) {
221
+ const componentConfig = input.component.config;
222
+ const context = {
223
+ componentInstanceId: input.integrationContext?.componentInstanceId,
224
+ };
225
+ const hasResolvedChildHtml = input.children !== undefined;
226
+ let html = this.normalizeUnresolvedMarkerArtifactHtml(renderComponentHtml({ input, context, runtimeContext, runtime: this.getReactRuntimeModules() }));
227
+ const queuedResolution = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
228
+ html = queuedResolution.html;
229
+ const canAttachAttributes = hasSingleRootElement(html);
230
+ const componentFile = getComponentIdentity(componentConfig)?.file;
231
+ let rootAttributes;
232
+ let assets;
233
+ if (canAttachAttributes && componentFile && context.componentInstanceId && !hasResolvedChildHtml) {
234
+ rootAttributes = buildIslandHostAttributes({
235
+ integrationName: this.name,
236
+ componentInstanceId: context.componentInstanceId,
237
+ componentKey: getIslandComponentKey(componentFile, componentConfig),
238
+ props: buildHydrationProps(input.props),
239
+ });
240
+ assets = this.getActiveIslandRenderAssets().get(componentFile);
241
+ html = `<eco-island style="display:contents">${html}</eco-island>`;
242
+ }
243
+ const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
244
+ ...(assets ?? []),
245
+ ...queuedResolution.assets,
246
+ ]);
247
+ return {
248
+ html,
249
+ canAttachAttributes,
250
+ integrationName: this.name,
251
+ rootAttributes,
252
+ assets: mergedAssets.length > 0 ? mergedAssets : undefined,
253
+ };
254
+ }
255
+ async renderQueuedChildrenHook(children, runtimeContext, queuedResolutionsByToken, resolveToken) {
256
+ if (children === undefined) {
257
+ return {};
258
+ }
259
+ const html = await this.renderQueuedChildrenToHtml({
260
+ children,
261
+ runtimeContext: runtimeContext,
262
+ queuedResolutionsByToken,
263
+ resolveToken,
264
+ });
265
+ return html === undefined ? {} : { html };
266
+ }
267
+ /**
268
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
269
+ * @param filePath - The file path to check
270
+ * @returns True if the file is an MDX file
271
+ */
272
+ isMdxFile(filePath) {
273
+ return this.pageModuleService.isMdxFile(filePath);
274
+ }
275
+ normalizeImportedPageFileHook(file, pageModule) {
276
+ const reactModule = pageModule;
277
+ const { default: Page, getMetadata, config } = reactModule;
278
+ if (this.pageModuleService.isMdxFile(file) && config) {
279
+ ensurePageConfigLayouts(config);
280
+ Page.config = config;
281
+ }
282
+ return {
283
+ ...pageModule,
284
+ default: Page,
285
+ getMetadata,
286
+ config,
287
+ };
288
+ }
289
+ async collectPageBrowserGraphContributionHook(context) {
290
+ try {
291
+ const { file: pagePath, pageModule } = context;
292
+ const shouldHydrate = this.forceBrowserGraph ? true : this.pageModuleService.shouldHydratePage(pageModule);
293
+ if (!shouldHydrate) {
294
+ return { assets: [] };
295
+ }
296
+ const isMdx = this.pageModuleService.isMdxFile(pagePath);
297
+ const declaredModules = this.pageModuleService.collectPageDeclaredModules(pageModule);
298
+ if (isMdx) {
299
+ await this.bundleService.ensurePageLayoutNormalizationVendorProcessed(this.assetProcessingService);
300
+ }
301
+ const dependencies = await this.hydrationAssetService.createPageBrowserGraphDependencies(pagePath, isMdx, declaredModules);
302
+ const assets = isMdx
303
+ ? await this.mdxConfigDependencyService.processMdxConfigDependencies({
304
+ pagePath,
305
+ config: pageModule.config,
306
+ processComponentDependencies: async (components) => await this.processComponentDependencies(components),
307
+ })
308
+ : [];
309
+ return { dependencies, assets };
310
+ }
311
+ catch (error) {
312
+ if (error instanceof BundleError) {
313
+ console.error('[ecopages] Bundle errors:', error.logs);
314
+ }
315
+ throw new ReactRenderError(`Failed to generate hydration script: ${error instanceof Error ? error.message : String(error)}`);
316
+ }
317
+ }
318
+ async composeReactLayoutPageChildrenForShell(page, context) {
319
+ const pageComponent = assertComposablePage(page.component);
320
+ const shellEntries = context.layouts.map((layout) => ({
321
+ component: layout.component,
322
+ props: layout.props,
323
+ }));
324
+ const { react, reactDomServer } = this.getReactRuntimeModules();
325
+ const tree = composeReactLayoutPageTree(pageComponent, page.props, shellEntries, {
326
+ context: resolveLayoutContextFromShell(page.props, shellEntries),
327
+ react,
328
+ });
329
+ const runtimeInput = {
330
+ component: page.component,
331
+ props: page.props,
332
+ integrationContext: {
333
+ rendererCache: context.rendererCache,
334
+ },
335
+ };
336
+ const runtimeContext = this.getQueuedForeignSubtreeContext(runtimeInput);
337
+ const html = this.normalizeUnresolvedMarkerArtifactHtml(reactDomServer.renderToString(tree));
338
+ const resolved = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
339
+ const primaryRender = {
340
+ html: resolved.html,
341
+ canAttachAttributes: hasSingleRootElement(resolved.html),
342
+ integrationName: this.name,
343
+ assets: resolved.assets.length > 0 ? resolved.assets : undefined,
344
+ };
345
+ return {
346
+ children: resolved.html,
347
+ layoutRenders: [],
348
+ primaryRender,
349
+ };
350
+ }
351
+ resolveComposeChildren(options) {
352
+ const { page, shellLayouts, foreignChildRoots } = options;
353
+ if (!shouldUseUnifiedReactLayoutComposition({
354
+ page: page.component,
355
+ shellLayouts,
356
+ reactIntegrationName: this.name,
357
+ })) {
358
+ return undefined;
359
+ }
360
+ if (this.hasForeignChildDescendants(page.component, foreignChildRoots) ||
361
+ shellLayouts.some((layout) => this.hasForeignChildDescendants(layout.component))) {
362
+ return undefined;
363
+ }
364
+ return (context) => this.composeReactLayoutPageChildrenForShell(page, context);
365
+ }
366
+ buildDocumentShellProps(options) {
367
+ const pagePayload = this.buildPagePayload({
368
+ Page: options.Page,
369
+ pageProps: options.pageProps,
370
+ params: options.params,
371
+ query: options.query,
372
+ locals: options.locals,
373
+ pagePackage: options.pagePackage,
374
+ });
375
+ return {
376
+ pageProps: pagePayload.pageProps,
377
+ documentProps: pagePayload.pageModuleUrl ? { pageModuleUrl: pagePayload.pageModuleUrl } : undefined,
378
+ };
379
+ }
380
+ getHtmlDocumentContributionsHook(options) {
381
+ const renderOptions = options.renderOptions;
382
+ if (options.partial ||
383
+ !renderOptions ||
384
+ !this.routerAdapter ||
385
+ isReactManagedComponent(renderOptions.HtmlTemplate, this.name)) {
386
+ return undefined;
387
+ }
388
+ const pagePayload = this.buildPagePayload({
389
+ Page: renderOptions.Page,
390
+ pageProps: renderOptions.pageProps,
391
+ params: renderOptions.params,
392
+ query: renderOptions.query,
393
+ locals: renderOptions.locals,
394
+ pagePackage: renderOptions.pagePackage,
395
+ });
396
+ return this.pagePayloadService.buildNonReactDocumentContributions({
397
+ htmlTemplate: renderOptions.HtmlTemplate,
398
+ pageProps: pagePayload.pageProps,
399
+ pageModuleUrl: pagePayload.pageModuleUrl,
400
+ reactIntegrationName: this.name,
401
+ routerEnabled: true,
402
+ });
403
+ }
404
+ getDocumentAttributesHook(_renderOptions) {
405
+ return this.getRouterDocumentAttributes();
406
+ }
407
+ }
408
+ function createReactRendererHookFactory(reactConfig, runtimeStateRef, hookTargets) {
409
+ return ({ appConfig, assetProcessingIntegration, assetProcessingService, applyPendingLazyTriggers, }) => {
410
+ const routerAdapter = reactConfig?.routerAdapter;
411
+ const mdxExtensions = reactConfig?.mdxExtensions ?? ['.mdx'];
412
+ const hmrPageMetadataCache = reactConfig?.hmrPageMetadataCache;
413
+ const forceBrowserGraph = reactConfig?.forceBrowserGraph ?? false;
414
+ const bundleService = new BundleService({
415
+ rootDir: appConfig.rootDir,
416
+ appConfig,
417
+ assetProcessingIntegration,
418
+ hostIntegrationName: REACT_PLUGIN_NAME,
419
+ routerAdapter,
420
+ runtimeModules: reactConfig?.runtimeModules,
421
+ getMdxLoaderPlugin: reactConfig?.getMdxLoaderPlugin,
422
+ });
423
+ const pageModuleService = new PageModuleService({
424
+ layoutsDir: appConfig.absolutePaths.layoutsDir,
425
+ componentsDir: appConfig.absolutePaths.componentsDir,
426
+ mdxExtensions,
427
+ integrationName: REACT_PLUGIN_NAME,
428
+ hasRouterAdapter: Boolean(routerAdapter),
429
+ });
430
+ const hydrationAssetService = new HydrationAssetService({
431
+ srcDir: appConfig.srcDir,
432
+ routerAdapter,
433
+ assetProcessingService,
434
+ assetProcessingIntegration,
435
+ bundleService,
436
+ hmrPageMetadataCache,
437
+ });
438
+ runtimeStateRef.current = {
439
+ routerAdapter,
440
+ mdxExtensions,
441
+ hmrPageMetadataCache,
442
+ forceBrowserGraph,
443
+ bundleService,
444
+ pageModuleService,
445
+ hydrationAssetService,
446
+ pagePayloadService: new PagePayloadService(),
447
+ mdxConfigDependencyService: new MdxConfigDependencyService({
448
+ integrationName: REACT_PLUGIN_NAME,
449
+ pageModuleService,
450
+ assetProcessingService,
451
+ assetProcessingIntegration,
452
+ }),
453
+ applyPendingLazyTriggers,
454
+ };
455
+ return {
456
+ buildIslandClientAssets: (plan) => requireReactRendererHookTarget(hookTargets, 'buildIslandClientAssets')(plan),
457
+ collectAppBrowserClientBuildEntries: (plan) => requireReactRendererHookTarget(hookTargets, 'collectAppBrowserClientBuildEntries')(plan),
458
+ renderComponent: (input) => requireReactRendererHookTarget(hookTargets, 'renderComponent')(input),
459
+ renderQueuedChildren: (children, runtimeContext, queuedResolutionsByToken, resolveToken) => requireReactRendererHookTarget(hookTargets, 'renderQueuedChildren')(children, runtimeContext, queuedResolutionsByToken, resolveToken),
460
+ normalizePageModule: (file, module) => requireReactRendererHookTarget(hookTargets, 'normalizePageModule')(file, module),
461
+ collectPageBrowserGraphContribution: (context) => requireReactRendererHookTarget(hookTargets, 'collectPageBrowserGraphContribution')(context),
462
+ composeChildren: (input) => requireReactRendererHookTarget(hookTargets, 'composeChildren')(input),
463
+ documentShellProps: (options) => requireReactRendererHookTarget(hookTargets, 'documentShellProps')(options),
464
+ documentContributions: (context) => requireReactRendererHookTarget(hookTargets, 'documentContributions')(context),
465
+ documentAttributes: (options) => requireReactRendererHookTarget(hookTargets, 'documentAttributes')(options),
466
+ renderRoute: async (_options, render) => {
467
+ try {
468
+ return await render();
469
+ }
470
+ catch (error) {
471
+ throw createReactRenderError('Failed to render component', error);
472
+ }
473
+ },
474
+ };
475
+ };
476
+ }
477
+ function requireReactRendererHookTarget(hookTargets, name) {
478
+ const hookTarget = hookTargets[name];
479
+ if (!hookTarget) {
480
+ throw new Error(`React renderer hook "${name}" was called before the renderer was initialized.`);
481
+ }
482
+ return hookTarget;
483
+ }
484
+ function createReactRenderError(message, cause) {
485
+ if (HttpError.isHttpError(cause)) {
486
+ return cause;
487
+ }
488
+ const errorMessage = cause instanceof Error ? `${message}: ${cause.message}` : message;
489
+ return HttpError.InternalServerError(errorMessage);
490
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Resolves the React and react-dom/server modules used for SSR.
3
+ *
4
+ * @remarks
5
+ * Prefers the app's own React install so SSR identity matches the app bundle.
6
+ * Falls back to the integration's React when the app package cannot resolve them.
7
+ */
8
+ import type { ReactRuntime } from './layout-compose.js';
9
+ export type ReactRuntimeModules = {
10
+ react: ReactRuntime;
11
+ reactDomServer: typeof import('react-dom/server');
12
+ };
13
+ export declare function resolveReactRuntimeModules(rootDir: string | undefined): ReactRuntimeModules;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Resolves the React and react-dom/server modules used for SSR.
3
+ *
4
+ * @remarks
5
+ * Prefers the app's own React install so SSR identity matches the app bundle.
6
+ * Falls back to the integration's React when the app package cannot resolve them.
7
+ */
8
+ import { createRequire } from 'node:module';
9
+ import path from 'node:path';
10
+ export function resolveReactRuntimeModules(rootDir) {
11
+ const appPackageJsonPath = path.resolve(rootDir || process.cwd(), 'package.json');
12
+ try {
13
+ const requireFromApp = createRequire(appPackageJsonPath);
14
+ return {
15
+ react: requireFromApp('react'),
16
+ reactDomServer: requireFromApp('react-dom/server'),
17
+ };
18
+ }
19
+ catch {
20
+ const requireFromIntegration = createRequire(import.meta.url);
21
+ return {
22
+ react: requireFromIntegration('react'),
23
+ reactDomServer: requireFromIntegration('react-dom/server'),
24
+ };
25
+ }
26
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Unified React layout + page composition for SSR document shells.
3
+ *
4
+ * @remarks
5
+ * When every shell layout is React-managed, compose one element tree via
6
+ * {@link composeLayoutPageTree} / {@link composeLayoutPageTreeFromShell} instead of
7
+ * rendering each tier separately. This keeps SSR DOM shape aligned with client
8
+ * hydration through `@ecopages/react/layout-compose`.
9
+ */
10
+ import type { EcoComponent } from '@ecopages/core';
11
+ import type { DocumentShellLayoutInput } from '@ecopages/core/integration';
12
+ import type { ReactElement } from 'react';
13
+ import { type ComposablePage, type LayoutComposeOptions } from './layout-compose.js';
14
+ export declare function composeReactLayoutPageTree(Page: ComposablePage, pageProps: Record<string, unknown>, shellEntries: Array<{
15
+ component: EcoComponent;
16
+ props?: Record<string, unknown>;
17
+ }>, options: LayoutComposeOptions): ReactElement;
18
+ export declare function shouldUseUnifiedReactLayoutComposition(options: {
19
+ page: EcoComponent;
20
+ shellLayouts: DocumentShellLayoutInput[];
21
+ reactIntegrationName: string;
22
+ }): boolean;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Unified React layout + page composition for SSR document shells.
3
+ *
4
+ * @remarks
5
+ * When every shell layout is React-managed, compose one element tree via
6
+ * {@link composeLayoutPageTree} / {@link composeLayoutPageTreeFromShell} instead of
7
+ * rendering each tier separately. This keeps SSR DOM shape aligned with client
8
+ * hydration through `@ecopages/react/layout-compose`.
9
+ */
10
+ import { isReactManagedComponent } from './component-ownership.js';
11
+ import { assertComposablePage, composeLayoutPageTree, composeLayoutPageTreeFromShell, } from './layout-compose.js';
12
+ export function composeReactLayoutPageTree(Page, pageProps, shellEntries, options) {
13
+ const hasNormalizedLayouts = Boolean(Page.config?.layoutEntries?.length) || Boolean(Page.config?.layouts?.length);
14
+ if (hasNormalizedLayouts) {
15
+ return composeLayoutPageTree(Page, pageProps, options);
16
+ }
17
+ return composeLayoutPageTreeFromShell(Page, pageProps, shellEntries, options);
18
+ }
19
+ export function shouldUseUnifiedReactLayoutComposition(options) {
20
+ const { page, shellLayouts, reactIntegrationName } = options;
21
+ if (!isReactManagedComponent(page, reactIntegrationName)) {
22
+ return false;
23
+ }
24
+ const composablePage = assertComposablePage(page);
25
+ const configLayouts = composablePage.config?.layouts ?? composablePage.config?.layoutEntries?.map((entry) => entry.component) ?? [];
26
+ const layoutComponents = shellLayouts.length > 0 ? shellLayouts.map((layout) => layout.component) : configLayouts;
27
+ if (layoutComponents.length === 0) {
28
+ return false;
29
+ }
30
+ return layoutComponents.every((component) => isReactManagedComponent(component, reactIntegrationName));
31
+ }
@@ -0,0 +1,3 @@
1
+ type Subscribe = (onStoreChange: () => void) => () => void;
2
+ export declare function useSyncExternalStoreWithSelector<Snapshot, Selection>(subscribe: Subscribe, getSnapshot: () => Snapshot, getServerSnapshot: (() => Snapshot) | undefined, selector: (snapshot: Snapshot) => Selection, isEqual?: (left: Selection, right: Selection) => boolean): Selection;
3
+ export {};
@@ -0,0 +1,54 @@
1
+ /* eslint-disable react-hooks/exhaustive-deps -- shim mirrors upstream ref-based hook semantics */
2
+ import { useDebugValue, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
3
+ const objectIs = Object.is;
4
+ export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
5
+ const instRef = useRef({ hasValue: false, value: undefined });
6
+ const memoizedSelectionRef = useMemo(() => {
7
+ let hasMemo = false;
8
+ let memoizedSnapshot;
9
+ let memoizedSelection;
10
+ const maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
11
+ const memoizedSelector = (nextSnapshot) => {
12
+ if (!hasMemo) {
13
+ hasMemo = true;
14
+ memoizedSnapshot = nextSnapshot;
15
+ const nextSelection = selector(nextSnapshot);
16
+ const inst = instRef.current;
17
+ if (isEqual !== undefined && inst.hasValue) {
18
+ const currentSelection = inst.value;
19
+ if (isEqual(currentSelection, nextSelection)) {
20
+ memoizedSelection = currentSelection;
21
+ return currentSelection;
22
+ }
23
+ }
24
+ memoizedSelection = nextSelection;
25
+ return nextSelection;
26
+ }
27
+ const currentSelection = memoizedSelection;
28
+ if (objectIs(memoizedSnapshot, nextSnapshot)) {
29
+ return currentSelection;
30
+ }
31
+ const nextSelection = selector(nextSnapshot);
32
+ if (isEqual !== undefined && isEqual(currentSelection, nextSelection)) {
33
+ memoizedSnapshot = nextSnapshot;
34
+ return currentSelection;
35
+ }
36
+ memoizedSnapshot = nextSnapshot;
37
+ memoizedSelection = nextSelection;
38
+ return nextSelection;
39
+ };
40
+ return [
41
+ () => memoizedSelector(getSnapshot()),
42
+ maybeGetServerSnapshot === null ? undefined : () => memoizedSelector(maybeGetServerSnapshot()),
43
+ ];
44
+ }, [getSnapshot, getServerSnapshot, selector, isEqual]);
45
+ const value = useSyncExternalStore(subscribe, memoizedSelectionRef[0], memoizedSelectionRef[1]);
46
+ useEffect(() => {
47
+ instRef.current = {
48
+ hasValue: true,
49
+ value,
50
+ };
51
+ }, [value]);
52
+ useDebugValue(value);
53
+ return value;
54
+ }
package/CHANGELOG.md DELETED
@@ -1,29 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to `@ecopages/react` are documented here.
4
-
5
- > **Note:** Changelog tracking begins at version `0.2.0`. Changes prior to this release are not recorded here but are available in the git history.
6
-
7
- ## [0.2.1] — 2026-04-16
8
-
9
- ### Bug Fixes
10
-
11
- - Fixed React hydration, Fast Refresh, module loading, doctype handling, island asset reuse, and mixed-renderer boundary resolution across Bun, Vite, and Nitro flows.
12
-
13
- ### Features
14
-
15
- - Added built-in React MDX support and reachability-based hydration analysis for React page bundles.
16
-
17
- ### Refactoring
18
-
19
- - Consolidated React bundling, hydration, and runtime state behind shared service boundaries and `window.__ECO_PAGES__`.
20
-
21
- ### Documentation
22
-
23
- - Updated the README to document React-owned mixed boundaries and React MDX setup.
24
-
25
- ---
26
-
27
- ## Migration Notes
28
-
29
- - React MDX support is built in and no longer requires installing `@ecopages/mdx` just to enable React MDX routes.