@ecopages/react 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +178 -35
  2. package/package.json +80 -32
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.d.ts +1 -0
  6. package/src/app/dynamic.test.browser.js +38 -0
  7. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  8. package/src/bundling/bootstrap-package-paths.js +5 -0
  9. package/src/bundling/bundle.d.ts +78 -0
  10. package/src/bundling/bundle.js +130 -0
  11. package/src/bundling/runtime-alias-map.d.ts +12 -0
  12. package/src/bundling/runtime-alias-map.js +110 -0
  13. package/src/bundling/runtime-bundle.d.ts +70 -0
  14. package/src/bundling/runtime-bundle.js +233 -0
  15. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  16. package/src/bundling/runtime-interop-plugin.js +32 -0
  17. package/src/bundling/runtime-mode.d.ts +1 -0
  18. package/src/bundling/runtime-mode.js +10 -0
  19. package/src/bundling/runtime-modules.d.ts +21 -0
  20. package/src/bundling/runtime-modules.js +28 -0
  21. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  22. package/src/client-graph/ast-transform-eco-page.js +71 -0
  23. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  24. package/src/client-graph/ast-transform-import-edits.js +75 -0
  25. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  26. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  27. package/src/client-graph/ast-transform.d.ts +12 -0
  28. package/src/client-graph/ast-transform.js +91 -0
  29. package/src/client-graph/ast-walk.d.ts +10 -0
  30. package/src/client-graph/ast-walk.js +26 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  32. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  33. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  34. package/src/client-graph/boundary-plugin-transform.js +31 -0
  35. package/src/client-graph/boundary-plugin.d.ts +23 -0
  36. package/src/client-graph/boundary-plugin.js +177 -0
  37. package/src/client-graph/component-config-traversal.d.ts +36 -0
  38. package/src/client-graph/component-config-traversal.js +77 -0
  39. package/src/{utils → client-graph}/declared-modules.d.ts +1 -1
  40. package/src/client-graph/declared-modules.js +69 -0
  41. package/src/client-graph/module-classification.d.ts +3 -0
  42. package/src/client-graph/module-classification.js +43 -0
  43. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  44. package/src/client-graph/reachability-analyzer.js +55 -0
  45. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  46. package/src/client-graph/reachability-client-roots.js +59 -0
  47. package/src/client-graph/reachability-export-names.d.ts +5 -0
  48. package/src/client-graph/reachability-export-names.js +34 -0
  49. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  50. package/src/client-graph/reachability-fallback-roots.js +71 -0
  51. package/src/client-graph/reachability-preload.d.ts +10 -0
  52. package/src/client-graph/reachability-preload.js +30 -0
  53. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  54. package/src/client-graph/reachability-top-level-index.js +93 -0
  55. package/src/client-graph/reachability-traverse.d.ts +7 -0
  56. package/src/client-graph/reachability-traverse.js +201 -0
  57. package/src/client-graph/specifier-classification.d.ts +74 -0
  58. package/src/client-graph/specifier-classification.js +191 -0
  59. package/src/content/collection-component-cache.d.ts +25 -0
  60. package/src/content/collection-component-cache.js +62 -0
  61. package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +7 -14
  62. package/src/contracts/router-adapter.js +6 -0
  63. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  64. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  65. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  66. package/src/hmr/hmr-strategy-process.js +83 -0
  67. package/src/hmr/hmr-strategy.d.ts +67 -0
  68. package/src/hmr/hmr-strategy.js +306 -0
  69. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +6 -2
  70. package/src/hmr/page-metadata-cache.js +44 -0
  71. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  72. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  73. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  74. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  75. package/src/hydration/bootstrap-imports.d.ts +25 -0
  76. package/src/hydration/bootstrap-imports.js +33 -0
  77. package/src/hydration/browser/island-hydration.d.ts +82 -0
  78. package/src/hydration/browser/island-hydration.js +251 -0
  79. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  80. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  81. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  82. package/src/hydration/browser/page-hydration-module.js +17 -0
  83. package/src/hydration/browser/page-hydration.d.ts +54 -0
  84. package/src/hydration/browser/page-hydration.js +177 -0
  85. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  86. package/src/hydration/compiled-page-hydration-options.js +1 -0
  87. package/src/hydration/hydration-asset.d.ts +127 -0
  88. package/src/hydration/hydration-asset.js +379 -0
  89. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  90. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  91. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  92. package/src/hydration/hydration-page-entry-source.js +87 -0
  93. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  94. package/src/hydration/hydration-script-compiler.js +213 -0
  95. package/src/hydration/page-data-manifest.d.ts +58 -0
  96. package/src/hydration/page-data-manifest.js +97 -0
  97. package/src/hydration/page-data-reader.d.ts +17 -0
  98. package/src/hydration/page-data-reader.js +31 -0
  99. package/src/hydration/page-payload.d.ts +68 -0
  100. package/src/hydration/page-payload.js +106 -0
  101. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  102. package/src/hydration/serialize-page-data-script.js +30 -0
  103. package/src/mdx/mdx-config-dependency.d.ts +37 -0
  104. package/src/mdx/mdx-config-dependency.js +107 -0
  105. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  106. package/src/mdx/mdx-loader-plugin.js +11 -0
  107. package/src/page/page-module.d.ts +46 -0
  108. package/src/page/page-module.js +74 -0
  109. package/src/plugin/react.constants.d.ts +1 -0
  110. package/src/plugin/react.constants.js +1 -0
  111. package/src/plugin/react.plugin.d.ts +71 -0
  112. package/src/plugin/react.plugin.js +210 -0
  113. package/src/plugin/react.types.d.ts +106 -0
  114. package/src/plugin/react.types.js +1 -0
  115. package/src/render/component-ownership.d.ts +49 -0
  116. package/src/render/component-ownership.js +47 -0
  117. package/src/render/component-ssr.d.ts +59 -0
  118. package/src/render/component-ssr.js +76 -0
  119. package/src/render/eco-embed.d.ts +11 -0
  120. package/src/render/eco-embed.js +9 -0
  121. package/src/render/errors.d.ts +16 -0
  122. package/src/render/errors.js +23 -0
  123. package/src/render/html-boundary.js +59 -0
  124. package/src/render/layout-compose.d.ts +66 -0
  125. package/src/render/layout-compose.js +134 -0
  126. package/src/render/react-renderer.d.ts +114 -0
  127. package/src/render/react-renderer.js +490 -0
  128. package/src/render/react-runtime.d.ts +13 -0
  129. package/src/render/react-runtime.js +26 -0
  130. package/src/render/unified-layout-composition.d.ts +22 -0
  131. package/src/render/unified-layout-composition.js +31 -0
  132. package/src/runtime/use-sync-external-store-with-selector.d.ts +3 -0
  133. package/src/runtime/use-sync-external-store-with-selector.js +54 -0
  134. package/CHANGELOG.md +0 -29
  135. package/src/react-hmr-strategy.d.ts +0 -148
  136. package/src/react-hmr-strategy.js +0 -313
  137. package/src/react-renderer.d.ts +0 -213
  138. package/src/react-renderer.js +0 -654
  139. package/src/react.plugin.d.ts +0 -147
  140. package/src/react.plugin.js +0 -146
  141. package/src/router-adapter.js +0 -0
  142. package/src/services/react-bundle.service.d.ts +0 -47
  143. package/src/services/react-bundle.service.js +0 -93
  144. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  145. package/src/services/react-hydration-asset.service.d.ts +0 -76
  146. package/src/services/react-hydration-asset.service.js +0 -210
  147. package/src/services/react-page-module.service.d.ts +0 -83
  148. package/src/services/react-page-module.service.js +0 -162
  149. package/src/services/react-runtime-bundle.service.d.ts +0 -40
  150. package/src/services/react-runtime-bundle.service.js +0 -130
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -43
  152. package/src/utils/client-graph-boundary-plugin.js +0 -494
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/declared-modules.js +0 -59
  155. package/src/utils/dynamic.js +0 -12
  156. package/src/utils/hmr-scripts.d.ts +0 -18
  157. package/src/utils/hmr-scripts.js +0 -31
  158. package/src/utils/html-boundary.js +0 -55
  159. package/src/utils/hydration-scripts.d.ts +0 -86
  160. package/src/utils/hydration-scripts.js +0 -285
  161. package/src/utils/reachability-analyzer.d.ts +0 -66
  162. package/src/utils/reachability-analyzer.js +0 -339
  163. package/src/utils/react-dom-runtime-interop-plugin.js +0 -29
  164. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  165. package/src/utils/react-mdx-loader-plugin.js +0 -45
  166. package/src/utils/react-runtime-specifier-map.d.ts +0 -6
  167. package/src/utils/react-runtime-specifier-map.js +0 -37
  168. package/src/utils/use-sync-external-store-shim-plugin.d.ts +0 -5
  169. package/src/utils/use-sync-external-store-shim-plugin.js +0 -41
  170. /package/src/{utils → app}/client-only.d.ts +0 -0
  171. /package/src/{utils → app}/dynamic.d.ts +0 -0
  172. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  173. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -1,148 +0,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 { HmrStrategy, type HmrAction } from '@ecopages/core/hmr/hmr-strategy';
