@ecopages/content-processor 0.2.0-beta.37 → 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
 
@@ -147,20 +150,22 @@ Run `ecopages dev` or `ecopages build` before expecting IDE types. Restart the T
147
150
 
148
151
  ## Virtual module API
149
152
 
150
- Each collection exposes `ecopages:content/<collection>`:
153
+ Each collection exposes `ecopages:content/<collection>` for metadata and `ecopages:content/<collection>/server` for MDX components:
151
154
 
152
155
  ```typescript
153
- import { entries, getEntry, getEntryBySegments, getComponent } from 'ecopages:content/docs';
156
+ import { entries, getEntry, getEntryBySegments } from 'ecopages:content/docs';
157
+ import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
154
158
  import type { Entry } from 'ecopages:content/docs';
155
159
  ```
156
160
 
157
- | Export | Description |
158
- | :----------------------------- | :---------------------------------------------------------------------------------------------- |
159
- | `entries` | Readonly manifest of all entries, sorted by `orderBy`. |
160
- | `getEntry(slug)` | Lookup by joined slug, e.g. `'getting-started/intro'`. |
161
- | `getEntryBySegments(segments)` | Lookup by segment array, e.g. `['getting-started', 'intro']`. |
162
- | `getComponent(slug)` | MDX component for the entry. |
163
- | `Entry` | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
161
+ | Export | Module | Description |
162
+ | :----------------------------- | :------ | :---------------------------------------------------------------------------------------------- |
163
+ | `entries` | entries | Readonly manifest of all entries, sorted by `orderBy`. |
164
+ | `getEntry(slug)` | entries | Lookup by joined slug, e.g. `'getting-started/intro'`. |
165
+ | `getEntryBySegments(segments)` | entries | Lookup by segment array, e.g. `['getting-started', 'intro']`. |
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. |
168
+ | `Entry` | entries | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
164
169
 
165
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`.
166
171
 
@@ -170,7 +175,8 @@ Define a catch-all or per-entry route with `eco.page`. Import the collection man
170
175
 
171
176
  ```typescript
172
177
  import { eco } from '@ecopages/core';
173
- import { entries, getComponent, getEntryBySegments } from 'ecopages:content/docs';
178
+ import { entries, getEntryBySegments } from 'ecopages:content/docs';
179
+ import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
174
180
  import type { Entry } from 'ecopages:content/docs';
175
181
 
176
182
  export default eco.page<{ entry: Entry }>({
@@ -188,17 +194,36 @@ export default eco.page<{ entry: Entry }>({
188
194
  props: { entry: getEntryBySegments(segments) },
189
195
  };
190
196
  },
197
+ dependencies: async ({ props }) => getEntryDependencies(props.entry.slug),
191
198
  metadata: ({ props: { entry } }) => ({
192
199
  title: entry.title,
193
200
  description: entry.description,
194
201
  }),
195
202
  render: async ({ entry }) => {
196
- const Content = getComponent(entry.slug);
203
+ const Content = await getComponent(entry.slug);
197
204
  return <Content />;
198
205
  },
199
206
  });
200
207
  ```
201
208
 
209
+ Content MDX entries may declare interactive demo dependencies without polluting the catch-all page shell:
210
+
211
+ ```mdx
212
+ import { WeatherApp } from '@/components/weather-app/weather-app';
213
+
214
+ export const config = {
215
+ dependencies: {
216
+ components: [WeatherApp],
217
+ },
218
+ };
219
+
220
+ # Weather app
221
+
222
+ <WeatherApp />
223
+ ```
224
+
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.
226
+
202
227
  ## Navigation (app-side)
203
228
 
204
229
  Navigation is app code. Map `entries` to links using the frontmatter and path fields the processor already validated:
@@ -247,6 +272,7 @@ const raw = await scanner.getRawContent('getting-started/intro');
247
272
  | Path | Purpose |
248
273
  | :------------------------------------------------------------------- | :----------------------------------------------------- |
249
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. |
250
276
  | `node_modules/@types/ecopages-content-processor/virtual-module.d.ts` | Generated TypeScript declarations for virtual modules. |
251
277
 
252
278
  Do not edit generated files manually.
@@ -257,7 +283,7 @@ Invalid frontmatter throws `SchemaError` from `@standard-schema/utils` during sc
257
283
 
258
284
  ## Dev / HMR
259
285
 
260
- 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.
261
287
 
262
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`.
263
289
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/content-processor",
3
- "version": "0.2.0-beta.37",
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.37"
20
+ "@ecopages/core": "0.2.0-beta.39"
21
21
  },
22
22
  "dependencies": {
23
- "@ecopages/file-system": "0.2.0-beta.37",
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
  }
@@ -38,29 +35,109 @@ export function getEntryBySegments(segments: string[]) {
38
35
  }
