@ecopages/react 0.2.0-beta.3 → 0.2.0-beta.30

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 (109) hide show
  1. package/README.md +168 -6
  2. package/package.json +51 -26
  3. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  4. package/src/bundling/bootstrap-package-paths.js +6 -0
  5. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +21 -8
  6. package/src/{services/react-bundle.service.js → bundling/bundle.js} +53 -21
  7. package/src/bundling/discover-layout-runtime-modules.d.ts +32 -0
  8. package/src/bundling/discover-layout-runtime-modules.js +180 -0
  9. package/src/bundling/runtime-alias-map.d.ts +10 -0
  10. package/src/{utils/react-runtime-alias-map.js → bundling/runtime-alias-map.js} +13 -2
  11. package/src/{services/react-runtime-bundle.service.d.ts → bundling/runtime-bundle.d.ts} +30 -5
  12. package/src/{services/react-runtime-bundle.service.js → bundling/runtime-bundle.js} +104 -8
  13. package/src/bundling/runtime-mode.d.ts +9 -0
  14. package/src/bundling/runtime-mode.js +6 -0
  15. package/src/bundling/runtime-modules.d.ts +29 -0
  16. package/src/bundling/runtime-modules.js +38 -0
  17. package/src/client-graph/ast-transform.d.ts +18 -0
  18. package/src/{utils/client-graph-boundary-plugin.js → client-graph/ast-transform.js} +15 -232
  19. package/src/{utils/client-graph-boundary-cache.d.ts → client-graph/boundary-cache.d.ts} +0 -5
  20. package/src/{utils/client-graph-boundary-cache.js → client-graph/boundary-cache.js} +1 -3
  21. package/src/{utils/client-graph-boundary-plugin.d.ts → client-graph/boundary-plugin.d.ts} +4 -13
  22. package/src/client-graph/boundary-plugin.js +107 -0
  23. package/src/{utils → client-graph}/component-config-traversal.js +4 -2
  24. package/src/{utils → client-graph}/reachability-analyzer.d.ts +2 -2
  25. package/src/{utils → client-graph}/reachability-analyzer.js +4 -1
  26. package/src/client-graph/specifier-classification.d.ts +75 -0
  27. package/src/client-graph/specifier-classification.js +155 -0
  28. package/src/{react-hmr-strategy.d.ts → hmr/hmr-strategy.d.ts} +19 -6
  29. package/src/{react-hmr-strategy.js → hmr/hmr-strategy.js} +154 -133
  30. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  31. package/src/{services/react-hmr-page-metadata-cache.js → hmr/page-metadata-cache.js} +8 -2
  32. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  33. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  34. package/src/hydration/bootstrap-imports.d.ts +25 -0
  35. package/src/hydration/bootstrap-imports.js +23 -0
  36. package/src/{services/react-hydration-asset.service.d.ts → hydration/hydration-asset.d.ts} +33 -33
  37. package/src/{services/react-hydration-asset.service.js → hydration/hydration-asset.js} +63 -56
  38. package/src/hydration/hydration-scripts.d.ts +100 -0
  39. package/src/hydration/hydration-scripts.js +350 -0
  40. package/src/{utils → hydration}/hydration-scripts.test.browser.js +11 -5
  41. package/src/hydration/page-data-manifest.d.ts +58 -0
  42. package/src/hydration/page-data-manifest.js +53 -0
  43. package/src/hydration/page-data-reader.d.ts +31 -0
  44. package/src/hydration/page-data-reader.js +64 -0
  45. package/src/hydration/page-payload.d.ts +67 -0
  46. package/src/hydration/page-payload.js +104 -0
  47. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  48. package/src/hydration/serialize-page-data-script.js +31 -0
  49. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +5 -5
  50. package/src/{services/react-mdx-config-dependency.service.js → mdx/mdx-config-dependency.js} +8 -10
  51. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  52. package/src/mdx/mdx-loader-plugin.js +11 -0
  53. package/src/page/page-module.d.ts +46 -0
  54. package/src/page/page-module.js +72 -0
  55. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +8 -3
  56. package/src/{react.plugin.js → plugin/react.plugin.js} +78 -54
  57. package/src/plugin/react.types.d.ts +149 -0
  58. package/src/render/component-ownership.d.ts +50 -0
  59. package/src/render/component-ownership.js +23 -0
  60. package/src/render/component-ssr.d.ts +113 -0
  61. package/src/render/component-ssr.js +202 -0
  62. package/src/render/errors.d.ts +16 -0
  63. package/src/render/errors.js +18 -0
  64. package/src/render/layout-compose.d.ts +66 -0
  65. package/src/render/layout-compose.js +106 -0
  66. package/src/render/react-renderer.d.ts +138 -0
  67. package/src/render/react-renderer.js +481 -0
  68. package/src/render/react-runtime.d.ts +13 -0
  69. package/src/render/react-runtime.js +21 -0
  70. package/src/render/unified-layout-composition.d.ts +53 -0
  71. package/src/render/unified-layout-composition.js +89 -0
  72. package/src/react-renderer.d.ts +0 -233
  73. package/src/react-renderer.js +0 -622
  74. package/src/react.types.d.ts +0 -88
  75. package/src/services/pages-index.d.ts +0 -64
  76. package/src/services/pages-index.js +0 -73
  77. package/src/services/react-page-module.service.d.ts +0 -88
  78. package/src/services/react-page-module.service.js +0 -166
  79. package/src/services/react-page-payload.service.d.ts +0 -46
  80. package/src/services/react-page-payload.service.js +0 -67
  81. package/src/utils/hydration-scripts.d.ts +0 -92
  82. package/src/utils/hydration-scripts.js +0 -358
  83. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  84. package/src/utils/react-mdx-loader-plugin.js +0 -45
  85. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  86. /package/src/{utils → app}/client-only.d.ts +0 -0
  87. /package/src/{utils → app}/client-only.js +0 -0
  88. /package/src/{utils → app}/dynamic.d.ts +0 -0
  89. /package/src/{utils → app}/dynamic.js +0 -0
  90. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  91. /package/src/{utils → app}/dynamic.test.browser.js +0 -0
  92. /package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +0 -0
  93. /package/src/{utils/react-dom-runtime-interop-plugin.js → bundling/runtime-interop-plugin.js} +0 -0
  94. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  95. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  96. /package/src/{utils → client-graph}/declared-modules.js +0 -0
  97. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  98. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  99. /package/src/{router-adapter.js → contracts/router-adapter.js} +0 -0
  100. /package/src/{utils → hmr}/hmr-scripts.d.ts +0 -0
  101. /package/src/{utils → hmr}/hmr-scripts.js +0 -0
  102. /package/src/{utils → hydration}/hydration-scripts.test.browser.d.ts +0 -0
  103. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  104. /package/src/{react.constants.js → plugin/react.constants.js} +0 -0
  105. /package/src/{react.types.js → plugin/react.types.js} +0 -0
  106. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  107. /package/src/{eco-embed.js → render/eco-embed.js} +0 -0
  108. /package/src/{utils → render}/html-boundary.d.ts +0 -0
  109. /package/src/{utils → render}/html-boundary.js +0 -0
