@ecopages/content-processor 0.2.0-beta.38 → 0.2.0-beta.39

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
@@ -23,7 +23,7 @@ The processor gives you a typed manifest and MDX components at build time. Wire
23
23
 
24
24
  ## Features
25
25
 
26
- - **Build-time scanning** — content metadata and MDX imports are resolved before page bundles ship.
26
+ - **Build-time scanning** — content metadata is resolved before page bundles ship; MDX entry modules load on demand per slug on the server.
27
27
  - **Standard Schema validation** — frontmatter schemas stay in your app; the library validates through the Standard Schema interface.
28
28
  - **Typed virtual modules** — `ecopages:content/<collection>` with generated `Entry` types.
29
29
  - **Multiple collections** — docs, blog, changelog, or any keyed collection you configure.
@@ -75,13 +75,16 @@ export default await new ConfigBuilder()
75
75
 
76
76
  ### Collection options
77
77
 
78
- | Option | Required | Description |
79
- | :----------- | :------: | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
80
- | `contentDir` | yes | Directory relative to app `srcDir`, e.g. `content/docs`. |
81
- | `schema` | yes | Standard Schema validator for frontmatter. |
82
- | `entryType` | no | Frontmatter type for generated virtual-module types. Format: `./path/to/schema#TypeName`. The processor wraps it as `ContentEntry<YourFrontmatter>`. |
83
- | `orderBy` | no | Comparator function for manifest sort. Default: {@link compareEntriesBySlug}. Use {@link compareEntriesByField} for frontmatter fields. |
84
- | `extensions` | no | File extensions to scan. Default: `['.mdx']`. |
78
+ | Option | Required | Description |
79
+ | :-------------------- | :------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
80
+ | `contentDir` | yes | Directory relative to app `srcDir`, e.g. `content/docs`. |
81
+ | `schema` | yes | Standard Schema validator for frontmatter. |
82
+ | `entryType` | no | Frontmatter type for generated virtual-module types. Format: `./path/to/schema#TypeName`. The processor wraps it as `ContentEntry<YourFrontmatter>`. |
83
+ | `orderBy` | no | Comparator function for manifest sort. Default: {@link compareEntriesBySlug}. Use {@link compareEntriesByField} for frontmatter fields. |
84
+ | `extensions` | no | File extensions to scan. Default: `['.mdx']`. |
85
+ | `routePrefix` | no | Public URL prefix for entries, e.g. `/docs`. Used with `devPrewarm`. |
86
+ | `devPrewarm` | no | Dev prewarm: `'first'`, `'all'`, `{ slugs }`, or `{ limit }`. Core SSR-prewarms after the HMR-ready pipeline exists; prewarm schedules renders only and does not control HTML cache admission. |
87
+ | `devPrewarmReadiness` | no | `'background'` (default) or `'beforeReady'` to block the framework ready signal until prewarm finishes (listen port may already be open). |
85
88
 
86
89
  Collection keys must be kebab-case (`docs`, `api-reference`). Each key becomes `ecopages:content/<key>`.
87
90
 
@@ -160,8 +163,8 @@ import type { Entry } from 'ecopages:content/docs';
160
163
  | `entries` | entries | Readonly manifest of all entries, sorted by `orderBy`. |
161
164
  | `getEntry(slug)` | entries | Lookup by joined slug, e.g. `'getting-started/intro'`. |
162
165
  | `getEntryBySegments(segments)` | entries | Lookup by segment array, e.g. `['getting-started', 'intro']`. |
163
- | `getComponent(slug)` | server | MDX component for the entry. |
164
- | `getEntryDependencies(slug)` | server | Browser dependency bag for the entry, with MDX source ownership for catch-all routes. |
166
+ | `getComponent(slug)` | server | `Promise` of the MDX component for the entry (lazy-loaded per slug). |
167
+ | `getEntryDependencies(slug)` | server | `Promise` of the browser dependency bag for the entry, with MDX source ownership. |
165
168
  | `Entry` | entries | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
166
169
 
167
170
  **Important:** `Entry` exists only in generated `.d.ts` files, not in the runtime cache module. Keep type imports on a separate `import type` line in page files that get bundled. Mixed imports like `import { entries, type Entry }` can cause the bundler to treat `Entry` as a runtime export and fail with `MISSING_EXPORT`.
@@ -191,13 +194,13 @@ export default eco.page<{ entry: Entry }>({
191
194
  props: { entry: getEntryBySegments(segments) },
192
195
  };
193
196
  },
194
- dependencies: ({ props }) => getEntryDependencies(props.entry.slug),
197
+ dependencies: async ({ props }) => getEntryDependencies(props.entry.slug),
195
198
  metadata: ({ props: { entry } }) => ({
196
199
  title: entry.title,
197
200
  description: entry.description,
198
201
  }),