39
36
  `;
40
37
  }
41
- export function renderCollectionComponentsModule(collectionName, outputDir, entrySources) {
42
- const importLines = [];
43
- const componentMapLines = [];
38
+ function renderAttachMdxExportsHelper() {
39
+ return `type ContentMdxModule = {
40
+ default: EcoComponent<Record<string, unknown>>;
41
+ config?: EcoComponent<Record<string, unknown>>['config'];
42
+ getMetadata?: EcoComponent<Record<string, unknown>>['metadata'];
43
+ };
44
+
45
+ function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComponent<Record<string, unknown>> {
46
+ const Page = module.default;
47
+ const component = Object.assign(
48
+ (props: Record<string, unknown>) => Page(props),
49
+ Page,
50
+ ) as EcoComponent<Record<string, unknown>>;
51
+
52
+ if (module.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
+ }, {
60
+ ...component.config,
61
+ ...module.config,
62
+ });
63
+ }
64
+
65
+ if (module.getMetadata) {
66
+ component.metadata = module.getMetadata;
67
+ }
68
+
69
+ return component;
70
+ }
71
+ `;
72
+ }
73
+ export function renderCollectionComponentsModule(_collectionName, outputDir, entrySources) {
74
+ const loaderLines = [];
75
+ const entrySourceFilesBySlugLines = [];
44
76
  for (const { entry, filePath } of entrySources) {
45
- const identifier = slugToIdentifier(collectionName, entry.slug);
46
77
  const importPath = relative(outputDir, filePath).split('\\').join('/');
47
- importLines.push(`import ${identifier} from '${importPath}';`);
48
- componentMapLines.push(`\t'${entry.slug}': ${identifier},`);
78
+ const escapedImportPath = importPath.replace(/'/g, "\\'");
79
+ const sourceFile = filePath.split('\\').join('/');
80
+ const escapedSourceFile = sourceFile.replace(/'/g, "\\'");
81
+ loaderLines.push(`\t'${entry.slug}': () => import('${escapedImportPath}'),`);
82
+ entrySourceFilesBySlugLines.push(`\t'${entry.slug}': '${escapedSourceFile}',`);
49
83
  }
50
84
  return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
51
85
 
52
- import type { EcoComponent } from '@ecopages/core';
86
+ import { bindComponentIdentity, getComponentIdentity, type EcoComponent, type PageDependenciesResult } from '@ecopages/core';
53
87
 
54
- ${importLines.join('\n')}
88
+ ${renderAttachMdxExportsHelper()}
55
89
 
56
- const componentsBySlug: Record<string, EcoComponent<Record<string, unknown>>> = {
57
- ${componentMapLines.join('\n')}
90
+ const loadersBySlug: Record<string, () => Promise<ContentMdxModule>> = {
91
+ ${loaderLines.join('\n')}
58
92
  };
59
93
 
60
- export function getComponent(slug: string): EcoComponent<Record<string, unknown>> {
61
- const component = componentsBySlug[slug];
62
- if (!component) throw new Error(\`Unknown content entry: \${slug}\`);
63
- return component;
94
+ const entrySourceFilesBySlug: Record<string, string> = {
95
+ ${entrySourceFilesBySlugLines.join('\n')}
96
+ };
97
+
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;
128
+ }
129
+
130
+ export async function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined> {
131
+ const component = await getComponent(slug);
132
+ const dependencies = component.config?.dependencies;
133
+ if (!dependencies) {
134
+ return undefined;
135
+ }
136
+
137
+ return {
138
+ ...dependencies,
139
+ ownerFile: entrySourceFilesBySlug[slug],
140
+ };
64
141
  }
65
142
  `;
66
143
  }
@@ -97,9 +174,10 @@ function renderCollectionEntriesTypesModule(collectionName, entryType, typeResol
97
174
  }
98
175
  function renderCollectionComponentsTypesModule(collectionName) {
99
176
  return `declare module "ecopages:content/${collectionName}/server" {
100
- import type { EcoComponent } from '@ecopages/core';
177
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
101
178
 
102
- export function getComponent(slug: string): EcoComponent<Record<string, unknown>>;
179
+ export function getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
180
+ export function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
103
181
  }`;
104
182
  }
105
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
  });
@@ -9,6 +9,7 @@ export type ContentScannerConfig<T extends Record<string, unknown> = Record<stri
9
9
  orderBy?: EntryComparator<T>;
10
10
  extensions?: string[];
11
11
  };
