@ecopages/content-processor 0.2.0 → 0.3.1

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
@@ -4,6 +4,8 @@ Build-time content collections for Ecopages. Scans MDX (or other configured exte
4
4
 
5
5
  ## Mental model
6
6
 
7
+ Build contributions use one `plugins(app)` method. Collection modules and types are generated in `setup()`, and a build that resolves a collection first waits for the same generation. The server resolver and browser resolver declare separate environments, so browser compilation cannot select the server implementation by registration order.
8
+
7
9
  1. **Declare collections** in `eco.config.ts` — content directory, frontmatter schema, and sort order.
8
10
  2. **Scan at build time** — the processor validates frontmatter and writes generated modules under `.eco/cache/`.
9
11
  3. **Import the virtual module** — pages and layouts use `ecopages:content/<collection>` for `entries`, metadata, and MDX components.
@@ -31,6 +33,8 @@ The processor gives you a typed manifest and MDX components at build time. Wire
31
33
 
32
34
  During development, edits to an entry's MDX body invalidate its compiled server collection bundle even when its frontmatter and generated manifest are unchanged. The next request rebuilds that bundle and renders the new body.
33
35
 
36
+ The content processor owns the compiled collection artifacts and their invalidation generation. Core provides the shared server-module build path; collection identity, source tracking, and cache lifetime stay with the content processor.
37
+
34
38
  Co-located non-entry files inside a collection directory (for example `survey-form.config.ts`, helper modules, or JSON data) also invalidate the compiled server collection without rewriting the generated entries manifest.
35
39
 
36
40
  ## Installation
@@ -46,14 +50,14 @@ Peer dependency: `@ecopages/core`.
46
50
  Register the processor in `eco.config.ts`:
47
51
 
48
52
  ```typescript
49
- import { ConfigBuilder } from '@ecopages/core/config-builder';
53
+ import { defineConfig } from '@ecopages/core/config';
50
54
  import { contentProcessorPlugin } from '@ecopages/content-processor/plugin';
51
55
  import { compareEntriesByField } from '@ecopages/content-processor';
56
+ import { blogFrontmatterSchema } from './src/content/blog-schema';
52
57
  import { docsFrontmatterSchema } from './src/content/docs-schema';
53
58
 
54
- export default await new ConfigBuilder()
55
- .setRootDir(import.meta.dir)
56
- .setProcessors([
59
+ export default defineConfig({
60
+ processors: [
57
61
  contentProcessorPlugin({
58
62
  options: {
59
63
  collections: {
@@ -73,22 +77,21 @@ export default await new ConfigBuilder()
73
77
  },
74
78
  },
75
79
  }),
76
- ])
77
- .build();
80
+ ],
81
+ });
78
82
  ```
79
83
 
80
84
  ### Collection options
81
85
 
82
- | Option | Required | Description |
83
- | :-------------------- | :------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
- | `contentDir` | yes | Directory relative to app `srcDir`, e.g. `content/docs`. |
85
- | `schema` | yes | Standard Schema validator for frontmatter. |
86
- | `entryType` | no | Frontmatter type for generated virtual-module types. Format: `./path/to/schema#TypeName`. The processor wraps it as `ContentEntry<YourFrontmatter>`. |
87
- | `orderBy` | no | Comparator function for manifest sort. Default: {@link compareEntriesBySlug}. Use {@link compareEntriesByField} for frontmatter fields. |
88
- | `extensions` | no | File extensions to scan. Default: `['.mdx']`. Multi-dot extensions (`.radiant.mdx`, `.react.mdx`) are matched longest-first; declaration order does not matter. |
89
- | `routePrefix` | no | Public URL prefix for entries, e.g. `/docs`. Used with `devPrewarm`. |
90
- | `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. |
91
- | `devPrewarmReadiness` | no | `'background'` (default) or `'beforeReady'` to block the framework ready signal until prewarm finishes (listen port may already be open). |
86
+ | Option | Required | Description |
87
+ | :------------ | :------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
88
+ | `contentDir` | yes | Directory relative to app `srcDir`, e.g. `content/docs`. |
89
+ | `schema` | yes | Standard Schema validator for frontmatter. |
90
+ | `entryType` | no | Frontmatter type for generated virtual-module types. Format: `./path/to/schema#TypeName`. The processor wraps it as `ContentEntry<YourFrontmatter>`. |
91
+ | `orderBy` | no | Comparator function for manifest sort. Default: {@link compareEntriesBySlug}. Use {@link compareEntriesByField} for frontmatter fields. |
92
+ | `extensions` | no | File extensions to scan. Default: `['.mdx']`. Multi-dot extensions (`.radiant.mdx`, `.react.mdx`) are matched longest-first; declaration order does not matter. |
93
+ | `routePrefix` | no | Public URL prefix for entries, e.g. `/docs`. Used with `devPrewarm`. |
94
+ | `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. |
92
95
 
93
96
  Collection keys must be kebab-case (`docs`, `api-reference`). Each key becomes `ecopages:content/<key>`.
94
97
 
@@ -305,17 +308,18 @@ const raw = await scanner.getRawContent('getting-started/intro');
305
308
 
306
309
  ## Generated artifacts
307
310
 
308
- | Path | Purpose |
309
- | :------------------------------------------------------------------- | :----------------------------------------------------- |
310
- | `.eco/cache/ecopages-content-processor/<collection>.ts` | Generated collection module (manifest + MDX imports). |
311
- | `.eco/.server-collections/<collection>/<collection>-<identity>.mjs` | Lazy-built server artifact for one collection. |
312
- | `node_modules/@types/ecopages-content-processor/virtual-module.d.ts` | Generated TypeScript declarations for virtual modules. |
311
+ | Path | Purpose |
312
+ | :------------------------------------------------------------------- | :------------------------------------------------------------------------- |
313
+ | `.eco/cache/ecopages-content-processor/<collection>.ts` | Generated collection module (manifest + MDX imports). |
314
+ | `.eco/cache/ecopages-content-processor/<collection>.browser.ts` | Browser-safe MDX loaders. Relative imports resolve from this file on disk. |
315
+ | `.eco/.server-collections/<collection>/<collection>-<identity>.mjs` | Lazy-built server artifact for one collection. |
316
+ | `node_modules/@types/ecopages-content-processor/virtual-module.d.ts` | Generated TypeScript declarations for virtual modules. |
313
317
 
314
318
  Do not edit generated files manually.
315
319
 
316
320
  ## Validation errors
317
321
 
318
- Invalid frontmatter throws `SchemaError` from `@standard-schema/utils` during scan/build. Fix the MDX frontmatter or relax the schema in your app.
322
+ Invalid frontmatter throws `SchemaError` from `@standard-schema/utils` during scan/build. Fix the MDX frontmatter or relax the schema in your app. In development the error appears in the browser overlay, and saving the fixed file recovers the collection without restarting the server.
319
323
 
320
324
  ## Dev / HMR
321
325
 
@@ -325,7 +329,7 @@ Watch config drives manifest regeneration only. Asset ownership (which would ski
325
329
 
326
330
  ## MDX integration
327
331
 
328
- Content files are MDX components. Ensure your JSX or React integration is configured in `eco.config.ts` with MDX enabled so collection entries compile as components.
332
+ Content files are MDX components. Ensure your JSX or React integration is configured in `eco.config.ts` with an `mdx` option so collection entries compile as components.
329
333
 
330
334
  Content collections with YAML frontmatter need `remark-frontmatter` in the **MDX compile pipeline**. The processor validates frontmatter at scan time (`vfile-matter`); MDX render time needs the remark plugin so `---` blocks are not emitted as content.
331
335
 
@@ -337,7 +341,6 @@ import remarkGfm from 'remark-gfm';
337
341
 
338
342
  ecopagesJsxPlugin({
339
343
  mdx: {
340
- enabled: true,
341
344
  ...withContentMdxPlugins({
342
345
  remarkPlugins: [remarkGfm],
343
346
  rehypePlugins: [/* app-specific rehype plugins */],
@@ -347,7 +350,6 @@ ecopagesJsxPlugin({
347
350
 
348
351
  reactPlugin({
349
352
  mdx: {
350
- enabled: true,
351
353
  ...withContentMdxPlugins(),
352
354
  },
353
355
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/content-processor",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
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",
@@ -20,10 +20,10 @@
20
20
  "directory": "packages/processors/content-processor"
21
21
  },
22
22
  "peerDependencies": {
23
- "@ecopages/core": "0.2.0"
23
+ "@ecopages/core": "0.3.1"
24
24
  },
25
25
  "dependencies": {
26
- "@ecopages/file-system": "0.2.0",
26
+ "@ecopages/file-system": "0.3.1",
27
27
  "@ecopages/logger": "^0.2.3",
28
28
  "remark-frontmatter": "^5.0.0",
29
29
  "unified": "^11.0.5",
@@ -0,0 +1,19 @@
1
+ import type { ProcessorContext } from '@ecopages/core/processor';
2
+ export type CollectionServerBuildArtifact = {
3
+ collectionName: string;
4
+ outputPath: string;
5
+ outputUrl: string;
6
+ sourcePaths: string[];
7
+ buildIdentity: string;
8
+ invalidationVersion: number;
9
+ };
10
+ type CollectionServerArtifacts = Map<string, CollectionServerBuildArtifact>;
11
+ /** Builds one generated collection server module as an independent server unit. */
12
+ export declare function buildCollectionServerModule(input: {
13
+ appConfig: ProcessorContext['config'];
14
+ artifacts: CollectionServerArtifacts;
15
+ collectionName: string;
16
+ sourceFilePath: string;
17
+ ownedSourcePaths: readonly string[];
18
+ }): Promise<CollectionServerBuildArtifact>;
19
+ export {};
@@ -0,0 +1,42 @@
1
+ import path from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { fileSystem } from '@ecopages/file-system';
4
+ import { buildServerModule, contentHash, recordCollectionBuild } from '@ecopages/core/build';
5
+ import { requireAppRuntime } from '@ecopages/core/integration';
6
+ function createCollectionBuildIdentity(sourceFilePath, ownedSourcePaths) {
7
+ const sourcePaths = [
8
+ ...new Set([sourceFilePath, ...ownedSourcePaths].map((sourcePath) => path.resolve(sourcePath))),
9
+ ].sort();
10
+ const sourceIdentity = sourcePaths
11
+ .map((sourcePath) => `${sourcePath}\0${fileSystem.exists(sourcePath) ? fileSystem.hash(sourcePath) : 'missing'}`)
12
+ .join('\0');
13
+ return contentHash(`collection-server-build-v3\0${sourceIdentity}`, 16);
14
+ }
15
+ /** Builds one generated collection server module as an independent server unit. */
16
+ export async function buildCollectionServerModule(input) {
17
+ const { appConfig, artifacts, collectionName, sourceFilePath, ownedSourcePaths } = input;
18
+ const runtime = requireAppRuntime(appConfig);
19
+ const invalidationVersion = runtime.moduleLoader.getDevelopmentGeneration();
20
+ const buildIdentity = createCollectionBuildIdentity(sourceFilePath, ownedSourcePaths);
21
+ const existing = artifacts.get(collectionName);
22
+ if (existing?.buildIdentity === buildIdentity && existing.invalidationVersion === invalidationVersion) {
23
+ return existing;
24
+ }
25
+ recordCollectionBuild(runtime.requestPipelineMetrics);
26
+ const outputPath = await buildServerModule(appConfig, {
27
+ entrypoint: sourceFilePath,
28
+ outputDirectory: path.join('.server-collections', collectionName),
29
+ outputFileName: `${collectionName}-${buildIdentity}-${invalidationVersion}.mjs`,
30
+ failureMessage: `Error building collection server module ${collectionName}`,
31
+ });
32
+ const artifact = {
33
+ collectionName,
34
+ outputPath,
35
+ outputUrl: pathToFileURL(outputPath).href,
36
+ sourcePaths: [...ownedSourcePaths, sourceFilePath],
37
+ buildIdentity,
38
+ invalidationVersion,
39
+ };
40
+ artifacts.set(collectionName, artifact);
41
+ return artifact;
42
+ }
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchema } from '@ecopages/core';
2
- import type { EntryComparator } from './sort.js';
2
+ import type { ContentEntry } from './types.js';
3
3
  /**
4
4
  * Declares one content collection scanned at build time.
5
5
  * Collection keys become virtual module paths: `ecopages:content/<key>`.
@@ -9,7 +9,16 @@ export type ContentCollectionDefinition<TFrontmatter extends Record<string, unkn
9
9
  contentDir: string;
10
10
  /** Standard Schema validator for frontmatter (Zod, Valibot, ArkType, etc.). */
11
11
  schema: StandardSchema<unknown, TFrontmatter>;
12
- orderBy?: EntryComparator<TFrontmatter>;
12
+ /**
13
+ * Sorts the collection manifest. Defaults to slug order.
14
+ *
15
+ * @remarks
16
+ * Declared as a method so a comparator typed for this collection's frontmatter, such as
17
+ * `(a: ContentEntry<DocsFrontmatter>, b: ContentEntry<DocsFrontmatter>) => number`, is
18
+ * accepted in the `collections` record, whose entries are not typed per collection. That
19
+ * is sound because `schema` validates every entry before it reaches the comparator.
20
+ */
21
+ orderBy?(a: ContentEntry<TFrontmatter>, b: ContentEntry<TFrontmatter>): number;
13
22
  /** File extensions treated as content. Defaults to `['.mdx']`. */
14
23
  extensions?: string[];
15
24
  /**
@@ -28,11 +37,6 @@ export type ContentCollectionDefinition<TFrontmatter extends Record<string, unkn
28
37
  * Rendering is performed by core; this only declares pathnames from the manifest.
29
38
  */
30
39
  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
40
  };
37
41
  /** Dev prewarm selection for a content collection manifest. */
38
42
  export type ContentDevPrewarmConfig = 'first' | 'all' | {
@@ -1,5 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export declare const CONTENT_PROCESSOR_NAME = "ecopages-content-processor";
3
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
3
+ export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from '@ecopages/core/build';
4
4
  /** Validates collection keys used in processor options and virtual module paths. */
5
5
  export declare const COLLECTION_NAME_PATTERN: RegExp;
package/src/constants.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export const CONTENT_PROCESSOR_NAME = 'ecopages-content-processor';
3
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
3
+ export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, } from '@ecopages/core/build';
4
4
  /** Validates collection keys used in processor options and virtual module paths. */
5
5
  export const COLLECTION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
@@ -1,8 +1,10 @@
1
- import type { EcoBuildPlugin } from '@ecopages/core/plugins/processor';
1
+ import type { EcoBuildPlugin } from '@ecopages/core/processor';
2
2
  import { type ParsedCollectionSpecifier } from './constants.js';
3
3
  export type { ParsedCollectionSpecifier };
4
4
  export { parseCollectionSpecifier } from './constants.js';
5
5
  export type EnsureCollectionServerArtifact = (collectionName: string) => Promise<void>;
6
+ /** Resolves once the generated collection modules exist. */
7
+ export type EnsureCollectionsGenerated = () => Promise<void>;
6
8
  export declare function parseCollectionName(specifier: string): string | null;
7
9
  export declare function resolveCollectionPath(specifier: string, collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>): string | null;
8
10
  /**
@@ -10,20 +12,24 @@ export declare function resolveCollectionPath(specifier: string, collectionModul
10
12
  *
11
13
  * @remarks
12
14
  * Compiled `/server` modules are externalized so Node can load the collection
13
- * artifact directly. The Page Browser Graph uses `createContentPluginBundler`,
15
+ * artifact directly. Every resolve waits for `ensureCollectionsGenerated`, so a build that runs before the
16
+ * Processor's `setup()` still finds the generated modules. The Page Browser Graph uses `createContentPluginBundler`,
14
17
  * where the content boundary rejects `/server` and resolves `/browser` to
15
18
  * browser-safe source.
16
19
  */
17
- export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>, ensureCollectionServerArtifact?: EnsureCollectionServerArtifact): EcoBuildPlugin;
20
+ export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>, ensureCollectionServerArtifact?: EnsureCollectionServerArtifact, ensureCollectionsGenerated?: EnsureCollectionsGenerated): EcoBuildPlugin;
18
21
  /**
19
22
  * Creates the Page Browser Graph resolver for collection virtual modules.
20
23
  *
21
24
  * @remarks
22
- * It resolves entries and `/browser` modules into browser source. `/server`
23
- * resolution is deliberately omitted so the content server-boundary plugin can
24
- * reject any server artifact that remains browser-reachable.
25
+ * It resolves entries and `/browser` modules to generated files on disk so
26
+ * relative MDX imports inside those files resolve as filesystem paths. A
27
+ * virtual namespace would keep those imports inside `ecopages-content:` and
28
+ * Rolldown would report them as missing. `/server` resolution is omitted so
29
+ * the content server-boundary plugin can reject any server artifact that
30
+ * remains browser-reachable.
25
31
  */
26
- export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>): EcoBuildPlugin;
32
+ export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>, ensureCollectionsGenerated?: EnsureCollectionsGenerated): EcoBuildPlugin;
27
33
  export declare function getCollectionCachePath(cacheDir: string, collectionName: string): string;
28
34
  export declare function getCollectionServerCachePath(cacheDir: string, collectionName: string): string;
29
35
  /** Returns the generated browser module path for one collection. */
@@ -1,5 +1,4 @@
1
1
  import path from 'node:path';
2
- import { fileSystem } from '@ecopages/file-system';
3
2
  import { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, parseCollectionSpecifier, } from './constants.js';
4
3
  export { parseCollectionSpecifier } from './constants.js';
5
4
  export function parseCollectionName(specifier) {
@@ -21,12 +20,13 @@ export function resolveCollectionPath(specifier, collectionModules, collectionSe
21
20
  }
22
21
  return collectionModules[parsed.collectionName] ?? null;
23
22
  }
24
- function createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, options) {
23
+ function createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, ensureCollectionsGenerated, options) {
25
24
  return {
26
25
  name: 'ecopages:content',
27
26
  setup(build) {
28
27
  const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules);
29
- build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, (args) => {
28
+ build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, async (args) => {
29
+ await ensureCollectionsGenerated?.();
30
30
  const modulePath = resolveCollection(args.path);
31
31
  if (!modulePath) {
32
32
  return undefined;
@@ -41,8 +41,9 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
41
41
  });
42
42
  if (options.includeServerModules !== false) {
43
43
  build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, async (args) => {
44
+ await ensureCollectionsGenerated?.();
44
45
  const parsed = parseCollectionSpecifier(args.path);
45
- if (parsed?.variant === 'server' && !collectionServerCompiledModules?.[parsed.collectionName]) {
46
+ if (parsed?.variant === 'server') {
46
47
  await ensureCollectionServerArtifact?.(parsed.collectionName);
47
48
  }
48
49
  const compiledPath = parsed?.variant === 'server'
@@ -64,7 +65,8 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
64
65
  return { path: modulePath };
65
66
  });
66
67
  }
67
- build.onResolve({ filter: CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN }, (args) => {
68
+ build.onResolve({ filter: CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN }, async (args) => {
69
+ await ensureCollectionsGenerated?.();
68
70
  const modulePath = resolveCollection(args.path);
69
71
  if (!modulePath) {
70
72
  return undefined;
@@ -82,36 +84,29 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
82
84
  *
83
85
  * @remarks
84
86
  * Compiled `/server` modules are externalized so Node can load the collection
85
- * artifact directly. The Page Browser Graph uses `createContentPluginBundler`,
87
+ * artifact directly. Every resolve waits for `ensureCollectionsGenerated`, so a build that runs before the
88
+ * Processor's `setup()` still finds the generated modules. The Page Browser Graph uses `createContentPluginBundler`,
86
89
  * where the content boundary rejects `/server` and resolves `/browser` to
87
90
  * browser-safe source.
88
91
  */
89
- export function createContentPlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}, ensureCollectionServerArtifact) {
90
- return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, { includeServerModules: true, externalizeCompiledServerModules: true });
92
+ export function createContentPlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}, ensureCollectionServerArtifact, ensureCollectionsGenerated) {
93
+ return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, ensureCollectionsGenerated, { includeServerModules: true, externalizeCompiledServerModules: true });
91
94
  }
92
95
  /**
93
96
  * Creates the Page Browser Graph resolver for collection virtual modules.
94
97
  *
95
98
  * @remarks
96
- * It resolves entries and `/browser` modules into browser source. `/server`
97
- * resolution is deliberately omitted so the content server-boundary plugin can
98
- * reject any server artifact that remains browser-reachable.
99
+ * It resolves entries and `/browser` modules to generated files on disk so
100
+ * relative MDX imports inside those files resolve as filesystem paths. A
101
+ * virtual namespace would keep those imports inside `ecopages-content:` and
102
+ * Rolldown would report them as missing. `/server` resolution is omitted so
103
+ * the content server-boundary plugin can reject any server artifact that
104
+ * remains browser-reachable.
99
105
  */
100
- export function createContentPluginBundler(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}) {
101
- const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, undefined, {
102
- namespace: 'ecopages-content',
106
+ export function createContentPluginBundler(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}, ensureCollectionsGenerated) {
107
+ return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, undefined, ensureCollectionsGenerated, {
103
108
  includeServerModules: false,
104
109
  });
105
- return {
106
- name: plugin.name,
107
- setup(build) {
108
- plugin.setup?.(build);
109
- build.onLoad({ filter: /.*/, namespace: 'ecopages-content' }, async (args) => {
110
- const contents = await fileSystem.readFile(args.path);
111
- return { contents, loader: 'ts' };
112
- });
113
- },
114
- };
115
110
  }
116
111
  export function getCollectionCachePath(cacheDir, collectionName) {
117
112
  return path.join(cacheDir, `${collectionName}.ts`);
@@ -31,6 +31,12 @@ export declare class ContentScanner<T extends Record<string, unknown> = Record<s
31
31
  clearCache(): void;
32
32
  private parseFrontmatter;
33
33
  private loadCache;
34
+ /**
35
+ * @remarks
36
+ * A rejected load is dropped so the next call re-reads the directory. Keeping it
37
+ * would replay the first schema error for every later edit, even after the
38
+ * offending file was fixed.
39
+ */
34
40
  private getCache;
35
41
  getManifest(): Promise<ContentEntry<T>[]>;
36
42
  getRawContent(slug: string): Promise<string>;
@@ -70,9 +70,21 @@ export class ContentScanner {
70
70
  filePathsBySlug,
71
71
  };
72
72
  }
73
+ /**
74
+ * @remarks
75
+ * A rejected load is dropped so the next call re-reads the directory. Keeping it
76
+ * would replay the first schema error for every later edit, even after the
77
+ * offending file was fixed.
78
+ */
73
79
  async getCache() {
74
80
  if (!this.cachePromise) {
75
- this.cachePromise = this.loadCache();
81
+ const pending = this.loadCache();
82
+ this.cachePromise = pending;
83
+ pending.catch(() => {
84
+ if (this.cachePromise === pending) {
85
+ this.cachePromise = undefined;
86
+ }
87
+ });
76
88
  }
77
89
  return this.cachePromise;
78
90
  }
@@ -1,4 +1,4 @@
1
- import type { EcoBuildPlugin } from '@ecopages/core/plugins/processor';
1
+ import type { EcoBuildPlugin } from '@ecopages/core/processor';
2
2
  /**
3
3
  * Rejects `ecopages:content/<collection>/server` in browser bundles.
4
4
  *
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Fallback declarations for content virtual modules before the configured
3
- * collection declarations are generated by `ecopages dev` or `ecopages build`.
3
+ * collection declarations are generated by `ecopages types`, `ecopages dev`, or `ecopages build`.
4
4
  *
5
5
  * @remarks This must remain a script (without imports or exports). In an
6
6
  * external module, these declarations become module augmentations and cannot
package/src/ownership.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getComponentRenderContext, } from '@ecopages/core/route-renderer/orchestration/foreign-child/component-render-context';
1
+ import { getComponentRenderContext } from '@ecopages/core/integration';
2
2
  /**
3
3
  * Throws when an MDX content entry is invoked under a different integration
4
4
  * than the one that compiled it.
package/src/plugin.d.ts CHANGED
@@ -2,17 +2,28 @@
2
2
  * ContentProcessorPlugin
3
3
  * @module @ecopages/content-processor
4
4
  */
5
- import { Processor, type EcoBuildPlugin, type ProcessorConfig } from '@ecopages/core/plugins/processor';
5
+ import { Processor, type EcoBuildPlugin, type ProcessorConfig } from '@ecopages/core/processor';
6
6
  import type { ContentProcessorConfig } from './collection-types.js';
7
7
  /**
8
8
  * Build-time processor that scans configured content collections and exposes
9
9
  * each one as `ecopages:content/<collection>` virtual modules.
10
10
  */
11
11
  export declare class ContentProcessorPlugin extends Processor<ContentProcessorConfig> {
12
- private collectionsGenerated;
12
+ private collectionsGeneration?;
13
13
  private readonly scanners;
14
14
  private readonly collectionBuildPromises;
15
15
  private readonly collectionGenerations;
16
+ private readonly collectionServerArtifacts;
17
+ /**
18
+ * Collections whose generated modules may not match the files on disk.
19
+ *
20
+ * @remarks
21
+ * A collection joins this set when a regeneration starts and leaves it when that
22
+ * regeneration completes. One that failed, for example on invalid frontmatter,
23
+ * stays in it so the next file change regenerates instead of diffing against a
24
+ * manifest that never reached the generated modules.
25
+ */
26
+ private readonly staleCollections;
16
27
  /**
17
28
  * Absolute paths to generated collection entry modules, keyed by collection name.
18
29
  * Virtual-module plugins close over this object so mutations stay live.
@@ -28,10 +39,9 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
28
39
  * Absolute paths to pre-built collection server artifacts for route-module externalization.
29
40
  */
30
41
  readonly collectionServerCompiledModules: Record<string, string>;
31
- constructor(config: Omit<ProcessorConfig<ContentProcessorConfig>, 'name' | 'description'>);
32
- get buildPlugins(): EcoBuildPlugin[];
33
- get plugins(): EcoBuildPlugin[];
34
- invalidateServerArtifacts(): void;
42
+ constructor(config: Omit<ProcessorConfig<ContentProcessorConfig>, 'name'>);
43
+ private get browserPlugins();
44
+ plugins(): EcoBuildPlugin[];
35
45
  private getCollectionsConfig;
36
46
  private getCollectionContentRoot;
37
47
  private writeGeneratedFile;
@@ -50,7 +60,11 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
50
60
  private regenerateCollections;
51
61
  private regenerateAllCollections;
52
62
  private isCollectionEntryPath;
53
- private handleContentFileEvent;
63
+ private handleContentFileChanges;
64
+ private collectCollectionWatchChanges;
65
+ private recordCollectionWatchChange;
66
+ private applyCollectionWatchChanges;
67
+ private updateChangedCollectionEntries;
54
68
  private initializeWatchPaths;
55
69
  private generateTypes;
56
70
  private buildCollectionServerArtifact;
@@ -63,19 +77,31 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
63
77
  * builds share the same promise.
64
78
  */
65
79
  ensureCollectionServerArtifact(collectionName: string): Promise<void>;
80
+ /**
81
+ * The app module loader's development generation, which advances whenever server source changes.
82
+ *
83
+ * @remarks
84
+ * A compiled collection embeds the modules its entries import, such as a component, so it is stale once the
85
+ * generation differs from the one it was built at. Core announces no invalidation to Processors.
86
+ */
87
+ private getServerSourceGeneration;
88
+ /**
89
+ * Generates the collection modules and types once, and shares that work between callers.
90
+ *
91
+ * @remarks
92
+ * {@link setup} and every collection resolve call it, so a build that starts before `setup()` waits for the
93
+ * generated modules instead of finding none. A failed generation is dropped so the next caller retries.
94
+ */
66
95
  private ensureCollectionsGenerated;
67
- prepareBuildContributions(): Promise<void>;
68
96
  setup(): Promise<void>;
69
- process(_input: unknown): Promise<void>;
70
97
  /**
71
- * Declares watch-mode SSR prewarm pathnames and readiness derived from collection manifests.
98
+ * Adds the pathnames of collections with `devPrewarm` and a `routePrefix` to the app's `devPrewarmPaths`.
72
99
  *
73
100
  * @remarks
74
- * Core executes rendering in parallel; this hook only maps `routePrefix` + entry slugs to URLs.
101
+ * Core renders the list in the background after the server is listening. The entries are read from the
102
+ * manifests at startup, so an entry created later is not prewarmed until the next start. Existing paths stay,
103
+ * and a repeated `setup()` adds nothing twice.
75
104
  */
76
- collectDevPrewarmPlan(): Promise<{
77
- pathnames: readonly string[];
78
- readiness: 'background' | 'beforeReady';
79
- }>;
105
+ private addDevPrewarmPaths;
80
106
  }
81
- export declare const contentProcessorPlugin: (config: Omit<ProcessorConfig<ContentProcessorConfig>, "name" | "description">) => ContentProcessorPlugin;
107
+ export declare const contentProcessorPlugin: (config: Omit<ProcessorConfig<ContentProcessorConfig>, "name">) => ContentProcessorPlugin;
package/src/plugin.js CHANGED
@@ -4,7 +4,9 @@
4
4
  */
5
5
  import path from 'node:path';
6
6
  import { fileSystem } from '@ecopages/file-system';
7
- import { mergeProcessorOptions, Processor, resolveGeneratedPath, writeGeneratedTypesPackage, } from '@ecopages/core/plugins/processor';
7
+ import { isEcopagesEnvEnabled } from '@ecopages/core/processor';
8
+ import { requireAppRuntime } from '@ecopages/core/integration';
9
+ import { mergeProcessorOptions, Processor, resolveGeneratedPath, writeGeneratedTypesPackage, } from '@ecopages/core/processor';
8
10
  import { Logger } from '@ecopages/logger';
9
11
  import { renderCollectionComponentsModule, renderCollectionBrowserModule, renderCollectionEntriesModule, renderVirtualModuleTypes, } from './codegen.js';
10
12
  import { compareEntriesBySlug } from './sort.js';
@@ -13,9 +15,9 @@ import { createContentPlugin, createContentPluginBundler, getCollectionCachePath
13
15
  import { createContentServerBoundaryPlugin } from './content-server-boundary-plugin.js';
14
16
  import { COLLECTION_NAME_PATTERN, CONTENT_PROCESSOR_NAME } from './constants.js';
15
17
  import { buildContentDevPrewarmPathnames } from './dev-prewarm-paths.js';
16
- import { buildCollectionServerModule } from '@ecopages/core/services/module-loading/collection-server-module-build.service';
18
+ import { buildCollectionServerModule, } from './collection-server-module-build.service.js';
17
19
  const logger = new Logger('[@ecopages/content-processor]', {
18
- debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true',
20
+ debug: isEcopagesEnvEnabled('ECOPAGES_LOGGER_DEBUG'),
19
21
  });
20
22
  function assertValidCollectionName(collectionName) {
21
23
  if (!COLLECTION_NAME_PATTERN.test(collectionName)) {
@@ -27,10 +29,21 @@ function assertValidCollectionName(collectionName) {
27
29
  * each one as `ecopages:content/<collection>` virtual modules.
28
30
  */
29
31
  export class ContentProcessorPlugin extends Processor {
30
- collectionsGenerated = false;
32
+ collectionsGeneration;
31
33
  scanners = new Map();
32
34
  collectionBuildPromises = new Map();
33
35
  collectionGenerations = new Map();
36
+ collectionServerArtifacts = new Map();
37
+ /**
38
+ * Collections whose generated modules may not match the files on disk.
39
+ *
40
+ * @remarks
41
+ * A collection joins this set when a regeneration starts and leaves it when that
42
+ * regeneration completes. One that failed, for example on invalid frontmatter,
43
+ * stays in it so the next file change regenerates instead of diffing against a
44
+ * manifest that never reached the generated modules.
45
+ */
46
+ staleCollections = new Set();
34
47
  /**
35
48
  * Absolute paths to generated collection entry modules, keyed by collection name.
36
49
  * Virtual-module plugins close over this object so mutations stay live.
@@ -50,33 +63,29 @@ export class ContentProcessorPlugin extends Processor {
50
63
  const defaultWatchConfig = {
51
64
  paths: [],
52
65
  extensions: ['.mdx', '.md', '.ts', '.tsx', '.js', '.jsx', '.json'],
53
- onCreate: async (ctx) => this.handleContentFileEvent(ctx.path, 'create'),
54
- onChange: async (ctx) => this.handleContentFileEvent(ctx.path, 'change'),
55
- onDelete: async (ctx) => this.handleContentFileEvent(ctx.path, 'delete'),
66
+ onChanges: async (changes) => this.handleContentFileChanges(changes),
56
67
  };
57
68
  super({
58
69
  ...config,
59
70
  name: CONTENT_PROCESSOR_NAME,
60
- description: 'Build-time content collections exposed as ecopages:content/* virtual modules.',
61
71
  watch: config.watch ? mergeProcessorOptions(defaultWatchConfig, config.watch) : defaultWatchConfig,
62
72
  });
63
73
  }
64
- get buildPlugins() {
74
+ get browserPlugins() {
65
75
  return [
66
76
  createContentServerBoundaryPlugin(),
67
- createContentPluginBundler(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules),
68
- ];
77
+ createContentPluginBundler(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules, () => this.ensureCollectionsGenerated()),
78
+ ].map((plugin) => ({ ...plugin, environments: ['browser'] }));
69
79
  }
70
- get plugins() {
80
+ plugins() {
71
81
  return [
72
- createContentPlugin(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules, (collectionName) => this.ensureCollectionServerArtifact(collectionName)),
82
+ {
83
+ ...createContentPlugin(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules, (collectionName) => this.ensureCollectionServerArtifact(collectionName), () => this.ensureCollectionsGenerated()),
84
+ environments: ['server'],
85
+ },
86
+ ...this.browserPlugins,
73
87
  ];
74
88
  }
75
- invalidateServerArtifacts() {
76
- for (const collectionName of Object.keys(this.getCollectionsConfig())) {
77
- this.invalidateCollectionServerArtifact(collectionName);
78
- }
79
- }
80
89
  getCollectionsConfig() {
81
90
  if (!this.options?.collections) {
82
91
  throw new Error('Content processor requires `options.collections`');
@@ -123,6 +132,7 @@ export class ContentProcessorPlugin extends Processor {
123
132
  if (!definition) {
124
133
  return;
125
134
  }
135
+ this.staleCollections.add(collectionName);
126
136
  const scanner = this.getOrCreateScanner(collectionName);
127
137
  scanner.clearCache();
128
138
  const entrySources = await scanner.getEntrySources();
@@ -141,6 +151,7 @@ export class ContentProcessorPlugin extends Processor {
141
151
  this.collectionServerModules[collectionName] = serverOutputFile;
142
152
  this.collectionBrowserModules[collectionName] = browserOutputFile;
143
153
  this.invalidateCollectionServerArtifact(collectionName);
154
+ this.staleCollections.delete(collectionName);
144
155
  logger.debug('Generated content collection module', {
145
156
  collectionName,
146
157
  outputFile,
@@ -189,49 +200,88 @@ export class ContentProcessorPlugin extends Processor {
189
200
  return normalizedPath.endsWith(dotted);
190
201
  });
191
202
  }
192
- async handleContentFileEvent(filePath, event) {
203
+ async handleContentFileChanges({ created, changed, deleted }) {
193
204
  if (!this.context) {
194
205
  return;
195
206
  }
196
- const normalizedPath = path.normalize(filePath);
197
- const affectedCollections = [];
198
- for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
199
- const contentRoot = this.getCollectionContentRoot(definition.contentDir);
200
- if (normalizedPath.startsWith(contentRoot + path.sep) || normalizedPath === contentRoot) {
201
- affectedCollections.push(collectionName);
202
- }
203
- }
207
+ const collectionChanges = this.collectCollectionWatchChanges({ created, changed, deleted });
204
208
  let shouldRegenerateTypes = false;
205
- for (const collectionName of affectedCollections) {
206
- const definition = this.getCollectionsConfig()[collectionName];
207
- const isEntry = this.isCollectionEntryPath(normalizedPath, definition.extensions);
208
- if (!isEntry) {
209
- this.invalidateCollectionServerArtifact(collectionName);
210
- continue;
211
- }
212
- if (event === 'create' || event === 'delete') {
213
- await this.regenerateCollectionModule(collectionName);
214
- shouldRegenerateTypes = true;
215
- continue;
216
- }
217
- const scanner = this.getOrCreateScanner(collectionName);
218
- const updateResult = await scanner.updateEntryForPath(normalizedPath, event);
219
- if (updateResult === 'no-op') {
220
- this.invalidateCollectionServerArtifact(collectionName);
221
- continue;
222
- }
223
- if (updateResult === 'manifest') {
224
- await this.regenerateCollectionEntriesModule(collectionName);
225
- shouldRegenerateTypes = true;
226
- continue;
227
- }
228
- await this.regenerateCollectionModule(collectionName);
229
- shouldRegenerateTypes = true;
209
+ for (const [collectionName, changes] of collectionChanges) {
210
+ const regeneratedTypes = await this.applyCollectionWatchChanges(collectionName, changes);
211
+ shouldRegenerateTypes ||= regeneratedTypes;
230
212
  }
231
213
  if (shouldRegenerateTypes) {
232
214
  this.generateTypes();
233
215
  }
234
216
  }
217
+ collectCollectionWatchChanges({ created, changed, deleted, }) {
218
+ const collectionChanges = new Map();
219
+ const events = [
220
+ { paths: created, event: 'create' },
221
+ { paths: changed, event: 'change' },
222
+ { paths: deleted, event: 'delete' },
223
+ ];
224
+ for (const { paths, event } of events) {
225
+ for (const filePath of paths) {
226
+ const normalizedPath = path.normalize(filePath);
227
+ for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
228
+ const contentRoot = this.getCollectionContentRoot(definition.contentDir);
229
+ if (normalizedPath.startsWith(contentRoot + path.sep) || normalizedPath === contentRoot) {
230
+ const changes = collectionChanges.get(collectionName) ?? {
231
+ regenerate: false,
232
+ changedEntries: [],
233
+ invalidateServerArtifact: false,
234
+ };
235
+ collectionChanges.set(collectionName, changes);
236
+ this.recordCollectionWatchChange(changes, normalizedPath, event, definition.extensions);
237
+ }
238
+ }
239
+ }
240
+ }
241
+ return collectionChanges;
242
+ }
243
+ recordCollectionWatchChange(changes, filePath, event, configuredExtensions) {
244
+ if (!this.isCollectionEntryPath(filePath, configuredExtensions)) {
245
+ changes.invalidateServerArtifact = true;
246
+ }
247
+ else if (event === 'change') {
248
+ changes.changedEntries.push(filePath);
249
+ }
250
+ else {
251
+ changes.regenerate = true;
252
+ }
253
+ }
254
+ async applyCollectionWatchChanges(collectionName, changes) {
255
+ if (changes.regenerate || this.staleCollections.has(collectionName)) {
256
+ await this.regenerateCollectionModule(collectionName);
257
+ return true;
258
+ }
259
+ const updateResult = await this.updateChangedCollectionEntries(collectionName, changes);
260
+ if (updateResult === 'collection') {
261
+ await this.regenerateCollectionModule(collectionName);
262
+ }
263
+ else if (updateResult === 'entries') {
264
+ await this.regenerateCollectionEntriesModule(collectionName);
265
+ }
266
+ if (changes.invalidateServerArtifact && updateResult !== 'collection') {
267
+ this.invalidateCollectionServerArtifact(collectionName);
268
+ }
269
+ return updateResult !== 'none';
270
+ }
271
+ async updateChangedCollectionEntries(collectionName, changes) {
272
+ let result = 'none';
273
+ for (const filePath of changes.changedEntries) {
274
+ changes.invalidateServerArtifact = true;
275
+ const updateResult = await this.getOrCreateScanner(collectionName).updateEntryForPath(filePath, 'change');
276
+ if (updateResult === 'structure') {
277
+ result = 'collection';
278
+ }
279
+ else if (updateResult === 'manifest' && result === 'none') {
280
+ result = 'entries';
281
+ }
282
+ }
283
+ return result;
284
+ }
235
285
  initializeWatchPaths() {
236
286
  if (!this.watchConfig || !this.context) {
237
287
  return;
@@ -270,11 +320,12 @@ export class ContentProcessorPlugin extends Processor {
270
320
  });
271
321
  }
272
322
  async buildCollectionServerArtifact(collectionName, serverOutputFile, ownedSourcePaths) {
273
- if (!this.context?.config.runtime?.buildRuntime) {
323
+ if (!this.context) {
274
324
  return;
275
325
  }
276
326
  const artifact = await buildCollectionServerModule({
277
327
  appConfig: this.context.config,
328
+ artifacts: this.collectionServerArtifacts,
278
329
  collectionName,
279
330
  sourceFilePath: serverOutputFile,
280
331
  ownedSourcePaths,
@@ -290,9 +341,12 @@ export class ContentProcessorPlugin extends Processor {
290
341
  * builds share the same promise.
291
342
  */
292
343
  async ensureCollectionServerArtifact(collectionName) {
293
- if (!this.context?.config.runtime?.buildRuntime) {
344
+ if (!this.context) {
294
345
  return;
295
346
  }
347
+ if (this.collectionServerArtifacts.get(collectionName)?.invalidationVersion !== this.getServerSourceGeneration()) {
348
+ delete this.collectionServerCompiledModules[collectionName];
349
+ }
296
350
  if (this.collectionServerCompiledModules[collectionName]) {
297
351
  return;
298
352
  }
@@ -305,6 +359,7 @@ export class ContentProcessorPlugin extends Processor {
305
359
  return;
306
360
  }
307
361
  const generation = this.collectionGenerations.get(collectionName) ?? 0;
362
+ const serverSourceGeneration = this.getServerSourceGeneration();
308
363
  const serverOutputFile = this.collectionServerModules[collectionName];
309
364
  if (!serverOutputFile) {
310
365
  throw new Error(`Unknown content collection: ${collectionName}`);
@@ -313,7 +368,9 @@ export class ContentProcessorPlugin extends Processor {
313
368
  const ownedSourcePaths = scanner ? (await scanner.getEntrySources()).map(({ filePath }) => filePath) : [];
314
369
  const buildPromise = this.buildCollectionServerArtifact(collectionName, serverOutputFile, ownedSourcePaths)
315
370
  .then(() => {
316
- if (generation !== (this.collectionGenerations.get(collectionName) ?? 0)) {
371
+ const changedDuringBuild = generation !== (this.collectionGenerations.get(collectionName) ?? 0) ||
372
+ serverSourceGeneration !== this.getServerSourceGeneration();
373
+ if (changedDuringBuild) {
317
374
  delete this.collectionServerCompiledModules[collectionName];
318
375
  }
319
376
  })
@@ -324,37 +381,51 @@ export class ContentProcessorPlugin extends Processor {
324
381
  await this.ensureCollectionServerArtifact(collectionName);
325
382
  }
326
383
  }
327
- async ensureCollectionsGenerated() {
328
- if (this.collectionsGenerated) {
329
- return;
330
- }
331
- this.initializeWatchPaths();
332
- await this.regenerateAllCollections();
333
- this.collectionsGenerated = true;
384
+ /**
385
+ * The app module loader's development generation, which advances whenever server source changes.
386
+ *
387
+ * @remarks
388
+ * A compiled collection embeds the modules its entries import, such as a component, so it is stale once the
389
+ * generation differs from the one it was built at. Core announces no invalidation to Processors.
390
+ */
391
+ getServerSourceGeneration() {
392
+ return this.context ? requireAppRuntime(this.context.config).moduleLoader.getDevelopmentGeneration() : 0;
334
393
  }
335
- async prepareBuildContributions() {
336
- await this.ensureCollectionsGenerated();
394
+ /**
395
+ * Generates the collection modules and types once, and shares that work between callers.
396
+ *
397
+ * @remarks
398
+ * {@link setup} and every collection resolve call it, so a build that starts before `setup()` waits for the
399
+ * generated modules instead of finding none. A failed generation is dropped so the next caller retries.
400
+ */
401
+ ensureCollectionsGenerated() {
402
+ this.collectionsGeneration ??= (async () => {
403
+ this.initializeWatchPaths();
404
+ await this.regenerateAllCollections();
405
+ })().catch((error) => {
406
+ this.collectionsGeneration = undefined;
407
+ throw error;
408
+ });
409
+ return this.collectionsGeneration;
337
410
  }
338
411
  async setup() {
339
412
  await this.ensureCollectionsGenerated();
340
- }
341
- async process(_input) {
342
- await this.regenerateAllCollections();
413
+ await this.addDevPrewarmPaths();
343
414
  }
344
415
  /**
345
- * Declares watch-mode SSR prewarm pathnames and readiness derived from collection manifests.
416
+ * Adds the pathnames of collections with `devPrewarm` and a `routePrefix` to the app's `devPrewarmPaths`.
346
417
  *
347
418
  * @remarks
348
- * Core executes rendering in parallel; this hook only maps `routePrefix` + entry slugs to URLs.
419
+ * Core renders the list in the background after the server is listening. The entries are read from the
420
+ * manifests at startup, so an entry created later is not prewarmed until the next start. Existing paths stay,
421
+ * and a repeated `setup()` adds nothing twice.
349
422
  */
350
- async collectDevPrewarmPlan() {
351
- await this.ensureCollectionsGenerated();
423
+ async addDevPrewarmPaths() {
424
+ if (!this.context) {
425
+ return;
426
+ }
352
427
  const pathnames = [];
353
- let readiness = 'background';
354
428
  for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
355
- if (definition.devPrewarmReadiness === 'beforeReady') {
356
- readiness = 'beforeReady';
357
- }
358
429
  if (!definition.devPrewarm || !definition.routePrefix) {
359
430
  continue;
360
431
  }
@@ -362,10 +433,8 @@ export class ContentProcessorPlugin extends Processor {
362
433
  const entries = await scanner.getManifest();
363
434
  pathnames.push(...buildContentDevPrewarmPathnames(definition, entries));
364
435
  }
365
- return {
366
- pathnames: [...new Set(pathnames)],
367
- readiness,
368
- };
436
+ const config = this.context.config;
437
+ config.devPrewarmPaths = [...new Set([...(config.devPrewarmPaths ?? []), ...pathnames])];
369
438
  }
370
439
  }
371
440
  export const contentProcessorPlugin = (config) => {