@ecopages/react 0.2.0-beta.9 → 0.2.0-rc.0

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