@ecopages/react 0.2.0-alpha.2 → 0.2.0-alpha.20

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 (66) hide show
  1. package/CHANGELOG.md +19 -39
  2. package/README.md +160 -18
  3. package/package.json +6 -6
  4. package/src/react-hmr-strategy.d.ts +26 -21
  5. package/src/react-hmr-strategy.js +91 -110
  6. package/src/react-renderer.d.ts +165 -41
  7. package/src/react-renderer.js +451 -158
  8. package/src/react.constants.d.ts +1 -0
  9. package/src/react.constants.js +4 -0
  10. package/src/react.plugin.d.ts +37 -108
  11. package/src/react.plugin.js +125 -54
  12. package/src/react.types.d.ts +88 -0
  13. package/src/react.types.js +0 -0
  14. package/src/router-adapter.d.ts +2 -2
  15. package/src/services/react-bundle.service.d.ts +4 -25
  16. package/src/services/react-bundle.service.js +39 -91
  17. package/src/services/react-hmr-page-metadata-cache.d.ts +9 -0
  18. package/src/services/react-hmr-page-metadata-cache.js +18 -2
  19. package/src/services/react-hydration-asset.service.d.ts +7 -6
  20. package/src/services/react-hydration-asset.service.js +29 -17
  21. package/src/services/react-mdx-config-dependency.service.d.ts +36 -0
  22. package/src/services/react-mdx-config-dependency.service.js +122 -0
  23. package/src/services/react-page-module.service.d.ts +8 -2
  24. package/src/services/react-page-module.service.js +44 -37
  25. package/src/services/react-page-payload.service.d.ts +46 -0
  26. package/src/services/react-page-payload.service.js +67 -0
  27. package/src/services/react-runtime-bundle.service.d.ts +14 -12
  28. package/src/services/react-runtime-bundle.service.js +103 -180
  29. package/src/utils/client-graph-boundary-plugin.js +149 -11
  30. package/src/utils/component-config-traversal.d.ts +36 -0
  31. package/src/utils/component-config-traversal.js +54 -0
  32. package/src/utils/declared-modules.d.ts +1 -1
  33. package/src/utils/declared-modules.js +7 -16
  34. package/src/utils/dynamic.test.browser.d.ts +1 -0
  35. package/src/utils/dynamic.test.browser.js +33 -0
  36. package/src/utils/hydration-scripts.d.ts +19 -4
  37. package/src/utils/hydration-scripts.js +102 -39
  38. package/src/utils/hydration-scripts.test.browser.d.ts +1 -0
  39. package/src/utils/hydration-scripts.test.browser.js +126 -0
  40. package/src/utils/reachability-analyzer.d.ts +12 -1
  41. package/src/utils/reachability-analyzer.js +101 -5
  42. package/src/utils/react-dom-runtime-interop-plugin.d.ts +5 -0
  43. package/src/utils/react-dom-runtime-interop-plugin.js +29 -0
  44. package/src/utils/react-mdx-loader-plugin.js +13 -5
  45. package/src/utils/react-runtime-specifier-map.d.ts +6 -0
  46. package/src/utils/react-runtime-specifier-map.js +37 -0
  47. package/src/utils/use-sync-external-store-shim-plugin.d.ts +5 -0
  48. package/src/utils/use-sync-external-store-shim-plugin.js +41 -0
  49. package/src/react-hmr-strategy.ts +0 -444
  50. package/src/react-renderer.ts +0 -403
  51. package/src/react.plugin.ts +0 -241
  52. package/src/router-adapter.ts +0 -95
  53. package/src/services/react-bundle.service.ts +0 -212
  54. package/src/services/react-hmr-page-metadata-cache.ts +0 -24
  55. package/src/services/react-hydration-asset.service.ts +0 -260
  56. package/src/services/react-page-module.service.ts +0 -214
  57. package/src/services/react-runtime-bundle.service.ts +0 -271
  58. package/src/utils/client-graph-boundary-plugin.ts +0 -590
  59. package/src/utils/client-only.ts +0 -27
  60. package/src/utils/declared-modules.ts +0 -99
  61. package/src/utils/dynamic.ts +0 -27
  62. package/src/utils/hmr-scripts.ts +0 -47
  63. package/src/utils/html-boundary.ts +0 -66
  64. package/src/utils/hydration-scripts.ts +0 -338
  65. package/src/utils/reachability-analyzer.ts +0 -440
  66. package/src/utils/react-mdx-loader-plugin.ts +0 -40
@@ -1,15 +1,19 @@
1
- import { IntegrationRenderer } from "@ecopages/core/route-renderer/integration-renderer";
2
- import { LocalsAccessError } from "@ecopages/core/errors/locals-access-error";
1
+ import {
2
+ IntegrationRenderer
3
+ } from "@ecopages/core/route-renderer/integration-renderer";
3
4
  import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
