@ecopages/react 0.6.1 → 0.7.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 (95) hide show
  1. package/README.md +50 -87
  2. package/package.json +32 -14
  3. package/src/bundling/bootstrap-package-paths.d.ts +13 -1
  4. package/src/bundling/bootstrap-package-paths.js +25 -3
  5. package/src/bundling/bundle.d.ts +8 -36
  6. package/src/bundling/bundle.js +42 -73
  7. package/src/client-graph/ast-transform-eco-page.d.ts +10 -6
  8. package/src/client-graph/ast-transform-eco-page.js +56 -35
  9. package/src/client-graph/ast-transform-import-edits.d.ts +10 -2
  10. package/src/client-graph/ast-transform-import-edits.js +36 -6
  11. package/src/client-graph/ast-transform-stripped-imports.d.ts +37 -0
  12. package/src/client-graph/ast-transform-stripped-imports.js +191 -0
  13. package/src/client-graph/ast-transform-walk-imports.d.ts +4 -0
  14. package/src/client-graph/ast-transform-walk-imports.js +15 -1
  15. package/src/client-graph/ast-transform.d.ts +12 -3
  16. package/src/client-graph/ast-transform.js +41 -56
  17. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +3 -0
  18. package/src/client-graph/boundary-plugin-read-file-inline.js +14 -10
  19. package/src/client-graph/boundary-plugin-transform.d.ts +5 -4
  20. package/src/client-graph/boundary-plugin-transform.js +6 -13
  21. package/src/client-graph/boundary-plugin.d.ts +47 -1
  22. package/src/client-graph/boundary-plugin.js +267 -53
  23. package/src/client-graph/foreign-boundary-rewrite.d.ts +31 -0
  24. package/src/client-graph/foreign-boundary-rewrite.js +360 -0
  25. package/src/client-graph/foreign-jsx-reach.d.ts +25 -0
  26. package/src/client-graph/foreign-jsx-reach.js +68 -0
  27. package/src/client-graph/module-classification.js +3 -10
  28. package/src/client-graph/reachability-traverse.js +35 -105
  29. package/src/client-graph/requested-exports-plan.d.ts +62 -0
  30. package/src/client-graph/requested-exports-plan.js +125 -0
  31. package/src/client-graph/scope-walk.d.ts +37 -0
  32. package/src/client-graph/scope-walk.js +407 -0
  33. package/src/client-graph/specifier-classification.d.ts +2 -1
  34. package/src/client-graph/specifier-classification.js +9 -7
  35. package/src/contracts/router-adapter.d.ts +9 -24
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +4 -4
  37. package/src/dev-transform/react-dev-transform-contributor.js +6 -7
  38. package/src/hmr/hmr-strategy-process.d.ts +7 -5
  39. package/src/hmr/hmr-strategy-process.js +21 -16
  40. package/src/hmr/hmr-strategy.d.ts +11 -10
  41. package/src/hmr/hmr-strategy.js +32 -53
  42. package/src/hmr/page-metadata-cache.js +1 -1
  43. package/src/hydration/browser/foreign-boundary.d.ts +29 -0
  44. package/src/hydration/browser/foreign-boundary.js +128 -0
  45. package/src/hydration/browser/island-hydration.d.ts +3 -4
  46. package/src/hydration/browser/island-hydration.js +3 -4
  47. package/src/hydration/browser/page-hydration-hmr.d.ts +8 -7
  48. package/src/hydration/browser/page-hydration-hmr.js +53 -10
  49. package/src/hydration/browser/page-hydration.d.ts +6 -5
  50. package/src/hydration/browser/page-hydration.js +8 -6
  51. package/src/hydration/foreign-subtree.d.ts +27 -0
  52. package/src/hydration/foreign-subtree.js +69 -0
  53. package/src/hydration/hydration-asset.d.ts +37 -29
  54. package/src/hydration/hydration-asset.js +74 -138
  55. package/src/hydration/hydration-island-entry-source.d.ts +17 -0
  56. package/src/hydration/hydration-island-entry-source.js +32 -0
  57. package/src/hydration/hydration-page-entry-source.d.ts +20 -2
  58. package/src/hydration/hydration-page-entry-source.js +17 -12
  59. package/src/hydration/page-data-reader.d.ts +4 -7
  60. package/src/hydration/page-data-reader.js +5 -10
  61. package/src/mdx/mdx-config-dependency.d.ts +10 -15
  62. package/src/mdx/mdx-config-dependency.js +9 -22
  63. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  64. package/src/mdx/mdx-loader-plugin.js +1 -0
  65. package/src/page/page-module.js +1 -1
  66. package/src/plugin/react.plugin.d.ts +0 -7
  67. package/src/plugin/react.plugin.js +4 -33
  68. package/src/plugin/react.types.d.ts +0 -29
  69. package/src/render/component-ssr.d.ts +18 -0
  70. package/src/render/component-ssr.js +37 -0
  71. package/src/render/layout-compose.d.ts +4 -2
  72. package/src/render/layout-compose.js +13 -6
  73. package/src/render/layout-render-tracker.d.ts +20 -0
  74. package/src/render/layout-render-tracker.js +33 -0
  75. package/src/render/react-renderer.d.ts +28 -10
  76. package/src/render/react-renderer.js +103 -38
  77. package/src/render/react-runtime.js +2 -2
  78. package/src/bundling/runtime-alias-map.d.ts +0 -12
  79. package/src/bundling/runtime-alias-map.js +0 -110
  80. package/src/bundling/runtime-bundle.d.ts +0 -70
  81. package/src/bundling/runtime-bundle.js +0 -233
  82. package/src/bundling/runtime-interop-plugin.d.ts +0 -5
  83. package/src/bundling/runtime-interop-plugin.js +0 -32
  84. package/src/bundling/runtime-mode.d.ts +0 -1
  85. package/src/bundling/runtime-mode.js +0 -10
  86. package/src/bundling/runtime-modules.d.ts +0 -21
  87. package/src/bundling/runtime-modules.js +0 -28
  88. package/src/hydration/bootstrap-imports.d.ts +0 -25
  89. package/src/hydration/bootstrap-imports.js +0 -33
  90. package/src/hydration/compiled-page-hydration-options.d.ts +0 -19
  91. package/src/hydration/compiled-page-hydration-options.js +0 -1
  92. package/src/hydration/hydration-script-compiler.d.ts +0 -47
  93. package/src/hydration/hydration-script-compiler.js +0 -213
  94. package/src/runtime/use-sync-external-store-with-selector.d.ts +0 -3
  95. package/src/runtime/use-sync-external-store-with-selector.js +0 -54