12
+ export type ContentEntryPathUpdateResult = 'no-op' | 'manifest' | 'structure';
12
13
  /**
13
14
  * Scans a content directory and exposes manifest metadata plus source file paths.
14
15
  * Used by the content processor at build time; it does not belong in page bundles.
@@ -30,4 +31,15 @@ export declare class ContentScanner<T extends Record<string, unknown> = Record<s
30
31
  entry: ContentEntry<T>;
31
32
  filePath: string;
32
33
  }>>;
34
+ /**
35
+ * Re-parses one content file and updates the in-memory manifest.
36
+ *
37
+ * @remarks
38
+ * Returns `no-op` when only the MDX body changed so callers can skip
39
+ * rewriting generated collection modules during dev HMR.
40
+ */
41
+ updateEntryForPath(filePath: string, event: 'change' | 'delete'): Promise<ContentEntryPathUpdateResult>;
42
+ private findSlugForFilePath;
43
+ private removeEntryAtPath;
44
+ private upsertEntryAtPath;
33
45
  }
@@ -1,4 +1,4 @@
1
- import { join, sep } from 'node:path';
1
+ import { join, relative, resolve, sep } from 'node:path';
2
2
  import { validateStandardSchema } from '@ecopages/core';
3
3
  import { VFile } from 'vfile';
4
4
  import { matter } from 'vfile-matter';
@@ -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();
@@ -84,4 +87,68 @@ export class ContentScanner {
84
87
  filePath: cache.filePathsBySlug.get(entry.slug),
85
88
  }));
86
89
  }
90
+ /**
91
+ * Re-parses one content file and updates the in-memory manifest.
92
+ *
93
+ * @remarks
94
+ * Returns `no-op` when only the MDX body changed so callers can skip
95
+ * rewriting generated collection modules during dev HMR.
96
+ */
97
+ async updateEntryForPath(filePath, event) {
98
+ const resolvedPath = resolve(filePath);
99
+ const cache = await this.getCache();
100
+ if (event === 'delete') {
101
+ return this.removeEntryAtPath(cache, resolvedPath);
102
+ }
103
+ const relativePath = relative(this.config.contentRoot, resolvedPath);
104
+ const nextSlug = slugFromRelativePath(relativePath, this.extensions);
105
+ const previousSlug = this.findSlugForFilePath(cache, resolvedPath);
106
+ return this.upsertEntryAtPath(cache, resolvedPath, nextSlug, previousSlug);
107
+ }
108
+ findSlugForFilePath(cache, filePath) {
109
+ for (const [slug, currentPath] of cache.filePathsBySlug) {
110
+ if (resolve(currentPath) === filePath) {
111
+ return slug;
112
+ }
113
+ }
114
+ return undefined;
115
+ }
116
+ removeEntryAtPath(cache, filePath) {
117
+ const slug = this.findSlugForFilePath(cache, filePath);
118
+ if (!slug) {
119
+ return 'no-op';
120
+ }
121
+ cache.filePathsBySlug.delete(slug);
122
+ cache.manifest = cache.manifest.filter((entry) => entry.slug !== slug);
123
+ return 'structure';
124
+ }
125
+ async upsertEntryAtPath(cache, filePath, nextSlug, previousSlug) {
126
+ const raw = await fileSystem.readFile(filePath);
127
+ const nextEntry = {
128
+ ...(await this.parseFrontmatter(raw)),
129
+ slug: nextSlug,
130
+ segments: nextSlug.split('/'),
131
+ };
132
+ if (!previousSlug) {
133
+ cache.manifest.push(nextEntry);
134
+ cache.filePathsBySlug.set(nextSlug, filePath);
135
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
136
+ return 'structure';
137
+ }
138
+ const previousEntry = cache.manifest.find((entry) => entry.slug === previousSlug);
139
+ if (!previousEntry) {
140
+ cache.manifest.push(nextEntry);
141
+ cache.filePathsBySlug.set(nextSlug, filePath);
142
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
143
+ return 'structure';
144
+ }
145
+ const entryMatches = JSON.stringify(previousEntry) === JSON.stringify(nextEntry);
146
+ if (entryMatches) {
147
+ return 'no-op';
148
+ }
149
+ cache.manifest = cache.manifest.map((entry) => (entry.slug === previousSlug ? nextEntry : entry));
150
+ cache.filePathsBySlug.set(nextSlug, filePath);
151
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
152
+ return 'manifest';
153
+ }
87
154
  }
@@ -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[];
@@ -28,14 +34,35 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
28
34
  private writeGeneratedFile;
29
35
  private getOrCreateScanner;
30
36
  private regenerateCollectionModule;
37
+ private regenerateCollectionEntriesModule;
31
38
  private regenerateCollections;
32
39
  private regenerateAllCollections;
33
- private regenerateCollectionsForPath;
40
+ private handleContentFileEvent;
34
41
  private initializeWatchPaths;
35
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>;
36
53
  private ensureCollectionsGenerated;
37
54
  prepareBuildContributions(): Promise<void>;
38
55
  setup(): Promise<void>;
39
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
+ }>;
40
67
  }
