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

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
@@ -147,20 +147,22 @@ Run `ecopages dev` or `ecopages build` before expecting IDE types. Restart the T
147
147
 
148
148
  ## Virtual module API
149
149
 
150
- Each collection exposes `ecopages:content/<collection>`:
150
+ Each collection exposes `ecopages:content/<collection>` for metadata and `ecopages:content/<collection>/server` for MDX components:
151
151
 
152
152
  ```typescript
153
- import { entries, getEntry, getEntryBySegments, getComponent } from 'ecopages:content/docs';
153
+ import { entries, getEntry, getEntryBySegments } from 'ecopages:content/docs';
154
+ import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
154
155
  import type { Entry } from 'ecopages:content/docs';
155
156
  ```
156
157
 
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`. |
158
+ | Export | Module | Description |
159
+ | :----------------------------- | :------ | :---------------------------------------------------------------------------------------------- |
160
+ | `entries` | entries | Readonly manifest of all entries, sorted by `orderBy`. |
161
+ | `getEntry(slug)` | entries | Lookup by joined slug, e.g. `'getting-started/intro'`. |
162
+ | `getEntryBySegments(segments)` | entries | Lookup by segment array, e.g. `['getting-started', 'intro']`. |
163
+ | `getComponent(slug)` | server | MDX component for the entry. |
164
+ | `getEntryDependencies(slug)` | server | Browser dependency bag for the entry, with MDX source ownership for catch-all routes. |
165
+ | `Entry` | entries | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
164
166
 
165
167
  **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
168
 
@@ -170,7 +172,8 @@ Define a catch-all or per-entry route with `eco.page`. Import the collection man
170
172
 
171
173
  ```typescript
172
174
  import { eco } from '@ecopages/core';
173
- import { entries, getComponent, getEntryBySegments } from 'ecopages:content/docs';
175
+ import { entries, getEntryBySegments } from 'ecopages:content/docs';
176
+ import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
174
177
  import type { Entry } from 'ecopages:content/docs';
175
178
 