199
202
  render: async ({ entry }) => {
200
- const Content = getComponent(entry.slug);
203
+ const Content = await getComponent(entry.slug);
201
204
  return <Content />;
202
205
  },
203
206
  });
@@ -219,7 +222,7 @@ export const config = {
219
222
  <WeatherApp />
220
223
  ```
221
224
 
222
- `getComponent()` returns the MDX default component with exported `config` attached. Pair that with `getEntryDependencies()` on the catch-all page so only the active entry contributes to the Page Browser Graph. The helper includes `ownerFile` so relative `scripts`, `stylesheets`, and `modules` declared in MDX resolve against the entry file, not the catch-all route.
225
+ `getComponent()` lazy-loads one MDX module per slug and returns the default component with exported `config` attached. Pair that with `getEntryDependencies()` on the catch-all page so only the active entry contributes to the Page Browser Graph. The helper includes `ownerFile` so relative `scripts`, `stylesheets`, and `modules` declared in MDX resolve against the entry file, not the catch-all route.
223
226
 
224
227
  ## Navigation (app-side)
225
228
 
@@ -269,6 +272,7 @@ const raw = await scanner.getRawContent('getting-started/intro');
269
272
  | Path | Purpose |
270
273
  | :------------------------------------------------------------------- | :----------------------------------------------------- |
271
274
  | `.eco/cache/ecopages-content-processor/<collection>.ts` | Generated collection module (manifest + MDX imports). |
275
+ | `.eco/.server-collections/<collection>/<collection>-<identity>.mjs` | Lazy-built server artifact for one collection. |
272
276
  | `node_modules/@types/ecopages-content-processor/virtual-module.d.ts` | Generated TypeScript declarations for virtual modules. |
273
277
 
274
278
  Do not edit generated files manually.
@@ -279,7 +283,7 @@ Invalid frontmatter throws `SchemaError` from `@standard-schema/utils` during sc
279
283
 
280
284
  ## Dev / HMR
281
285
 
282
- In development, the processor watches collection files to regenerate `ecopages:content/*` manifests when MDX changes. Collection MDX is still server source: Ecopages invalidates server modules and runs HMR so page imports pick up the updated MDX component.
286
+ In development, the processor watches collection files to regenerate `ecopages:content/*` manifests when MDX changes. The generated server artifact is built lazily on the first server import and reused by its content-derived identity; MDX edits invalidate that artifact before the next Page build. Collection MDX is still server source: Ecopages invalidates server modules and runs HMR so page imports pick up the updated MDX component.
283
287
 
284
288
  Watch config drives manifest regeneration only. Asset ownership (which would skip server invalidation) requires declared processor capabilities. Content-processor does not claim MDX as an asset, so no `capabilities` workaround is needed in `eco.config.ts`.
285
289
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/content-processor",
3
- "version": "0.2.0-beta.38",
3
+ "version": "0.2.0-beta.39",
4
4
  "description": "Scan MDX collections at build time and expose typed ecopages:content/* virtual modules for pages and scripts",
5
5
  "keywords": [
6
6
  "content",
@@ -17,10 +17,10 @@
17
17
  "directory": "packages/processors/content-processor"
18
18
  },
19
19
  "peerDependencies": {
20
- "@ecopages/core": "0.2.0-beta.38"
20
+ "@ecopages/core": "0.2.0-beta.39"
21
21
  },
22
22
  "dependencies": {
23
- "@ecopages/file-system": "0.2.0-beta.38",
23
+ "@ecopages/file-system": "0.2.0-beta.39",
24
24
  "@ecopages/logger": "^0.2.3",
25
25
  "remark-frontmatter": "^5.0.0",
26
26
  "unified": "^11.0.5",
package/src/codegen.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ContentEntry } from './types.js';
2
2
  export declare function renderCollectionEntriesModule(collectionName: string, manifest: ContentEntry[]): string;
3
- export declare function renderCollectionComponentsModule(collectionName: string, outputDir: string, entrySources: Array<{
3
+ export declare function renderCollectionComponentsModule(_collectionName: string, outputDir: string, entrySources: Array<{
4
4
  entry: ContentEntry;
5
5
  filePath: string;
6
6
  }>): string;
package/src/codegen.js CHANGED
@@ -1,7 +1,4 @@
1
1
  import { relative, resolve, dirname, join } from 'node:path';
2
- function slugToIdentifier(collectionName, slug) {
3
- return `${collectionName}_${slug.replace(/[^a-zA-Z0-9]/g, '_')}`;
4
- }
5
2
  function serializeEntry(entry) {
6
3
  return JSON.stringify(entry);
7
4
  }
@@ -53,16 +50,16 @@ function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComp
53
50
  ) as EcoComponent<Record<string, unknown>>;
54
51
 
55
52
  if (module.config) {
56
- component.config = {
53
+ const moduleIdentity = getComponentIdentity(module.config);
54
+ const componentIdentity = getComponentIdentity(component);
55
+ component.config = bindComponentIdentity({
56
+ id: moduleIdentity?.id ?? componentIdentity?.id ?? sourceFile,
57
+ file: sourceFile,
58
+ integration: moduleIdentity?.integration ?? componentIdentity?.integration ?? 'content',
59
+ }, {
57
60
  ...component.config,
58
61
  ...module.config,
59
- __eco: {
60
- ...(component.config?.__eco ?? module.config.__eco),
61
- id: module.config.__eco?.id ?? component.config?.__eco?.id ?? sourceFile,
62
- file: sourceFile,
63
- integration: module.config.__eco?.integration ?? component.config?.__eco?.integration ?? 'content',
64
- },
65
- };
62
+ });
66
63
  }
67
64
 
68
65
  if (module.getMetadata) {
@@ -73,43 +70,65 @@ function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComp
73
70
  }
74
71
  `;
75
72
  }
76
- export function renderCollectionComponentsModule(collectionName, outputDir, entrySources) {
77
- const importLines = [];
78
- const componentMapLines = [];
73
+ export function renderCollectionComponentsModule(_collectionName, outputDir, entrySources) {
74
+ const loaderLines = [];
79
75
  const entrySourceFilesBySlugLines = [];
80
76
  for (const { entry, filePath } of entrySources) {
81
- const identifier = slugToIdentifier(collectionName, entry.slug);
82
77
  const importPath = relative(outputDir, filePath).split('\\').join('/');
78
+ const escapedImportPath = importPath.replace(/'/g, "\\'");
83
79
  const sourceFile = filePath.split('\\').join('/');
84
80
  const escapedSourceFile = sourceFile.replace(/'/g, "\\'");
85
- importLines.push(`import * as ${identifier}_module from '${importPath}';`);
86
- componentMapLines.push(`\t'${entry.slug}': attachMdxExports(${identifier}_module, '${escapedSourceFile}'),`);
81
+ loaderLines.push(`\t'${entry.slug}': () => import('${escapedImportPath}'),`);
87
82
  entrySourceFilesBySlugLines.push(`\t'${entry.slug}': '${escapedSourceFile}',`);
88
83
  }
89
84
  return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
90
85
 
91
- import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
86
+ import { bindComponentIdentity, getComponentIdentity, type EcoComponent, type PageDependenciesResult } from '@ecopages/core';
92
87
 
93
88
  ${renderAttachMdxExportsHelper()}
94
89
 
95
- ${importLines.join('\n')}
96
-
97
- const componentsBySlug: Record<string, EcoComponent<Record<string, unknown>>> = {
98
- ${componentMapLines.join('\n')}
90
+ const loadersBySlug: Record<string, () => Promise<ContentMdxModule>> = {
91
+ ${loaderLines.join('\n')}
99
92
  };
100
93
 
101
94
  const entrySourceFilesBySlug: Record<string, string> = {
102
95
  ${entrySourceFilesBySlugLines.join('\n')}
103
96
  };
104
97
 
105
- export function getComponent(slug: string): EcoComponent<Record<string, unknown>> {
106
- const component = componentsBySlug[slug];
107
- if (!component) throw new Error(\`Unknown content entry: \${slug}\`);
108
- return component;
98
+ const componentCache = new Map<string, EcoComponent<Record<string, unknown>>>();
99
+ const componentLoadPromises = new Map<string, Promise<EcoComponent<Record<string, unknown>>>>();
100
+
101
+ export async function getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>> {
102
+ const cached = componentCache.get(slug);
103
+ if (cached) {
104
+ return cached;
105
+ }
106
+
107
+ const pending = componentLoadPromises.get(slug);
108
+ if (pending) {
109
+ return pending;
110
+ }
111
+
112
+ const load = loadersBySlug[slug];
113
+ if (!load) {
114
+ throw new Error(\`Unknown content entry: \${slug}\`);
115
+ }
116
+
117
+ const loadPromise = (async () => {
118
+ const module = await load();
119
+ const component = attachMdxExports(module, entrySourceFilesBySlug[slug]!);
120
+ componentCache.set(slug, component);
121
+ return component;
122
+ })().finally(() => {
123
+ componentLoadPromises.delete(slug);
124
+ });
125
+
126
+ componentLoadPromises.set(slug, loadPromise);
127
+ return loadPromise;
109
128
  }
110
129
 
111
- export function getEntryDependencies(slug: string): PageDependenciesResult | undefined {
112
- const component = getComponent(slug);
130
+ export async function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined> {
131
+ const component = await getComponent(slug);
113
132
  const dependencies = component.config?.dependencies;
114
133
  if (!dependencies) {
115
134
  return undefined;
@@ -157,8 +176,8 @@ function renderCollectionComponentsTypesModule(collectionName) {
157
176
  return `declare module "ecopages:content/${collectionName}/server" {
158
177
  import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
159
178
 
160
- export function getComponent(slug: string): EcoComponent<Record<string, unknown>>;
161
- export function getEntryDependencies(slug: string): PageDependenciesResult | undefined;
179
+ export function getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
180
+ export function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
162
181
  }`;
163
182
  }
164
183
  export function renderCollectionTypesModule(collectionName, entryType, typeResolution) {
@@ -18,6 +18,27 @@ export type ContentCollectionDefinition<TFrontmatter extends Record<string, unkn
18
18
  * Format: `./path/to/schema-file#ExportedTypeName`
19
19
  */
20
20
  entryType?: string;
21
+ /**
22
+ * Public URL prefix for entries in this collection, e.g. `/docs`.
23
+ * Used with {@link ContentDevPrewarmConfig} to build dev prewarm paths.
24
+ */
25
+ routePrefix?: string;
26
+ /**
27
+ * Which entries to SSR-prewarm in dev when {@link routePrefix} is set.
28
+ * Rendering is performed by core; this only declares pathnames from the manifest.
29
+ */
30
+ devPrewarm?: ContentDevPrewarmConfig;
31
+ /**
32
+ * When `beforeReady`, core awaits SSR prewarm for declared paths before the dev server reports ready.
33
+ * @default 'background'
34
+ */
35
+ devPrewarmReadiness?: 'background' | 'beforeReady';
36
+ };
37
+ /** Dev prewarm selection for a content collection manifest. */
38
+ export type ContentDevPrewarmConfig = 'first' | 'all' | {
39
+ slugs: readonly string[];
40
+ } | {
41
+ limit: number;
21
42
  };