@@ -0,0 +1,155 @@
1
+ import { loadTsconfigPathPrefixes, matchesTsconfigPathPrefix } from "@ecopages/core/plugins/tsconfig-import-resolver";
2
+ import { dirname, resolve } from "node:path";
3
+ function isBareSpecifier(specifier) {
4
+ if (specifier.startsWith(".")) return false;
5
+ if (specifier.startsWith("/")) return false;
6
+ if (specifier.includes("://")) return false;
7
+ return true;
8
+ }
9
+ function isProjectAliasSpecifier(specifier, projectRoot) {
10
+ if (specifier.startsWith("ecopages:")) {
11
+ return true;
12
+ }
13
+ if (projectRoot) {
14
+ return matchesTsconfigPathPrefix(specifier, loadTsconfigPathPrefixes(projectRoot));
15
+ }
16
+ return false;
17
+ }
18
+ function isServerOnlySpecifier(specifier) {
19
+ if (specifier.startsWith("node:")) return true;
20
+ return /(?:^|[/])[^/]+\.server(?:$|\.)/.test(specifier);
21
+ }
22
+ function toModuleBaseSpecifier(specifier) {
23
+ if (!isBareSpecifier(specifier) || specifier.startsWith("node:")) {
24
+ return specifier;
25
+ }
26
+ if (specifier.startsWith("@")) {
27
+ const [scope, name2] = specifier.split("/");
28
+ if (!scope || !name2) return specifier;
29
+ return `${scope}/${name2}`;
30
+ }
31
+ const [name] = specifier.split("/");
32
+ return name ?? specifier;
33
+ }
34
+ function parseDeclaredModules(moduleDeclarations) {
35
+ const map = /* @__PURE__ */ new Map();
36
+ for (const declaration of moduleDeclarations ?? []) {
37
+ const source = declaration.trim();
38
+ if (source.length === 0) continue;
39
+ const openBraceIndex = source.indexOf("{");
40
+ if (openBraceIndex < 0) {
41
+ map.set(toModuleBaseSpecifier(source), "*");
42
+ continue;
43
+ }
44
+ const closeBraceIndex = source.indexOf("}", openBraceIndex);
45
+ const rawPkg = source.slice(0, openBraceIndex).trim();
46
+ if (rawPkg.length === 0) continue;
47
+ const pkg = toModuleBaseSpecifier(rawPkg);
48
+ const namedImportsStr = closeBraceIndex > openBraceIndex ? source.slice(openBraceIndex + 1, closeBraceIndex) : source.slice(openBraceIndex + 1);
49
+ const namedImports = namedImportsStr.split(",").map((s) => s.trim()).filter(Boolean);
50
+ const existing = map.get(pkg);
51
+ if (existing === "*") continue;
52
+ if (!existing) {
53
+ if (namedImports.length === 0) {
54
+ map.set(pkg, "*");
55
+ } else {
56
+ map.set(pkg, new Set(namedImports));
57
+ }
58
+ } else {
59
+ for (const name of namedImports) {
60
+ existing.add(name);
61
+ }
62
+ }
63
+ }
64
+ return map;
65
+ }
66
+ function mergeDeclaredModulesMap(a, b) {
67
+ const result = new Map(a);
68
+ for (const [pkg, imports] of b.entries()) {
69
+ const existing = result.get(pkg);
70
+ if (existing === "*") continue;
71
+ if (imports === "*") {
72
+ result.set(pkg, "*");
73
+ continue;
74
+ }
75
+ if (!existing) {
76
+ result.set(pkg, imports);
77
+ } else {
78
+ for (const name of imports) {
79
+ existing.add(name);
80
+ }
81
+ }
82
+ }
83
+ return result;
84
+ }
85
+ function normalizeRequestedExportsKey(pathname) {
86
+ let normalized = pathname.replace(/\\/g, "/");
87
+ normalized = normalized.replace(/\.(tsx?|jsx?)$/i, "");
88
+ if (normalized.endsWith("/index")) {
89
+ normalized = normalized.slice(0, -"/index".length);
90
+ }
91
+ return normalized;
92
+ }
93
+ function resolveRequestedExportsKey(importer, specifier) {
94
+ if (isBareSpecifier(specifier) || isProjectAliasSpecifier(specifier)) {
95
+ return void 0;
96
+ }
97
+ const resolved = specifier.startsWith("/") ? specifier : resolve(dirname(importer), specifier);
98
+ return normalizeRequestedExportsKey(resolved);
99
+ }
100
+ function mergeRequestedExportRules(registry, moduleKey, rules) {
101
+ const existing = registry.get(moduleKey);
102
+ if (existing === "*") return;
103
+ if (rules === "*") {
104
+ registry.set(moduleKey, "*");
105
+ return;
106
+ }
107
+ if (!existing) {
108
+ registry.set(moduleKey, new Set(rules));
109
+ return;
110
+ }
111
+ for (const rule of rules) {
112
+ existing.add(rule);
113
+ }
114
+ }
115
+ function cloneRequestedExportRules(rules) {
116
+ return rules === "*" ? rules : new Set(rules);
117
+ }
118
+ function snapshotRegistry(registry) {
119
+ const out = /* @__PURE__ */ new Map();
120
+ for (const [key, rules] of registry) {
121
+ out.set(key, cloneRequestedExportRules(rules));
122
+ }
123
+ return out;
124
+ }
125
+ function diffRequestedExportRules(before, after) {
126
+ if (!before) {
127
+ return cloneRequestedExportRules(after);
128
+ }
129
+ if (before === "*") {
130
+ return void 0;
131
+ }
132
+ if (after === "*") {
133
+ return "*";
134
+ }
135
+ const addedRules = /* @__PURE__ */ new Set();
136
+ for (const rule of after) {
137
+ if (!before.has(rule)) {
138
+ addedRules.add(rule);
139
+ }
140
+ }
141
+ return addedRules.size > 0 ? addedRules : void 0;
142
+ }
143
+ export {
144
+ diffRequestedExportRules,
145
+ isBareSpecifier,
146
+ isProjectAliasSpecifier,
147
+ isServerOnlySpecifier,
148
+ mergeDeclaredModulesMap,
149
+ mergeRequestedExportRules,
150
+ normalizeRequestedExportsKey,
151
+ parseDeclaredModules,
152
+ resolveRequestedExportsKey,
153
+ snapshotRegistry,
154
+ toModuleBaseSpecifier
155
+ };
@@ -10,16 +10,15 @@ import { HmrStrategy, type HmrAction } from '@ecopages/core/hmr/hmr-strategy';
10
10
  import type { BrowserRuntimeManifest } from '@ecopages/core/build/browser-runtime-manifest';