package/README.md CHANGED
@@ -26,9 +26,10 @@ For component-level islands, Ecopages React uses this contract:
26
26
 
27
27
  - SSR output preserves the authored DOM structure (no unnecessary wrapper elements).
28
28
  - A stable island host contract is stamped on the component SSR root via core (`data-eco-island`, `data-eco-island-integration`, `data-eco-component-id`, optional `data-eco-component-key` / `data-eco-props`).
29
- - During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to compatible app-wide browser build groups. Hydration scripts import the recorded output URLs. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. Those scripts join the page's assets during route preparation; SSR only stamps the host and never starts a per-island build.
29
+ - During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to the app-wide browser build. React's client build plugins decide by the module itself, not by the entry that reached it, because a module has one URL and so one compiled form: the MDX loader matches its file extensions. The client-graph boundary leaves other Integrations' entry files alone and also processes every other source module of the shared build, so it strips server-only imports from them too. The foreign-JSX override gives React's JSX runtime to a file another JSX Integration owns only when a static import scan from React's island and Page files, run before the build loads any module, reaches it; a foreign file only another Integration's entries reach keeps its owner's runtime, and one that both reach fails the build with the file and both Integrations named. React and other Integrations therefore share one build, and a Layout or package that MDX Pages, TSX Pages and other Integrations' scripts share loads once across client navigation. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. Those scripts join the page's assets during route preparation; SSR only stamps the host and never starts a per-island build.
30
30
  - Each island component gets its own hydration script, keyed by its component identity. A file that exports several island components is built once and its declared modules are merged, while each component's hosts hydrate the export whose identity matches.
31
31
  - The island runtime keeps the SSR host and its children in place and hydrates that host with `hydrateRoot()`. The host uses `display: contents` so it does not introduce an extra layout box. Full-page hydration paths also use `hydrateRoot()`.
32
+ - Hydration scripts are short generated entries that import the lifecycle from `@ecopages/react/island-hydration` or `@ecopages/react/page-hydration`, and React itself, by package name. Outside HMR every island and Page entry, with or without a router, is an entry of one grouped browser build (the app-wide build in production), so React, the bootstrap and the router are content-hashed chunks the entries share and a page loads React once. With HMR the entries stay unbundled and core rewrites their imports to dev-transform and vendor URLs. No server process compiles a bootstrap, so `ecopages start` serves islands from the bundled server.
32
33
 
33
34
  > [!TIP]
34
35
  > **Full React SPA Routing:**
@@ -85,7 +86,7 @@ The React integration supports Node.js modules and server-only code **only on th
85
86
 
86
87
  Keep server helpers close, but separate them physically or logically so they do not leak into the client bundle.
87
88
 
88
- The `.server` naming rule comes from the browser-safe `@ecopages/core/build/contracts` entry. React applies it during import pruning before core's browser resolution guard runs. A Page that uses `.server.ts` imports only in server options such as `middleware` still builds: the imports and server options are removed before resolution.
89
+ The `.server` naming rule comes from the browser-safe `@ecopages/core/build/contracts` entry. React applies it during import pruning before core's browser resolution guard runs. A Page that uses `.server.ts` imports only in server options such as `middleware`, or in helpers only those options use, still builds: the imports, the options and those helpers are removed before resolution, in every module of the client graph. Other top-level code the browser does not need that uses a stripped import is removed too. A stripped import that code the browser needs still uses fails the build and names the binding, its specifier and its `file:line:column`; see [AST Pipeline Order](#ast-pipeline-order).
89
90
 
90
91
  For a hydratable Page that renders collection MDX, call `createLazyCollectionComponents()` from `@ecopages/react/lazy-collection-components` once at module level with the collection's `/component` loader. Its `get(slug)` returns one `React.lazy` component per slug, so the Page reads `const Content = posts.get(entry.slug)` and renders `<Content />` inside a `<Suspense>` boundary. The server waits for the entry and sends it in the HTML, hydration keeps that HTML until the browser has loaded the entry, and `dependencies` stays server-only and is removed from the Page Browser Graph. Keep the boundary at a fixed place in the Page, not keyed by slug: when a client navigation moves to another entry, React then leaves the current Page on screen until the next entry has loaded instead of showing the fallback. When the browser cannot load an entry during a client navigation (a replaced chunk, a dropped connection), `@ecopages/react-router` falls back to a full navigation to that URL. The helper keeps one lookup per collection outside the Page module. In development, HMR of the Page module therefore renders the already-loaded entry again without the Suspense fallback; the Page's own DOM is still replaced, because the reloaded Page is a new component. An edited MDX file re-renders that entry in place without a document reload. On the server, a reloaded server module graph starts a new lookup.