22
43
  /**
23
44
  * Collection registry keyed by collection name.
@@ -1,10 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export declare const CONTENT_PROCESSOR_NAME = "ecopages-content-processor";
3
- /** Virtual module prefix for collection imports, e.g. `ecopages:content/docs`. */
4
- export declare const CONTENT_VIRTUAL_MODULE_PREFIX = "ecopages:content";
5
- /** Matches `ecopages:content/<collection>` metadata specifiers (no MDX imports). */
6
- export declare const CONTENT_VIRTUAL_MODULE_PATTERN: RegExp;
7
- /** Matches `ecopages:content/<collection>/server` component resolver specifiers (MDX imports). */
8
- export declare const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN: RegExp;
3
+ export { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
9
4
  /** Validates collection keys used in processor options and virtual module paths. */
10
5
  export declare const COLLECTION_NAME_PATTERN: RegExp;
package/src/constants.js CHANGED
@@ -1,10 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export const CONTENT_PROCESSOR_NAME = 'ecopages-content-processor';
3
- /** Virtual module prefix for collection imports, e.g. `ecopages:content/docs`. */
4
- export const CONTENT_VIRTUAL_MODULE_PREFIX = 'ecopages:content';
5
- /** Matches `ecopages:content/<collection>` metadata specifiers (no MDX imports). */
6
- export const CONTENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]*$/;
7
- /** Matches `ecopages:content/<collection>/server` component resolver specifiers (MDX imports). */
8
- export const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/server$/;
3
+ export { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
9
4
  /** Validates collection keys used in processor options and virtual module paths. */
10
5
  export const COLLECTION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
@@ -1,12 +1,11 @@
1
1
  import type { EcoBuildPlugin } from '@ecopages/core/plugins/processor';
2
- export type ParsedCollectionSpecifier = {
3
- collectionName: string;
4
- variant: 'entries' | 'server';
5
- };
2
+ import { type ParsedCollectionSpecifier } from './constants.js';
3
+ export type { ParsedCollectionSpecifier };
4
+ export { parseCollectionSpecifier } from './constants.js';
5
+ export type EnsureCollectionServerArtifact = (collectionName: string) => Promise<void>;
6
6
  export declare function parseCollectionName(specifier: string): string | null;
7
- export declare function parseCollectionSpecifier(specifier: string): ParsedCollectionSpecifier | null;
8
- export declare function resolveCollectionPath(specifier: string, collectionModules: Record<string, string>, collectionServerModules: Record<string, string>): string | null;
9
- export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>): EcoBuildPlugin;
10
- export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>): EcoBuildPlugin;
7
+ export declare function resolveCollectionPath(specifier: string, collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>): string | null;
8
+ export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, ensureCollectionServerArtifact?: EnsureCollectionServerArtifact): EcoBuildPlugin;
9
+ export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>): EcoBuildPlugin;
11
10
  export declare function getCollectionCachePath(cacheDir: string, collectionName: string): string;