- import { rapidhash } from "@ecopages/core/hash";
5
- import { createElement } from "react";
6
- import { renderToReadableStream, renderToString } from "react-dom/server";
7
- import { PLUGIN_NAME } from "./react.plugin.js";
5
+ import { getAppBuildExecutor } from "@ecopages/core/build/build-adapter";
6
+ import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from "@ecopages/core/router/navigation-coordinator";
7
+ import { createRequire } from "node:module";
8
+ import path from "node:path";
9
+ import { REACT_PLUGIN_NAME } from "./react.constants.js";
8
10
  import { hasSingleRootElement } from "./utils/html-boundary.js";
9
11
  import { ReactBundleService } from "./services/react-bundle.service.js";
10
12
  import { ReactHmrPageMetadataCache } from "./services/react-hmr-page-metadata-cache.js";
13
+ import { ReactMdxConfigDependencyService } from "./services/react-mdx-config-dependency.service.js";
11
14
  import { ReactPageModuleService } from "./services/react-page-module.service.js";
12
- import { ReactHydrationAssetService } from "./services/react-hydration-asset.service.js";
15
+ import { ReactPagePayloadService } from "./services/react-page-payload.service.js";
16
+ import { getReactIslandComponentKey, ReactHydrationAssetService } from "./services/react-hydration-asset.service.js";
13
17
  class ReactRenderError extends Error {
14
18
  constructor(message) {
15
19
  super(message);
@@ -17,103 +21,403 @@ class ReactRenderError extends Error {
17
21
  }
18
22
  }
19
23
  class BundleError extends Error {
24
+ logs;
20
25
  constructor(message, logs) {
21
26
  super(message);
22
- this.logs = logs;
23
27
  this.name = "BundleError";
28
+ this.logs = logs;
24
29
  }
25
30
  }
26
31
  class ReactRenderer extends IntegrationRenderer {
27
- name = PLUGIN_NAME;
32
+ name = REACT_PLUGIN_NAME;
28
33
  componentDirectory = RESOLVED_ASSETS_DIR;
29
- componentRenderSequence = 0;
30
- static routerAdapter;
31
- static mdxCompilerOptions;
32
- static mdxExtensions = [".mdx"];
33
- static hmrPageMetadataCache;
34
+ reactRuntimeModules;
35
+ routerAdapter;
36
+ mdxCompilerOptions;
37
+ mdxExtensions;
38
+ hmrPageMetadataCache;
34
39
  /**
35
40
  * Enables explicit graph behavior for React page-entry bundling.
36
41
  *
37
42
  * When true, page-entry bundles disable AST server-only stripping and rely
38
43
  * on explicit dependency declarations for browser graph composition.
39
44
  */
40
- static explicitGraphEnabled = false;
45
+ explicitGraphEnabled;
41
46
  /** @internal */
42
47
  bundleService;
43
48
  /** @internal */
44
49
  pageModuleService;
45
50
  /** @internal */
46
51
  hydrationAssetService;
52
+ /** @internal */
53
+ pagePayloadService;
54
+ /** @internal */
55
+ mdxConfigDependencyService;
47
56
  constructor(options) {
48
- super(options);
57
+ const { reactConfig, ...rendererOptions } = options;
58
+ super(rendererOptions);
59
+ this.routerAdapter = reactConfig?.routerAdapter;
60
+ this.mdxCompilerOptions = reactConfig?.mdxCompilerOptions;
61
+ this.mdxExtensions = reactConfig?.mdxExtensions ?? [".mdx"];
62
+ this.hmrPageMetadataCache = reactConfig?.hmrPageMetadataCache;
63
+ this.explicitGraphEnabled = reactConfig?.explicitGraphEnabled ?? false;
49
64
  this.bundleService = new ReactBundleService({
50
65
  rootDir: this.appConfig.rootDir,
51
- routerAdapter: ReactRenderer.routerAdapter,
52
- mdxCompilerOptions: ReactRenderer.mdxCompilerOptions
66
+ routerAdapter: this.routerAdapter,
67
+ mdxCompilerOptions: this.mdxCompilerOptions,
68
+ jsxImportSource: (this.appConfig.integrations ?? []).find((integration) => integration.name === this.name)?.jsxImportSource,
69
+ nonReactExtensions: (this.appConfig.integrations ?? []).filter((integration) => integration.name !== this.name).flatMap((integration) => integration.extensions)
53
70
  });
54
71
  this.pageModuleService = new ReactPageModuleService({
55
72
  rootDir: this.appConfig.rootDir,
56
73
  distDir: this.appConfig.absolutePaths.distDir,
74
+ workDir: this.appConfig.absolutePaths.workDir,
75
+ buildExecutor: getAppBuildExecutor(this.appConfig),
57
76
  layoutsDir: this.appConfig.absolutePaths.layoutsDir,
58
77
  componentsDir: this.appConfig.absolutePaths.componentsDir,
59
- mdxCompilerOptions: ReactRenderer.mdxCompilerOptions,
60
- mdxExtensions: ReactRenderer.mdxExtensions,
78
+ mdxCompilerOptions: this.mdxCompilerOptions,
79
+ mdxExtensions: this.mdxExtensions,
61
80
  integrationName: this.name,
62
- hasRouterAdapter: Boolean(ReactRenderer.routerAdapter)
81
+ hasRouterAdapter: Boolean(this.routerAdapter)
63
82
  });
64
83
  this.hydrationAssetService = new ReactHydrationAssetService({
65
84
  srcDir: this.appConfig.srcDir,
66
- routerAdapter: ReactRenderer.routerAdapter,
85
+ routerAdapter: this.routerAdapter,
67
86
  assetProcessingService: this.assetProcessingService,
68
87
  bundleService: this.bundleService,
69
- hmrPageMetadataCache: ReactRenderer.hmrPageMetadataCache
88
+ hmrPageMetadataCache: this.hmrPageMetadataCache
89
+ });
90
+ this.pagePayloadService = new ReactPagePayloadService();
91
+ this.mdxConfigDependencyService = new ReactMdxConfigDependencyService({
92
+ integrationName: this.name,
93
+ pageModuleService: this.pageModuleService,
94
+ assetProcessingService: this.assetProcessingService
70
95
  });
71
96
  }
72
97
  shouldRenderPageComponent() {
73
98
  return false;
74
99
  }
75
100
  /**
76
- * Renders a React component for component-level orchestration.
101
+ * Reads the declared integration name for a component or layout.
77
102
  *
78
- * Behavior:
79
- * - SSR always returns the component's own root HTML (no synthetic wrapper).
80
- * - For single-root output, a stable `data-eco-component-id` attribute is attached
81
- * to the root element so the client island runtime can target it directly.
82
- * - Island client scripts are emitted through `assets` and mounted independently.
103
+ * We honor both the explicit `config.integration` override and injected
104
+ * `config.__eco.integration` metadata because pages can arrive here through
105
+ * authored config as well as build-time component metadata.
106
+ */
107
+ getComponentIntegration(component) {
108
+ return component?.config?.integration ?? component?.config?.__eco?.integration;
109
+ }
110
+ /**
111
+ * Returns whether a component should stay inside the React render lane.
83
112
  *
84
- * This preserves DOM shape for global CSS/layout selectors while keeping a
85
- * deterministic mount target per component instance.
113
+ * Components without explicit integration metadata are treated as React-owned
114
+ * here because this renderer only receives them after the route pipeline has
115
+ * already selected the React integration.
86
116
  */
87
- async renderComponent(input) {
88
- const Component = input.component;
117
+ isReactManagedComponent(component) {
118
+ const integration = this.getComponentIntegration(component);
119
+ return integration === void 0 || integration === this.name;
120
+ }
121
+ getRouterDocumentAttributes() {
122
+ if (!this.routerAdapter) {
123
+ return void 0;
124
+ }
125
+ return {
126
+ [ECO_DOCUMENT_OWNER_ATTRIBUTE]: "react-router"
127
+ };
128
+ }
129
+ /**
130
+ * Commits a framework-agnostic component to React semantics.
131
+ *
132
+ * This is one of the two real cast boundaries in this file. Core keeps
133
+ * `EcoComponent` broad so integrations can share the same public surface; once
134
+ * the React renderer is executing, `createElement()` needs a concrete React
135
+ * component signature.
136
+ */
137
+ asReactComponent(component) {
138
+ return component;
139
+ }
140
+ /**
141
+ * Commits a mixed-shell component to the string-returning contract required by
142
+ * non-React layouts and HTML templates.
143
+ *
144
+ * This is the second real cast boundary: once we decide a shell is not managed
145
+ * by React, we call it directly and require serialized HTML back.
146
+ */
147
+ asNonReactShellComponent(component) {
148
+ return component;
149
+ }
150
+ resolveReactRuntimeModules() {
151
+ const appPackageJsonPath = path.resolve(this.appConfig.rootDir || process.cwd(), "package.json");
152
+ try {
153
+ const requireFromApp = createRequire(appPackageJsonPath);
154
+ return {
155
+ react: requireFromApp("react"),
156
+ reactDomServer: requireFromApp("react-dom/server")
157
+ };
158
+ } catch {
159
+ const requireFromIntegration = createRequire(import.meta.url);
160
+ return {
161
+ react: requireFromIntegration("react"),
162
+ reactDomServer: requireFromIntegration("react-dom/server")
163
+ };
164
+ }
165
+ }
166
+ getReactRuntimeModules() {
167
+ this.reactRuntimeModules ??= this.resolveReactRuntimeModules();
168
+ return this.reactRuntimeModules;
169
+ }
170
+ /**
171
+ * Appends route hydration assets for a concrete page/view file to the current
172
+ * HTML transformer state.
173
+ */
174
+ async appendHydrationAssetsForFile(filePath) {
175
+ if (!filePath) {
176
+ return;
177
+ }
178
+ const hydrationAssets = await this.buildRouteRenderAssets(filePath);
179
+ this.appendProcessedDependencies(hydrationAssets);
180
+ }
181
+ /**
182
+ * Renders a non-React layout or HTML template and enforces that mixed shells
183
+ * return serialized HTML.
184
+ *
185
+ * The React renderer can compose through another integration's shell, but only
186
+ * if that shell yields a string that can be inserted into the final document.
187
+ */
188
+ async renderNonReactShellComponent(Component, props, label) {
189
+ const output = await Component(props);
190
+ if (typeof output === "string") {
191
+ return output;
192
+ }
193
+ throw new ReactRenderError(`${label} must return a string when used as a mixed shell for React pages.`);
194
+ }
195
+ /**
196
+ * Renders one React component boundary while preserving already-resolved child HTML.
197
+ *
198
+ * When nested boundary resolution has already produced child HTML for this
199
+ * boundary, the child payload must remain raw SSR output rather than a React
200
+ * string child, otherwise React would escape it. This helper renders a unique
201
+ * token through React and swaps that token back to the resolved HTML
202
+ * afterward.
203
+ *
204
+ * @param input Component render input for the current boundary.
205
+ * @param context React-specific render context for stable token generation.
206
+ * @returns Serialized component HTML with resolved child markup preserved.
207
+ */
208
+ renderComponentHtml(input, context, runtimeContext) {
209
+ const { react, reactDomServer } = this.getReactRuntimeModules();
210
+ if (input.children === void 0) {
211
+ return this.normalizeBoundaryArtifactHtml(
212
+ reactDomServer.renderToString(react.createElement(this.asReactComponent(input.component), input.props))
213
+ );
214
+ }
215
+ const resolvedChildHtml = typeof input.children === "string" ? input.children : String(input.children ?? "");
216
+ const rawChildrenToken = `__ECO_RAW_HTML_CHILD_${context.componentInstanceId ?? "component"}__`;
217
+ if (runtimeContext) {
218
+ runtimeContext.rawChildrenToken = rawChildrenToken;
219
+ runtimeContext.rawChildrenHtml = resolvedChildHtml;
220
+ }
221
+ const html = reactDomServer.renderToString(
222
+ react.createElement(this.asReactComponent(input.component), input.props, rawChildrenToken)
223
+ );
224
+ return this.normalizeBoundaryArtifactHtml(html.split(rawChildrenToken).join(resolvedChildHtml));
225
+ }
226
+ /**
227
+ * Restores raw child HTML that was temporarily replaced by a token during React SSR.
228
+ *
229
+ * Queued boundary resolution may render children through a fragment path before all
230
+ * nested integration tokens are resolved. When that happens, React must never see
231
+ * the resolved child HTML as a normal string child or it would escape it. The
232
+ * runtime context stores the placeholder token and the raw child HTML so the
233
+ * fragment render path can reinsert it before foreign boundary tokens are handled.
234
+ */
235
+ restoreRuntimeChildHtml(html, runtimeContext) {
236
+ if (!runtimeContext?.rawChildrenToken || runtimeContext.rawChildrenHtml === void 0) {
237
+ return html;
238
+ }
239
+ return html.split(runtimeContext.rawChildrenToken).join(runtimeContext.rawChildrenHtml);
240
+ }
241
+ /**
242
+ * Renders queued child content through React and then resolves nested boundary tokens.
243
+ *
244
+ * This path is only used for children that were deferred while React rendered the
245
+ * parent boundary. It first restores any raw child HTML placeholders owned by the
246
+ * current runtime context, then asks the shared queued-boundary resolver to swap
247
+ * foreign integration tokens with their resolved HTML.
248
+ */
249
+ async renderQueuedChildrenToHtml(children, runtimeContext, queuedResolutionsByToken, resolveToken) {
250
+ if (children === void 0) {
251
+ return void 0;
252
+ }
253
+ const { react, reactDomServer } = this.getReactRuntimeModules();
254
+ let html = this.normalizeBoundaryArtifactHtml(
255
+ reactDomServer.renderToString(react.createElement(react.Fragment, null, children))
256
+ );
257
+ html = this.restoreRuntimeChildHtml(html, runtimeContext);
258
+ html = await this.resolveQueuedBoundaryTokens(html, queuedResolutionsByToken, resolveToken);
259
+ return html;
260
+ }
261
+ /**
262
+ * Resolves queued renderer-owned boundary tokens produced during React component rendering.
263
+ *
264
+ * React components can enqueue nested boundaries while the parent HTML is being
265
+ * rendered. This delegates to the shared renderer-owned queue resolver but keeps
266
+ * the React-specific child rendering behavior local so raw child HTML and React's
267
+ * fragment rendering semantics stay coordinated.
268
+ */
269
+ async resolveQueuedBoundaryHtml(html, runtimeContext) {
270
+ return this.resolveRendererOwnedQueuedBoundaryHtml({
271
+ html,
272
+ runtimeContext,
273
+ queueLabel: "React",
274
+ renderQueuedChildren: async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => {
275
+ const renderedHtml = await this.renderQueuedChildrenToHtml(
276
+ children,
277
+ currentRuntimeContext,
278
+ queuedResolutionsByToken,
279
+ resolveToken
280
+ );
281
+ return {
282
+ assets: [],
283
+ html: renderedHtml
284
+ };
285
+ }
286
+ });
287
+ }
288
+ buildHydrationProps(props) {
289
+ if (!props || !Object.prototype.hasOwnProperty.call(props, "locals")) {
290
+ return props ?? {};
291
+ }
292
+ const { locals: _locals, ...hydrationProps } = props;
293
+ return hydrationProps;
294
+ }
295
+ /**
296
+ * Builds the extra document props needed when React renders through a non-React HTML shell.
297
+ *
298
+ * Router-backed React pages still need to publish the canonical page-data script
299
+ * even when the outer document shell belongs to another integration.
300
+ */
301
+ buildNonReactDocumentProps(htmlTemplate, pageProps) {
302
+ if (this.isReactManagedComponent(htmlTemplate) || !this.routerAdapter) {
303
+ return void 0;
304
+ }
305
+ return {
306
+ headContent: this.pagePayloadService.buildRouterPageDataScript(pageProps)
307
+ };
308
+ }
309
+ /**
310
+ * Renders a foreign integration component boundary that participates in React composition.
311
+ *
312
+ * Non-React components must resolve to serialized HTML so React can embed them as
313
+ * mixed-shell boundaries. Any component-owned dependencies still need to flow
314
+ * through the shared dependency resolver before queued boundary tokens are finalized.
315
+ */
316
+ async renderForeignComponentBoundary(input, runtimeContext) {
317
+ let props = input.props;
318
+ if (input.children !== void 0) {
319
+ props = {
320
+ ...input.props,
321
+ children: typeof input.children === "string" ? input.children : String(input.children ?? "")
322
+ };
323
+ }
324
+ const html = await this.renderNonReactShellComponent(
325
+ this.asNonReactShellComponent(input.component),
326
+ props,
327
+ "Component"
328
+ );
329
+ const hasDependencies = Boolean(input.component.config?.dependencies);
330
+ const canResolveAssets = typeof this.assetProcessingService?.processDependencies === "function";
331
+ const assets = hasDependencies && canResolveAssets ? await this.processComponentDependencies([input.component]) : void 0;
332
+ const queuedBoundaryResolution = await this.resolveQueuedBoundaryHtml(html, runtimeContext);
333
+ const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
334
+ ...assets ?? [],
335
+ ...queuedBoundaryResolution.assets
336
+ ]);
337
+ return {
338
+ html: queuedBoundaryResolution.html,
339
+ canAttachAttributes: true,
340
+ rootTag: this.getRootTagName(queuedBoundaryResolution.html),
341
+ integrationName: this.name,
342
+ assets: mergedAssets.length > 0 ? mergedAssets : void 0
343
+ };
344
+ }
345
+ /**
346
+ * Renders a React-owned component boundary and attaches island hydration metadata when possible.
347
+ *
348
+ * This path keeps React-owned SSR, queued boundary resolution, and optional
349
+ * island hydration wiring together so the public `renderComponent()` method can
350
+ * read as orchestration rather than implementation detail.
351
+ */
352
+ async renderReactComponentBoundary(input, runtimeContext) {
89
353
  const componentConfig = input.component.config;
90
- const element = input.children === void 0 ? createElement(Component, input.props) : createElement(Component, input.props, input.children);
91
- let html = renderToString(element);
92
- let canAttachAttributes = hasSingleRootElement(html);
93
- let rootTag = this.getRootTagName(html);
94
- const componentFile = componentConfig?.__eco?.file;
95
354
  const context = input.integrationContext ?? {};
355
+ const hasResolvedChildHtml = input.children !== void 0;
356
+ let html = this.renderComponentHtml(input, context, runtimeContext);
357
+ const queuedBoundaryResolution = await this.resolveQueuedBoundaryHtml(html, runtimeContext);
358
+ html = queuedBoundaryResolution.html;
359
+ const canAttachAttributes = hasSingleRootElement(html);
360
+ const rootTag = this.getRootTagName(html);
361
+ const componentFile = componentConfig?.__eco?.file;
96
362
  let rootAttributes;
97
363
  let assets;
98
- if (canAttachAttributes && componentFile && this.assetProcessingService) {
99
- const componentInstanceId = context.componentInstanceId ?? `eco-component-${rapidhash(componentFile)}-${++this.componentRenderSequence}`;
100
- assets = await this.hydrationAssetService.buildComponentRenderAssets(
101
- componentFile,
102
- componentInstanceId,
103
- input.props,
104
- componentConfig
105
- );
106
- rootAttributes = { "data-eco-component-id": componentInstanceId };
364
+ if (canAttachAttributes && componentFile && context.componentInstanceId && this.assetProcessingService && !hasResolvedChildHtml) {
365
+ const componentInstanceId = context.componentInstanceId;
366
+ assets = await this.hydrationAssetService.buildComponentRenderAssets(componentFile, componentConfig);
367
+ rootAttributes = {
368
+ "data-eco-component-id": componentInstanceId,
369
+ "data-eco-component-key": getReactIslandComponentKey(componentFile, componentConfig),
370
+ "data-eco-props": btoa(JSON.stringify(this.buildHydrationProps(input.props)))
371
+ };
107
372
  }
373
+ const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
374
+ ...assets ?? [],
375
+ ...queuedBoundaryResolution.assets
376
+ ]);
108
377
  return {
109
378
  html,
110
379
  canAttachAttributes,
111
380
  rootTag,
112
381
  integrationName: this.name,
113
382
  rootAttributes,
114
- assets
383
+ assets: mergedAssets.length > 0 ? mergedAssets : void 0
115
384
  };
116
385
  }