176
179
  export default eco.page<{ entry: Entry }>({
@@ -188,6 +191,7 @@ export default eco.page<{ entry: Entry }>({
188
191
  props: { entry: getEntryBySegments(segments) },
189
192
  };
190
193
  },
194
+ dependencies: ({ props }) => getEntryDependencies(props.entry.slug),
191
195
  metadata: ({ props: { entry } }) => ({
192
196
  title: entry.title,
193
197
  description: entry.description,
@@ -199,6 +203,24 @@ export default eco.page<{ entry: Entry }>({
199
203
  });
200
204
  ```
201
205
 
206
+ Content MDX entries may declare interactive demo dependencies without polluting the catch-all page shell:
207
+
208
+ ```mdx
209
+ import { WeatherApp } from '@/components/weather-app/weather-app';
210
+
211
+ export const config = {
212
+ dependencies: {
213
+ components: [WeatherApp],
214
+ },
215
+ };
216
+
217
+ # Weather app
218
+
219
+ <WeatherApp />
220
+ ```
221
+
222
+ `getComponent()` returns the MDX default component with exported `config` attached. Pair that with `getEntryDependencies()` on the catch-all page so only the active entry contributes to the Page Browser Graph. The helper includes `ownerFile` so relative `scripts`, `stylesheets`, and `modules` declared in MDX resolve against the entry file, not the catch-all route.
223
+
202
224
  ## Navigation (app-side)
203
225
 
204
226
  Navigation is app code. Map `entries` to links using the frontmatter and path fields the processor already validated:
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.38",
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.38"
21
21
  },
22
22
  "dependencies": {
23
- "@ecopages/file-system": "0.2.0-beta.37",
23
+ "@ecopages/file-system": "0.2.0-beta.38",
24
24
  "@ecopages/logger": "^0.2.3",
25
25
  "remark-frontmatter": "^5.0.0",
26
26
  "unified": "^11.0.5",
package/src/codegen.js CHANGED
@@ -38,18 +38,59 @@ export function getEntryBySegments(segments: string[]) {
38
38
  }
39
39
  `;
40
40
  }
41
+ function renderAttachMdxExportsHelper() {
42
+ return `type ContentMdxModule = {
43
+ default: EcoComponent<Record<string, unknown>>;
44
+ config?: EcoComponent<Record<string, unknown>>['config'];
45
+ getMetadata?: EcoComponent<Record<string, unknown>>['metadata'];
46
+ };
47
+
48
+ function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComponent<Record<string, unknown>> {
49
+ const Page = module.default;
50
+ const component = Object.assign(
51
+ (props: Record<string, unknown>) => Page(props),
52
+ Page,
53
+ ) as EcoComponent<Record<string, unknown>>;
54
+
55
+ if (module.config) {
56
+ component.config = {
57
+ ...component.config,
58
+ ...module.config,
59
+ __eco: {
60
+ ...(component.config?.__eco ?? module.config.__eco),
61
+ id: module.config.__eco?.id ?? component.config?.__eco?.id ?? sourceFile,
62
+ file: sourceFile,
63
+ integration: module.config.__eco?.integration ?? component.config?.__eco?.integration ?? 'content',
64
+ },
65
+ };
66
+ }
67
+
68
+ if (module.getMetadata) {
69
+ component.metadata = module.getMetadata;
70
+ }
71
+
72
+ return component;
73
+ }
74
+ `;
75
+ }
41
76
  export function renderCollectionComponentsModule(collectionName, outputDir, entrySources) {
42
77
  const importLines = [];
43
78
  const componentMapLines = [];
79
+ const entrySourceFilesBySlugLines = [];
44
80
  for (const { entry, filePath } of entrySources) {
45
81
  const identifier = slugToIdentifier(collectionName, entry.slug);
46
82
  const importPath = relative(outputDir, filePath).split('\\').join('/');
47
- importLines.push(`import ${identifier} from '${importPath}';`);
48
- componentMapLines.push(`\t'${entry.slug}': ${identifier},`);
83
+ const sourceFile = filePath.split('\\').join('/');
84
+ const escapedSourceFile = sourceFile.replace(/'/g, "\\'");
85
+ importLines.push(`import * as ${identifier}_module from '${importPath}';`);
86
+ componentMapLines.push(`\t'${entry.slug}': attachMdxExports(${identifier}_module, '${escapedSourceFile}'),`);
87
+ entrySourceFilesBySlugLines.push(`\t'${entry.slug}': '${escapedSourceFile}',`);
49
88
  }
50
89
  return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
51
90
 
52
- import type { EcoComponent } from '@ecopages/core';
91
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
92
+
93
+ ${renderAttachMdxExportsHelper()}
53
94
 
54
95
  ${importLines.join('\n')}
55
96
 
@@ -57,11 +98,28 @@ const componentsBySlug: Record<string, EcoComponent<Record<string, unknown>>> =
57
98
  ${componentMapLines.join('\n')}
58
99
  };
59
100
 
101
+ const entrySourceFilesBySlug: Record<string, string> = {
102
+ ${entrySourceFilesBySlugLines.join('\n')}
103
+ };
104
+
60
105
  export function getComponent(slug: string): EcoComponent<Record<string, unknown>> {
61
106
  const component = componentsBySlug[slug];
62
107
  if (!component) throw new Error(\`Unknown content entry: \${slug}\`);
63
108
  return component;
64
109
  }
110
+
111
+ export function getEntryDependencies(slug: string): PageDependenciesResult | undefined {
112
+ const component = getComponent(slug);
113
+ const dependencies = component.config?.dependencies;
114
+ if (!dependencies) {
115
+ return undefined;
116
+ }
117
+
118
+ return {
119
+ ...dependencies,
120
+ ownerFile: entrySourceFilesBySlug[slug],
121
+ };
122
+ }
65
123
  `;
66
124
  }
67
125
  function resolveEntryTypeImport(entryType, rootDir, typesOutputFile) {
@@ -97,9 +155,10 @@ function renderCollectionEntriesTypesModule(collectionName, entryType, typeResol
97
155
  }
98
156
  function renderCollectionComponentsTypesModule(collectionName) {
99
157
  return `declare module "ecopages:content/${collectionName}/server" {
100
- import type { EcoComponent } from '@ecopages/core';
158
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
101
159
 
102
160
  export function getComponent(slug: string): EcoComponent<Record<string, unknown>>;
161
+ export function getEntryDependencies(slug: string): PageDependenciesResult | undefined;
103
162
  }`;
104
163
  }
105
164
  export function renderCollectionTypesModule(collectionName, entryType, typeResolution) {
@@ -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';
@@ -84,4 +84,68 @@ export class ContentScanner {
84
84
  filePath: cache.filePathsBySlug.get(entry.slug),
85
85
  }));
86
86
  }
87
+ /**
88
+ * Re-parses one content file and updates the in-memory manifest.
89
+ *
90
+ * @remarks
91
+ * Returns `no-op` when only the MDX body changed so callers can skip
92
+ * rewriting generated collection modules during dev HMR.
93
+ */
94
+ async updateEntryForPath(filePath, event) {
95
+ const resolvedPath = resolve(filePath);
96
+ const cache = await this.getCache();
97
+ if (event === 'delete') {
98
+ return this.removeEntryAtPath(cache, resolvedPath);
99
+ }
100
+ const relativePath = relative(this.config.contentRoot, resolvedPath);
101
+ const nextSlug = slugFromRelativePath(relativePath, this.extensions);
102
+ const previousSlug = this.findSlugForFilePath(cache, resolvedPath);
103
+ return this.upsertEntryAtPath(cache, resolvedPath, nextSlug, previousSlug);
104
+ }
105
+ findSlugForFilePath(cache, filePath) {
106
+ for (const [slug, currentPath] of cache.filePathsBySlug) {
107
+ if (resolve(currentPath) === filePath) {
108
+ return slug;
109
+ }
110
+ }
111
+ return undefined;
112
+ }
113
+ removeEntryAtPath(cache, filePath) {
114
+ const slug = this.findSlugForFilePath(cache, filePath);
115
+ if (!slug) {
116
+ return 'no-op';
117
+ }
118
+ cache.filePathsBySlug.delete(slug);
119
+ cache.manifest = cache.manifest.filter((entry) => entry.slug !== slug);
120
+ return 'structure';
121
+ }
122
+ async upsertEntryAtPath(cache, filePath, nextSlug, previousSlug) {
123
+ const raw = await fileSystem.readFile(filePath);
124
+ const nextEntry = {
125
+ ...(await this.parseFrontmatter(raw)),
126
+ slug: nextSlug,
127
+ segments: nextSlug.split('/'),
128
+ };
129
+ if (!previousSlug) {
130
+ cache.manifest.push(nextEntry);
131
+ cache.filePathsBySlug.set(nextSlug, filePath);
132
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
133
+ return 'structure';
134
+ }
135
+ const previousEntry = cache.manifest.find((entry) => entry.slug === previousSlug);
136
+ if (!previousEntry) {
137
+ cache.manifest.push(nextEntry);
138
+ cache.filePathsBySlug.set(nextSlug, filePath);
139
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
140
+ return 'structure';
141
+ }
142
+ const entryMatches = JSON.stringify(previousEntry) === JSON.stringify(nextEntry);
143
+ if (entryMatches) {
144
+ return 'no-op';
145
+ }
146
+ cache.manifest = cache.manifest.map((entry) => (entry.slug === previousSlug ? nextEntry : entry));
147
+ cache.filePathsBySlug.set(nextSlug, filePath);
148
+ cache.manifest.sort((left, right) => this.orderBy(left, right));
149
+ return 'manifest';
150
+ }
87
151
  }
package/src/plugin.d.ts CHANGED
@@ -28,9 +28,10 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
28
28
  private writeGeneratedFile;
29
29
  private getOrCreateScanner;
30
30
  private regenerateCollectionModule;
31
+ private regenerateCollectionEntriesModule;
31
32
  private regenerateCollections;
32
33
  private regenerateAllCollections;
33
- private regenerateCollectionsForPath;
34
+ private handleContentFileEvent;
34
35
  private initializeWatchPaths;
35
36
  private generateTypes;
36
37
  private ensureCollectionsGenerated;
package/src/plugin.js CHANGED
@@ -40,9 +40,9 @@ export class ContentProcessorPlugin extends Processor {
40
40
  const defaultWatchConfig = {
41
41
  paths: [],
42
42
  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),
43
+ onCreate: async (ctx) => this.handleContentFileEvent(ctx.path, 'create'),
44
+ onChange: async (ctx) => this.handleContentFileEvent(ctx.path, 'change'),
45
+ onDelete: async (ctx) => this.handleContentFileEvent(ctx.path, 'delete'),
46
46
  };
47
47
  super({
48
48
  ...config,
@@ -126,6 +126,18 @@ export class ContentProcessorPlugin extends Processor {
126
126
  entryCount: manifest.length,
127
127
  });
128
128
  }
129
+ async regenerateCollectionEntriesModule(collectionName) {
130
+ if (!this.context?.cache) {
131
+ throw new Error('Content processor requires context to be set');
132
+ }
133
+ assertValidCollectionName(collectionName);
134
+ const scanner = this.getOrCreateScanner(collectionName);
135
+ const manifest = (await scanner.getManifest()).map((entry) => entry);
136
+ const outputFile = getCollectionCachePath(this.context.cache, collectionName);
137
+ const entriesOutput = renderCollectionEntriesModule(collectionName, manifest);
138
+ this.writeGeneratedFile(outputFile, entriesOutput);
139
+ this.collectionModules[collectionName] = outputFile;
140
+ }
129
141
  async regenerateCollections(collectionNames) {
130
142
  for (const collectionName of collectionNames) {
131
143
  await this.regenerateCollectionModule(collectionName);
@@ -135,7 +147,7 @@ export class ContentProcessorPlugin extends Processor {
135
147
  async regenerateAllCollections() {
136
148
  await this.regenerateCollections(Object.keys(this.getCollectionsConfig()));
137
149
  }
138
- async regenerateCollectionsForPath(filePath) {
150
+ async handleContentFileEvent(filePath, event) {
139
151
  if (!this.context) {
140
152
  return;
141
153
  }
@@ -147,8 +159,28 @@ export class ContentProcessorPlugin extends Processor {
147
159
  affectedCollections.push(collectionName);
148
160
  }
149
161
  }
150
- if (affectedCollections.length > 0) {
151
- await this.regenerateCollections(affectedCollections);
162
+ let shouldRegenerateTypes = false;
163
+ for (const collectionName of affectedCollections) {
164
+ if (event === 'create' || event === 'delete') {
165
+ await this.regenerateCollectionModule(collectionName);
166
+ shouldRegenerateTypes = true;
167
+ continue;
168
+ }
169
+ const scanner = this.getOrCreateScanner(collectionName);
170
+ const updateResult = await scanner.updateEntryForPath(normalizedPath, event);
171
+ if (updateResult === 'no-op') {
172
+ continue;
173
+ }
174
+ if (updateResult === 'manifest') {
175
+ await this.regenerateCollectionEntriesModule(collectionName);
176
+ shouldRegenerateTypes = true;
177
+ continue;
178
+ }
179
+ await this.regenerateCollectionModule(collectionName);
180
+ shouldRegenerateTypes = true;
181
+ }
182
+ if (shouldRegenerateTypes) {
183
+ this.generateTypes();
152
184
  }
153
185
  }
154
186
  initializeWatchPaths() {
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
  /**
@@ -22,6 +22,7 @@ export type ContentCollectionEntriesModule<TEntry extends Record<string, unknown
22
22
  /** Runtime shape of a generated `ecopages:content/<collection>/server` module. */
23
23
  export type ContentCollectionComponentsModule = {
24
24
  getComponent(slug: string): EcoComponent<Record<string, unknown>>;
25
+ getEntryDependencies(slug: string): 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;