@ecopages/react 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +179 -35
  2. package/package.json +78 -33
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  6. package/src/bundling/bootstrap-package-paths.js +5 -0
  7. package/src/bundling/bundle.d.ts +78 -0
  8. package/src/bundling/bundle.js +130 -0
  9. package/src/bundling/runtime-alias-map.d.ts +12 -0
  10. package/src/bundling/runtime-alias-map.js +110 -0
  11. package/src/bundling/runtime-bundle.d.ts +70 -0
  12. package/src/bundling/runtime-bundle.js +233 -0
  13. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  14. package/src/bundling/runtime-interop-plugin.js +32 -0
  15. package/src/bundling/runtime-mode.d.ts +1 -0
  16. package/src/bundling/runtime-mode.js +10 -0
  17. package/src/bundling/runtime-modules.d.ts +21 -0
  18. package/src/bundling/runtime-modules.js +28 -0
  19. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  20. package/src/client-graph/ast-transform-eco-page.js +71 -0
  21. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  22. package/src/client-graph/ast-transform-import-edits.js +75 -0
  23. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  24. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  25. package/src/client-graph/ast-transform.d.ts +12 -0
  26. package/src/client-graph/ast-transform.js +91 -0
  27. package/src/client-graph/ast-walk.d.ts +10 -0
  28. package/src/client-graph/ast-walk.js +26 -0
  29. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  31. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  32. package/src/client-graph/boundary-plugin-transform.js +31 -0
  33. package/src/client-graph/boundary-plugin.d.ts +23 -0
  34. package/src/client-graph/boundary-plugin.js +177 -0
  35. package/src/client-graph/component-config-traversal.d.ts +36 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/{utils → client-graph}/declared-modules.d.ts +1 -1
  38. package/src/client-graph/declared-modules.js +69 -0
  39. package/src/client-graph/module-classification.d.ts +3 -0
  40. package/src/client-graph/module-classification.js +43 -0
  41. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  42. package/src/client-graph/reachability-analyzer.js +55 -0
  43. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  44. package/src/client-graph/reachability-client-roots.js +59 -0
  45. package/src/client-graph/reachability-export-names.d.ts +5 -0
  46. package/src/client-graph/reachability-export-names.js +34 -0
  47. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  48. package/src/client-graph/reachability-fallback-roots.js +71 -0
  49. package/src/client-graph/reachability-preload.d.ts +10 -0
  50. package/src/client-graph/reachability-preload.js +30 -0
  51. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  52. package/src/client-graph/reachability-top-level-index.js +93 -0
  53. package/src/client-graph/reachability-traverse.d.ts +7 -0
  54. package/src/client-graph/reachability-traverse.js +201 -0
  55. package/src/client-graph/specifier-classification.d.ts +74 -0
  56. package/src/client-graph/specifier-classification.js +191 -0
  57. package/src/content/collection-component-cache.d.ts +25 -0
  58. package/src/content/collection-component-cache.js +62 -0
  59. package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +7 -14
  60. package/src/contracts/router-adapter.js +6 -0
  61. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  62. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  63. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  64. package/src/hmr/hmr-strategy-process.js +83 -0
  65. package/src/hmr/hmr-strategy.d.ts +67 -0
  66. package/src/hmr/hmr-strategy.js +306 -0
  67. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +6 -2
  68. package/src/hmr/page-metadata-cache.js +44 -0
  69. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  70. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +81 -0
  74. package/src/hydration/browser/island-hydration.js +247 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/compiled-page-hydration-options.js +1 -0
  83. package/src/hydration/hydration-asset.d.ts +128 -0
  84. package/src/hydration/hydration-asset.js +388 -0
  85. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  86. package/src/hydration/hydration-page-entry-source.js +87 -0
  87. package/src/hydration/hydration-script-compiler.d.ts +47 -0
  88. package/src/hydration/hydration-script-compiler.js +213 -0
  89. package/src/hydration/page-data-manifest.d.ts +58 -0
  90. package/src/hydration/page-data-manifest.js +97 -0
  91. package/src/hydration/page-data-reader.d.ts +17 -0
  92. package/src/hydration/page-data-reader.js +31 -0
  93. package/src/hydration/page-payload.d.ts +68 -0
  94. package/src/hydration/page-payload.js +106 -0
  95. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  96. package/src/hydration/serialize-page-data-script.js +30 -0
  97. package/src/mdx/mdx-config-dependency.d.ts +37 -0
  98. package/src/mdx/mdx-config-dependency.js +107 -0
  99. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  100. package/src/mdx/mdx-loader-plugin.js +11 -0
  101. package/src/page/page-module.d.ts +46 -0
  102. package/src/page/page-module.js +74 -0
  103. package/src/plugin/react.constants.d.ts +1 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/plugin/react.plugin.d.ts +71 -0
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.d.ts +11 -0
  114. package/src/render/eco-embed.js +9 -0
  115. package/src/render/errors.d.ts +16 -0
  116. package/src/render/errors.js +23 -0
  117. package/src/render/html-boundary.js +59 -0
  118. package/src/render/layout-compose.d.ts +66 -0
  119. package/src/render/layout-compose.js +134 -0
  120. package/src/render/react-renderer.d.ts +114 -0
  121. package/src/render/react-renderer.js +490 -0
  122. package/src/render/react-runtime.d.ts +13 -0
  123. package/src/render/react-runtime.js +26 -0
  124. package/src/render/unified-layout-composition.d.ts +22 -0
  125. package/src/render/unified-layout-composition.js +31 -0
  126. package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
  127. package/src/runtime/use-sync-external-store-with-selector.js +54 -0
  128. package/CHANGELOG.md +0 -29
  129. package/src/react-hmr-strategy.d.ts +0 -148
  130. package/src/react-hmr-strategy.js +0 -313
  131. package/src/react-renderer.d.ts +0 -213
  132. package/src/react-renderer.js +0 -654
  133. package/src/react.plugin.d.ts +0 -147
  134. package/src/react.plugin.js +0 -146
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/react-bundle.service.d.ts +0 -47
  137. package/src/services/react-bundle.service.js +0 -93
  138. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  139. package/src/services/react-hydration-asset.service.d.ts +0 -76
  140. package/src/services/react-hydration-asset.service.js +0 -210
  141. package/src/services/react-page-module.service.d.ts +0 -83
  142. package/src/services/react-page-module.service.js +0 -162
  143. package/src/services/react-runtime-bundle.service.d.ts +0 -40
  144. package/src/services/react-runtime-bundle.service.js +0 -130
  145. package/src/utils/client-graph-boundary-plugin.d.ts +0 -43
  146. package/src/utils/client-graph-boundary-plugin.js +0 -494
  147. package/src/utils/client-only.js +0 -19
  148. package/src/utils/declared-modules.js +0 -59
  149. package/src/utils/dynamic.js +0 -12
  150. package/src/utils/hmr-scripts.d.ts +0 -18
  151. package/src/utils/hmr-scripts.js +0 -31
  152. package/src/utils/html-boundary.js +0 -55
  153. package/src/utils/hydration-scripts.d.ts +0 -86
  154. package/src/utils/hydration-scripts.js +0 -285
  155. package/src/utils/reachability-analyzer.d.ts +0 -66
  156. package/src/utils/reachability-analyzer.js +0 -339
  157. package/src/utils/react-dom-runtime-interop-plugin.js +0 -29
  158. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  159. package/src/utils/react-mdx-loader-plugin.js +0 -45
  160. package/src/utils/react-runtime-specifier-map.d.ts +0 -6
  161. package/src/utils/react-runtime-specifier-map.js +0 -37
  162. package/src/utils/use-sync-external-store-shim-plugin.d.ts +0 -5
  163. package/src/utils/use-sync-external-store-shim-plugin.js +0 -41
  164. /package/src/{utils → app}/client-only.d.ts +0 -0
  165. /package/src/{utils → app}/dynamic.d.ts +0 -0
  166. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  167. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Browser-side React Island Host lifecycle.
