@ecopages/react 0.2.1-beta.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -0,0 +1,22 @@
1
+ import type { EcoBuildPlugin } from '@ecopages/core/integration';
2
+ import type { EcoComponentConfig } from '@ecopages/core';
3
+ import type { HmrPageMetadataCache } from './page-metadata-cache.js';
4
+ export type ReactHmrBuildTarget = {
5
+ entrypointPath: string;
6
+ outputUrl: string;
7
+ };
8
+ type ImportedReactPageModule = {
9
+ default?: {
10
+ config?: EcoComponentConfig;
11
+ };
12
+ config?: EcoComponentConfig;
13
+ };
14
+ export type ReactHmrDevTransformPluginOptions = {
15
+ pageMetadataCache: HmrPageMetadataCache;
16
+ getMdxLoaderPlugin?: () => EcoBuildPlugin;
17
+ getBuildPlugins: (declaredModules?: readonly string[]) => EcoBuildPlugin[];
18
+ importNodePageModule: (entrypointPath: string) => Promise<ImportedReactPageModule>;
19
+ };
20
+ export declare function resolveReactDeclaredModulesForEntrypoint(options: ReactHmrDevTransformPluginOptions, entrypointPath: string): Promise<readonly string[]>;
21
+ export declare function buildReactDevTransformPlugins(options: ReactHmrDevTransformPluginOptions, declaredModules: readonly string[], shouldEnableMdx: boolean): EcoBuildPlugin[];
22
+ export {};
@@ -0,0 +1,19 @@
1
+ import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from '../client-graph/declared-modules.js';
2
+ export async function resolveReactDeclaredModulesForEntrypoint(options, entrypointPath) {
3
+ const cached = options.pageMetadataCache.getDeclaredModules(entrypointPath);
4
+ if (cached) {
5
+ return cached;
6
+ }
7
+ const declaredModules = entrypointPath.endsWith('.mdx')
8
+ ? await collectPageDeclaredModules(entrypointPath)
9
+ : collectPageDeclaredModulesFromModule(await options.importNodePageModule(entrypointPath));
10
+ options.pageMetadataCache.setDeclaredModules(entrypointPath, declaredModules);
11
+ return declaredModules;
12
+ }
13
+ export function buildReactDevTransformPlugins(options, declaredModules, shouldEnableMdx) {
14
+ const plugins = options.getBuildPlugins(declaredModules);
15
+ if (shouldEnableMdx && options.getMdxLoaderPlugin) {
16
+ plugins.unshift(options.getMdxLoaderPlugin());
17
+ }
18
+ return plugins;
19
+ }
@@ -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
+ /**
3
+ * Test helper: assert generated hydration bootstrap source has no bare `@ecopages/*` imports.
4
+ */
5
+ export function assertNoBareEcopagesImports(source) {
6
+ expect(source).not.toMatch(/from\s+["']@ecopages\//);
7
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import type { ReactRuntimeImports } from '../bundling/runtime-bundle.js';
10
+ export type HydrationBootstrapImportPaths = {
11
+ reactImportPath: string;
12
+ reactDomClientImportPath: string;
13
+ routerImportPath?: string;
14
+ layoutComposeImportPath: string;
15
+ pageLayoutNormalizationImportPath: string;
16
+ };
17
+ export type ResolveHydrationBootstrapImportsOptions = {
18
+ useBrowserRuntimeImports: boolean;
19
+ runtimeImports: ReactRuntimeImports;
20
+ routerAdapterImportPath?: string;
21
+ };
22
+ /**
23
+ * Returns import paths for React page hydration scripts.
24
+ */
25
+ export declare function resolveHydrationBootstrapImports(options: ResolveHydrationBootstrapImportsOptions): HydrationBootstrapImportPaths;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Resolves browser import paths for React page hydration bootstraps.
3
+ *
4
+ * @remarks
5
+ * When `useBrowserRuntimeImports` is true, helpers and runtimes resolve to shared
6
+ * `/assets/vendors/*.js` URLs so unbundled HMR bootstraps evaluate as native ESM.
7
+ * When false, bare package names are emitted for the production page bundler.
8
+ */
9
+ import { LAYOUT_COMPOSE_PACKAGE, PAGE_LAYOUT_NORMALIZATION_PACKAGE } from '../bundling/bootstrap-package-paths.js';
10
+ /**
11
+ * Returns import paths for React page hydration scripts.
12
+ */
13
+ export function resolveHydrationBootstrapImports(options) {
14
+ const { useBrowserRuntimeImports, runtimeImports, routerAdapterImportPath } = options;
15
+ if (useBrowserRuntimeImports) {
16
+ return {
17
+ reactImportPath: runtimeImports.react,
18
+ reactDomClientImportPath: runtimeImports.reactDomClient,
19
+ ...(runtimeImports.router || routerAdapterImportPath
20
+ ? { routerImportPath: runtimeImports.router ?? routerAdapterImportPath }
21
+ : {}),
22
+ layoutComposeImportPath: runtimeImports.layoutCompose,
23
+ pageLayoutNormalizationImportPath: runtimeImports.pageLayoutNormalization,
24
+ };
25
+ }
26
+ return {
27
+ reactImportPath: 'react',
28
+ reactDomClientImportPath: 'react-dom/client',
29
+ ...(routerAdapterImportPath ? { routerImportPath: routerAdapterImportPath } : {}),
30
+ layoutComposeImportPath: LAYOUT_COMPOSE_PACKAGE,
31
+ pageLayoutNormalizationImportPath: PAGE_LAYOUT_NORMALIZATION_PACKAGE,
32
+ };
33
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Browser-side React Island Host lifecycle.
3
+ *
4
+ * @remarks
5
+ * This module intentionally receives React's browser runtime as a value. The
6
+ * server entry compiler can therefore keep the application's React and
7
+ * ReactDOM imports external while bundling this framework-owned lifecycle.
8
+ */
9
+ export type IslandComponent = (props: Record<string, unknown>) => unknown;
10
+ export type IslandReactRuntime = {
11
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
12
+ onRecoverableError?: (error: unknown) => void;
13
+ }) => IslandRoot;
14
+ createElement: (type: unknown, props: Record<string, unknown>) => unknown;
15
+ useEffect: (effect: () => void, dependencies: unknown[]) => void;
16
+ };
17
+ export type IslandRoot = {
18
+ render: (tree: unknown) => void;
19
+ unmount: () => void;
20
+ };
21
+ /** Shared browser state for all Island Host entries on one document. */
22
+ export type IslandHydrationRuntime = {
23
+ islandRoots: Record<string, IslandRoot>;
24
+ islandComponents: Record<string, IslandComponent>;
25
+ observer?: MutationObserver;
26
+ };
27
+ /** Configuration for one compiled React Island Host entry. */
28
+ export type IslandHydrationOptions = {
29
+ targetSelector: string;
30
+ componentModule: Record<string, unknown>;
31
+ componentRef?: string;
32
+ componentFile?: string;
33
+ scriptId: string;
34
+ runtime: IslandReactRuntime;
35
+ runtimeState: IslandHydrationRuntime;
36
+ };
37
+ /**
38
+ * Returns the shared page runtime used by all React Island Host entries.
39
+ *
40
+ * @remarks
41
+ * Keeping initialization here means generated entries only describe their
42
+ * component and selector; they do not duplicate global runtime setup.
43
+ *
44
+ * @returns The shared mutable state used by all island entries on this page.
45
+ */
46
+ export declare function getIslandHydrationRuntime(): IslandHydrationRuntime;
47
+ /**
48
+ * Registers the development HMR callback for one component module.
49
+ *
50
+ * @remarks
51
+ * The callback imports the replacement module and delegates to
52
+ * {@link updateIslands}, which updates every live host matching this entry.
53
+ * The dynamic import function is supplied by the generated entry so HMR keeps
54
+ * the browser's normal module-resolution behavior.
55
+ *
56
+ * @param options - Entry configuration whose hosts should receive updates.
57
+ * @param importModule - Browser dynamic-import function for the replacement module.
58
+ * @param importPath - HMR source URL used as the global handler key.
59
+ */
60
+ export declare function registerIslandHmr(options: IslandHydrationOptions, importModule: (url: string) => Promise<Record<string, unknown>>, importPath?: string): void;
61
+ /**
62
+ * Hydrates every eligible host for one component entry.
63
+ *
64
+ * @remarks
65
+ * Existing host records are skipped. This makes rerun scripts idempotent and
66
+ * avoids calling `render` while an initial `hydrateRoot` commit is
67
+ * still pending.
68
+ *
69
+ * @param options - Component, selector, React runtime, and shared state for the entry.
70
+ */
71
+ export declare function mountIslands(options: IslandHydrationOptions): void;
72
+ /**
73
+ * Applies a hot-reloaded component to every live host owned by this entry.
74
+ *
75
+ * @remarks
76
+ * Updates arriving before the initial commit are stored on each host and
77
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
78
+ *
79
+ * @param options - The live entry configuration and runtime state.
80
+ * @param newModule - Newly imported component module.
81
+ */
82
+ export declare function updateIslands(options: IslandHydrationOptions, newModule: Record<string, unknown>): void;
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Browser-side React Island Host lifecycle.
3
+ *
4
+ * @remarks
5
+ * This module intentionally receives React's browser runtime as a value. The
6
+ * server entry compiler can therefore keep the application's React and
7
+ * ReactDOM imports external while bundling this framework-owned lifecycle.
8
+ */
9
+ /**
10
+ * Returns the shared page runtime used by all React Island Host entries.
11
+ *
12
+ * @remarks
13
+ * Keeping initialization here means generated entries only describe their
14
+ * component and selector; they do not duplicate global runtime setup.
15
+ *
16
+ * @returns The shared mutable state used by all island entries on this page.
17
+ */
18
+ export function getIslandHydrationRuntime() {
19
+ const pageWindow = window;
20
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
21
+ pageRuntime.islandRoots ??= {};
22
+ pageRuntime.islandComponents ??= {};
23
+ pageRuntime.__ecoIslandRuntime ??= {
24
+ islandRoots: pageRuntime.islandRoots,
25
+ islandComponents: pageRuntime.islandComponents,
26
+ };
27
+ pageRuntime.__ecoIslandRuntime.islandRoots = pageRuntime.islandRoots;
28
+ pageRuntime.__ecoIslandRuntime.islandComponents = pageRuntime.islandComponents;
29
+ return pageRuntime.__ecoIslandRuntime;
30
+ }
31
+ /**
32
+ * Registers the development HMR callback for one component module.
33
+ *
34
+ * @remarks
35
+ * The callback imports the replacement module and delegates to
36
+ * {@link updateIslands}, which updates every live host matching this entry.
37
+ * The dynamic import function is supplied by the generated entry so HMR keeps
38
+ * the browser's normal module-resolution behavior.
39
+ *
40
+ * @param options - Entry configuration whose hosts should receive updates.
41
+ * @param importModule - Browser dynamic-import function for the replacement module.
42
+ * @param importPath - HMR source URL used as the global handler key.
43
+ */
44
+ export function registerIslandHmr(options, importModule, importPath) {
45
+ if (!importPath)
46
+ return;
47
+ const pageWindow = window;
48
+ const pageRuntime = (pageWindow.__ECO_PAGES__ ??= {});
49
+ pageRuntime.hmrHandlers ??= {};
50
+ pageRuntime.hmrHandlers[importPath] = async (url) => {
51
+ updateIslands(options, await importModule(url));
52
+ };
53
+ }
54
+ /**
55
+ * Selects the component exported by a browser entry for the current Island Host.
56
+ *
57
+ * @remarks
58
+ * Component identity is preferred when a file exports several components. The
59
+ * default export and then the first function remain compatibility fallbacks for
60
+ * entries without framework identity metadata.
61
+ */
62
+ function resolveComponent(module, componentRef, componentFile) {
63
+ const values = Object.values(module).filter((entry) => typeof entry === 'function');
64
+ if (componentRef) {
65
+ const matchById = values.find((entry) => entry.config?.identity?.id === componentRef);
66
+ if (matchById)
67
+ return matchById;
68
+ }
69
+ if (componentFile) {
70
+ const matchByFile = values.find((entry) => entry.config?.identity?.file === componentFile);
71
+ if (matchByFile)
72
+ return matchByFile;
73
+ }
74
+ if (typeof module.default === 'function')
75
+ return module.default;
76
+ return values[0] ?? null;
77
+ }
78
+ function getComponentId(target) {
79
+ return target.getAttribute('data-eco-component-id');
80
+ }
81
+ function getIslandIdentity(target) {
82
+ return getComponentId(target) ?? target.getAttribute('data-eco-component-key') ?? 'unknown';
83
+ }
84
+ /**
85
+ * Adds the initial-commit marker while keeping one stable React component type
86
+ * around the application component. A stable type lets HMR update props without
87
+ * remounting this lifecycle boundary on every render.
88
+ */
89
+ function IslandLifecycle({ target, runtime, Component, props }) {
90
+ runtime.useEffect(() => {
91
+ target.setAttribute('data-eco-hydrated', 'true');
92
+ const record = target.__eco_island;
93
+ if (!record)
94
+ return;
95
+ record.hydrated = true;
96
+ if (record.pendingComponent) {
97
+ const pendingComponent = record.pendingComponent;
98
+ record.pendingComponent = undefined;
99
+ record.root.render(runtime.createElement(IslandLifecycle, {
100
+ target,
101
+ runtime,
102
+ Component: pendingComponent,
103
+ props: readProps(target),
104
+ }));
105
+ }
106
+ }, [target, runtime]);
107
+ return runtime.createElement(Component, props);
108
+ }
109
+ /**
110
+ * Decodes the serialized props stamped on an Island Host by the server.
111
+ * Malformed or non-object payloads become an empty props object so a broken
112
+ * diagnostic attribute cannot prevent the rest of the page from hydrating.
113
+ *
114
+ * @remarks
115
+ * Decodes the format core's `encodeIslandProps` writes in `islands/island-host.ts` (base64 of UTF-8 JSON). It is
116
+ * inlined because this module compiles into a self-contained browser script that cannot import core.
117
+ */
118
+ function readProps(target) {
119
+ try {
120
+ const encoded = target.getAttribute('data-eco-props') ?? 'e30=';
121
+ const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0))));
122
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
123
+ ? parsed
124
+ : {};
125
+ }
126
+ catch {
127
+ return {};
128
+ }
129
+ }
130
+ /**
131
+ * Unmounts a disconnected island and removes only its matching registry entry.
132
+ *
133
+ * @remarks
134
+ * Connectivity is checked by the observer callback, after the mutation batch,
135
+ * so moving a host within the document does not release its React root.
136
+ */
137
+ function releaseIsland(target, runtimeState) {
138
+ if (target.isConnected)
139
+ return;
140
+ const record = target.__eco_island;
141
+ if (!record)
142
+ return;
143
+ record.root.unmount();
144
+ const componentId = getComponentId(target);
145
+ if (componentId && runtimeState.islandRoots[componentId] === record.root) {
146
+ delete runtimeState.islandRoots[componentId];
147
+ }
148
+ delete target.__eco_island;
149
+ }
150
+ /**
151
+ * Installs the one document observer shared by all island entries on the page.
152
+ * The observer releases roots for removed hosts and their descendants.
153
+ */
154
+ function ensureObserver(runtimeState) {
155
+ if (runtimeState.observer || !document.documentElement)
156
+ return;
157
+ runtimeState.observer = new MutationObserver((mutations) => {
158
+ for (const mutation of mutations) {
159
+ for (const node of mutation.removedNodes) {
160
+ if (!(node instanceof HTMLElement))
161
+ continue;
162
+ releaseIsland(node, runtimeState);
163
+ for (const target of node.querySelectorAll('[data-eco-island]'))
164
+ releaseIsland(target, runtimeState);
165
+ }
166
+ }
167
+ });
168
+ runtimeState.observer.observe(document.documentElement, { childList: true, subtree: true });
169
+ }
170
+ /**
171
+ * Hydrates one server-emitted Island Host in place and records its lifecycle.
172
+ *
173
+ * @remarks
174
+ * The record is attached immediately after `hydrateRoot` returns so
175
+ * duplicate startup and HMR can see the host before React's initial effect runs.
176
+ */
177
+ function hydrateTarget(target, component, runtime, runtimeState) {
178
+ const root = runtime.hydrateRoot(target, runtime.createElement(IslandLifecycle, { target, runtime, Component: component, props: readProps(target) }), {
179
+ onRecoverableError: (error) => console.warn('[ecopages] Island hydration error', getIslandIdentity(target), error),
180
+ });
181
+ const record = { root, hydrated: false, component };
182
+ target.__eco_island = record;
183
+ const componentId = getComponentId(target);
184
+ if (componentId)
185
+ runtimeState.islandRoots[componentId] = record.root;
186
+ }
187
+ /**
188
+ * Hydrates every eligible host for one component entry.
189
+ *
190
+ * @remarks
191
+ * Existing host records are skipped. This makes rerun scripts idempotent and
192
+ * avoids calling `render` while an initial `hydrateRoot` commit is
193
+ * still pending.
194
+ *
195
+ * @param options - Component, selector, React runtime, and shared state for the entry.
196
+ */
197
+ export function mountIslands(options) {
198
+ const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '', options.componentFile ?? '');
199
+ ensureObserver(options.runtimeState);
200
+ const pageRuntime = (window.__ECO_PAGES__ ??= {});
201
+ pageRuntime.rerunScripts ??= {};
202
+ pageRuntime.rerunScripts[options.scriptId] = () => mountIslands(options);
203
+ const scriptId = options.scriptId;
204
+ const component = options.runtimeState.islandComponents[scriptId] ?? resolvedComponent;
205
+ if (!component)
206
+ return;
207
+ options.runtimeState.islandComponents[scriptId] = component;
208
+ for (const element of document.querySelectorAll(options.targetSelector)) {
209
+ const target = element;
210
+ if (target.__eco_island?.root)
211
+ continue;
212
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
213
+ }
214
+ }
215
+ /**
216
+ * Applies a hot-reloaded component to every live host owned by this entry.
217
+ *
218
+ * @remarks
219
+ * Updates arriving before the initial commit are stored on each host and
220
+ * rendered by {@link IslandLifecycle} after it marks that host hydrated.
221
+ *
222
+ * @param options - The live entry configuration and runtime state.
223
+ * @param newModule - Newly imported component module.
224
+ */
225
+ export function updateIslands(options, newModule) {
226
+ const component = resolveComponent(newModule, options.componentRef ?? '', options.componentFile ?? '');
227
+ if (!component)
228
+ return;
229
+ options.componentModule = newModule;
230
+ const scriptId = options.scriptId;
231
+ options.runtimeState.islandComponents[scriptId] = component;
232
+ for (const element of document.querySelectorAll(options.targetSelector)) {
233
+ const target = element;
234
+ const record = target.__eco_island;
235
+ if (!record) {
236
+ hydrateTarget(target, component, options.runtime, options.runtimeState);
237
+ continue;
238
+ }
239
+ record.component = component;
240
+ if (!record.hydrated) {
241
+ record.pendingComponent = component;
242
+ continue;
243
+ }
244
+ record.root.render(options.runtime.createElement(IslandLifecycle, {
245
+ target,
246
+ runtime: options.runtime,
247
+ Component: component,
248
+ props: readProps(target),
249
+ }));
250
+ }
251
+ }
@@ -0,0 +1,11 @@
1
+ import type { PageHydrationOptions } from './page-hydration.js';
2
+ /**
3
+ * Imports and applies one HMR page update.
4
+ */
5
+ export declare function handlePageHmr(options: PageHydrationOptions, newUrl: string, generation: number, readPageData: (options: PageHydrationOptions) => {
6
+ moduleUrl?: string;
7
+ props: Record<string, unknown>;
8
+ }, setPageState: (options: PageHydrationOptions, pageData: {
9
+ moduleUrl?: string;
10
+ props: Record<string, unknown>;
11
+ }) => void, getPageDataFromDocument: (options: PageHydrationOptions) => Record<string, unknown>): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { resolvePageModule } from './page-hydration-module.js';
2
+ function getRuntime() {
3
+ return (window.__ECO_PAGES__ ??= {});
4
+ }
5
+ function isCurrentMountGeneration(generation) {
6
+ return (getRuntime().react?.mountGeneration ?? 0) === generation;
7
+ }
8
+ async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, _nextProps) {
9
+ if (!options.hasRouter || getRuntime().navigation?.getOwnerState?.().owner !== 'react-router') {
10
+ return false;
11
+ }
12
+ const currentLayoutStack = options.hmr.getLayoutStack?.(currentPage) ?? '';
13
+ const nextLayoutStack = options.hmr.getLayoutStack?.(nextPage.Page) ?? '';
14
+ await getRuntime().navigation?.reloadCurrentPage?.({
15
+ clearCache: currentLayoutStack !== nextLayoutStack,
16
+ moduleUrl: newUrl,
17
+ source: 'react-router',
18
+ });
19
+ console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated via router`);
20
+ return true;
21
+ }
22
+ function applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation) {
23
+ const activeRoot = getRuntime().react?.pageRoot ?? null;
24
+ if (!activeRoot || !isCurrentMountGeneration(generation))
25
+ return;
26
+ setPageState(options, readPageData(options));
27
+ activeRoot.render(options.createTree(nextPage.Page, nextProps));
28
+ console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
29
+ }
30
+ /**
31
+ * Imports and applies one HMR page update.
32
+ */
33
+ export async function handlePageHmr(options, newUrl, generation, readPageData, setPageState, getPageDataFromDocument) {
34
+ if (!options.hmr || !isCurrentMountGeneration(generation))
35
+ return;
36
+ try {
37
+ const newModule = (await import(/* @vite-ignore */ newUrl));
38
+ if (!isCurrentMountGeneration(generation))
39
+ return;
40
+ const nextPage = resolvePageModule(newModule, options.isMdx, options.normalizePageConfig);
41
+ const nextProps = getPageDataFromDocument(options);
42
+ await nextPage.preload?.(nextProps);
43
+ if (!isCurrentMountGeneration(generation))
44
+ return;
45
+ const currentPage = options.Page;
46
+ options.Page = nextPage.Page;
47
+ options.preload = nextPage.preload;
48
+ if (await applyRouterHmrUpdate(options, newUrl, currentPage, nextPage, nextProps)) {
49
+ return;
50
+ }
51
+ applyDirectHmrRender(options, nextPage, nextProps, readPageData, setPageState, generation);
52
+ }
53
+ catch (error) {
54
+ console.error(`[ecopages] Failed to hot-reload ${options.isMdx ? 'MDX' : 'React'} component:`, error);
55
+ }
56
+ }
@@ -0,0 +1,8 @@
1
+ export type PageModule = {
2
+ Page: unknown;
3
+ preload?: (props: Record<string, unknown>) => void | Promise<void>;
4
+ };
5
+ /**
6
+ * Normalizes a loaded Page module into the shape used by hydration and HMR.
7
+ */
8
+ export declare function resolvePageModule(module: Record<string, unknown>, isMdx: boolean, normalizePageConfig?: (config: unknown) => void): PageModule;
@@ -0,0 +1,17 @@
1
+ function isPagePreload(value) {
2
+ return typeof value === 'function';
3
+ }
4
+ /**
5
+ * Normalizes a loaded Page module into the shape used by hydration and HMR.
6
+ */
7
+ export function resolvePageModule(module, isMdx, normalizePageConfig) {
8
+ const Page = module.default ?? module;
9
+ if (isMdx && module.config && Page && typeof Page === 'function') {
10
+ Object.assign(Page, { config: module.config });
11
+ normalizePageConfig?.(module.config);
12
+ }
13
+ return {
14
+ Page,
15
+ preload: isPagePreload(module.preload) ? module.preload : undefined,
16
+ };
17
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Browser-side React page lifecycle.
3
+ *
4
+ * @remarks
5
+ * The entry module supplies the page tree and module resolution details. This
6
+ * module owns document state, navigation ownership, cleanup, and HMR so those
7
+ * behaviors stay identical for readable and compiled bootstraps.
8
+ */
9
+ export type PageRoot = {
10
+ render: (tree: unknown) => void;
11
+ unmount: () => void;
12
+ };
13
+ export type PageReactRuntime = {
14
+ hydrateRoot: (target: HTMLElement, tree: unknown, options?: {
15
+ onRecoverableError?: (error: unknown) => void;
16
+ }) => PageRoot;
17
+ createElement: (...args: unknown[]) => unknown;
18
+ };
19
+ export type PageData = {
20
+ moduleUrl?: string;
21
+ props: Record<string, unknown>;
22
+ };
23
+ export type { PageModule } from './page-hydration-module.js';
24
+ export { resolvePageModule } from './page-hydration-module.js';
25
+ /** Configuration passed from a generated Page hydration entry. */
26
+ export type PageHydrationOptions = {
27
+ scriptId: string;
28
+ pageModuleUrl: string;
29
+ Page: unknown;
30
+ pageDataReader: {
31
+ readPageDataDocument: () => PageData;
32
+ getPageDataFromDocument: () => Record<string, unknown>;
33
+ };
34
+ runtime: PageReactRuntime;
35
+ createTree: (Page: unknown, props: Record<string, unknown>) => unknown;
36
+ hasRouter: boolean;
37
+ isMdx: boolean;
38
+ normalizePageConfig?: (config: unknown) => void;
39
+ hmr?: {
40
+ importPath: string;
41
+ getLayoutStack?: (Page: unknown) => string;
42
+ };
43
+ preload?: (props: Record<string, unknown>) => void | Promise<void>;
44
+ };
45
+ /**
46
+ * Registers and starts the Page lifecycle when its persistent script is present.
47
+ *
48
+ * @remarks
49
+ * Restores lifecycle registration, router ownership, and HMR generation binding
50
+ * whenever the page is activated or rerun after navigation.
51
+ *
52
+ * @param options - Generated entry configuration for the current Page.
53
+ */
54
+ export declare function startPageHydration(options: PageHydrationOptions): void;