@ecopages/react 0.2.1-beta.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -1,217 +0,0 @@
1
- import path from "node:path";
2
- import { rapidhash } from "@ecopages/core/hash";
3
- import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
4
- import {
5
- AssetFactory
6
- } from "@ecopages/core/services/asset-processing-service";
7
- import { createHydrationScript, createIslandHydrationScript } from "../utils/hydration-scripts.js";
8
- import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
9
- function getReactIslandComponentKey(componentFile, config) {
10
- return rapidhash(`${componentFile}:${config?.__eco?.id ?? ""}`).toString();
11
- }
12
- class ReactHydrationAssetService {
13
- config;
14
- static ROUTER_PAGE_GROUPED_BUNDLE_ID = "ecopages-react-router-pages";
15
- constructor(config) {
16
- this.config = config;
17
- }
18
- getIslandBundleName(componentFile) {
19
- return `ecopages-react-island-${rapidhash(componentFile)}`;
20
- }
21
- getIslandHydrationName(bundleName, componentKey) {
22
- return `${bundleName}-hydration-${componentKey}`;
23
- }
24
- getRouterPageGroupedEntryName(pagePath) {
25
- const relativePath = path.relative(this.config.srcDir, pagePath);
26
- return relativePath.replace(/\.(tsx?|jsx?|mdx?)$/, "").replace(/[\\/]+/g, "__").replace(/\[([^\]]+)\]/g, "_$1_");
27
- }
28
- /**
29
- * Resolves the browser import path used for a React-owned page or island module.
30
- * Uses HMR manager for development or constructs static path for production.
31
- *
32
- * @param pagePath - Absolute path to the page source file
33
- * @param assetName - Generated asset name
34
- * @returns The resolved browser import path for the module
35
- */
36
- async resolveAssetImportPath(pagePath, assetName) {
37
- const hmrManager = this.config.assetProcessingService?.getHmrManager();
38
- if (hmrManager?.isEnabled()) {
39
- return hmrManager.registerEntrypoint(pagePath);
40
- }
41
- return `/${path.join(RESOLVED_ASSETS_DIR, path.relative(this.config.srcDir, pagePath)).replace(path.basename(pagePath), `${assetName}.js`).replace(/\\/g, "/")}`;
42
- }
43
- /**
44
- * Creates the page-owned route entry asset for hydration and client navigation.
45
- *
46
- * @param pagePath - Absolute path to the page source file
47
- * @param componentName - Generated unique component name
48
- * @param importPath - Resolved browser import path used by development HMR
49
- * @param bundleOptions - Bundle configuration options
50
- * @param isDevelopment - Whether running in development mode with HMR
51
- * @param isMdx - Whether the source file is an MDX file
52
- * @returns One page-owned asset definition for processing
53
- */
54
- createPageDependencies(pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, isDevelopment, useBrowserRuntimeImports, isMdx) {
55
- const runtimeImports = this.config.bundleService.getRuntimeImports();
56
- const groupedBundle = this.config.routerAdapter ? {
57
- id: ReactHydrationAssetService.ROUTER_PAGE_GROUPED_BUNDLE_ID,
58
- entryName: this.getRouterPageGroupedEntryName(pagePath)
59
- } : void 0;
60
- return [
61
- AssetFactory.createContentScript({
62
- position: "head",
63
- content: createHydrationScript({
64
- importPath: isDevelopment ? importPath : pagePath,
65
- pageModuleUrlExpression,
66
- reactImportPath: useBrowserRuntimeImports ? runtimeImports.react : "react",
67
- reactDomClientImportPath: useBrowserRuntimeImports ? runtimeImports.reactDomClient : "react-dom/client",
68
- routerImportPath: useBrowserRuntimeImports ? runtimeImports.router : this.config.routerAdapter?.bundle.importPath,
69
- isDevelopment,
70
- isMdx,
71
- router: this.config.routerAdapter,
72
- scriptId: componentName
73
- }),
74
- name: componentName,
75
- packageRole: "page-script",
76
- bundle: !isDevelopment,
77
- groupedBundle,
78
- bundleOptions,
79
- attributes: {
80
- type: "module",
81
- defer: "",
82
- "data-eco-rerun": "true",
83
- "data-eco-script-id": componentName,
84
- ...this.config.routerAdapter ? { "data-eco-page-bootstrap": "react-router" } : {},
85
- "data-eco-persist": "true"
86
- }
87
- })
88
- ];
89
- }
90
- /**
91
- * Builds client-side assets for a React component island.
92
- *
93
- * Includes the bundled component entry and a shared hydration bootstrap script.
94
- *
95
- * @param componentFile - Absolute path to the component source file
96
- * @param config - Optional component config with `__eco` metadata
97
- * @returns Processed assets ready for injection
98
- */
99
- async buildComponentRenderAssets(componentFile, config) {
100
- const componentName = this.getIslandBundleName(componentFile);
101
- const componentKey = getReactIslandComponentKey(componentFile, config);
102
- const hydrationName = this.getIslandHydrationName(componentName, componentKey);
103
- const hmrManager = this.config.assetProcessingService?.getHmrManager();
104
- const isDevelopment = hmrManager?.isEnabled() ?? false;
105
- if (isDevelopment) {
106
- this.config.hmrPageMetadataCache?.markOwnedEntrypoint(componentFile);
107
- }
108
- const importPath = await this.resolveAssetImportPath(componentFile, componentName);
109
- const declaredModules = collectDeclaredModulesInConfig(config);
110
- const bundleOptions = await this.config.bundleService.createBundleOptions(
111
- componentName,
112
- false,
113
- declaredModules
114
- );
115
- const runtimeImports = this.config.bundleService.getRuntimeImports();
116
- const dependencies = [
117
- AssetFactory.createFileScript({
118
- position: "head",
119
- filepath: componentFile,
120
- name: componentName,
121
- packageRole: "dynamic-chunk",
122
- excludeFromHtml: true,
123
- bundle: true,
124
- bundleOptions,
125
- attributes: {
126
- type: "module",
127
- defer: "",
128
- "data-eco-persist": "true"
129
- }
130
- }),
131
- AssetFactory.createContentScript({
132
- position: "head",
133
- content: createIslandHydrationScript({
134
- importPath,
135
- scriptId: hydrationName,
136
- reactImportPath: runtimeImports.react,
137
- reactDomClientImportPath: runtimeImports.reactDomClient,
138
- targetSelector: `[data-eco-component-key="${componentKey}"]`,
139
- componentRef: config?.__eco?.id,
140
- componentFile,
141
- isDevelopment
142
- }),
143
- name: hydrationName,
144
- packageRole: "keep-separate",
145
- bundle: false,
146
- attributes: {
147
- type: "module",
148
- defer: "",
149
- "data-eco-rerun": "true",
150
- "data-eco-script-id": hydrationName,
151
- "data-eco-persist": "true"
152
- }
153
- })
154
- ];
155
- if (!this.config.assetProcessingService) {
156
- return [];
157
- }
158
- return this.config.assetProcessingService.processDependencies(dependencies, componentName);
159
- }
160
- /**
161
- * Creates the Page Browser Graph dependency declarations for a React page.
162
- *
163
- * @param pagePath - Absolute file path of the page
164
- * @param isMdx - Whether the page is an MDX file
165
- * @param declaredModules - Explicitly declared browser module specifiers
166
- * @returns Declarative assets for core-owned processing
167
- */
168
- async createPageBrowserGraphDependencies(pagePath, isMdx, declaredModules) {
169
- const componentName = `ecopages-react-${rapidhash(pagePath)}`;
170
- const hmrManager = this.config.assetProcessingService?.getHmrManager();
171
- const isDevelopment = hmrManager?.isEnabled() ?? false;
172
- const isHostedDevelopment = !isDevelopment && process.env.NODE_ENV !== "production";
173
- const usesRouterRuntime = Boolean(this.config.routerAdapter);
174
- const useBrowserRuntimeImports = isDevelopment || isHostedDevelopment || usesRouterRuntime;
175
- if (isDevelopment) {
176
- this.config.hmrPageMetadataCache?.setDeclaredModules(pagePath, declaredModules);
177
- }
178
- const importPath = await this.resolveAssetImportPath(pagePath, componentName);
179
- const pageModuleUrlExpression = isDevelopment ? JSON.stringify(importPath) : "import.meta.url";
180
- const bundleOptions = await this.config.bundleService.createBundleOptions(
181
- componentName,
182
- isMdx,
183
- declaredModules,
184
- { includeRuntime: !useBrowserRuntimeImports, splitting: usesRouterRuntime }
185
- );
186
- const dependencies = this.createPageDependencies(
187
- pagePath,
188
- componentName,
189
- importPath,
190
- pageModuleUrlExpression,
191
- bundleOptions,
192
- isDevelopment,
193
- useBrowserRuntimeImports,
194
- isMdx
195
- );
196
- return dependencies;
197
- }
198
- /**
199
- * Builds the Page Browser Graph assets for a React page.
200
- *
201
- * @remarks
202
- * Kept as a compatibility wrapper while callers migrate to core-owned page
203
- * graph assembly.
204
- */
205
- async buildPageBrowserGraphAssets(pagePath, isMdx, declaredModules) {
206
- const componentName = `ecopages-react-${rapidhash(pagePath)}`;
207
- const dependencies = await this.createPageBrowserGraphDependencies(pagePath, isMdx, declaredModules);
208
- if (!this.config.assetProcessingService) {
209
- throw new Error("AssetProcessingService is not set");
210
- }
211
- return this.config.assetProcessingService.processDependencies(dependencies, componentName);
212
- }
213
- }
214
- export {
215
- ReactHydrationAssetService,
216
- getReactIslandComponentKey
217
- };
@@ -1,122 +0,0 @@
1
- import path from "node:path";
2
- import { rapidhash } from "@ecopages/core/hash";
3
- import {
4
- AssetFactory
5
- } from "@ecopages/core/services/asset-processing-service";
6
- import { collectFromConfigForest, getComponentConfigs } from "../utils/component-config-traversal.js";
7
- class ReactMdxConfigDependencyService {
8
- config;
9
- constructor(config) {
10
- this.config = config;
11
- }
12
- /**
13
- * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
14
- */
15
- async processMdxConfigDependencies(options) {
16
- const components = this.createOwnedConfigComponents(options.pagePath, options.config);
17
- if (components.length === 0) {
18
- return [];
19
- }
20
- const processedDependencies = await options.processComponentDependencies(components);
21
- const eagerSsrLazyDependencies = await this.processDeclaredSsrLazyDependencies(components, options.pagePath);
22
- return [...processedDependencies, ...eagerSsrLazyDependencies];
23
- }
24
- createOwnedConfigComponents(pagePath, config) {
25
- const components = [];
26
- const resolvedLayout = config?.layout;
27
- if (resolvedLayout?.config?.dependencies) {
28
- const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(
29
- resolvedLayout.config,
30
- pagePath
31
- );
32
- components.push({ config: layoutConfig });
33
- }
34
- if (config?.dependencies) {
35
- components.push({
36
- config: {
37
- ...config,
38
- __eco: {
39
- id: rapidhash(pagePath).toString(36),
40
- file: pagePath,
41
- integration: this.config.integrationName
42
- }
43
- }
44
- });
45
- }
46
- return components;
47
- }
48
- async processDeclaredSsrLazyDependencies(components, pagePath) {
49
- if (!this.config.assetProcessingService?.processDependencies) {
50
- return [];
51
- }
52
- const dependencies = this.collectDeclaredSsrLazyDependencies(components);
53
- if (dependencies.length === 0) {
54
- return [];
55
- }
56
- return this.config.assetProcessingService.processDependencies(
57
- dependencies,
58
- `${this.config.integrationName}-mdx-ssr-lazy:${pagePath}`
59
- );
60
- }
61
- /**
62
- * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
63
- */
64
- collectDeclaredSsrLazyDependencies(components) {
65
- const dependencies = [];
66
- const seenKeys = /* @__PURE__ */ new Set();
67
- const normalizeAttributes = (attributes) => ({
68
- type: "module",
69
- defer: "",
70
- ...attributes ?? {}
71
- });
72
- collectFromConfigForest(getComponentConfigs(components), (config) => {
73
- const componentFile = config.__eco?.file;
74
- if (!componentFile) {
75
- return [];
76
- }
77
- const componentDir = path.dirname(componentFile);
78
- for (const script of config.dependencies?.scripts ?? []) {
79
- if (typeof script === "string" || !script.lazy || script.ssr !== true) {
80
- continue;
81
- }
82
- const attributes = normalizeAttributes(script.attributes);
83
- if (script.content) {
84
- const key2 = `content:${script.content}:${JSON.stringify(attributes)}`;
85
- if (seenKeys.has(key2)) {
86
- continue;
87
- }
88
- seenKeys.add(key2);
89
- dependencies.push(
90
- AssetFactory.createContentScript({
91
- position: "head",
92
- content: script.content,
93
- attributes
94
- })
95
- );
96
- continue;
97
- }
98
- if (!script.src) {
99
- continue;
100
- }
101
- const resolvedPath = path.resolve(componentDir, script.src);
102
- const key = `file:${resolvedPath}:${JSON.stringify(attributes)}`;
103
- if (seenKeys.has(key)) {
104
- continue;
105
- }
106
- seenKeys.add(key);
107
- dependencies.push(
108
- AssetFactory.createFileScript({
109
- filepath: resolvedPath,
110
- position: "head",
111
- attributes
112
- })
113
- );
114
- }
115
- return [];
116
- });
117
- return dependencies;
118
- }
119
- }
120
- export {
121
- ReactMdxConfigDependencyService
122
- };
@@ -1,88 +0,0 @@
1
- /**
2
- * Page module loading and configuration resolution service for React integration.
3
- *
4
- * Handles MDX compilation, component config metadata resolution,
5
- * and module hydration analysis.
6
- *
7
- * @module
8
- */
9
- import type { EcoComponentConfig, EcoPageFile } from '@ecopages/core';
10
- import { type BuildExecutor } from '@ecopages/core/build/build-adapter';
11
- import type { CompileOptions } from '@mdx-js/mdx';
12
- /**
13
- * Configuration for the ReactPageModuleService.
14
- */
15
- export interface ReactPageModuleServiceConfig {
16
- rootDir: string;
17
- distDir: string;
18
- workDir: string;
19
- buildExecutor: BuildExecutor;
20
- layoutsDir?: string;
21
- componentsDir?: string;
22
- mdxCompilerOptions?: CompileOptions;
23
- mdxExtensions: string[];
24
- integrationName: string;
25
- hasRouterAdapter: boolean;
26
- }
27
- /**
28
- * Manages page module loading (including MDX compilation), config metadata
29
- * resolution, and hydration analysis for React pages.
30
- */
31
- export declare class ReactPageModuleService {
32
- private readonly config;
33
- constructor(config: ReactPageModuleServiceConfig);
34
- /**
35
- * Checks if the given file path corresponds to an MDX file based on configured extensions.
36
- * @param filePath - The file path to check
37
- * @returns True if the file is an MDX file
38
- */
39
- isMdxFile(filePath: string): boolean;
40
- /**
41
- * Compiles and imports an MDX file as a page module.
42
- *
43
- * @param filePath - Absolute path to the MDX file
44
- * @returns The imported module
45
- */
46
- importMdxPageFile(filePath: string, options?: {
47
- bypassCache?: boolean;
48
- cacheScope?: string;
49
- }): Promise<EcoPageFile<{
50
- config?: EcoComponentConfig;
51
- }>>;
52
- /**
53
- * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
54
- * Resolves the file path from dependency declarations when not already set.
55
- *
56
- * @param config - The component config to augment
57
- * @param pagePath - Fallback file path if dependency resolution fails
58
- * @returns Config with `__eco` metadata populated
59
- */
60
- ensureConfigFileMetadata(config: EcoComponentConfig, pagePath: string): EcoComponentConfig;
61
- /**
62
- * Recursively checks whether a component config tree declares any browser modules.
63
- * Used to determine if a page needs hydration.
64
- */
65
- hasModulesInConfig(config: EcoComponentConfig | undefined): boolean;
66
- /**
67
- * Determines whether a page needs client-side hydration.
68
- *
69
- * @param pageModule - The imported page module
70
- * @returns True if the page should be hydrated
71
- */
72
- shouldHydratePage(pageModule: EcoPageFile<{
73
- config?: EcoComponentConfig;
74
- }> & {
75
- config?: EcoComponentConfig;
76
- }): boolean;
77
- /**
78
- * Collects all explicitly declared browser module specifiers from a page module.
79
- *
80
- * @param pageModule - The imported page module
81
- * @returns Deduplicated list of declared module specifiers
82
- */
83
- collectPageDeclaredModules(pageModule: EcoPageFile<{
84
- config?: EcoComponentConfig;
85
- }> & {
86
- config?: EcoComponentConfig;
87
- }): string[];
88
- }
@@ -1,166 +0,0 @@
1
- import path from "node:path";
2
- import { pathToFileURL } from "node:url";
3
- import { build } from "@ecopages/core/build/build-adapter";
4
- import { normalizeNodeRuntimeBuildOutputFile } from "@ecopages/core/build/runtime-build-output-normalizer";
5
- import { rapidhash } from "@ecopages/core/hash";
6
- import { fileSystem } from "@ecopages/file-system";
7
- import { someInConfigTree } from "../utils/component-config-traversal.js";
8
- import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
9
- import { createReactMdxLoaderPlugin } from "../utils/react-mdx-loader-plugin.js";
10
- class ReactPageModuleService {
11
- config;
12
- constructor(config) {
13
- this.config = config;
14
- }
15
- /**
16
- * Checks if the given file path corresponds to an MDX file based on configured extensions.
17
- * @param filePath - The file path to check
18
- * @returns True if the file is an MDX file
19
- */
20
- isMdxFile(filePath) {
21
- return this.config.mdxExtensions.some((ext) => filePath.endsWith(ext));
22
- }
23
- /**
24
- * Compiles and imports an MDX file as a page module.
25
- *
26
- * @param filePath - Absolute path to the MDX file
27
- * @returns The imported module
28
- */
29
- async importMdxPageFile(filePath, options) {
30
- const mdxPlugin = createReactMdxLoaderPlugin(
31
- this.config.mdxCompilerOptions ?? {
32
- jsxImportSource: "react",
33
- jsxRuntime: "automatic",
34
- development: process?.env?.NODE_ENV === "development"
35
- }
36
- );
37
- const outdir = path.join(this.config.workDir, ".server-modules-react-mdx");
38
- const fileBaseName = path.basename(filePath, path.extname(filePath));
39
- const fileHash = fileSystem.hash(filePath);
40
- const cacheScopeSuffix = options?.cacheScope ? `-${sanitizeCacheScope(options.cacheScope)}` : "";
41
- const cacheBuster = options?.bypassCache || process?.env?.NODE_ENV === "development" ? `-${Date.now()}` : "";
42
- const outputFileName = `${fileBaseName}-${fileHash}${cacheScopeSuffix}${cacheBuster}.mjs`;
43
- const outputNamingTemplate = `${fileBaseName}-${fileHash}${cacheScopeSuffix}${cacheBuster}.[ext]`;
44
- const buildResult = await build(
45
- {
46
- entrypoints: [filePath],
47
- root: this.config.rootDir,
48
- outdir,
49
- target: "es2022",
50
- format: "esm",
51
- sourcemap: "none",
52
- splitting: false,
53
- minify: false,
54
- treeshaking: false,
55
- externalPackages: true,
56
- naming: outputNamingTemplate,
57
- plugins: [mdxPlugin]
58
- },
59
- this.config.buildExecutor
60
- );
61
- if (!buildResult.success) {
62
- const details = buildResult.logs.map((log) => log.message).join(" | ");
63
- throw new Error(`Failed to compile MDX page module: ${details}`);
64
- }
65
- const preferredOutputPath = path.join(outdir, outputFileName);
66
- const compiledOutput = buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ?? buildResult.outputs.find((output) => /\.(?:[cm]?js)$/u.test(output.path))?.path;
67
- if (!compiledOutput) {
68
- throw new Error(`No compiled MDX output generated for page: ${filePath}`);
69
- }
70
- normalizeNodeRuntimeBuildOutputFile(compiledOutput, this.config.rootDir);
71
- const compiledOutputUrl = pathToFileURL(compiledOutput);
72
- if (process?.env?.NODE_ENV === "development" || options?.cacheScope) {
73
- compiledOutputUrl.searchParams.set(
74
- "update",
75
- [fileHash, options?.cacheScope ? sanitizeCacheScope(options.cacheScope) : void 0].filter((value) => value !== void 0).join("-")
76
- );
77
- }
78
- return await import(
79
- /* @vite-ignore */
80
- compiledOutputUrl.href
81
- );
82
- }
83
- /**
84
- * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
85
- * Resolves the file path from dependency declarations when not already set.
86
- *
87
- * @param config - The component config to augment
88
- * @param pagePath - Fallback file path if dependency resolution fails
89
- * @returns Config with `__eco` metadata populated
90
- */
91
- ensureConfigFileMetadata(config, pagePath) {
92
- if (config.__eco?.file) {
93
- return config;
94
- }
95
- const buildEcoMeta = (file) => ({
96
- id: config.__eco?.id ?? rapidhash(file).toString(36),
97
- integration: config.__eco?.integration ?? this.config.integrationName,
98
- file
99
- });
100
- const resolveDependencyValue = (value) => typeof value === "string" ? value : value.src;
101
- const dependencyPaths = [
102
- ...(config.dependencies?.stylesheets ?? []).map(resolveDependencyValue),
103
- ...(config.dependencies?.scripts ?? []).map(resolveDependencyValue)
104
- ].filter((value) => Boolean(value)).filter((value) => value.startsWith("./") || value.startsWith("../"));
105
- const candidateDirs = [this.config.layoutsDir, this.config.componentsDir, path.dirname(pagePath)].filter(
106
- (value) => typeof value === "string" && value.length > 0
107
- );
108
- for (const dependencyPath of dependencyPaths) {
109
- for (const candidateDir of candidateDirs) {
110
- const resolvedDependency = path.resolve(candidateDir, dependencyPath);
111
- if (fileSystem.exists(resolvedDependency)) {
112
- return {
113
- ...config,
114
- __eco: buildEcoMeta(path.join(candidateDir, path.basename(pagePath)))
115
- };
116
- }
117
- }
118
- }
119
- return {
120
- ...config,
121
- __eco: buildEcoMeta(pagePath)
122
- };
123
- }
124
- /**
125
- * Recursively checks whether a component config tree declares any browser modules.
126
- * Used to determine if a page needs hydration.
127
- */
128
- hasModulesInConfig(config) {
129
- return someInConfigTree(
130
- config,
131
- (node) => node.dependencies?.modules?.some((entry) => entry.trim().length > 0) ?? false
132
- );
133
- }
134
- /**
135
- * Determines whether a page needs client-side hydration.
136
- *
137
- * @param pageModule - The imported page module
138
- * @returns True if the page should be hydrated
139
- */
140
- shouldHydratePage(pageModule) {
141
- if (this.config.hasRouterAdapter) {
142
- return true;
143
- }
144
- const pageConfig = pageModule.default?.config;
145
- return this.hasModulesInConfig(pageConfig) || this.hasModulesInConfig(pageModule.config);
146
- }
147
- /**
148
- * Collects all explicitly declared browser module specifiers from a page module.
149
- *
150
- * @param pageModule - The imported page module
151
- * @returns Deduplicated list of declared module specifiers
152
- */
153
- collectPageDeclaredModules(pageModule) {
154
- const declarations = [
155
- ...collectDeclaredModulesInConfig(pageModule.default?.config),
156
- ...collectDeclaredModulesInConfig(pageModule.config)
157
- ];
158
- return Array.from(new Set(declarations));
159
- }
160
- }
161
- function sanitizeCacheScope(cacheScope) {
162
- return cacheScope.replace(/[^a-zA-Z0-9_-]+/g, "-");
163
- }
164
- export {
165
- ReactPageModuleService
166
- };
@@ -1,46 +0,0 @@
1
- import type { HtmlTemplateProps, IntegrationRendererRenderOptions, RequestLocals } from '@ecopages/core';
2
- import type { ReactNode } from 'react';
3
- type PagePayloadOptions = {
4
- pageProps?: HtmlTemplateProps['pageProps'];
5
- params: IntegrationRendererRenderOptions<ReactNode>['params'];
6
- query: IntegrationRendererRenderOptions<ReactNode>['query'];
7
- safeLocals?: RequestLocals;
8
- };
9
- /**
10
- * Builds the serialized page payload React exposes to document shells and the browser.
11
- *
12
- * This keeps hydration payload shaping away from the renderer so the renderer can
13
- * stay focused on component orchestration instead of data serialization rules.
14
- */
15
- export declare class ReactPagePayloadService {
16
- /**
17
- * Creates the canonical page-props payload used by router hydration.
18
- *
19
- * React pages embedded in a non-React HTML shell still need to expose the same
20
- * page-data contract as fully React-owned documents so navigation and hydration
21
- * can read one shared document payload consistently.
22
- */
23
- buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined): string;
24
- /**
25
- * Builds the serialized page-props payload embedded into the final HTML.
26
- *
27
- * The document payload is intentionally narrower than the full server render
28
- * input: only routing data, public page props, and explicitly allowed locals are
29
- * exposed to the browser.
30
- */
31
- buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
32
- /**
33
- * Safely extracts the declared subset of locals for client-side hydration.
34
- *
35
- * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
36
- * request-scoped data (e.g., session). Only keys explicitly declared via
37
- * `Page.requires` are serialized to the client so sensitive request-only data
38
- * is not leaked into hydration payloads by default.
39
- *
40
- * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
41
- * to prevent accidental use. This method safely detects that case and returns
42
- * `undefined` instead of throwing.
43
- */
44
- getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
45
- }
46
- export {};