91
92
 
@@ -113,7 +114,7 @@ Think about each React page as two related graphs:
113
114
 
114
115
  The React integration builds the client graph conservatively. If a server-only module becomes reachable from the hydrated render path, the build should fail rather than silently shipping unsafe code.
115
116
 
116
- The client-graph boundary analyzes project modules during each browser build and HMR rebuild; transform results and requested-export changes are not cached or replayed across builds. In grouped island builds, each entry file uses its own declared modules, while helper modules use the group's merged declarations because the build has one module instance for each helper. Set `ECO_AST_PROFILE=1` to emit one structured timing record per client-graph analysis while investigating a development rebuild.
117
+ The client-graph boundary analyzes project modules during each browser build and HMR rebuild; transform results and requested exports are not cached or replayed across builds. Before it transforms a module that is not an entry, it follows, from the build's entries, the imports each module's browser code reaches once server-only Page options are set aside (resolved by the build itself, so a workspace package imported by name is followed; installed packages are not), and works out which exports each module's importers use, so a shared helper is pruned the same way whichever importer Rolldown loads first; an entry keeps all of its exports. Each module is read and parsed once for both. One build registers one boundary handler however many React entries it has, and installed packages never reach it. A file the boundary inlines through `fs.readFileSync(path.resolve(...), 'utf8')` becomes a dependency of the module, so editing it rebuilds that module in development. In grouped island builds, each entry file uses its own declared modules, while helper modules use the group's merged declarations because the build has one module instance for each helper. Set `ECO_AST_PROFILE=1` to emit one structured timing record per client-graph analysis while investigating a development rebuild.
117
118
 
118
119
  ### `explicitGraph` option
119
120
 
@@ -145,15 +146,21 @@ Important:
145
146
 
146
147
  ### AST Pipeline Order
147
148
 
148
- The browser-bound transform in [src/client-graph/boundary-plugin.ts](src/client-graph/boundary-plugin.ts) follows this order:
149
+ The browser-bound transform in [src/client-graph/boundary-plugin.ts](src/client-graph/boundary-plugin.ts) runs on every module of the client graph, not only on Page and Layout entries, and plans all of its edits on one parse of the module:
149
150
 
150
- 1. Parse the module and build a reachability view of the client render graph.
151
- 2. Remove imports that are not allowed or not reachable from the client graph.
152
- 3. Reparse the transformed source.
153
- 4. Strip server-only `eco.page(...)` object properties from the reparsed AST.
154
- 5. Return the rewritten source to the bundle step.
151
+ 1. Build a reachability view of the client render graph.
152
+ 2. Remove imports that are not allowed: Node built-ins, `.server` modules, `ecopages:content/*/server` modules and named imports outside the declared `pkg{name}` rules. An import reachable from a client root fails the build instead.
153
+ 3. Remove server-only `eco.page(...)` options.
154
+ 4. Work out which top-level code the browser module needs: every top-level statement that is not a declaration (the default export included), declarations that create a client root such as `eco.component(...)`, the named exports browser importers are known to request, and every declaration those reach.
155
+ 5. Remove each declaration the browser module does not need when only removed code used it, or when it uses a removed import or another removed declaration, repeating until nothing else changes. An exported name keeps its binding, set to `undefined`. Imports only removed code used are removed too, so their modules stay out of the browser graph.
156
+ 6. Fail the build when needed code, or an `export { ... }` list, still uses a binding whose import step 2 removed.
157
+ 7. Apply the edits and return the rewritten source to the bundle step.
155
158
 
156
- The reparse step is important. Once import edits change source offsets, the original AST locations are stale. Reusing them for later edits can corrupt the output or remove the wrong code.
159
+ A named export nothing requests is not needed, because rolldown would tree-shake it anyway, and requests are unknown for imports through a path alias such as `@/utils/mixed-utils`. So a helper module can keep `export function dbSecretQuery() { return readFileSync(...) }` next to the `formatDate` a Page renders: in the browser, `dbSecretQuery` is `undefined` and `node:fs` is gone.
160
+
161
+ Step 5 does not look at side effects. A declaration such as `const registered = register('x')` that only server-only options use is removed with its call. Code that must run in the browser for its effect, such as `customElements.define(...)`, belongs in a top-level statement of its own, which always stays.
162
+
163
+ The analysis is scope-aware ([src/client-graph/scope-walk.ts](src/client-graph/scope-walk.ts)). A parameter, local or destructured binding that shadows an import name is not a use of the import, and neither is a property key or a class member name. A parameter default sees the parameters but not the function body's declarations. Type positions and the bare operand of `typeof` are not uses. The operand of `as`, `satisfies` and `!` is a use, as is code in enums and namespaces. A JSX element name such as `<Secret />` is a use.
157
164
 
158
165
  ### Why `eco.page(...)` Options Are Stripped
159
166
 
@@ -163,18 +170,28 @@ Consider a page like this:
163
170
 
164
171
  ```tsx
165
172
  import { authMiddleware } from './auth.server';
173
+ import { getPost } from './posts.server';
174
+
175
+ const staticProps = async () => ({ props: { post: await getPost() } });
166
176
 
167
177
  export default eco.page({
168
178
  cache: 'dynamic',
169
179
  middleware: [authMiddleware],
170
180
  requires: ['session'] as const,
181
+ staticProps,
171
182
  render: () => <div>Dashboard</div>,
172
183
  });
173
184
  ```