11
11
  import type { DefaultHmrContext } from '@ecopages/core';
12
12
  import type { CompileOptions } from '@mdx-js/mdx';
13
- import { ClientGraphBoundaryCache } from './utils/client-graph-boundary-cache.js';
14
- import type { ReactHmrPageMetadataCache } from './services/react-hmr-page-metadata-cache.js';
13
+ import { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
14
+ import type { HmrPageMetadataCache } from './page-metadata-cache.js';
15
15
  export interface ReactHmrStrategyOptions {
16
16
  context: DefaultHmrContext;
17
- pageMetadataCache: ReactHmrPageMetadataCache;
17
+ pageMetadataCache: HmrPageMetadataCache;
18
18
  runtimeManifest: BrowserRuntimeManifest;
19
19
  mdxCompilerOptions?: CompileOptions;
20
20
  ownedTemplateExtensions?: string[];
21
21
  allTemplateExtensions?: string[];
22
- explicitGraphEnabled?: boolean;
23
22
  /**
24
23
  * Per-app cache for client-graph-boundary transform results. Owned by
25
24
  * the React plugin for the app's lifetime. When omitted, the strategy
@@ -82,10 +81,8 @@ export declare class ReactHmrStrategy extends HmrStrategy {
82
81
  */
83
82
  private context;
84
83
  private pageMetadataCache;
85
- private explicitGraphEnabled;
86
84
  private readonly runtimeManifest;
87
85
  private readonly clientGraphBoundaryCache;
88
- private readonly pagesIndex;
89
86
  constructor(options: ReactHmrStrategyOptions);
90
87
  /**
91
88
  * Returns build plugins for React HMR bundling.
@@ -127,6 +124,8 @@ export declare class ReactHmrStrategy extends HmrStrategy {
127
124
  * @returns True if this file should trigger React HMR rebuilds
128
125
  */
129
126
  matches(filePath: string): boolean;
127
+ canEmitEntrypoint(entrypointPath: string): boolean;
128
+ emitEntrypoint(entrypointPath: string, _outputPath: string): Promise<void>;
130
129
  /**
131
130
  * Checks if a file is a layout file.
132
131
  *
@@ -171,6 +170,19 @@ export declare class ReactHmrStrategy extends HmrStrategy {
171
170
  * @returns Action to broadcast update events (layout-update for layouts, update for components)
172
171
  */
173
172
  process(_filePath: string): Promise<HmrAction>;
173
+ /**
174
+ * Clears stale HMR output once per outdir before any rebuild pass in `process()`.
175
+ *
176
+ * @remarks
177
+ * Grouped page builds share `getDistDir()`; single page and non-page targets use
178
+ * per-entrypoint temp directories. Clearing here avoids redundant work when both
179
+ * page and non-page targets land in the same outdir.
180
+ */
181
+ private clearOutdirsForTargets;
182
+ private resolveDeclaredModulesForEntrypoint;
183
+ private collectDeclaredModulesForTargets;
184
+ private buildPluginsForDeclaredModules;
185
+ private recordBuildDependencyGraph;
174
186
  /**
175
187
  * Bundles a single React/MDX entrypoint with HMR support.
176
188
  *
@@ -195,6 +207,7 @@ export declare class ReactHmrStrategy extends HmrStrategy {
195
207
  * @returns Array of output URLs that were successfully built
196
208
  */
197
209
  private bundleReactEntrypoints;
210
+ private bundleReactBuildTargets;
198
211
  private resolveTempOutputPath;
199
212
  /**
200
213
  * Clears stale HMR output from a directory before a rebuild.
@@ -4,14 +4,13 @@ import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
4
  import { createBrowserRuntimePlugin } from "@ecopages/core/build/browser-runtime-plugin";
5
5
  import { FileNotFoundError, fileSystem } from "@ecopages/file-system";
6
6
  import { Logger } from "@ecopages/logger";
7
- import { injectHmrHandler } from "./utils/hmr-scripts.js";
8
- import { createClientGraphBoundaryPlugin } from "./utils/client-graph-boundary-plugin.js";
9
- import { ClientGraphBoundaryCache } from "./utils/client-graph-boundary-cache.js";
10
- import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from "./utils/declared-modules.js";
11
- import { someInConfigTree } from "./utils/component-config-traversal.js";
12
- import { createReactMdxLoaderPlugin } from "./utils/react-mdx-loader-plugin.js";
13
- import { getReactClientGraphAllowSpecifiers } from "./utils/react-runtime-alias-map.js";
14
- import { PagesIndex } from "./services/pages-index.js";
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";
15
14
  const appLogger = new Logger("[ReactHmrStrategy]");
16
15
  class ReactHmrStrategy extends HmrStrategy {
17
16
  type = HmrStrategyType.INTEGRATION;
@@ -28,22 +27,14 @@ class ReactHmrStrategy extends HmrStrategy {
28
27
  */
29
28
  context;
30
29
  pageMetadataCache;
31
- explicitGraphEnabled;
32
30
  runtimeManifest;
33
31
  clientGraphBoundaryCache;
34
- pagesIndex;
35
32
  constructor(options) {
36
33
  super();
37
34
  this.context = options.context;
38
35
  this.pageMetadataCache = options.pageMetadataCache;
39
36
  this.runtimeManifest = options.runtimeManifest;
40
- this.explicitGraphEnabled = options.explicitGraphEnabled ?? false;
41
37
  this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
42
- this.pagesIndex = new PagesIndex({
43
- pagesDir: this.context.getPagesDir(),
44
- extensions: options.allTemplateExtensions,
45
- isPageEntrypoint: (file) => this.isPageEntrypoint(file)
46
- });
47
38
  this.mdxCompilerOptions = options.mdxCompilerOptions;
48
39
  this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? [".tsx"]);
49
40
  this.allTemplateExtensions = [...options.allTemplateExtensions ?? [".tsx"]].sort(
@@ -70,13 +61,13 @@ class ReactHmrStrategy extends HmrStrategy {
70
61
  });
71
62
  return [
72
63
  createClientGraphBoundaryPlugin({
64
+ projectRoot: path.dirname(this.context.getSrcDir()),
73
65
  absWorkingDir: path.dirname(this.context.getSrcDir()),
74
66
  alwaysAllowSpecifiers: allowSpecifiers,
75
67
  declaredModules,
76
68
  cache: this.clientGraphBoundaryCache
77
69
  }),
78
- ...runtimeRewritePlugin ? [runtimeRewritePlugin] : [],
79
- ...this.context.getPlugins()
70
+ ...runtimeRewritePlugin ? [runtimeRewritePlugin] : []
80
71
  ];
81
72
  }
82
73
  isReactEntrypoint(filePath) {
@@ -126,7 +117,7 @@ class ReactHmrStrategy extends HmrStrategy {
126
117
  }
127
118
  pageModuleRequiresLayoutRefresh(pageModule, filePath) {
128
119
  return [pageModule.default?.config, pageModule.config].some((config) => {
129
- return this.configContainsFile(config?.layout?.config, filePath);
120
+ return (config?.layouts ?? []).some((layout) => this.configContainsFile(layout?.config, filePath));
130
121
  });
131
122
  }
132
123
  async hasLayoutOwnedDependencyTarget(changedFilePath, requestedTargets) {
@@ -157,9 +148,6 @@ class ReactHmrStrategy extends HmrStrategy {
157
148
  matches(filePath) {
158
149
  const watchedFiles = this.context.getWatchedFiles();
159
150
  appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
160
- if (watchedFiles.size === 0) {
161
- return false;
162
- }
163
151
  if (watchedFiles.has(filePath)) {
164
152
  return this.ownsWatchedEntrypoint(filePath);
165
153
  }
@@ -174,6 +162,13 @@ class ReactHmrStrategy extends HmrStrategy {
174
162
  }
175
163
  return this.isReactEntrypoint(filePath);
176
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
+ }
177
172
  /**
178
173
  * Checks if a file is a layout file.
179
174
  *
@@ -214,11 +209,11 @@ class ReactHmrStrategy extends HmrStrategy {
214
209
  return path.basename(encodedPath);
215
210
  }
216
211
  async collectReactPageBuildTargets() {
217
- await this.pagesIndex.refresh();
218
- const indexed = this.pagesIndex.list();
219
212
  const targets = /* @__PURE__ */ new Map();
220
- for (const entrypointPath of indexed) {
221
- this.pageMetadataCache.markOwnedEntrypoint(entrypointPath);
213
+ for (const entrypointPath of this.pageMetadataCache.getOwnedEntrypoints()) {
214
+ if (!this.isPageEntrypoint(entrypointPath)) {
215
+ continue;
216
+ }
222
217
  targets.set(entrypointPath, {
223
218
  entrypointPath,
224
219
  outputUrl: this.getEntrypointOutput(entrypointPath).outputUrl
@@ -338,6 +333,7 @@ class ReactHmrStrategy extends HmrStrategy {
338
333
  hasLayoutOwnedRequestedTarget = await this.hasLayoutOwnedDependencyTarget(_filePath, requestedTargets);
339
334
  }
340
335
  const requiresLayoutRefresh = isLayout || hasOwnedLayoutDependencyHit || hasLayoutOwnedRequestedTarget;
336
+ await this.clearOutdirsForTargets(pageTargets, nonPageTargets);
341
337
  const updates = [];
342
338
  const requestedOutputUrls = new Set(requestedTargets.map((target) => target.outputUrl));
343
339
  if (pageTargets.length > 1) {
@@ -392,6 +388,67 @@ class ReactHmrStrategy extends HmrStrategy {
392
388
  appLogger.debug(`No updates generated`);
393
389
  return { type: "none" };
394
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
+ }
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
+ }
395
452
  /**
396
453
  * Bundles a single React/MDX entrypoint with HMR support.
397
454
  *
@@ -405,61 +462,8 @@ class ReactHmrStrategy extends HmrStrategy {
405
462
  * @returns True if bundling was successful
406
463
  */
407
464
  async bundleReactEntrypoint(entrypointPath, outputUrl) {
408
- try {
409
- const isMdx = entrypointPath.endsWith(".mdx");
410
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
411
- const tempDir = path.dirname(outputPath);
412
- const cachedDeclared = this.pageMetadataCache.getDeclaredModules(entrypointPath);
413
- let entrypointDeclaredModules;
414
- let declaredModules;
415
- if (cachedDeclared) {
416
- entrypointDeclaredModules = cachedDeclared;
417
- declaredModules = cachedDeclared;
418
- } else {
419
- entrypointDeclaredModules = isMdx ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
420
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
421
- declaredModules = entrypointDeclaredModules;
422
- }
423
- const plugins = this.getBuildPlugins(declaredModules);
424
- if (isMdx && this.mdxCompilerOptions) {
425
- const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
426
- plugins.unshift(mdxPlugin);
427
- }
428
- await this.clearHmrOutdir(tempDir);
429
- const result = await this.context.getBrowserBundleService().bundle({
430
- profile: "hmr-entrypoint",
431
- entrypoints: [entrypointPath],
432
- outdir: tempDir,
433
- naming: `[name].[hash].tmp`,
434
- plugins,
435
- minify: false
436
- });
437
- if (!result.success) {
438
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
439
- return false;
440
- }
441
- if (result.dependencyGraph?.entrypoints) {
442
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
443
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
444
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
445
- }
446
- }
447
- const tempFile = result.outputs[0]?.path;
448
- if (!tempFile) {
449
- appLogger.error(`No output file generated for ${entrypointPath}`);
450
- return false;
451
- }
452
- const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
453
- if (!resolvedTempFile) {
454
- appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
455
- return false;
456
- }
457
- const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
458
- return processed;
459
- } catch (error) {
460
- appLogger.error(`Error bundling ${entrypointPath}:`, error);
461
- return false;
462
- }
465
+ const rebuiltOutputs = await this.bundleReactBuildTargets([{ entrypointPath, outputUrl }], { grouped: false });
466
+ return rebuiltOutputs.length > 0;
463
467
  }
464
468
  /**
465
469
  * Bundles multiple React/MDX entrypoints in a single build pass.
@@ -472,73 +476,90 @@ class ReactHmrStrategy extends HmrStrategy {
472
476
  * @returns Array of output URLs that were successfully built
473
477
  */
474
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
+ }
475
485
  try {
476
- const declaredModules = /* @__PURE__ */ new Set();
477
- let shouldEnableMdx = false;
478
- for (const { entrypointPath } of entrypoints) {
479
- const entrypointDeclaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath) ? this.pageMetadataCache.getDeclaredModules(entrypointPath) : entrypointPath.endsWith(".mdx") ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
480
- this.pageMetadataCache.setDeclaredModules(entrypointPath, entrypointDeclaredModules);
481
- for (const declaredModule of entrypointDeclaredModules) {
482
- declaredModules.add(declaredModule);
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
+ });
483
495
  }
484
- if (entrypointPath.endsWith(".mdx")) {
485
- shouldEnableMdx = true;
486
- }
487
- }
488
- const plugins = this.getBuildPlugins([...declaredModules]);
489
- if (shouldEnableMdx && this.mdxCompilerOptions) {
490
- plugins.unshift(createReactMdxLoaderPlugin(this.mdxCompilerOptions));
491
- }
492
- await this.clearHmrOutdir(this.context.getDistDir());
493
- const entryNameByPath = /* @__PURE__ */ new Map();
494
- for (const { entrypointPath } of entrypoints) {
495
- entryNameByPath.set(entrypointPath, {
496
- key: this.getRolldownEntryKey(entrypointPath),
497
- basename: this.getTempFileBasename(entrypointPath)
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
498
506
  });
507
+ if (!result2.success) {
508
+ appLogger.error(`Failed to build grouped React entrypoints:`, result2.logs);
509
+ return [];
510
+ }
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
+ }
529
+ }
530
+ return updatedOutputs;
499
531
  }
532
+ const { entrypointPath, outputUrl } = targets[0];
533
+ const { outputPath } = this.getEntrypointOutput(entrypointPath);
534
+ const tempDir = path.dirname(outputPath);
500
535
  const result = await this.context.getBrowserBundleService().bundle({
501
536
  profile: "hmr-entrypoint",
502
- entrypoints: Object.fromEntries(
503
- entrypoints.map(({ entrypointPath }) => [entryNameByPath.get(entrypointPath).key, entrypointPath])
504
- ),
505
- outdir: this.context.getDistDir(),
506
- naming: "[name].[hash].tmp",
507
- splitting: true,
537
+ entrypoints: [entrypointPath],
538
+ outdir: tempDir,
539
+ naming: `[name].[hash].tmp`,
508
540
  plugins,
509
541
  minify: false
510
542
  });
511
543
  if (!result.success) {
512
- appLogger.error(`Failed to build grouped React entrypoints:`, result.logs);
544
+ appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
513
545
  return [];
514
546
  }
515
- if (result.dependencyGraph?.entrypoints) {
516
- const dependencyGraph = this.context.getEntrypointDependencyGraph();
517
- for (const [entrypoint, deps] of Object.entries(result.dependencyGraph.entrypoints)) {
518
- dependencyGraph.setEntrypointDependencies(entrypoint, deps);
519
- }
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 [];
520
552
  }
521
- const updatedOutputs = [];
522
- for (const { entrypointPath, outputUrl } of entrypoints) {
523
- const { outputPath } = this.getEntrypointOutput(entrypointPath);
524
- const { basename: tempBasename, key: entryKey } = entryNameByPath.get(entrypointPath);
525
- const expectedSubdir = path.join(this.context.getDistDir(), path.dirname(entryKey));
526
- const tempOutput = result.outputs.find((output) => {
527
- return path.dirname(output.path) === expectedSubdir && path.basename(output.path).startsWith(`${tempBasename}.`) && path.basename(output.path).includes(".tmp");
528
- })?.path;
529
- const resolvedTempOutput = tempOutput ? await this.resolveTempOutputPath(tempOutput) : await this.resolveTempOutputPath(path.join(expectedSubdir, `${tempBasename}.[hash].tmp.js`));
530
- if (!resolvedTempOutput) {
531
- appLogger.debug(`Missing grouped temp output for ${outputUrl}`);
532
- continue;
533
- }
534
- const processed = await this.processOutput(resolvedTempOutput, outputPath, outputUrl);
535
- if (processed) {
536
- updatedOutputs.push(outputUrl);
537
- }
553
+ const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
554
+ if (!resolvedTempFile) {
555
+ appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
556
+ return [];
538
557
  }
539
- return updatedOutputs;
558
+ const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
559
+ return processed ? [outputUrl] : [];
540
560
  } catch (error) {
541
- appLogger.error(`Error bundling grouped React entrypoints:`, error);
561
+ const label = options.grouped ? "grouped React entrypoints" : targets[0]?.entrypointPath ?? "React entrypoint";
562
+ appLogger.error(`Error bundling ${label}:`, error);
542
563
  return [];
543
564
  }
544
565
  }
@@ -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
  */
@@ -1,5 +1,5 @@
1
1
  import path from "node:path";
2
- class ReactHmrPageMetadataCache {
2
+ class HmrPageMetadataCache {
3
3
  declaredModulesByEntrypoint = /* @__PURE__ */ new Map();
4
4
  ownedEntrypoints = /* @__PURE__ */ new Set();
5
5
  /**
@@ -23,6 +23,12 @@ class ReactHmrPageMetadataCache {
23
23
  const declaredModules = this.declaredModulesByEntrypoint.get(path.resolve(entrypointPath));
24
24
  return declaredModules ? [...declaredModules] : void 0;
25
25
  }
26
+ /**
27
+ * Returns React-owned page entrypoints discovered during development renders.
28
+ */
29
+ getOwnedEntrypoints() {
30
+ return [...this.ownedEntrypoints].sort((left, right) => left.localeCompare(right));
31
+ }
26
32
  /**
27
33
  * Returns true when the watched entrypoint is owned by the React integration.
28
34
  */
@@ -31,5 +37,5 @@ class ReactHmrPageMetadataCache {
31
37
  }
32
38
  }
33
39
  export {
34
- ReactHmrPageMetadataCache
40
+ HmrPageMetadataCache
35
41
  };
@@ -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
+ function assertNoBareEcopagesImports(source) {
3
+ expect(source).not.toMatch(/from\s+["']@ecopages\//);
4
+ }
5
+ export {
6
+ assertNoBareEcopagesImports
7
+ };