@ecopages/react 0.2.0-beta.31 → 0.2.0-beta.33

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 (57) hide show
  1. package/README.md +5 -1
  2. package/package.json +4 -4
  3. package/src/app/client-only.js +13 -17
  4. package/src/app/dynamic.js +7 -10
  5. package/src/app/dynamic.test.browser.js +27 -29
  6. package/src/bundling/bootstrap-package-paths.js +5 -6
  7. package/src/bundling/bundle.js +115 -114
  8. package/src/bundling/discover-layout-runtime-modules.js +166 -155
  9. package/src/bundling/runtime-alias-map.d.ts +4 -1
  10. package/src/bundling/runtime-alias-map.js +107 -95
  11. package/src/bundling/runtime-bundle.js +250 -274
  12. package/src/bundling/runtime-interop-plugin.js +31 -35
  13. package/src/bundling/runtime-mode.js +10 -5
  14. package/src/bundling/runtime-modules.js +46 -35
  15. package/src/client-graph/ast-transform.js +415 -305
  16. package/src/client-graph/boundary-cache.js +146 -104
  17. package/src/client-graph/boundary-plugin.js +122 -104
  18. package/src/client-graph/component-config-traversal.js +70 -49
  19. package/src/client-graph/declared-modules.js +63 -41
  20. package/src/client-graph/reachability-analyzer.js +506 -313
  21. package/src/client-graph/specifier-classification.js +209 -141
  22. package/src/contracts/router-adapter.js +6 -0
  23. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  24. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  25. package/src/hmr/hmr-scripts.js +22 -9
  26. package/src/hmr/hmr-strategy.d.ts +12 -181
  27. package/src/hmr/hmr-strategy.js +321 -650
  28. package/src/hmr/page-metadata-cache.js +43 -40
  29. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  30. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  31. package/src/hydration/assert-no-bare-ecopages-imports.js +6 -6
  32. package/src/hydration/bootstrap-imports.js +30 -20
  33. package/src/hydration/hydration-asset.js +216 -213
  34. package/src/hydration/hydration-scripts.d.ts +4 -0
  35. package/src/hydration/hydration-scripts.js +199 -66
  36. package/src/hydration/hydration-scripts.test.browser.js +163 -168
  37. package/src/hydration/page-data-manifest.js +89 -45
  38. package/src/hydration/page-data-reader.js +45 -32
  39. package/src/hydration/page-payload.js +101 -99
  40. package/src/hydration/serialize-page-data-script.js +27 -28
  41. package/src/mdx/mdx-config-dependency.js +108 -112
  42. package/src/mdx/mdx-loader-plugin.js +7 -10
  43. package/src/page/page-module.js +72 -66
  44. package/src/plugin/react.constants.js +1 -4
  45. package/src/plugin/react.plugin.d.ts +1 -0
  46. package/src/plugin/react.plugin.js +227 -216
  47. package/src/plugin/react.types.js +1 -0
  48. package/src/render/component-ownership.js +42 -18
  49. package/src/render/component-ssr.js +168 -190
  50. package/src/render/eco-embed.js +8 -10
  51. package/src/render/errors.js +21 -16
  52. package/src/render/html-boundary.js +55 -51
  53. package/src/render/layout-compose.js +122 -94
  54. package/src/render/react-renderer.js +433 -468
  55. package/src/render/react-runtime.js +25 -20
  56. package/src/render/unified-layout-composition.js +74 -85
  57. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