174
185
 
175
- If the client transform removes the `auth.server` import but leaves `middleware: [authMiddleware]` in place, the browser bundle still contains a dangling identifier. That breaks production hydration even though the import was removed correctly.
186
+ If the client transform removed the `auth.server` import but left `middleware: [authMiddleware]` in place, the browser bundle would contain a dangling identifier and throw a `ReferenceError` when it loads. The boundary therefore strips the server-only options, then the `staticProps` helper they alone used, while keeping `render` intact.
187
+
188
+ A stripped import still used by code the browser module needs fails the build with its `file:line:column`:
189
+
190
+ ```text
191
+ [Ecopages Client Graph] 'authMiddleware' (imported from './auth.server') is used at src/widget.tsx:2:22, but that import is server-only and the browser build removes it. ...
192
+ ```
176
193
 
177
- The fix is to strip server-only `eco.page(...)` options after import pruning, while keeping `render` intact.
194
+ Move that code into a server-only Page option, into a helper only those options use, or out of the code the browser module reaches.
178
195
 
179
196
  ### Hydration Contract for `locals`
180
197
 
@@ -216,7 +233,8 @@ The main regression coverage lives in:
216
233
 
217
234
  - [src/client-graph/boundary-plugin.test.ts](src/client-graph/boundary-plugin.test.ts): verifies server-only `eco.page(...)` options are stripped from browser bundles.
218
235
  - [src/render/react-renderer.locals.test.ts](src/render/react-renderer.locals.test.ts): verifies only declared `requires` keys are serialized into hydration payloads.
219
- - [src/hydration/hydration-script-compiler.test.ts](src/hydration/hydration-script-compiler.test.ts): verifies editable browser sources compile to readable and minified entries.
236
+ - [src/hydration/hydration-entry-source.test.ts](src/hydration/hydration-entry-source.test.ts): a generated island entry registers, and a generated Page entry hydrates, through the bootstrap module it imports.
237
+ - [../../../e2e/fixtures/react-production-start/react-production-start.test.e2e.ts](../../../e2e/fixtures/react-production-start/react-production-start.test.e2e.ts): a built app serves a static and a dynamic Page under `ecopages start`, and their React island hydrates.
220
238
  - [../../react-router/test/layout-persistence.test.browser.ts](../../react-router/test/layout-persistence.test.browser.ts): verifies router-backed layout hydration receives `locals` with `persistLayouts` both enabled and disabled.
221
239
  - [src/hydration/hydration-lifecycle.test.browser.ts](src/hydration/hydration-lifecycle.test.browser.ts): an uncaught `React.lazy` rejection during first hydration restores the server HTML, keeps body nodes added after mount, drops the page root and makes the next HMR update reload; a Page-level error boundary around the entry still shows its fallback.
222
240
  - [../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts](../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts): a collection chunk that fails during first hydration restores the server HTML (including the playground shell) and is not retried. A Page-level error boundary around the entry keeps the rest of the Page and shows the boundary fallback.
@@ -228,7 +246,9 @@ If you change the AST transform or hydration flow, update the corresponding test
228
246
 
229
247
  ### Nested layouts and unified SSR
230
248
 
231
- Pages may declare `layout` as a single component or an **outer → inner** array on `eco.page()`. On the server, React-managed layout stacks compose through `composeDocumentShell` + `composeLayoutPageTree` so provider context reaches nested pages during SSR. On the client, `@ecopages/react-router` `PageContent` uses the same `composeLayoutPageTree` helper unless `persistLayouts` is enabled (then each tier is cached independently).
249
+ Pages may declare `layout` as a single component or an **outer → inner** array on `eco.page()`. On the server, React-managed layout stacks compose through `composeDocumentShell` + `composeLayoutPageTree` so provider context reaches nested pages during SSR. On the client, `@ecopages/react-router` `PageContent` uses the same `composeLayoutPageTree` helper; a tier stays mounted while consecutive pages pass the same layout function.
250
+
251
+ A server render tracks which tiers and the page it reached (`LayoutRenderTracker`): a layout that renders without its page is reported through the renderer's render-mode handler (`Layout <name> (<file>) did not render its children`), which throws for static build output, warns in development and stays silent in production. Each tier is wrapped in a function that calls it directly, so the tree keeps its depth and `useId` values match the browser's.
232
252
 
233
253
  During SSR, `ReactRenderer` passes the app-resolved React runtime into `composeLayoutPageTree` via `options.react` so layout trees are built with the same module instance the server renders them with. App code should import hooks and context from `react` normally; keep a single React version in the app dependency graph (avoid duplicate `react` copies in monorepos).
234
254
 
@@ -238,94 +258,37 @@ Layout prop factories receive `LayoutPropsContext` (`params`, `query`, `locals`)
238
258
  - [src/test/react-ssr-hydration-parity.test.tsx](src/test/react-ssr-hydration-parity.test.tsx): nested tier order parity between SSR and `composeLayoutPageTree`.
239
259
  - [src/test/react-ssr-unified.test.tsx](src/test/react-ssr-unified.test.tsx): provider context through nested SSR layouts.
240
260
 
241
- ### Shared runtime vendors (SPA + persisted layouts)
261
+ ### Shared browser modules (SPA + persisted layouts)
242
262
 
243
263
  With `ecoRouter()`, Ecopages keeps outer layout tiers mounted across client navigation (`persistLayouts` defaults to `true`). Each Page chunk still loads separately, while its Layout tiers can stay alive in the DOM.