386
+ /**
387
+ * Renders a React component for component-level orchestration.
388
+ *
389
+ * Behavior:
390
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
391
+ * - When an explicit component instance id is provided, a stable
392
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
393
+ * - Without an explicit instance id, component renders remain plain SSR output.
394
+ * - When resolved child HTML is provided, that boundary is treated as a pure SSR
395
+ * composition step and does not emit hydration assets for the parent wrapper.
396
+ *
397
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
398
+ * deterministic mount target per component instance.
399
+ */
400
+ async renderComponent(input) {
401
+ const runtimeContext = this.getQueuedBoundaryRuntime(input);
402
+ if (!this.isReactManagedComponent(input.component)) {
403
+ return this.renderForeignComponentBoundary(input, runtimeContext);
404
+ }
405
+ return this.renderReactComponentBoundary(input, runtimeContext);
406
+ }
407
+ createComponentBoundaryRuntime(options) {
408
+ return this.createQueuedBoundaryRuntime({
409
+ boundaryInput: options.boundaryInput,
410
+ rendererCache: options.rendererCache,
411
+ createRuntimeContext: (integrationContext, rendererCache) => ({
412
+ rendererCache,
413
+ componentInstanceScope: integrationContext.componentInstanceId,
414
+ nextBoundaryId: 0,
415
+ queuedResolutions: [],
416
+ rawChildrenToken: void 0,
417
+ rawChildrenHtml: void 0
418
+ })
419
+ });
420
+ }
117
421
  /**
118
422
  * Checks if the given file path corresponds to an MDX file based on configured extensions.
119
423
  * @param filePath - The file path to check
@@ -122,32 +426,29 @@ class ReactRenderer extends IntegrationRenderer {
122
426
  isMdxFile(filePath) {
123
427
  return this.pageModuleService.isMdxFile(filePath);
124
428
  }
125
- /**
126
- * Processes MDX-specific configuration dependencies including layout dependencies.
127
- * @param pagePath - Absolute path to the MDX page file
128
- * @returns Processed assets for MDX configuration dependencies
129
- */
130
- async processMdxConfigDependencies(pagePath) {
131
- const { config } = await this.importPageFile(pagePath);
132
- const resolvedLayout = config?.layout;
133
- const components = [];
134
- if (resolvedLayout?.config?.dependencies) {
135
- const layoutConfig = this.pageModuleService.ensureConfigFileMetadata(resolvedLayout.config, pagePath);
136
- components.push({ config: layoutConfig });
137
- }
138
- if (config?.dependencies) {
139
- const configWithMeta = {
140
- ...config,
141
- __eco: { id: rapidhash(pagePath).toString(36), file: pagePath, integration: "react" }
142
- };
143
- components.push({ config: configWithMeta });
429
+ usesIntegrationPageImporter(file) {
430
+ return this.pageModuleService.isMdxFile(file);
431
+ }
432
+ async importIntegrationPageFile(file, options) {
433
+ return await this.pageModuleService.importMdxPageFile(file, options);
434
+ }
435
+ normalizeImportedPageFile(file, pageModule) {
436
+ const reactModule = pageModule;
437
+ const { default: Page, getMetadata, config } = reactModule;
438
+ if (this.pageModuleService.isMdxFile(file) && config) {
439
+ Page.config = config;
144
440
  }
145
- return this.processComponentDependencies(components);
441
+ return {
442
+ ...pageModule,
443
+ default: Page,
444
+ getMetadata,
445
+ config
446
+ };
146
447
  }
147
448
  async buildRouteRenderAssets(pagePath) {
148
449
  try {
149
450
  const pageModule = await this.importPageFile(pagePath);
150
- const shouldHydrate = ReactRenderer.explicitGraphEnabled ? true : this.pageModuleService.shouldHydratePage(pageModule);
451
+ const shouldHydrate = this.explicitGraphEnabled ? true : this.pageModuleService.shouldHydratePage(pageModule);
151
452
  if (!shouldHydrate) {
152
453
  return [];
153
454
  }
@@ -159,7 +460,11 @@ class ReactRenderer extends IntegrationRenderer {
159
460
  declaredModules
160
461
  );
161
462
  if (isMdx) {
162
- const mdxConfigAssets = await this.processMdxConfigDependencies(pagePath);
463
+ const mdxConfigAssets = await this.mdxConfigDependencyService.processMdxConfigDependencies({
464
+ pagePath,
465
+ config: pageModule.config,
466
+ processComponentDependencies: async (components) => await this.processComponentDependencies(components)
467
+ });
163
468
  return [...processedAssets, ...mdxConfigAssets];
164
469
  }
165
470
  return processedAssets;
@@ -172,18 +477,14 @@ class ReactRenderer extends IntegrationRenderer {
172
477
  );
173
478
  }
174
479
  }
175
- async importPageFile(file) {
176
- const module = this.pageModuleService.isMdxFile(file) ? await this.pageModuleService.importMdxPageFile(file) : await super.importPageFile(file);
177
- const { default: Page, getMetadata, config } = module;
178
- if (this.pageModuleService.isMdxFile(file) && config) {
179
- Page.config = config;
180
- }
181
- return {
182
- default: Page,
183
- getMetadata,
184
- config
185
- };
186
- }
480
+ /**
481
+ * Renders a full route response for the filesystem page pipeline.
482
+ *
483
+ * This path receives already-resolved route metadata, layout, locals, and HTML
484
+ * template instances from the shared renderer orchestration. Its main job is to
485
+ * serialize only the browser-safe page payload, compose the mixed React/non-
486
+ * React shell tree, and hand the result back as a document body.
487
+ */
187
488
  async render({
188
489
  params,
189
490
  query,
@@ -197,99 +498,91 @@ class ReactRenderer extends IntegrationRenderer {
197
498
  pageProps
198
499
  }) {
199
500
  try {
200
- const pageElement = createElement(Page, { params, query, ...props, locals: pageLocals });
201
- const contentElement = Layout ? createElement(Layout, { locals }, pageElement) : pageElement;
202
- const safeLocals = this.getSerializableLocals(locals);
203
- const allPageProps = {
204
- ...pageProps,
501
+ const safeLocals = this.pagePayloadService.getSerializableLocals(
502
+ locals,
503
+ Page.requires
504
+ );
505
+ const allPageProps = this.pagePayloadService.buildSerializedPageProps({
506
+ pageProps,
205
507
  params,
206
508
  query,
207
- ...safeLocals && { locals: safeLocals }
208
- };
209
- return await renderToReadableStream(
210
- createElement(
211
- HtmlTemplate,
212
- {
213
- metadata,
214
- pageProps: allPageProps
215
- },
216
- contentElement
217
- )
218
- );
509
+ safeLocals
510
+ });
511
+ return await this.renderPageWithDocumentShell({
512
+ page: {
513
+ component: Page,
514
+ props: { params, query, ...props, locals: pageLocals }
515
+ },
516
+ layout: Layout ? {
517
+ component: Layout,
518
+ props: locals ? { locals } : {}
519
+ } : void 0,
520
+ htmlTemplate: HtmlTemplate,
521
+ metadata,
522
+ pageProps: allPageProps,
523
+ documentProps: this.buildNonReactDocumentProps(HtmlTemplate, allPageProps)
524
+ });
219
525
  } catch (error) {
220
526
  throw this.createRenderError("Failed to render component", error);
221
527
  }
222
528
  }
529
+ getDocumentAttributes() {
530
+ return this.getRouterDocumentAttributes();
531
+ }
223
532
  /**
224
- * Safely extracts locals for client-side hydration.
225
- *
226
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
227
- * request-scoped data (e.g., session). This data needs to be serialized to the
228
- * client for hydration to match the server-rendered output.
229
- *
230
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
231
- * to prevent accidental use. This method safely detects that case and returns
232
- * `undefined` instead of throwing.
533
+ * Renders an arbitrary React view through the application's HTML shell.
233
534
  *
234
- * @param locals - The locals object from the render context
235
- * @returns The locals object if serializable, undefined otherwise
535
+ * Unlike route rendering, this path starts from a single component rather than a
536
+ * page module discovered by the router. It still needs to resolve metadata,
537
+ * layout dependencies, and hydration assets so direct `ctx.render()` calls match
538
+ * normal page responses.
236
539
  */
237
- getSerializableLocals(locals) {
238
- try {
239
- if (locals && Object.keys(locals).length > 0) {
240
- return locals;
241
- }
242
- return void 0;
243
- } catch (e) {
244
- if (e instanceof LocalsAccessError) {
245
- return void 0;
246
- }
247
- throw e;
248
- }
249
- }
250
540
  async renderToResponse(view, props, ctx) {
251
541
  try {
542
+ const { react, reactDomServer } = this.getReactRuntimeModules();
252
543
  const viewConfig = view.config;
253
544
  const Layout = viewConfig?.layout;
254
- const ViewComponent = view;
255
- const pageElement = createElement(ViewComponent, props || {});
545
+ const ViewComponent = this.asReactComponent(view);
546
+ const normalizedProps = props ?? {};
256
547
  if (ctx.partial) {
257
- const stream = await renderToReadableStream(pageElement);
258
- return this.createHtmlResponse(stream, ctx);
548
+ return this.renderPartialViewResponse({
549
+ view,
550
+ props,
551
+ ctx,
552
+ renderInline: async () => await reactDomServer.renderToReadableStream(
553
+ react.createElement(ViewComponent, normalizedProps)
554
+ )
555
+ });
259
556
  }
260
- const contentElement = Layout ? createElement(Layout, {}, pageElement) : pageElement;
261
557
  const HtmlTemplate = await this.getHtmlTemplate();
262
- const metadata = view.metadata ? await view.metadata({
263
- params: {},
264
- query: {},
265
- props,
266
- appConfig: this.appConfig
267
- }) : this.appConfig.defaultMetadata;
558
+ const metadata = await this.resolveViewMetadata(view, props);
268
559
  await this.prepareViewDependencies(view, Layout);
269
- const viewFilePath = viewConfig?.__eco?.file;
270
- if (viewFilePath) {
271
- const hydrationAssets = await this.buildRouteRenderAssets(viewFilePath);
272
- this.htmlTransformer.setProcessedDependencies([
273
- ...this.htmlTransformer.getProcessedDependencies(),
274
- ...hydrationAssets
275
- ]);
276
- }
277
- const streamBody = await renderToReadableStream(
278
- createElement(
279
- HtmlTemplate,
280
- {
281
- metadata,
282
- pageProps: props
283
- },
284
- contentElement
285
- )
286
- );
287
- const transformedResponse = await this.htmlTransformer.transform(
288
- new Response(streamBody, {
289
- headers: { "Content-Type": "text/html" }
290
- })
291
- );
292
- return this.createHtmlResponse(transformedResponse.body ?? "", ctx);
560
+ await this.appendHydrationAssetsForFile(viewConfig?.__eco?.file);
561
+ const viewRender = await this.renderComponentBoundary({
562
+ component: view,
563
+ props: normalizedProps
564
+ });
565
+ const layoutRender = Layout ? await this.renderComponentBoundary({
566
+ component: Layout,
567
+ props: {},
568
+ children: viewRender.html
569
+ }) : void 0;
570
+ const documentRender = await this.renderComponentBoundary({
571
+ component: HtmlTemplate,
572
+ props: {
573
+ metadata,
574
+ pageProps: normalizedProps,
575
+ ...this.buildNonReactDocumentProps(HtmlTemplate, normalizedProps) ?? {}
576
+ },
577
+ children: layoutRender?.html ?? viewRender.html
578
+ });
579
+ this.appendProcessedDependencies(viewRender.assets, layoutRender?.assets, documentRender.assets);
580
+ const transformedHtml = await this.finalizeResolvedHtml({
581
+ html: `${this.DOC_TYPE}${documentRender.html}`,
582
+ partial: false,
583
+ documentAttributes: this.getRouterDocumentAttributes()
584
+ });
585
+ return this.createHtmlResponse(transformedHtml, ctx);
293
586
  } catch (error) {
294
587
  throw this.createRenderError("Failed to render view", error);
295
588
  }