@ecopages/react 0.2.1-beta.0 → 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 (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -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 +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -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/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  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.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Creates the synchronous component lookup required by a Page that preloads
3
+ * collection MDX before SSR, hydration, and client navigation.
4
+ *
5
+ * @remarks
6
+ * `preload()` loads the browser-compiled component and must not run in
7
+ * `staticProps`. A hydratable collection Page primes the cache in `staticProps`
8
+ * with its server component, then exposes a named `preload` export for
9
+ * hydration and client navigation to load the browser component.
10
+ *
11
+ * Completed loads are deliberately refreshed by the next preload. Native
12
+ * module caching keeps that inexpensive while allowing HMR to replace a
13
+ * component before the Page re-renders.
14
+ *
15
+ * `prime()` always stores the provided server component, even when a
16
+ * `preload()` is already in flight. Completions from a superseded load are
17
+ * ignored so they cannot replace the primed entry.
18
+ */
19
+ export function createCollectionComponentCache(loadComponent) {
20
+ const records = new Map();
21
+ const store = async (slug, component) => {
22
+ const pending = {};
23
+ const promise = component.then((resolvedComponent) => {
24
+ if (records.get(slug) === pending.record) {
25
+ records.set(slug, { status: 'success', component: resolvedComponent });
26
+ }
27
+ }, (error) => {
28
+ if (records.get(slug) === pending.record) {
29
+ records.set(slug, { status: 'error', error });
30
+ }
31
+ throw error;
32
+ });
33
+ pending.record = { status: 'pending', promise };
34
+ records.set(slug, pending.record);
35
+ return await promise;
36
+ };
37
+ return {
38
+ async preload(slug) {
39
+ const existing = records.get(slug);
40
+ if (existing?.status === 'pending') {
41
+ return await existing.promise;
42
+ }
43
+ return await store(slug, loadComponent(slug));
44
+ },
45
+ async prime(slug, component) {
46
+ return await store(slug, component);
47
+ },
48
+ get(slug) {
49
+ const record = records.get(slug);
50
+ if (!record) {
51
+ throw new Error(`[ecopages] Collection content '${slug}' was rendered before it was preloaded.`);
52
+ }
53
+ if (record.status === 'success') {
54
+ return record.component;
55
+ }
56
+ if (record.status === 'error') {
57
+ throw record.error;
58
+ }
59
+ throw new Error(`[ecopages] Collection content '${slug}' is still loading during render.`);
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Router adapter interface for React integration.
3
+ * Allows pluggable SPA routers to be used with the React plugin.
4
+ * @module
5
+ */
6
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { EcoBuildPlugin } from '@ecopages/core/integration';
2
+ import type { DevTransformBundleContributor } from '@ecopages/core/integration';
3
+ import type { ReactHmrStrategy } from '../hmr/hmr-strategy.js';
4
+ export type ReactDevTransformContributorOptions = {
5
+ strategy: ReactHmrStrategy;
6
+ };
7
+ /**
8
+ * Supplies React module plugins for the core dev transform bundler.
9
+ */
10
+ export declare class ReactDevTransformContributor implements DevTransformBundleContributor {
11
+ private readonly strategy;
12
+ constructor(options: ReactDevTransformContributorOptions);
13
+ ownsModule(sourcePath: string): boolean;
14
+ getModulePlugins(sourcePath: string): Promise<readonly EcoBuildPlugin[]>;
15
+ getRuntimeSpecifierMap(): ReadonlyMap<string, string>;
16
+ getVendorBundlePlugins(): Promise<readonly EcoBuildPlugin[]>;
17
+ }
@@ -0,0 +1,22 @@
1
+ import { getBrowserRuntimeSpecifierMap } from '@ecopages/core/build';
2
+ /**
3
+ * Supplies React module plugins for the core dev transform bundler.
4
+ */
5
+ export class ReactDevTransformContributor {
6
+ strategy;
7
+ constructor(options) {
8
+ this.strategy = options.strategy;
9
+ }
10
+ ownsModule(sourcePath) {
11
+ return this.strategy.ownsDevTransformEntrypoint(sourcePath);
12
+ }
13
+ async getModulePlugins(sourcePath) {
14
+ return this.strategy.createDevTransformPlugins(sourcePath);
15
+ }
16
+ getRuntimeSpecifierMap() {
17
+ return getBrowserRuntimeSpecifierMap(this.strategy.getRuntimeManifest());
18
+ }
19
+ async getVendorBundlePlugins() {
20
+ return this.strategy.getVendorBundlePlugins();
21
+ }
22
+ }
@@ -0,0 +1,34 @@
1
+ import type { HmrAction } from '@ecopages/core/integration';
2
+ import type { ReactHmrBuildTarget } from './react-hmr-dev-transform-plugins.js';
3
+ export type HmrProcessContext = {
4
+ resolvedFilePath: string;
5
+ watchedFiles: Map<string, string>;
6
+ isLayoutFile: (filePath: string) => boolean;
7
+ isPageEntrypoint: (filePath: string) => boolean;
8
+ isReactEntrypoint: (filePath: string) => boolean;
9
+ ownsWatchedEntrypoint: (filePath: string) => boolean;
10
+ isDevTransformOutputUrl: (outputUrl: string) => boolean;
11
+ collectReactPageBuildTargets: () => Promise<ReactHmrBuildTarget[]>;
12
+ hasLayoutOwnedDependencyTarget: (changedFilePath: string, requestedTargets: ReactHmrBuildTarget[]) => Promise<boolean>;
13
+ resolveBuildTargets: (requestedTargets: ReactHmrBuildTarget[], changedFilePath: string) => Promise<ReactHmrBuildTarget[]>;
14
+ partitionBuildTargets: (requestedTargets: ReactHmrBuildTarget[], groupedPageTargets: ReactHmrBuildTarget[]) => {
15
+ pageTargets: ReactHmrBuildTarget[];
16
+ nonPageTargets: ReactHmrBuildTarget[];
17
+ };
18
+ queueDevTransformOutputUpdates: (targets: readonly ReactHmrBuildTarget[], requestedOutputUrls: ReadonlySet<string>, updates: string[]) => void;
19
+ markOwnedEntrypoint: (filePath: string) => void;
20
+ getDependencyEntrypoints: (filePath: string) => Set<string>;
21
+ };
22
+ export type DependencyScanResult = {
23
+ affectedEntrypoints: Map<string, string>;
24
+ hasOwnedLayoutDependencyHit: boolean;
25
+ shouldAbort: boolean;
26
+ };
27
+ export declare function scanDependencyHits(ctx: HmrProcessContext, changedEntrypointOutput?: string): DependencyScanResult;
28
+ export declare function resolveRequestedTargets(ctx: HmrProcessContext, changedEntrypointOutput: string | undefined, isLayout: boolean, isChangedPageEntrypoint: boolean, hasOwnedLayoutDependencyHit: boolean, affectedEntrypoints: Map<string, string>, hasDependencyHits: boolean): Promise<{
29
+ requestedTargets: ReactHmrBuildTarget[];
30
+ hasLayoutOwnedRequestedTarget: boolean;
31
+ }>;
32
+ export declare function collectHmrUpdateUrls(ctx: HmrProcessContext, requestedTargets: ReactHmrBuildTarget[], pageTargets: ReactHmrBuildTarget[], nonPageTargets: ReactHmrBuildTarget[]): string[];
33
+ export declare function buildHmrAction(requiresLayoutRefresh: boolean, updates: string[]): HmrAction;
34
+ export declare function ensureWatchedEntrypointOwnership(ctx: HmrProcessContext, changedEntrypointOutput: string | undefined): 'continue' | 'abort';
@@ -0,0 +1,83 @@
1
+ import path from 'node:path';
2
+ export function scanDependencyHits(ctx, changedEntrypointOutput) {
3
+ const dependencyHits = ctx.getDependencyEntrypoints(ctx.resolvedFilePath);
4
+ const affectedEntrypoints = new Map();
5
+ let hasOwnedLayoutDependencyHit = false;
6
+ if (dependencyHits.size === 0 || changedEntrypointOutput) {
7
+ return { affectedEntrypoints, hasOwnedLayoutDependencyHit, shouldAbort: false };
8
+ }
9
+ for (const entrypoint of dependencyHits) {
10
+ const resolvedEntrypoint = path.resolve(entrypoint);
11
+ const outputUrl = ctx.watchedFiles.get(resolvedEntrypoint);
12
+ if (outputUrl && (ctx.ownsWatchedEntrypoint(resolvedEntrypoint) || ctx.isDevTransformOutputUrl(outputUrl))) {
13
+ affectedEntrypoints.set(resolvedEntrypoint, outputUrl);
14
+ continue;
15
+ }
16
+ if (ctx.isLayoutFile(resolvedEntrypoint) && ctx.ownsWatchedEntrypoint(resolvedEntrypoint)) {
17
+ hasOwnedLayoutDependencyHit = true;
18
+ }
19
+ }
20
+ const shouldAbort = affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit && !ctx.isLayoutFile(ctx.resolvedFilePath);
21
+ return { affectedEntrypoints, hasOwnedLayoutDependencyHit, shouldAbort };
22
+ }
23
+ export async function resolveRequestedTargets(ctx, changedEntrypointOutput, isLayout, isChangedPageEntrypoint, hasOwnedLayoutDependencyHit, affectedEntrypoints, hasDependencyHits) {
24
+ let layoutOwnedPageTargets = [];
25
+ let hasLayoutOwnedRequestedTarget = false;
26
+ if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
27
+ layoutOwnedPageTargets = await ctx.collectReactPageBuildTargets();
28
+ hasLayoutOwnedRequestedTarget = await ctx.hasLayoutOwnedDependencyTarget(ctx.resolvedFilePath, layoutOwnedPageTargets);
29
+ }
30
+ const requestedTargets = changedEntrypointOutput
31
+ ? hasLayoutOwnedRequestedTarget
32
+ ? [{ entrypointPath: ctx.resolvedFilePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets]
33
+ : [{ entrypointPath: ctx.resolvedFilePath, outputUrl: changedEntrypointOutput }]
34
+ : hasOwnedLayoutDependencyHit
35
+ ? await ctx.collectReactPageBuildTargets()
36
+ : hasDependencyHits
37
+ ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }))
38
+ : Array.from(ctx.watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
39
+ return { requestedTargets, hasLayoutOwnedRequestedTarget };
40
+ }
41
+ export function collectHmrUpdateUrls(ctx, requestedTargets, pageTargets, nonPageTargets) {
42
+ const updates = [];
43
+ const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
44
+ ctx.queueDevTransformOutputUpdates(pageTargets, requestedOutputUrls, updates);
45
+ for (const { outputUrl } of nonPageTargets) {
46
+ if (!requestedOutputUrls.has(outputUrl)) {
47
+ continue;
48
+ }
49
+ if (ctx.isDevTransformOutputUrl(outputUrl)) {
50
+ updates.push(outputUrl);
51
+ }
52
+ }
53
+ return updates;
54
+ }
55
+ export function buildHmrAction(requiresLayoutRefresh, updates) {
56
+ if (requiresLayoutRefresh) {
57
+ return {
58
+ type: 'broadcast',
59
+ events: [{ type: 'layout-update' }],
60
+ };
61
+ }
62
+ if (updates.length > 0) {
63
+ return {
64
+ type: 'broadcast',
65
+ events: updates.map((path) => ({
66
+ type: 'update',
67
+ path,
68
+ timestamp: Date.now(),
69
+ })),
70
+ };
71
+ }
72
+ return { type: 'none' };
73
+ }
74
+ export function ensureWatchedEntrypointOwnership(ctx, changedEntrypointOutput) {
75
+ if (!changedEntrypointOutput || ctx.ownsWatchedEntrypoint(ctx.resolvedFilePath)) {
76
+ return 'continue';
77
+ }
78
+ if (ctx.isReactEntrypoint(ctx.resolvedFilePath)) {
79
+ ctx.markOwnedEntrypoint(ctx.resolvedFilePath);
80
+ return 'continue';
81
+ }
82
+ return 'abort';
83
+ }
@@ -0,0 +1,67 @@
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 { HmrStrategy, type HmrAction } from '@ecopages/core/integration';
10
+ import type { EcoBuildPlugin } from '@ecopages/core/integration';
11
+ import type { BrowserRuntimeManifest } from '@ecopages/core/build';
12
+ import type { DefaultHmrContext } from '@ecopages/core/integration';
13
+ import type { HmrPageMetadataCache } from './page-metadata-cache.js';
14
+ export interface ReactHmrStrategyOptions {
15
+ context: DefaultHmrContext;
16
+ projectRoot?: string;
17
+ pageMetadataCache: HmrPageMetadataCache;
18
+ runtimeManifest: BrowserRuntimeManifest;
19
+ getMdxLoaderPlugin?: () => EcoBuildPlugin;
20
+ ownedTemplateExtensions?: string[];
21
+ allTemplateExtensions?: string[];
22
+ }
23
+ /**
24
+ * Strategy for handling React component HMR updates.
25
+ */
26
+ export declare class ReactHmrStrategy extends HmrStrategy {
27
+ readonly type: 100;
28
+ private readonly getMdxLoaderPlugin?;
29
+ private readonly projectRoot;
30
+ private readonly ownedTemplateExtensions;
31
+ private readonly allTemplateExtensions;
32
+ private readonly context;
33
+ private readonly pageMetadataCache;
34
+ private readonly runtimeManifest;
35
+ private importNodePageModule;
36
+ private getDevTransformPluginOptions;
37
+ constructor(options: ReactHmrStrategyOptions);
38
+ private getBuildPlugins;
39
+ private isReactEntrypoint;
40
+ /**
41
+ * @remarks
42
+ * React integration owns plain `.tsx` route templates. Compound extensions in
43
+ * pages/layouts are integration-specific route templates and should not be
44
+ * claimed by React HMR strategy.
45
+ */
46
+ private isRouteTemplate;
47
+ private resolveTemplateExtension;
48
+ private isDevTransformOutputUrl;
49
+ private queueDevTransformOutputUpdates;
50
+ private ownsWatchedEntrypoint;
51
+ private configContainsFile;
52
+ private pageModuleRequiresLayoutRefresh;
53
+ private hasLayoutOwnedDependencyTarget;
54
+ matches(filePath: string): boolean;
55
+ ownsDevTransformEntrypoint(sourcePath: string): boolean;
56
+ getRuntimeManifest(): BrowserRuntimeManifest;
57
+ getVendorBundlePlugins(): Promise<readonly EcoBuildPlugin[]>;
58
+ createDevTransformPlugins(sourcePath: string): Promise<EcoBuildPlugin[]>;
59
+ private isLayoutFile;
60
+ private isPageEntrypoint;
61
+ private resolveEntrypointOutputUrl;
62
+ private collectReactPageBuildTargets;
63
+ private resolveBuildTargets;
64
+ private partitionBuildTargets;
65
+ private createProcessContext;
66
+ process(_filePath: string): Promise<HmrAction>;
67
+ }
@@ -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
  /**
@@ -19,6 +19,10 @@ export declare class ReactHmrPageMetadataCache {
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
+ }