10
- import type { DefaultHmrContext } from '@ecopages/core';
11
- import type { CompileOptions } from '@mdx-js/mdx';
12
- import type { ReactHmrPageMetadataCache } from './services/react-hmr-page-metadata-cache.js';
13
- /**
14
- * Strategy for handling React component HMR updates.
15
- *
16
- * This strategy provides React-specific HMR handling by rebuilding entrypoints
17
- * and injecting HMR acceptance handlers that trigger module invalidation.
18
- *
19
- * The processing steps are:
20
- * 1. Check if any React entrypoints are registered
21
- * 2. Rebuild all React entrypoints (the changed file could be a dependency)
22
- * 3. Rebuild browser output through the shared browser bundle service while
23
- * preserving React-specific runtime aliases and graph policy
24
- * 4. Read page config metadata through the shared server-module loading path
25
- * 5. Inject HMR acceptance handler
26
- * 6. Broadcast update events for each rebuilt entrypoint
27
- *
28
- * @remarks
29
- * This strategy has higher priority than generic JsHmrStrategy, allowing it
30
- * to handle React files specially while falling back to generic handling for
31
- * non-React files.
32
- *
33
- * Future enhancement: Track dependencies using Bun's transpiler API to only
34
- * rebuild affected entrypoints instead of all of them.
35
- *
36
- * @see https://bun.sh/docs/runtime/transpiler
37
- *
38
- * @example
39
- * ```typescript
40
- * const context = {
41
- * getWatchedFiles: () => watchedFilesMap,
42
- * getSpecifierMap: () => specifierMap,
43
- * getDistDir: () => '/path/to/dist/_hmr',
44
- * getPlugins: () => [],
45
- * getSrcDir: () => '/path/to/src',
46
- * getLayoutsDir: () => '/path/to/src/layouts'
47
- * };
48
- * const strategy = new ReactHmrStrategy(context);
49
- * ```
50
- */
51
- export declare class ReactHmrStrategy extends HmrStrategy {
52
- readonly type: 100;
53
- private mdxCompilerOptions?;
54
- private readonly ownedTemplateExtensions;
55
- private readonly allTemplateExtensions;
56
- private importNodePageModule;
57
- /**
58
- * Creates a new React HMR strategy instance.
59
- *
60
- * @param context - The HMR context providing access to watched files, plugins, build directories,
61
- * and the layouts directory for detecting layout file changes that require full
62
- * page reloads instead of module-level HMR updates.
63
- * @param pageMetadataCache - React-only cache of declared browser modules discovered during
64
- * server rendering. This avoids re-importing unchanged page modules
65
- * during save-time Fast Refresh rebuilds.
66
- * @param mdxCompilerOptions - Optional MDX compiler options for processing .mdx files
67
- * @param explicitGraphEnabled - Enables explicit graph mode for React HMR bundling.
68
- * In explicit mode, HMR builds omit AST server-only stripping plugins in React paths.
69
- */
70
- private context;
71
- private pageMetadataCache;
72
- private explicitGraphEnabled;
73
- constructor(context: DefaultHmrContext, pageMetadataCache: ReactHmrPageMetadataCache, mdxCompilerOptions?: CompileOptions, ownedTemplateExtensions?: string[], allTemplateExtensions?: string[], explicitGraphEnabled?: boolean);
74
- /**
75
- * Returns build plugins for React HMR bundling.
76
- *
77
- * Includes the client graph boundary plugin to prevent undeclared imports
78
- * (including `node:*`) from breaking the browser bundle.
79
- */
80
- private getBuildPlugins;
81
- private isReactEntrypoint;
82
- /**
83
- * Returns true when a route file uses a compound extension like `page.foo.tsx`.
84
- *
85
- * @remarks
86
- * React integration owns plain `.tsx` route templates. Compound extensions in
87
- * pages/layouts are integration-specific route templates and should not be
88
- * claimed by React HMR strategy.
89
- */
90
- private isRouteTemplate;
91
- private resolveTemplateExtension;
92
- private ownsWatchedEntrypoint;
93
- /**
94
- * Determines if the file is a React/MDX entrypoint that's registered for HMR.
95
- *
96
- * @param filePath - Absolute path to the changed file
97
- * @returns True if this is a registered React or MDX entrypoint
98
- */
99
- matches(filePath: string): boolean;
100
- /**
101
- * Checks if a file is a layout file.
102
- *
103
- * Layout files require special HMR handling because they wrap multiple pages and affect
104
- * the entire page structure. When a layout changes, we trigger a 'layout-update' event
105
- * instead of a regular 'update' event, which instructs the browser to perform a full
106
- * page reload (or clear cache and re-render) rather than attempting module-level HMR.
107
- *
108
- * @param filePath - Absolute path to the file
109
- * @returns True if the file is in the layouts directory
110
- */
111
- private isLayoutFile;
112
- /**
113
- * Processes a React file change by rebuilding all React entrypoints.
114
- *
115
- * For layout files, broadcasts a 'layout-update' event to trigger full page reload.
116
- * For regular components/pages, broadcasts 'update' events for module-level HMR.
117
- * When a page entrypoint is first registered, only that entrypoint is built.
118
- * Subsequent file updates rebuild all watched React entrypoints as usual.
119
- *
120
- * @param _filePath - Absolute path to the changed file
121
- * @returns Action to broadcast update events (layout-update for layouts, update for components)
122
- */
123
- process(_filePath: string): Promise<HmrAction>;
124
- /**
125
- * Bundles a single React/MDX entrypoint with HMR support.
126
- *
127
- * @param entrypointPath - Absolute path to the source file
128
- * @param outputUrl - URL path for the bundled file
129
- * @returns True if bundling was successful
130
- */
131
- private bundleReactEntrypoint;
132
- private resolveTempOutputPath;
133
- /**
134
- * Encodes dynamic route segments (brackets) in file paths.
135
- * Converts `[slug]` to `_slug_` to avoid filesystem issues.
136
- */
137
- private encodeDynamicSegments;
138
- /**
139
- * Processes bundled output and injects the React HMR handler.
140
- * Writes to temp file first, then renames atomically to avoid conflicts.
141
- *
142
- * @param tempPath - Path to the temporary bundled file
143
- * @param finalPath - Final destination path
144
- * @param url - URL path for logging
145
- * @returns True if processing was successful
146
- */
147
- private processOutput;
148
- }
@@ -1,313 +0,0 @@
1
- import path from "node:path";
2
- import { HmrStrategy, HmrStrategyType } from "@ecopages/core/hmr/hmr-strategy";
3
- import { rewriteRuntimeSpecifierAliases } from "@ecopages/core/build/runtime-specifier-aliases";
4
- import { createRuntimeSpecifierAliasPlugin } from "@ecopages/core/build/runtime-specifier-alias-plugin";
5
- import { FileNotFoundError, fileSystem } from "@ecopages/file-system";
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 { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from "./utils/declared-modules.js";
10
- import { getReactClientGraphAllowSpecifiers } from "./utils/react-runtime-specifier-map.js";
11
- import { createUseSyncExternalStoreShimPlugin } from "./utils/use-sync-external-store-shim-plugin.js";
12
- const appLogger = new Logger("[ReactHmrStrategy]");
13
- class ReactHmrStrategy extends HmrStrategy {
14
- type = HmrStrategyType.INTEGRATION;
15
- mdxCompilerOptions;
16
- ownedTemplateExtensions;
17
- allTemplateExtensions;
18
- async importNodePageModule(entrypointPath) {
19
- return await this.context.importServerModule(entrypointPath);
20
- }
21
- /**
22
- * Creates a new React HMR strategy instance.
23
- *
24
- * @param context - The HMR context providing access to watched files, plugins, build directories,
25
- * and the layouts directory for detecting layout file changes that require full
26
- * page reloads instead of module-level HMR updates.
27
- * @param pageMetadataCache - React-only cache of declared browser modules discovered during
28
- * server rendering. This avoids re-importing unchanged page modules
29
- * during save-time Fast Refresh rebuilds.
30
- * @param mdxCompilerOptions - Optional MDX compiler options for processing .mdx files
31
- * @param explicitGraphEnabled - Enables explicit graph mode for React HMR bundling.
32
- * In explicit mode, HMR builds omit AST server-only stripping plugins in React paths.
33
- */
34
- context;
35
- pageMetadataCache;
36
- explicitGraphEnabled;
37
- constructor(context, pageMetadataCache, mdxCompilerOptions, ownedTemplateExtensions = [".tsx"], allTemplateExtensions = [".tsx"], explicitGraphEnabled = false) {
38
- super();
39
- this.context = context;
40
- this.pageMetadataCache = pageMetadataCache;
41
- this.explicitGraphEnabled = explicitGraphEnabled;
42
- this.mdxCompilerOptions = mdxCompilerOptions;
43
- this.ownedTemplateExtensions = new Set(ownedTemplateExtensions);
44
- this.allTemplateExtensions = [...allTemplateExtensions].sort((a, b) => b.length - a.length);
45
- }
46
- /**
47
- * Returns build plugins for React HMR bundling.
48
- *
49
- * Includes the client graph boundary plugin to prevent undeclared imports
50
- * (including `node:*`) from breaking the browser bundle.
51
- */
52
- getBuildPlugins(declaredModules) {
53
- const runtimeSpecifierMap = this.context.getSpecifierMap();
54
- const allowSpecifiers = getReactClientGraphAllowSpecifiers(runtimeSpecifierMap.keys());
55
- const runtimeAliasPlugin = createRuntimeSpecifierAliasPlugin(runtimeSpecifierMap, {
56
- name: "react-hmr-runtime-specifier-alias"
57
- });
58
- return [
59
- createClientGraphBoundaryPlugin({
60
- absWorkingDir: path.dirname(this.context.getSrcDir()),
61
- alwaysAllowSpecifiers: allowSpecifiers,
62
- declaredModules
63
- }),
64
- ...runtimeAliasPlugin ? [runtimeAliasPlugin] : [],
65
- ...this.context.getPlugins(),
66
- createUseSyncExternalStoreShimPlugin({
67
- name: "react-hmr-use-sync-external-store-shim",
68
- namespace: "ecopages-react-hmr-shim"
69
- })
70
- ];
71
- }
72
- isReactEntrypoint(filePath) {
73
- if (filePath.endsWith(".mdx")) {
74
- return this.mdxCompilerOptions !== void 0;
75
- }
76
- if (!filePath.endsWith(".tsx")) {
77
- return false;
78
- }
79
- if (!this.isRouteTemplate(filePath)) {
80
- return true;
81
- }
82
- const templateExtension = this.resolveTemplateExtension(filePath);
83
- if (!templateExtension) {
84
- return false;
85
- }
86
- return this.ownedTemplateExtensions.has(templateExtension);
87
- }
88
- /**
89
- * Returns true when a route file uses a compound extension like `page.foo.tsx`.
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
- ownsWatchedEntrypoint(filePath) {
103
- return this.pageMetadataCache.ownsEntrypoint(filePath);
104
- }
105
- /**
106
- * Determines if the file is a React/MDX entrypoint that's registered for HMR.
107
- *
108
- * @param filePath - Absolute path to the changed file
109
- * @returns True if this is a registered React or MDX entrypoint
110
- */
111
- matches(filePath) {
112
- const watchedFiles = this.context.getWatchedFiles();
113
- appLogger.debug(`Checking ${filePath}. Watched: ${watchedFiles.size}`);
114
- if (watchedFiles.size === 0) {
115
- return false;
116
- }
117
- if (watchedFiles.has(filePath)) {
118
- return this.ownsWatchedEntrypoint(filePath);
119
- }
120
- return this.isReactEntrypoint(filePath);
121
- }
122
- /**
123
- * Checks if a file is a layout file.
124
- *
125
- * Layout files require special HMR handling because they wrap multiple pages and affect
126
- * the entire page structure. When a layout changes, we trigger a 'layout-update' event
127
- * instead of a regular 'update' event, which instructs the browser to perform a full
128
- * page reload (or clear cache and re-render) rather than attempting module-level HMR.
129
- *
130
- * @param filePath - Absolute path to the file
131
- * @returns True if the file is in the layouts directory
132
- */
133
- isLayoutFile(filePath) {
134
- return filePath.startsWith(this.context.getLayoutsDir());
135
- }
136
- /**
137
- * Processes a React file change by rebuilding all React entrypoints.
138
- *
139
- * For layout files, broadcasts a 'layout-update' event to trigger full page reload.
140
- * For regular components/pages, broadcasts 'update' events for module-level HMR.
141
- * When a page entrypoint is first registered, only that entrypoint is built.
142
- * Subsequent file updates rebuild all watched React entrypoints as usual.
143
- *
144
- * @param _filePath - Absolute path to the changed file
145
- * @returns Action to broadcast update events (layout-update for layouts, update for components)
146
- */
147
- async process(_filePath) {
148
- appLogger.debug(`Processing ${_filePath}`);
149
- const watchedFiles = this.context.getWatchedFiles();
150
- if (watchedFiles.size === 0) {
151
- appLogger.debug(`No watched files`);
152
- return { type: "none" };
153
- }
154
- const isLayout = this.isLayoutFile(_filePath);
155
- if (isLayout) {
156
- appLogger.debug(`Detected layout file change: ${_filePath}`);
157
- }
158
- const changedEntrypointOutput = watchedFiles.get(_filePath);
159
- if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(_filePath)) {
160
- appLogger.debug(`Skipping non-React watched entrypoint: ${_filePath}`);
161
- return { type: "none" };
162
- }
163
- const entrypointsToBuild = changedEntrypointOutput ? [[_filePath, changedEntrypointOutput]] : watchedFiles.entries();
164
- const updates = [];
165
- for (const [entrypoint, outputUrl] of entrypointsToBuild) {
166
- if (!this.isReactEntrypoint(entrypoint)) {
167
- continue;
168
- }
169
- appLogger.debug(`Bundling ${entrypoint}`);
170
- const success = await this.bundleReactEntrypoint(entrypoint, outputUrl);
171
- if (success) {
172
- updates.push(outputUrl);
173
- }
174
- }
175
- if (updates.length > 0) {
176
- if (isLayout) {
177
- appLogger.debug(`Layout update detected, sending layout-update event`);
178
- return {
179
- type: "broadcast",
180
- events: [
181
- {
182
- type: "layout-update"
183
- }
184
- ]
185
- };
186
- }
187
- appLogger.debug(`Broadcasting ${updates.length} updates`);
188
- return {
189
- type: "broadcast",
190
- events: updates.map((path2) => ({
191
- type: "update",
192
- path: path2,
193
- timestamp: Date.now()
194
- }))
195
- };
196
- }
197
- appLogger.debug(`No updates generated`);
198
- return { type: "none" };
199
- }
200
- /**
201
- * Bundles a single React/MDX entrypoint with HMR support.
202
- *
203
- * @param entrypointPath - Absolute path to the source file
204
- * @param outputUrl - URL path for the bundled file
205
- * @returns True if bundling was successful
206
- */
207
- async bundleReactEntrypoint(entrypointPath, outputUrl) {
208
- try {
209
- const isMdx = entrypointPath.endsWith(".mdx");
210
- const srcDir = this.context.getSrcDir();
211
- const relativePath = path.relative(srcDir, entrypointPath);
212
- const relativePathJs = relativePath.replace(/\.(tsx?|jsx?|mdx)$/, ".js");
213
- const encodedPathJs = this.encodeDynamicSegments(relativePathJs);
214
- const outputPath = path.join(this.context.getDistDir(), encodedPathJs);
215
- const tempDir = path.dirname(outputPath);
216
- const declaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath) ? this.pageMetadataCache.getDeclaredModules(entrypointPath) : isMdx ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
217
- const plugins = this.getBuildPlugins(declaredModules);
218
- if (isMdx && this.mdxCompilerOptions) {
219
- const { createReactMdxLoaderPlugin } = await import("./utils/react-mdx-loader-plugin.js");
220
- const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
221
- plugins.unshift(mdxPlugin);
222
- }
223
- const result = await this.context.getBrowserBundleService().bundle({
224
- profile: "hmr-entrypoint",
225
- entrypoints: [entrypointPath],
226
- outdir: tempDir,
227
- naming: `[name].[hash].tmp`,
228
- plugins,
229
- minify: false
230
- });
231
- if (!result.success) {
232
- appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
233
- return false;
234
- }
235
- const tempFile = result.outputs[0]?.path;
236
- if (!tempFile) {
237
- appLogger.error(`No output file generated for ${entrypointPath}`);
238
- return false;
239
- }
240
- const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
241
- if (!resolvedTempFile) {
242
- appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
243
- return false;
244
- }
245
- const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
246
- return processed;
247
- } catch (error) {
248
- appLogger.error(`Error bundling ${entrypointPath}:`, error);
249
- return false;
250
- }
251
- }
252
- async resolveTempOutputPath(tempPath) {
253
- if (fileSystem.exists(tempPath)) {
254
- return tempPath;
255
- }
256
- if (!tempPath.includes("[hash]")) {
257
- return tempPath;
258
- }
259
- const directory = path.dirname(tempPath);
260
- const pattern = path.basename(tempPath).replaceAll("[hash]", "*");
261
- const matches = await fileSystem.glob([pattern], { cwd: directory });
262
- if (matches.length === 0) {
263
- return null;
264
- }
265
- return path.isAbsolute(matches[0]) ? matches[0] : path.join(directory, matches[0]);
266
- }
267
- /**
268
- * Encodes dynamic route segments (brackets) in file paths.
269
- * Converts `[slug]` to `_slug_` to avoid filesystem issues.
270
- */
271
- encodeDynamicSegments(filepath) {
272
- return filepath.replace(/\[([^\]]+)\]/g, "_$1_");
273
- }
274
- /**
275
- * Processes bundled output and injects the React HMR handler.
276
- * Writes to temp file first, then renames atomically to avoid conflicts.
277
- *
278
- * @param tempPath - Path to the temporary bundled file
279
- * @param finalPath - Final destination path
280
- * @param url - URL path for logging
281
- * @returns True if processing was successful
282
- */
283
- async processOutput(tempPath, finalPath, url) {
284
- if (!fileSystem.exists(tempPath)) {
285
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
286
- return false;
287
- }
288
- try {
289
- let code = await fileSystem.readFile(tempPath);
290
- code = rewriteRuntimeSpecifierAliases(code, this.context.getSpecifierMap());
291
- code = injectHmrHandler(code);
292
- await fileSystem.writeAsync(finalPath, code);
293
- await fileSystem.removeAsync(tempPath).catch(() => {
294
- });
295
- appLogger.debug(`Processed ${url} with HMR handler`);
296
- return true;
297
- } catch (error) {
298
- if (error instanceof FileNotFoundError || error instanceof Error && error.message.includes("not found") || error instanceof Error && "code" in error && error.code === "ENOENT") {
299
- appLogger.debug(`Skipping stale temp output for ${url}: ${tempPath}`);
300
- await fileSystem.removeAsync(tempPath).catch(() => {
301
- });
302
- return false;
303
- }
304
- appLogger.error(`Error processing output for ${url}:`, error);
305
- await fileSystem.removeAsync(tempPath).catch(() => {
306
- });
307
- return false;
308
- }
309
- }
310
- }
311
- export {
312
- ReactHmrStrategy
313
- };
@@ -1,213 +0,0 @@
1
- /**
2
- * This module contains the React renderer
3
- * @module
4
- */
5
- import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
6
- import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
7
- import type { ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
8
- import { type ReactNode } from 'react';
9
- import type { CompileOptions } from '@mdx-js/mdx';
10
- import type { ReactRouterAdapter } from './router-adapter.js';
11
- import { ReactBundleService } from './services/react-bundle.service.js';
12
- import { ReactHmrPageMetadataCache } from './services/react-hmr-page-metadata-cache.js';
13
- import { ReactPageModuleService } from './services/react-page-module.service.js';
14
- import { ReactHydrationAssetService } from './services/react-hydration-asset.service.js';
15
- /**
16
- * Error thrown when an error occurs while rendering a React component.
17
- */
18
- export declare class ReactRenderError extends Error {
19
- constructor(message: string);
20
- }
21
- /**
22
- * Error thrown when an error occurs while bundling a React component.
23
- */
24
- export declare class BundleError extends Error {
25
- readonly logs: string[];
26
- constructor(message: string, logs: string[]);
27
- }
28
- /**
29
- * Renderer for React components.
30
- * @extends IntegrationRenderer
31
- */
32
- export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
33
- name: string;
34
- componentDirectory: string;
35
- static routerAdapter: ReactRouterAdapter | undefined;
36
- static mdxCompilerOptions: CompileOptions | undefined;
37
- static mdxExtensions: string[];
38
- static hmrPageMetadataCache: ReactHmrPageMetadataCache | undefined;
39
- /**
40
- * Enables explicit graph behavior for React page-entry bundling.
41
- *
42
- * When true, page-entry bundles disable AST server-only stripping and rely
43
- * on explicit dependency declarations for browser graph composition.
44
- */
45
- static explicitGraphEnabled: boolean;
46
- /** @internal */
47
- readonly bundleService: ReactBundleService;
48
- /** @internal */
49
- readonly pageModuleService: ReactPageModuleService;
50
- /** @internal */
51
- readonly hydrationAssetService: ReactHydrationAssetService;
52
- constructor(options: {
53
- appConfig: ConstructorParameters<typeof IntegrationRenderer>[0]['appConfig'];
54
- assetProcessingService: ConstructorParameters<typeof IntegrationRenderer>[0]['assetProcessingService'];
55
- resolvedIntegrationDependencies?: ProcessedAsset[];
56
- runtimeOrigin: string;
57
- });
58
- protected shouldRenderPageComponent(): boolean;
59
- /**
60
- * Reads the declared integration name for a component or layout.
61
- *
62
- * We honor both the explicit `config.integration` override and injected
63
- * `config.__eco.integration` metadata because pages can arrive here through
64
- * authored config as well as build-time component metadata.
65
- */
66
- private getComponentIntegration;
67
- /**
68
- * Returns whether a component should stay inside the React render lane.
69
- *
70
- * Components without explicit integration metadata are treated as React-owned
71
- * here because this renderer only receives them after the route pipeline has
72
- * already selected the React integration.
73
- */
74
- private isReactManagedComponent;
75
- /**
76
- * Creates the canonical page-props payload used by router hydration.
77
- *
78
- * React pages embedded in a non-React HTML shell still need to expose the same
79
- * page-data contract as fully React-owned documents so navigation and hydration
80
- * can read one shared document payload consistently.
81
- */
82
- private buildRouterPageDataScript;
83
- private getRouterDocumentAttributes;
84
- /**
85
- * Commits a framework-agnostic component to React semantics.
86
- *
87
- * This is one of the two real cast boundaries in this file. Core keeps
88
- * `EcoComponent` broad so integrations can share the same public surface; once
89
- * the React renderer is executing, `createElement()` needs a concrete React
90
- * component signature.
91
- */
92
- private asReactComponent;
93
- /**
94
- * Commits a mixed-shell component to the string-returning contract required by
95
- * non-React layouts and HTML templates.
96
- *
97
- * This is the second real cast boundary: once we decide a shell is not managed
98
- * by React, we call it directly and require serialized HTML back.
99
- */
100
- private asNonReactShellComponent;
101
- /**
102
- * Builds the serialized page-props payload embedded into the final HTML.
103
- *
104
- * The document payload is intentionally narrower than the full server render
105
- * input: only routing data, public page props, and explicitly allowed locals are
106
- * exposed to the browser.
107
- */
108
- private buildSerializedPageProps;
109
- /**
110
- * Appends route hydration assets for a concrete page/view file to the current
111
- * HTML transformer state.
112
- */
113
- private appendHydrationAssetsForFile;
114
- /**
115
- * Renders a non-React layout or HTML template and enforces that mixed shells
116
- * return serialized HTML.
117
- *
118
- * The React renderer can compose through another integration's shell, but only
119
- * if that shell yields a string that can be inserted into the final document.
120
- */
121
- private renderNonReactShellComponent;
122
- /**
123
- * Renders one React component boundary while preserving already-resolved child HTML.
124
- *
125
- * When nested boundary resolution has already produced child HTML for this
126
- * boundary, the child payload must remain raw SSR output rather than a React
127
- * string child, otherwise React would escape it. This helper renders a unique
128
- * token through React and swaps that token back to the resolved HTML
129
- * afterward.
130
- *
131
- * @param input Component render input for the current boundary.
132
- * @param context React-specific render context for stable token generation.
133
- * @returns Serialized component HTML with resolved child markup preserved.
134
- */
135
- private renderComponentHtml;
136
- private restoreRuntimeChildHtml;
137
- private renderQueuedChildrenToHtml;
138
- private resolveQueuedBoundaryHtml;
139
- private buildHydrationProps;
140
- /**
141
- * Renders a React component for component-level orchestration.
142
- *
143
- * Behavior:
144
- * - SSR always returns the component's own root HTML (no synthetic wrapper).
145
- * - When an explicit component instance id is provided, a stable
146
- * `data-eco-component-id` attribute is attached so island hydration can target it.
147
- * - Without an explicit instance id, component renders remain plain SSR output.
148
- * - When resolved child HTML is provided, that boundary is treated as a pure SSR
149
- * composition step and does not emit hydration assets for the parent wrapper.
150
- *
151
- * This preserves DOM shape for global CSS/layout selectors while keeping a
152
- * deterministic mount target per component instance.
153
- */
154
- renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult>;
155
- protected createComponentBoundaryRuntime(options: {
156
- boundaryInput: ComponentRenderInput;
157
- rendererCache: Map<string, IntegrationRenderer<any>>;
158
- }): import("@ecopages/core").ComponentBoundaryRuntime;
159
- /**
160
- * Checks if the given file path corresponds to an MDX file based on configured extensions.
161
- * @param filePath - The file path to check
162
- * @returns True if the file is an MDX file
163
- */
164
- isMdxFile(filePath: string): boolean;
165
- protected usesIntegrationPageImporter(file: string): boolean;
166
- protected importIntegrationPageFile(file: string): Promise<EcoPageFile>;
167
- protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(file: string, pageModule: TPageModule): TPageModule;
168
- /**
169
- * Processes MDX-specific configuration dependencies including layout dependencies.
170
- * @param pagePath - Absolute path to the MDX page file
171
- * @returns Processed assets for MDX configuration dependencies
172
- */
173
- private processMdxConfigDependencies;
174
- private processDeclaredMdxSsrLazyDependencies;
175
- private collectDeclaredMdxSsrLazyDependencies;
176
- buildRouteRenderAssets(pagePath: string): Promise<ProcessedAsset[]>;
177
- /**
178
- * Renders a full route response for the filesystem page pipeline.
179
- *
180
- * This path receives already-resolved route metadata, layout, locals, and HTML
181
- * template instances from the shared renderer orchestration. Its main job is to
182
- * serialize only the browser-safe page payload, compose the mixed React/non-
183
- * React shell tree, and hand the result back as a document body.
184
- */
185
- render({ params, query, props, locals, pageLocals, metadata, Page, Layout, HtmlTemplate, pageProps, }: IntegrationRendererRenderOptions<ReactNode>): Promise<RouteRendererBody>;
186
- protected getDocumentAttributes(): Record<string, string> | undefined;
187
- /**
188
- * Safely extracts the declared subset of locals for client-side hydration.
189
- *
190
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
191
- * request-scoped data (e.g., session). Only keys explicitly declared via
192
- * `Page.requires` are serialized to the client so sensitive request-only data
193
- * is not leaked into hydration payloads by default.
194
- *
195
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
196
- * to prevent accidental use. This method safely detects that case and returns
197
- * `undefined` instead of throwing.
198
- *
199
- * @param locals - The locals object from the render context
200
- * @param requiredLocals - Keys explicitly requested for client hydration
201
- * @returns The filtered locals object if serializable, undefined otherwise
202
- */
203
- private getSerializableLocals;
204
- /**
205
- * Renders an arbitrary React view through the application's HTML shell.
206
- *
207
- * Unlike route rendering, this path starts from a single component rather than a
208
- * page module discovered by the router. It still needs to resolve metadata,
209
- * layout dependencies, and hydration assets so direct `ctx.render()` calls match
210
- * normal page responses.
211
- */
212
- renderToResponse<P = Record<string, unknown>>(view: EcoComponent<P>, props: P, ctx: RenderToResponseContext): Promise<Response>;
213
- }