@ecopages/react 0.2.1 → 0.3.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 (173) hide show
  1. package/README.md +178 -35
  2. package/package.json +80 -32
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.d.ts +1 -0
  6. package/src/app/dynamic.test.browser.js +38 -0
  7. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  8. package/src/bundling/bootstrap-package-paths.js +5 -0
  9. package/src/bundling/bundle.d.ts +78 -0
  10. package/src/bundling/bundle.js +130 -0
  11. package/src/bundling/runtime-alias-map.d.ts +12 -0
  12. package/src/bundling/runtime-alias-map.js +110 -0
  13. package/src/bundling/runtime-bundle.d.ts +70 -0
  14. package/src/bundling/runtime-bundle.js +233 -0
  15. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  16. package/src/bundling/runtime-interop-plugin.js +32 -0
  17. package/src/bundling/runtime-mode.d.ts +1 -0
  18. package/src/bundling/runtime-mode.js +10 -0
  19. package/src/bundling/runtime-modules.d.ts +21 -0
  20. package/src/bundling/runtime-modules.js +28 -0
  21. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  22. package/src/client-graph/ast-transform-eco-page.js +71 -0
  23. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  24. package/src/client-graph/ast-transform-import-edits.js +75 -0
  25. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  26. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  27. package/src/client-graph/ast-transform.d.ts +12 -0
  28. package/src/client-graph/ast-transform.js +91 -0
  29. package/src/client-graph/ast-walk.d.ts +10 -0
  30. package/src/client-graph/ast-walk.js +26 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  32. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  33. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  34. package/src/client-graph/boundary-plugin-transform.js +31 -0
  35. package/src/client-graph/boundary-plugin.d.ts +23 -0
  36. package/src/client-graph/boundary-plugin.js +177 -0
  37. package/src/client-graph/component-config-traversal.d.ts +36 -0
  38. package/src/client-graph/component-config-traversal.js +77 -0
  39. package/src/{utils → client-graph}/declared-modules.d.ts +1 -1
  40. package/src/client-graph/declared-modules.js +69 -0
  41. package/src/client-graph/module-classification.d.ts +3 -0
  42. package/src/client-graph/module-classification.js +43 -0
  43. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  44. package/src/client-graph/reachability-analyzer.js +55 -0
  45. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  46. package/src/client-graph/reachability-client-roots.js +59 -0
  47. package/src/client-graph/reachability-export-names.d.ts +5 -0
  48. package/src/client-graph/reachability-export-names.js +34 -0
  49. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  50. package/src/client-graph/reachability-fallback-roots.js +71 -0
  51. package/src/client-graph/reachability-preload.d.ts +10 -0
  52. package/src/client-graph/reachability-preload.js +30 -0
  53. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  54. package/src/client-graph/reachability-top-level-index.js +93 -0
  55. package/src/client-graph/reachability-traverse.d.ts +7 -0
  56. package/src/client-graph/reachability-traverse.js +201 -0
  57. package/src/client-graph/specifier-classification.d.ts +74 -0
  58. package/src/client-graph/specifier-classification.js +191 -0
  59. package/src/content/collection-component-cache.d.ts +25 -0
  60. package/src/content/collection-component-cache.js +62 -0
  61. package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +7 -14
  62. package/src/contracts/router-adapter.js +6 -0
  63. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  64. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  65. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  66. package/src/hmr/hmr-strategy-process.js +83 -0
  67. package/src/hmr/hmr-strategy.d.ts +67 -0
  68. package/src/hmr/hmr-strategy.js +306 -0
  69. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +6 -2
  70. package/src/hmr/page-metadata-cache.js +44 -0
  71. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  72. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  73. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  74. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  75. package/src/hydration/bootstrap-imports.d.ts +25 -0
  76. package/src/hydration/bootstrap-imports.js +33 -0
  77. package/src/hydration/browser/island-hydration.d.ts +82 -0
  78. package/src/hydration/browser/island-hydration.js +251 -0
  79. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  80. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  81. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  82. package/src/hydration/browser/page-hydration-module.js +17 -0
  83. package/src/hydration/browser/page-hydration.d.ts +54 -0
  84. package/src/hydration/browser/page-hydration.js +177 -0
  85. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  86. package/src/hydration/compiled-page-hydration-options.js +1 -0
  87. package/src/hydration/hydration-asset.d.ts +127 -0
  88. package/src/hydration/hydration-asset.js +379 -0
  89. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  90. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  91. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  92. package/src/hydration/hydration-page-entry-source.js +87 -0
  93. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  94. package/src/hydration/hydration-script-compiler.js +213 -0
  95. package/src/hydration/page-data-manifest.d.ts +58 -0
  96. package/src/hydration/page-data-manifest.js +97 -0
  97. package/src/hydration/page-data-reader.d.ts +17 -0
  98. package/src/hydration/page-data-reader.js +31 -0
  99. package/src/hydration/page-payload.d.ts +68 -0
  100. package/src/hydration/page-payload.js +106 -0
  101. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  102. package/src/hydration/serialize-page-data-script.js +30 -0
  103. package/src/mdx/mdx-config-dependency.d.ts +37 -0
  104. package/src/mdx/mdx-config-dependency.js +107 -0
  105. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  106. package/src/mdx/mdx-loader-plugin.js +11 -0
  107. package/src/page/page-module.d.ts +46 -0
  108. package/src/page/page-module.js +74 -0
  109. package/src/plugin/react.constants.d.ts +1 -0
  110. package/src/plugin/react.constants.js +1 -0
  111. package/src/plugin/react.plugin.d.ts +71 -0
  112. package/src/plugin/react.plugin.js +210 -0
  113. package/src/plugin/react.types.d.ts +106 -0
  114. package/src/plugin/react.types.js +1 -0
  115. package/src/render/component-ownership.d.ts +49 -0
  116. package/src/render/component-ownership.js +47 -0
  117. package/src/render/component-ssr.d.ts +59 -0
  118. package/src/render/component-ssr.js +76 -0
  119. package/src/render/eco-embed.d.ts +11 -0
  120. package/src/render/eco-embed.js +9 -0
  121. package/src/render/errors.d.ts +16 -0
  122. package/src/render/errors.js +23 -0
  123. package/src/render/html-boundary.js +59 -0
  124. package/src/render/layout-compose.d.ts +66 -0
  125. package/src/render/layout-compose.js +134 -0
  126. package/src/render/react-renderer.d.ts +114 -0
  127. package/src/render/react-renderer.js +490 -0
  128. package/src/render/react-runtime.d.ts +13 -0
  129. package/src/render/react-runtime.js +26 -0
  130. package/src/render/unified-layout-composition.d.ts +22 -0
  131. package/src/render/unified-layout-composition.js +31 -0
  132. package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
  133. package/src/runtime/use-sync-external-store-with-selector.js +54 -0
  134. package/CHANGELOG.md +0 -29
  135. package/src/react-hmr-strategy.d.ts +0 -148
  136. package/src/react-hmr-strategy.js +0 -313
  137. package/src/react-renderer.d.ts +0 -213
  138. package/src/react-renderer.js +0 -654
  139. package/src/react.plugin.d.ts +0 -147
  140. package/src/react.plugin.js +0 -146
  141. package/src/router-adapter.js +0 -0
  142. package/src/services/react-bundle.service.d.ts +0 -47
  143. package/src/services/react-bundle.service.js +0 -93
  144. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  145. package/src/services/react-hydration-asset.service.d.ts +0 -76
  146. package/src/services/react-hydration-asset.service.js +0 -210
  147. package/src/services/react-page-module.service.d.ts +0 -83
  148. package/src/services/react-page-module.service.js +0 -162
  149. package/src/services/react-runtime-bundle.service.d.ts +0 -40
  150. package/src/services/react-runtime-bundle.service.js +0 -130
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -43
  152. package/src/utils/client-graph-boundary-plugin.js +0 -494
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/declared-modules.js +0 -59
  155. package/src/utils/dynamic.js +0 -12
  156. package/src/utils/hmr-scripts.d.ts +0 -18
  157. package/src/utils/hmr-scripts.js +0 -31
  158. package/src/utils/html-boundary.js +0 -55
  159. package/src/utils/hydration-scripts.d.ts +0 -86
  160. package/src/utils/hydration-scripts.js +0 -285
  161. package/src/utils/reachability-analyzer.d.ts +0 -66
  162. package/src/utils/reachability-analyzer.js +0 -339
  163. package/src/utils/react-dom-runtime-interop-plugin.js +0 -29
  164. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  165. package/src/utils/react-mdx-loader-plugin.js +0 -45
  166. package/src/utils/react-runtime-specifier-map.d.ts +0 -6
  167. package/src/utils/react-runtime-specifier-map.js +0 -37
  168. package/src/utils/use-sync-external-store-shim-plugin.d.ts +0 -5
  169. package/src/utils/use-sync-external-store-shim-plugin.js +0 -41
  170. /package/src/{utils → app}/client-only.d.ts +0 -0
  171. /package/src/{utils → app}/dynamic.d.ts +0 -0
  172. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  173. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,306 @@