12
11
  export declare function getCollectionServerCachePath(cacheDir: string, collectionName: string): string;
@@ -1,45 +1,28 @@
1
1
  import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
- import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN } from './constants.js';
3
+ import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, parseCollectionSpecifier, } from './constants.js';
4
+ export { parseCollectionSpecifier } from './constants.js';
4
5
  export function parseCollectionName(specifier) {
5
6
  const parsed = parseCollectionSpecifier(specifier);
6
7
  return parsed?.collectionName ?? null;
7
8
  }
8
- export function parseCollectionSpecifier(specifier) {
9
- const normalized = specifier.startsWith('ecopages:content/')
10
- ? specifier.slice('ecopages:content/'.length)
11
- : specifier.startsWith('content/')
12
- ? specifier.slice('content/'.length)
13
- : null;
14
- if (!normalized) {
15
- return null;
16
- }
17
- if (normalized.endsWith('/server')) {
18
- return {
19
- collectionName: normalized.slice(0, -'/server'.length),
20
- variant: 'server',
21
- };
22
- }
23
- return {
24
- collectionName: normalized,
25
- variant: 'entries',
26
- };
27
- }
28
- export function resolveCollectionPath(specifier, collectionModules, collectionServerModules) {
9
+ export function resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules) {
29
10
  const parsed = parseCollectionSpecifier(specifier);
30
11
  if (!parsed) {
31
12
  return null;
32
13
  }
33
14
  if (parsed.variant === 'server') {
34
- return collectionServerModules[parsed.collectionName] ?? null;
15
+ return (collectionServerCompiledModules?.[parsed.collectionName] ??
16
+ collectionServerModules[parsed.collectionName] ??
17
+ null);
35
18
  }
36
19
  return collectionModules[parsed.collectionName] ?? null;
37
20
  }