3
+ *
4
+ * @remarks
5
+ * This module intentionally receives React's browser runtime as a value. The
6
+ * server entry compiler can therefore keep the application's React and
7
+ * ReactDOM imports external while bundling this framework-owned lifecycle.
8
+ */
9
+ /**
10
+ * Returns the shared page runtime used by all React Island Host entries.
11
+ *
12
+ * @remarks
13
+ * Keeping initialization here means generated entries only describe their
14
+ * component and selector; they do not duplicate global runtime setup.
15
+ *
16
+ * @returns The shared mutable state used by all island entries on this page.
17
+ */
18
+ export function getIslandHydrationRuntime() {
19
+ const pageWindow = window;
20
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
21
+ pageRuntime.islandRoots ??= {};
22
+ pageRuntime.islandComponents ??= {};
23
+ pageRuntime.__ecoIslandRuntime ??= {
24
+ islandRoots: pageRuntime.islandRoots,
25
+ islandComponents: pageRuntime.islandComponents,
26
+ };
27
+ pageRuntime.__ecoIslandRuntime.islandRoots = pageRuntime.islandRoots;
28
+ pageRuntime.__ecoIslandRuntime.islandComponents = pageRuntime.islandComponents;
29
+ return pageRuntime.__ecoIslandRuntime;
30
+ }
31
+ /**
32
+ * Registers the development HMR callback for one component module.
33
+ *
34
+ * @remarks
35
+ * The callback imports the replacement module and delegates to
36
+ * {@link updateIslands}, which updates every live host matching this entry.
37
+ * The dynamic import function is supplied by the generated entry so HMR keeps
38
+ * the browser's normal module-resolution behavior.
39
+ *
40
+ * @param options - Entry configuration whose hosts should receive updates.
41
+ * @param importModule - Browser dynamic-import function for the replacement module.
42
+ * @param importPath - HMR source URL used as the global handler key.
43
+ */
44
+ export function registerIslandHmr(options, importModule, importPath) {
45
+ if (!importPath)
46
+ return;
47
+ const pageWindow = window;
48
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
49
+ pageRuntime.hmrHandlers ??= {};
50
+ pageRuntime.hmrHandlers[importPath] = async (url) => {
51
+ updateIslands(options, await importModule(url));
52
+ };
53
+ }
54
+ /**
55
+ * Selects the component exported by a browser entry for the current Island Host.
56
+ *
57
+ * @remarks
58
+ * Component identity is preferred when a file exports several components; each
59
+ * declaration has its own id, so the file alone cannot tell them apart. The
60
+ * default export and then the first function remain compatibility fallbacks for
61
+ * entries without framework identity metadata.
62
+ */
63
+ function resolveComponent(module, componentRef) {
64
+ const values = Object.values(module).filter((entry) => typeof entry === 'function');
65
+ if (componentRef) {
66
+ const matchById = values.find((entry) => entry.config?.identity?.id === componentRef);
67
+ if (matchById)
68
+ return matchById;
69
+ }
70
+ if (typeof module.default === 'function')
71
+ return module.default;
72
+ return values[0] ?? null;
73
+ }
74
+ function getComponentId(target) {
75
+ return target.getAttribute('data-eco-component-id');
76
+ }
77
+ function getIslandIdentity(target) {
78
+ return getComponentId(target) ?? target.getAttribute('data-eco-component-key') ?? 'unknown';
79
+ }
80
+ /**
81
+ * Adds the initial-commit marker while keeping one stable React component type
82
+ * around the application component. A stable type lets HMR update props without
83
+ * remounting this lifecycle boundary on every render.
84
+ */
85
+ function IslandLifecycle({ target, runtime, Component, props }) {
86
+ runtime.useEffect(() => {
87
+ target.setAttribute('data-eco-hydrated', 'true');
88
+ const record = target.__eco_island;
89
+ if (!record)
90
+ return;
91
+ record.hydrated = true;
92
+ if (record.pendingComponent) {
93
+ const pendingComponent = record.pendingComponent;
94
+ record.pendingComponent = undefined;
95
+ record.root.render(runtime.createElement(IslandLifecycle, {
96
+ target,
97
+ runtime,
98
+ Component: pendingComponent,
99
+ props: readProps(target),
100
+ }));
101
+ }
102
+ }, [target, runtime]);
103
+ return runtime.createElement(Component, props);
104
+ }
105
+ /**
106
+ * Decodes the serialized props stamped on an Island Host by the server.
107
+ * Malformed or non-object payloads become an empty props object so a broken
108
+ * diagnostic attribute cannot prevent the rest of the page from hydrating.
109
+ *
110
+ * @remarks
111
+ * Decodes the format core's `encodeIslandProps` writes in `islands/island-host.ts` (base64 of UTF-8 JSON). It is
112
+ * inlined because this module compiles into a self-contained browser script that cannot import core.
113
+ */
114
+ function readProps(target) {
115
+ try {
116
+ const encoded = target.getAttribute('data-eco-props') ?? 'e30=';
117
+ const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0))));
118
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
119
+ ? parsed
120
+ : {};
121
+ }
122
+ catch {
123
+ return {};
124
+ }
125
+ }
126
+ /**
127
+ * Unmounts a disconnected island and removes only its matching registry entry.
128
+ *
129
+ * @remarks
130
+ * Connectivity is checked by the observer callback, after the mutation batch,
131
+ * so moving a host within the document does not release its React root.
132
+ */
133
+ function releaseIsland(target, runtimeState) {
134
+ if (target.isConnected)
135
+ return;
136
+ const record = target.__eco_island;
137
+ if (!record)
138
+ return;
139
+ record.root.unmount();
140
+ const componentId = getComponentId(target);
141
+ if (componentId && runtimeState.islandRoots[componentId] === record.root) {
142
+ delete runtimeState.islandRoots[componentId];
143
+ }
144
+ delete target.__eco_island;
145
+ }
146
+ /**
147
+ * Installs the one document observer shared by all island entries on the page.
148
+ * The observer releases roots for removed hosts and their descendants.
149
+ */
150
+ function ensureObserver(runtimeState) {
151
+ if (runtimeState.observer || !document.documentElement)
152
+ return;
153
+ runtimeState.observer = new MutationObserver((mutations) => {
154
+ for (const mutation of mutations) {
155
+ for (const node of mutation.removedNodes) {
156
+ if (!(node instanceof HTMLElement))
157
+ continue;
158
+ releaseIsland(node, runtimeState);
159
+ for (const target of node.querySelectorAll('[data-eco-island]'))
160
+ releaseIsland(target, runtimeState);
161
+ }
162
+ }
163
+ });
164
+ runtimeState.observer.observe(document.documentElement, { childList: true, subtree: true });
165
+ }
166
+ /**
167
+ * Hydrates one server-emitted Island Host in place and records its lifecycle.
168
+ *
169
+ * @remarks
170
+ * The record is attached immediately after `hydrateRoot` returns so
171
+ * duplicate startup and HMR can see the host before React's initial effect runs.
172
+ */
173
+ function hydrateTarget(target, component, runtime, runtimeState) {
174
+ const root = runtime.hydrateRoot(target, runtime.createElement(IslandLifecycle, { target, runtime, Component: component, props: readProps(target) }), {
175
+ onRecoverableError: (error) => console.warn('[ecopages] Island hydration error', getIslandIdentity(target), error),
176
+ });
177
+ const record = { root, hydrated: false, component };
178
+ target.__eco_island = record;
179
+ const componentId = getComponentId(target);
180
+ if (componentId)
181
+ runtimeState.islandRoots[componentId] = record.root;
182
+ }
183
+ /**
184
+ * Hydrates every eligible host for one component entry.
185
+ *
186
+ * @remarks
187
+ * Existing host records are skipped. This makes rerun scripts idempotent and
188
+ * avoids calling `render` while an initial `hydrateRoot` commit is
189
+ * still pending.
190
+ *
191
+ * @param options - Component, selector, React runtime, and shared state for the entry.
192
+ */
193
+ export function mountIslands(options) {
194
+ const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '');
195
+ ensureObserver(options.runtimeState);
196
+ const pageRuntime = (window.__ECO_PAGES__ ??= {});
197
+ pageRuntime.rerunScripts ??= {};
198
+ pageRuntime.rerunScripts[options.scriptId] = () => mountIslands(options);
199
+ const scriptId = options.scriptId;
200
+ const component = options.runtimeState.islandComponents[scriptId] ?? resolvedComponent;
201
+ if (!component)
202
+ return;
203
+ options.runtimeState.islandComponents[scriptId] = component;
204
+ for (const element of document.querySelectorAll(options.targetSelector)) {
205
+ const target = element;
206
+ if (target.__eco_island?.root)
207
+ continue;
208
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
209
+ }
210
+ }
211
+ /**
212
+ * Applies a hot-reloaded component to every live host owned by this entry.
213
+ *
214
+ * @remarks
215
+ * Updates arriving before the initial commit are stored on each host and
216
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
217
+ *
218
+ * @param options - The live entry configuration and runtime state.
219
+ * @param newModule - Newly imported component module.
220
+ */
221
+ export function updateIslands(options, newModule) {
222
+ const component = resolveComponent(newModule, options.componentRef ?? '');
223
+ if (!component)
224
+ return;
225
+ options.componentModule = newModule;
226
+ const scriptId = options.scriptId;
227
+ options.runtimeState.islandComponents[scriptId] = component;
228
+ for (const element of document.querySelectorAll(options.targetSelector)) {
229
+ const target = element;
230
+ const record = target.__eco_island;
231
+ if (!record) {
232
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
233
+ continue;
234
+ }
235
+ record.component = component;
236
+ if (!record.hydrated) {
237
+ record.pendingComponent = component;
238
+ continue;
239
+ }
240
+ record.root.render(options.runtime.createElement(IslandLifecycle, {
241
+ target,
242
+ runtime: options.runtime,
243
+ Component: component,
244
+ props: readProps(target),
245
+ }));
246
+ }
247
+ }
@@ -0,0 +1,11 @@
1
+ import type { PageHydrationOptions } from './page-hydration.js';
2
+ /**
3
+ * Imports and applies one HMR page update.
4
+ */
5
+ export declare function handlePageHmr(options: PageHydrationOptions, newUrl: string, generation: number, readPageData: (options: PageHydrationOptions) => {
6
+ moduleUrl?: string;
7
+ props: Record<string, unknown>;
8
+ }, setPageState: (options: PageHydrationOptions, pageData: {
9
+ moduleUrl?: string;
10
+ props: Record<string, unknown>;
11
+ }) => void, getPageDataFromDocument: (options: PageHydrationOptions) => Record<string, unknown>): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { resolvePageModule } from './page-hydration-module.js';
2
+ function getRuntime() {
3
+ return (window.__ECO_PAGES__ ??= {});
4
+ }
5
+ function isCurrentMountGeneration(generation) {
6
+ return (getRuntime().react?.mountGeneration ?? 0) === generation;
7
+ }
8
+ async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, _nextProps) {
9
+ if (!options.hasRouter || getRuntime().navigation?.getOwnerState?.().owner !== 'react-router') {
10
+ return false;
11
+ }
12
+ const currentLayoutStack = options.hmr.getLayoutStack?.(currentPage) ?? '';
13
+ const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage.Page) ?? '';
14
+ await getRuntime().navigation?.reloadCurrentPage?.({
15
+ clearCache: currentLayoutStack !== nextLayoutStack,
16
+ moduleUrl: newUrl,
17
+ source: 'react-router',
18
+ });
19
+ console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated via router`);
20
+ return true;
21
+ }
22
+ function applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation) {
23
+ const activeRoot = getRuntime().react?.pageRoot ?? null;
24
+ if (!activeRoot || !isCurrentMountGeneration(generation))
25
+ return;
26
+ setPageState(options, readPageData(options));
27
+ activeRoot.render(options.createTree(nextPage.Page, nextProps));
28
+ console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
29
+ }
30
+ /**
31
+ * Imports and applies one HMR page update.
32
+ */
33
+ export async function handlePageHmr(options, newUrl, generation, readPageData, setPageState, getPageDataFromDocument) {
34
+ if (!options.hmr || !isCurrentMountGeneration(generation))
35
+ return;
36
+ try {
37
+ const newModule = (await import(/* @vite-ignore */ newUrl));
38
+ if (!isCurrentMountGeneration(generation))
39
+ return;
40
+ const nextPage = resolvePageModule(newModule, options.isMdx, options.normalizePageConfig);
41
+ const nextProps = getPageDataFromDocument(options);
42
+ await nextPage.preload?.(nextProps);
43
+ if (!isCurrentMountGeneration(generation))
44
+ return;
45
+ const currentPage = options.Page;
46
+ options.Page = nextPage.Page;
47
+ options.preload = nextPage.preload;
48
+ if (await applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, nextProps)) {
49
+ return;
50
+ }
51
+ applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation);
52
+ }
53
+ catch (error) {
54
+ console.error(`[ecopages] Failed to hot-reload ${options.isMdx ? 'MDX' : 'React'} component:`, error);
55
+ }
56
+ }
@@ -0,0 +1,8 @@
1
+ export type PageModule = {
2
+ Page: unknown;
3
+ preload?: (props: Record<string, unknown>) => void | Promise<void>;
4
+ };
5
+ /**
6
+ * Normalizes a loaded Page module into the shape used by hydration and HMR.
7
+ */
8
+ export declare function resolvePageModule(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): PageModule;
@@ -0,0 +1,17 @@
1
+ function isPagePreload(value) {
2
+ return typeof value === 'function';
3
+ }
4
+ /**
5
+ * Normalizes a loaded Page module into the shape used by hydration and HMR.
6
+ */
7
+ export function resolvePageModule(module, isMdx, normalizePageConfig) {
8
+ const Page = module.default ?? module;
9
+ if (isMdx && module.config && Page && typeof Page === 'function') {
10
+ Object.assign(Page, { config: module.config });
11
+ normalizePageConfig?.(module.config);
12
+ }
13
+ return {
14
+ Page,
15
+ preload: isPagePreload(module.preload) ? module.preload : undefined,
16
+ };
17
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Browser-side React page lifecycle.
3
+ *
4
+ * @remarks
5
+ * The entry module supplies the page tree and module resolution details. This
6
+ * module owns document state, navigation ownership, cleanup, and HMR so those
7
+ * behaviors stay identical for readable and compiled bootstraps.
8
+ */
9
+ export type PageRoot = {
10
+ render: (tree: unknown) => void;
11
+ unmount: () => void;
12
+ };
13
+ export type PageReactRuntime = {
14
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
15
+ onRecoverableError?: (error: unknown) => void;
16
+ }) => PageRoot;
17
+ createElement: (...args: unknown[]) => unknown;
18
+ };
19
+ export type PageData = {
20
+ moduleUrl?: string;
21
+ props: Record<string, unknown>;
22
+ };
23
+ export type { PageModule } from './page-hydration-module.js';
24
+ export { resolvePageModule } from './page-hydration-module.js';
25
+ /** Configuration passed from a generated Page hydration entry. */
26
+ export type PageHydrationOptions = {
27
+ scriptId: string;
28
+ pageModuleUrl: string;
29
+ Page: unknown;
30
+ pageDataReader: {
31
+ readPageDataDocument: () => PageData;
32
+ getPageDataFromDocument: () => Record<string, unknown>;
33
+ };
34
+ runtime: PageReactRuntime;
35
+ createTree: (Page: unknown, props: Record<string, unknown>) => unknown;
36
+ hasRouter: boolean;
37
+ isMdx: boolean;
38
+ normalizePageConfig?: (config: unknown) => void;
39
+ hmr?: {
40
+ importPath: string;
41
+ getLayoutStack?: (Page: unknown) => string;
42
+ };
43
+ preload?: (props: Record<string, unknown>) => void | Promise<void>;
44
+ };
45
+ /**
46
+ * Registers and starts the Page lifecycle when its persistent script is present.
47
+ *
48
+ * @remarks
49
+ * Restores lifecycle registration, router ownership, and HMR generation binding
50
+ * whenever the page is activated or rerun after navigation.
51
+ *
52
+ * @param options - Generated entry configuration for the current Page.
53
+ */
54
+ export declare function startPageHydration(options: PageHydrationOptions): void;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Browser-side React page lifecycle.
3
+ *
4
+ * @remarks
5
+ * The entry module supplies the page tree and module resolution details. This
6
+ * module owns document state, navigation ownership, cleanup, and HMR so those
7
+ * behaviors stay identical for readable and compiled bootstraps.
8
+ */
9
+ export { resolvePageModule } from './page-hydration-module.js';
10
+ import { handlePageHmr } from './page-hydration-hmr.js';
11
+ /** Returns and lazily initializes the shared page runtime on `window`. */
12
+ function getRuntime() {
13
+ const pageWindow = window;
14
+ const runtime = (pageWindow.__ECO_PAGES__ ??= {});
15
+ runtime.react ??= {};
16
+ return runtime;
17
+ }
18
+ /** Records the development hydration duration when the dev marker is present. */
19
+ function recordHydrationTiming() {
20
+ const pageWindow = window;
21
+ if (pageWindow.__ECO_DEV_HYDRATION_STARTED__ == null)
22
+ return;
23
+ pageWindow.__ECO_DEV_HYDRATION_MS__ = Math.round(performance.now() - pageWindow.__ECO_DEV_HYDRATION_STARTED__);
24
+ }
25
+ /** Reads the current page-data document through the shared reader contract. */
26
+ function readPageData(options) {
27
+ return options.pageDataReader.readPageDataDocument();
28
+ }
29
+ /** Publishes the current module URL and props for router/navigation consumers. */
30
+ function setPageState(options, pageData) {
31
+ const runtime = getRuntime();
32
+ runtime.page = {
33
+ module: pageData.moduleUrl || options.pageModuleUrl,
34
+ props: pageData.props,
35
+ };
36
+ }
37
+ /**
38
+ * Invalidates pending startup, releases the page root, and hands navigation
39
+ * ownership back to the document runtime.
40
+ *
41
+ * @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.
45
+ */
46
+ function cleanupPageRoot(root) {
47
+ const runtime = getRuntime();
48
+ if (runtime.react) {
49
+ runtime.react.mountGeneration = (runtime.react.mountGeneration ?? 0) + 1;
50
+ delete runtime.react.mountPromise;
51
+ }
52
+ const activeRoot = runtime.react?.pageRoot || root;
53
+ runtime.react.pageRoot = null;
54
+ runtime.navigation?.releaseOwnership?.('react-router');
55
+ delete runtime.page;
56
+ activeRoot?.unmount();
57
+ }
58
+ /** Registers React Router as the page navigation owner when this page uses it. */
59
+ function registerRouterOwnership(options) {
60
+ if (!options.hasRouter)
61
+ return;
62
+ const runtime = getRuntime();
63
+ const ownerState = runtime.navigation?.getOwnerState?.();
64
+ if (ownerState?.owner === 'react-router' && ownerState.canHandleSpaNavigation)
65
+ return;
66
+ runtime.navigation?.register?.({
67
+ owner: 'react-router',
68
+ cleanupBeforeHandoff: async () => cleanupPageRoot(runtime.react?.pageRoot ?? null),
69
+ });
70
+ runtime.navigation?.claimOwnership?.('react-router');
71
+ }
72
+ /**
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.
85
+ *
86
+ * @remarks
87
+ * The global handler index can outlive the page. Capturing the generation here
88
+ * makes retained callbacks inert after cleanup, including calls that begin only
89
+ * after another page has mounted. Reactivation renews this binding for the
90
+ * new generation.
91
+ */
92
+ function registerHmr(options) {
93
+ if (!options.hmr)
94
+ return;
95
+ const runtime = getRuntime();
96
+ const generation = runtime.react?.mountGeneration ?? 0;
97
+ runtime.hmrHandlers ??= {};
98
+ runtime.hmrHandlers[options.hmr.importPath] = (newUrl) => handlePageHmr(options, newUrl, generation, readPageData, setPageState, (opts) => opts.pageDataReader.getPageDataFromDocument());
99
+ }
100
+ /**
101
+ * Coalesces concurrent page starts into one promise.
102
+ *
103
+ * @remarks
104
+ * Rerun scripts and DOM-ready callbacks can arrive together. Sharing the
105
+ * pending promise prevents two calls to `hydrateRoot` for document.body.
106
+ */
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;
123
+ }
124
+ /** Performs one page start after the caller has reserved the current generation. */
125
+ async function mountPage(options, generation) {
126
+ const runtime = getRuntime();
127
+ const pageData = readPageData(options);
128
+ setPageState(options, pageData);
129
+ if (runtime.react?.pageRoot) {
130
+ if (!options.hasRouter) {
131
+ runtime.react.pageRoot.render(options.createTree(options.Page, pageData.props));
132
+ }
133
+ return;
134
+ }
135
+ await options.preload?.(pageData.props);
136
+ if (!isCurrentMountGeneration(generation))
137
+ return;
138
+ if (runtime.react?.pageRoot)
139
+ return;
140
+ window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
141
+ const root = options.runtime.hydrateRoot(document.body, options.createTree(options.Page, pageData.props), {
142
+ onRecoverableError: (error) => console.warn('[ecopages] Hydration error:', error),
143
+ });
144
+ runtime.react.pageRoot = root;
145
+ recordHydrationTiming();
146
+ }
147
+ /**
148
+ * Registers and starts the Page lifecycle when its persistent script is present.
149
+ *
150
+ * @remarks
151
+ * Restores lifecycle registration, router ownership, and HMR generation binding
152
+ * whenever the page is activated or rerun after navigation.
153
+ *
154
+ * @param options - Generated entry configuration for the current Page.
155
+ */
156
+ export function startPageHydration(options) {
157
+ if (!document.querySelector(`script[data-eco-script-id="${options.scriptId}"]`))
158
+ return;
159
+ const runtime = getRuntime();
160
+ runtime.react.pageRoot ??= null;
161
+ const initialPageData = readPageData(options);
162
+ setPageState(options, initialPageData);
163
+ const activatePage = () => {
164
+ runtime.react.cleanupPageRoot = () => cleanupPageRoot(runtime.react?.pageRoot ?? null);
165
+ registerRouterOwnership(options);
166
+ registerHmr(options);
167
+ return mount(options);
168
+ };
169
+ runtime.rerunScripts ??= {};
170
+ runtime.rerunScripts[options.scriptId] = activatePage;
171
+ if (document.readyState === 'loading') {
172
+ document.addEventListener('DOMContentLoaded', activatePage, { once: true });
173
+ }
174
+ else {
175
+ void activatePage();
176
+ }
177
+ }
@@ -0,0 +1,20 @@
1
+ /** Complete inputs that affect a Page hydration script's generated source. */
2
+ export type CompiledPageHydrationOptions = {
3
+ importPath: string;
4
+ pageModuleUrlExpression: string;
5
+ scriptId: string;
6
+ reactImportPath: string;
7
+ reactDomClientImportPath: string;
8
+ routerImportPath?: string;
9
+ layoutComposeImportPath: string;
10
+ pageLayoutNormalizationImportPath: string;
11
+ routerComponents?: {
12
+ router: string;
13
+ pageContent: string;
14
+ };
15
+ routerPropsExpression?: string;
16
+ hmrEnabled: boolean;
17
+ isMdx: boolean;
18
+ hasPagePreload: boolean;
19
+ minify: boolean;
20
+ };
@@ -0,0 +1 @@
1
+ export {};