1
+ /**
2
+ * React HMR Strategy
3
+ *
4
+ * Handles hot module replacement for React components.
5
+ * Triggers module invalidation on changes to ensure fresh component re-renders.
6
+ *
7
+ * @module
8
+ */
9
+ import path from 'node:path';
10
+ import { HmrStrategy, HmrStrategyType } from '@ecopages/core/integration';
11
+ import { isRegisteredScriptEntrypoint } from '@ecopages/core/integration';
12
+ import { DEV_TRANSFORM_URL_PREFIX } from '@ecopages/core/integration';
13
+ import { isPathInside } from '@ecopages/core/build';
14
+ import { createBrowserRuntimePlugin } from '@ecopages/core/build';
15
+ import { Logger } from '@ecopages/logger';
16
+ import { createClientGraphBoundaryPlugin } from '../client-graph/boundary-plugin.js';
17
+ import { someInConfigTree } from '../client-graph/component-config-traversal.js';
18
+ import { getReactClientGraphAllowSpecifiers } from '../bundling/runtime-alias-map.js';
19
+ import { getComponentIdentity } from '@ecopages/core';
20
+ import { buildReactDevTransformPlugins, resolveReactDeclaredModulesForEntrypoint, } from './react-hmr-dev-transform-plugins.js';
21
+ import { buildHmrAction, collectHmrUpdateUrls, ensureWatchedEntrypointOwnership, resolveRequestedTargets, scanDependencyHits, } from './hmr-strategy-process.js';
22
+ const appLogger = new Logger('[ReactHmrStrategy]');
23
+ /**
24
+ * Strategy for handling React component HMR updates.
25
+ */
26
+ export class ReactHmrStrategy extends HmrStrategy {
27
+ type = HmrStrategyType.INTEGRATION;
28
+ getMdxLoaderPlugin;
29
+ projectRoot;
30
+ ownedTemplateExtensions;
31
+ allTemplateExtensions;
32
+ context;
33
+ pageMetadataCache;
34
+ runtimeManifest;
35
+ async importNodePageModule(entrypointPath) {
36
+ return await this.context.importServerModule(entrypointPath);
37
+ }
38
+ getDevTransformPluginOptions() {
39
+ return {
40
+ pageMetadataCache: this.pageMetadataCache,
41
+ getMdxLoaderPlugin: this.getMdxLoaderPlugin,
42
+ getBuildPlugins: (declaredModules) => this.getBuildPlugins(declaredModules),
43
+ importNodePageModule: (entrypointPath) => this.importNodePageModule(entrypointPath),
44
+ };
45
+ }
46
+ constructor(options) {
47
+ super();
48
+ this.context = options.context;
49
+ this.projectRoot = options.projectRoot ?? path.dirname(this.context.getSrcDir());
50
+ this.pageMetadataCache = options.pageMetadataCache;
51
+ this.runtimeManifest = options.runtimeManifest;
52
+ this.getMdxLoaderPlugin = options.getMdxLoaderPlugin;
53
+ this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? ['.tsx']);
54
+ this.allTemplateExtensions = [...(options.allTemplateExtensions ?? ['.tsx'])].sort((a, b) => b.length - a.length);
55
+ }
56
+ getBuildPlugins(declaredModules) {
57
+ const allowSpecifiers = getReactClientGraphAllowSpecifiers(this.runtimeManifest.assets.map((asset) => asset.specifier));
58
+ const runtimeRewritePlugin = createBrowserRuntimePlugin({
59
+ name: 'react-hmr-runtime-import-rewrite',
60
+ manifest: this.runtimeManifest,
61
+ });
62
+ return [
63
+ createClientGraphBoundaryPlugin({
64
+ projectRoot: this.projectRoot,
65
+ absWorkingDir: this.projectRoot,
66
+ alwaysAllowSpecifiers: allowSpecifiers,
67
+ declaredModules,
68
+ }),
69
+ ...(runtimeRewritePlugin ? [runtimeRewritePlugin] : []),
70
+ ];
71
+ }
72
+ isReactEntrypoint(filePath) {
73
+ if (filePath.endsWith('.mdx')) {
74
+ return this.getMdxLoaderPlugin !== undefined;
75
+ }
76
+ if (!filePath.endsWith('.tsx')) {
77
+ return false;
78
+ }
79
+ const templateExtension = this.resolveTemplateExtension(filePath);
80
+ if (templateExtension && templateExtension !== '.tsx') {
81
+ return this.ownedTemplateExtensions.has(templateExtension);
82
+ }
83
+ if (!this.isRouteTemplate(filePath)) {
84
+ return true;
85
+ }
86
+ if (!templateExtension) {
87
+ return false;
88
+ }
89
+ return this.ownedTemplateExtensions.has(templateExtension);
90
+ }
91
+ /**
92
+ * @remarks
93
+ * React integration owns plain `.tsx` route templates. Compound extensions in
94
+ * pages/layouts are integration-specific route templates and should not be
95
+ * claimed by React HMR strategy.
96
+ */
97
+ isRouteTemplate(filePath) {
98
+ return (isPathInside(filePath, this.context.getPagesDir()) || isPathInside(filePath, this.context.getLayoutsDir()));
99
+ }
100
+ resolveTemplateExtension(filePath) {
101
+ return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
102
+ }
103
+ isDevTransformOutputUrl(outputUrl) {
104
+ return outputUrl.startsWith(`${DEV_TRANSFORM_URL_PREFIX}/`);
105
+ }
106
+ queueDevTransformOutputUpdates(targets, requestedOutputUrls, updates) {
107
+ for (const { outputUrl } of targets) {
108
+ if (requestedOutputUrls.has(outputUrl)) {
109
+ updates.push(outputUrl);
110
+ }
111
+ }
112
+ }
113
+ ownsWatchedEntrypoint(filePath) {
114
+ return this.pageMetadataCache.ownsEntrypoint(filePath);
115
+ }
116
+ configContainsFile(config, filePath) {
117
+ const resolvedFilePath = path.resolve(filePath);
118
+ return someInConfigTree(config, (node) => {
119
+ const identity = getComponentIdentity(node);
120
+ if (!identity?.file) {
121
+ return false;
122
+ }
123
+ return path.resolve(identity.file) === resolvedFilePath;
124
+ });
125
+ }
126
+ pageModuleRequiresLayoutRefresh(pageModule, filePath) {
127
+ return [pageModule.default?.config, pageModule.config].some((config) => {
128
+ return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
129
+ });
130
+ }
131
+ async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
132
+ for (const target of requestedTargets) {
133
+ if (!this.isPageEntrypoint(target.entrypointPath)) {
134
+ continue;
135
+ }
136
+ const pageModule = await this.importNodePageModule(target.entrypointPath);
137
+ if (this.pageModuleRequiresLayoutRefresh(pageModule, changedFilePath)) {
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ matches(filePath) {
144
+ const watchedFiles = this.context.getWatchedFiles();
145
+ const resolvedFilePath = path.resolve(filePath);
146
+ appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
147
+ if (isRegisteredScriptEntrypoint(this.context.getRegisteredEntrypoints(), resolvedFilePath)) {
148
+ return false;
149
+ }
150
+ if (watchedFiles.has(resolvedFilePath)) {
151
+ if (this.ownsWatchedEntrypoint(resolvedFilePath)) {
152
+ return true;
153
+ }
154
+ const outputUrl = watchedFiles.get(resolvedFilePath);
155
+ if (outputUrl && this.isDevTransformOutputUrl(outputUrl) && this.isReactEntrypoint(resolvedFilePath)) {
156
+ return true;
157
+ }
158
+ return false;
159
+ }
160
+ const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
161
+ if (dependencyHits.size > 0) {
162
+ for (const entrypoint of dependencyHits) {
163
+ if (this.ownsWatchedEntrypoint(entrypoint)) {
164
+ return true;
165
+ }
166
+ }
167
+ return false;
168
+ }
169
+ return this.isReactEntrypoint(filePath);
170
+ }
171
+ ownsDevTransformEntrypoint(sourcePath) {
172
+ if (!this.isReactEntrypoint(sourcePath)) {
173
+ return false;
174
+ }
175
+ return isPathInside(sourcePath, this.context.getSrcDir());
176
+ }
177
+ getRuntimeManifest() {
178
+ return this.runtimeManifest;
179
+ }
180
+ async getVendorBundlePlugins() {
181
+ return this.getBuildPlugins();
182
+ }
183
+ async createDevTransformPlugins(sourcePath) {
184
+ const shouldResolveDeclaredModules = this.isPageEntrypoint(sourcePath) || sourcePath.endsWith('.mdx');
185
+ const declaredModules = shouldResolveDeclaredModules
186
+ ? await resolveReactDeclaredModulesForEntrypoint(this.getDevTransformPluginOptions(), sourcePath)
187
+ : [];
188
+ return buildReactDevTransformPlugins(this.getDevTransformPluginOptions(), declaredModules, sourcePath.endsWith('.mdx'));
189
+ }
190
+ isLayoutFile(filePath) {
191
+ return isPathInside(filePath, this.context.getLayoutsDir());
192
+ }
193
+ isPageEntrypoint(filePath) {
194
+ return isPathInside(filePath, this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
195
+ }
196
+ resolveEntrypointOutputUrl(entrypointPath) {
197
+ return this.context.getWatchedFiles().get(path.resolve(entrypointPath));
198
+ }
199
+ async collectReactPageBuildTargets() {
200
+ const targets = new Map();
201
+ for (const entrypointPath of this.pageMetadataCache.getOwnedEntrypoints()) {
202
+ if (!this.isPageEntrypoint(entrypointPath)) {
203
+ continue;
204
+ }
205
+ const outputUrl = this.resolveEntrypointOutputUrl(entrypointPath);
206
+ if (!outputUrl) {
207
+ continue;
208
+ }
209
+ targets.set(entrypointPath, {
210
+ entrypointPath,
211
+ outputUrl,
212
+ });
213
+ }
214
+ return Array.from(targets.values()).sort((left, right) => left.entrypointPath.localeCompare(right.entrypointPath));
215
+ }
216
+ async resolveBuildTargets(requestedTargets, changedFilePath) {
217
+ const requestedPageTargets = requestedTargets.filter((target) => this.isPageEntrypoint(target.entrypointPath));
218
+ const shouldGroupPageBuilds = this.isLayoutFile(changedFilePath) || requestedPageTargets.length > 0;
219
+ if (!shouldGroupPageBuilds) {
220
+ return [];
221
+ }
222
+ const groupedTargets = new Map(requestedPageTargets.map((target) => [target.entrypointPath, target]));
223
+ for (const target of await this.collectReactPageBuildTargets()) {
224
+ if (!groupedTargets.has(target.entrypointPath)) {
225
+ groupedTargets.set(target.entrypointPath, target);
226
+ }
227
+ }
228
+ return Array.from(groupedTargets.values()).sort((left, right) => left.entrypointPath.localeCompare(right.entrypointPath));
229
+ }
230
+ partitionBuildTargets(requestedTargets, groupedPageTargets) {
231
+ if (groupedPageTargets.length === 0) {
232
+ return {
233
+ pageTargets: [],
234
+ nonPageTargets: requestedTargets,
235
+ };
236
+ }
237
+ const groupedPageEntrypoints = new Set(groupedPageTargets.map((target) => target.entrypointPath));
238
+ return {
239
+ pageTargets: groupedPageTargets,
240
+ nonPageTargets: requestedTargets.filter((target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)),
241
+ };
242
+ }
243
+ createProcessContext(resolvedFilePath, watchedFiles) {
244
+ return {
245
+ resolvedFilePath,
246
+ watchedFiles,
247
+ isLayoutFile: (filePath) => this.isLayoutFile(filePath),
248
+ isPageEntrypoint: (filePath) => this.isPageEntrypoint(filePath),
249
+ isReactEntrypoint: (filePath) => this.isReactEntrypoint(filePath),
250
+ ownsWatchedEntrypoint: (filePath) => this.ownsWatchedEntrypoint(filePath),
251
+ isDevTransformOutputUrl: (outputUrl) => this.isDevTransformOutputUrl(outputUrl),
252
+ collectReactPageBuildTargets: () => this.collectReactPageBuildTargets(),
253
+ hasLayoutOwnedDependencyTarget: (changedFilePath, requestedTargets) => this.hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets),
254
+ resolveBuildTargets: (requestedTargets, changedFilePath) => this.resolveBuildTargets(requestedTargets, changedFilePath),
255
+ partitionBuildTargets: (requestedTargets, groupedPageTargets) => this.partitionBuildTargets(requestedTargets, groupedPageTargets),
256
+ queueDevTransformOutputUpdates: (targets, requestedOutputUrls, updates) => this.queueDevTransformOutputUpdates(targets, requestedOutputUrls, updates),
257
+ markOwnedEntrypoint: (filePath) => this.pageMetadataCache.markOwnedEntrypoint(filePath),
258
+ getDependencyEntrypoints: (filePath) => this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(filePath),
259
+ };
260
+ }
261
+ async process(_filePath) {
262
+ appLogger.debug(`Processing ${_filePath}`);
263
+ const resolvedFilePath = path.resolve(_filePath);
264
+ const watchedFiles = this.context.getWatchedFiles();
265
+ if (watchedFiles.size === 0) {
266
+ appLogger.debug(`No watched files`);
267
+ return { type: 'none' };
268
+ }
269
+ const processContext = this.createProcessContext(resolvedFilePath, watchedFiles);
270
+ const isLayout = processContext.isLayoutFile(resolvedFilePath);
271
+ const isChangedPageEntrypoint = processContext.isPageEntrypoint(resolvedFilePath);
272
+ if (isLayout) {
273
+ appLogger.debug(`Detected layout file change: ${resolvedFilePath}`);
274
+ }
275
+ const changedEntrypointOutput = watchedFiles.get(resolvedFilePath);
276
+ if (ensureWatchedEntrypointOwnership(processContext, changedEntrypointOutput) === 'abort') {
277
+ appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
278
+ return { type: 'none' };
279
+ }
280
+ const dependencyHits = processContext.getDependencyEntrypoints(resolvedFilePath);
281
+ const dependencyScan = scanDependencyHits(processContext, changedEntrypointOutput);
282
+ if (dependencyScan.shouldAbort) {
283
+ appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
284
+ return { type: 'none' };
285
+ }
286
+ const { requestedTargets, hasLayoutOwnedRequestedTarget: initialLayoutOwned } = await resolveRequestedTargets(processContext, changedEntrypointOutput, isLayout, isChangedPageEntrypoint, dependencyScan.hasOwnedLayoutDependencyHit, dependencyScan.affectedEntrypoints, dependencyHits.size > 0);
287
+ const groupedPageTargets = await processContext.resolveBuildTargets(requestedTargets, resolvedFilePath);
288
+ const { pageTargets, nonPageTargets } = processContext.partitionBuildTargets(requestedTargets, groupedPageTargets);
289
+ let hasLayoutOwnedRequestedTarget = initialLayoutOwned;
290
+ if (!changedEntrypointOutput) {
291
+ hasLayoutOwnedRequestedTarget = await processContext.hasLayoutOwnedDependencyTarget(resolvedFilePath, requestedTargets);
292
+ }
293
+ const requiresLayoutRefresh = isLayout || dependencyScan.hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
294
+ const updates = collectHmrUpdateUrls(processContext, requestedTargets, pageTargets, nonPageTargets);
295
+ if (requiresLayoutRefresh) {
296
+ appLogger.debug(`Layout update detected, sending layout-update event`);
297
+ }
298
+ else if (updates.length > 0) {
299
+ appLogger.debug(`Broadcasting ${updates.length} updates`);
300
+ }
301
+ else {
302
+ appLogger.debug(`No updates generated`);
303
+ }
304
+ return buildHmrAction(requiresLayoutRefresh, updates);
305
+ }
306
+ }
@@ -4,7 +4,7 @@
4
4
  * This keeps React Fast Refresh optimizations local to the React integration so
5
5
  * core HMR interfaces do not need React-specific metadata hooks.
6
6
  */
7
- export declare class ReactHmrPageMetadataCache {
7
+ export declare class HmrPageMetadataCache {
8
8
  private readonly declaredModulesByEntrypoint;
9
9
  private readonly ownedEntrypoints;
10
10
  /**
@@ -14,11 +14,15 @@ export declare class ReactHmrPageMetadataCache {
14
14
  /**
15
15
  * Stores the declared browser modules for a page entrypoint.
16
16
  */
17
- setDeclaredModules(entrypointPath: string, declaredModules: string[]): void;
17
+ setDeclaredModules(entrypointPath: string, declaredModules: readonly string[]): void;
18
18
  /**
19
19
  * Returns the last known declared browser modules for a page entrypoint.
20
20
  */
21
21
  getDeclaredModules(entrypointPath: string): string[] | undefined;
22
+ /**
23
+ * Returns React-owned page entrypoints discovered during development renders.
24
+ */
25
+ getOwnedEntrypoints(): string[];
22
26
  /**
23
27
  * Returns true when the watched entrypoint is owned by the React integration.
24
28
  */
@@ -0,0 +1,44 @@
1
+ import path from 'node:path';
2
+ /**
3
+ * React-only cache for page metadata that HMR rebuilds need during development.
4
+ *
5
+ * This keeps React Fast Refresh optimizations local to the React integration so
6
+ * core HMR interfaces do not need React-specific metadata hooks.
7
+ */
8
+ export class HmrPageMetadataCache {
9
+ declaredModulesByEntrypoint = new Map();
10
+ ownedEntrypoints = new Set();
11
+ /**
12
+ * Marks an HMR entrypoint as React-owned.
13
+ */
14
+ markOwnedEntrypoint(entrypointPath) {
15
+ this.ownedEntrypoints.add(path.resolve(entrypointPath));
16
+ }
17
+ /**
18
+ * Stores the declared browser modules for a page entrypoint.
19
+ */
20
+ setDeclaredModules(entrypointPath, declaredModules) {
21
+ const resolvedEntrypointPath = path.resolve(entrypointPath);
22
+ this.markOwnedEntrypoint(resolvedEntrypointPath);
23
+ this.declaredModulesByEntrypoint.set(resolvedEntrypointPath, [...declaredModules]);
24
+ }
25
+ /**
26
+ * Returns the last known declared browser modules for a page entrypoint.
27
+ */
28
+ getDeclaredModules(entrypointPath) {
29
+ const declaredModules = this.declaredModulesByEntrypoint.get(path.resolve(entrypointPath));
30
+ return declaredModules ? [...declaredModules] : undefined;
31
+ }
32
+ /**
33
+ * Returns React-owned page entrypoints discovered during development renders.
34
+ */
35
+ getOwnedEntrypoints() {
36
+ return [...this.ownedEntrypoints].sort((left, right) => left.localeCompare(right));
37
+ }
38
+ /**
39
+ * Returns true when the watched entrypoint is owned by the React integration.
40
+ */
41
+ ownsEntrypoint(entrypointPath) {
42
+ return this.ownedEntrypoints.has(path.resolve(entrypointPath));
43
+ }
44
+ }
@@ -0,0 +1,22 @@
1
+ import type { EcoBuildPlugin } from '@ecopages/core/integration';
2
+ import type { EcoComponentConfig } from '@ecopages/core';
3
+ import type { HmrPageMetadataCache } from './page-metadata-cache.js';
4
+ export type ReactHmrBuildTarget = {
5
+ entrypointPath: string;
6
+ outputUrl: string;
7
+ };
8
+ type ImportedReactPageModule = {
9
+ default?: {
10
+ config?: EcoComponentConfig;
11
+ };
12
+ config?: EcoComponentConfig;
13
+ };
14
+ export type ReactHmrDevTransformPluginOptions = {
15
+ pageMetadataCache: HmrPageMetadataCache;
16
+ getMdxLoaderPlugin?: () => EcoBuildPlugin;
17
+ getBuildPlugins: (declaredModules?: readonly string[]) => EcoBuildPlugin[];
18
+ importNodePageModule: (entrypointPath: string) => Promise<ImportedReactPageModule>;
19
+ };
20
+ export declare function resolveReactDeclaredModulesForEntrypoint(options: ReactHmrDevTransformPluginOptions, entrypointPath: string): Promise<readonly string[]>;
21
+ export declare function buildReactDevTransformPlugins(options: ReactHmrDevTransformPluginOptions, declaredModules: readonly string[], shouldEnableMdx: boolean): EcoBuildPlugin[];
22
+ export {};
@@ -0,0 +1,19 @@
1
+ import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from '../client-graph/declared-modules.js';
2
+ export async function resolveReactDeclaredModulesForEntrypoint(options, entrypointPath) {
3
+ const cached = options.pageMetadataCache.getDeclaredModules(entrypointPath);
4
+ if (cached) {
5
+ return cached;
6
+ }
7
+ const declaredModules = entrypointPath.endsWith('.mdx')
8
+ ? await collectPageDeclaredModules(entrypointPath)
9
+ : collectPageDeclaredModulesFromModule(await options.importNodePageModule(entrypointPath));
10
+ options.pageMetadataCache.setDeclaredModules(entrypointPath, declaredModules);
11
+ return declaredModules;
12
+ }
13
+ export function buildReactDevTransformPlugins(options, declaredModules, shouldEnableMdx) {
14
+ const plugins = options.getBuildPlugins(declaredModules);
15
+ if (shouldEnableMdx && options.getMdxLoaderPlugin) {
16
+ plugins.unshift(options.getMdxLoaderPlugin());
17
+ }
18
+ return plugins;
19
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
3
+ */
4
+ export declare function assertNoBareEcopagesImports(source: string): void;
@@ -0,0 +1,7 @@
1
+ import { expect } from 'vitest';
2
+ /**
3
+ * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
4
+ */
5
+ export function assertNoBareEcopagesImports(source) {
6
+ expect(source).not.toMatch(/from\s+["']@ecopages\//);
7
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import type { ReactRuntimeImports } from '../bundling/runtime-bundle.js';
10
+ export type HydrationBootstrapImportPaths = {
11
+ reactImportPath: string;
12
+ reactDomClientImportPath: string;
13
+ routerImportPath?: string;
14
+ layoutComposeImportPath: string;
15
+ pageLayoutNormalizationImportPath: string;
16
+ };
17
+ export type ResolveHydrationBootstrapImportsOptions = {
18
+ useBrowserRuntimeImports: boolean;
19
+ runtimeImports: ReactRuntimeImports;
20
+ routerAdapterImportPath?: string;
21
+ };
22
+ /**
23
+ * Returns import paths for React page hydration scripts.
24
+ */
25
+ export declare function resolveHydrationBootstrapImports(options: ResolveHydrationBootstrapImportsOptions): HydrationBootstrapImportPaths;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import { LAYOUT_COMPOSE_PACKAGE, PAGE_LAYOUT_NORMALIZATION_PACKAGE } from '../bundling/bootstrap-package-paths.js';
10
+ /**
11
+ * Returns import paths for React page hydration scripts.
12
+ */
13
+ export function resolveHydrationBootstrapImports(options) {
14
+ const { useBrowserRuntimeImports, runtimeImports, routerAdapterImportPath } = options;
15
+ if (useBrowserRuntimeImports) {
16
+ return {
17
+ reactImportPath: runtimeImports.react,
18
+ reactDomClientImportPath: runtimeImports.reactDomClient,
19
+ ...(runtimeImports.router || routerAdapterImportPath
20
+ ? { routerImportPath: runtimeImports.router ?? routerAdapterImportPath }
21
+ : {}),
22
+ layoutComposeImportPath: runtimeImports.layoutCompose,
23
+ pageLayoutNormalizationImportPath: runtimeImports.pageLayoutNormalization,
24
+ };
25
+ }
26
+ return {
27
+ reactImportPath: 'react',
28
+ reactDomClientImportPath: 'react-dom/client',
29
+ ...(routerAdapterImportPath ? { routerImportPath: routerAdapterImportPath } : {}),
30
+ layoutComposeImportPath: LAYOUT_COMPOSE_PACKAGE,
31
+ pageLayoutNormalizationImportPath: PAGE_LAYOUT_NORMALIZATION_PACKAGE,
32
+ };
33
+ }
@@ -0,0 +1,82 @@
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
+ export type IslandComponent = (props: Record<string, unknown>) => unknown;
10
+ export type IslandReactRuntime = {
11
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
12
+ onRecoverableError?: (error: unknown) => void;
13
+ }) => IslandRoot;
14
+ createElement: (type: unknown, props: Record<string, unknown>) => unknown;
15
+ useEffect: (effect: () => void, dependencies: unknown[]) => void;
16
+ };
17
+ export type IslandRoot = {
18
+ render: (tree: unknown) => void;
19
+ unmount: () => void;
20
+ };
21
+ /** Shared browser state for all Island Host entries on one document. */
22
+ export type IslandHydrationRuntime = {
23
+ islandRoots: Record<string, IslandRoot>;
24
+ islandComponents: Record<string, IslandComponent>;
25
+ observer?: MutationObserver;
26
+ };
27
+ /** Configuration for one compiled React Island Host entry. */
28
+ export type IslandHydrationOptions = {
29
+ targetSelector: string;
30
+ componentModule: Record<string, unknown>;
31
+ componentRef?: string;
32
+ componentFile?: string;
33
+ scriptId: string;
34
+ runtime: IslandReactRuntime;
35
+ runtimeState: IslandHydrationRuntime;
36
+ };
37
+ /**
38
+ * Returns the shared page runtime used by all React Island Host entries.
39
+ *
40
+ * @remarks
41
+ * Keeping initialization here means generated entries only describe their
42
+ * component and selector; they do not duplicate global runtime setup.
43
+ *
44
+ * @returns The shared mutable state used by all island entries on this page.
45
+ */
46
+ export declare function getIslandHydrationRuntime(): IslandHydrationRuntime;
47
+ /**
48
+ * Registers the development HMR callback for one component module.
49
+ *
50
+ * @remarks
51
+ * The callback imports the replacement module and delegates to
52
+ * {@link updateIslands}, which updates every live host matching this entry.
53
+ * The dynamic import function is supplied by the generated entry so HMR keeps
54
+ * the browser's normal module-resolution behavior.
55
+ *
56
+ * @param options - Entry configuration whose hosts should receive updates.
57
+ * @param importModule - Browser dynamic-import function for the replacement module.
58
+ * @param importPath - HMR source URL used as the global handler key.
59
+ */
60
+ export declare function registerIslandHmr(options: IslandHydrationOptions, importModule: (url: string) => Promise<Record<string, unknown>>, importPath?: string): void;
61
+ /**
62
+ * Hydrates every eligible host for one component entry.
63
+ *
64
+ * @remarks
65
+ * Existing host records are skipped. This makes rerun scripts idempotent and
66
+ * avoids calling `render` while an initial `hydrateRoot` commit is
67
+ * still pending.
68
+ *
69
+ * @param options - Component, selector, React runtime, and shared state for the entry.
70
+ */
71
+ export declare function mountIslands(options: IslandHydrationOptions): void;
72
+ /**
73
+ * Applies a hot-reloaded component to every live host owned by this entry.
74
+ *
75
+ * @remarks
76
+ * Updates arriving before the initial commit are stored on each host and
77
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
78
+ *
79
+ * @param options - The live entry configuration and runtime state.
80
+ * @param newModule - Newly imported component module.
81
+ */
82
+ export declare function updateIslands(options: IslandHydrationOptions, newModule: Record<string, unknown>): void;