@ecopages/react 0.4.0 → 0.5.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 (36) hide show
  1. package/README.md +21 -6
  2. package/package.json +10 -10
  3. package/src/client-graph/reachability-analyzer.d.ts +1 -2
  4. package/src/client-graph/reachability-analyzer.js +2 -4
  5. package/src/client-graph/reachability-client-roots.d.ts +1 -8
  6. package/src/client-graph/reachability-client-roots.js +8 -25
  7. package/src/client-graph/reachability-top-level-index.d.ts +1 -2
  8. package/src/client-graph/reachability-top-level-index.js +7 -11
  9. package/src/content/lazy-collection-components.d.ts +38 -0
  10. package/src/content/lazy-collection-components.js +104 -0
  11. package/src/hydration/browser/page-hydration-hmr.js +8 -13
  12. package/src/hydration/browser/page-hydration-module.d.ts +2 -6
  13. package/src/hydration/browser/page-hydration-module.js +3 -9
  14. package/src/hydration/browser/page-hydration.d.ts +8 -6
  15. package/src/hydration/browser/page-hydration.js +120 -50
  16. package/src/hydration/compiled-page-hydration-options.d.ts +0 -1
  17. package/src/hydration/hydration-asset.d.ts +5 -10
  18. package/src/hydration/hydration-asset.js +11 -54
  19. package/src/hydration/hydration-page-entry-source.js +8 -10
  20. package/src/plugin/react.constants.d.ts +4 -0
  21. package/src/plugin/react.constants.js +4 -0
  22. package/src/plugin/react.plugin.js +11 -2
  23. package/src/plugin/react.types.d.ts +23 -0
  24. package/src/render/component-ssr.d.ts +5 -6
  25. package/src/render/component-ssr.js +8 -9
  26. package/src/render/errors.d.ts +1 -1
  27. package/src/render/errors.js +2 -2
  28. package/src/render/layout-compose.d.ts +1 -1
  29. package/src/render/react-renderer.d.ts +2 -11
  30. package/src/render/react-renderer.js +30 -65
  31. package/src/render/react-runtime.d.ts +50 -2
  32. package/src/render/react-runtime.js +131 -1
  33. package/src/client-graph/reachability-preload.d.ts +0 -10
  34. package/src/client-graph/reachability-preload.js +0 -30
  35. package/src/content/collection-component-cache.d.ts +0 -25
  36. package/src/content/collection-component-cache.js +0 -62
@@ -6,7 +6,7 @@
6
6
  * module owns document state, navigation ownership, cleanup, and HMR so those
7
7
  * behaviors stay identical for readable and compiled bootstraps.
8
8
  */
9
- export { resolvePageModule } from './page-hydration-module.js';
9
+ export { resolvePageComponent } from './page-hydration-module.js';
10
10
  import { handlePageHmr } from './page-hydration-hmr.js';
11
11
  /** Returns and lazily initializes the shared page runtime on `window`. */
12
12
  function getRuntime() {
@@ -35,25 +35,34 @@ function setPageState(options, pageData) {
35
35
  };
36
36
  }
37
37
  /**
38
- * Invalidates pending startup, releases the page root, and hands navigation
39
- * ownership back to the document runtime.
38
+ * Unmounts a page root when it is still mounted.
40
39
  *
41
40
  * @remarks
42
- * Incrementing the generation prevents an already-running preload from
43
- * hydrating after cleanup. The pending promise is cleared so a later page can
44
- * start independently while the old preload settles.
41
+ * React may already have unmounted the root for an uncaught error before
42
+ * cleanup runs.
43
+ */
44
+ function unmountPageRoot(root) {
45
+ try {
46
+ root?.unmount();
47
+ }
48
+ catch {
49
+ return;
50
+ }
51
+ }
52
+ /**
53
+ * Invalidates pending HMR updates, releases the page root, and hands navigation
54
+ * ownership back to the document runtime.
45
55
  */
46
56
  function cleanupPageRoot(root) {
47
57
  const runtime = getRuntime();
48
58
  if (runtime.react) {
49
59
  runtime.react.mountGeneration = (runtime.react.mountGeneration ?? 0) + 1;
50
- delete runtime.react.mountPromise;
51
60
  }
52
61
  const activeRoot = runtime.react?.pageRoot || root;
53
62
  runtime.react.pageRoot = null;
54
63
  runtime.navigation?.releaseOwnership?.('react-router');
55
64
  delete runtime.page;
56
- activeRoot?.unmount();
65
+ unmountPageRoot(activeRoot);
57
66
  }
58
67
  /** Registers React Router as the page navigation owner when this page uses it. */