244
264
 
245
- A package imported by both a persisted Layout and multiple Page chunks must resolve to one browser module instance. Otherwise, a library with module-level state such as React context can be duplicated, and navigation can fail with errors such as `No QueryClient set`.
246
-
247
- Register shared packages explicitly with `reactPlugin({ runtimeModules })`. Each listed package is built once into `/assets/vendors/*.js`, and browser graphs import that vendor URL. React, React DOM, and the configured router are already shared. Layout files do not add packages to `runtimeModules` automatically.
248
-
249
- In `ecopages dev`, page modules are served from `/assets/__eco_dev__/` and should import `/assets/vendors/*` for shared packages instead of inlining `node_modules`. Kitchen-sink routes `/vendor-share/a` and `/vendor-share/b` (with `runtimeModules: ['zod']`) are the reference fixture; see `playground/kitchen-sink/e2e/shared-vendors.test.e2e.ts`.
250
-
251
- #### Register shared packages
252
-
253
- List the package specifier that Page or Layout code imports:
254
-
255
- ```ts
256
- import { defineConfig } from '@ecopages/core/config';
257
- import { reactPlugin } from '@ecopages/react';
258
- import { ecoRouter } from '@ecopages/react-router';
259
-
260
- export default defineConfig({
261
- integrations: [
262
- reactPlugin({
263
- router: ecoRouter(),
264
- runtimeModules: ['@tanstack/react-query'],
265
- }),
266
- ],
267
- });
268
- ```
269
-
270
- Use the package root when all imports use that root. Import rewrites match exact specifiers, so add a separate entry for each package subpath used by app code.
265
+ A package imported by both a persisted Layout and several Pages must be one browser module instance. Otherwise a library with module-level state, such as a React context, MobX store or TanStack Query client, is duplicated and navigation fails with errors such as `No QueryClient set`. Ecopages guarantees one instance without configuration:
271
266
 
272
- **Migration from layout discovery:** remove `runtimeProvider` from layout options. Add each shared package the scanner previously supplied to `runtimeModules` using the exact specifier imported by app code.
273
-
274
- `runtimeModules` also accepts objects with a custom vendor output name:
275
-
276
- ```ts
277
- reactPlugin({
278
- router: ecoRouter(),
279
- runtimeModules: ['@tanstack/react-query', { specifier: '@acme/ui', outputName: 'acme-ui' }],
280
- });
281
- ```
267
+ - Production builds every browser entry of the app in one build with code splitting, so a package that several Pages, Layouts or islands import is one chunk with one URL. See the build README for the options that still separate entries.
268
+ - `ecopages dev` serves Page modules from `/assets/__eco_dev__/` and every bare import from a vendor URL under `/assets/vendors/`, one per resolved package entry, so every importer shares it.
282
269
 
