@ecopages/react 0.2.0-beta.26 → 0.2.0-beta.27

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 (98) hide show
  1. package/README.md +17 -9
  2. package/package.json +42 -34
  3. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +7 -7
  4. package/src/{services/react-bundle.service.js → bundling/bundle.js} +9 -11
  5. package/src/{utils → bundling}/discover-layout-runtime-modules.js +2 -2
  6. package/src/{utils/react-runtime-alias-map.d.ts → bundling/runtime-alias-map.d.ts} +3 -3
  7. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +5 -5
  8. package/src/{services/react-runtime-bundle.service.js → bundling/runtime-bundle.js} +4 -4
  9. package/src/bundling/runtime-mode.d.ts +9 -0
  10. package/src/bundling/runtime-mode.js +6 -0
  11. package/src/{utils/client-graph-ast-transform.d.ts → client-graph/ast-transform.d.ts} +1 -1
  12. package/src/{utils/client-graph-ast-transform.js → client-graph/ast-transform.js} +1 -1
  13. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +0 -5
  14. package/src/{utils/client-graph-boundary-cache.js → client-graph/boundary-cache.js} +1 -3
  15. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +1 -1
  16. package/src/{utils/client-graph-boundary-plugin.js → client-graph/boundary-plugin.js} +3 -3
  17. package/src/{utils/client-graph-reachability.d.ts → client-graph/specifier-classification.d.ts} +1 -1
  18. package/src/{react-hmr-strategy.d.ts → hmr/hmr-strategy.d.ts} +3 -6
  19. package/src/{react-hmr-strategy.js → hmr/hmr-strategy.js} +11 -20
  20. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  21. package/src/{services/react-hmr-page-metadata-cache.js → hmr/page-metadata-cache.js} +8 -2
  22. package/src/{services/react-hydration-asset.service.d.ts → hydration/hydration-asset.d.ts} +33 -33
  23. package/src/{services/react-hydration-asset.service.js → hydration/hydration-asset.js} +45 -52
  24. package/src/{utils → hydration}/hydration-scripts.d.ts +33 -41
  25. package/src/hydration/hydration-scripts.js +353 -0
  26. package/src/{utils → hydration}/hydration-scripts.test.browser.js +6 -4
  27. package/src/hydration/page-data-manifest.d.ts +58 -0
  28. package/src/hydration/page-data-manifest.js +53 -0
  29. package/src/hydration/page-data-reader.d.ts +31 -0
  30. package/src/hydration/page-data-reader.js +64 -0
  31. package/src/hydration/page-payload.d.ts +67 -0
  32. package/src/hydration/page-payload.js +104 -0
  33. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  34. package/src/hydration/serialize-page-data-script.js +31 -0
  35. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +5 -5
  36. package/src/{services/react-mdx-config-dependency.service.js → mdx/mdx-config-dependency.js} +3 -3
  37. package/src/{services/react-page-module.service.d.ts → page/page-module.d.ts} +4 -7
  38. package/src/{services/react-page-module.service.js → page/page-module.js} +5 -9
  39. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +7 -3
  40. package/src/{react.plugin.js → plugin/react.plugin.js} +32 -30
  41. package/src/{react.types.d.ts → plugin/react.types.d.ts} +23 -8
  42. package/src/render/component-ownership.d.ts +50 -0
  43. package/src/render/component-ownership.js +23 -0
  44. package/src/render/component-ssr.d.ts +113 -0
  45. package/src/render/component-ssr.js +202 -0
  46. package/src/render/errors.d.ts +16 -0
  47. package/src/render/errors.js +18 -0
  48. package/src/{layout-compose.d.ts → render/layout-compose.d.ts} +8 -0
  49. package/src/{layout-compose.js → render/layout-compose.js} +14 -6
  50. package/src/render/react-renderer.d.ts +137 -0
  51. package/src/render/react-renderer.js +444 -0
  52. package/src/render/react-runtime.d.ts +13 -0
  53. package/src/render/react-runtime.js +21 -0
  54. package/src/render/unified-layout-composition.d.ts +53 -0
  55. package/src/render/unified-layout-composition.js +89 -0
  56. package/src/react-renderer.d.ts +0 -254
  57. package/src/react-renderer.js +0 -726
  58. package/src/serialize-page-data-script.d.ts +0 -8
  59. package/src/serialize-page-data-script.js +0 -10
  60. package/src/services/pages-index.d.ts +0 -64
  61. package/src/services/pages-index.js +0 -73
  62. package/src/services/react-page-payload.service.d.ts +0 -46
  63. package/src/services/react-page-payload.service.js +0 -67
  64. package/src/utils/hydration-scripts.js +0 -371
  65. /package/src/{utils → app}/client-only.d.ts +0 -0
  66. /package/src/{utils → app}/client-only.js +0 -0
  67. /package/src/{utils → app}/dynamic.d.ts +0 -0
  68. /package/src/{utils → app}/dynamic.js +0 -0
  69. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  70. /package/src/{utils → app}/dynamic.test.browser.js +0 -0
  71. /package/src/{utils → bundling}/discover-layout-runtime-modules.d.ts +0 -0
  72. /package/src/{utils/react-runtime-alias-map.js → bundling/runtime-alias-map.js} +0 -0
  73. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  74. /package/src/{utils/react-dom-runtime-interop-plugin.js → bundling/runtime-interop-plugin.js} +0 -0
  75. /package/src/{utils/react-plugin-runtime-modules.d.ts → bundling/runtime-modules.d.ts} +0 -0
  76. /package/src/{utils/react-plugin-runtime-modules.js → bundling/runtime-modules.js} +0 -0
  77. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  78. /package/src/{utils → client-graph}/component-config-traversal.js +0 -0
  79. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  80. /package/src/{utils → client-graph}/declared-modules.js +0 -0
  81. /package/src/{utils → client-graph}/reachability-analyzer.d.ts +0 -0
  82. /package/src/{utils → client-graph}/reachability-analyzer.js +0 -0
  83. /package/src/{utils/client-graph-reachability.js → client-graph/specifier-classification.js} +0 -0
  84. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  85. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  86. /package/src/{router-adapter.js → contracts/router-adapter.js} +0 -0
  87. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  88. /package/src/{utils → hmr}/hmr-scripts.js +0 -0
  89. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  90. /package/src/{utils/react-mdx-loader-plugin.d.ts → mdx/mdx-loader-plugin.d.ts} +0 -0
  91. /package/src/{utils/react-mdx-loader-plugin.js → mdx/mdx-loader-plugin.js} +0 -0
  92. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  93. /package/src/{react.constants.js → plugin/react.constants.js} +0 -0
  94. /package/src/{react.types.js → plugin/react.types.js} +0 -0
  95. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  96. /package/src/{eco-embed.js → render/eco-embed.js} +0 -0
  97. /package/src/{utils → render}/html-boundary.d.ts +0 -0
  98. /package/src/{utils → render}/html-boundary.js +0 -0
