@ecopages/react 0.6.0 → 0.7.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 (95) hide show
  1. package/README.md +50 -87
  2. package/package.json +32 -14
  3. package/src/bundling/bootstrap-package-paths.d.ts +13 -1
  4. package/src/bundling/bootstrap-package-paths.js +25 -3
  5. package/src/bundling/bundle.d.ts +8 -36
  6. package/src/bundling/bundle.js +42 -73
  7. package/src/client-graph/ast-transform-eco-page.d.ts +10 -6
  8. package/src/client-graph/ast-transform-eco-page.js +56 -35
  9. package/src/client-graph/ast-transform-import-edits.d.ts +10 -2
  10. package/src/client-graph/ast-transform-import-edits.js +36 -6
  11. package/src/client-graph/ast-transform-stripped-imports.d.ts +37 -0
  12. package/src/client-graph/ast-transform-stripped-imports.js +191 -0
  13. package/src/client-graph/ast-transform-walk-imports.d.ts +4 -0
  14. package/src/client-graph/ast-transform-walk-imports.js +15 -1
  15. package/src/client-graph/ast-transform.d.ts +12 -3
  16. package/src/client-graph/ast-transform.js +41 -56
  17. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +3 -0
  18. package/src/client-graph/boundary-plugin-read-file-inline.js +14 -10
  19. package/src/client-graph/boundary-plugin-transform.d.ts +5 -4
  20. package/src/client-graph/boundary-plugin-transform.js +6 -13
  21. package/src/client-graph/boundary-plugin.d.ts +47 -1
  22. package/src/client-graph/boundary-plugin.js +267 -53
  23. package/src/client-graph/foreign-boundary-rewrite.d.ts +31 -0
  24. package/src/client-graph/foreign-boundary-rewrite.js +360 -0
  25. package/src/client-graph/foreign-jsx-reach.d.ts +25 -0
  26. package/src/client-graph/foreign-jsx-reach.js +68 -0
  27. package/src/client-graph/module-classification.js +3 -10
  28. package/src/client-graph/reachability-traverse.js +35 -105
  29. package/src/client-graph/requested-exports-plan.d.ts +62 -0
  30. package/src/client-graph/requested-exports-plan.js +125 -0
  31. package/src/client-graph/scope-walk.d.ts +37 -0
  32. package/src/client-graph/scope-walk.js +407 -0
  33. package/src/client-graph/specifier-classification.d.ts +2 -1
  34. package/src/client-graph/specifier-classification.js +9 -7
  35. package/src/contracts/router-adapter.d.ts +9 -24
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +4 -4
  37. package/src/dev-transform/react-dev-transform-contributor.js +6 -7
  38. package/src/hmr/hmr-strategy-process.d.ts +7 -5
  39. package/src/hmr/hmr-strategy-process.js +21 -16
  40. package/src/hmr/hmr-strategy.d.ts +11 -10
  41. package/src/hmr/hmr-strategy.js +32 -53
  42. package/src/hmr/page-metadata-cache.js +1 -1
  43. package/src/hydration/browser/foreign-boundary.d.ts +29 -0
  44. package/src/hydration/browser/foreign-boundary.js +128 -0
  45. package/src/hydration/browser/island-hydration.d.ts +3 -4
  46. package/src/hydration/browser/island-hydration.js +3 -4
  47. package/src/hydration/browser/page-hydration-hmr.d.ts +8 -7
  48. package/src/hydration/browser/page-hydration-hmr.js +53 -10
  49. package/src/hydration/browser/page-hydration.d.ts +6 -5
  50. package/src/hydration/browser/page-hydration.js +8 -6
  51. package/src/hydration/foreign-subtree.d.ts +27 -0
  52. package/src/hydration/foreign-subtree.js +69 -0
  53. package/src/hydration/hydration-asset.d.ts +37 -29
  54. package/src/hydration/hydration-asset.js +74 -138
  55. package/src/hydration/hydration-island-entry-source.d.ts +17 -0
  56. package/src/hydration/hydration-island-entry-source.js +32 -0
  57. package/src/hydration/hydration-page-entry-source.d.ts +20 -2
  58. package/src/hydration/hydration-page-entry-source.js +17 -12
  59. package/src/hydration/page-data-reader.d.ts +4 -7
  60. package/src/hydration/page-data-reader.js +5 -10
  61. package/src/mdx/mdx-config-dependency.d.ts +10 -15
  62. package/src/mdx/mdx-config-dependency.js +9 -22
  63. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  64. package/src/mdx/mdx-loader-plugin.js +1 -0
  65. package/src/page/page-module.js +1 -1
  66. package/src/plugin/react.plugin.d.ts +0 -7
  67. package/src/plugin/react.plugin.js +4 -33
  68. package/src/plugin/react.types.d.ts +0 -29
  69. package/src/render/component-ssr.d.ts +18 -0
  70. package/src/render/component-ssr.js +37 -0
  71. package/src/render/layout-compose.d.ts +4 -2
  72. package/src/render/layout-compose.js +13 -6
  73. package/src/render/layout-render-tracker.d.ts +20 -0
  74. package/src/render/layout-render-tracker.js +33 -0
  75. package/src/render/react-renderer.d.ts +28 -10
  76. package/src/render/react-renderer.js +103 -38
  77. package/src/render/react-runtime.js +2 -2
  78. package/src/bundling/runtime-alias-map.d.ts +0 -12
  79. package/src/bundling/runtime-alias-map.js +0 -110
  80. package/src/bundling/runtime-bundle.d.ts +0 -70
  81. package/src/bundling/runtime-bundle.js +0 -233
  82. package/src/bundling/runtime-interop-plugin.d.ts +0 -5
  83. package/src/bundling/runtime-interop-plugin.js +0 -32
  84. package/src/bundling/runtime-mode.d.ts +0 -1
  85. package/src/bundling/runtime-mode.js +0 -10
  86. package/src/bundling/runtime-modules.d.ts +0 -21
  87. package/src/bundling/runtime-modules.js +0 -28
  88. package/src/hydration/bootstrap-imports.d.ts +0 -25
  89. package/src/hydration/bootstrap-imports.js +0 -33
  90. package/src/hydration/compiled-page-hydration-options.d.ts +0 -19
  91. package/src/hydration/compiled-page-hydration-options.js +0 -1
  92. package/src/hydration/hydration-script-compiler.d.ts +0 -47
  93. package/src/hydration/hydration-script-compiler.js +0 -213
  94. package/src/runtime/use-sync-external-store-with-selector.d.ts +0 -3
  95. package/src/runtime/use-sync-external-store-with-selector.js +0 -54