283
- Each vendor entry is built from the package's browser ESM surface: Ecopages follows an `exports` import target when present and otherwise prefers a package's legacy `module` field over CJS `main`. ESM files are re-exported with `export *`. CJS files (including React's published `index.js` / `jsx-runtime`) emit explicit named exports from that same file so the vendor can provide `jsx`.
270
+ React, React DOM, `layout-compose`, the bootstraps and the configured router are ordinary packages. Production bundles them into the app-wide build's content-hashed chunks, served `immutable`, with Rolldown's CommonJS interop giving importers React's named exports. `ecopages dev` serves each from its one vendor URL; React's entries are CommonJS, so the dev transform reads named imports of them from the default export (`import { useState } from 'react'` becomes a default import plus a destructuring). Both builds define `process.env.NODE_ENV`, so React picks its development or production build the same way in each.
284
271
 
285
- Each vendor bundles its package dependencies. Imports whose exact specifiers are registered in `runtimeModules` are rewritten to the corresponding shared vendor URL; React and the configured router are shared automatically.
286
-
287
- #### Singleton packages (MobX, Redux, Query client, audio engines)
288
-
289
- React context, MobX observables, Redux stores, TanStack Query clients, and audio runtimes (for example Tone.js) depend on one module instance. Register a singleton package in `runtimeModules` when Page and Layout code must share its state.
290
-
291
- **Library packaging:** ship singleton dependencies as `peerDependencies` and keep them external in the library build so `dist/` retains `import … from "mobx"` (or equivalent) instead of inlining a private copy.
292
-
293
- **Ecopages app config:** register each singleton and library package as its own `runtimeModules` entry. Imports between those vendors are rewritten to the shared vendor URLs when their specifiers match:
294
-
295
- ```ts
296
- reactPlugin({
297
- router: ecoRouter(),
298
- runtimeModules: [
299
- { specifier: 'mobx', outputName: 'mobx' },
300
- { specifier: 'mobx-react-lite', outputName: 'mobx-react-lite' },
301
- { specifier: '@acme/store-ui', outputName: 'acme-store-ui' },
302
- ],
303
- });
304
- ```
272
+ **Library packaging:** a library that depends on a singleton such as MobX should declare it as a `peerDependency` and keep it external in its own build, so its `dist/` keeps `import … from "mobx"` instead of inlining a private copy that the app's copy cannot see.
305
273
 
306
- Registering only the library vendor or only the singleton is not enough when the published library still inlines the singleton. Peer the dependency in the library, externalize it in the library build, and register both the library and singleton specifiers in `runtimeModules`. Existing `externals` fields on runtime module entries should be removed; register each non-framework shared dependency as its own entry. React, React DOM, and the configured router are shared automatically. Rebuild vendors (and clear `.eco` / `dist/client/assets/vendors` in dev) after changing package entry points or `runtimeModules`.
274
+ Kitchen-sink routes `/vendor-share/a` and `/vendor-share/b` are the reference fixture for one shared package across navigation; see `playground/kitchen-sink/e2e/shared-vendors.test.e2e.ts`.
307
275
 
308
276
  #### Troubleshooting
309
277
 
310
- | Symptom | Likely cause | Fix |
311
- | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
312
- | `No QueryClient set` after SPA navigation | Query client package is not shared by the Page and Layout graphs | Add `@tanstack/react-query` to `runtimeModules` and rebuild vendors |
313
- | Duplicate React context / Tone init logs | Provider package is bundled through multiple client entrypoints | Import through the package root and register that root in `runtimeModules` |
314
- | Store updates / `reaction` / `observer` no-op | Duplicate singleton (for example MobX) — a library inlines one copy and app code loads another | Peer the singleton in the library; register the library and singleton specifiers in `runtimeModules`; rebuild vendors |
315
- | `@/` alias not followed | Missing or invalid tsconfig paths | Add `compilerOptions.paths`; ensure `include` globs are valid JSON (not broken by comment stripping) |
316
- | Stale bootstrap script hash in dev | Rendered HTML cached before runtime vendors/bootstrap scripts changed | Rebuild or touch a route file; development HTML cache keys include browser-runtime generation |
317
- | `MISSING_EXPORT` for names like `BasePlugin` | Vendor listed CJS enumerable keys that the ESM file does not export | Register the package root only; rebuild vendors. Subpath plugins are separate module contracts and must be bundled or declared themselves |
318
- | `does not provide an export named 'jsx'` | Stale React vendor generated with `export *` from CJS `jsx-runtime` | Clear `.eco` / `dist/client/assets/vendors` and rebuild so the CJS entry lists `jsx` / `jsxs` explicitly |
319
- | `Calling require for "/assets/vendors/…"` | A CJS vendor graph `require()`d another runtime module after URL rewrite | Prefer packages with an ESM/`module` entry; register sibling singletons as separate `runtimeModules` entries |
278
+ | Symptom | Likely cause | Fix |
279
+ | --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
280
+ | Store updates / `reaction` / `observer` no-op | Duplicate singleton (for example MobX) — a library inlines one copy and app code loads another | Peer the singleton in the library and keep it external in the library build |
281
+ | `@/` alias not followed | Missing or invalid tsconfig paths | Add `compilerOptions.paths`; ensure `include` globs are valid JSON (not broken by comment stripping) |
282
+ | `does not provide an export named …` in dev | An inline or non-module script imports a CommonJS package such as React by name; the dev rewrite skips it | Move the import into a module file or a non-inline `type="module"` script |
320
283
 
321
284
  Use the dev toolbar **Deps** panel to inspect vendor URLs loaded by the active Page. See [Dev Toolbar](/docs/core/dev-toolbar).
322
285
 
323
286
  #### Tests
324
287
 
325
- - `src/bundling/runtime-modules.test.ts`: explicit entries, exact package specifiers, and vendor filename normalization.
326
- - `src/bundling/runtime-bundle.test.ts`: vendor registration and manifest paths.
327
- - `../../core/src/assets/asset-processing-service/browser-runtime-entry-resolution.test.ts`: ESM entry resolution and default-export policy for React vs TanStack Query.
328
- - `../../../e2e/fixtures/react-router/persist-layouts.test.e2e.ts`: one QueryClient shared across Page navigation with an explicit `runtimeModules` entry.
288
+ - `../../core/src/dev/transform-server/dev-transform-import-rewriter.test.ts`: named imports and re-exports of a CommonJS vendor read its default export.
289
+ - `../../../e2e/fixtures/react-production-start/react-production-start.e2e-shared.ts`: under `ecopages dev`, `preview` and `start`, React islands and router Pages hydrate, a router Layout keeps its state across navigation, and every page loads React from one module, which `start` and `preview` serve content-hashed and `immutable`.
290
+ - `../../../e2e/fixtures/react-router/persist-layouts.test.e2e.ts`: one QueryClient shared across Page navigation, without configuration.
291
+ - `../../../e2e/fixtures/react-router/layout-persistence.e2e-shared.ts`: in dev and preview, a plain Layout and an `eco.layout()` Layout keep their React state across navigation, and one Layout module is evaluated once across MDX and TSX Pages.
329
292
 
330
293
  ### Suspense on the server
331
294
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -8,6 +8,9 @@
8
8
  "plugin"
9
9
  ],
10
10
  "license": "MIT",
11
+ "engines": {
12
+ "node": "^24.22.0 || >=26.0.0"
13
+ },
11
14
  "main": "./src/plugin/react.plugin.js",
12
15
  "types": "./src/plugin/react.plugin.d.ts",
13
16
  "type": "module",
@@ -34,10 +37,6 @@
34
37
  "types": "./src/app/client-only.d.ts",
35
38
  "default": "./src/app/client-only.js"
36
39
  },
37
- "./runtime/use-sync-external-store-with-selector": {
38
- "types": "./src/runtime/use-sync-external-store-with-selector.d.ts",
39
- "default": "./src/runtime/use-sync-external-store-with-selector.js"
40
- },
41
40
  "./router-adapter": {
42
41
  "types": "./src/contracts/router-adapter.d.ts",
43
42
  "default": "./src/contracts/router-adapter.js"
@@ -46,6 +45,18 @@
46
45
  "types": "./src/render/layout-compose.d.ts",
47
46
  "default": "./src/render/layout-compose.js"
48
47
  },
