@ecopages/react 0.2.0-rc.4 → 0.2.0-rc.6

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.
package/README.md CHANGED
@@ -87,6 +87,8 @@ The React integration supports Node.js modules and server-only code **only on th
87
87
 
88
88
  Keep server helpers close, but separate them physically or logically so they do not leak into the client bundle.
89
89
 
90
+ For a hydratable Page that renders collection MDX, use `createCollectionComponentCache()` with the collection's `/browser` loader. Export `preload` from the Page so hydration, router navigation, and HMR load the current entry before synchronous render. The server may prime the same cache with `/server`'s `getComponent()` inside `staticProps`; `dependencies` remains server-only and is removed from the Page Browser Graph.
91
+
90
92
  ## Client Graph Boundary Architecture
91
93
 
92
94
  This section explains the internal contract used to keep the browser bundle minimal while preventing server-only code and request-only configuration from leaking into client output.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/react",
3
- "version": "0.2.0-rc.4",
3
+ "version": "0.2.0-rc.6",
4
4
  "description": "React integration for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -11,6 +11,9 @@
11
11
  "main": "./src/plugin/react.plugin.js",
12
12
  "types": "./src/plugin/react.plugin.d.ts",
13
13
  "type": "module",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
14
17
  "exports": {
15
18
  ".": {
16
19
  "default": "./src/plugin/react.plugin.js",
@@ -43,6 +46,10 @@
43
46
  "types": "./src/render/layout-compose.d.ts",
44
47
  "default": "./src/render/layout-compose.js"
45
48
  },
49
+ "./collection-component-cache": {
50
+ "types": "./src/content/collection-component-cache.d.ts",
51
+ "default": "./src/content/collection-component-cache.js"
52
+ },
46
53
  "./serialize-page-data-script": {
47
54
  "types": "./src/hydration/serialize-page-data-script.d.ts",
48
55
  "default": "./src/hydration/serialize-page-data-script.js"
@@ -78,6 +85,10 @@
78
85
  "types": "./src/render/layout-compose.d.ts",
79
86
  "default": "./src/render/layout-compose.js"
80
87
  },
88
+ "./collection-component-cache.ts": {
89
+ "types": "./src/content/collection-component-cache.d.ts",
90
+ "default": "./src/content/collection-component-cache.js"
91
+ },
81
92
  "./serialize-page-data-script.ts": {
82
93
  "types": "./src/hydration/serialize-page-data-script.d.ts",
83
94
  "default": "./src/hydration/serialize-page-data-script.js"
@@ -93,20 +104,20 @@
93
104
  "directory": "packages/integrations/react"
94
105
  },
95
106
  "peerDependencies": {
96
- "@ecopages/core": "0.2.0-rc.4",
107
+ "@ecopages/core": "0.2.0-rc.6",
97
108
  "@types/react": "^19",
98
109
  "@types/react-dom": "^19",
99
110
  "react": "^19",
100
111
  "react-dom": "^19"
101
112
  },
102
113
  "dependencies": {
103
- "@ecopages/file-system": "0.2.0-rc.4",
114
+ "@ecopages/file-system": "0.2.0-rc.6",
104
115
  "@ecopages/logger": "^0.2.3",
105
- "@ecopages/mdx": "0.2.0-rc.4",
116
+ "@ecopages/mdx": "0.2.0-rc.6",
106
117
  "@mdx-js/mdx": "^3.1.1",
107
118
  "oxc-parser": "^0.141.0",
108
119
  "oxc-transform": "^0.141.0",
109
120
  "source-map": "^0.8.0",
110
121
  "vfile": "^6.0.3"
111
122
  }
112
- }
123
+ }
@@ -100,7 +100,10 @@ export class BundleService {
100
100
  ? []
101
101
  : [runtimeRewritePlugin].filter((plugin) => plugin !== null);
102
102
  if (isMdx && this.config.mdxCompilerOptions) {
103
- const mdxPlugin = createReactMdxLoaderPlugin(this.config.mdxCompilerOptions);
103
+ const mdxPlugin = createReactMdxLoaderPlugin({
104
+ compilerOptions: this.config.mdxCompilerOptions,
105
+ projectRoot: this.config.rootDir,
106
+ });
104
107
  options.plugins = [
105
108
  ...(foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : []),
106
109
  graphBoundaryPlugin,
@@ -7,6 +7,7 @@ import { isBareSpecifier, isProjectAliasSpecifier, isServerOnlySpecifier, toModu
7
7
  const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set([
8
8
  'cache',
9
9
  'middleware',
10
+ 'dependencies',
10
11
  'requires',
11
12
  'metadata',
12
13
  'staticProps',
@@ -36,9 +37,9 @@ function getObjectPropertyKeyName(node) {
36
37
  * Removes server-only `eco.page(...)` options from browser-bound modules.
37
38
  *
38
39
  * Import pruning alone is not sufficient because a page module can still retain
39
- * references to stripped server imports through config fields like `middleware`
40
- * or `metadata`. This pass rewrites the `eco.page(...)` object literal so only
41
- * browser-relevant properties remain.
40
+ * references to stripped server imports through options such as `middleware`,
41
+ * `dependencies`, or `metadata`. This pass rewrites the `eco.page(...)` object
42
+ * literal so only browser-relevant properties remain.
42
43
  *
43
44
  * @param source - Original or already-transformed module source.
44
45
  * @param program - Parsed OXC program for the same source text.
@@ -5,10 +5,10 @@
5
5
  * using the Oxc AST parser. It computes a strict "reachability graph" of all JavaScript/TypeScript
6
6
  * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
7
  *
8
- * In Ecopages, "client roots" are defined as the `render`, `errorBoundary`, or `loadingFallback`
9
- * properties passed into `eco.page()`, `eco.layout()`, or `eco.component()`. By tracing the execution path from
10
- * these roots, the analyzer determines exactly which modules and bindings are actually needed
11
- * by the browser to hydrate the page, and which imports are unused on the client (and thus can be pruned).
8
+ * In Ecopages, client roots are the `render`, `errorBoundary`, and `loadingFallback`
9
+ * properties passed into `eco.page()`, `eco.layout()`, or `eco.component()`. A Page's named
10
+ * `preload` export is an additional root. By tracing from these roots, the analyzer determines
11
+ * which modules and bindings the browser needs and which imports it can prune.
12
12
  */
13
13
  import type { ParseResult } from 'oxc-parser';
14
14
  /**
@@ -34,6 +34,14 @@ export type ReachabilityResult = {
34
34
  */
35
35
  analyzed: boolean;
36
36
  };
37
+ /**
38
+ * Returns whether a module exports a named `preload` binding.
39
+ *
40
+ * @remarks
41
+ * Hydration entries only wire `preload` when this is true, so Pages without
42
+ * that export do not produce a missing-named-import warning.
43
+ */
44
+ export declare function hasPagePreloadExport(source: string, filename: string): boolean;
37
45
  /**
38
46
  * Optional export filter supplied by the client graph boundary when a local
39
47
  * module is imported through a narrower named-export surface.
@@ -45,7 +53,8 @@ export type ReachabilityResult = {
45
53
  type ExplicitlyRequestedExports = Set<string> | '*';
46
54
  /**
47
55
  * Analyzes a module using Oxc AST and extracts a strict reachability graph
48
- * starting from client roots (`render`, `errorBoundary`, `loadingFallback` of `eco.page`, `eco.layout`, or `eco.component`).
56
+ * starting from client roots: `render`, `errorBoundary`, and `loadingFallback` of
57
+ * `eco.page`, `eco.layout`, or `eco.component`, plus a Page's named `preload` export.
49
58
  *
50
59
  * @param source - Raw source string of the module.
51
60
  * @param filename - Absolute or relative path to the module file.
@@ -5,15 +5,45 @@
5
5
  * using the Oxc AST parser. It computes a strict "reachability graph" of all JavaScript/TypeScript
6
6
  * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
7
  *
8
- * In Ecopages, "client roots" are defined as the `render`, `errorBoundary`, or `loadingFallback`
9
- * properties passed into `eco.page()`, `eco.layout()`, or `eco.component()`. By tracing the execution path from
10
- * these roots, the analyzer determines exactly which modules and bindings are actually needed
11
- * by the browser to hydrate the page, and which imports are unused on the client (and thus can be pruned).
8
+ * In Ecopages, client roots are the `render`, `errorBoundary`, and `loadingFallback`
9
+ * properties passed into `eco.page()`, `eco.layout()`, or `eco.component()`. A Page's named
10
+ * `preload` export is an additional root. By tracing from these roots, the analyzer determines
11
+ * which modules and bindings the browser needs and which imports it can prune.
12
12
  */
13
13
  import { parseModuleSource } from '@ecopages/core/cache';
14
+ function isPreloadExportStatement(statement) {
15
+ const declaration = statement.declaration;
16
+ if (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') {
17
+ return declaration.id?.type === 'Identifier' && declaration.id.name === 'preload';
18
+ }
19
+ if (declaration?.type === 'VariableDeclaration') {
20
+ return (declaration.declarations?.some((declarator) => declarator.id.type === 'Identifier' && declarator.id.name === 'preload') ?? false);
21
+ }
22
+ return statement.specifiers.some((specifier) => {
23
+ const exported = specifier.exported;
24
+ return exported.type === 'Identifier' ? exported.name === 'preload' : exported.value === 'preload';
25
+ });
26
+ }
27
+ /**
28
+ * Returns whether a module exports a named `preload` binding.
29
+ *
30
+ * @remarks
31
+ * Hydration entries only wire `preload` when this is true, so Pages without
32
+ * that export do not produce a missing-named-import warning.
33
+ */
34
+ export function hasPagePreloadExport(source, filename) {
35
+ try {
36
+ const { program } = parseModuleSource(filename, source);
37
+ return program.body.some((statement) => statement.type === 'ExportNamedDeclaration' && isPreloadExportStatement(statement));
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
14
43
  /**
15
44
  * Analyzes a module using Oxc AST and extracts a strict reachability graph
16
- * starting from client roots (`render`, `errorBoundary`, `loadingFallback` of `eco.page`, `eco.layout`, or `eco.component`).
45
+ * starting from client roots: `render`, `errorBoundary`, and `loadingFallback` of
46
+ * `eco.page`, `eco.layout`, or `eco.component`, plus a Page's named `preload` export.
17
47
  *
18
48
  * @param source - Raw source string of the module.
19
49
  * @param filename - Absolute or relative path to the module file.
@@ -68,6 +98,8 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
68
98
  const topLevelImports = [];
69
99
  const topLevelDeclarations = new Map();
70
100
  const potentialClientRoots = [];
101
+ const pagePreloadRoots = [];
102
+ let hasEcoPageRoot = false;
71
103
  for (const statement of resolvedProgram.body) {
72
104
  if (statement.type === 'ImportDeclaration') {
73
105
  if (statement.importKind === 'type') {
@@ -110,6 +142,9 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
110
142
  else if (statement.type === 'ExportNamedDeclaration') {
111
143
  if (statement.declaration) {
112
144
  const decl = statement.declaration;
145
+ if (isPreloadExportStatement(statement)) {
146
+ pagePreloadRoots.push(statement);
147
+ }
113
148
  if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
114
149
  if (decl.id && decl.id.type === 'Identifier') {
115
150
  topLevelDeclarations.set(decl.id.name, statement);
@@ -124,6 +159,9 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
124
159
  }
125
160
  }
126
161
  }
162
+ else if (isPreloadExportStatement(statement)) {
163
+ pagePreloadRoots.push(statement);
164
+ }
127
165
  }
128
166
  else if (statement.type === 'ExportDefaultDeclaration') {
129
167
  checkPotentialClientRoot(statement.declaration);
@@ -160,19 +198,16 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
160
198
  (prop.name === 'page' ||
161
199
  prop.name === 'component' ||
162
200
  prop.name === 'layout')) {
201
+ if (prop.name === 'page') {
202
+ hasEcoPageRoot = true;
203
+ }
163
204
  potentialClientRoots.push(node.callee);
164
205
  const arg = node.arguments[0];
165
206
  if (arg && arg.type === 'ObjectExpression') {
166
207
  for (const prop of arg.properties) {
167
208
  if (prop.type === 'Property' &&
168
209
  prop.key.type === 'Identifier') {
169
- if ([
170
- 'render',
171
- 'errorBoundary',
172
- 'loadingFallback',
173
- 'clientScripts',
174
- 'dependencies',
175
- ].includes(prop.key.name)) {
210
+ if (['render', 'errorBoundary', 'loadingFallback', 'clientScripts'].includes(prop.key.name)) {
176
211
  potentialClientRoots.push(prop.value);
177
212
  }
178
213
  }
@@ -186,6 +221,9 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
186
221
  potentialClientRoots.push(node);
187
222
  }
188
223
  }
224
+ if (hasEcoPageRoot) {
225
+ potentialClientRoots.push(...pagePreloadRoots);
226
+ }
189
227
  /**
190
228
  * Resolves the externally visible export name from an export specifier.
191
229
  *
@@ -7,8 +7,9 @@ export declare function isProjectAliasSpecifier(specifier: string, projectRoot?:
7
7
  /**
8
8
  * Determines whether a specifier should be treated as server-only.
9
9
  *
10
- * This covers Node built-ins as well as local module conventions such as
11
- * `.server.ts` and extensionless imports that resolve to `.server.*` files.
10
+ * This covers Node built-ins, content collection `/server` virtual modules,
11
+ * and local module conventions such as `.server.ts` and extensionless imports
12
+ * that resolve to `.server.*` files.
12
13
  *
13
14
  * @param specifier - Raw import specifier from the module source.
14
15
  * @returns True when the import must never become client-reachable.
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { loadTsconfigPathPrefixes, matchesTsconfigPathPrefix } from '@ecopages/core/plugins/tsconfig-import-resolver';
5
5
  import { toPackageRootSpecifier } from '@ecopages/core/plugins/package-specifier';
6
+ import { isContentServerVirtualModule } from '@ecopages/core/build/contracts/content-virtual-modules';
6
7
  import { dirname, resolve } from 'node:path';
7
8
  export function isBareSpecifier(specifier) {
8
9
  if (specifier.startsWith('.'))
@@ -25,8 +26,9 @@ export function isProjectAliasSpecifier(specifier, projectRoot) {
25
26
  /**
26
27
  * Determines whether a specifier should be treated as server-only.
27
28
  *
28
- * This covers Node built-ins as well as local module conventions such as
29
- * `.server.ts` and extensionless imports that resolve to `.server.*` files.
29
+ * This covers Node built-ins, content collection `/server` virtual modules,
30
+ * and local module conventions such as `.server.ts` and extensionless imports
31
+ * that resolve to `.server.*` files.
30
32
  *
31
33
  * @param specifier - Raw import specifier from the module source.
32
34
  * @returns True when the import must never become client-reachable.
@@ -34,6 +36,8 @@ export function isProjectAliasSpecifier(specifier, projectRoot) {
34
36
  export function isServerOnlySpecifier(specifier) {
35
37
  if (specifier.startsWith('node:'))
36
38
  return true;
39
+ if (isContentServerVirtualModule(specifier))
40
+ return true;
37
41
  return /(?:^|[/])[^/]+\.server(?:$|\.)/.test(specifier);
38
42
  }
39
43
  /**
@@ -0,0 +1,25 @@
1
+ import type { EcoComponent } from '@ecopages/core';
2
+ export type CollectionComponentCache = {
3
+ preload(slug: string): Promise<void>;
4
+ prime(slug: string, component: Promise<EcoComponent<Record<string, unknown>>>): Promise<void>;
5
+ get(slug: string): EcoComponent<Record<string, unknown>>;
6
+ };
7
+ /**
8
+ * Creates the synchronous component lookup required by a Page that preloads
9
+ * collection MDX before SSR, hydration, and client navigation.
10
+ *
11
+ * @remarks
12
+ * `preload()` loads the browser-compiled component and must not run in
13
+ * `staticProps`. A hydratable collection Page primes the cache in `staticProps`
14
+ * with its server component, then exposes a named `preload` export for
15
+ * hydration and client navigation to load the browser component.
16
+ *
17
+ * Completed loads are deliberately refreshed by the next preload. Native
18
+ * module caching keeps that inexpensive while allowing HMR to replace a
19
+ * component before the Page re-renders.
20
+ *
21
+ * `prime()` always stores the provided server component, even when a
22
+ * `preload()` is already in flight. Completions from a superseded load are
23
+ * ignored so they cannot replace the primed entry.
24
+ */
25
+ export declare function createCollectionComponentCache(loadComponent: (slug: string) => Promise<EcoComponent<Record<string, unknown>>>): CollectionComponentCache;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Creates the synchronous component lookup required by a Page that preloads
3
+ * collection MDX before SSR, hydration, and client navigation.
4
+ *
5
+ * @remarks
6
+ * `preload()` loads the browser-compiled component and must not run in
7
+ * `staticProps`. A hydratable collection Page primes the cache in `staticProps`
8
+ * with its server component, then exposes a named `preload` export for
9
+ * hydration and client navigation to load the browser component.
10
+ *
11
+ * Completed loads are deliberately refreshed by the next preload. Native
12
+ * module caching keeps that inexpensive while allowing HMR to replace a
13
+ * component before the Page re-renders.
14
+ *
15
+ * `prime()` always stores the provided server component, even when a
16
+ * `preload()` is already in flight. Completions from a superseded load are
17
+ * ignored so they cannot replace the primed entry.
18
+ */
19
+ export function createCollectionComponentCache(loadComponent) {
20
+ const records = new Map();
21
+ const store = async (slug, component) => {
22
+ const pending = {};
23
+ const promise = component.then((resolvedComponent) => {
24
+ if (records.get(slug) === pending.record) {
25
+ records.set(slug, { status: 'success', component: resolvedComponent });
26
+ }
27
+ }, (error) => {
28
+ if (records.get(slug) === pending.record) {
29
+ records.set(slug, { status: 'error', error });
30
+ }
31
+ throw error;
32
+ });
33
+ pending.record = { status: 'pending', promise };
34
+ records.set(slug, pending.record);
35
+ return await promise;
36
+ };
37
+ return {
38
+ async preload(slug) {
39
+ const existing = records.get(slug);
40
+ if (existing?.status === 'pending') {
41
+ return await existing.promise;
42
+ }
43
+ return await store(slug, loadComponent(slug));
44
+ },
45
+ async prime(slug, component) {
46
+ return await store(slug, component);
47
+ },
48
+ get(slug) {
49
+ const record = records.get(slug);
50
+ if (!record) {
51
+ throw new Error(`[ecopages] Collection content '${slug}' was rendered before it was preloaded.`);
52
+ }
53
+ if (record.status === 'success') {
54
+ return record.component;
55
+ }
56
+ if (record.status === 'error') {
57
+ throw record.error;
58
+ }
59
+ throw new Error(`[ecopages] Collection content '${slug}' is still loading during render.`);
60
+ },
61
+ };
62
+ }
@@ -15,6 +15,7 @@ import { ClientGraphBoundaryCache } from '../client-graph/boundary-cache.js';
15
15
  import type { HmrPageMetadataCache } from './page-metadata-cache.js';
16
16
  export interface ReactHmrStrategyOptions {
17
17
  context: DefaultHmrContext;
18
+ projectRoot?: string;
18
19
  pageMetadataCache: HmrPageMetadataCache;
19
20
  runtimeManifest: BrowserRuntimeManifest;
20
21
  mdxCompilerOptions?: CompileOptions;
@@ -34,6 +35,7 @@ export interface ReactHmrStrategyOptions {
34
35
  export declare class ReactHmrStrategy extends HmrStrategy {
35
36
  readonly type: 100;
36
37
  private mdxCompilerOptions?;
38
+ private readonly projectRoot;
37
39
  private readonly ownedTemplateExtensions;
38
40
  private readonly allTemplateExtensions;
39
41
  private readonly context;
@@ -25,6 +25,7 @@ const appLogger = new Logger('[ReactHmrStrategy]');
25
25
  export class ReactHmrStrategy extends HmrStrategy {
26
26
  type = HmrStrategyType.INTEGRATION;
27
27
  mdxCompilerOptions;
28
+ projectRoot;
28
29
  ownedTemplateExtensions;
29
30
  allTemplateExtensions;
30
31
  context;
@@ -38,6 +39,7 @@ export class ReactHmrStrategy extends HmrStrategy {
38
39
  return {
39
40
  pageMetadataCache: this.pageMetadataCache,
40
41
  mdxCompilerOptions: this.mdxCompilerOptions,
42
+ projectRoot: this.projectRoot,
41
43
  getBuildPlugins: (declaredModules) => this.getBuildPlugins(declaredModules),
42
44
  importNodePageModule: (entrypointPath) => this.importNodePageModule(entrypointPath),
43
45
  };
@@ -45,6 +47,7 @@ export class ReactHmrStrategy extends HmrStrategy {
45
47
  constructor(options) {
46
48
  super();
47
49
  this.context = options.context;
50
+ this.projectRoot = options.projectRoot ?? path.dirname(this.context.getSrcDir());
48
51
  this.pageMetadataCache = options.pageMetadataCache;
49
52
  this.runtimeManifest = options.runtimeManifest;
50
53
  this.clientGraphBoundaryCache = options.clientGraphBoundaryCache ?? new ClientGraphBoundaryCache();
@@ -60,8 +63,8 @@ export class ReactHmrStrategy extends HmrStrategy {
60
63
  });
61
64
  return [
62
65
  createClientGraphBoundaryPlugin({
63
- projectRoot: path.dirname(this.context.getSrcDir()),
64
- absWorkingDir: path.dirname(this.context.getSrcDir()),
66
+ projectRoot: this.projectRoot,
67
+ absWorkingDir: this.projectRoot,
65
68
  alwaysAllowSpecifiers: allowSpecifiers,
66
69
  declaredModules,
67
70
  cache: this.clientGraphBoundaryCache,
@@ -15,6 +15,7 @@ type ImportedReactPageModule = {
15
15
  export type ReactHmrDevTransformPluginOptions = {
16
16
  pageMetadataCache: HmrPageMetadataCache;
17
17
  mdxCompilerOptions?: CompileOptions;
18
+ projectRoot: string;
18
19
  getBuildPlugins: (declaredModules?: readonly string[]) => EcoBuildPlugin[];
19
20
  importNodePageModule: (entrypointPath: string) => Promise<ImportedReactPageModule>;
20
21
  };
@@ -14,7 +14,10 @@ export async function resolveReactDeclaredModulesForEntrypoint(options, entrypoi
14
14
  export function buildReactDevTransformPlugins(options, declaredModules, shouldEnableMdx) {
15
15
  const plugins = options.getBuildPlugins(declaredModules);
16
16
  if (shouldEnableMdx && options.mdxCompilerOptions) {
17
- plugins.unshift(createReactMdxLoaderPlugin(options.mdxCompilerOptions));
17
+ plugins.unshift(createReactMdxLoaderPlugin({
18
+ compilerOptions: options.mdxCompilerOptions,
19
+ projectRoot: options.projectRoot,
20
+ }));
18
21
  }
19
22
  return plugins;
20
23
  }
@@ -31,6 +31,7 @@ type PageDependencyOptions = {
31
31
  hmrEnabled: boolean;
32
32
  useBrowserRuntimeImports: boolean;
33
33
  isMdx: boolean;
34
+ hasPagePreload?: boolean;
34
35
  };
35
36
  export declare function getIslandComponentKey(componentFile: string, config?: EcoComponentConfig): string;
36
37
  /**
@@ -14,6 +14,8 @@ import { AssetFactory, } from '@ecopages/core/services/asset-processing-service'
14
14
  import { createHydrationScript, createIslandHydrationScript } from './hydration-scripts.js';
15
15
  import { resolveHydrationBootstrapImports } from './bootstrap-imports.js';
16
16
  import { collectDeclaredModulesInConfig } from '../client-graph/declared-modules.js';
17
+ import { hasPagePreloadExport } from '../client-graph/reachability-analyzer.js';
18
+ import { fileSystem } from '@ecopages/file-system';
17
19
  export function getIslandComponentKey(componentFile, config) {
18
20
  return rapidhash(`${componentFile}:${config?.identity?.id ?? ''}`).toString();
19
21
  }
@@ -61,7 +63,7 @@ export class HydrationAssetService {
61
63
  * Creates the page-owned route entry asset for hydration and client navigation.
62
64
  */
63
65
  createPageDependencies(options) {
64
- const { pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, hmrEnabled, useBrowserRuntimeImports, isMdx, } = options;
66
+ const { pagePath, componentName, importPath, pageModuleUrlExpression, bundleOptions, hmrEnabled, useBrowserRuntimeImports, isMdx, hasPagePreload, } = options;
65
67
  const runtimeImports = this.config.bundleService.getRuntimeImports();
66
68
  /**
67
69
  * @remarks
@@ -92,6 +94,7 @@ export class HydrationAssetService {
92
94
  pageLayoutNormalizationImportPath: bootstrapImports.pageLayoutNormalizationImportPath,
93
95
  hmrEnabled,
94
96
  isMdx,
97
+ hasPagePreload,
95
98
  router: this.config.routerAdapter,
96
99
  scriptId: componentName,
97
100
  }),
@@ -211,6 +214,14 @@ export class HydrationAssetService {
211
214
  }
212
215
  const importPath = await this.resolveAssetImportPath(pagePath, componentName);
213
216
  const pageModuleUrlExpression = hmrEnabled ? JSON.stringify(importPath) : 'import.meta.url';
217
+ let hasPagePreload = false;
218
+ try {
219
+ const source = await fileSystem.readFile(pagePath);
220
+ hasPagePreload = hasPagePreloadExport(source, pagePath);
221
+ }
222
+ catch {
223
+ hasPagePreload = false;
224
+ }
214
225
  const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, isMdx, declaredModules, { includeRuntime: !useBrowserRuntimeImports, splitting: usesRouterRuntime });
215
226
  const dependencies = this.createPageDependencies({
216
227
  pagePath,
@@ -221,6 +232,7 @@ export class HydrationAssetService {
221
232
  hmrEnabled,
222
233
  useBrowserRuntimeImports,
223
234
  isMdx,
235
+ hasPagePreload,
224
236
  });
225
237
  return dependencies;
226
238
  }
@@ -32,6 +32,11 @@ export type HydrationScriptOptions = {
32
32
  hmrEnabled: boolean;
33
33
  /** Whether the source file is an MDX file */
34
34
  isMdx: boolean;
35
+ /**
36
+ * When true, the Page module exports a named `preload` and the generated
37
+ * entry must import, await, and re-export it.
38
+ */
39
+ hasPagePreload?: boolean;
35
40
  /** Optional router adapter for SPA navigation */
36
41
  router?: ReactRouterAdapter;
37
42
  /**
@@ -92,6 +97,9 @@ export type IslandHydrationScriptOptions = {
92
97
  * @remarks
93
98
  * Always emits readable source. Production page assets set `bundle: true` so
94
99
  * core's content-script processor minifies the result. Do not hand-minify here.
100
+ * If the Page exports `preload`, the generated entry imports, awaits, and
101
+ * re-exports it. Pages without that export keep a default import so the
102
+ * bundler does not warn about a missing named export.
95
103
  */
96
104
  export declare function createHydrationScript(options: HydrationScriptOptions): string;
97
105
  /**
@@ -15,30 +15,45 @@ function getPageDataReaderSource(options) {
15
15
  *
16
16
  * @remarks
17
17
  * MDX pages need a namespace import so `config` can be copied onto the default
18
- * export before layout normalization runs.
18
+ * export before layout normalization runs. Named `preload` is imported only
19
+ * when the Page actually exports it.
19
20
  */
20
- function getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath) {
21
- return isMdx
22
- ? `import * as MDXModule from "${importPath}";
21
+ function getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath, hasPagePreload) {
22
+ if (isMdx) {
23
+ const preloadLine = hasPagePreload ? '\nconst preload = MDXModule.preload;' : '';
24
+ return `import * as MDXModule from "${importPath}";
23
25
  import { ensurePageConfigLayouts } from "${pageLayoutNormalizationImportPath}";
24
- const Page = MDXModule.default;
26
+ const Page = MDXModule.default;${preloadLine}
25
27
  if (MDXModule.config) {
26
28
  Page.config = MDXModule.config;
27
29
  ensurePageConfigLayouts(Page.config);
28
- }`
29
- : `import Page from "${importPath}";`;
30
+ }`;
31
+ }
32
+ if (hasPagePreload) {
33
+ return `import * as PageModule from "${importPath}";
34
+ const Page = PageModule.default;
35
+ const preload = PageModule.preload;`;
36
+ }
37
+ return `import Page from "${importPath}";`;
30
38
  }
31
39
  /**
32
40
  * Assigns `NewPage` from a hot-reloaded module, including MDX `config` reattach.
33
41
  */
34
- function getHmrImportStatement(isMdx) {
42
+ function getHmrImportStatement(isMdx, hasPagePreload) {
43
+ const preloadLine = hasPagePreload ? '\nconst nextPreload = newModule.preload;' : '';
35
44
  return isMdx
36
- ? `const NewPage = newModule.default;
45
+ ? `const NewPage = newModule.default;${preloadLine}
37
46
  if (newModule.config) {
38
47
  NewPage.config = newModule.config;
39
48
  ensurePageConfigLayouts(NewPage.config);
40
49
  }`
41
- : 'const NewPage = newModule.default;';
50
+ : `const NewPage = newModule.default;${preloadLine}`;
51
+ }
52
+ function getPreloadAwaitStatement(identifier, propsIdentifier, hasPagePreload) {
53
+ return hasPagePreload ? `await ${identifier}?.(${propsIdentifier});` : '';
54
+ }
55
+ function getPreloadReexportStatement(hasPagePreload) {
56
+ return hasPagePreload ? 'export { preload };' : '';
42
57
  }
43
58
  function getComponentType(isMdx) {
44
59
  return isMdx ? 'MDX' : 'React';
@@ -117,12 +132,14 @@ function getHydrationTimingScript() {
117
132
  * otherwise re-renders the existing root.
118
133
  */
119
134
  function getRouterHmrHandlerScript(options) {
120
- const { importPath, isMdx } = options;
135
+ const { importPath, isMdx, hasPagePreload } = options;
136
+ const preloadAwait = getPreloadAwaitStatement('nextPreload', 'nextProps', hasPagePreload);
121
137
  return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
122
138
  try {
123
139
  const newModule = await import(newUrl);
124
140
  const nextProps = getPageData();
125
- ${getHmrImportStatement(isMdx)}
141
+ ${getHmrImportStatement(isMdx, hasPagePreload)}
142
+ ${preloadAwait}
126
143
  const currentPageLayoutStack = (Component) =>
127
144
  (Component.config?.layouts ?? []).map((layout) => layout?.config?.identity?.file ?? '').join('|');
128
145
  const currentPageLayoutStackKey = currentPageLayoutStack(Page);
@@ -154,11 +171,13 @@ function getRouterHmrHandlerScript(options) {
154
171
  * HMR handler for non-router pages: hot-imports the module and re-renders the layout tree.
155
172
  */
156
173
  function getNonRouterHmrHandlerScript(options) {
157
- const { importPath, isMdx } = options;
174
+ const { importPath, isMdx, hasPagePreload } = options;
175
+ const preloadAwait = getPreloadAwaitStatement('nextPreload', 'props', hasPagePreload);
158
176
  return ` window.__ECO_PAGES__.hmrHandlers["${importPath}"] = async (newUrl) => {
159
177
  try {
160
178
  const newModule = await import(newUrl);
161
- ${getHmrImportStatement(isMdx)}
179
+ ${getHmrImportStatement(isMdx, hasPagePreload)}
180
+ ${preloadAwait}
162
181
  root.render(createTree(NewPage, props));
163
182
  console.log("[ecopages] ${getComponentType(isMdx)} component updated");
164
183
  } catch (e) {
@@ -177,6 +196,7 @@ function getNonRouterHmrHandlerScript(options) {
177
196
  */
178
197
  function createScriptWithRouter(options) {
179
198
  const { importPath, isMdx, router, reactImportPath, reactDomClientImportPath, routerImportPath, scriptId, hmrEnabled, } = options;
199
+ const hasPagePreload = options.hasPagePreload === true;
180
200
  const pageModuleUrlExpression = options.pageModuleUrlExpression ?? 'import.meta.url';
181
201
  const { components, getRouterProps } = router;
182
202
  if (!routerImportPath) {
@@ -187,15 +207,18 @@ function createScriptWithRouter(options) {
187
207
  ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
188
208
  `
189
209
  : '';
190
- const hmrHandler = hmrEnabled ? getRouterHmrHandlerScript({ importPath, isMdx }) : '';
210
+ const hmrHandler = hmrEnabled ? getRouterHmrHandlerScript({ importPath, isMdx, hasPagePreload }) : '';
211
+ const preloadReexport = getPreloadReexportStatement(hasPagePreload);
212
+ const preloadAwait = getPreloadAwaitStatement('preload', 'props', hasPagePreload);
191
213
  return `
192
214
  import { hydrateRoot } from "${reactDomClientImportPath}";
193
215
  import { createElement } from "${reactImportPath}";
194
216
  import { ${components.router}, ${components.pageContent} } from "${routerImportPath}";
195
217
  ${getPageDataReaderSource(options)}
196
- ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath)}
218
+ ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath, hasPagePreload)}
197
219
  const pageModuleUrl = ${pageModuleUrlExpression};
198
220
  export default Page;
221
+ ${preloadReexport}
199
222
  export const config = Page.config;
200
223
  const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
201
224
 
@@ -223,7 +246,7 @@ const createTree = (Component, props) => {
223
246
  return createElement(${components.router}, ${getRouterProps('Component', 'props')}, pageContent);
224
247
  };
225
248
 
226
- const mount = () => {
249
+ const mount = async () => {
227
250
  const pageData = readPageDataDocument();
228
251
  const props = pageData.props;
229
252
  window.__ECO_PAGES__.page = {
@@ -241,6 +264,8 @@ const mount = () => {
241
264
  return;
242
265
  }
243
266
 
267
+ ${preloadAwait}
268
+
244
269
  window.__ECO_DEV_HYDRATION_STARTED__ = performance.now();
245
270
  root = hydrateRoot(document.body, createTree(Page, props), {
246
271
  onRecoverableError: (err) => console.warn("[ecopages] Hydration error:", err)
@@ -269,22 +294,26 @@ if (document.readyState === "loading") {
269
294
  */
270
295
  function createScriptWithoutRouter(options) {
271
296
  const { importPath, isMdx, reactImportPath, reactDomClientImportPath, scriptId, hmrEnabled } = options;
297
+ const hasPagePreload = options.hasPagePreload === true;
272
298
  const pageModuleUrlExpression = options.pageModuleUrlExpression ?? 'import.meta.url';
273
299
  const layoutComposeImportPath = options.layoutComposeImportPath;
274
300
  const pageLayoutNormalizationImportPath = options.pageLayoutNormalizationImportPath;
301
+ const preloadReexport = getPreloadReexportStatement(hasPagePreload);
302
+ const preloadAwait = getPreloadAwaitStatement('preload', 'props', hasPagePreload);
275
303
  const hmrInit = hmrEnabled
276
304
  ? `window.__ECO_PAGES__.hmrHandlers = window.__ECO_PAGES__.hmrHandlers || {};
277
305
  `
278
306
  : '';
279
- const hmrHandler = hmrEnabled ? getNonRouterHmrHandlerScript({ importPath, isMdx }) : '';
307
+ const hmrHandler = hmrEnabled ? getNonRouterHmrHandlerScript({ importPath, isMdx, hasPagePreload }) : '';
280
308
  return `
281
309
  import { hydrateRoot } from "${reactDomClientImportPath}";
282
310
  import { createElement } from "${reactImportPath}";
283
311
  import { composeLayoutPageTree } from "${layoutComposeImportPath}";
284
312
  ${getPageDataReaderSource(options)}
285
- ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath)}
313
+ ${getImportStatement(importPath, isMdx, pageLayoutNormalizationImportPath, hasPagePreload)}
286
314
  const pageModuleUrl = ${pageModuleUrlExpression};
287
315
  export default Page;
316
+ ${preloadReexport}
288
317
  export const config = Page.config;
289
318
  const isActivePageEntry = Boolean(document.querySelector('script[data-eco-script-id="${scriptId}"]'));
290
319
 
@@ -307,7 +336,7 @@ window.__ECO_PAGES__.page = {
307
336
 
308
337
  const createTree = (Component, props) => composeLayoutPageTree(Component, props);
309
338
 
310
- const mount = () => {
339
+ const mount = async () => {
311
340
  const pageData = readPageDataDocument();
312
341
  const props = pageData.props;
313
342
  window.__ECO_PAGES__.page = {
@@ -315,6 +344,8 @@ const mount = () => {
315
344
  props
316
345
  };
317
346
 
347
+ ${preloadAwait}
348
+
318
349
  if (window.__ECO_PAGES__.react?.pageRoot) {
319
350
  root = window.__ECO_PAGES__.react.pageRoot;
320
351
  root.render(createTree(Page, props));
@@ -345,6 +376,9 @@ if (document.readyState === "loading") {
345
376
  * @remarks
346
377
  * Always emits readable source. Production page assets set `bundle: true` so
347
378
  * core's content-script processor minifies the result. Do not hand-minify here.
379
+ * If the Page exports `preload`, the generated entry imports, awaits, and
380
+ * re-exports it. Pages without that export keep a default import so the
381
+ * bundler does not warn about a missing named export.
348
382
  */
349
383
  export function createHydrationScript(options) {
350
384
  return options.router ? createScriptWithRouter(options) : createScriptWithoutRouter(options);
@@ -1,2 +1,6 @@
1
1
  import type { CompileOptions } from '@mdx-js/mdx';
2
- export declare function createReactMdxLoaderPlugin(compilerOptions?: CompileOptions): import("@ecopages/core/build/build-types").EcoBuildPlugin;
2
+ export interface CreateReactMdxLoaderPluginOptions {
3
+ compilerOptions?: CompileOptions;
4
+ projectRoot: string;
5
+ }
6
+ export declare function createReactMdxLoaderPlugin(options: CreateReactMdxLoaderPluginOptions): import("@ecopages/core/build/build-types").EcoBuildPlugin;
@@ -1,8 +1,10 @@
1
1
  import { createMdxLoaderPlugin as createMdxLoaderPluginCore } from '@ecopages/mdx/core';
2
- export function createReactMdxLoaderPlugin(compilerOptions) {
2
+ export function createReactMdxLoaderPlugin(options) {
3
3
  return createMdxLoaderPluginCore({
4
4
  name: 'react-mdx-loader',
5
- compilerOptions,
5
+ integrationName: 'react',
6
+ compilerOptions: options.compilerOptions,
6
7
  defaultMdExtensions: [],
8
+ projectRoot: options.projectRoot,
7
9
  });
8
10
  }
@@ -175,7 +175,13 @@ export class ReactPlugin extends IntegrationPlugin {
175
175
  if (!this.mdxEnabled || !this.mdxCompilerOptions || this.mdxLoaderPlugin) {
176
176
  return;
177
177
  }
178
- this.mdxLoaderPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
178
+ if (!this.appConfig?.rootDir) {
179
+ throw new Error('[ReactPlugin] Cannot create MDX loader: appConfig.rootDir is required.');
180
+ }
181
+ this.mdxLoaderPlugin = createReactMdxLoaderPlugin({
182
+ compilerOptions: this.mdxCompilerOptions,
183
+ projectRoot: this.appConfig.rootDir,
184
+ });
179
185
  }
180
186
  /**
181
187
  * Prepares React's build-facing loader contributions before config build seals
@@ -220,6 +226,7 @@ export class ReactPlugin extends IntegrationPlugin {
220
226
  if (!this.hmrStrategy) {
221
227
  this.hmrStrategy = new ReactHmrStrategy({
222
228
  context: this.hmrManager.getDefaultContext(),
229
+ projectRoot: this.appConfig.rootDir,
223
230
  pageMetadataCache: this.hmrPageMetadataCache,
224
231
  runtimeManifest: this.runtimeBundleService.getRuntimeManifest('development'),
225
232
  mdxCompilerOptions: this.mdxCompilerOptions,