@@ -1,15 +1,14 @@
1
- import path from 'node:path';
1
+ import { path } from '@ecopages/file-system/path';
2
2
  import { getComponentIdentity, } from '@ecopages/core';
3
3
  import { attachEcoFileMetadataToConfig } from '@ecopages/core/integration';
4
- import { AssetFactory, } from '@ecopages/core/integration';
4
+ import { AssetFactory } from '@ecopages/core/integration';
5
5
  import { collectFromConfigForest, getComponentConfigs } from '../client-graph/component-config-traversal.js';
6
6
  /**
7
7
  * Resolves MDX-owned config dependencies that live outside the normal React component tree.
8
8
  *
9
9
  * React MDX pages can declare dependencies on the page config itself or on a
10
- * resolved layout config. Those roots need to be materialized as synthetic
11
- * component configs so the shared dependency pipeline can process them without
12
- * growing more MDX-specific logic inside the renderer.
10
+ * resolved layout config. Those roots become synthetic component configs that core
11
+ * processes through the shared dependency pipeline, and plans for the app-wide browser build.
13
12
  */
14
13
  export class MdxConfigDependencyService {
15
14
  config;
@@ -17,16 +16,11 @@ export class MdxConfigDependencyService {
17
16
  this.config = config;
18
17
  }
19
18
  /**
20
- * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
19
+ * Returns the MDX-owned config components and, as eager head scripts, their SSR-marked lazy scripts.
21
20
  */
22
- async processMdxConfigDependencies(options) {
23
- const components = this.createOwnedConfigComponents(options.pagePath, options.config);
24
- if (components.length === 0) {
25
- return [];
26
- }
27
- const processedDependencies = await options.processComponentDependencies(components);
28
- const eagerSsrLazyDependencies = await this.processDeclaredSsrLazyDependencies(components);
29
- return [...processedDependencies, ...eagerSsrLazyDependencies];
21
+ collectMdxConfigContribution(pagePath, config) {
22
+ const components = this.createOwnedConfigComponents(pagePath, config);
23
+ return { components, bundledScripts: this.collectDeclaredSsrLazyDependencies(components) };
30
24
  }
31
25
  createOwnedConfigComponents(pagePath, config) {
32
26
  const components = [];
@@ -43,13 +37,6 @@ export class MdxConfigDependencyService {
43
37
  }
44
38
  return components;
45
39
  }
46
- async processDeclaredSsrLazyDependencies(components) {
47
- const dependencies = this.collectDeclaredSsrLazyDependencies(components);
48
- if (dependencies.length === 0) {
49
- return [];
50
- }
51
- return this.config.assetProcessingService.processDependencies(dependencies, this.config.assetProcessingIntegration);
52
- }
53
40
  /**
54
41
  * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
55
42
  */
@@ -66,7 +53,7 @@ export class MdxConfigDependencyService {
66
53
  if (!componentFile) {
67
54
  return [];
68
55
  }
69
- const componentDir = path.dirname(componentFile);
56
+ const componentDir = path.dirname(path.resolve(this.config.rootDir, componentFile));
70
57
  for (const script of config.dependencies?.scripts ?? []) {
71
58
  if (typeof script === 'string' || !script.lazy || script.ssr !== true) {
72
59
  continue;
@@ -1,8 +1,10 @@
1
1
  import type { CompileOptions } from '@mdx-js/mdx';
2
2
  import type { RequestPipelineMetricsState } from '@ecopages/core/build';
3
+ import type { StylesheetKinds } from '@ecopages/core/integration';
3
4
  export interface CreateReactMdxLoaderPluginOptions {
4
5
  compilerOptions?: CompileOptions;
5
6
  projectRoot: string;
6
7
  requestPipelineMetrics: RequestPipelineMetricsState;
8
+ stylesheets?: StylesheetKinds;
7
9
  }
8
10
  export declare function createReactMdxLoaderPlugin(options: CreateReactMdxLoaderPluginOptions): import("@ecopages/core/integration").EcoBuildPlugin;
@@ -7,5 +7,6 @@ export function createReactMdxLoaderPlugin(options) {
7
7
  defaultMdExtensions: [],
8
8
  projectRoot: options.projectRoot,
9
9
  requestPipelineMetrics: options.requestPipelineMetrics,
10
+ stylesheets: options.stylesheets,
10
11
  });
11
12
  }
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @module
9
9
  */
10
- import path from 'node:path';
10
+ import { path } from '@ecopages/file-system/path';
11
11
  import { bindComponentIdentity, getComponentIdentity, getComponentOwner, } from '@ecopages/core';
12
12
  import { contentHash } from '@ecopages/core/build';
13
13
  import { fileSystem } from '@ecopages/file-system';
@@ -18,9 +18,7 @@ export declare class ReactPlugin extends IntegrationPlugin<React.ReactNode> {
18
18
  private readonly mdxExtensions;
19
19
  private readonly mdxCompilerOptions;
20
20
  private readonly getMdxLoaderPlugin?;
21
- private readonly runtimeBundleService;
22
21
  private readonly hmrPageMetadataCache;
23
- private runtimeDependenciesInitialized;
24
22
  /**
25
23
  * When true, always emit page browser graph / hydration assets.
26
24
  *
@@ -38,7 +36,6 @@ export declare class ReactPlugin extends IntegrationPlugin<React.ReactNode> {
38
36
  * preserving the same runtime services the base initializer wires up.
39
37
  */
40
38
  createRenderer(base: IntegrationRendererBase): ReactRenderer;
41
- private ensureRuntimeDependencies;
42
39
  /**
43
40
  * Returns the MDX loader when MDX is enabled.
44
41
  *
@@ -48,10 +45,6 @@ export declare class ReactPlugin extends IntegrationPlugin<React.ReactNode> {
48
45
  */
49
46
  plugins(app: IntegrationRuntimeContext['appConfig']): EcoBuildPlugin[];
50
47
  private resolveMdxLoaderPlugin;
51
- /**
52
- * Adds the React runtime vendor assets to the global dependencies, then processes them.
53
- */
54
- setup(context: IntegrationRuntimeContext): Promise<void>;
55
48
  /**
56
49
  * Provides React-specific HMR strategy with Fast Refresh support.
57
50
  *
@@ -2,19 +2,16 @@
2
2
  * This module contains the react plugin for Ecopages
3
3
  * @module
4
4
  */
5
- import { requireAppRuntime } from '@ecopages/core/integration';
5
+ import { getStylesheetKinds, requireAppRuntime } from '@ecopages/core/integration';
6
6
  import { IntegrationPlugin, } from '@ecopages/core/integration';
7
7
  import { Logger } from '@ecopages/logger';
8
- import path from 'node:path';
9
8
  import { REACT_PLUGIN_NAME, REACT_SSR_RENDER_TIMEOUT_MAX_MS } from './react.constants.js';
10
9
  import { ReactRenderer } from '../render/react-renderer.js';
11
10
  import { ReactHmrStrategy } from '../hmr/hmr-strategy.js';
12
11
  import { ReactDevTransformContributor } from '../dev-transform/react-dev-transform-contributor.js';
13
- import { RuntimeBundleService } from '../bundling/runtime-bundle.js';
14
12
  import { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
15
13
  import { createReactMdxLoaderPlugin } from '../mdx/mdx-loader-plugin.js';
16
14
  import { appendMdxExtensions, resolveMdxCompilerOptions } from '@ecopages/mdx/core';
17
- import { resolveReactPluginRuntimeModules } from '../bundling/runtime-modules.js';
18
15
  const appLogger = new Logger('[ReactPlugin]');
19
16
  /**
20
17
  * The name of the React plugin
@@ -38,18 +35,16 @@ function assertValidRenderTimeout(renderTimeoutMs) {
38
35
  * - `mdx.extensions`: `['.mdx']`
39
36
  */
40
37
  const resolveReactPluginOptions = (options) => {
41
- const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, runtimeModules, renderTimeoutMs, ...baseConfig } = options ?? {};
38
+ const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, renderTimeoutMs, ...baseConfig } = options ?? {};
42
39
  assertValidRenderTimeout(renderTimeoutMs);
43
40
  const extensions = [...(userExtensions ?? ['.tsx'])];
44
41
  const mdxEnabled = mdx !== undefined;
45
42
  const mdxExtensions = mdx?.extensions ?? ['.mdx'];
46
- const resolvedRuntimeModules = resolveReactPluginRuntimeModules(runtimeModules);
47
43
  if (mdxEnabled) {
48
44
  appendMdxExtensions(extensions, mdxExtensions);
49
45
  }
50
46
  const rendererConfig = {
51
47
  routerAdapter: router,
52
- runtimeModules: resolvedRuntimeModules,
53
48
  mdxExtensions,
54
49
  hmrPageMetadataCache: new HmrPageMetadataCache(),
55
50
  forceBrowserGraph: explicitGraph ?? false,
@@ -74,9 +69,7 @@ export class ReactPlugin extends IntegrationPlugin {
74
69
  mdxExtensions;
75
70
  mdxCompilerOptions;
76
71
  getMdxLoaderPlugin;
77
- runtimeBundleService;
78
72
  hmrPageMetadataCache;
79
- runtimeDependenciesInitialized = false;
80
73
  /**
81
74
  * When true, always emit page browser graph / hydration assets.
82
75
  *
@@ -88,16 +81,11 @@ export class ReactPlugin extends IntegrationPlugin {
88
81
  constructor(options) {
89
82
  const config = resolveReactPluginOptions(options);
90
83
  const { extensions, rendererConfig, integrationDependencies, mdxCompilerOptions, ...baseConfig } = config;
91
- const runtimeBundleService = new RuntimeBundleService({
92
- routerAdapter: rendererConfig.routerAdapter,
93
- runtimeModules: rendererConfig.runtimeModules,
94
- });
95
84
  super({
96
85
  name: PLUGIN_NAME,
97
86
  extensions,
98
87
  jsxImportSource: 'react',
99
88
  integrationDependencies,
100
- browserRuntimeManifest: runtimeBundleService.getRuntimeManifest(),
101
89
  ...baseConfig,
102
90
  });
103
91
  this.routerAdapter = rendererConfig.routerAdapter;
@@ -127,7 +115,6 @@ export class ReactPlugin extends IntegrationPlugin {
127
115
  if (mdxCompilerOptions) {
128
116
  appLogger.debug('MDX mode enabled with React jsx runtime');
129
117
  }
130
- this.runtimeBundleService = runtimeBundleService;
131
118
  }
132
119
  /**
133
120
  * Creates a React renderer with instance-owned runtime configuration.
@@ -144,16 +131,6 @@ export class ReactPlugin extends IntegrationPlugin {
144
131
  renderer.name ||= this.name;
145
132
  return renderer;
146
133
  }
147
- ensureRuntimeDependencies(appConfig) {
148
- if (this.runtimeDependenciesInitialized) {
149
- return;
150
- }
151
- this.runtimeBundleService.setRootDir(appConfig.rootDir);
152
- this.runtimeBundleService.setWorkDir(appConfig.absolutePaths.workDir ?? path.join(appConfig.rootDir, appConfig.workDir ?? '.eco'));
153
- this.runtimeBundleService.setRuntimeModules(this.rendererConfig.runtimeModules ?? []);
154
- this.integrationDependencies.unshift(...this.runtimeBundleService.getDependencies());
155
- this.runtimeDependenciesInitialized = true;
156
- }
157
134
  /**
158
135
  * Returns the MDX loader when MDX is enabled.
159
136
  *
@@ -171,15 +148,9 @@ export class ReactPlugin extends IntegrationPlugin {
171
148
  compilerOptions,
172
149
  projectRoot: appConfig.rootDir,
173
150
  requestPipelineMetrics,
151
+ stylesheets: getStylesheetKinds(appConfig),
174
152
  });
175
153
  }
176
- /**
177
- * Adds the React runtime vendor assets to the global dependencies, then processes them.
178
- */
179
- async setup(context) {
180
- this.ensureRuntimeDependencies(context.appConfig);
181
- await super.setup(context);
182
- }
183
154
  /**
184
155
  * Provides React-specific HMR strategy with Fast Refresh support.
185
156
  *
@@ -198,7 +169,7 @@ export class ReactPlugin extends IntegrationPlugin {
198
169
  context: manager.getDefaultContext(),
199
170
  projectRoot: context.appConfig.rootDir,
200
171
  pageMetadataCache: this.hmrPageMetadataCache,
201
- runtimeManifest: this.runtimeBundleService.getRuntimeManifest('development'),
172
+ routerAdapter: this.routerAdapter,
202
173
  getMdxLoaderPlugin: this.getMdxLoaderPlugin,
203
174
  ownedTemplateExtensions: this.extensions,
204
175
  allTemplateExtensions: context.appConfig.templatesExt,
@@ -3,7 +3,6 @@ import type { EcoBuildPlugin } from '@ecopages/core/integration';
3
3
  import type { MdxCompilerOptionsInput } from '@ecopages/mdx/core';
4
4
  import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
5
5
  import type { HmrPageMetadataCache } from '../hmr/page-metadata-cache.js';
6
- import type { ReactPluginRuntimeModule, ResolvedReactPluginRuntimeModule } from '../bundling/runtime-modules.js';
7
6
  export type ReactMdxOptions = MdxCompilerOptionsInput;
8
7
  /**
9
8
  * Options for the React plugin.
@@ -37,33 +36,6 @@ export type ReactPluginOptions = {
37
36
  * ```
38
37
  */
39
38
  router?: ReactRouterAdapter;
40
- /**
41
- * Optional shared browser runtime vendors.
42
- *
43
- * @remarks
44
- * Packages listed here use one vendor URL across page browser graphs. Add
45
- * singleton packages such as TanStack Query or MobX when pages and layouts
46
- * need to share the same module instance; layouts do not infer these entries.
47
- *
48
- * @example
49
- * ```ts
50
- * reactPlugin({
51
- * router: ecoRouter(),
52
- * runtimeModules: ['@tanstack/react-query'],
53
- * });
54
- * ```
55
- *
56
- * Register the exact specifier imported by the page or layout. Package
57
- * subpaths are separate module contracts and need separate entries.
58
- *
59
- * @example Advanced vendor config
60
- * ```ts
61
- * runtimeModules: [
62
- * { specifier: '@acme/ui', outputName: 'acme-ui' },
63
- * ]
64
- * ```
65
- */
66
- runtimeModules?: ReactPluginRuntimeModule[];
67
39
  /**
68
40
  * MDX configuration for handling .mdx files within the React plugin.
69
41
  * When configured, MDX files are treated as React pages with full router support.
@@ -98,7 +70,6 @@ export type ReactPluginOptions = {
98
70
  };
99
71
  export type ReactRendererConfig = {
100
72
  routerAdapter?: ReactRouterAdapter;
101
- runtimeModules?: ResolvedReactPluginRuntimeModule[];
102
73
  /**
103
74
  * Returns the plugin-owned MDX loader, creating it on first call. Set only
104
75
  * when MDX is enabled.
@@ -56,3 +56,21 @@ export declare function toReactNode(children: unknown, integrationName: string):
56
56
  * normal string child or it would escape it.
57
57
  */
58
58
  export declare function restoreRuntimeChildHtml(html: string, runtimeContext: ReactForeignSubtreeResolutionContext | undefined): string;
59
+ /**
60
+ * Wraps each Foreign Subtree token React rendered in `html` in the boundary element hydration keeps.
61
+ *
62
+ * @remarks
63
+ * Run it before the tokens are resolved. Only tokens of this tree are present: those queued while rendering a
64
+ * Foreign Subtree's own children end up inside that subtree's HTML, which the browser keeps whole. A token before
65
+ * `<body` stays unwrapped: React never hydrates the document head, and a custom element there would end it.
66
+ */
67
+ export declare function wrapForeignSubtreeTokens(html: string, runtimeContext: ReactForeignSubtreeResolutionContext | undefined): string;
68
+ /**
69
+ * Replaces each Foreign Subtree token in `html` with `replacement`, to inspect the shape of the tree before the
70
+ * tokens resolve.
71
+ *
72
+ * @remarks
73
+ * A token is text until it resolves, so a root-level Foreign Subtree would hide a single root. The boundary or the
74
+ * owner's element takes its place, hence the caller passes an element.
75
+ */
76
+ export declare function replaceForeignSubtreeTokens(html: string, runtimeContext: ReactForeignSubtreeResolutionContext | undefined, replacement: string): string;
@@ -2,6 +2,7 @@ import { isValidElement } from 'react';
2
2
  import { asReactComponent } from './component-ownership.js';
3
3
  import { ReactRenderError } from './errors.js';
4
4
  import { renderReactHtml } from './react-runtime.js';
5
+ import { getForeignSubtreeKey, renderForeignSubtreeBoundary } from '../hydration/foreign-subtree.js';
5
6
  export function buildHydrationProps(props) {
6
7
  if (!props || !Object.prototype.hasOwnProperty.call(props, 'locals')) {
7
8
  return props ?? {};
@@ -73,3 +74,39 @@ export function restoreRuntimeChildHtml(html, runtimeContext) {
73
74
  }
74
75
  return html.split(runtimeContext.rawChildrenToken).join(runtimeContext.rawChildrenHtml);
75
76
  }
77
+ /**
78
+ * Wraps each Foreign Subtree token React rendered in `html` in the boundary element hydration keeps.
79
+ *
80
+ * @remarks
81
+ * Run it before the tokens are resolved. Only tokens of this tree are present: those queued while rendering a
82
+ * Foreign Subtree's own children end up inside that subtree's HTML, which the browser keeps whole. A token before
83
+ * `<body` stays unwrapped: React never hydrates the document head, and a custom element there would end it.
84
+ */
85
+ export function wrapForeignSubtreeTokens(html, runtimeContext) {
86
+ let wrappedHtml = html;
87
+ for (const { token, component, props } of runtimeContext?.queuedResolutions ?? []) {
88
+ const tokenIndex = wrappedHtml.indexOf(token);
89
+ const bodyIndex = wrappedHtml.indexOf('<body');
90
+ if (tokenIndex < 0 || (bodyIndex >= 0 && tokenIndex < bodyIndex))
91
+ continue;
92
+ wrappedHtml = wrappedHtml
93
+ .split(token)
94
+ .join(renderForeignSubtreeBoundary(getForeignSubtreeKey(component, props), token));
95
+ }
96
+ return wrappedHtml;
97
+ }
98
+ /**
99
+ * Replaces each Foreign Subtree token in `html` with `replacement`, to inspect the shape of the tree before the
100
+ * tokens resolve.
101
+ *
102
+ * @remarks
103
+ * A token is text until it resolves, so a root-level Foreign Subtree would hide a single root. The boundary or the
104
+ * owner's element takes its place, hence the caller passes an element.
105
+ */
106
+ export function replaceForeignSubtreeTokens(html, runtimeContext, replacement) {
107
+ let replaced = html;
108
+ for (const { token } of runtimeContext?.queuedResolutions ?? []) {
109
+ replaced = replaced.split(token).join(replacement);
110
+ }
111
+ return replaced;
112
+ }
@@ -2,6 +2,7 @@ import * as bundledReact from 'react';
2
2
  import type { FunctionComponent, ReactElement } from 'react';
3
3
  import type { EcoComponent, EcoPageLayoutEntry, LayoutPropsContext } from '@ecopages/core';
4
4
  import type { EcoComponentConfig } from '@ecopages/core';
5
+ import type { LayoutRenderTracker } from './layout-render-tracker.js';
5
6
  export type LayoutComposeContext = LayoutPropsContext;
6
7
  export type ReactRuntime = typeof bundledReact;
7
8
  export type LayoutComposeOptions = {
@@ -9,13 +10,14 @@ export type LayoutComposeOptions = {
9
10
  /** @remarks Pass the app-resolved React runtime during SSR so composition uses the same React instance as server rendering. */
10
11
  react?: ReactRuntime;
11
12
  /**
12
- * Optional resolver that substitutes cached layout instances and React keys
13
- * for SPA layout persistence.
13
+ * Optional resolver that substitutes layout instances and React keys per tier.
14
14
  */
15
15
  resolvePersistedTier?: (layout: EcoComponent, index: number) => {
16
16
  layout: EcoComponent;
17
17
  key?: string;
18
18
  };
19
+ /** Records which tiers render, so a server render can tell a layout that drops its children. */
20
+ renderTracker?: LayoutRenderTracker;
19
21
  };
20
22
  export type LayoutShellEntry = {
21
23
  component: EcoComponent;
@@ -83,7 +83,8 @@ export function assertComposablePage(Page) {
83
83
  export function composeLayoutPageTree(Page, pageProps, options) {
84
84
  const { createElement } = resolveReact(options);
85
85
  const context = options?.context ?? resolveLayoutContext(pageProps);
86
- const pageElement = createElement(Page, pageProps);
86
+ const tracker = options?.renderTracker;
87
+ const pageElement = createElement(tracker ? tracker.trackPage(Page) : Page, pageProps);
87
88
  const layoutEntries = Page.config?.layoutEntries;
88
89
  const resolvePersistedTier = options?.resolvePersistedTier;
89
90
  if (layoutEntries && layoutEntries.length > 0) {
@@ -91,7 +92,7 @@ export function composeLayoutPageTree(Page, pageProps, options) {
91
92
  const index = layoutEntries.length - 1 - reverseIndex;
92
93
  const layoutProps = resolveLayoutEntryProps(entry, context);
93
94
  const tier = resolvePersistedTier?.(entry.component, index);
94
- const Layout = toReactComponent(tier?.layout ?? entry.component);
95
+ const Layout = toTrackedReactComponent(tier?.layout ?? entry.component, index, tracker);
95
96
  const elementProps = tier?.key ? { key: tier.key, ...layoutProps } : layoutProps;
96
97
  return createElement(Layout, elementProps, children);
97
98
  }, pageElement);
@@ -102,13 +103,17 @@ export function composeLayoutPageTree(Page, pageProps, options) {
102
103
  return [...layouts].reverse().reduce((children, Layout, reverseIndex) => {
103
104
  const index = layouts.length - 1 - reverseIndex;
104
105
  const tier = resolvePersistedTier?.(Layout, index);
105
- const ResolvedLayout = toReactComponent(tier?.layout ?? Layout);
106
+ const ResolvedLayout = toTrackedReactComponent(tier?.layout ?? Layout, index, tracker);
106
107
  const elementProps = tier?.key ? { key: tier.key, ...layoutProps } : layoutProps;
107
108
  return createElement(ResolvedLayout, elementProps, children);
108
109
  }, pageElement);
109
110
  }
110
111
  return pageElement;
111
112
  }
113
+ function toTrackedReactComponent(component, index, tracker) {
114
+ const Layout = toReactComponent(component);
115
+ return tracker ? tracker.trackLayout(Layout, index) : Layout;
116
+ }
112
117
  /**
113
118
  * Builds a layout tree from explicit document-shell layout entries.
114
119
  *
@@ -121,9 +126,11 @@ export function composeLayoutPageTreeFromShell(Page, pageProps, shellLayouts, op
121
126
  if (shellLayouts.length === 0) {
122
127
  return composeLayoutPageTree(Page, pageProps, options);
123
128
  }
124
- const pageElement = createElement(Page, pageProps);
125
- return [...shellLayouts].reverse().reduce((children, entry) => {
126
- return createElement(toReactComponent(entry.component), entry.props ?? {}, children);
129
+ const tracker = options?.renderTracker;
130
+ const pageElement = createElement(tracker ? tracker.trackPage(Page) : Page, pageProps);
131
+ return [...shellLayouts].reverse().reduce((children, entry, reverseIndex) => {
132
+ const index = shellLayouts.length - 1 - reverseIndex;
133
+ return createElement(toTrackedReactComponent(entry.component, index, tracker), entry.props ?? {}, children);
127
134
  }, pageElement);
128
135
  }
129
136
  /**
@@ -0,0 +1,20 @@
1
+ import type { EcoComponent } from '@ecopages/core';
2
+ import { LayoutChildrenNotRenderedError } from '@ecopages/core/integration';
3
+ import type { FunctionComponent } from 'react';
4
+ /**
5
+ * Records the layout tiers and the page a React render reaches.
6
+ *
7
+ * @remarks
8
+ * A tier is wrapped in a function that records it and then calls the tier directly, so the tree keeps its
9
+ * depth and `useId` values match the browser's. Use it for server renders only.
10
+ */
11
+ export declare class LayoutRenderTracker {
12
+ private readonly renderedLayouts;
13
+ private pageRendered;
14
+ trackLayout(component: FunctionComponent<Record<string, unknown>>, index: number): FunctionComponent<Record<string, unknown>>;
15
+ trackPage<P extends Record<string, unknown>>(Page: FunctionComponent<P>): FunctionComponent<P>;
16
+ /**
17
+ * Returns the error for the innermost rendered layout when the page did not render.
18
+ */
19
+ findLayoutWithoutChildren(page: EcoComponent): LayoutChildrenNotRenderedError | undefined;
20
+ }
@@ -0,0 +1,33 @@
1
+ import { LayoutChildrenNotRenderedError } from '@ecopages/core/integration';
2
+ /**
3
+ * Records the layout tiers and the page a React render reaches.
4
+ *
5
+ * @remarks
6
+ * A tier is wrapped in a function that records it and then calls the tier directly, so the tree keeps its
7
+ * depth and `useId` values match the browser's. Use it for server renders only.
8
+ */
9
+ export class LayoutRenderTracker {
10
+ renderedLayouts = new Map();
11
+ pageRendered = false;
12
+ trackLayout(component, index) {
13
+ return (props) => {
14
+ this.renderedLayouts.set(index, component);
15
+ return component(props);
16
+ };
17
+ }
18
+ trackPage(Page) {
19
+ return (props) => {
20
+ this.pageRendered = true;
21
+ return Page(props);
22
+ };
23
+ }
24
+ /**
25
+ * Returns the error for the innermost rendered layout when the page did not render.
26
+ */
27
+ findLayoutWithoutChildren(page) {
28
+ if (this.pageRendered || this.renderedLayouts.size === 0)
29
+ return undefined;
30
+ const innermost = Math.max(...this.renderedLayouts.keys());
31
+ return LayoutChildrenNotRenderedError.forLayout(this.renderedLayouts.get(innermost), page);
32
+ }
33
+ }
@@ -1,14 +1,5 @@
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
1
  import type { EcoComponent } from '@ecopages/core';
2
+ import type { IntegrationRendererRenderOptions } from '@ecopages/core/integration';
12
3
  import { type IntegrationRendererOptions } from '@ecopages/core/integration';
13
4
  import type { ReactNode } from 'react';
14
5
  import type { ReactRendererConfig } from '../plugin/react.types.js';
@@ -53,7 +44,25 @@ export declare class ReactRenderer extends ReactIntegrationRenderer {
53
44
  private getRouterDocumentAttributes;
54
45
  protected resolveReactRuntimeModules(): ReactRuntimeModules;
55
46
  private getReactRuntimeModules;
47
+ /**
48
+ * Renders the route with the Page's hydration decision available to every Layout and document it composes.
49
+ *
50
+ * @remarks
51
+ * A Layout or document is rendered on its own when the Page has Foreign Children, and its config does not say
52
+ * whether the Page hydrates; only the Page's does.
53
+ */
54
+ render(options: IntegrationRendererRenderOptions<ReactNode>): Promise<import("@ecopages/core/integration").RouteRendererBody>;
56
55
  private renderReactTree;
56
+ /**
57
+ * Whether the browser hydrates the tree of the Page `component`.
58
+ *
59
+ * @remarks
60
+ * It reads the Page's own config, which holds the modules of its Layouts and nested Components.
61
+ */
62
+ private hydratesPageTree;
63
+ /**
64
+ * Resolves the Foreign Subtree tokens in `html`, wrapping them in the hydration boundary only when `hydrates`.
65
+ */
57
66
  private resolveReactQueuedForeignSubtreeHtml;
58
67
  private renderQueuedChildrenToHtml;
59
68
  private buildPagePayload;
@@ -101,5 +110,14 @@ export declare class ReactRenderer extends ReactIntegrationRenderer {
101
110
  }): ((context: DocumentShellComposeChildrenContext) => Promise<DocumentShellComposeChildrenResult>) | undefined;
102
111
  private buildDocumentShellProps;
103
112
  private getHtmlDocumentContributionsHook;
113
+ /**
114
+ * Publishes the props of a hydrating Page that has no router.
115
+ *
116
+ * @remarks
117
+ * A router's Html shell emits `__ECO_PAGE_DATA__` itself (`EcoPropsScript`). Without a router nothing does, so the
118
+ * hydration entry and a direct HMR update would read empty props. The script is a head contribution, whatever
119
+ * Integration owns the Html template, and only a Page the browser hydrates gets it.
120
+ */
121
+ private buildRouterlessPageDataContributions;
104
122
  private getDocumentAttributesHook;
105
123
  }