48
+ "./island-hydration": {
49
+ "types": "./src/hydration/browser/island-hydration.d.ts",
50
+ "default": "./src/hydration/browser/island-hydration.js"
51
+ },
52
+ "./page-hydration": {
53
+ "types": "./src/hydration/browser/page-hydration.d.ts",
54
+ "default": "./src/hydration/browser/page-hydration.js"
55
+ },
56
+ "./foreign-boundary": {
57
+ "types": "./src/hydration/browser/foreign-boundary.d.ts",
58
+ "default": "./src/hydration/browser/foreign-boundary.js"
59
+ },
49
60
  "./lazy-collection-components": {
50
61
  "types": "./src/content/lazy-collection-components.d.ts",
51
62
  "default": "./src/content/lazy-collection-components.js"
@@ -73,10 +84,6 @@
73
84
  "types": "./src/app/client-only.d.ts",
74
85
  "default": "./src/app/client-only.js"
75
86
  },
76
- "./runtime/use-sync-external-store-with-selector.ts": {
77
- "types": "./src/runtime/use-sync-external-store-with-selector.d.ts",
78
- "default": "./src/runtime/use-sync-external-store-with-selector.js"
79
- },
80
87
  "./router-adapter.ts": {
81
88
  "types": "./src/contracts/router-adapter.d.ts",
82
89
  "default": "./src/contracts/router-adapter.js"
@@ -85,6 +92,18 @@
85
92
  "types": "./src/render/layout-compose.d.ts",
86
93
  "default": "./src/render/layout-compose.js"
87
94
  },
95
+ "./island-hydration.ts": {
96
+ "types": "./src/hydration/browser/island-hydration.d.ts",
97
+ "default": "./src/hydration/browser/island-hydration.js"
98
+ },
99
+ "./page-hydration.ts": {
100
+ "types": "./src/hydration/browser/page-hydration.d.ts",
101
+ "default": "./src/hydration/browser/page-hydration.js"
102
+ },
103
+ "./foreign-boundary.ts": {
104
+ "types": "./src/hydration/browser/foreign-boundary.d.ts",
105
+ "default": "./src/hydration/browser/foreign-boundary.js"
106
+ },
88
107
  "./lazy-collection-components.ts": {
89
108
  "types": "./src/content/lazy-collection-components.d.ts",
90
109
  "default": "./src/content/lazy-collection-components.js"
@@ -104,18 +123,17 @@
104
123
  "directory": "packages/integrations/react"
105
124
  },
106
125
  "peerDependencies": {
107
- "@ecopages/core": "0.6.1",
126
+ "@ecopages/core": "0.7.0",
108
127
  "@types/react": "^19",
109
128
  "@types/react-dom": "^19",
110
129
  "react": "^19",
111
130
  "react-dom": "^19"
112
131
  },
113
132
  "dependencies": {
114
- "@ecopages/file-system": "0.6.1",
133
+ "@ecopages/file-system": "0.7.0",
115
134
  "@ecopages/logger": "^0.2.3",
116
- "@ecopages/mdx": "0.6.1",
135
+ "@ecopages/mdx": "0.7.0",
117
136
  "@mdx-js/mdx": "^3.1.1",
118
- "oxc-parser": "^0.141.0",
119
- "rolldown": "^1.1.0"
137
+ "oxc-parser": "^0.141.0"
120
138
  }
121
139
  }
@@ -1,5 +1,17 @@
1
1
  /**
2
- * Bare package specifiers for React page hydration bootstrap helpers.
2
+ * The packages React's generated browser entries import, in one place.
3
+ *
4
+ * @remarks
5
+ * The Page and island entries import them by name, the development vendor graph builds them up front, and the
6
+ * client-graph boundary keeps their imports in every client graph.
3
7
  */
8
+ import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
9
+ export declare const REACT_PACKAGE = "react";
10
+ export declare const REACT_DOM_CLIENT_PACKAGE = "react-dom/client";
4
11
  export declare const PAGE_LAYOUT_NORMALIZATION_PACKAGE = "@ecopages/core/client";
5
12
  export declare const LAYOUT_COMPOSE_PACKAGE = "@ecopages/react/layout-compose";
13
+ export declare const ISLAND_HYDRATION_PACKAGE = "@ecopages/react/island-hydration";
14
+ export declare const PAGE_HYDRATION_PACKAGE = "@ecopages/react/page-hydration";
15
+ export declare const FOREIGN_BOUNDARY_PACKAGE = "@ecopages/react/foreign-boundary";
16
+ /** Every package React's browser entries import, plus the configured router's browser entry. */
17
+ export declare function getReactBrowserPackages(routerAdapter?: ReactRouterAdapter): string[];
@@ -1,5 +1,27 @@
1
- /**
2
- * Bare package specifiers for React page hydration bootstrap helpers.
3
- */
1
+ export const REACT_PACKAGE = 'react';
2
+ export const REACT_DOM_CLIENT_PACKAGE = 'react-dom/client';
4
3
  export const PAGE_LAYOUT_NORMALIZATION_PACKAGE = '@ecopages/core/client';
5
4
  export const LAYOUT_COMPOSE_PACKAGE = '@ecopages/react/layout-compose';