@@ -1,678 +1,349 @@
1
- import path from "node:path";
2
- import { HmrStrategy, HmrStrategyType } from "@ecopages/core/hmr/hmr-strategy";
3
- import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
- import { createBrowserRuntimePlugin } from "@ecopages/core/build/browser-runtime-plugin";
5
- import { FileNotFoundError, fileSystem } from "@ecopages/file-system";
6
- import { Logger } from "@ecopages/logger";
7
- import { injectHmrHandler } from "./hmr-scripts.js";
8
- import { createClientGraphBoundaryPlugin } from "../client-graph/boundary-plugin.js";
9
- import { ClientGraphBoundaryCache } from "../client-graph/boundary-cache.js";
10
- import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from "../client-graph/declared-modules.js";
11
- import { someInConfigTree } from "../client-graph/component-config-traversal.js";
12
- import { createReactMdxLoaderPlugin } from "../mdx/mdx-loader-plugin.js";
13
- import { getReactClientGraphAllowSpecifiers } from "../bundling/runtime-alias-map.js";
14
- const appLogger = new Logger("[ReactHmrStrategy]");
15
- class ReactHmrStrategy extends HmrStrategy {
16
- type = HmrStrategyType.INTEGRATION;
17
- mdxCompilerOptions;
18
- ownedTemplateExtensions;
19
- allTemplateExtensions;
20
- async importNodePageModule(entrypointPath) {
21
- return await this.context.importServerModule(entrypointPath);
22
- }
23
- /**
24
- * Creates a new React HMR strategy instance.
25
- *
26
- * @param options - React HMR runtime services and behavior flags.
27
- */
28
- context;
29
- pageMetadataCache;
30
- runtimeManifest;
31
- clientGraphBoundaryCache;
32
- constructor(options) {
33
- super();
34
- this.context = options.context;
35
- this.pageMetadataCache = options.pageMetadataCache;
36
- this.runtimeManifest = options.runtimeManifest;
37
- this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
38
- this.mdxCompilerOptions = options.mdxCompilerOptions;
39
- this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? [".tsx"]);
40
- this.allTemplateExtensions = [...options.allTemplateExtensions ?? [".tsx"]].sort(
41
- (a, b) => b.length - a.length
42
- );
43
- }
44
- /**
45
- * Returns build plugins for React HMR bundling.
46
- *
47
- * Includes the client graph boundary plugin to prevent undeclared imports
48
- * (including `node:*`) from breaking the browser bundle.
49
- *
50
- * @remarks
51
- * HMR builds receive the React runtime manifest and rewrite manifest-owned
52
- * runtime imports to concrete asset URLs before module resolution.
53
- */
54
- getBuildPlugins(declaredModules) {
55
- const allowSpecifiers = getReactClientGraphAllowSpecifiers(
56
- this.runtimeManifest.assets.map((asset) => asset.specifier)
57
- );
58
- const runtimeRewritePlugin = createBrowserRuntimePlugin({
59
- name: "react-hmr-runtime-import-rewrite",
60
- manifest: this.runtimeManifest
61
- });
62
- return [
63
- createClientGraphBoundaryPlugin({
64
- projectRoot: path.dirname(this.context.getSrcDir()),
65
- absWorkingDir: path.dirname(this.context.getSrcDir()),
66
- alwaysAllowSpecifiers: allowSpecifiers,
67
- declaredModules,
68
- cache: this.clientGraphBoundaryCache
69
- }),
70
- ...runtimeRewritePlugin ? [runtimeRewritePlugin] : []
71
- ];
72
- }
73
- isReactEntrypoint(filePath) {
74
- if (filePath.endsWith(".mdx")) {
75
- return this.mdxCompilerOptions !== void 0;
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/hmr/hmr-strategy';
11
+ import { isRegisteredScriptEntrypoint } from '@ecopages/core/hmr/hmr-entrypoint-output';
12
+ import { DEV_TRANSFORM_URL_PREFIX } from '@ecopages/core/dev/transform-server';
13
+ import { createBrowserRuntimePlugin } from '@ecopages/core/build/browser-runtime-plugin';
14
+ import { Logger } from '@ecopages/logger';
15
+ import { createClientGraphBoundaryPlugin } from '../client-graph/boundary-plugin.js';
16
+ import { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
17
+ import { someInConfigTree } from '../client-graph/component-config-traversal.js';
18
+ import { getReactClientGraphAllowSpecifiers } from '../bundling/runtime-alias-map.js';
19
+ import { buildReactDevTransformPlugins, resolveReactDeclaredModulesForEntrypoint, } from './react-hmr-dev-transform-plugins.js';
20
+ const appLogger = new Logger('[ReactHmrStrategy]');
21
+ /**
22
+ * Strategy for handling React component HMR updates.
23
+ */
24
+ export class ReactHmrStrategy extends HmrStrategy {
25
+ type = HmrStrategyType.INTEGRATION;
26
+ mdxCompilerOptions;
27
+ ownedTemplateExtensions;
28
+ allTemplateExtensions;
29
+ context;
30
+ pageMetadataCache;
31
+ runtimeManifest;
32
+ clientGraphBoundaryCache;
33
+ async importNodePageModule(entrypointPath) {
34
+ return await this.context.importServerModule(entrypointPath);
35
+ }
36
+ getDevTransformPluginOptions() {
37
+ return {
38
+ pageMetadataCache: this.pageMetadataCache,
39
+ mdxCompilerOptions: this.mdxCompilerOptions,
40
+ getBuildPlugins: (declaredModules) => this.getBuildPlugins(declaredModules),
41
+ importNodePageModule: (entrypointPath) => this.importNodePageModule(entrypointPath),
42
+ };
76
43
  }
77
- if (!filePath.endsWith(".tsx")) {
78
- return false;
44
+ constructor(options) {
45
+ super();
46
+ this.context = options.context;
47
+ this.pageMetadataCache = options.pageMetadataCache;
48
+ this.runtimeManifest = options.runtimeManifest;
49
+ this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
50
+ this.mdxCompilerOptions = options.mdxCompilerOptions;
51
+ this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? ['.tsx']);
52
+ this.allTemplateExtensions = [...(options.allTemplateExtensions ?? ['.tsx'])].sort((a, b) => b.length - a.length);
53
+ }
54
+ getBuildPlugins(declaredModules) {
55
+ const allowSpecifiers = getReactClientGraphAllowSpecifiers(this.runtimeManifest.assets.map((asset) => asset.specifier));
56
+ const runtimeRewritePlugin = createBrowserRuntimePlugin({
57
+ name: 'react-hmr-runtime-import-rewrite',
58
+ manifest: this.runtimeManifest,
59
+ });
60
+ return [
61
+ createClientGraphBoundaryPlugin({
62
+ projectRoot: path.dirname(this.context.getSrcDir()),
63
+ absWorkingDir: path.dirname(this.context.getSrcDir()),
64
+ alwaysAllowSpecifiers: allowSpecifiers,
65
+ declaredModules,
66
+ cache: this.clientGraphBoundaryCache,
67
+ }),
68
+ ...(runtimeRewritePlugin ? [runtimeRewritePlugin] : []),
69
+ ];
70
+ }
71
+ isReactEntrypoint(filePath) {
72
+ if (filePath.endsWith('.mdx')) {
73
+ return this.mdxCompilerOptions !== undefined;
74
+ }
75
+ if (!filePath.endsWith('.tsx')) {
76
+ return false;
77
+ }
78
+ const templateExtension = this.resolveTemplateExtension(filePath);
79
+ if (templateExtension && templateExtension !== '.tsx') {
80
+ return this.ownedTemplateExtensions.has(templateExtension);
81
+ }
82
+ if (!this.isRouteTemplate(filePath)) {
83
+ return true;
84
+ }
85
+ if (!templateExtension) {
86
+ return false;
87
+ }
88
+ return this.ownedTemplateExtensions.has(templateExtension);
89
+ }
90
+ /**
91
+ * @remarks
92
+ * React integration owns plain `.tsx` route templates. Compound extensions in
93
+ * pages/layouts are integration-specific route templates and should not be
94
+ * claimed by React HMR strategy.
95
+ */
96
+ isRouteTemplate(filePath) {
97
+ return filePath.startsWith(this.context.getPagesDir()) || filePath.startsWith(this.context.getLayoutsDir());
98
+ }
99
+ resolveTemplateExtension(filePath) {
100
+ return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
101
+ }
102
+ isDevTransformOutputUrl(outputUrl) {
103
+ return outputUrl.startsWith(`${DEV_TRANSFORM_URL_PREFIX}/`);
104
+ }
105
+ queueDevTransformOutputUpdates(targets, requestedOutputUrls, updates) {
106
+ for (const { outputUrl } of targets) {
107
+ if (requestedOutputUrls.has(outputUrl)) {
108
+ updates.push(outputUrl);
109
+ }
110
+ }
79
111
  }
80
- const templateExtension = this.resolveTemplateExtension(filePath);
81
- if (templateExtension && templateExtension !== ".tsx") {
82
- return this.ownedTemplateExtensions.has(templateExtension);
112
+ ownsWatchedEntrypoint(filePath) {
113
+ return this.pageMetadataCache.ownsEntrypoint(filePath);
83
114
  }
84
- if (!this.isRouteTemplate(filePath)) {
85
- return true;
115
+ configContainsFile(config, filePath) {
116
+ const resolvedFilePath = path.resolve(filePath);
117
+ return someInConfigTree(config, (node) => {
118
+ if (!node.__eco?.file) {
119
+ return false;
120
+ }
121
+ return path.resolve(node.__eco.file) === resolvedFilePath;
122
+ });
86
123
  }
87
- if (!templateExtension) {
88
- return false;
124
+ pageModuleRequiresLayoutRefresh(pageModule, filePath) {
125
+ return [pageModule.default?.config, pageModule.config].some((config) => {
126
+ return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
127
+ });
89
128
  }
90
- return this.ownedTemplateExtensions.has(templateExtension);
91
- }
92
- /**
93
- * Returns true when a route file uses a compound extension like `page.foo.tsx`.
94
- *
95
- * @remarks
96
- * React integration owns plain `.tsx` route templates. Compound extensions in
97
- * pages/layouts are integration-specific route templates and should not be
98
- * claimed by React HMR strategy.
99
- */
100
- isRouteTemplate(filePath) {
101
- return filePath.startsWith(this.context.getPagesDir()) || filePath.startsWith(this.context.getLayoutsDir());
102
- }
103
- resolveTemplateExtension(filePath) {
104
- return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
105
- }
106
- ownsWatchedEntrypoint(filePath) {
107
- return this.pageMetadataCache.ownsEntrypoint(filePath);
108
- }
109
- configContainsFile(config, filePath) {
110
- const resolvedFilePath = path.resolve(filePath);
111
- return someInConfigTree(config, (node) => {
112
- if (!node.__eco?.file) {
129
+ async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
130
+ for (const target of requestedTargets) {
131
+ if (!this.isPageEntrypoint(target.entrypointPath)) {
132
+ continue;
133
+ }
134
+ const pageModule = await this.importNodePageModule(target.entrypointPath);
135
+ if (this.pageModuleRequiresLayoutRefresh(pageModule, changedFilePath)) {
136
+ return true;
137
+ }
138
+ }
113
139
  return false;
114
- }
115
- return path.resolve(node.__eco.file) === resolvedFilePath;
116
- });
117
- }
118
- pageModuleRequiresLayoutRefresh(pageModule, filePath) {
119
- return [pageModule.default?.config, pageModule.config].some((config) => {
120
- return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
121
- });
122
- }
123
- async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
124
- for (const target of requestedTargets) {
125
- if (!this.isPageEntrypoint(target.entrypointPath)) {
126
- continue;
127
- }
128
- const pageModule = await this.importNodePageModule(target.entrypointPath);
129
- if (this.pageModuleRequiresLayoutRefresh(pageModule, changedFilePath)) {
130
- return true;
131
- }
132
- }
133
- return false;
134
- }
135
- /**
136
- * Determines if the file is a React/MDX entrypoint that's registered for HMR.
137
- *
138
- * Uses a three-way decision strategy for selective invalidation:
139
- * 1. If the file is a watched entrypoint, check if React owns it
140
- * 2. If the file is a dependency of watched entrypoints (via dependency graph),
141
- * check if any affected entrypoints are React-owned. Returns false if hits
142
- * exist but none are owned (prevents unnecessary rebuilds).
143
- * 3. Otherwise, check if the file itself is a React entrypoint template
144
- *
145
- * @param filePath - Absolute path to the changed file
146
- * @returns True if this file should trigger React HMR rebuilds
147
- */
148
- matches(filePath) {
149
- const watchedFiles = this.context.getWatchedFiles();
150
- appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
151
- if (watchedFiles.has(filePath)) {
152
- return this.ownsWatchedEntrypoint(filePath);
153
140
  }
154
- const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(filePath);
155
- if (dependencyHits.size > 0) {
156
- for (const entrypoint of dependencyHits) {
157
- if (this.ownsWatchedEntrypoint(entrypoint)) {
158
- return true;
141
+ matches(filePath) {
142
+ const watchedFiles = this.context.getWatchedFiles();
143
+ const resolvedFilePath = path.resolve(filePath);
144
+ appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
145
+ if (isRegisteredScriptEntrypoint(this.context.getRegisteredEntrypoints(), resolvedFilePath)) {
146
+ return false;
159
147
  }
160
- }
161
- return false;
148
+ if (watchedFiles.has(resolvedFilePath)) {
149
+ if (this.ownsWatchedEntrypoint(resolvedFilePath)) {
150
+ return true;
151
+ }
152
+ const outputUrl = watchedFiles.get(resolvedFilePath);
153
+ if (outputUrl && this.isDevTransformOutputUrl(outputUrl) && this.isReactEntrypoint(resolvedFilePath)) {
154
+ return true;
155
+ }
156
+ return false;
157
+ }
158
+ const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
159
+ if (dependencyHits.size > 0) {
160
+ for (const entrypoint of dependencyHits) {
161
+ if (this.ownsWatchedEntrypoint(entrypoint)) {
162
+ return true;
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+ return this.isReactEntrypoint(filePath);
162
168
  }
163
- return this.isReactEntrypoint(filePath);
164
- }
165
- canEmitEntrypoint(entrypointPath) {
166
- return this.isReactEntrypoint(entrypointPath) && this.ownsWatchedEntrypoint(entrypointPath);
167
- }
168
- async emitEntrypoint(entrypointPath, _outputPath) {
169
- const { outputUrl } = this.getEntrypointOutput(entrypointPath);
170
- await this.bundleReactEntrypoint(entrypointPath, outputUrl);
171
- }
172
- /**
173
- * Checks if a file is a layout file.
174
- *
175
- * Layout files require special HMR handling because they wrap multiple pages and affect
176
- * the entire page structure. When a layout changes, we trigger a 'layout-update' event
177
- * instead of a regular 'update' event, which instructs the browser to perform a full
178
- * page reload (or clear cache and re-render) rather than attempting module-level HMR.
179
- *
180
- * @param filePath - Absolute path to the file
181
- * @returns True if the file is in the layouts directory
182
- */
183
- isLayoutFile(filePath) {
184
- return filePath.startsWith(this.context.getLayoutsDir());
185
- }
186
- isPageEntrypoint(filePath) {
187
- return filePath.startsWith(this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
188
- }
189
- getEntrypointOutput(entrypointPath) {
190
- const srcDir = this.context.getSrcDir();
191
- const relativePath = path.relative(srcDir, entrypointPath);
192
- const relativePathJs = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, ".js");
193
- const encodedPathJs = this.encodeDynamicSegments(relativePathJs);
194
- const outputPath = path.join(this.context.getDistDir(), encodedPathJs);
195
- const outputUrl = `/${path.join(RESOLVED_ASSETS_DIR, "_hmr", encodedPathJs).split(path.sep).join("/")}`;
196
- return { outputPath, outputUrl };
197
- }
198
- getRolldownEntryKey(entrypointPath) {
199
- const srcDir = this.context.getSrcDir();
200
- const relativePath = path.relative(srcDir, entrypointPath);
201
- const relativePathNoExt = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, "");
202
- return relativePathNoExt;
203
- }
204
- getTempFileBasename(entrypointPath) {
205
- const srcDir = this.context.getSrcDir();
206
- const relativePath = path.relative(srcDir, entrypointPath);
207
- const relativePathNoExt = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, "");
208
- const encodedPath = this.encodeDynamicSegments(relativePathNoExt);
209
- return path.basename(encodedPath);
210
- }
211
- async collectReactPageBuildTargets() {
212
- const targets = /* @__PURE__ */ new Map();
213
- for (const entrypointPath of this.pageMetadataCache.getOwnedEntrypoints()) {
214
- if (!this.isPageEntrypoint(entrypointPath)) {
215
- continue;
216
- }
217
- targets.set(entrypointPath, {
218
- entrypointPath,
219
- outputUrl: this.getEntrypointOutput(entrypointPath).outputUrl
220
- });
169
+ ownsDevTransformEntrypoint(sourcePath) {
170
+ if (!this.isReactEntrypoint(sourcePath)) {
171
+ return false;
172
+ }
173
+ const normalized = path.resolve(sourcePath);
174
+ const srcDir = path.resolve(this.context.getSrcDir());
175
+ return normalized === srcDir || normalized.startsWith(`${srcDir}${path.sep}`);
221
176
  }
222
- return Array.from(targets.values()).sort(
223
- (left, right) => left.entrypointPath.localeCompare(right.entrypointPath)
224
- );
225
- }
226
- /**
227
- * Expands one HMR request into the full React page build cohort when needed.
228
- *
229
- * @remarks
230
- * Page and layout changes need one shared rebuild pass so sibling routes keep
231
- * a consistent client module graph. Non-page changes that do not touch a page
232
- * cohort can stay scoped to the originally requested targets.
233
- */
234
- async resolveBuildTargets(requestedTargets, changedFilePath) {
235
- const requestedPageTargets = requestedTargets.filter((target) => this.isPageEntrypoint(target.entrypointPath));
236
- const shouldGroupPageBuilds = this.isLayoutFile(changedFilePath) || requestedPageTargets.length > 0;
237
- if (!shouldGroupPageBuilds) {
238
- return [];
177
+ getRuntimeManifest() {
178
+ return this.runtimeManifest;
239
179
  }
240
- const groupedTargets = new Map(requestedPageTargets.map((target) => [target.entrypointPath, target]));
241
- for (const target of await this.collectReactPageBuildTargets()) {
242
- groupedTargets.set(target.entrypointPath, target);
180
+ async getVendorBundlePlugins() {
181
+ return this.getBuildPlugins();
243
182
  }
244
- return Array.from(groupedTargets.values()).sort(
245
- (left, right) => left.entrypointPath.localeCompare(right.entrypointPath)
246
- );
247
- }
248
- partitionBuildTargets(requestedTargets, groupedPageTargets) {
249
- if (groupedPageTargets.length === 0) {
250
- return {
251
- pageTargets: [],
252
- nonPageTargets: requestedTargets
253
- };
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'));
254
189
  }
255
- const groupedPageEntrypoints = new Set(groupedPageTargets.map((target) => target.entrypointPath));
256
- return {
257
- pageTargets: groupedPageTargets,
258
- nonPageTargets: requestedTargets.filter(
259
- (target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)
260
- )
261
- };
262
- }
263
- /**
264
- * Processes a React file change by rebuilding affected React entrypoints.
265
- *
266
- * Uses a three-way decision strategy for selective invalidation:
267
- * 1. Changed file is a watched entrypoint: rebuild only that entrypoint
268
- * 2. Dependency graph has hits: rebuild only affected React-owned entrypoints.
269
- * If hits exist but none map to React-owned entrypoints, return 'none' to
270
- * prevent unnecessary rebuilds.
271
- * 3. Dependency graph miss: fall back to rebuilding all watched entrypoints
272
- *
273
- * For layout files, broadcasts a 'layout-update' event to trigger full page reload.
274
- * For regular components/pages, broadcasts 'update' events for module-level HMR.
275
- *
276
- * @param _filePath - Absolute path to the changed file
277
- * @returns Action to broadcast update events (layout-update for layouts, update for components)
278
- */
279
- async process(_filePath) {
280
- appLogger.debug(`Processing ${_filePath}`);
281
- const watchedFiles = this.context.getWatchedFiles();
282
- if (watchedFiles.size === 0) {
283
- appLogger.debug(`No watched files`);
284
- return { type: "none" };
190
+ isLayoutFile(filePath) {
191
+ return filePath.startsWith(this.context.getLayoutsDir());
285
192
  }
286
- const isLayout = this.isLayoutFile(_filePath);
287
- const isChangedPageEntrypoint = this.isPageEntrypoint(_filePath);
288
- if (isLayout) {
289
- appLogger.debug(`Detected layout file change: ${_filePath}`);
193
+ isPageEntrypoint(filePath) {
194
+ return filePath.startsWith(this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
290
195
  }
291
- const changedEntrypointOutput = watchedFiles.get(_filePath);
292
- if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(_filePath)) {
293
- if (this.isReactEntrypoint(_filePath)) {
294
- this.pageMetadataCache.markOwnedEntrypoint(_filePath);
295
- } else {
296
- appLogger.debug(`Skipping non-React watched entrypoint: ${_filePath}`);
297
- return { type: "none" };
298
- }
196
+ resolveEntrypointOutputUrl(entrypointPath) {
197
+ return this.context.getWatchedFiles().get(path.resolve(entrypointPath));
299
198
  }
300
- const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(_filePath);
301
- const hasDependencyHits = dependencyHits.size > 0;
302
- const affectedEntrypoints = /* @__PURE__ */ new Map();
303
- let hasOwnedLayoutDependencyHit = false;
304
- let layoutOwnedPageTargets = [];
305
- let hasLayoutOwnedRequestedTarget = false;
306
- if (hasDependencyHits && !changedEntrypointOutput) {
307
- for (const entrypoint of dependencyHits) {
308
- const outputUrl = watchedFiles.get(entrypoint);
309
- if (outputUrl && this.ownsWatchedEntrypoint(entrypoint)) {
310
- affectedEntrypoints.set(entrypoint, outputUrl);
311
- continue;
312
- }
313
- if (this.isLayoutFile(entrypoint) && this.ownsWatchedEntrypoint(entrypoint)) {
314
- hasOwnedLayoutDependencyHit = true;
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
+ });
315
213
  }
316
- }
317
- if (affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit) {
318
- appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
319
- return { type: "none" };
320
- }
214
+ return Array.from(targets.values()).sort((left, right) => left.entrypointPath.localeCompare(right.entrypointPath));
321
215
  }
322
- if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
323
- layoutOwnedPageTargets = await this.collectReactPageBuildTargets();
324
- hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(
325
- _filePath,
326
- layoutOwnedPageTargets
327
- );
328
- }
329
- const requestedTargets = changedEntrypointOutput ? hasLayoutOwnedRequestedTarget ? [{ entrypointPath: _filePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets] : [{ entrypointPath: _filePath, outputUrl: changedEntrypointOutput }] : hasOwnedLayoutDependencyHit ? await this.collectReactPageBuildTargets() : hasDependencyHits ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl })) : Array.from(watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
330
- const groupedPageTargets = await this.resolveBuildTargets(requestedTargets, _filePath);
331
- const { pageTargets, nonPageTargets } = this.partitionBuildTargets(requestedTargets, groupedPageTargets);
332
- if (!changedEntrypointOutput) {
333
- hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(_filePath, requestedTargets);
334
- }
335
- const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
336
- await this.clearOutdirsForTargets(pageTargets, nonPageTargets);
337
- const updates = [];
338
- const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
339
- if (pageTargets.length > 1) {
340
- appLogger.debug(`Bundling ${pageTargets.length} React page entrypoints together`);
341
- const rebuiltOutputs = await this.bundleReactEntrypoints(pageTargets);
342
- for (const outputUrl of rebuiltOutputs) {
343
- if (requestedOutputUrls.has(outputUrl)) {
344
- updates.push(outputUrl);
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 [];
345
221
  }
346
- }
347
- } else {
348
- for (const { entrypointPath, outputUrl } of pageTargets) {
349
- appLogger.debug(`Bundling ${entrypointPath}`);
350
- const success = await this.bundleReactEntrypoint(entrypointPath, outputUrl);
351
- if (success && requestedOutputUrls.has(outputUrl)) {
352
- updates.push(outputUrl);
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
+ }
353
227
  }
354
- }
355
- }
356
- for (const { entrypointPath, outputUrl } of nonPageTargets) {
357
- if (!this.isReactEntrypoint(entrypointPath)) {
358
- continue;
359
- }
360
- appLogger.debug(`Bundling ${entrypointPath}`);
361
- const success = await this.bundleReactEntrypoint(entrypointPath, outputUrl);
362
- if (success && requestedOutputUrls.has(outputUrl)) {
363
- updates.push(outputUrl);
364
- }
365
- }
366
- if (updates.length > 0) {
367
- if (requiresLayoutRefresh) {
368
- appLogger.debug(`Layout update detected, sending layout-update event`);
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));
369
238
  return {
370
- type: "broadcast",
371
- events: [
372
- {
373
- type: "layout-update"
374
- }
375
- ]
239
+ pageTargets: groupedPageTargets,
240
+ nonPageTargets: requestedTargets.filter((target) => !groupedPageEntrypoints.has(target.entrypointPath) && !this.isPageEntrypoint(target.entrypointPath)),
376
241
  };
377
- }
378
- appLogger.debug(`Broadcasting ${updates.length} updates`);
379
- return {
380
- type: "broadcast",
381
- events: updates.map((path2) => ({
382
- type: "update",
383
- path: path2,
384
- timestamp: Date.now()
385
- }))
386
- };
387
- }
388
- appLogger.debug(`No updates generated`);
389
- return { type: "none" };
390
- }
391
- /**
392
- * Clears stale HMR output once per outdir before any rebuild pass in `process()`.
393
- *
394
- * @remarks
395
- * Grouped page builds share `getDistDir()`; single page and non-page targets use
396
- * per-entrypoint temp directories. Clearing here avoids redundant work when both
397
- * page and non-page targets land in the same outdir.
398
- */
399
- async clearOutdirsForTargets(pageTargets, nonPageTargets) {
400
- const outdirs = /* @__PURE__ */ new Set();
401
- if (pageTargets.length > 1) {
402
- outdirs.add(this.context.getDistDir());
403
- } else {
404
- for (const { entrypointPath } of pageTargets) {
405
- outdirs.add(path.dirname(this.getEntrypointOutput(entrypointPath).outputPath));
406
- }
407
242
  }
408
- for (const { entrypointPath } of nonPageTargets) {
409
- outdirs.add(path.dirname(this.getEntrypointOutput(entrypointPath).outputPath));
410
- }
411
- await Promise.all([...outdirs].map((outdir) => this.clearHmrOutdir(outdir)));
412
- }
413
- async resolveDeclaredModulesForEntrypoint(entrypointPath) {
414
- const cached = this.pageMetadataCache.getDeclaredModules(entrypointPath);
415
- if (cached) {
416
- return cached;
417
- }
418
- const declaredModules = entrypointPath.endsWith(".mdx") ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
419
- this.pageMetadataCache.setDeclaredModules(entrypointPath, declaredModules);
420
- return declaredModules;
421
- }
422
- async collectDeclaredModulesForTargets(targets) {
423
- const declaredModules = /* @__PURE__ */ new Set();
424
- let shouldEnableMdx = false;
425
- for (const { entrypointPath } of targets) {
426
- const entrypointDeclaredModules = await this.resolveDeclaredModulesForEntrypoint(entrypointPath);
427
- for (const declaredModule of entrypointDeclaredModules) {
428
- declaredModules.add(declaredModule);
429
- }
430
- if (entrypointPath.endsWith(".mdx")) {
431
- shouldEnableMdx = true;
432
- }
433
- }
434
- return { declaredModules: [...declaredModules], shouldEnableMdx };
435
- }
436
- buildPluginsForDeclaredModules(declaredModules, shouldEnableMdx) {
437
- const plugins = this.getBuildPlugins(declaredModules);
438
- if (shouldEnableMdx && this.mdxCompilerOptions) {
439
- plugins.unshift(createReactMdxLoaderPlugin(this.mdxCompilerOptions));
440
- }
441
- return plugins;
442
- }
443
- recordBuildDependencyGraph(result) {
444
- if (!result.dependencyGraph?.entrypoints) {
445
- return;
446
- }
447
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
448
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
449
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
450
- }
451
- }
452
- /**
453
- * Bundles a single React/MDX entrypoint with HMR support.
454
- *
455
- * After successful bundling, populates the entrypoint dependency graph with
456
- * the build's dependency metadata. This enables selective invalidation on
457
- * subsequent file changes, so only entrypoints affected by a changed
458
- * dependency are rebuilt.
459
- *
460
- * @param entrypointPath - Absolute path to the source file
461
- * @param outputUrl - URL path for the bundled file
462
- * @returns True if bundling was successful
463
- */
464
- async bundleReactEntrypoint(entrypointPath, outputUrl) {
465
- const rebuiltOutputs = await this.bundleReactBuildTargets([{ entrypointPath, outputUrl }], { grouped: false });
466
- return rebuiltOutputs.length > 0;
467
- }
468
- /**
469
- * Bundles multiple React/MDX entrypoints in a single build pass.
470
- *
471
- * Uses code splitting to share common dependencies across entrypoints.
472
- * After successful bundling, populates the entrypoint dependency graph with
473
- * the build's dependency metadata for selective invalidation.
474
- *
475
- * @param entrypoints - Array of entrypoint paths and their output URLs
476
- * @returns Array of output URLs that were successfully built
477
- */
478
- async bundleReactEntrypoints(entrypoints) {
479
- return this.bundleReactBuildTargets(entrypoints, { grouped: true });
480
- }
481
- async bundleReactBuildTargets(targets, options) {
482
- if (targets.length === 0) {
483
- return [];
484
- }
485
- try {
486
- const { declaredModules, shouldEnableMdx } = await this.collectDeclaredModulesForTargets(targets);
487
- const plugins = this.buildPluginsForDeclaredModules(declaredModules, shouldEnableMdx);
488
- if (options.grouped) {
489
- const entryNameByPath = /* @__PURE__ */ new Map();
490
- for (const { entrypointPath: entrypointPath2 } of targets) {
491
- entryNameByPath.set(entrypointPath2, {
492
- key: this.getRolldownEntryKey(entrypointPath2),
493
- basename: this.getTempFileBasename(entrypointPath2)
494
- });
243
+ async process(_filePath) {
244
+ appLogger.debug(`Processing ${_filePath}`);
245
+ const resolvedFilePath = path.resolve(_filePath);
246
+ const watchedFiles = this.context.getWatchedFiles();
247
+ if (watchedFiles.size === 0) {
248
+ appLogger.debug(`No watched files`);
249
+ return { type: 'none' };
495
250
  }
496
- const result2 = await this.context.getBrowserBundleService().bundle({
497
- profile: "hmr-entrypoint",
498
- entrypoints: Object.fromEntries(
499
- targets.map(({ entrypointPath: entrypointPath2 }) => [entryNameByPath.get(entrypointPath2).key, entrypointPath2])
500
- ),
501
- outdir: this.context.getDistDir(),
502
- naming: "[name].[hash].tmp",
503
- splitting: true,
504
- plugins,
505
- minify: false
506
- });
507
- if (!result2.success) {
508
- appLogger.error(`Failed to build grouped React entrypoints:`, result2.logs);
509
- return [];
251
+ const isLayout = this.isLayoutFile(resolvedFilePath);
252
+ const isChangedPageEntrypoint = this.isPageEntrypoint(resolvedFilePath);
253
+ if (isLayout) {
254
+ appLogger.debug(`Detected layout file change: ${resolvedFilePath}`);
510
255
  }
511
- this.recordBuildDependencyGraph(result2);
512
- const updatedOutputs = [];
513
- for (const { entrypointPath: entrypointPath2, outputUrl: outputUrl2 } of targets) {
514
- const { outputPath: outputPath2 } = this.getEntrypointOutput(entrypointPath2);
515
- const { basename: tempBasename, key: entryKey } = entryNameByPath.get(entrypointPath2);
516
- const expectedSubdir = path.join(this.context.getDistDir(), path.dirname(entryKey));
517
- const tempOutput = result2.outputs.find((output) => {
518
- return path.dirname(output.path) === expectedSubdir && path.basename(output.path).startsWith(`${tempBasename}.`) && path.basename(output.path).includes(".tmp");
519
- })?.path;
520
- const resolvedTempOutput = tempOutput ? await this.resolveTempOutputPath(tempOutput) : await this.resolveTempOutputPath(path.join(expectedSubdir, `${tempBasename}.[hash].tmp.js`));
521
- if (!resolvedTempOutput) {
522
- appLogger.debug(`Missing grouped temp output for ${outputUrl2}`);
523
- continue;
524
- }
525
- const processed2 = await this.processOutput(resolvedTempOutput, outputPath2, outputUrl2);
526
- if (processed2) {
527
- updatedOutputs.push(outputUrl2);
528
- }
256
+ const changedEntrypointOutput = watchedFiles.get(resolvedFilePath);
257
+ if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(resolvedFilePath)) {
258
+ if (this.isReactEntrypoint(resolvedFilePath)) {
259
+ this.pageMetadataCache.markOwnedEntrypoint(resolvedFilePath);
260
+ }
261
+ else {
262
+ appLogger.debug(`Skipping non-React watched entrypoint: ${resolvedFilePath}`);
263
+ return { type: 'none' };
264
+ }
529
265
  }
530
- return updatedOutputs;
531
- }
532
- const { entrypointPath, outputUrl } = targets[0];
533
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
534
- const tempDir = path.dirname(outputPath);
535
- const result = await this.context.getBrowserBundleService().bundle({
536
- profile: "hmr-entrypoint",
537
- entrypoints: [entrypointPath],
538
- outdir: tempDir,
539
- naming: `[name].[hash].tmp`,
540
- plugins,
541
- minify: false
542
- });
543
- if (!result.success) {
544
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
545
- return [];
546
- }
547
- this.recordBuildDependencyGraph(result);
548
- const tempFile = result.outputs[0]?.path;
549
- if (!tempFile) {
550
- appLogger.error(`No output file generated for ${entrypointPath}`);
551
- return [];
552
- }
553
- const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
554
- if (!resolvedTempFile) {
555
- appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
556
- return [];
557
- }
558
- const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
559
- return processed ? [outputUrl] : [];
560
- } catch (error) {
561
- const label = options.grouped ? "grouped React entrypoints" : targets[0]?.entrypointPath ?? "React entrypoint";
562
- appLogger.error(`Error bundling ${label}:`, error);
563
- return [];
564
- }
565
- }
566
- async resolveTempOutputPath(tempPath) {
567
- if (fileSystem.exists(tempPath)) {
568
- return tempPath;
569
- }
570
- if (!tempPath.includes("[hash]")) {
571
- return null;
572
- }
573
- const directory = path.dirname(tempPath);
574
- const pattern = path.basename(tempPath).replaceAll("[hash]", "*");
575
- const matches = await fileSystem.glob([pattern], { cwd: directory });
576
- if (matches.length === 0) {
577
- return null;
578
- }
579
- return path.isAbsolute(matches[0]) ? matches[0] : path.join(directory, matches[0]);
580
- }
581
- /**
582
- * Clears stale HMR output from a directory before a rebuild.
583
- *
584
- * Only removes:
585
- * - `*.tmp.js` files (the per-build bundler output the strategy owns)
586
- * - the `chunks/` subdirectory (the bundler's splitting target)
587
- *
588
- * The HMR runtime script (`_hmr_runtime.js`) and any user-authored
589
- * assets in the outdir are preserved. This is the minimal set of
590
- * files that, if left from a previous build, can cause the bundler
591
- * to emit `ENOENT` for chunk references that point to entrypoints
592
- * whose hash has since changed.
593
- */
594
- async clearHmrOutdir(outdir) {
595
- if (!fileSystem.exists(outdir)) {
596
- return;
597
- }
598
- const tempFiles = await fileSystem.glob(["**/*.tmp.js"], { cwd: outdir });
599
- await Promise.all(
600
- tempFiles.map((relativePath) => {
601
- const absolutePath = path.isAbsolute(relativePath) ? relativePath : path.join(outdir, relativePath);
602
- return fileSystem.removeAsync(absolutePath).catch(() => void 0);
603
- })
604
- );
605
- const chunksDir = path.join(outdir, "chunks");
606
- if (fileSystem.exists(chunksDir)) {
607
- await fileSystem.removeAsync(chunksDir).catch(() => void 0);
608
- }
609
- }
610
- /**
611
- * Encodes dynamic route segments (brackets) in file paths.
612
- * Converts `[slug]` to `_slug_` to avoid filesystem issues.
613
- */
614
- encodeDynamicSegments(filepath) {
615
- return filepath.replace(/\[([^\]]+)\]/g, "_$1_");
616
- }
617
- rewriteChunkImportUrls(code) {
618
- const hmrChunkBaseUrl = `/${path.join(RESOLVED_ASSETS_DIR, "_hmr").split(path.sep).join("/")}`;
619
- return code.replace(/(['"])(?:\.\.\/)+(chunk-[^'"]+\.js)\1/g, (_match, quote, chunkFile) => {
620
- return `${quote}${hmrChunkBaseUrl}/${chunkFile}${quote}`;
621
- });
622
- }
623
- isMissingTempOutputError(error) {
624
- if (error instanceof FileNotFoundError) {
625
- return true;
626
- }
627
- if (!(error instanceof Error)) {
628
- return false;
629
- }
630
- if (error.message.includes("not found") || error.message.includes("ENOENT")) {
631
- return true;
632
- }
633
- const errorCause = error.cause;
634
- if (errorCause instanceof FileNotFoundError) {
635
- return true;
636
- }
637
- return typeof errorCause === "object" && errorCause !== null && "code" in errorCause && errorCause.code === "ENOENT";
638
- }
639
- /**
640
- * Processes bundled output and injects the React HMR handler.
641
- * Writes to temp file first, then renames atomically to avoid conflicts.
642
- *
643
- * @param tempPath - Path to the temporary bundled file
644
- * @param finalPath - Final destination path
645
- * @param url - URL path for logging
646
- * @returns True if processing was successful
647
- */
648
- async processOutput(tempPath, finalPath, url) {
649
- if (!fileSystem.exists(tempPath)) {
650
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
651
- return false;
652
- }
653
- try {
654
- let code = await fileSystem.readFile(tempPath);
655
- code = this.rewriteChunkImportUrls(code);
656
- code = injectHmrHandler(code);
657
- await fileSystem.writeAsync(finalPath, code);
658
- await fileSystem.removeAsync(tempPath).catch(() => {
659
- });
660
- appLogger.debug(`Processed ${url} with HMR handler`);
661
- return true;
662
- } catch (error) {
663
- if (this.isMissingTempOutputError(error)) {
664
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
665
- await fileSystem.removeAsync(tempPath).catch(() => {
666
- });
667
- return false;
668
- }
669
- appLogger.error(`Error processing output for ${url}:`, error);
670
- await fileSystem.removeAsync(tempPath).catch(() => {
671
- });
672
- return false;
266
+ const dependencyHits = this.context.getEntrypointDependencyGraph().getDependencyEntrypoints(resolvedFilePath);
267
+ const hasDependencyHits = dependencyHits.size > 0;
268
+ const affectedEntrypoints = new Map();
269
+ let hasOwnedLayoutDependencyHit = false;
270
+ let layoutOwnedPageTargets = [];
271
+ let hasLayoutOwnedRequestedTarget = false;
272
+ if (hasDependencyHits && !changedEntrypointOutput) {
273
+ for (const entrypoint of dependencyHits) {
274
+ const resolvedEntrypoint = path.resolve(entrypoint);
275
+ const outputUrl = watchedFiles.get(resolvedEntrypoint);
276
+ if (outputUrl &&
277
+ (this.ownsWatchedEntrypoint(resolvedEntrypoint) || this.isDevTransformOutputUrl(outputUrl))) {
278
+ affectedEntrypoints.set(resolvedEntrypoint, outputUrl);
279
+ continue;
280
+ }
281
+ if (this.isLayoutFile(resolvedEntrypoint) && this.ownsWatchedEntrypoint(resolvedEntrypoint)) {
282
+ hasOwnedLayoutDependencyHit = true;
283
+ }
284
+ }
285
+ if (affectedEntrypoints.size === 0 && !hasOwnedLayoutDependencyHit) {
286
+ if (!isLayout) {
287
+ appLogger.debug(`Dependency hits found but none map to React-owned watched entrypoints`);
288
+ return { type: 'none' };
289
+ }
290
+ }
291
+ }
292
+ if (changedEntrypointOutput && !isLayout && !isChangedPageEntrypoint) {
293
+ layoutOwnedPageTargets = await this.collectReactPageBuildTargets();
294
+ hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(resolvedFilePath, layoutOwnedPageTargets);
295
+ }
296
+ const requestedTargets = changedEntrypointOutput
297
+ ? hasLayoutOwnedRequestedTarget
298
+ ? [{ entrypointPath: resolvedFilePath, outputUrl: changedEntrypointOutput }, ...layoutOwnedPageTargets]
299
+ : [{ entrypointPath: resolvedFilePath, outputUrl: changedEntrypointOutput }]
300
+ : hasOwnedLayoutDependencyHit
301
+ ? await this.collectReactPageBuildTargets()
302
+ : hasDependencyHits
303
+ ? Array.from(affectedEntrypoints, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }))
304
+ : Array.from(watchedFiles, ([entrypointPath, outputUrl]) => ({ entrypointPath, outputUrl }));
305
+ const groupedPageTargets = await this.resolveBuildTargets(requestedTargets, resolvedFilePath);
306
+ const { pageTargets, nonPageTargets } = this.partitionBuildTargets(requestedTargets, groupedPageTargets);
307
+ if (!changedEntrypointOutput) {
308
+ hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(resolvedFilePath, requestedTargets);
309
+ }
310
+ const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
311
+ const updates = [];
312
+ const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
313
+ this.queueDevTransformOutputUpdates(pageTargets, requestedOutputUrls, updates);
314
+ for (const { outputUrl } of nonPageTargets) {
315
+ if (!requestedOutputUrls.has(outputUrl)) {
316
+ continue;
317
+ }
318
+ if (this.isDevTransformOutputUrl(outputUrl)) {
319
+ updates.push(outputUrl);
320
+ continue;
321
+ }
322
+ appLogger.debug(`Skipping non-dev-transform HMR output: ${outputUrl}`);
323
+ }
324
+ if (requiresLayoutRefresh) {
325
+ appLogger.debug(`Layout update detected, sending layout-update event`);
326
+ return {
327
+ type: 'broadcast',
328
+ events: [
329
+ {
330
+ type: 'layout-update',
331
+ },
332
+ ],
333
+ };
334
+ }
335
+ if (updates.length > 0) {
336
+ appLogger.debug(`Broadcasting ${updates.length} updates`);
337
+ return {
338
+ type: 'broadcast',
339
+ events: updates.map((path) => ({
340
+ type: 'update',
341
+ path,
342
+ timestamp: Date.now(),
343
+ })),
344
+ };
345
+ }
346
+ appLogger.debug(`No updates generated`);
347
+ return { type: 'none' };
673
348
  }
674
- }
675
349
  }
676
- export {
677
- ReactHmrStrategy
678
- };