59
68
  function registerRouterOwnership(options) {
@@ -70,18 +79,7 @@ function registerRouterOwnership(options) {
70
79
  runtime.navigation?.claimOwnership?.('react-router');
71
80
  }
72
81
  /**
73
- * Checks whether asynchronous work still belongs to the current page instance.
74
- *
75
- * @remarks
76
- * Cleanup increments this token before unmounting. Any import or preload that
77
- * settles afterward must leave the document alone, even if a new page has
78
- * already mounted a root in the same global runtime slot.
79
- */
80
- function isCurrentMountGeneration(generation) {
81
- return (getRuntime().react?.mountGeneration ?? 0) === generation;
82
- }
83
- /**
84
- * Registers HMR before initial preload and binds it to this page generation.
82
+ * Registers HMR before the page mounts and binds it to this page generation.
85
83
  *
86
84
  * @remarks
87
85
  * The global handler index can outlive the page. Capturing the generation here
@@ -98,31 +96,79 @@ function registerHmr(options) {
98
96
  runtime.hmrHandlers[options.hmr.importPath] = (newUrl) => handlePageHmr(options, newUrl, generation, readPageData, setPageState, (opts) => opts.pageDataReader.getPageDataFromDocument());
99
97
  }
100
98
  /**
101
- * Coalesces concurrent page starts into one promise.
99
+ * Returns the target's children that were not there before `hydrateRoot`.
102
100
  *
103
101
  * @remarks
104
- * Rerun scripts and DOM-ready callbacks can arrive together. Sharing the
105
- * pending promise prevents two calls to `hydrateRoot` for document.body.
102
+ * Call it before unmounting: unmounting a root React already tore down clears
103
+ * the body, sparing only scripts, styles and stylesheet links.
106
104
  */
107
- async function mount(options) {
108
- const runtime = getRuntime();
109
- const reactRuntime = runtime.react;
110
- if (reactRuntime.mountPromise)
111
- return reactRuntime.mountPromise;
112
- const generation = reactRuntime.mountGeneration ?? 0;
113
- const pendingMount = mountPage(options, generation);
114
- reactRuntime.mountPromise = pendingMount;
115
- pendingMount.then(() => {
116
- if (reactRuntime.mountPromise === pendingMount)
117
- delete reactRuntime.mountPromise;
118
- }, () => {
119
- if (reactRuntime.mountPromise === pendingMount)
120
- delete reactRuntime.mountPromise;
121
- });
122
- return pendingMount;
105
+ function findAddedNodes(target, serverNodes) {
106
+ return Array.from(target.childNodes).filter((node) => !serverNodes.includes(node));
107
+ }
108
+ /**
109
+ * Puts the server children back in their original order, followed by `addedNodes`.
110
+ *
111
+ * @remarks
112
+ * A server child still attached (React spares scripts, styles and stylesheet
113
+ * links when it clears the body) stays as is, so a stylesheet is not fetched
114
+ * again; every other one comes back as its pre-`hydrateRoot` clone.
115
+ */
116
+ function restoreChildNodes(target, serverNodes, serverClones, addedNodes) {
117
+ target.replaceChildren(...serverNodes.map((node, index) => (node.parentNode === target ? node : serverClones[index])), ...addedNodes);
123
118
  }
124
- /** Performs one page start after the caller has reserved the current generation. */
125
- async function mountPage(options, generation) {
119
+ /**
120
+ * Makes this Page's HMR handler reject so the HMR client reloads the document.
121
+ *
122
+ * @remarks
123
+ * Restoring bumps the mount generation, so the registered handler would return
124
+ * without rendering and the client would count the edit as applied. Deleting
125
+ * the entry is not enough: the page module is a dev-transform URL, and the
126
+ * client imports an unhandled one that is not the active page module and also
127
+ * counts it as applied.
128
+ */
129
+ function requireReloadForHmr(options) {
130
+ const handlers = getRuntime().hmrHandlers;
131
+ if (!options.hmr || !handlers)
132
+ return;
133
+ handlers[options.hmr.importPath] = async () => {
134
+ throw new Error('The React Page root failed and its server HTML was restored; reloading to apply the update');
135
+ };
136
+ }
137
+ /** The path and query of the document, without the fragment, which does not change the Page. */
138
+ function currentDocumentUrl() {
139
+ return `${window.location.pathname}${window.location.search}`;
140
+ }
141
+ /** Logs the component stack that React's default uncaught error reporter would print. */
142
+ function logUncaughtError(error, componentStack) {
143
+ const message = error instanceof Error ? error.message : String(error);
144
+ console.error(`[ecopages] Uncaught error in the React Page: ${message}${componentStack ?? ''}`);
145
+ }
146
+ /**
147
+ * Hydrates the page, or re-renders it when a root already exists.
148
+ *
149
+ * @remarks
150
+ * Starting is synchronous, so rerun scripts and DOM-ready callbacks that arrive
151
+ * together cannot call `hydrateRoot` twice for document.body: the second sees
152
+ * the root the first created.
153
+ *
154
+ * React tears the root down after any uncaught error, such as a `React.lazy`
155
+ * chunk that never loads with no Page-level error boundary, and would leave the
156
+ * body empty. This snapshots the target before `hydrateRoot` and puts that
157
+ * server HTML back on a microtask after `onUncaughtError`: the Page stays
158
+ * readable but not interactive, and an HMR update reloads the document.
159
+ * `React.lazy` caches a rejection, so nothing is retried.
160
+ *
161
+ * Restore is not limited to hydration itself: it covers any uncaught error on
162
+ * the first-loaded Page until `root.render` (a rerun or HMR update), `unmount`
163
+ * or a change of URL disarms it, so a stale snapshot cannot come back. The
164
+ * router changes Pages inside the same root, so the URL is what shows it has
165
+ * navigated; after that a Page render error becomes a full navigation, and an
166
+ * error outside the Page leaves React's own handling.
167
+ *
168
+ * Providing `onUncaughtError` replaces React's default reporter, so it still
169
+ * calls `reportError` and logs the component stack.
170
+ */
171
+ function mount(options) {
126
172
  const runtime = getRuntime();
127
173
  const pageData = readPageData(options);
128
174
  setPageState(options, pageData);
@@ -132,16 +178,40 @@ async function mountPage(options, generation) {
132
178
  }
133
179
  return;
134
180
  }
135
- await options.preload?.(pageData.props);
136
- if (!isCurrentMountGeneration(generation))
137
- return;
138
- if (runtime.react?.pageRoot)
139
- return;
140
181
  window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
141
- const root = options.runtime.hydrateRoot(document.body, options.createTree(options.Page, pageData.props), {
182
+ const target = document.body;
183
+ const serverNodes = Array.from(target.childNodes);
184
+ const serverClones = serverNodes.map((node) => node.cloneNode(true));
185
+ const serverUrl = currentDocumentUrl();
186
+ let allowRestore = true;
187
+ let root;
188
+ const restoreServerHtml = () => {
189
+ if (!allowRestore || currentDocumentUrl() !== serverUrl)
190
+ return;
191
+ allowRestore = false;
192
+ const addedNodes = findAddedNodes(target, serverNodes);
193
+ cleanupPageRoot(runtime.react?.pageRoot ?? root ?? null);
194
+ requireReloadForHmr(options);
195
+ restoreChildNodes(target, serverNodes, serverClones, addedNodes);
196
+ };
197
+ root = options.runtime.hydrateRoot(target, options.createTree(options.Page, pageData.props), {
142
198
  onRecoverableError: (error) => console.warn('[ecopages] Hydration error:', error),
199
+ onUncaughtError: (error, errorInfo) => {
200
+ reportError(error);
201
+ logUncaughtError(error, errorInfo.componentStack);
202
+ queueMicrotask(restoreServerHtml);
203
+ },
143
204
  });
144
- runtime.react.pageRoot = root;
205
+ runtime.react.pageRoot = {
206
+ render: (tree) => {
207
+ allowRestore = false;
208
+ root.render(tree);
209
+ },
210
+ unmount: () => {
211
+ allowRestore = false;
212
+ unmountPageRoot(root);
213
+ },
214
+ };
145
215
  recordHydrationTiming();
146
216
  }
147
217
  /**
@@ -164,7 +234,7 @@ export function startPageHydration(options) {
164
234
  runtime.react.cleanupPageRoot = () => cleanupPageRoot(runtime.react?.pageRoot ?? null);
165
235
  registerRouterOwnership(options);
166
236
  registerHmr(options);
167
- return mount(options);
237
+ mount(options);
168
238
  };
169
239
  runtime.rerunScripts ??= {};
170
240
  runtime.rerunScripts[options.scriptId] = activatePage;
@@ -172,6 +242,6 @@ export function startPageHydration(options) {
172
242
  document.addEventListener('DOMContentLoaded', activatePage, { once: true });
173
243
  }
174
244
  else {
175
- void activatePage();
245
+ activatePage();
176
246
  }
177
247
  }
@@ -15,6 +15,5 @@ export type CompiledPageHydrationOptions = {
15
15
  routerPropsExpression?: string;
16
16
  hmrEnabled: boolean;
17
17
  isMdx: boolean;
18
- hasPagePreload: boolean;
19
18
  minify: boolean;
20
19
  };
@@ -33,7 +33,6 @@ type PageDependencyOptions = {
33
33
  hmrEnabled: boolean;
34
34
  useBrowserRuntimeImports: boolean;
35
35
  isMdx: boolean;
36
- hasPagePreload?: boolean;
37
36
  };
38
37
  /**
39
38
  * Derives the stable component key used by asset grouping and host selectors.
@@ -85,16 +84,13 @@ export declare class HydrationAssetService {
85
84
  * Production reads island module URLs from processed grouped-build outputs.
86
85
  * HMR keeps per-file transform URLs and does not start a disk bundle.
87
86
  */
88
- buildPageClientRenderAssets(input: {
87
+ buildPageClientAssets(input: {
89
88
  islands: Array<{
90
89
  file: string;
91
90
  config?: EcoComponentConfig;
92
91
  }>;
93
92
  lazyEntries?: AssetDefinition[];
94
- }): Promise<{
95
- assetsByFile: Map<string, ProcessedAsset[]>;
96
- processedAssets: ProcessedAsset[];
97
- }>;
93
+ }): Promise<ProcessedAsset[]>;
98
94
  /** Collects React island hydration entries for the production app browser build. */
99
95
  collectAppBrowserClientBuildEntries(islands: Array<{
100
96
  file: string;
@@ -102,13 +98,12 @@ export declare class HydrationAssetService {
102
98
  }>): Promise<PageClientBuildEntry[]>;
103
99
  /** Keeps one entry per component; a file that declares several island components keeps each of them. */
104
100
  private uniqueIslands;
105
- private buildHmrPageClientRenderAssets;
106
- private buildGroupedPageClientRenderAssets;
101
+ private buildHmrPageClientAssets;
102
+ private buildGroupedPageClientAssets;
107
103
  private createGroupedIslandEntries;
108
104
  private indexSrcUrlsByEntryName;
109
105
  private createGroupedHydrationScripts;
110
- private collectIslandAssetsByFile;
111
- private buildHmrIslandRenderAssets;
106
+ private buildHmrIslandAssets;
112
107
  private createIslandHydrationScript;
113
108
  /**
114
109
  * Creates the page browser graph dependency declarations for a React page.
@@ -14,8 +14,6 @@ import { APP_BROWSER_CLIENT_BUNDLE_ID, AssetFactory, createAppBrowserClientEntry
14
14
  import { IslandHydrationScriptCompiler, PageHydrationScriptCompiler } from './hydration-script-compiler.js';
15
15
  import { resolveHydrationBootstrapImports } from './bootstrap-imports.js';
16
16
  import { collectDeclaredModulesInConfig } from '../client-graph/declared-modules.js';
17
- import { hasPagePreloadExport } from '../client-graph/reachability-analyzer.js';
18
- import { fileSystem } from '@ecopages/file-system';
19
17
  /**
20
18
  * Derives the stable component key used by asset grouping and host selectors.
21
19
  *
@@ -82,7 +80,7 @@ export class HydrationAssetService {
82
80
  * HMR entries remain separate ESM scripts with browser-resolvable imports.
83
81
  */
84
82
  async createPageDependencies(options) {
85
- const { pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, hmrEnabled, useBrowserRuntimeImports, isMdx, hasPagePreload, } = options;
83
+ const { pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, hmrEnabled, useBrowserRuntimeImports, isMdx, } = options;
86
84
  const runtimeImports = this.config.bundleService.getRuntimeImports();
87
85
  const groupedBundle = !hmrEnabled && this.config.routerAdapter
88
86
  ? {
@@ -108,7 +106,6 @@ export class HydrationAssetService {
108
106
  routerPropsExpression: this.config.routerAdapter?.getRouterProps('Page', 'props'),
109
107
  hmrEnabled,
110
108
  isMdx,
111
- hasPagePreload: hasPagePreload === true,
112
109
  minify: !hmrEnabled && isReactProductionRuntime(),
113
110
  });
114
111
  return [
@@ -144,16 +141,16 @@ export class HydrationAssetService {
144
141
  * Production reads island module URLs from processed grouped-build outputs.
145
142
  * HMR keeps per-file transform URLs and does not start a disk bundle.
146
143
  */
147
- async buildPageClientRenderAssets(input) {
144
+ async buildPageClientAssets(input) {
148
145
  if (!this.config.assetProcessingService) {
149
- return { assetsByFile: new Map(), processedAssets: [] };
146
+ return [];
150
147
  }
151
148
  const uniqueIslands = this.uniqueIslands(input.islands);
152
149
  const hmrEnabled = this.config.assetProcessingService.getHmrManager()?.isEnabled() ?? false;
153
150
  if (hmrEnabled) {
154
- return this.buildHmrPageClientRenderAssets(uniqueIslands, input.lazyEntries);
151
+ return this.buildHmrPageClientAssets(uniqueIslands, input.lazyEntries);
155
152
  }
156
- return this.buildGroupedPageClientRenderAssets(uniqueIslands, input.lazyEntries);
153
+ return this.buildGroupedPageClientAssets(uniqueIslands, input.lazyEntries);
157
154
  }
158
155
  /** Collects React island hydration entries for the production app browser build. */
159
156
  async collectAppBrowserClientBuildEntries(islands) {
@@ -180,7 +177,6 @@ export class HydrationAssetService {
180
177
  },
181
178
  bundleOptions,
182
179
  },
183
- islandFile: island.file,
184
180
  });
185
181
  }
186
182
  return entries;
@@ -199,21 +195,18 @@ export class HydrationAssetService {
199
195
  }
200
196
  return uniqueIslands;
201
197
  }
202
- async buildHmrPageClientRenderAssets(uniqueIslands, lazyEntries) {
203
- const assetsByFile = new Map();
198
+ async buildHmrPageClientAssets(uniqueIslands, lazyEntries) {
204
199
  const processedAssets = [];
205
200
  for (const island of uniqueIslands) {
206
201
  this.config.hmrPageMetadataCache?.markOwnedEntrypoint(island.file);
207
- const assets = await this.buildHmrIslandRenderAssets(island.file, island.config);
208
- assetsByFile.set(island.file, [...(assetsByFile.get(island.file) ?? []), ...assets]);
209
- processedAssets.push(...assets);
202
+ processedAssets.push(...(await this.buildHmrIslandAssets(island.file, island.config)));
210
203
  }
211
204
  if (lazyEntries?.length) {
212
205
  processedAssets.push(...(await this.config.assetProcessingService.processDependencies(lazyEntries, this.config.assetProcessingIntegration)));
213
206
  }
214
- return { assetsByFile, processedAssets };
207
+ return processedAssets;
215
208
  }
216
- async buildGroupedPageClientRenderAssets(uniqueIslands, lazyEntries) {
209
+ async buildGroupedPageClientAssets(uniqueIslands, lazyEntries) {
217
210
  const islandEntries = await this.createGroupedIslandEntries(uniqueIslands);
218
211
  const clientEntries = [...islandEntries, ...(lazyEntries ?? [])];
219
212
  const processedClientEntries = clientEntries.length > 0
@@ -224,10 +217,7 @@ export class HydrationAssetService {
224
217
  const processedHydration = hydrationScripts.length > 0
225
218
  ? await this.config.assetProcessingService.processDependencies(hydrationScripts, this.config.assetProcessingIntegration)
226
219
  : [];
227
- return {
228
- assetsByFile: this.collectIslandAssetsByFile(uniqueIslands, processedClientEntries, processedHydration),
229
- processedAssets: [...processedClientEntries, ...processedHydration],
230
- };
220
+ return [...processedClientEntries, ...processedHydration];
231
221
  }
232
222
  async createGroupedIslandEntries(uniqueIslands) {
233
223
  const islandEntries = [];
@@ -279,31 +269,7 @@ export class HydrationAssetService {
279
269
  }
280
270
  return hydrationScripts;
281
271
  }
282
- collectIslandAssetsByFile(uniqueIslands, processedClientEntries, processedHydration) {
283
- const assetsByFile = new Map();
284
- const hydrationByName = new Map();
285
- for (const processed of processedHydration) {
286
- const name = processed.attributes?.['data-eco-script-id'];
287
- if (!name) {
288
- continue;
289
- }
290
- const existing = hydrationByName.get(name) ?? [];
291
- existing.push(processed);
292
- hydrationByName.set(name, existing);
293
- }
294
- for (const island of uniqueIslands) {
295
- const componentName = this.getIslandBundleName(island.file);
296
- const hydrationName = this.getIslandHydrationName(componentName, getIslandComponentKey(island.file, island.config));
297
- const islandAsset = processedClientEntries.find((processed) => processed.groupedBundle?.entryName === componentName);
298
- const fileAssets = assetsByFile.get(island.file);
299
- assetsByFile.set(island.file, [
300
- ...(fileAssets ?? (islandAsset ? [islandAsset] : [])),
301
- ...(hydrationByName.get(hydrationName) ?? []),
302
- ]);
303
- }
304
- return assetsByFile;
305
- }
306
- async buildHmrIslandRenderAssets(componentFile, config) {
272
+ async buildHmrIslandAssets(componentFile, config) {
307
273
  const importPath = await this.resolveAssetImportPath(componentFile, this.getIslandBundleName(componentFile));
308
274
  const hydrationScript = await this.createIslandHydrationScript(componentFile, config, importPath, true);
309
275
  return this.config.assetProcessingService.processDependencies([hydrationScript], this.config.assetProcessingIntegration);
@@ -363,14 +329,6 @@ export class HydrationAssetService {
363
329
  }
364
330
  const importPath = await this.resolveAssetImportPath(pagePath, componentName);
365
331
  const pageModuleUrlExpression = hmrEnabled ? JSON.stringify(importPath) : 'import.meta.url';
366
- let hasPagePreload = false;
367
- try {
368
- const source = await fileSystem.readFile(pagePath);
369
- hasPagePreload = hasPagePreloadExport(source, pagePath);
370
- }
371
- catch {
372
- hasPagePreload = false;
373
- }
374
332
  const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, isMdx, declaredModules, { includeRuntime: !useBrowserRuntimeImports, splitting: usesRouterRuntime }, pagePath);
375
333
  const dependencies = await this.createPageDependencies({
376
334
  pagePath,
@@ -381,7 +339,6 @@ export class HydrationAssetService {
381
339
  hmrEnabled,
382
340
  useBrowserRuntimeImports,
383
341
  isMdx,
384
- hasPagePreload,
385
342
  });
386
343
  return dependencies;
387
344
  }
@@ -7,16 +7,16 @@ function assertRouterConfiguration(options) {
7
7
  }
8
8
  }
9
9
  function buildPageImport(options) {
10
- if (options.isMdx || options.hasPagePreload) {
10
+ if (options.isMdx) {
11
11
  return `import * as PageModule from ${JSON.stringify(options.importPath)};`;
12
12
  }
13
13
  return `import Page from ${JSON.stringify(options.importPath)};`;
14
14
  }
15
15
  function buildInitialPageBinding(options) {
16
- if (options.isMdx || options.hasPagePreload) {
17
- return `const initialPage = resolvePageModule(PageModule, ${options.isMdx}, ${options.isMdx ? 'ensurePageConfigLayouts' : 'undefined'});`;
16
+ if (options.isMdx) {
17
+ return 'const initialPage = resolvePageComponent(PageModule, true, ensurePageConfigLayouts);';
18
18
  }
19
- return `const initialPage = resolvePageModule({ default: Page }, false);`;
19
+ return 'const initialPage = Page;';
20
20
  }
21
21
  function buildRouterImports(options) {
22
22
  if (!options.routerComponents)
@@ -58,7 +58,7 @@ export function createPageEntrySource(options) {
58
58
  return `
59
59
  import { hydrateRoot } from ${JSON.stringify(options.reactDomClientImportPath)};
60
60
  import { createElement } from ${JSON.stringify(options.reactImportPath)};
61
- import { resolvePageModule, startPageHydration } from ${JSON.stringify(pageBootstrapId)};
61
+ import { resolvePageComponent, startPageHydration } from ${JSON.stringify(pageBootstrapId)};
62
62
  import { readPageDataDocument, getPageDataFromDocument } from ${JSON.stringify(pageDataReaderId)};
63
63
  ${options.routerComponents ? '' : `import { composeLayoutPageTree } from ${JSON.stringify(options.layoutComposeImportPath)};`}
64
64
  ${buildRouterImports(options)}
@@ -67,20 +67,18 @@ ${buildPageImport(options)}
67
67
  const pageModuleUrl = ${options.pageModuleUrlExpression};
68
68
  ${buildInitialPageBinding(options)}
69
69
  ${buildRouterTree(options)}
70
- export default initialPage.Page;
71
- ${options.hasPagePreload ? 'export const preload = initialPage.preload;' : ''}
72
- export const config = initialPage.Page.config;
70
+ export default initialPage;
71
+ export const config = initialPage.config;
73
72
  startPageHydration({
74
73
  scriptId: ${JSON.stringify(options.scriptId)},
75
74
  pageModuleUrl,
76
- Page: initialPage.Page,
75
+ Page: initialPage,
77
76
  pageDataReader: { readPageDataDocument, getPageDataFromDocument },
78
77
  runtime: { hydrateRoot, createElement },
79
78
  createTree,
80
79
  hasRouter: ${Boolean(options.routerComponents)},
81
80
  isMdx: ${options.isMdx},
82
81
  ${options.isMdx ? 'normalizePageConfig: ensurePageConfigLayouts,' : ''}
83
- ${options.hasPagePreload ? 'preload: initialPage.preload,' : ''}
84
82
  ${buildHmrOptions(options)}
85
83
  });
86
84
  `.trim();
@@ -1 +1,5 @@
1
1
  export declare const REACT_PLUGIN_NAME = "react";
2
+ /** React's documented prerender abort delay, used when `reactPlugin()` does not set `renderTimeoutMs`. */
3
+ export declare const REACT_SSR_RENDER_TIMEOUT_MS = 10000;
4
+ /** The longest delay Node's `setTimeout` honours; a longer one fires after 1 ms instead. */
5
+ export declare const REACT_SSR_RENDER_TIMEOUT_MAX_MS = 2147483647;
@@ -1 +1,5 @@
1
1
  export const REACT_PLUGIN_NAME = 'react';
2
+ /** React's documented prerender abort delay, used when `reactPlugin()` does not set `renderTimeoutMs`. */
3
+ export const REACT_SSR_RENDER_TIMEOUT_MS = 10_000;
4
+ /** The longest delay Node's `setTimeout` honours; a longer one fires after 1 ms instead. */
5
+ export const REACT_SSR_RENDER_TIMEOUT_MAX_MS = 2_147_483_647;
@@ -6,7 +6,7 @@ import { requireAppRuntime } from '@ecopages/core/integration';
6
6
  import { IntegrationPlugin, } from '@ecopages/core/integration';
7
7
  import { Logger } from '@ecopages/logger';
8
8
  import path from 'node:path';
9
- import { REACT_PLUGIN_NAME } from './react.constants.js';
9
+ import { REACT_PLUGIN_NAME, REACT_SSR_RENDER_TIMEOUT_MAX_MS } from './react.constants.js';
10
10
  import { ReactRenderer } from '../render/react-renderer.js';
11
11
  import { ReactHmrStrategy } from '../hmr/hmr-strategy.js';
12
12
  import { ReactDevTransformContributor } from '../dev-transform/react-dev-transform-contributor.js';
@@ -21,6 +21,13 @@ const appLogger = new Logger('[ReactPlugin]');
21
21
  */
22
22
  export const PLUGIN_NAME = REACT_PLUGIN_NAME;
23
23
  const resolveReactMdxCompilerOptions = (mdxOptions) => resolveMdxCompilerOptions(mdxOptions, { jsxImportSource: 'react' });
24
+ function assertValidRenderTimeout(renderTimeoutMs) {
25
+ if (renderTimeoutMs === undefined ||
26
+ (Number.isInteger(renderTimeoutMs) && renderTimeoutMs > 0 && renderTimeoutMs <= REACT_SSR_RENDER_TIMEOUT_MAX_MS)) {
27
+ return;
28
+ }
29
+ throw new RangeError(`reactPlugin({ renderTimeoutMs }) must be a whole number of milliseconds from 1 to ${REACT_SSR_RENDER_TIMEOUT_MAX_MS}, got ${renderTimeoutMs}.`);
30
+ }
24
31
  /**
25
32
  * Resolves user-facing React plugin options into the internal plugin config.
26
33
  *
@@ -31,7 +38,8 @@ const resolveReactMdxCompilerOptions = (mdxOptions) => resolveMdxCompilerOptions
31
38
  * - `mdx.extensions`: `['.mdx']`
32
39
  */
33
40
  const resolveReactPluginOptions = (options) => {
34
- const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, runtimeModules, ...baseConfig } = options ?? {};
41
+ const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, runtimeModules, renderTimeoutMs, ...baseConfig } = options ?? {};
42
+ assertValidRenderTimeout(renderTimeoutMs);
35
43
  const extensions = [...(userExtensions ?? ['.tsx'])];
36
44
  const mdxEnabled = mdx !== undefined;
37
45
  const mdxExtensions = mdx?.extensions ?? ['.mdx'];
@@ -45,6 +53,7 @@ const resolveReactPluginOptions = (options) => {
45
53
  mdxExtensions,
46
54
  hmrPageMetadataCache: new HmrPageMetadataCache(),
47
55
  forceBrowserGraph: explicitGraph ?? false,
56
+ renderTimeoutMs,
48
57
  };
49
58
  return {
50
59
  ...baseConfig,
@@ -80,6 +80,21 @@ export type ReactPluginOptions = {
80
80
  * ```
81
81
  */
82
82
  mdx?: ReactMdxOptions;
83
+ /**
84
+ * How long server rendering waits for Suspense before serving unfinished
85
+ * boundaries as their fallback.
86
+ *
87
+ * @remarks
88
+ * React's documented prerender abort delay is 10 seconds. One limit covers
89
+ * every React tree of a Page render. A `React.lazy()` import or suspending
90
+ * promise that never settles then leaves that boundary in its fallback for
91
+ * the browser to retry; the rest of the Page is served. A tree still waiting
92
+ * outside every boundary fails the render. Must be a whole number from 1 to
93
+ * 2147483647, the longest Node timer delay.
94
+ *
95
+ * @default 10000
96
+ */
97
+ renderTimeoutMs?: number;
83
98
  };
84
99
  export type ReactRendererConfig = {
85
100
  routerAdapter?: ReactRouterAdapter;
@@ -103,4 +118,12 @@ export type ReactRendererConfig = {
103
118
  * client-graph AST strip of server-only `eco.page(...)` options.
104
119
  */
105
120
  forceBrowserGraph?: boolean;
121
+ /**
122
+ * How long server rendering waits for Suspense, in milliseconds.
123
+ *
124
+ * @remarks
125
+ * Mapped from the public `renderTimeoutMs` plugin option. Unfinished
126
+ * boundaries are served as their fallback when the limit fires.
127
+ */
128
+ renderTimeoutMs?: number;
106
129
  };
@@ -1,15 +1,12 @@
1
1
  /**
2
- * React component SSR helpers: renderToString, foreign-subtree HTML, island attributes.
3
- */
4
- /**
5
- * React component SSR helpers: renderToString, foreign-subtree HTML, island attributes.
2
+ * React component SSR helpers: component HTML, foreign-subtree HTML, island attributes.
6
3
  */
7
4
  import type { EcoComponent, EcoPagesElement } from '@ecopages/core';
8
5
  import type { ComponentRenderInput } from '@ecopages/core/integration';
9
6
  import type { IntegrationRenderer } from '@ecopages/core/integration';
10
7
  import type { ReactNode } from 'react';
11
8
  import { type SerializableProps } from './component-ownership.js';
12
- import type { ReactRuntimeModules } from './react-runtime.js';
9
+ import { type ReactRuntimeModules } from './react-runtime.js';
13
10
  export type ReactComponentRenderContext = {
14
11
  componentInstanceId?: string;
15
12
  };
@@ -46,7 +43,9 @@ export declare function renderComponentHtml(options: {
46
43
  context: ReactComponentRenderContext;
47
44
  runtimeContext?: ReactForeignSubtreeResolutionContext;
48
45
  runtime: ReactRuntimeModules;
49
- }): string;
46
+ timeoutMs: number;
47
+ label: string;
48
+ }): Promise<string>;
50
49
  export declare function toReactNode(children: unknown, integrationName: string): ReactNode;
51
50
  /**
52
51
  * Restores raw child HTML placeholders stored on the foreign-subtree runtime context.
@@ -1,9 +1,7 @@
1
- /**
2
- * React component SSR helpers: renderToString, foreign-subtree HTML, island attributes.
3
- */
4
1
  import { isValidElement } from 'react';
5
2
  import { asReactComponent } from './component-ownership.js';
6
3
  import { ReactRenderError } from './errors.js';
4
+ import { renderReactHtml } from './react-runtime.js';
7
5
  export function buildHydrationProps(props) {
8
6
  if (!props || !Object.prototype.hasOwnProperty.call(props, 'locals')) {
9
7
  return props ?? {};
@@ -31,14 +29,15 @@ export async function renderNonReactShellComponent(Component, props, label) {
31
29
  * React would escape it. This helper renders a unique token through React and swaps
32
30
  * that token back to the resolved HTML afterward.
33
31
  */
34
- export function renderComponentHtml(options) {
35
- const { input, context, runtimeContext, runtime } = options;
36
- const { react, reactDomServer } = runtime;
32
+ export async function renderComponentHtml(options) {
33
+ const { input, context, runtimeContext, runtime, timeoutMs, label } = options;
34
+ const component = asReactComponent(input.component);
35
+ const renderOptions = { timeoutMs, label };
37
36
  if (input.children === undefined) {
38
- return reactDomServer.renderToString(react.createElement(asReactComponent(input.component), input.props));
37
+ return await renderReactHtml(runtime, runtime.react.createElement(component, input.props), renderOptions);
39
38
  }
40
39
  if (isValidElement(input.children)) {
41
- return reactDomServer.renderToString(react.createElement(asReactComponent(input.component), input.props, input.children));
40
+ return await renderReactHtml(runtime, runtime.react.createElement(component, input.props, input.children), renderOptions);
42
41
  }
43
42
  const resolvedChildHtml = typeof input.children === 'string' ? input.children : String(input.children ?? '');
44
43
  const rawChildrenToken = `__ECO_RAW_HTML_CHILD_${context.componentInstanceId ?? 'component'}__`;
@@ -46,7 +45,7 @@ export function renderComponentHtml(options) {
46
45
  runtimeContext.rawChildrenToken = rawChildrenToken;
47
46
  runtimeContext.rawChildrenHtml = resolvedChildHtml;
48
47
  }
49
- const html = reactDomServer.renderToString(react.createElement(asReactComponent(input.component), input.props, rawChildrenToken));
48
+ const html = await renderReactHtml(runtime, runtime.react.createElement(component, input.props, rawChildrenToken), renderOptions);
50
49
  return html.split(rawChildrenToken).join(resolvedChildHtml);
51
50
  }
52
51
  export function toReactNode(children, integrationName) {
@@ -5,7 +5,7 @@
5
5
  * Error thrown when an error occurs while rendering a React component.
6
6
  */
7
7
  export declare class ReactRenderError extends Error {
8
- constructor(message: string);
8
+ constructor(message: string, options?: ErrorOptions);
9
9
  }
10
10
  /**
11
11
  * Error thrown when an error occurs while bundling a React component.