41
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,13 +40,17 @@ 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: [],
42
50
  extensions: ['mdx'],
43
- onCreate: async (ctx) => this.regenerateCollectionsForPath(ctx.path),
44
- onChange: async (ctx) => this.regenerateCollectionsForPath(ctx.path),
45
- onDelete: async (ctx) => this.regenerateCollectionsForPath(ctx.path),
51
+ onCreate: async (ctx) => this.handleContentFileEvent(ctx.path, 'create'),
52
+ onChange: async (ctx) => this.handleContentFileEvent(ctx.path, 'change'),
53
+ onDelete: async (ctx) => this.handleContentFileEvent(ctx.path, 'delete'),
46
54
  };
47
55
  super({
48
56
  ...config,
@@ -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,
@@ -126,6 +138,18 @@ export class ContentProcessorPlugin extends Processor {
126
138
  entryCount: manifest.length,
127
139
  });
128
140
  }
141
+ async regenerateCollectionEntriesModule(collectionName) {
142
+ if (!this.context?.cache) {
143
+ throw new Error('Content processor requires context to be set');
144
+ }
145
+ assertValidCollectionName(collectionName);
146
+ const scanner = this.getOrCreateScanner(collectionName);
147
+ const manifest = (await scanner.getManifest()).map((entry) => entry);
148
+ const outputFile = getCollectionCachePath(this.context.cache, collectionName);
149
+ const entriesOutput = renderCollectionEntriesModule(collectionName, manifest);
150
+ this.writeGeneratedFile(outputFile, entriesOutput);
151
+ this.collectionModules[collectionName] = outputFile;
152
+ }
129
153
  async regenerateCollections(collectionNames) {
130
154
  for (const collectionName of collectionNames) {
131
155
  await this.regenerateCollectionModule(collectionName);
@@ -135,7 +159,7 @@ export class ContentProcessorPlugin extends Processor {
135
159
  async regenerateAllCollections() {
136
160
  await this.regenerateCollections(Object.keys(this.getCollectionsConfig()));
137
161
  }
138
- async regenerateCollectionsForPath(filePath) {
162
+ async handleContentFileEvent(filePath, event) {
139
163
  if (!this.context) {
140
164
  return;
141
165
  }
@@ -147,8 +171,28 @@ export class ContentProcessorPlugin extends Processor {
147
171
  affectedCollections.push(collectionName);
148
172
  }
149
173
  }
150
- if (affectedCollections.length > 0) {
151
- await this.regenerateCollections(affectedCollections);
174
+ let shouldRegenerateTypes = false;
175
+ for (const collectionName of affectedCollections) {
176
+ if (event === 'create' || event === 'delete') {
177
+ await this.regenerateCollectionModule(collectionName);
178
+ shouldRegenerateTypes = true;
179
+ continue;
180
+ }
181
+ const scanner = this.getOrCreateScanner(collectionName);
182
+ const updateResult = await scanner.updateEntryForPath(normalizedPath, event);
183
+ if (updateResult === 'no-op') {
184
+ continue;
185
+ }
186
+ if (updateResult === 'manifest') {
187
+ await this.regenerateCollectionEntriesModule(collectionName);
188
+ shouldRegenerateTypes = true;
189
+ continue;
190
+ }
191
+ await this.regenerateCollectionModule(collectionName);
192
+ shouldRegenerateTypes = true;
193
+ }
194
+ if (shouldRegenerateTypes) {
195
+ this.generateTypes();
152
196
  }
153
197
  }
154
198
  initializeWatchPaths() {
@@ -182,6 +226,61 @@ export class ContentProcessorPlugin extends Processor {
182
226
  });
183
227
  this.writeGeneratedFile(indexTypesDir, 'import "./virtual-module.d.js";\n');
184
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
+ }
185
284
  async ensureCollectionsGenerated() {
186
285
  if (this.collectionsGenerated) {
187
286
  return;
@@ -199,6 +298,32 @@ export class ContentProcessorPlugin extends Processor {
199
298
  async process(_input) {
200
299
  await this.regenerateAllCollections();
201
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
+ }
202
327
  }
203
328
  export const contentProcessorPlugin = (config) => {
204
329
  return new ContentProcessorPlugin(config);
package/src/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { EcoComponent } from '@ecopages/core';
1
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
2
2
  import type { EntryComparator } from './sort.js';
3
3
  export type { EntryComparator } from './sort.js';
4
4
  /**
@@ -21,7 +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>>;
24
+ getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
25
+ getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
25
26
  };
26
27
  /** @deprecated Import entries and server modules separately. */
27
28
  export type ContentCollectionModule<TEntry extends Record<string, unknown> = Record<string, unknown>> = ContentCollectionEntriesModule<TEntry> & ContentCollectionComponentsModule;