38
- function createContentResolvePlugin(collectionModules, collectionServerModules, options) {
21
+ function createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact, options) {
39
22
  return {
40
23
  name: 'ecopages:content',
41
24
  setup(build) {
42
- const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules);
25
+ const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules);
43
26
  build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, (args) => {
44
27
  const modulePath = resolveCollection(args.path);
45
28
  if (!modulePath) {
@@ -54,7 +37,17 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
54
37
  return { path: modulePath };
55
38
  });
56
39
  if (options.includeServerModules !== false) {
57
- build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => {
40
+ build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, async (args) => {
41
+ const parsed = parseCollectionSpecifier(args.path);
42
+ if (parsed?.variant === 'server' && !collectionServerCompiledModules?.[parsed.collectionName]) {
43
+ await ensureCollectionServerArtifact?.(parsed.collectionName);
44
+ }
45
+ const compiledPath = parsed?.variant === 'server'
46
+ ? collectionServerCompiledModules?.[parsed.collectionName]
47
+ : undefined;
48
+ if (compiledPath && options.externalizeCompiledServerModules) {
49
+ return { path: compiledPath, external: true };
50
+ }
58
51
  const modulePath = resolveCollection(args.path);
59
52
  if (!modulePath) {
60
53
  return undefined;
@@ -71,13 +64,11 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
71
64
  },
72
65
  };
73
66
  }
74
- export function createContentPlugin(collectionModules, collectionServerModules) {
75
- return createContentResolvePlugin(collectionModules, collectionServerModules, {
76
- includeServerModules: true,
77
- });
67
+ export function createContentPlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact) {
68
+ return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact, { includeServerModules: true, externalizeCompiledServerModules: true });
78
69
  }
79
- export function createContentPluginBundler(collectionModules, collectionServerModules) {
80
- const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, {
70
+ export function createContentPluginBundler(collectionModules, collectionServerModules, collectionServerCompiledModules) {
71
+ const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, undefined, {
81
72
  namespace: 'ecopages-content',
82
73
  includeServerModules: false,
83
74
  });
@@ -48,7 +48,10 @@ export class ContentScanner {
48
48
  slug,
49
49
  segments: slug.split('/'),
50
50
  };
51
- return { filePath, entry };
51
+ return {
52
+ filePath,
53
+ entry,
54
+ };
52
55
  }));
53
56
  files.sort((a, b) => this.orderBy(a.entry, b.entry));
54
57
  const filePathsBySlug = new Map();
@@ -3,7 +3,7 @@ import type { EcoBuildPlugin } from '@ecopages/core/plugins/processor';
3
3
  * Keeps `ecopages:content/<collection>/server` out of browser bundles.