@@ -0,0 +1,353 @@
1
+ import { getDevPageDataReaderBootstrapSource } from "./page-data-reader.js";
2
+ const DEFAULT_LAYOUT_COMPOSE_IMPORT_PATH = "@ecopages/react/layout-compose";
3
+ const PAGE_LAYOUT_NORMALIZATION_IMPORT = "@ecopages/core/eco/page-layout-normalization";
4
+ function getPageDataReaderSource(options) {
5
+ if (options.pageDataReaderImportPath) {
6
+ return `import { readPageDataDocument, getPageDataFromDocument as getPageData } from "${options.pageDataReaderImportPath}";`;
7
+ }
8
+ return getDevPageDataReaderBootstrapSource();
9
+ }
10
+ function resolveLayoutComposeImportPath(options) {
11
+ return options.layoutComposeImportPath ?? DEFAULT_LAYOUT_COMPOSE_IMPORT_PATH;
12
+ }
13
+ function getImportStatement(importPath, isMdx) {
14
+ return isMdx ? `import * as MDXModule from "${importPath}";
15
+ import { ensurePageConfigLayouts } from "${PAGE_LAYOUT_NORMALIZATION_IMPORT}";
16
+ const Page = MDXModule.default;
17
+ if (MDXModule.config) {
18
+ Page.config = MDXModule.config;
19
+ ensurePageConfigLayouts(Page.config);
20
+ }` : `import Page from "${importPath}";`;
21
+ }
22
+ function getHmrImportStatement(isMdx) {
23
+ return isMdx ? `const NewPage = newModule.default;
24
+ if (newModule.config) {
25
+ NewPage.config = newModule.config;
26
+ ensurePageConfigLayouts(NewPage.config);
27
+ }` : "const NewPage = newModule.default;";
28
+ }
29
+ function getComponentType(isMdx) {
30
+ return isMdx ? "MDX" : "React";
31
+ }
32
+ function getPageRootCleanupScript() {
33
+ return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
34
+ window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
35
+ window.__ECO_PAGES__.react.cleanupPageRoot = () => {
36
+ const activeRoot = window.__ECO_PAGES__.react?.pageRoot || root;
37
+ if (!activeRoot) {
38
+ window.__ECO_PAGES__.react.pageRoot = null;
39
+ window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
40
+ delete window.__ECO_PAGES__.page;
41
+ return;
42
+ }
43
+ window.__ECO_PAGES__.react.pageRoot = null;
44
+ window.__ECO_PAGES__?.navigation?.releaseOwnership?.("react-router");
45
+ delete window.__ECO_PAGES__.page;
46
+ root = null;
47
+ activeRoot.unmount();
48
+ };`;
49
+ }
50
+ function getRouterBootstrapRegistrationScript() {
51
+ return `const currentOwnerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
52
+ if (!(currentOwnerState?.owner === "react-router" && currentOwnerState.canHandleSpaNavigation)) {
53
+ window.__ECO_PAGES__?.navigation?.register({
54
+ owner: "react-router",
55
+ cleanupBeforeHandoff: async () => {
56
+ window.__ECO_PAGES__?.react?.cleanupPageRoot?.();
57
+ }
58
+ });
59
+ window.__ECO_PAGES__?.navigation?.claimOwnership?.("react-router");
60
+ }`;
61
+ }
62
+ function getReuseExistingRouterRootScript() {
63
+ return `const shouldReuseExistingRouterRoot = () => {
64
+ const ownerState = window.__ECO_PAGES__?.navigation?.getOwnerState?.();
65
+ return Boolean(
66
+ window.__ECO_PAGES__.react?.pageRoot &&
67
+ ownerState?.owner === "react-router" &&
68
+ ownerState.canHandleSpaNavigation
69
+ );
70
+ };`;
71
+ }
72
+ function getRerunRegistrationScript(scriptId) {
73
+ return `window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
74
+ window.__ECO_PAGES__.rerunScripts = window.__ECO_PAGES__.rerunScripts || {};
75
+ window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}] = mount;`;
76
+ }
77
+ function getRouterHmrHandlerScript(options) {
78
+ const { importPath, isMdx } = options;
79
+ return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
80
+ try {
81
+ const newModule = await import(newUrl);
82
+ const nextProps = getPageData();
83
+ ${getHmrImportStatement(isMdx)}
84
+ const currentPageLayoutStack = (Component) =>
85
+ (Component.config?.layouts ?? []).map((layout) => layout?.config?.__eco?.file ?? '').join('|');
86
+ const currentPageLayoutStackKey = currentPageLayoutStack(Page);
87
+ const nextPageLayoutStackKey = currentPageLayoutStack(NewPage);
88
+
89
+ if (window.__ECO_PAGES__?.navigation?.getOwnerState().owner === "react-router") {
90
+ await window.__ECO_PAGES__?.navigation?.reloadCurrentPage?.({
91
+ clearCache: currentPageLayoutStackKey !== nextPageLayoutStackKey,
92
+ moduleUrl: newUrl,
93
+ source: "react-router"
94
+ });
95
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated via router");
96
+ return;
97
+ }
98
+
99
+ const nextPageData = readPageDataDocument();
100
+ window.__ECO_PAGES__.page = {
101
+ module: nextPageData.moduleUrl || pageModuleUrl,
102
+ props: nextProps
103
+ };
104
+ root.render(createTree(NewPage, nextProps));
105
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated");
106
+ } catch (e) {
107
+ console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
108
+ }
109
+ };`;
110
+ }
111
+ function getNonRouterHmrHandlerScript(options) {
112
+ const { importPath, isMdx } = options;
113
+ return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
114
+ try {
115
+ const newModule = await import(newUrl);
116
+ ${getHmrImportStatement(isMdx)}
117
+ root.render(createTree(NewPage, props));
118
+ console.log("[ecopages] ${getComponentType(isMdx)} component updated");
119
+ } catch (e) {
120
+ console.error("[ecopages] Failed to hot-reload ${getComponentType(isMdx)} component:", e);
121
+ }
122
+ };`;
123
+ }
124
+ function createScriptWithRouter(options) {
125
+ const {
126
+ importPath,
127
+ isMdx,
128
+ router,
129
+ reactImportPath,
130
+ reactDomClientImportPath,
131
+ routerImportPath,
132
+ scriptId,
133
+ hmrEnabled
134
+ } = options;
135
+ const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
136
+ const { components, getRouterProps } = router;
137
+ if (!routerImportPath) {
138
+ throw new Error("routerImportPath is required when router adapter is configured");
139
+ }
140
+ const hmrInit = hmrEnabled ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
141
+ ` : "";
142
+ const hmrHandler = hmrEnabled ? getRouterHmrHandlerScript({ importPath, isMdx }) : "";
143
+ return `
144
+ import { hydrateRoot } from "${reactDomClientImportPath}";
145
+ import { createElement } from "${reactImportPath}";
146
+ import { ${components.router}, ${components.pageContent} } from "${routerImportPath}";
147
+ ${getPageDataReaderSource(options)}
148
+ ${getImportStatement(importPath, isMdx)}
149
+ const pageModuleUrl = ${pageModuleUrlExpression};
150
+ export default Page;
151
+ export const config = Page.config;
152
+ const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
153
+
154
+ if (isActivePageEntry) {
155
+
156
+ window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
157
+ ${hmrInit}window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
158
+ window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
159
+ let root = window.__ECO_PAGES__.react.pageRoot;
160
+ ${getPageRootCleanupScript()}
161
+ ${getRouterBootstrapRegistrationScript()}
162
+ ${getReuseExistingRouterRootScript()}
163
+
164
+ const initialPageData = readPageDataDocument();
165
+ const props = initialPageData.props;
166
+
167
+ window.__ECO_PAGES__.page = {
168
+ module: initialPageData.moduleUrl || pageModuleUrl,
169
+ props
170
+ };
171
+
172
+ const createTree = (Component, props) => {
173
+ const pageContent = createElement(${components.pageContent});
174
+ return createElement(${components.router}, ${getRouterProps("Component", "props")}, pageContent);
175
+ };
176
+
177
+ const mount = () => {
178
+ const pageData = readPageDataDocument();
179
+ const props = pageData.props;
180
+ window.__ECO_PAGES__.page = {
181
+ module: pageData.moduleUrl || pageModuleUrl,
182
+ props
183
+ };
184
+
185
+ if (shouldReuseExistingRouterRoot()) {
186
+ root = window.__ECO_PAGES__.react.pageRoot;
187
+ return;
188
+ }
189
+
190
+ if (window.__ECO_PAGES__.react?.pageRoot) {
191
+ root = window.__ECO_PAGES__.react.pageRoot;
192
+ return;
193
+ }
194
+
195
+ root = hydrateRoot(document.body, createTree(Page, props), {
196
+ onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
197
+ });
198
+ window.__ECO_PAGES__.react.pageRoot = root;
199
+ ${hmrHandler}
200
+ };
201
+
202
+ ${getRerunRegistrationScript(scriptId)}
203
+
204
+ if (document.readyState === "loading") {
205
+ document.addEventListener("DOMContentLoaded", mount);
206
+ } else {
207
+ mount();
208
+ }
209
+ }
210
+ `.trim();
211
+ }
212
+ function createScriptWithoutRouter(options) {
213
+ const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId, hmrEnabled } = options;
214
+ const pageModuleUrlExpression = options.pageModuleUrlExpression ?? "import.meta.url";
215
+ const layoutComposeImportPath = resolveLayoutComposeImportPath(options);
216
+ const hmrInit = hmrEnabled ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
217
+ ` : "";
218
+ const hmrHandler = hmrEnabled ? getNonRouterHmrHandlerScript({ importPath, isMdx }) : "";
219
+ return `
220
+ import { hydrateRoot } from "${reactDomClientImportPath}";
221
+ import { createElement } from "${reactImportPath}";
222
+ import { composeLayoutPageTree } from "${layoutComposeImportPath}";
223
+ ${getPageDataReaderSource(options)}
224
+ ${getImportStatement(importPath, isMdx)}
225
+ const pageModuleUrl = ${pageModuleUrlExpression};
226
+ export default Page;
227
+ export const config = Page.config;
228
+ const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
229
+
230
+ if (isActivePageEntry) {
231
+
232
+ window.__ECO_PAGES__ = window.__ECO_PAGES__ || {};
233
+ ${hmrInit}window.__ECO_PAGES__.react = window.__ECO_PAGES__.react || {};
234
+ window.__ECO_PAGES__.react.pageRoot = window.__ECO_PAGES__.react.pageRoot || null;
235
+ let root = window.__ECO_PAGES__.react.pageRoot;
236
+ ${getPageRootCleanupScript()}
237
+
238
+ const initialPageData = readPageDataDocument();
239
+ const props = initialPageData.props;
240
+
241
+ window.__ECO_PAGES__.page = {
242
+ module: initialPageData.moduleUrl || pageModuleUrl,
243
+ props
244
+ };
245
+
246
+ const createTree = (Component, props) => composeLayoutPageTree(Component, props);
247
+
248
+ const mount = () => {
249
+ const pageData = readPageDataDocument();
250
+ const props = pageData.props;
251
+ window.__ECO_PAGES__.page = {
252
+ module: pageData.moduleUrl || pageModuleUrl,
253
+ props
254
+ };
255
+
256
+ if (window.__ECO_PAGES__.react?.pageRoot) {
257
+ root = window.__ECO_PAGES__.react.pageRoot;
258
+ root.render(createTree(Page, props));
259
+ } else {
260
+ root = hydrateRoot(document.body, createTree(Page, props), {
261
+ onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
262
+ });
263
+ window.__ECO_PAGES__.react.pageRoot = root;
264
+ }
265
+ ${hmrHandler}
266
+ };
267
+
268
+ ${getRerunRegistrationScript(scriptId)}
269
+
270
+ if (document.readyState === "loading") {
271
+ document.addEventListener("DOMContentLoaded", mount);
272
+ } else {
273
+ mount();
274
+ }
275
+ }
276
+ `.trim();
277
+ }
278
+ function createHydrationScript(options) {
279
+ return options.router ? createScriptWithRouter(options) : createScriptWithoutRouter(options);
280
+ }
281
+ function createIslandHydrationScript(options) {
282
+ const targetSelector = JSON.stringify(options.targetSelector);
283
+ const componentRef = JSON.stringify(options.componentRef ?? "");
284
+ const componentFile = JSON.stringify(options.componentFile ?? "");
285
+ const scriptId = options.scriptId;
286
+ if (options.minify) {
287
+ return `import{createRoot as cr}from"${options.reactDomClientImportPath}";import{createElement as ce}from"${options.reactImportPath}";import*as M from"${options.importPath}";const r=${componentRef};const f=${componentFile};const mv=Object.values(M);const c=mv.find((e)=>{if(typeof e!=="function")return false;const ec=e.config?.__eco;if(!ec)return false;if(r&&ec.id===r)return true;if(f&&ec.file===f)return true;return false;})??(typeof M.default==="function"?M.default:mv.find((e)=>typeof e==="function")??null);const m=()=>{const ts=document.querySelectorAll(${targetSelector});if(!c||ts.length===0)return;ts.forEach((t)=>{if(!(t instanceof HTMLElement))return;const p=JSON.parse(atob(t.getAttribute("data-eco-props")||"e30="));const ct=document.createElement("eco-island");ct.style.display="block";t.replaceWith(ct);cr(ct).render(ce(c,p))})};window.__ECO_PAGES__=window.__ECO_PAGES__||{};window.__ECO_PAGES__.rerunScripts=window.__ECO_PAGES__.rerunScripts||{};window.__ECO_PAGES__.rerunScripts[${JSON.stringify(scriptId)}]=m;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",m,{once:true}):m()`;
288
+ }
289
+ return `
290
+ import { createRoot } from "${options.reactDomClientImportPath}";
291
+ import { createElement } from "${options.reactImportPath}";
292
+ import * as ComponentModule from "${options.importPath}";
293
+
294
+ const resolveComponent = () => {
295
+ const id = ${componentRef};
296
+ const file = ${componentFile};
297
+ const moduleValues = Object.values(ComponentModule);
298
+
299
+ const matchByMetadata = moduleValues.find((entry) => {
300
+ if (typeof entry !== "function") return false;
301
+ const config = entry.config;
302
+ const eco = config?.__eco;
303
+ if (!eco) return false;
304
+ if (id && eco.id === id) return true;
305
+ if (file && eco.file === file) return true;
306
+ return false;
307
+ });
308
+
309
+ if (matchByMetadata && typeof matchByMetadata === "function") {
310
+ return matchByMetadata;
311
+ }
312
+
313
+ const defaultExport = ComponentModule.default;
314
+ if (typeof defaultExport === "function") {
315
+ return defaultExport;
316
+ }
317
+
318
+ const firstFunction = moduleValues.find((entry) => typeof entry === "function");
319
+ return typeof firstFunction === "function" ? firstFunction : null;
320
+ };
321
+
322
+ const mount = () => {
323
+ const targets = document.querySelectorAll(${targetSelector});
324
+ const Component = resolveComponent();
325
+ if (!Component || targets.length === 0) {
326
+ return;
327
+ }
328
+ targets.forEach((target) => {
329
+ if (!(target instanceof HTMLElement)) {
330
+ return;
331
+ }
332
+ const props = JSON.parse(atob(target.getAttribute("data-eco-props") || "e30="));
333
+ const container = document.createElement("eco-island");
334
+ container.style.display = "block";
335
+ target.replaceWith(container);
336
+ const root = createRoot(container);
337
+ root.render(createElement(Component, props));
338
+ });
339
+ };
340
+
341
+ ${getRerunRegistrationScript(scriptId)}
342
+
343
+ if (document.readyState === "loading") {
344
+ document.addEventListener("DOMContentLoaded", mount, { once: true });
345
+ } else {
346
+ mount();
347
+ }
348
+ `.trim();
349
+ }
350
+ export {
351
+ createHydrationScript,
352
+ createIslandHydrationScript
353
+ };
@@ -107,9 +107,10 @@ describe("createHydrationScript browser execution", () => {
107
107
  const script = createHydrationScript({
108
108
  ...runtimeModules,
109
109
  scriptId: "ecopages-react-page",
110
- isDevelopment: true,
110
+ hmrEnabled: true,
111
111
  isMdx: false,
112
- router: routerAdapter
112
+ router: routerAdapter,
113
+ pageDataReaderImportPath: new URL("./page-data-reader.js", import.meta.url).href
113
114
  });
114
115
  const moduleUrl = createModuleUrl(script);
115
116
  await importModule(moduleUrl, "ecopages-react-page");
@@ -177,9 +178,10 @@ describe("createHydrationScript browser execution", () => {
177
178
  const script = createHydrationScript({
178
179
  ...runtimeModules,
179
180
  scriptId: "ecopages-react-page-rerun",
180
- isDevelopment: true,
181
+ hmrEnabled: true,
181
182
  isMdx: false,
182
- router: routerAdapter
183
+ router: routerAdapter,
184
+ pageDataReaderImportPath: new URL("./page-data-reader.js", import.meta.url).href
183
185
  });
184
186
  const moduleUrl = createModuleUrl(script);
185
187
  await importModule(moduleUrl, "ecopages-react-page-rerun");
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Versioned React page-data document payload.
3
+ *
4
+ * @remarks
5
+ * The `__ECO_PAGE_DATA__` script emits this envelope so client navigation can
6
+ * read module identity without parsing generated hydration JavaScript. Older
7
+ * documents may still contain a flat props object; consumers must detect both.
8
+ *
9
+ * Compatibility matrix:
10
+ * - new client / new document: prefer `schemaVersion:1` envelope (`moduleUrl` + `props`)
11
+ * - new client / old document: accept legacy flat props; module discovery uses
12
+ * `window.__ECO_PAGES__.page.module` or `script[data-eco-page-bootstrap="react-router"]`
13
+ * - old client / new document: old clients that only read flat props should be
14
+ * upgraded; envelope consumers must unwrap `props` before hydration
15
+ * - malformed / unknown schema (numeric `schemaVersion` present but envelope invalid):
16
+ * empty props and no module URL from the manifest
17
+ * - HMR: `moduleUrlOverride` still bypasses document discovery
18
+ * - legacy flat props may include a string `schemaVersion` field without being treated as an envelope
19
+ */
20
+ export declare const ECO_PAGE_DATA_SCHEMA_VERSION: 1;
21
+ export type EcoPageDataProps = Record<string, unknown>;
22
+ export type EcoPageDataManifestV1 = {
23
+ schemaVersion: typeof ECO_PAGE_DATA_SCHEMA_VERSION;
24
+ navigationOwner: 'react-router';
25
+ moduleUrl: string;
26
+ props: EcoPageDataProps;
27
+ };
28
+ export type EcoPageDataDocumentPayload = EcoPageDataManifestV1 | EcoPageDataProps;
29
+ /**
30
+ * Returns whether a parsed JSON value is a versioned page-data envelope.
31
+ */
32
+ export declare function isEcoPageDataManifestV1(value: unknown): value is EcoPageDataManifestV1;
33
+ /**
34
+ * Extracts browser page props from either a v1 envelope or a legacy flat payload.
35
+ */
36
+ export declare function resolveEcoPageDataProps(payload: unknown): EcoPageDataProps;
37
+ /**
38
+ * Extracts the page module URL from a v1 envelope when present.
39
+ */
40
+ export declare function resolveEcoPageDataModuleUrl(payload: unknown): string | null;
41
+ /**
42
+ * Builds the canonical v1 page-data envelope for React documents.
43
+ */
44
+ export declare function createEcoPageDataManifestV1(input: {
45
+ moduleUrl: string;
46
+ props: EcoPageDataProps;
47
+ }): EcoPageDataManifestV1;
48
+ /**
49
+ * Normalizes flat page props or an existing envelope into the document payload shape.
50
+ *
51
+ * @remarks
52
+ * Shared by server serializers and `EcoPropsScript` so envelope rules stay in one place.
53
+ * A valid v1 envelope is returned as-is; `options.moduleUrl` is ignored in that case.
54
+ * Flat props wrap into a v1 envelope only when `options.moduleUrl` is provided.
55
+ */
56
+ export declare function resolvePageDataDocumentPayload(data: EcoPageDataDocumentPayload, options?: {
57
+ moduleUrl?: string;
58
+ }): EcoPageDataDocumentPayload;
@@ -0,0 +1,53 @@
1
+ const ECO_PAGE_DATA_SCHEMA_VERSION = 1;
2
+ function isEcoPageDataManifestV1(value) {
3
+ if (typeof value !== "object" || value === null) {
4
+ return false;
5
+ }
6
+ const candidate = value;
7
+ return candidate.schemaVersion === ECO_PAGE_DATA_SCHEMA_VERSION && candidate.navigationOwner === "react-router" && typeof candidate.moduleUrl === "string" && typeof candidate.props === "object" && candidate.props !== null && !Array.isArray(candidate.props);
8
+ }
9
+ function isMalformedPageDataEnvelope(payload) {
10
+ return "schemaVersion" in payload && typeof payload.schemaVersion === "number";
11
+ }
12
+ function resolveEcoPageDataProps(payload) {
13
+ if (isEcoPageDataManifestV1(payload)) {
14
+ return payload.props;
15
+ }
16
+ if (typeof payload === "object" && payload !== null && !Array.isArray(payload)) {
17
+ if (isMalformedPageDataEnvelope(payload)) {
18
+ return {};
19
+ }
20
+ return payload;
21
+ }
22
+ return {};
23
+ }
24
+ function resolveEcoPageDataModuleUrl(payload) {
25
+ return isEcoPageDataManifestV1(payload) ? payload.moduleUrl : null;
26
+ }
27
+ function createEcoPageDataManifestV1(input) {
28
+ return {
29
+ schemaVersion: ECO_PAGE_DATA_SCHEMA_VERSION,
30
+ navigationOwner: "react-router",
31
+ moduleUrl: input.moduleUrl,
32
+ props: input.props
33
+ };
34
+ }
35
+ function resolvePageDataDocumentPayload(data, options) {
36
+ if (isEcoPageDataManifestV1(data)) {
37
+ return data;
38
+ }
39
+ const props = { ...data };
40
+ const moduleUrl = options?.moduleUrl;
41
+ if (!moduleUrl) {
42
+ return props;
43
+ }
44
+ return createEcoPageDataManifestV1({ moduleUrl, props });
45
+ }
46
+ export {
47
+ ECO_PAGE_DATA_SCHEMA_VERSION,
48
+ createEcoPageDataManifestV1,
49
+ isEcoPageDataManifestV1,
50
+ resolveEcoPageDataModuleUrl,
51
+ resolveEcoPageDataProps,
52
+ resolvePageDataDocumentPayload
53
+ };
@@ -0,0 +1,31 @@
1
+ import { type EcoPageDataProps } from './page-data-manifest.js';
2
+ export type ReadPageDataDocumentResult = {
3
+ moduleUrl?: string;
4
+ props: EcoPageDataProps;
5
+ };
6
+ /**
7
+ * Reads `__ECO_PAGE_DATA__`, supporting both v1 envelopes and legacy flat props.
8
+ *
9
+ * @remarks
10
+ * Always returns unwrapped `props`. `moduleUrl` is set only when the document
11
+ * carries a valid v1 envelope.
12
+ */
13
+ export declare function readPageDataDocument(): ReadPageDataDocumentResult;
14
+ /**
15
+ * Returns page props from `__ECO_PAGE_DATA__` for hydration and HMR handlers.
16
+ */
17
+ export declare function getPageDataFromDocument(): EcoPageDataProps;
18
+ /**
19
+ * Inlined browser bootstrap for generated hydration scripts.
20
+ *
21
+ * @remarks
22
+ * Hydration and HMR entry modules are evaluated as native browser ESM. Bare
23
+ * package imports such as `@ecopages/react/page-data-reader` are not resolvable
24
+ * there, so the reader algorithm is embedded. Keep this string aligned with
25
+ * {@link readPageDataDocument} / {@link getPageDataFromDocument}.
26
+ */
27
+ export declare function getDevPageDataReaderBootstrapSource(): string;
28
+ /**
29
+ * Minified equivalent of {@link getDevPageDataReaderBootstrapSource}.
30
+ */
31
+ export declare function getProdPageDataReaderBootstrapSource(): string;
@@ -0,0 +1,64 @@
1
+ import {
2
+ ECO_PAGE_DATA_SCHEMA_VERSION,
3
+ resolveEcoPageDataModuleUrl,
4
+ resolveEcoPageDataProps
5
+ } from "./page-data-manifest.js";
6
+ function readPageDataDocument() {
7
+ const element = document.getElementById("__ECO_PAGE_DATA__");
8
+ if (!element?.textContent) {
9
+ return { props: {} };
10
+ }
11
+ try {
12
+ const parsed = JSON.parse(element.textContent);
13
+ const moduleUrl = resolveEcoPageDataModuleUrl(parsed) ?? void 0;
14
+ return {
15
+ ...moduleUrl && { moduleUrl },
16
+ props: resolveEcoPageDataProps(parsed)
17
+ };
18
+ } catch {
19
+ return { props: {} };
20
+ }
21
+ }
22
+ function getPageDataFromDocument() {
23
+ return readPageDataDocument().props;
24
+ }
25
+ function getDevPageDataReaderBootstrapSource() {
26
+ return `const readPageDataDocument = () => {
27
+ const el = document.getElementById("__ECO_PAGE_DATA__");
28
+ if (!el?.textContent) {
29
+ return { props: {} };
30
+ }
31
+ try {
32
+ const parsed = JSON.parse(el.textContent);
33
+ if (
34
+ parsed &&
35
+ parsed.schemaVersion === ${ECO_PAGE_DATA_SCHEMA_VERSION} &&
36
+ parsed.navigationOwner === "react-router" &&
37
+ typeof parsed.moduleUrl === "string" &&
38
+ parsed.props &&
39
+ typeof parsed.props === "object" &&
40
+ !Array.isArray(parsed.props)
41
+ ) {
42
+ return { moduleUrl: parsed.moduleUrl, props: parsed.props };
43
+ }
44
+ if (parsed && typeof parsed === "object" && typeof parsed.schemaVersion === "number") {
45
+ return { props: {} };
46
+ }
47
+ return {
48
+ props: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {},
49
+ };
50
+ } catch {
51
+ return { props: {} };
52
+ }
53
+ };
54
+ const getPageData = () => readPageDataDocument().props;`;
55
+ }
56
+ function getProdPageDataReaderBootstrapSource() {
57
+ return `const rd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(!e?.textContent)return{props:{}};try{const p=JSON.parse(e.textContent);if(p&&p.schemaVersion===${ECO_PAGE_DATA_SCHEMA_VERSION}&&p.navigationOwner==="react-router"&&typeof p.moduleUrl==="string"&&p.props&&typeof p.props==="object"&&!Array.isArray(p.props))return{moduleUrl:p.moduleUrl,props:p.props};if(p&&typeof p==="object"&&typeof p.schemaVersion==="number")return{props:{}};return{props:p&&typeof p==="object"&&!Array.isArray(p)?p:{}}}catch{return{props:{}}}};const gd=()=>rd().props;`;
58
+ }
59
+ export {
60
+ getDevPageDataReaderBootstrapSource,
61
+ getPageDataFromDocument,
62
+ getProdPageDataReaderBootstrapSource,
63
+ readPageDataDocument
64
+ };
@@ -0,0 +1,67 @@
1
+ import type { EcoComponentConfig, HtmlTemplateProps, IntegrationRendererRenderOptions, RequestLocals } from '@ecopages/core';
2
+ import type { HtmlDocumentContribution } from '@ecopages/core/route-renderer/integration-renderer';
3
+ import type { ReactNode } from 'react';
4
+ type PagePayloadOptions = {
5
+ pageProps?: HtmlTemplateProps['pageProps'];
6
+ params: IntegrationRendererRenderOptions<ReactNode>['params'];
7
+ query: IntegrationRendererRenderOptions<ReactNode>['query'];
8
+ safeLocals?: RequestLocals;
9
+ };
10
+ type PagePackage = IntegrationRendererRenderOptions<ReactNode>['pagePackage'];
11
+ /**
12
+ * Builds the serialized page payload React exposes to document shells and the browser.
13
+ *
14
+ * @remarks
15
+ * Keeps hydration payload shaping away from the renderer so orchestration stays
16
+ * focused on component composition instead of document serialization rules.
17
+ */
18
+ export declare class PagePayloadService {
19
+ /**
20
+ * Resolves the browser-importable page module URL from processed page entry assets.
21
+ */
22
+ resolvePageModuleUrl(pagePackage: PagePackage | undefined, options: {
23
+ routerEnabled: boolean;
24
+ }): string | undefined;
25
+ /**
26
+ * Creates the `__ECO_PAGE_DATA__` script for router hydration.
27
+ *
28
+ * @remarks
29
+ * When `moduleUrl` is present, emits the v1 envelope via
30
+ * {@link serializePageDataManifestScript}. Otherwise emits legacy flat props
31
+ * for non-router shells.
32
+ */
33
+ buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined, moduleUrl?: string): string;
34
+ /**
35
+ * Builds shared document html contributions for router-backed React pages rendered
36
+ * through a non-React HTML shell.
37
+ */
38
+ buildNonReactDocumentContributions(options: {
39
+ htmlTemplate: {
40
+ config?: EcoComponentConfig;
41
+ } | null | undefined;
42
+ pageProps: Record<string, unknown>;
43
+ pageModuleUrl?: string;
44
+ reactIntegrationName: string;
45
+ routerEnabled: boolean;
46
+ }): HtmlDocumentContribution[] | undefined;
47
+ /**
48
+ * Builds the browser-safe page-props object embedded into the final HTML.
49
+ *
50
+ * @remarks
51
+ * Narrower than the full server render input: only routing data, public page
52
+ * props, and explicitly allowed locals. Page module identity is threaded via
53
+ * `HtmlTemplateProps.pageModuleUrl`, not serialized page props.
54
+ */
55
+ buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
56
+ /**
57
+ * Extracts the declared subset of locals for client-side hydration.
58
+ *
59
+ * @remarks
60
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
61
+ * request-scoped data. Only keys declared via `Page.requires` are serialized.
62
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError`; this
63
+ * method returns `undefined` instead of throwing.
64
+ */
65
+ getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
66
+ }
67
+ export {};