@ecopages/react 0.2.0-beta.9 → 0.2.0-rc.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 (142) hide show
  1. package/README.md +179 -7
  2. package/package.json +53 -28
  3. package/src/app/client-only.js +15 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +31 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +23 -8
  9. package/src/bundling/bundle.js +120 -0
  10. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  11. package/src/bundling/discover-layout-runtime-modules.js +185 -0
  12. package/src/bundling/runtime-alias-map.d.ts +13 -0
  13. package/src/bundling/runtime-alias-map.js +113 -0
  14. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +25 -4
  15. package/src/bundling/runtime-bundle.js +258 -0
  16. package/src/bundling/runtime-interop-plugin.js +34 -0
  17. package/src/bundling/runtime-mode.d.ts +9 -0
  18. package/src/bundling/runtime-mode.js +11 -0
  19. package/src/bundling/runtime-modules.d.ts +29 -0
  20. package/src/bundling/runtime-modules.js +49 -0
  21. package/src/client-graph/ast-transform.d.ts +18 -0
  22. package/src/client-graph/ast-transform.js +426 -0
  23. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +23 -13
  24. package/src/client-graph/boundary-cache.js +182 -0
  25. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  26. package/src/client-graph/boundary-plugin.js +149 -0
  27. package/src/client-graph/component-config-traversal.js +77 -0
  28. package/src/client-graph/declared-modules.js +69 -0
  29. package/src/client-graph/module-classification.d.ts +3 -0
  30. package/src/client-graph/module-classification.js +43 -0
  31. package/src/{utils → client-graph}/reachability-analyzer.d.ts +4 -12
  32. package/src/client-graph/reachability-analyzer.js +515 -0
  33. package/src/client-graph/specifier-classification.d.ts +75 -0
  34. package/src/client-graph/specifier-classification.js +214 -0
  35. package/src/contracts/router-adapter.js +6 -0
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  37. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  38. package/src/hmr/hmr-scripts.js +44 -0
  39. package/src/hmr/hmr-strategy.d.ts +74 -0
  40. package/src/hmr/hmr-strategy.js +351 -0
  41. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  42. package/src/hmr/page-metadata-cache.js +44 -0
  43. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  44. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  45. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  46. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  47. package/src/hydration/bootstrap-imports.d.ts +25 -0
  48. package/src/hydration/bootstrap-imports.js +33 -0
  49. package/src/hydration/hydration-asset.d.ts +84 -0
  50. package/src/hydration/hydration-asset.js +227 -0
  51. package/src/hydration/hydration-scripts.d.ts +104 -0
  52. package/src/hydration/hydration-scripts.js +483 -0
  53. package/src/hydration/hydration-scripts.test.browser.js +199 -0
  54. package/src/hydration/page-data-manifest.d.ts +58 -0
  55. package/src/hydration/page-data-manifest.js +97 -0
  56. package/src/hydration/page-data-reader.d.ts +31 -0
  57. package/src/hydration/page-data-reader.js +77 -0
  58. package/src/hydration/page-payload.d.ts +67 -0
  59. package/src/hydration/page-payload.js +106 -0
  60. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  61. package/src/hydration/serialize-page-data-script.js +30 -0
  62. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +6 -6
  63. package/src/mdx/mdx-config-dependency.js +110 -0
  64. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  65. package/src/mdx/mdx-loader-plugin.js +8 -0
  66. package/src/page/page-module.d.ts +46 -0
  67. package/src/page/page-module.js +74 -0
  68. package/src/plugin/react.constants.js +1 -0
  69. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +9 -3
  70. package/src/plugin/react.plugin.js +241 -0
  71. package/src/plugin/react.types.d.ts +156 -0
  72. package/src/plugin/react.types.js +1 -0
  73. package/src/render/component-ownership.d.ts +49 -0
  74. package/src/render/component-ownership.js +46 -0
  75. package/src/render/component-ssr.d.ts +113 -0
  76. package/src/render/component-ssr.js +180 -0
  77. package/src/render/eco-embed.js +9 -0
  78. package/src/render/errors.d.ts +16 -0
  79. package/src/render/errors.js +23 -0
  80. package/src/render/html-boundary.js +59 -0
  81. package/src/render/layout-compose.d.ts +66 -0
  82. package/src/render/layout-compose.js +134 -0
  83. package/src/render/react-renderer.d.ts +139 -0
  84. package/src/render/react-renderer.js +450 -0
  85. package/src/render/react-runtime.d.ts +13 -0
  86. package/src/render/react-runtime.js +26 -0
  87. package/src/render/unified-layout-composition.d.ts +53 -0
  88. package/src/render/unified-layout-composition.js +78 -0
  89. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  90. package/src/eco-embed.js +0 -11
  91. package/src/react-hmr-strategy.d.ts +0 -230
  92. package/src/react-hmr-strategy.js +0 -657
  93. package/src/react-renderer.d.ts +0 -233
  94. package/src/react-renderer.js +0 -622
  95. package/src/react.constants.js +0 -4
  96. package/src/react.plugin.js +0 -209
  97. package/src/react.types.d.ts +0 -88
  98. package/src/react.types.js +0 -0
  99. package/src/router-adapter.js +0 -0
  100. package/src/services/pages-index.d.ts +0 -64
  101. package/src/services/pages-index.js +0 -73
  102. package/src/services/react-bundle.service.js +0 -86
  103. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  104. package/src/services/react-hydration-asset.service.d.ts +0 -84
  105. package/src/services/react-hydration-asset.service.js +0 -217
  106. package/src/services/react-mdx-config-dependency.service.js +0 -122
  107. package/src/services/react-page-module.service.d.ts +0 -88
  108. package/src/services/react-page-module.service.js +0 -166
  109. package/src/services/react-page-payload.service.d.ts +0 -46
  110. package/src/services/react-page-payload.service.js +0 -67
  111. package/src/services/react-runtime-bundle.service.js +0 -192
  112. package/src/utils/client-graph-boundary-cache.js +0 -116
  113. package/src/utils/client-graph-boundary-plugin.js +0 -552
  114. package/src/utils/client-only.js +0 -19
  115. package/src/utils/component-config-traversal.js +0 -54
  116. package/src/utils/declared-modules.js +0 -47
  117. package/src/utils/dynamic.js +0 -12
  118. package/src/utils/dynamic.test.browser.js +0 -33
  119. package/src/utils/hmr-scripts.js +0 -31
  120. package/src/utils/html-boundary.js +0 -55
  121. package/src/utils/hydration-scripts.d.ts +0 -92
  122. package/src/utils/hydration-scripts.js +0 -358
  123. package/src/utils/hydration-scripts.test.browser.js +0 -198
  124. package/src/utils/reachability-analyzer.js +0 -339
  125. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  126. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  127. package/src/utils/react-mdx-loader-plugin.js +0 -45
  128. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  129. package/src/utils/react-runtime-alias-map.js +0 -90
  130. /package/src/{utils → app}/client-only.d.ts +0 -0
  131. /package/src/{utils → app}/dynamic.d.ts +0 -0
  132. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  133. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  134. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  135. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  136. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  137. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  138. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  139. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  140. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  141. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  142. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,139 @@
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 type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, PageMetadataProps, RouteRendererBody } from '@ecopages/core';
12
+ import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext } from '@ecopages/core/route-renderer/orchestration/integration-renderer';
13
+ import type { AssetDefinition, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
14
+ import type { ReactNode } from 'react';
15
+ import type { ReactRendererConfig } from '../plugin/react.types.js';
16
+ import { BundleService } from '../bundling/bundle.js';
17
+ import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
18
+ import { PageModuleService } from '../page/page-module.js';
19
+ import { PagePayloadService } from '../hydration/page-payload.js';
20
+ import { HydrationAssetService } from '../hydration/hydration-asset.js';
21
+ import { type DocumentShellLayoutInput } from '@ecopages/core/route-renderer/orchestration/document-shell/document-shell-render.service';
22
+ import type { ForeignChildRuntime } from '@ecopages/core/route-renderer/orchestration/foreign-child/component-render-context';
23
+ import { type ReactRuntimeModules } from './react-runtime.js';
24
+ export type { ReactRendererConfig } from '../plugin/react.types.js';
25
+ export { BundleError, ReactRenderError } from './errors.js';
26
+ export type ReactRendererOptions = ConstructorParameters<typeof IntegrationRenderer>[0] & {
27
+ reactConfig?: ReactRendererConfig;
28
+ };
29
+ /**
30
+ * Renderer for React components.
31
+ * @extends IntegrationRenderer
32
+ */
33
+ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
34
+ name: string;
35
+ componentDirectory: string;
36
+ private reactRuntimeModules?;
37
+ private readonly routerAdapter?;
38
+ private readonly mdxCompilerOptions?;
39
+ private readonly mdxExtensions;
40
+ private readonly hmrPageMetadataCache?;
41
+ /**
42
+ * When true, always emit page browser graph / hydration assets for React pages.
43
+ *
44
+ * Mapped from the public `explicitGraph` plugin option. Does not disable the
45
+ * client-graph AST boundary.
46
+ */
47
+ private readonly forceBrowserGraph;
48
+ /** @internal */
49
+ readonly bundleService: BundleService;
50
+ /** @internal */
51
+ readonly pageModuleService: PageModuleService;
52
+ /** @internal */
53
+ readonly hydrationAssetService: HydrationAssetService;
54
+ /** @internal */
55
+ readonly pagePayloadService: PagePayloadService;
56
+ /** @internal */
57
+ readonly mdxConfigDependencyService: MdxConfigDependencyService;
58
+ constructor(options: ReactRendererOptions);
59
+ private getRouterDocumentAttributes;
60
+ protected resolveReactRuntimeModules(): ReactRuntimeModules;
61
+ private getReactRuntimeModules;
62
+ /**
63
+ * Appends route hydration assets for a concrete page/view file to the current
64
+ * HTML transformer state.
65
+ */
66
+ private appendHydrationAssetsForFile;
67
+ private resolveOwningRenderer;
68
+ private resolveReactQueuedForeignSubtreeHtml;
69
+ /**
70
+ * Renders a React component for component-level orchestration.
71
+ *
72
+ * Behavior:
73
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
74
+ * - When an explicit component instance id is provided, a stable
75
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
76
+ * - Without an explicit instance id, component renders remain plain SSR output.
77
+ * - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
78
+ * composition step and does not emit hydration assets for the parent wrapper.
79
+ *
80
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
81
+ * deterministic mount target per component instance.
82
+ */
83
+ renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult>;
84
+ protected createForeignChildRuntime(options: {
85
+ renderInput: ComponentRenderInput;
86
+ rendererCache: Map<string, IntegrationRenderer<any>>;
87
+ }): ForeignChildRuntime;
88
+ /**
89
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
90
+ * @param filePath - The file path to check
91
+ * @returns True if the file is an MDX file
92
+ */
93
+ isMdxFile(filePath: string): boolean;
94
+ protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(file: string, pageModule: TPageModule): TPageModule;
95
+ protected collectPageBrowserGraphContribution(context: PageBrowserGraphContributionContext): Promise<{
96
+ dependencies?: AssetDefinition[];
97
+ assets?: ProcessedAsset[];
98
+ }>;
99
+ private composeReactLayoutPageChildrenForShell;
100
+ protected renderPageWithDocumentShell(input: {
101
+ page: {
102
+ component: EcoComponent;
103
+ props: Record<string, unknown>;
104
+ };
105
+ layout?: DocumentShellLayoutInput;
106
+ layouts?: DocumentShellLayoutInput[];
107
+ htmlTemplate: EcoComponent;
108
+ metadata: PageMetadataProps;
109
+ pageProps: Record<string, unknown>;
110
+ documentProps?: Record<string, unknown>;
111
+ transformDocumentHtml?: (html: string) => string;
112
+ }): Promise<string>;
113
+ /**
114
+ * Renders a full route response for the filesystem page pipeline.
115
+ *
116
+ * This path receives already-resolved route metadata, layout, locals, and HTML
117
+ * template instances from the shared renderer orchestration. Its main job is to
118
+ * serialize only the browser-safe page payload, compose the mixed React/non-
119
+ * React shell tree, and hand the result back as a document body.
120
+ */
121
+ render({ params, query, props, locals, pageLocals, metadata, Page, Layout, layoutEntries, HtmlTemplate, pageProps, pagePackage, }: IntegrationRendererRenderOptions<ReactNode>): Promise<RouteRendererBody>;
122
+ protected getHtmlDocumentContributions(options: HtmlDocumentContributionContext<ReactNode>): HtmlDocumentContribution[] | undefined;
123
+ protected getDocumentAttributes(): Record<string, string> | undefined;
124
+ protected renderViewWithDocumentShell<P>(input: {
125
+ view: EcoComponent<P>;
126
+ props: P;
127
+ ctx: RenderToResponseContext;
128
+ layout?: EcoComponent;
129
+ }): Promise<Response>;
130
+ /**
131
+ * Renders an arbitrary React view through the application's HTML shell.
132
+ *
133
+ * Unlike route rendering, this path starts from a single component rather than a
134
+ * page module discovered by the router. It still needs to resolve metadata,
135
+ * layout dependencies, and hydration assets so direct `ctx.render()` calls match
136
+ * normal page responses.
137
+ */
138
+ renderToResponse<P = Record<string, unknown>>(view: EcoComponent<P>, props: P, ctx: RenderToResponseContext): Promise<Response>;
139
+ }
@@ -0,0 +1,450 @@
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 { getComponentIdentity } from '@ecopages/core';
12
+ import { IntegrationRenderer, } from '@ecopages/core/route-renderer/orchestration/integration-renderer';
13
+ import { resolveDocumentShellLayouts } from '@ecopages/core/route-renderer/orchestration/document-shell/layout-shell-props.service';
14
+ import { RESOLVED_ASSETS_DIR } from '@ecopages/core/constants';
15
+ import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from '@ecopages/core/router/navigation-coordinator';
16
+ import { ensurePageConfigLayouts } from '@ecopages/core/eco/page-layout-normalization';
17
+ import { REACT_PLUGIN_NAME } from '../plugin/react.constants.js';
18
+ import { BundleService } from '../bundling/bundle.js';
19
+ import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
20
+ import { MdxConfigDependencyService } from '../mdx/mdx-config-dependency.js';
21
+ import { PageModuleService } from '../page/page-module.js';
22
+ import { PagePayloadService } from '../hydration/page-payload.js';
23
+ import { HydrationAssetService } from '../hydration/hydration-asset.js';
24
+ import { composeDocumentShell, finalizeDocumentShellHtml, renderPageDocumentShell, } from '@ecopages/core/route-renderer/orchestration/document-shell/document-shell-render.service';
25
+ import { mergePageBrowserGraph } from '@ecopages/core/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils';
26
+ import { getForeignSubtreeResolutionContextKey, getForeignSubtreeTokenPrefix, resolveOwningIntegrationRenderer, } from '@ecopages/core/route-renderer/orchestration/foreign-child/owning-renderer-resolution';
27
+ import { asReactComponent, getComponentRequires, isReactManagedComponent } from './component-ownership.js';
28
+ import { createForeignSubtreeRuntimeContext, renderForeignComponentWithSerializedHtml, renderReactManagedComponent, renderReactQueuedForeignSubtreeChildren, } from './component-ssr.js';
29
+ import { BundleError, ReactRenderError } from './errors.js';
30
+ import { resolveReactRuntimeModules } from './react-runtime.js';
31
+ import { composeReactLayoutPageChildren, resolveComposeChildren } from './unified-layout-composition.js';
32
+ export { BundleError, ReactRenderError } from './errors.js';
33
+ /**
34
+ * Renderer for React components.
35
+ * @extends IntegrationRenderer
36
+ */
37
+ export class ReactRenderer extends IntegrationRenderer {
38
+ name = REACT_PLUGIN_NAME;
39
+ componentDirectory = RESOLVED_ASSETS_DIR;
40
+ reactRuntimeModules;
41
+ routerAdapter;
42
+ mdxCompilerOptions;
43
+ mdxExtensions;
44
+ hmrPageMetadataCache;
45
+ /**
46
+ * When true, always emit page browser graph / hydration assets for React pages.
47
+ *
48
+ * Mapped from the public `explicitGraph` plugin option. Does not disable the
49
+ * client-graph AST boundary.
50
+ */
51
+ forceBrowserGraph;
52
+ /** @internal */
53
+ bundleService;
54
+ /** @internal */
55
+ pageModuleService;
56
+ /** @internal */
57
+ hydrationAssetService;
58
+ /** @internal */
59
+ pagePayloadService;
60
+ /** @internal */
61
+ mdxConfigDependencyService;
62
+ constructor(options) {
63
+ const { reactConfig, ...rendererOptions } = options;
64
+ super(rendererOptions);
65
+ this.routerAdapter = reactConfig?.routerAdapter;
66
+ this.mdxCompilerOptions = reactConfig?.mdxCompilerOptions;
67
+ this.mdxExtensions = reactConfig?.mdxExtensions ?? ['.mdx'];
68
+ this.hmrPageMetadataCache = reactConfig?.hmrPageMetadataCache;
69
+ this.forceBrowserGraph = reactConfig?.forceBrowserGraph ?? false;
70
+ this.bundleService = new BundleService({
71
+ rootDir: this.appConfig.rootDir,
72
+ appConfig: this.appConfig,
73
+ hostIntegrationName: this.name,
74
+ routerAdapter: this.routerAdapter,
75
+ runtimeModules: reactConfig?.runtimeModules,
76
+ mdxCompilerOptions: this.mdxCompilerOptions,
77
+ clientGraphBoundaryCache: reactConfig?.clientGraphBoundaryCache,
78
+ });
79
+ this.pageModuleService = new PageModuleService({
80
+ layoutsDir: this.appConfig.absolutePaths.layoutsDir,
81
+ componentsDir: this.appConfig.absolutePaths.componentsDir,
82
+ mdxExtensions: this.mdxExtensions,
83
+ integrationName: this.name,
84
+ hasRouterAdapter: Boolean(this.routerAdapter),
85
+ });
86
+ this.hydrationAssetService = new HydrationAssetService({
87
+ srcDir: this.appConfig.srcDir,
88
+ routerAdapter: this.routerAdapter,
89
+ assetProcessingService: this.assetProcessingService,
90
+ bundleService: this.bundleService,
91
+ hmrPageMetadataCache: this.hmrPageMetadataCache,
92
+ });
93
+ this.pagePayloadService = new PagePayloadService();
94
+ this.mdxConfigDependencyService = new MdxConfigDependencyService({
95
+ integrationName: this.name,
96
+ pageModuleService: this.pageModuleService,
97
+ assetProcessingService: this.assetProcessingService,
98
+ });
99
+ }
100
+ getRouterDocumentAttributes() {
101
+ if (!this.routerAdapter) {
102
+ return undefined;
103
+ }
104
+ return {
105
+ [ECO_DOCUMENT_OWNER_ATTRIBUTE]: 'react-router',
106
+ };
107
+ }
108
+ resolveReactRuntimeModules() {
109
+ return resolveReactRuntimeModules(this.appConfig.rootDir);
110
+ }
111
+ getReactRuntimeModules() {
112
+ this.reactRuntimeModules ??= this.resolveReactRuntimeModules();
113
+ return this.reactRuntimeModules;
114
+ }
115
+ /**
116
+ * Appends route hydration assets for a concrete page/view file to the current
117
+ * HTML transformer state.
118
+ */
119
+ async appendHydrationAssetsForFile(filePath) {
120
+ if (!filePath) {
121
+ return;
122
+ }
123
+ const pageBrowserGraph = await this.resolvePageBrowserGraphForFile(filePath);
124
+ if (!pageBrowserGraph) {
125
+ return;
126
+ }
127
+ const { pagePackage } = mergePageBrowserGraph(this.htmlTransformer.getPagePackage(), this.htmlTransformer.getProcessedDependencies(), pageBrowserGraph);
128
+ this.htmlTransformer.setPagePackage(pagePackage);
129
+ }
130
+ resolveOwningRenderer(integrationName, rendererCache) {
131
+ return resolveOwningIntegrationRenderer({
132
+ appConfig: this.appConfig,
133
+ runtimeOrigin: this.runtimeOrigin,
134
+ currentIntegrationName: this.name,
135
+ currentRenderer: this,
136
+ integrationName,
137
+ cache: rendererCache,
138
+ });
139
+ }
140
+ resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) {
141
+ return this.foreignSubtreeExecutionService.resolveQueuedHtml({
142
+ currentIntegrationName: this.name,
143
+ html,
144
+ runtimeContext,
145
+ queueLabel: 'React',
146
+ getOwningRenderer: (integrationName, rendererCache) => this.resolveOwningRenderer(integrationName, rendererCache),
147
+ applyAttributesToFirstElement: (resolvedHtml, attributes) => this.htmlTransformer.applyAttributesToFirstElement(resolvedHtml, attributes),
148
+ dedupeProcessedAssets: (assets) => this.htmlTransformer.dedupeProcessedAssets(assets),
149
+ renderQueuedChildren: (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => renderReactQueuedForeignSubtreeChildren({
150
+ children,
151
+ currentRuntimeContext,
152
+ queuedResolutionsByToken,
153
+ resolveToken,
154
+ runtime: this.getReactRuntimeModules(),
155
+ integrationName: this.name,
156
+ normalizeUnresolvedMarkerArtifactHtml: (value) => this.normalizeUnresolvedMarkerArtifactHtml(value),
157
+ resolveQueuedTokens: (value, tokens, resolve) => this.foreignSubtreeExecutionService.resolveQueuedTokens(value, tokens, resolve),
158
+ }),
159
+ });
160
+ }
161
+ /**
162
+ * Renders a React component for component-level orchestration.
163
+ *
164
+ * Behavior:
165
+ * - SSR always returns the component's own root HTML (no synthetic wrapper).
166
+ * - When an explicit component instance id is provided, a stable
167
+ * `data-eco-component-id` attribute is attached so island hydration can target it.
168
+ * - Without an explicit instance id, component renders remain plain SSR output.
169
+ * - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
170
+ * composition step and does not emit hydration assets for the parent wrapper.
171
+ *
172
+ * This preserves DOM shape for global CSS/layout selectors while keeping a
173
+ * deterministic mount target per component instance.
174
+ */
175
+ async renderComponent(input) {
176
+ const runtimeContext = this.foreignSubtreeExecutionService.getQueuedRuntimeContext(input, getForeignSubtreeResolutionContextKey(this.name));
177
+ if (!isReactManagedComponent(input.component, this.name)) {
178
+ return renderForeignComponentWithSerializedHtml({
179
+ input,
180
+ runtimeContext,
181
+ integrationName: this.name,
182
+ canResolveAssets: typeof this.assetProcessingService?.processDependencies === 'function',
183
+ processComponentDependencies: (components) => this.processComponentDependencies(components),
184
+ dedupeProcessedAssets: (assets) => this.htmlTransformer.dedupeProcessedAssets(assets),
185
+ getRootTagName: (html) => this.getRootTagName(html),
186
+ resolveQueuedForeignSubtreeHtml: (html, context) => this.resolveReactQueuedForeignSubtreeHtml(html, context),
187
+ });
188
+ }
189
+ return renderReactManagedComponent({
190
+ input,
191
+ runtimeContext,
192
+ runtime: this.getReactRuntimeModules(),
193
+ integrationName: this.name,
194
+ normalizeUnresolvedMarkerArtifactHtml: (html) => this.normalizeUnresolvedMarkerArtifactHtml(html),
195
+ resolveQueuedForeignSubtreeHtml: (html, context) => this.resolveReactQueuedForeignSubtreeHtml(html, context),
196
+ getRootTagName: (html) => this.getRootTagName(html),
197
+ dedupeProcessedAssets: (assets) => this.htmlTransformer.dedupeProcessedAssets(assets),
198
+ hydrationAssetService: this.hydrationAssetService,
199
+ canBuildIslandAssets: Boolean(this.assetProcessingService),
200
+ });
201
+ }
202
+ createForeignChildRuntime(options) {
203
+ return this.foreignSubtreeExecutionService.createQueuedRuntime({
204
+ renderInput: options.renderInput,
205
+ rendererCache: options.rendererCache,
206
+ runtimeContextKey: getForeignSubtreeResolutionContextKey(this.name),
207
+ tokenPrefix: getForeignSubtreeTokenPrefix(this.name),
208
+ createRuntimeContext: (integrationContext, rendererCache) => createForeignSubtreeRuntimeContext({
209
+ rendererCache: rendererCache,
210
+ componentInstanceScope: integrationContext.componentInstanceId,
211
+ }),
212
+ });
213
+ }
214
+ /**
215
+ * Checks if the given file path corresponds to an MDX file based on configured extensions.
216
+ * @param filePath - The file path to check
217
+ * @returns True if the file is an MDX file
218
+ */
219
+ isMdxFile(filePath) {
220
+ return this.pageModuleService.isMdxFile(filePath);
221
+ }
222
+ normalizeImportedPageFile(file, pageModule) {
223
+ const reactModule = pageModule;
224
+ const { default: Page, getMetadata, config } = reactModule;
225
+ if (this.pageModuleService.isMdxFile(file) && config) {
226
+ ensurePageConfigLayouts(config);
227
+ Page.config = config;
228
+ }
229
+ return {
230
+ ...pageModule,
231
+ default: Page,
232
+ getMetadata,
233
+ config,
234
+ };
235
+ }
236
+ async collectPageBrowserGraphContribution(context) {
237
+ try {
238
+ const { file: pagePath, pageModule } = context;
239
+ const shouldHydrate = this.forceBrowserGraph ? true : this.pageModuleService.shouldHydratePage(pageModule);
240
+ if (!shouldHydrate) {
241
+ return { assets: [] };
242
+ }
243
+ const isMdx = this.pageModuleService.isMdxFile(pagePath);
244
+ const declaredModules = this.pageModuleService.collectPageDeclaredModules(pageModule);
245
+ if (isMdx) {
246
+ await this.bundleService.ensurePageLayoutNormalizationVendorProcessed(this.assetProcessingService);
247
+ }
248
+ const dependencies = await this.hydrationAssetService.createPageBrowserGraphDependencies(pagePath, isMdx, declaredModules);
249
+ const assets = isMdx
250
+ ? await this.mdxConfigDependencyService.processMdxConfigDependencies({
251
+ pagePath,
252
+ config: pageModule.config,
253
+ processComponentDependencies: async (components) => await this.processComponentDependencies(components),
254
+ })
255
+ : [];
256
+ return { dependencies, assets };
257
+ }
258
+ catch (error) {
259
+ if (error instanceof BundleError) {
260
+ console.error('[ecopages] Bundle errors:', error.logs);
261
+ }
262
+ throw new ReactRenderError(`Failed to generate hydration script: ${error instanceof Error ? error.message : String(error)}`);
263
+ }
264
+ }
265
+ async composeReactLayoutPageChildrenForShell(page, context) {
266
+ return composeReactLayoutPageChildren({
267
+ page,
268
+ context,
269
+ runtime: this.getReactRuntimeModules(),
270
+ integrationName: this.name,
271
+ normalizeUnresolvedMarkerArtifactHtml: (html) => this.normalizeUnresolvedMarkerArtifactHtml(html),
272
+ getRootTagName: (html) => this.getRootTagName(html),
273
+ getQueuedForeignSubtreeResolutionContext: (input) => this.foreignSubtreeExecutionService.getQueuedRuntimeContext(input, getForeignSubtreeResolutionContextKey(this.name)),
274
+ resolveQueuedForeignSubtreeHtml: (html, runtimeContext) => this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext),
275
+ });
276
+ }
277
+ async renderPageWithDocumentShell(input) {
278
+ const shellLayouts = input.layouts ?? (input.layout ? [input.layout] : []);
279
+ const composeChildren = resolveComposeChildren({
280
+ page: input.page,
281
+ shellLayouts,
282
+ reactIntegrationName: this.name,
283
+ composeChildren: (page, context) => this.composeReactLayoutPageChildrenForShell(page, context),
284
+ });
285
+ return renderPageDocumentShell({
286
+ renderComponentWithForeignChildren: (renderInput) => this.renderComponentWithForeignChildren(renderInput),
287
+ appendProcessedDependencies: (...assetGroups) => this.appendProcessedDependencies(...assetGroups),
288
+ }, {
289
+ ...input,
290
+ composeChildren,
291
+ }, this.DOC_TYPE);
292
+ }
293
+ /**
294
+ * Renders a full route response for the filesystem page pipeline.
295
+ *
296
+ * This path receives already-resolved route metadata, layout, locals, and HTML
297
+ * template instances from the shared renderer orchestration. Its main job is to
298
+ * serialize only the browser-safe page payload, compose the mixed React/non-
299
+ * React shell tree, and hand the result back as a document body.
300
+ */
301
+ async render({ params, query, props, locals, pageLocals, metadata, Page, Layout, layoutEntries, HtmlTemplate, pageProps, pagePackage, }) {
302
+ try {
303
+ const pageModuleUrl = this.pagePayloadService.resolvePageModuleUrl(pagePackage, {
304
+ routerEnabled: Boolean(this.routerAdapter),
305
+ });
306
+ const safeLocals = this.pagePayloadService.getSerializableLocals(locals, getComponentRequires(Page));
307
+ const allPageProps = this.pagePayloadService.buildSerializedPageProps({
308
+ pageProps,
309
+ params,
310
+ query,
311
+ safeLocals,
312
+ });
313
+ return await this.renderPageWithDocumentShell({
314
+ page: {
315
+ component: Page,
316
+ props: { params, query, ...props, locals: pageLocals },
317
+ },
318
+ layouts: resolveDocumentShellLayouts({
319
+ layout: Layout,
320
+ layoutEntries,
321
+ params,
322
+ query,
323
+ locals,
324
+ }),
325
+ htmlTemplate: HtmlTemplate,
326
+ metadata,
327
+ pageProps: allPageProps,
328
+ documentProps: pageModuleUrl ? { pageModuleUrl } : undefined,
329
+ });
330
+ }
331
+ catch (error) {
332
+ throw this.createRenderError('Failed to render component', error);
333
+ }
334
+ }
335
+ getHtmlDocumentContributions(options) {
336
+ if (options.partial || !options.renderOptions) {
337
+ return undefined;
338
+ }
339
+ const safeLocals = this.pagePayloadService.getSerializableLocals(options.renderOptions.locals, getComponentRequires(options.renderOptions.Page));
340
+ const pageModuleUrl = this.pagePayloadService.resolvePageModuleUrl(options.renderOptions.pagePackage, {
341
+ routerEnabled: Boolean(this.routerAdapter),
342
+ });
343
+ const allPageProps = this.pagePayloadService.buildSerializedPageProps({
344
+ pageProps: options.renderOptions.pageProps,
345
+ params: options.renderOptions.params,
346
+ query: options.renderOptions.query,
347
+ safeLocals,
348
+ });
349
+ return this.pagePayloadService.buildNonReactDocumentContributions({
350
+ htmlTemplate: options.renderOptions.HtmlTemplate,
351
+ pageProps: allPageProps,
352
+ pageModuleUrl,
353
+ reactIntegrationName: this.name,
354
+ routerEnabled: Boolean(this.routerAdapter),
355
+ });
356
+ }
357
+ getDocumentAttributes() {
358
+ return this.getRouterDocumentAttributes();
359
+ }
360
+ async renderViewWithDocumentShell(input) {
361
+ const normalizedProps = (input.props ?? {});
362
+ if (input.ctx.partial) {
363
+ const { react, reactDomServer } = this.getReactRuntimeModules();
364
+ const ViewComponent = asReactComponent(input.view);
365
+ return this.renderPartialViewResponse({
366
+ ...input,
367
+ renderInline: async () => await reactDomServer.renderToReadableStream(react.createElement(ViewComponent, normalizedProps)),
368
+ });
369
+ }
370
+ await this.prepareViewDependencies(input.view, input.layout);
371
+ if (!input.ctx.partial) {
372
+ await this.appendHydrationAssetsForFile(getComponentIdentity(input.view)?.file);
373
+ }
374
+ const HtmlTemplate = await this.getHtmlTemplate();
375
+ const metadata = await this.resolveViewMetadata(input.view, input.props);
376
+ const pageModuleUrl = this.pagePayloadService.resolvePageModuleUrl(this.htmlTransformer.getPagePackage(), {
377
+ routerEnabled: Boolean(this.routerAdapter),
378
+ });
379
+ const serializedPageProps = this.pagePayloadService.buildSerializedPageProps({
380
+ pageProps: normalizedProps,
381
+ params: {},
382
+ query: {},
383
+ safeLocals: this.pagePayloadService.getSerializableLocals(undefined, getComponentRequires(input.view)),
384
+ });
385
+ const shellLayouts = input.layout ? [{ component: input.layout, props: {} }] : [];
386
+ const composeChildren = resolveComposeChildren({
387
+ page: { component: input.view, props: normalizedProps },
388
+ shellLayouts,
389
+ reactIntegrationName: this.name,
390
+ composeChildren: (page, context) => this.composeReactLayoutPageChildrenForShell(page, context),
391
+ });
392
+ const { documentHtml } = await composeDocumentShell({
393
+ renderComponentWithForeignChildren: (renderInput) => this.renderComponentWithForeignChildren(renderInput),
394
+ appendProcessedDependencies: (...assetGroups) => this.appendProcessedDependencies(...assetGroups),
395
+ }, {
396
+ primaryComponent: input.view,
397
+ primaryProps: normalizedProps,
398
+ layout: input.layout
399
+ ? {
400
+ component: input.layout,
401
+ props: {},
402
+ }
403
+ : undefined,
404
+ layouts: shellLayouts.length > 0 ? shellLayouts : undefined,
405
+ composeChildren,
406
+ htmlTemplate: HtmlTemplate,
407
+ documentProps: {
408
+ metadata,
409
+ pageProps: serializedPageProps,
410
+ ...(pageModuleUrl && { pageModuleUrl }),
411
+ },
412
+ });
413
+ this.appendProcessedDependencies(this.getRendererBootstrapDependencies(false));
414
+ const html = await finalizeDocumentShellHtml(this.htmlTransformer, {
415
+ html: `${this.DOC_TYPE}${documentHtml}`,
416
+ partial: false,
417
+ documentAttributes: this.getRouterDocumentAttributes(),
418
+ htmlContributions: this.pagePayloadService.buildNonReactDocumentContributions({
419
+ htmlTemplate: HtmlTemplate,
420
+ pageProps: serializedPageProps,
421
+ pageModuleUrl,
422
+ reactIntegrationName: this.name,
423
+ routerEnabled: Boolean(this.routerAdapter),
424
+ }),
425
+ });
426
+ return this.createHtmlResponse(html, input.ctx);
427
+ }
428
+ /**
429
+ * Renders an arbitrary React view through the application's HTML shell.
430
+ *
431
+ * Unlike route rendering, this path starts from a single component rather than a
432
+ * page module discovered by the router. It still needs to resolve metadata,
433
+ * layout dependencies, and hydration assets so direct `ctx.render()` calls match
434
+ * normal page responses.
435
+ */
436
+ async renderToResponse(view, props, ctx) {
437
+ try {
438
+ const layouts = view.config?.layouts;
439
+ return await this.renderViewWithDocumentShell({
440
+ view,
441
+ props,
442
+ ctx,
443
+ layout: layouts?.[layouts.length - 1],
444
+ });
445
+ }
446
+ catch (error) {
447
+ throw this.createRenderError('Failed to render view', error);
448
+ }
449
+ }
450
+ }
@@ -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
+ }