4
4
  *
5
5
  * @remarks
6
- * Server modules static-import every MDX entry for `getComponent`. Browser builds
6
+ * Server modules lazy-load MDX entries via dynamic `import()` for `getComponent`. Browser builds
7
7
  * must never follow that graph — highlighted MDX output belongs in SSR HTML only.
8
8
  */
9
9
  export declare function createContentServerBoundaryPlugin(): EcoBuildPlugin;
@@ -3,7 +3,7 @@ import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN } from './constants.js';
3
3
  * Keeps `ecopages:content/<collection>/server` out of browser bundles.
4
4
  *
5
5
  * @remarks
6
- * Server modules static-import every MDX entry for `getComponent`. Browser builds
6
+ * Server modules lazy-load MDX entries via dynamic `import()` for `getComponent`. Browser builds
7
7
  * must never follow that graph — highlighted MDX output belongs in SSR HTML only.
8
8
  */
9
9
  export function createContentServerBoundaryPlugin() {
@@ -0,0 +1,10 @@
1
+ import type { ContentEntry } from './types.js';
2
+ import type { ContentCollectionDefinition, ContentDevPrewarmConfig } from './collection-types.js';
3
+ /**
4
+ * Resolves entry slugs to prewarm for one collection from processor config.
5
+ */
6
+ export declare function resolveContentDevPrewarmSlugs<T extends Record<string, unknown>>(config: ContentDevPrewarmConfig, entries: readonly ContentEntry<T>[]): string[];
7
+ /**
8
+ * Builds absolute URL pathnames for dev prewarm from collection config and manifest order.
9
+ */
10
+ export declare function buildContentDevPrewarmPathnames<T extends Record<string, unknown>>(definition: Pick<ContentCollectionDefinition<T>, 'routePrefix' | 'devPrewarm'>, entries: readonly ContentEntry<T>[]): string[];
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Resolves entry slugs to prewarm for one collection from processor config.
3
+ */
4
+ export function resolveContentDevPrewarmSlugs(config, entries) {
5
+ if (config === 'first') {
6
+ const first = entries[0];
7
+ return first ? [first.slug] : [];
8
+ }
9
+ if (config === 'all') {
10
+ return entries.map((entry) => entry.slug);
11
+ }
12
+ if ('slugs' in config) {
13
+ return [...config.slugs];
14
+ }
15
+ if ('limit' in config) {
16
+ return entries.slice(0, Math.max(0, config.limit)).map((entry) => entry.slug);
17
+ }
18
+ return [];
19
+ }
20
+ /**
21
+ * Builds absolute URL pathnames for dev prewarm from collection config and manifest order.
22
+ */
23
+ export function buildContentDevPrewarmPathnames(definition, entries) {
24
+ if (!definition.devPrewarm || !definition.routePrefix) {
25
+ return [];
26
+ }
27
+ const prefix = definition.routePrefix.replace(/\/$/, '');
28
+ const slugs = resolveContentDevPrewarmSlugs(definition.devPrewarm, entries);
29
+ return slugs.map((slug) => `${prefix}/${slug}`.replace(/\/{2,}/g, '/'));
30
+ }
package/src/plugin.d.ts CHANGED
@@ -11,6 +11,8 @@ import type { ContentProcessorConfig } from './collection-types.js';
11
11
  export declare class ContentProcessorPlugin extends Processor<ContentProcessorConfig> {
12
12
  private collectionsGenerated;
13
13
  private readonly scanners;
14
+ private readonly collectionBuildPromises;
15
+ private readonly collectionGenerations;
14
16
  /**
15
17
  * Absolute paths to generated collection entry modules, keyed by collection name.
16
18
  * Virtual-module plugins close over this object so mutations stay live.
@@ -20,6 +22,10 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
20
22
  * Absolute paths to generated server-only component resolver modules.
21
23
  */
22
24
  readonly collectionServerModules: Record<string, string>;
25
+ /**
26
+ * Absolute paths to pre-built collection server artifacts for route-module externalization.
27
+ */
28
+ readonly collectionServerCompiledModules: Record<string, string>;
23
29
  constructor(config: Omit<ProcessorConfig<ContentProcessorConfig>, 'name' | 'description'>);
24
30
  get buildPlugins(): EcoBuildPlugin[];
25
31
  get plugins(): EcoBuildPlugin[];
@@ -34,9 +40,29 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
34
40
  private handleContentFileEvent;
35
41
  private initializeWatchPaths;
36
42
  private generateTypes;
43
+ private buildCollectionServerArtifact;
44
+ /**
45
+ * Builds one collection artifact on demand when a server build first resolves it.
46
+ *
47
+ * @remarks
48
+ * Startup only generates the small virtual modules. The expensive MDX bundle is
49
+ * single-flight and starts after the server is listening, while concurrent Page
50
+ * builds share the same promise.
51
+ */
52
+ ensureCollectionServerArtifact(collectionName: string): Promise<void>;
37
53
  private ensureCollectionsGenerated;
38
54
  prepareBuildContributions(): Promise<void>;
39
55
  setup(): Promise<void>;
40
56
  process(_input: unknown): Promise<void>;
57
+ /**
58
+ * Declares watch-mode SSR prewarm pathnames and readiness derived from collection manifests.
59
+ *
60
+ * @remarks
61
+ * Core executes rendering in parallel; this hook only maps `routePrefix` + entry slugs to URLs.
62
+ */
63
+ collectDevPrewarmPlan(): Promise<{
64
+ pathnames: readonly string[];
65
+ readiness: 'background' | 'beforeReady';
66
+ }>;
41
67
  }
42
68
  export declare const contentProcessorPlugin: (config: Omit<ProcessorConfig<ContentProcessorConfig>, "name" | "description">) => ContentProcessorPlugin;
package/src/plugin.js CHANGED
@@ -12,6 +12,8 @@ import { ContentScanner } from './content-scanner.js';
12
12
  import { createContentPlugin, createContentPluginBundler, getCollectionCachePath, getCollectionServerCachePath, } from './content-plugins.js';
13
13
  import { createContentServerBoundaryPlugin } from './content-server-boundary-plugin.js';
14
14
  import { COLLECTION_NAME_PATTERN, CONTENT_PROCESSOR_NAME } from './constants.js';
15
+ import { buildContentDevPrewarmPathnames } from './dev-prewarm-paths.js';
16
+ import { buildCollectionServerModule } from '@ecopages/core/services/module-loading/collection-server-module-build.service';
15
17
  const logger = new Logger('[@ecopages/content-processor]', {
16
18
  debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true',
17
19
  });
@@ -27,6 +29,8 @@ function assertValidCollectionName(collectionName) {
27
29
  export class ContentProcessorPlugin extends Processor {
28
30
  collectionsGenerated = false;
29
31
  scanners = new Map();
32
+ collectionBuildPromises = new Map();
33
+ collectionGenerations = new Map();
30
34
  /**
31
35
  * Absolute paths to generated collection entry modules, keyed by collection name.
32
36
  * Virtual-module plugins close over this object so mutations stay live.
@@ -36,6 +40,10 @@ export class ContentProcessorPlugin extends Processor {
36
40
  * Absolute paths to generated server-only component resolver modules.
37
41
  */
38
42
  collectionServerModules = {};
43
+ /**
44
+ * Absolute paths to pre-built collection server artifacts for route-module externalization.
45
+ */
46
+ collectionServerCompiledModules = {};
39
47
  constructor(config) {
40
48
  const defaultWatchConfig = {
41
49
  paths: [],
@@ -54,11 +62,13 @@ export class ContentProcessorPlugin extends Processor {
54
62
  get buildPlugins() {
55
63
  return [
56
64
  createContentServerBoundaryPlugin(),
57
- createContentPluginBundler(this.collectionModules, this.collectionServerModules),
65
+ createContentPluginBundler(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules),
58
66
  ];
59
67
  }
60
68
  get plugins() {
61
- return [createContentPlugin(this.collectionModules, this.collectionServerModules)];
69
+ return [
70
+ createContentPlugin(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, (collectionName) => this.ensureCollectionServerArtifact(collectionName)),
71
+ ];
62
72
  }
63
73
  getCollectionsConfig() {
64
74
  if (!this.options?.collections) {
@@ -119,6 +129,8 @@ export class ContentProcessorPlugin extends Processor {
119
129
  this.writeGeneratedFile(serverOutputFile, componentsOutput);
120
130
  this.collectionModules[collectionName] = outputFile;
121
131
  this.collectionServerModules[collectionName] = serverOutputFile;
132
+ delete this.collectionServerCompiledModules[collectionName];
133
+ this.collectionGenerations.set(collectionName, (this.collectionGenerations.get(collectionName) ?? 0) + 1);
122
134
  logger.debug('Generated content collection module', {
123
135
  collectionName,
124
136
  outputFile,
@@ -214,6 +226,61 @@ export class ContentProcessorPlugin extends Processor {
214
226
  });
215
227
  this.writeGeneratedFile(indexTypesDir, 'import "./virtual-module.d.js";\n');
216
228
  }
229
+ async buildCollectionServerArtifact(collectionName, serverOutputFile, ownedSourcePaths) {
230
+ if (!this.context?.config.runtime?.buildRuntime) {
231
+ return;
232
+ }
233
+ const artifact = await buildCollectionServerModule({
234
+ appConfig: this.context.config,
235
+ collectionName,
236
+ sourceFilePath: serverOutputFile,
237
+ ownedSourcePaths,
238
+ });
239
+ this.collectionServerCompiledModules[collectionName] = artifact.outputPath;
240
+ }
241
+ /**
242
+ * Builds one collection artifact on demand when a server build first resolves it.
243
+ *
244
+ * @remarks
245
+ * Startup only generates the small virtual modules. The expensive MDX bundle is
246
+ * single-flight and starts after the server is listening, while concurrent Page
247
+ * builds share the same promise.
248
+ */
249
+ async ensureCollectionServerArtifact(collectionName) {
250
+ if (!this.context?.config.runtime?.buildRuntime) {
251
+ return;
252
+ }
253
+ if (this.collectionServerCompiledModules[collectionName]) {
254
+ return;
255
+ }
256
+ const inFlight = this.collectionBuildPromises.get(collectionName);
257
+ if (inFlight) {
258
+ await inFlight;
259
+ if (!this.collectionServerCompiledModules[collectionName]) {
260
+ await this.ensureCollectionServerArtifact(collectionName);
261
+ }
262
+ return;
263
+ }
264
+ const generation = this.collectionGenerations.get(collectionName) ?? 0;
265
+ const serverOutputFile = this.collectionServerModules[collectionName];
266
+ if (!serverOutputFile) {
267
+ throw new Error(`Unknown content collection: ${collectionName}`);
268
+ }
269
+ const scanner = this.scanners.get(collectionName);
270
+ const ownedSourcePaths = scanner ? (await scanner.getEntrySources()).map(({ filePath }) => filePath) : [];
271
+ const buildPromise = this.buildCollectionServerArtifact(collectionName, serverOutputFile, ownedSourcePaths)
272
+ .then(() => {
273
+ if (generation !== (this.collectionGenerations.get(collectionName) ?? 0)) {
274
+ delete this.collectionServerCompiledModules[collectionName];
275
+ }
276
+ })
277
+ .finally(() => this.collectionBuildPromises.delete(collectionName));
278
+ this.collectionBuildPromises.set(collectionName, buildPromise);
279
+ await buildPromise;
280
+ if (!this.collectionServerCompiledModules[collectionName]) {
281
+ await this.ensureCollectionServerArtifact(collectionName);
282
+ }
283
+ }
217
284
  async ensureCollectionsGenerated() {
218
285
  if (this.collectionsGenerated) {
219
286
  return;
@@ -231,6 +298,32 @@ export class ContentProcessorPlugin extends Processor {
231
298
  async process(_input) {
232
299
  await this.regenerateAllCollections();
233
300
  }
301
+ /**
302
+ * Declares watch-mode SSR prewarm pathnames and readiness derived from collection manifests.
303
+ *
304
+ * @remarks
305
+ * Core executes rendering in parallel; this hook only maps `routePrefix` + entry slugs to URLs.
306
+ */
307
+ async collectDevPrewarmPlan() {
308
+ await this.ensureCollectionsGenerated();
309
+ const pathnames = [];
310
+ let readiness = 'background';
311
+ for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
312
+ if (definition.devPrewarmReadiness === 'beforeReady') {
313
+ readiness = 'beforeReady';
314
+ }
315
+ if (!definition.devPrewarm || !definition.routePrefix) {
316
+ continue;
317
+ }
318
+ const scanner = this.getOrCreateScanner(collectionName);
319
+ const entries = await scanner.getManifest();
320
+ pathnames.push(...buildContentDevPrewarmPathnames(definition, entries));
321
+ }
322
+ return {
323
+ pathnames: [...new Set(pathnames)],
324
+ readiness,
325
+ };
326
+ }
234
327
  }
235
328
  export const contentProcessorPlugin = (config) => {
236
329
  return new ContentProcessorPlugin(config);
package/src/types.d.ts CHANGED
@@ -21,8 +21,8 @@ export type ContentCollectionEntriesModule<TEntry extends Record<string, unknown
21
21
  };
22
22
  /** Runtime shape of a generated `ecopages:content/<collection>/server` module. */
23
23
  export type ContentCollectionComponentsModule = {
24
- getComponent(slug: string): EcoComponent<Record<string, unknown>>;
25
- getEntryDependencies(slug: string): PageDependenciesResult | undefined;
24
+ getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
25
+ getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
26
26
  };
27
27
  /** @deprecated Import entries and server modules separately. */
28
28
  export type ContentCollectionModule<TEntry extends Record<string, unknown> = Record<string, unknown>> = ContentCollectionEntriesModule<TEntry> & ContentCollectionComponentsModule;