5
+ export const ISLAND_HYDRATION_PACKAGE = '@ecopages/react/island-hydration';
6
+ export const PAGE_HYDRATION_PACKAGE = '@ecopages/react/page-hydration';
7
+ export const FOREIGN_BOUNDARY_PACKAGE = '@ecopages/react/foreign-boundary';
8
+ /** React, React DOM and the JSX runtimes compiled React modules import. */
9
+ const REACT_RUNTIME_PACKAGES = [
10
+ REACT_PACKAGE,
11
+ 'react/jsx-runtime',
12
+ 'react/jsx-dev-runtime',
13
+ 'react-dom',
14
+ REACT_DOM_CLIENT_PACKAGE,
15
+ ];
16
+ /** Every package React's browser entries import, plus the configured router's browser entry. */
17
+ export function getReactBrowserPackages(routerAdapter) {
18
+ return [
19
+ ...REACT_RUNTIME_PACKAGES,
20
+ PAGE_HYDRATION_PACKAGE,
21
+ ISLAND_HYDRATION_PACKAGE,
22
+ FOREIGN_BOUNDARY_PACKAGE,
23
+ LAYOUT_COMPOSE_PACKAGE,
24
+ PAGE_LAYOUT_NORMALIZATION_PACKAGE,
25
+ ...(routerAdapter ? [routerAdapter.importPath] : []),
26
+ ];
27
+ }
@@ -7,72 +7,44 @@
7
7
  * @module
8
8
  */
9
9
  import type { EcoBuildPlugin, IntegrationRuntimeContext } from '@ecopages/core/integration';
10
- import type { AssetProcessingIntegration, AssetProcessingService } from '@ecopages/core/integration';
11
10
  import type { ReactRouterAdapter } from '../contracts/router-adapter.js';
12
- import { type ReactRuntimeImports } from './runtime-bundle.js';
13
- import type { ResolvedReactPluginRuntimeModule } from './runtime-modules.js';
14
11
  /**
15
12
  * Configuration for the BundleService.
16
13
  */
17
14
  export interface BundleServiceConfig {
18
15
  rootDir: string;
19
16
  appConfig: IntegrationRuntimeContext['appConfig'];
20
- assetProcessingIntegration?: AssetProcessingIntegration;
21
17
  hostIntegrationName: string;
22
18
  routerAdapter?: ReactRouterAdapter;
23
- runtimeModules?: ResolvedReactPluginRuntimeModule[];
24
19
  getMdxLoaderPlugin?: () => EcoBuildPlugin;
25
20
  }
26
21
  /**
27
- * Optional flags that adjust how a React client entry is bundled.
22
+ * Packages whose imports the client-graph boundary keeps whatever a module's declared `modules` say.
23
+ *
24
+ * @remarks
25
+ * Hydration needs core and every package React's browser entries import, the configured router included.
28
26
  */
29
- export interface ReactClientBundleOptions {
30
- /**
31
- * When `true`, bundle React runtime dependencies into the emitted entry instead of
32
- * rewriting them to external runtime specifiers.
33
- */
34
- includeRuntime?: boolean;
35
- /**
36
- * When set, overrides the build adapter chunk splitting mode for this entry.
37
- */
38
- splitting?: boolean;
39
- }
27
+ export declare function getReactClientGraphAllowSpecifiers(routerAdapter?: ReactRouterAdapter): string[];
40
28
  /**
41
29
  * Manages bundle configuration and plugin creation for React page/component builds.
42
30
  */
43
31
  export declare class BundleService {
44
- private readonly runtimeBundleService;
45
32
  private readonly config;
46
33
  private readonly foreignJsxOverridePlugin;
47
- private readonly runtimeRewritePlugin;
48
- private pageLayoutNormalizationVendorPromise;
49
34
  private mdxLoaderPlugin;
50
35
  constructor(config: BundleServiceConfig);
51
- /**
52
- * Returns resolved runtime import paths for the React runtime.
53
- */
54
- getRuntimeImports(): ReactRuntimeImports;
55
- /**
56
- * Processes the MDX-only page-layout-normalization vendor once per BundleService instance.
57
- *
58
- * @remarks
59
- * Concurrent callers share the same in-flight promise. Asset processing itself caches
60
- * by dependency key, so repeats after success remain cheap.
61
- */
62
- ensurePageLayoutNormalizationVendorProcessed(assetProcessingService: Pick<AssetProcessingService, 'processDependencies'>): Promise<void>;
63
36
  /**
64
37
  * Creates bundle options for a page or component entry.
65
38
  *
66
39
  * @remarks
67
- * React derives runtime specifier mappings from the core browser runtime manifest
68
- * so ESM imports resolve to concrete runtime asset URLs during module loading.
40
+ * React, React DOM and the router are ordinary packages of the build, so the bundler resolves and shares them
41
+ * like any other import.
69
42
  *
70
43
  * @param componentName - Generated unique component name for output naming
71
- * @param isMdx - Whether the source file is an MDX file
72
44
  * @param declaredModules - Explicitly declared browser module specifiers
73
45
  * @returns Bundle options object for the build adapter
74
46
  */
75
- createBundleOptions(componentName: string, isMdx: boolean, declaredModules: string[], bundleOptions?: ReactClientBundleOptions, entrypointFile?: string, groupedEntrypointFiles?: readonly string[], groupedDeclaredModules?: readonly string[]): Promise<Record<string, unknown>>;
47
+ createBundleOptions(componentName: string, declaredModules: string[], entrypointFile?: string, groupedEntrypointFiles?: readonly string[], groupedDeclaredModules?: readonly string[]): Promise<Record<string, unknown>>;
76
48
  private createClientBuildPlugins;
77
49
  private getMdxLoaderPlugin;
78
50
  }