@ecopages/content-processor 0.2.0-beta.30 → 0.2.0-beta.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/content-processor",
3
- "version": "0.2.0-beta.30",
3
+ "version": "0.2.0-beta.32",
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.30"
20
+ "@ecopages/core": "0.2.0-beta.32"
21
21
  },
22
22
  "dependencies": {
23
- "@ecopages/file-system": "0.2.0-beta.30",
23
+ "@ecopages/file-system": "0.2.0-beta.32",
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
@@ -1,30 +1,30 @@
1
- import { relative, resolve, dirname, join } from "node:path";
1
+ import { relative, resolve, dirname, join } from 'node:path';
2
2
  function slugToIdentifier(collectionName, slug) {
3
- return `${collectionName}_${slug.replace(/[^a-zA-Z0-9]/g, "_")}`;
3
+ return `${collectionName}_${slug.replace(/[^a-zA-Z0-9]/g, '_')}`;
4
4
  }
5
5
  function serializeEntry(entry) {
6
- return JSON.stringify(entry);
6
+ return JSON.stringify(entry);
7
7
  }
8
8
  function parseEntryTypeImport(entryType) {
9
- const [module, name = "Entry"] = entryType.split("#");
10
- if (!module) {
11
- throw new Error(`Invalid entryType "${entryType}". Expected format: "./path/to/file#TypeName"`);
12
- }
13
- return { module, name };
9
+ const [module, name = 'Entry'] = entryType.split('#');
10
+ if (!module) {
11
+ throw new Error(`Invalid entryType "${entryType}". Expected format: "./path/to/file#TypeName"`);
12
+ }
13
+ return { module, name };
14
14
  }
15
- function renderCollectionEntriesModule(collectionName, manifest) {
16
- const entriesBySlugLines = [];
17
- for (const [index, entry] of manifest.entries()) {
18
- entriesBySlugLines.push(` '${entry.slug}': entries[${index}],`);
19
- }
20
- return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
15
+ export function renderCollectionEntriesModule(collectionName, manifest) {
16
+ const entriesBySlugLines = [];
17
+ for (const [index, entry] of manifest.entries()) {
18
+ entriesBySlugLines.push(`\t'${entry.slug}': entries[${index}],`);
19
+ }
20
+ return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
21
21
 
22
22
  export const entries = [
23
- ${manifest.map((entry) => ` ${serializeEntry(entry)},`).join("\n")}
23
+ ${manifest.map((entry) => `\t${serializeEntry(entry)},`).join('\n')}
24
24
  ] as const;
25
25
 
26
26
  const entriesBySlug: Record<string, (typeof entries)[number]> = {
27
- ${entriesBySlugLines.join("\n")}
27
+ ${entriesBySlugLines.join('\n')}
28
28
  };
29
29
 
30
30
  export function getEntry(slug: string) {
@@ -38,23 +38,23 @@ export function getEntryBySegments(segments: string[]) {
38
38
  }
39
39
  `;
40
40
  }
41
- function renderCollectionComponentsModule(collectionName, outputDir, entrySources) {
42
- const importLines = [];
43
- const componentMapLines = [];
44
- for (const { entry, filePath } of entrySources) {
45
- const identifier = slugToIdentifier(collectionName, entry.slug);
46
- const importPath = relative(outputDir, filePath).split("\\").join("/");
47
- importLines.push(`import ${identifier} from '${importPath}';`);
48
- componentMapLines.push(` '${entry.slug}': ${identifier},`);
49
- }
50
- return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
41
+ export function renderCollectionComponentsModule(collectionName, outputDir, entrySources) {
42
+ const importLines = [];
43
+ const componentMapLines = [];
44
+ for (const { entry, filePath } of entrySources) {
45
+ const identifier = slugToIdentifier(collectionName, entry.slug);
46
+ const importPath = relative(outputDir, filePath).split('\\').join('/');
47
+ importLines.push(`import ${identifier} from '${importPath}';`);
48
+ componentMapLines.push(`\t'${entry.slug}': ${identifier},`);
49
+ }
50
+ return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
51
51
 
52
52
  import type { EcoComponent } from '@ecopages/core';
53
53
 
54
- ${importLines.join("\n")}
54
+ ${importLines.join('\n')}
55
55
 
56
56
  const componentsBySlug: Record<string, EcoComponent<Record<string, unknown>>> = {
57
- ${componentMapLines.join("\n")}
57
+ ${componentMapLines.join('\n')}
58
58
  };
59
59
 
60
60
  export function getComponent(slug: string): EcoComponent<Record<string, unknown>> {
@@ -65,29 +65,29 @@ export function getComponent(slug: string): EcoComponent<Record<string, unknown>
65
65
  `;
66
66
  }
67
67
  function resolveEntryTypeImport(entryType, rootDir, typesOutputFile) {
68
- const { module, name } = parseEntryTypeImport(entryType);
69
- const absoluteModule = resolve(rootDir, module);
70
- const srcDir = join(rootDir, "src");
71
- const relativeToSrc = relative(srcDir, absoluteModule).split("\\").join("/");
72
- if (!relativeToSrc.startsWith("..") && !relativeToSrc.startsWith("/")) {
73
- return { module: `@/${relativeToSrc}`, name };
74
- }
75
- let relativeModule = relative(dirname(typesOutputFile), absoluteModule).split("\\").join("/");
76
- if (!relativeModule.startsWith(".")) {
77
- relativeModule = `./${relativeModule}`;
78
- }
79
- return { module: relativeModule, name };
68
+ const { module, name } = parseEntryTypeImport(entryType);
69
+ const absoluteModule = resolve(rootDir, module);
70
+ const srcDir = join(rootDir, 'src');
71
+ const relativeToSrc = relative(srcDir, absoluteModule).split('\\').join('/');
72
+ if (!relativeToSrc.startsWith('..') && !relativeToSrc.startsWith('/')) {
73
+ return { module: `@/${relativeToSrc}`, name };
74
+ }
75
+ let relativeModule = relative(dirname(typesOutputFile), absoluteModule).split('\\').join('/');
76
+ if (!relativeModule.startsWith('.')) {
77
+ relativeModule = `./${relativeModule}`;
78
+ }
79
+ return { module: relativeModule, name };
80
80
  }
81
81
  function renderCollectionEntriesTypesModule(collectionName, entryType, typeResolution) {
82
- const entryDeclaration = entryType ? (() => {
83
- const { module, name } = typeResolution ? resolveEntryTypeImport(entryType, typeResolution.rootDir, typeResolution.typesOutputFile) : parseEntryTypeImport(entryType);
84
- return `import type { ContentEntry } from '@ecopages/content-processor/types';
85
- import type { ${name} } from '${module}';
86
- export type Entry = ContentEntry<${name}>;`;
87
- })() : `import type { ContentEntry } from '@ecopages/content-processor/types';
88
-
89
- export type Entry = ContentEntry<Record<string, unknown>>;`;
90
- return `declare module "ecopages:content/${collectionName}" {
82
+ const entryDeclaration = entryType
83
+ ? (() => {
84
+ const { module, name } = typeResolution
85
+ ? resolveEntryTypeImport(entryType, typeResolution.rootDir, typeResolution.typesOutputFile)
86
+ : parseEntryTypeImport(entryType);
87
+ return `import type { ContentEntry } from '@ecopages/content-processor/types';\n\timport type { ${name} } from '${module}';\n\texport type Entry = ContentEntry<${name}>;`;
88
+ })()
89
+ : `import type { ContentEntry } from '@ecopages/content-processor/types';\n\n\texport type Entry = ContentEntry<Record<string, unknown>>;`;
90
+ return `declare module "ecopages:content/${collectionName}" {
91
91
  ${entryDeclaration}
92
92
 
93
93
  export const entries: readonly Entry[];
@@ -96,29 +96,23 @@ function renderCollectionEntriesTypesModule(collectionName, entryType, typeResol
96
96
  }`;
97
97
  }
98
98
  function renderCollectionComponentsTypesModule(collectionName) {
99
- return `declare module "ecopages:content/${collectionName}/server" {
99
+ return `declare module "ecopages:content/${collectionName}/server" {
100
100
  import type { EcoComponent } from '@ecopages/core';
101
101
 
102
102
  export function getComponent(slug: string): EcoComponent<Record<string, unknown>>;
103
103
  }`;
104
104
  }
105
- function renderCollectionTypesModule(collectionName, entryType, typeResolution) {
106
- return `${renderCollectionEntriesTypesModule(collectionName, entryType, typeResolution)}
107
-
108
- ${renderCollectionComponentsTypesModule(collectionName)}`;
105
+ export function renderCollectionTypesModule(collectionName, entryType, typeResolution) {
106
+ return `${renderCollectionEntriesTypesModule(collectionName, entryType, typeResolution)}\n\n${renderCollectionComponentsTypesModule(collectionName)}`;
109
107
  }
110
- function renderVirtualModuleTypes(collections, typeResolution) {
111
- return `/**
108
+ export function renderVirtualModuleTypes(collections, typeResolution) {
109
+ return `/**
112
110
  * Do not edit manually. This file is auto-generated.
113
111
  * Virtual module types for ecopages:content/* imports.
114
112
  */
115
113
 
116
- ${Object.entries(collections).map(([name, definition]) => renderCollectionTypesModule(name, definition.entryType, typeResolution)).join("\n\n")}
114
+ ${Object.entries(collections)
115
+ .map(([name, definition]) => renderCollectionTypesModule(name, definition.entryType, typeResolution))
116
+ .join('\n\n')}
117
117
  `;
118
118
  }
119
- export {
120
- renderCollectionComponentsModule,
121
- renderCollectionEntriesModule,
122
- renderCollectionTypesModule,
123
- renderVirtualModuleTypes
124
- };
@@ -0,0 +1 @@
1
+ export {};
package/src/constants.js CHANGED
@@ -1,12 +1,10 @@
1
- const CONTENT_PROCESSOR_NAME = "ecopages-content-processor";
2
- const CONTENT_VIRTUAL_MODULE_PREFIX = "ecopages:content";
3
- const CONTENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]*$/;
4
- const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/server$/;
5
- const COLLECTION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
6
- export {
7
- COLLECTION_NAME_PATTERN,
8
- CONTENT_PROCESSOR_NAME,
9
- CONTENT_SERVER_VIRTUAL_MODULE_PATTERN,
10
- CONTENT_VIRTUAL_MODULE_PATTERN,
11
- CONTENT_VIRTUAL_MODULE_PREFIX
12
- };
1
+ /** Processor registry name and generated artifact namespace. */
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$/;
9
+ /** Validates collection keys used in processor options and virtual module paths. */
10
+ export const COLLECTION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
@@ -1,105 +1,100 @@
1
- import path from "node:path";
2
- import { fileSystem } from "@ecopages/file-system";
3
- import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN } from "./constants.js";
4
- function parseCollectionName(specifier) {
5
- const parsed = parseCollectionSpecifier(specifier);
6
- return parsed?.collectionName ?? null;
1
+ import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN } from './constants.js';
4
+ export function parseCollectionName(specifier) {
5
+ const parsed = parseCollectionSpecifier(specifier);
6
+ return parsed?.collectionName ?? null;
7
7
  }
8
- function parseCollectionSpecifier(specifier) {
9
- const normalized = specifier.startsWith("ecopages:content/") ? specifier.slice("ecopages:content/".length) : specifier.startsWith("content/") ? specifier.slice("content/".length) : null;
10
- if (!normalized) {
11
- return null;
12
- }
13
- if (normalized.endsWith("/server")) {
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
+ }
14
23
  return {
15
- collectionName: normalized.slice(0, -"/server".length),
16
- variant: "server"
24
+ collectionName: normalized,
25
+ variant: 'entries',
17
26
  };
18
- }
19
- return {
20
- collectionName: normalized,
21
- variant: "entries"
22
- };
23
27
  }
24
- function resolveCollectionPath(specifier, collectionModules, collectionServerModules) {
25
- const parsed = parseCollectionSpecifier(specifier);
26
- if (!parsed) {
27
- return null;
28
- }
29
- if (parsed.variant === "server") {
30
- return collectionServerModules[parsed.collectionName] ?? null;
31
- }
32
- return collectionModules[parsed.collectionName] ?? null;
28
+ export function resolveCollectionPath(specifier, collectionModules, collectionServerModules) {
29
+ const parsed = parseCollectionSpecifier(specifier);
30
+ if (!parsed) {
31
+ return null;
32
+ }
33
+ if (parsed.variant === 'server') {
34
+ return collectionServerModules[parsed.collectionName] ?? null;
35
+ }
36
+ return collectionModules[parsed.collectionName] ?? null;
33
37
  }
34
38
  function createContentResolvePlugin(collectionModules, collectionServerModules, options) {
35
- return {
36
- name: "ecopages:content",
37
- setup(build) {
38
- const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules);
39
- build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, (args) => {
40
- const modulePath = resolveCollection(args.path);
41
- if (!modulePath) {
42
- return void 0;
43
- }
44
- if (options.namespace) {
45
- return {
46
- namespace: options.namespace,
47
- path: modulePath
48
- };
49
- }
50
- return { path: modulePath };
51
- });
52
- if (options.includeServerModules !== false) {
53
- build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => {
54
- const modulePath = resolveCollection(args.path);
55
- if (!modulePath) {
56
- return void 0;
57
- }
58
- if (options.namespace) {
59
- return {
60
- namespace: options.namespace,
61
- path: modulePath
62
- };
63
- }
64
- return { path: modulePath };
65
- });
66
- }
67
- }
68
- };
39
+ return {
40
+ name: 'ecopages:content',
41
+ setup(build) {
42
+ const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules);
43
+ build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, (args) => {
44
+ const modulePath = resolveCollection(args.path);
45
+ if (!modulePath) {
46
+ return undefined;
47
+ }
48
+ if (options.namespace) {
49
+ return {
50
+ namespace: options.namespace,
51
+ path: modulePath,
52
+ };
53
+ }
54
+ return { path: modulePath };
55
+ });
56
+ if (options.includeServerModules !== false) {
57
+ build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => {
58
+ const modulePath = resolveCollection(args.path);
59
+ if (!modulePath) {
60
+ return undefined;
61
+ }
62
+ if (options.namespace) {
63
+ return {
64
+ namespace: options.namespace,
65
+ path: modulePath,
66
+ };
67
+ }
68
+ return { path: modulePath };
69
+ });
70
+ }
71
+ },
72
+ };
69
73
  }
70
- function createContentPlugin(collectionModules, collectionServerModules) {
71
- return createContentResolvePlugin(collectionModules, collectionServerModules, {
72
- includeServerModules: true
73
- });
74
+ export function createContentPlugin(collectionModules, collectionServerModules) {
75
+ return createContentResolvePlugin(collectionModules, collectionServerModules, {
76
+ includeServerModules: true,
77
+ });
74
78
  }
75
- function createContentPluginBundler(collectionModules, collectionServerModules) {
76
- const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, {
77
- namespace: "ecopages-content",
78
- includeServerModules: false
79
- });
80
- return {
81
- name: plugin.name,
82
- setup(build) {
83
- plugin.setup?.(build);
84
- build.onLoad({ filter: /.*/, namespace: "ecopages-content" }, async (args) => {
85
- const contents = await fileSystem.readFile(args.path);
86
- return { contents, loader: "ts" };
87
- });
88
- }
89
- };
79
+ export function createContentPluginBundler(collectionModules, collectionServerModules) {
80
+ const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, {
81
+ namespace: 'ecopages-content',
82
+ includeServerModules: false,
83
+ });
84
+ return {
85
+ name: plugin.name,
86
+ setup(build) {
87
+ plugin.setup?.(build);
88
+ build.onLoad({ filter: /.*/, namespace: 'ecopages-content' }, async (args) => {
89
+ const contents = await fileSystem.readFile(args.path);
90
+ return { contents, loader: 'ts' };
91
+ });
92
+ },
93
+ };
90
94
  }
91
- function getCollectionCachePath(cacheDir, collectionName) {
92
- return path.join(cacheDir, `${collectionName}.ts`);
95
+ export function getCollectionCachePath(cacheDir, collectionName) {
96
+ return path.join(cacheDir, `${collectionName}.ts`);
93
97
  }
94
- function getCollectionServerCachePath(cacheDir, collectionName) {
95
- return path.join(cacheDir, `${collectionName}.server.ts`);
98
+ export function getCollectionServerCachePath(cacheDir, collectionName) {
99
+ return path.join(cacheDir, `${collectionName}.server.ts`);
96
100
  }
97
- export {
98
- createContentPlugin,
99
- createContentPluginBundler,
100
- getCollectionCachePath,
101
- getCollectionServerCachePath,
102
- parseCollectionName,
103
- parseCollectionSpecifier,
104
- resolveCollectionPath
105
- };
@@ -1,88 +1,87 @@
1
- import { join, sep } from "node:path";
2
- import { validateStandardSchema } from "@ecopages/core";
3
- import { VFile } from "vfile";
4
- import { matter } from "vfile-matter";
5
- import { fileSystem } from "@ecopages/file-system";
6
- import { compareEntriesBySlug } from "./sort.js";
1
+ import { join, sep } from 'node:path';
2
+ import { validateStandardSchema } from '@ecopages/core';
3
+ import { VFile } from 'vfile';
4
+ import { matter } from 'vfile-matter';
5
+ import { fileSystem } from '@ecopages/file-system';
6
+ import { compareEntriesBySlug } from './sort.js';
7
7
  function slugFromRelativePath(relativePath, extensions) {
8
- for (const ext of extensions) {
9
- if (relativePath.endsWith(ext)) {
10
- return relativePath.slice(0, -ext.length).split(sep).join("/");
8
+ for (const ext of extensions) {
9
+ if (relativePath.endsWith(ext)) {
10
+ return relativePath.slice(0, -ext.length).split(sep).join('/');
11
+ }
11
12
  }
12
- }
13
- return relativePath.split(sep).join("/");
13
+ return relativePath.split(sep).join('/');
14
14
  }
15
- class ContentScanner {
16
- constructor(config) {
17
- this.config = config;
18
- this.extensions = config.extensions ?? [".mdx"];
19
- this.orderBy = config.orderBy ?? compareEntriesBySlug;
20
- this.schema = config.schema;
21
- }
22
- config;
23
- extensions;
24
- orderBy;
25
- schema;
26
- cachePromise;
27
- clearCache() {
28
- this.cachePromise = void 0;
29
- }
30
- async parseFrontmatter(raw) {
31
- const file = new VFile({ value: raw });
32
- matter(file);
33
- return validateStandardSchema(this.schema, file.data.matter);
34
- }
35
- async loadCache() {
36
- const patterns = this.extensions.map((ext) => `**/*${ext}`);
37
- const relativePaths = await fileSystem.glob(patterns, { cwd: this.config.contentRoot });
38
- const files = await Promise.all(
39
- relativePaths.map(async (relativePath) => {
40
- const filePath = join(this.config.contentRoot, relativePath);
41
- const slug = slugFromRelativePath(relativePath, this.extensions);
42
- const raw = await fileSystem.readFile(filePath);
43
- const entry = {
44
- ...await this.parseFrontmatter(raw),
45
- slug,
46
- segments: slug.split("/")
15
+ /**
16
+ * Scans a content directory and exposes manifest metadata plus source file paths.
17
+ * Used by the content processor at build time; it does not belong in page bundles.
18
+ */
19
+ export class ContentScanner {
20
+ config;
21
+ extensions;
22
+ orderBy;
23
+ schema;
24
+ cachePromise;
25
+ constructor(config) {
26
+ this.config = config;
27
+ this.extensions = config.extensions ?? ['.mdx'];
28
+ this.orderBy = config.orderBy ?? compareEntriesBySlug;
29
+ this.schema = config.schema;
30
+ }
31
+ clearCache() {
32
+ this.cachePromise = undefined;
33
+ }
34
+ async parseFrontmatter(raw) {
35
+ const file = new VFile({ value: raw });
36
+ matter(file);
37
+ return validateStandardSchema(this.schema, file.data.matter);
38
+ }
39
+ async loadCache() {
40
+ const patterns = this.extensions.map((ext) => `**/*${ext}`);
41
+ const relativePaths = await fileSystem.glob(patterns, { cwd: this.config.contentRoot });
42
+ const files = await Promise.all(relativePaths.map(async (relativePath) => {
43
+ const filePath = join(this.config.contentRoot, relativePath);
44
+ const slug = slugFromRelativePath(relativePath, this.extensions);
45
+ const raw = await fileSystem.readFile(filePath);
46
+ const entry = {
47
+ ...(await this.parseFrontmatter(raw)),
48
+ slug,
49
+ segments: slug.split('/'),
50
+ };
51
+ return { filePath, entry };
52
+ }));
53
+ files.sort((a, b) => this.orderBy(a.entry, b.entry));
54
+ const filePathsBySlug = new Map();
55
+ for (const { entry, filePath } of files) {
56
+ filePathsBySlug.set(entry.slug, filePath);
57
+ }
58
+ return {
59
+ manifest: files.map((file) => file.entry),
60
+ filePathsBySlug,
47
61
  };
48
- return { filePath, entry };
49
- })
50
- );
51
- files.sort((a, b) => this.orderBy(a.entry, b.entry));
52
- const filePathsBySlug = /* @__PURE__ */ new Map();
53
- for (const { entry, filePath } of files) {
54
- filePathsBySlug.set(entry.slug, filePath);
55
62
  }
56
- return {
57
- manifest: files.map((file) => file.entry),
58
- filePathsBySlug
59
- };
60
- }
61
- async getCache() {
62
- if (!this.cachePromise) {
63
- this.cachePromise = this.loadCache();
63
+ async getCache() {
64
+ if (!this.cachePromise) {
65
+ this.cachePromise = this.loadCache();
66
+ }
67
+ return this.cachePromise;
68
+ }
69
+ async getManifest() {
70
+ return (await this.getCache()).manifest;
71
+ }
72
+ async getRawContent(slug) {
73
+ const cache = await this.getCache();
74
+ const filePath = cache.filePathsBySlug.get(slug);
75
+ if (!filePath) {
76
+ throw new Error(`Unknown content entry: ${slug}`);
77
+ }
78
+ return fileSystem.readFile(filePath);
64
79
  }
65
- return this.cachePromise;
66
- }
67
- async getManifest() {
68
- return (await this.getCache()).manifest;
69
- }
70
- async getRawContent(slug) {
71
- const cache = await this.getCache();
72
- const filePath = cache.filePathsBySlug.get(slug);
73
- if (!filePath) {
74
- throw new Error(`Unknown content entry: ${slug}`);
80
+ async getEntrySources() {
81
+ const cache = await this.getCache();
82
+ return cache.manifest.map((entry) => ({
83
+ entry,
84
+ filePath: cache.filePathsBySlug.get(entry.slug),
85
+ }));
75
86
  }
76
- return fileSystem.readFile(filePath);
77
- }
78
- async getEntrySources() {
79
- const cache = await this.getCache();
80
- return cache.manifest.map((entry) => ({
81
- entry,
82
- filePath: cache.filePathsBySlug.get(entry.slug)
83
- }));
84
- }
85
87
  }
86
- export {
87
- ContentScanner
88
- };
@@ -1,15 +1,19 @@
1
- import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN } from "./constants.js";
2
- function createContentServerBoundaryPlugin() {
3
- return {
4
- name: "ecopages:content-server-boundary",
5
- setup(build) {
6
- build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => ({
7
- path: args.path,
8
- external: true
9
- }));
10
- }
11
- };
1
+ import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN } from './constants.js';
2
+ /**
3
+ * Keeps `ecopages:content/<collection>/server` out of browser bundles.
4
+ *
5
+ * @remarks
6
+ * Server modules static-import every MDX entry for `getComponent`. Browser builds
7
+ * must never follow that graph — highlighted MDX output belongs in SSR HTML only.
8
+ */
9
+ export function createContentServerBoundaryPlugin() {
10
+ return {
11
+ name: 'ecopages:content-server-boundary',
12
+ setup(build) {
13
+ build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => ({
14
+ path: args.path,
15
+ external: true,
16
+ }));
17
+ },
18
+ };
12
19
  }
13
- export {
14
- createContentServerBoundaryPlugin
15
- };
package/src/index.js CHANGED
@@ -1,17 +1,3 @@
1
- import { ContentScanner } from "./content-scanner.js";
2
- import {
3
- CONTENT_PROCESSOR_NAME,
4
- CONTENT_VIRTUAL_MODULE_PATTERN,
5
- CONTENT_VIRTUAL_MODULE_PREFIX,
6
- COLLECTION_NAME_PATTERN
7
- } from "./constants.js";
8
- import { compareEntriesByField, compareEntriesBySlug } from "./sort.js";
9
- export {
10
- COLLECTION_NAME_PATTERN,
11
- CONTENT_PROCESSOR_NAME,
12
- CONTENT_VIRTUAL_MODULE_PATTERN,
13
- CONTENT_VIRTUAL_MODULE_PREFIX,
14
- ContentScanner,
15
- compareEntriesByField,
16
- compareEntriesBySlug
17
- };
1
+ export { ContentScanner } from './content-scanner.js';
2
+ export { CONTENT_PROCESSOR_NAME, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, COLLECTION_NAME_PATTERN, } from './constants.js';
3
+ export { compareEntriesByField, compareEntriesBySlug } from './sort.js';
package/src/mdx.js CHANGED
@@ -1,12 +1,16 @@
1
- import remarkFrontmatter from "remark-frontmatter";
2
- import { default as default2 } from "remark-frontmatter";
3
- function withContentMdxPlugins(options = {}) {
4
- return {
5
- remarkPlugins: [remarkFrontmatter, ...options.remarkPlugins ?? []],
6
- rehypePlugins: options.rehypePlugins ?? []
7
- };
1
+ import remarkFrontmatter from 'remark-frontmatter';
2
+ export { default as remarkFrontmatter } from 'remark-frontmatter';
3
+ /**
4
+ * Builds MDX plugin options for content collections that use YAML frontmatter.
5
+ *
6
+ * Prepends `remark-frontmatter` so `---` blocks are consumed at compile time
7
+ * instead of rendering as thematic breaks. Pair this with
8
+ * `contentProcessorPlugin()` — the processor validates frontmatter at scan time;
9
+ * this helper wires the matching MDX remark plugin for render time.
10
+ */
11
+ export function withContentMdxPlugins(options = {}) {
12
+ return {
13
+ remarkPlugins: [remarkFrontmatter, ...(options.remarkPlugins ?? [])],
14
+ rehypePlugins: options.rehypePlugins ?? [],
15
+ };
8
16
  }
9
- export {
10
- default2 as remarkFrontmatter,
11
- withContentMdxPlugins
12
- };
package/src/plugin.js CHANGED
@@ -1,218 +1,205 @@
1
- import path from "node:path";
2
- import { fileSystem } from "@ecopages/file-system";
3
- import {
4
- mergeProcessorOptions,
5
- Processor,
6
- resolveGeneratedPath
7
- } from "@ecopages/core/plugins/processor";
8
- import { Logger } from "@ecopages/logger";
9
- import {
10
- renderCollectionComponentsModule,
11
- renderCollectionEntriesModule,
12
- renderVirtualModuleTypes
13
- } from "./codegen.js";
14
- import { compareEntriesBySlug } from "./sort.js";
15
- import { ContentScanner } from "./content-scanner.js";
16
- import {
17
- createContentPlugin,
18
- createContentPluginBundler,
19
- getCollectionCachePath,
20
- getCollectionServerCachePath
21
- } from "./content-plugins.js";
22
- import { createContentServerBoundaryPlugin } from "./content-server-boundary-plugin.js";
23
- import { COLLECTION_NAME_PATTERN, CONTENT_PROCESSOR_NAME } from "./constants.js";
24
- const logger = new Logger("[@ecopages/content-processor]", {
25
- debug: process.env.ECOPAGES_LOGGER_DEBUG === "true"
1
+ /**
2
+ * ContentProcessorPlugin
3
+ * @module @ecopages/content-processor
4
+ */
5
+ import path from 'node:path';
6
+ import { fileSystem } from '@ecopages/file-system';
7
+ import { mergeProcessorOptions, Processor, resolveGeneratedPath, } from '@ecopages/core/plugins/processor';
8
+ import { Logger } from '@ecopages/logger';
9
+ import { renderCollectionComponentsModule, renderCollectionEntriesModule, renderVirtualModuleTypes, } from './codegen.js';
10
+ import { compareEntriesBySlug } from './sort.js';
11
+ import { ContentScanner } from './content-scanner.js';
12
+ import { createContentPlugin, createContentPluginBundler, getCollectionCachePath, getCollectionServerCachePath, } from './content-plugins.js';
13
+ import { createContentServerBoundaryPlugin } from './content-server-boundary-plugin.js';
14
+ import { COLLECTION_NAME_PATTERN, CONTENT_PROCESSOR_NAME } from './constants.js';
15
+ const logger = new Logger('[@ecopages/content-processor]', {
16
+ debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true',
26
17
  });
27
18
  function assertValidCollectionName(collectionName) {
28
- if (!COLLECTION_NAME_PATTERN.test(collectionName)) {
29
- throw new Error(
30
- `Invalid content collection name "${collectionName}". Use kebab-case identifiers matching ${COLLECTION_NAME_PATTERN}.`
31
- );
32
- }
19
+ if (!COLLECTION_NAME_PATTERN.test(collectionName)) {
20
+ throw new Error(`Invalid content collection name "${collectionName}". Use kebab-case identifiers matching ${COLLECTION_NAME_PATTERN}.`);
21
+ }
33
22
  }
34
- class ContentProcessorPlugin extends Processor {
35
- collectionsGenerated = false;
36
- scanners = /* @__PURE__ */ new Map();
37
- /**
38
- * Absolute paths to generated collection entry modules, keyed by collection name.
39
- * Virtual-module plugins close over this object so mutations stay live.
40
- */
41
- collectionModules = {};
42
- /**
43
- * Absolute paths to generated server-only component resolver modules.
44
- */
45
- collectionServerModules = {};
46
- constructor(config) {
47
- const defaultWatchConfig = {
48
- paths: [],
49
- extensions: ["mdx"],
50
- onCreate: async (ctx) => this.regenerateCollectionsForPath(ctx.path),
51
- onChange: async (ctx) => this.regenerateCollectionsForPath(ctx.path),
52
- onDelete: async (ctx) => this.regenerateCollectionsForPath(ctx.path)
53
- };
54
- super({
55
- ...config,
56
- name: CONTENT_PROCESSOR_NAME,
57
- description: "Build-time content collections exposed as ecopages:content/* virtual modules.",
58
- watch: config.watch ? mergeProcessorOptions(defaultWatchConfig, config.watch) : defaultWatchConfig
59
- });
60
- }
61
- get buildPlugins() {
62
- return [
63
- createContentServerBoundaryPlugin(),
64
- createContentPluginBundler(this.collectionModules, this.collectionServerModules)
65
- ];
66
- }
67
- get plugins() {
68
- return [createContentPlugin(this.collectionModules, this.collectionServerModules)];
69
- }
70
- getCollectionsConfig() {
71
- if (!this.options?.collections) {
72
- throw new Error("Content processor requires `options.collections`");
73
- }
74
- return this.options.collections;
75
- }
76
- getCollectionContentRoot(contentDir) {
77
- if (!this.context) {
78
- throw new Error("Content processor requires context to be set");
79
- }
80
- return path.join(this.context.srcDir, contentDir);
81
- }
82
- writeGeneratedFile(filePath, content) {
83
- fileSystem.ensureDir(path.dirname(filePath));
84
- if (fileSystem.exists(filePath) && fileSystem.readFileSync(filePath) === content) {
85
- return;
86
- }
87
- fileSystem.write(filePath, content);
88
- }
89
- getOrCreateScanner(collectionName) {
90
- const existing = this.scanners.get(collectionName);
91
- if (existing) {
92
- return existing;
93
- }
94
- const definition = this.getCollectionsConfig()[collectionName];
95
- if (!definition) {
96
- throw new Error(`Unknown content collection: ${collectionName}`);
97
- }
98
- const scanner = new ContentScanner({
99
- contentRoot: this.getCollectionContentRoot(definition.contentDir),
100
- orderBy: definition.orderBy ?? compareEntriesBySlug,
101
- extensions: definition.extensions,
102
- schema: definition.schema
103
- });
104
- this.scanners.set(collectionName, scanner);
105
- return scanner;
106
- }
107
- async regenerateCollectionModule(collectionName) {
108
- if (!this.context?.cache) {
109
- throw new Error("Content processor requires context to be set");
110
- }
111
- assertValidCollectionName(collectionName);
112
- const definition = this.getCollectionsConfig()[collectionName];
113
- if (!definition) {
114
- return;
115
- }
116
- const scanner = this.getOrCreateScanner(collectionName);
117
- scanner.clearCache();
118
- const entrySources = await scanner.getEntrySources();
119
- const manifest = entrySources.map(({ entry }) => entry);
120
- const outputFile = getCollectionCachePath(this.context.cache, collectionName);
121
- const serverOutputFile = getCollectionServerCachePath(this.context.cache, collectionName);
122
- const outputDir = path.dirname(outputFile);
123
- const entriesOutput = renderCollectionEntriesModule(collectionName, manifest);
124
- const componentsOutput = renderCollectionComponentsModule(collectionName, outputDir, entrySources);
125
- this.writeGeneratedFile(outputFile, entriesOutput);
126
- this.writeGeneratedFile(serverOutputFile, componentsOutput);
127
- this.collectionModules[collectionName] = outputFile;
128
- this.collectionServerModules[collectionName] = serverOutputFile;
129
- logger.debug("Generated content collection module", {
130
- collectionName,
131
- outputFile,
132
- serverOutputFile,
133
- entryCount: manifest.length
134
- });
135
- }
136
- async regenerateCollections(collectionNames) {
137
- for (const collectionName of collectionNames) {
138
- await this.regenerateCollectionModule(collectionName);
139
- }
140
- this.generateTypes();
141
- }
142
- async regenerateAllCollections() {
143
- await this.regenerateCollections(Object.keys(this.getCollectionsConfig()));
144
- }
145
- async regenerateCollectionsForPath(filePath) {
146
- if (!this.context) {
147
- return;
148
- }
149
- const normalizedPath = path.normalize(filePath);
150
- const affectedCollections = [];
151
- for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
152
- const contentRoot = this.getCollectionContentRoot(definition.contentDir);
153
- if (normalizedPath.startsWith(contentRoot + path.sep) || normalizedPath === contentRoot) {
154
- affectedCollections.push(collectionName);
155
- }
156
- }
157
- if (affectedCollections.length > 0) {
158
- await this.regenerateCollections(affectedCollections);
159
- }
160
- }
161
- initializeWatchPaths() {
162
- if (!this.watchConfig || !this.context) {
163
- return;
164
- }
165
- this.watchConfig.paths = Object.values(this.getCollectionsConfig()).map(
166
- (definition) => this.getCollectionContentRoot(definition.contentDir)
167
- );
168
- }
169
- generateTypes() {
170
- if (!this.context) {
171
- throw new Error("Content processor requires context to be set");
172
- }
173
- const collectionNames = Object.keys(this.getCollectionsConfig());
174
- for (const collectionName of collectionNames) {
175
- assertValidCollectionName(collectionName);
176
- }
177
- const typesDir = resolveGeneratedPath("types", {
178
- root: this.context.rootDir,
179
- module: this.name,
180
- subPath: "virtual-module.d.ts"
181
- });
182
- const content = renderVirtualModuleTypes(this.getCollectionsConfig(), {
183
- rootDir: this.context.rootDir,
184
- typesOutputFile: typesDir
185
- });
186
- this.writeGeneratedFile(typesDir, content);
187
- const indexTypesDir = resolveGeneratedPath("types", {
188
- root: this.context.rootDir,
189
- module: this.name,
190
- subPath: "index.d.ts"
191
- });
192
- this.writeGeneratedFile(indexTypesDir, 'import "./virtual-module.d.js";\n');
193
- }
194
- async ensureCollectionsGenerated() {
195
- if (this.collectionsGenerated) {
196
- return;
197
- }
198
- this.initializeWatchPaths();
199
- await this.regenerateAllCollections();
200
- this.collectionsGenerated = true;
201
- }
202
- async prepareBuildContributions() {
203
- await this.ensureCollectionsGenerated();
204
- }
205
- async setup() {
206
- await this.ensureCollectionsGenerated();
207
- }
208
- async process(_input) {
209
- await this.regenerateAllCollections();
210
- }
23
+ /**
24
+ * Build-time processor that scans configured content collections and exposes
25
+ * each one as `ecopages:content/<collection>` virtual modules.
26
+ */
27
+ export class ContentProcessorPlugin extends Processor {
28
+ collectionsGenerated = false;
29
+ scanners = new Map();
30
+ /**
31
+ * Absolute paths to generated collection entry modules, keyed by collection name.
32
+ * Virtual-module plugins close over this object so mutations stay live.
33
+ */
34
+ collectionModules = {};
35
+ /**
36
+ * Absolute paths to generated server-only component resolver modules.
37
+ */
38
+ collectionServerModules = {};
39
+ constructor(config) {
40
+ const defaultWatchConfig = {
41
+ paths: [],
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),
46
+ };
47
+ super({
48
+ ...config,
49
+ name: CONTENT_PROCESSOR_NAME,
50
+ description: 'Build-time content collections exposed as ecopages:content/* virtual modules.',
51
+ watch: config.watch ? mergeProcessorOptions(defaultWatchConfig, config.watch) : defaultWatchConfig,
52
+ });
53
+ }
54
+ get buildPlugins() {
55
+ return [
56
+ createContentServerBoundaryPlugin(),
57
+ createContentPluginBundler(this.collectionModules, this.collectionServerModules),
58
+ ];
59
+ }
60
+ get plugins() {
61
+ return [createContentPlugin(this.collectionModules, this.collectionServerModules)];
62
+ }
63
+ getCollectionsConfig() {
64
+ if (!this.options?.collections) {
65
+ throw new Error('Content processor requires `options.collections`');
66
+ }
67
+ return this.options.collections;
68
+ }
69
+ getCollectionContentRoot(contentDir) {
70
+ if (!this.context) {
71
+ throw new Error('Content processor requires context to be set');
72
+ }
73
+ return path.join(this.context.srcDir, contentDir);
74
+ }
75
+ writeGeneratedFile(filePath, content) {
76
+ fileSystem.ensureDir(path.dirname(filePath));
77
+ if (fileSystem.exists(filePath) && fileSystem.readFileSync(filePath) === content) {
78
+ return;
79
+ }
80
+ fileSystem.write(filePath, content);
81
+ }
82
+ getOrCreateScanner(collectionName) {
83
+ const existing = this.scanners.get(collectionName);
84
+ if (existing) {
85
+ return existing;
86
+ }
87
+ const definition = this.getCollectionsConfig()[collectionName];
88
+ if (!definition) {
89
+ throw new Error(`Unknown content collection: ${collectionName}`);
90
+ }
91
+ const scanner = new ContentScanner({
92
+ contentRoot: this.getCollectionContentRoot(definition.contentDir),
93
+ orderBy: definition.orderBy ?? compareEntriesBySlug,
94
+ extensions: definition.extensions,
95
+ schema: definition.schema,
96
+ });
97
+ this.scanners.set(collectionName, scanner);
98
+ return scanner;
99
+ }
100
+ async regenerateCollectionModule(collectionName) {
101
+ if (!this.context?.cache) {
102
+ throw new Error('Content processor requires context to be set');
103
+ }
104
+ assertValidCollectionName(collectionName);
105
+ const definition = this.getCollectionsConfig()[collectionName];
106
+ if (!definition) {
107
+ return;
108
+ }
109
+ const scanner = this.getOrCreateScanner(collectionName);
110
+ scanner.clearCache();
111
+ const entrySources = await scanner.getEntrySources();
112
+ const manifest = entrySources.map(({ entry }) => entry);
113
+ const outputFile = getCollectionCachePath(this.context.cache, collectionName);
114
+ const serverOutputFile = getCollectionServerCachePath(this.context.cache, collectionName);
115
+ const outputDir = path.dirname(outputFile);
116
+ const entriesOutput = renderCollectionEntriesModule(collectionName, manifest);
117
+ const componentsOutput = renderCollectionComponentsModule(collectionName, outputDir, entrySources);
118
+ this.writeGeneratedFile(outputFile, entriesOutput);
119
+ this.writeGeneratedFile(serverOutputFile, componentsOutput);
120
+ this.collectionModules[collectionName] = outputFile;
121
+ this.collectionServerModules[collectionName] = serverOutputFile;
122
+ logger.debug('Generated content collection module', {
123
+ collectionName,
124
+ outputFile,
125
+ serverOutputFile,
126
+ entryCount: manifest.length,
127
+ });
128
+ }
129
+ async regenerateCollections(collectionNames) {
130
+ for (const collectionName of collectionNames) {
131
+ await this.regenerateCollectionModule(collectionName);
132
+ }
133
+ this.generateTypes();
134
+ }
135
+ async regenerateAllCollections() {
136
+ await this.regenerateCollections(Object.keys(this.getCollectionsConfig()));
137
+ }
138
+ async regenerateCollectionsForPath(filePath) {
139
+ if (!this.context) {
140
+ return;
141
+ }
142
+ const normalizedPath = path.normalize(filePath);
143
+ const affectedCollections = [];
144
+ for (const [collectionName, definition] of Object.entries(this.getCollectionsConfig())) {
145
+ const contentRoot = this.getCollectionContentRoot(definition.contentDir);
146
+ if (normalizedPath.startsWith(contentRoot + path.sep) || normalizedPath === contentRoot) {
147
+ affectedCollections.push(collectionName);
148
+ }
149
+ }
150
+ if (affectedCollections.length > 0) {
151
+ await this.regenerateCollections(affectedCollections);
152
+ }
153
+ }
154
+ initializeWatchPaths() {
155
+ if (!this.watchConfig || !this.context) {
156
+ return;
157
+ }
158
+ this.watchConfig.paths = Object.values(this.getCollectionsConfig()).map((definition) => this.getCollectionContentRoot(definition.contentDir));
159
+ }
160
+ generateTypes() {
161
+ if (!this.context) {
162
+ throw new Error('Content processor requires context to be set');
163
+ }
164
+ const collectionNames = Object.keys(this.getCollectionsConfig());
165
+ for (const collectionName of collectionNames) {
166
+ assertValidCollectionName(collectionName);
167
+ }
168
+ const typesDir = resolveGeneratedPath('types', {
169
+ root: this.context.rootDir,
170
+ module: this.name,
171
+ subPath: 'virtual-module.d.ts',
172
+ });
173
+ const content = renderVirtualModuleTypes(this.getCollectionsConfig(), {
174
+ rootDir: this.context.rootDir,
175
+ typesOutputFile: typesDir,
176
+ });
177
+ this.writeGeneratedFile(typesDir, content);
178
+ const indexTypesDir = resolveGeneratedPath('types', {
179
+ root: this.context.rootDir,
180
+ module: this.name,
181
+ subPath: 'index.d.ts',
182
+ });
183
+ this.writeGeneratedFile(indexTypesDir, 'import "./virtual-module.d.js";\n');
184
+ }
185
+ async ensureCollectionsGenerated() {
186
+ if (this.collectionsGenerated) {
187
+ return;
188
+ }
189
+ this.initializeWatchPaths();
190
+ await this.regenerateAllCollections();
191
+ this.collectionsGenerated = true;
192
+ }
193
+ async prepareBuildContributions() {
194
+ await this.ensureCollectionsGenerated();
195
+ }
196
+ async setup() {
197
+ await this.ensureCollectionsGenerated();
198
+ }
199
+ async process(_input) {
200
+ await this.regenerateAllCollections();
201
+ }
211
202
  }
212
- const contentProcessorPlugin = (config) => {
213
- return new ContentProcessorPlugin(config);
214
- };
215
- export {
216
- ContentProcessorPlugin,
217
- contentProcessorPlugin
203
+ export const contentProcessorPlugin = (config) => {
204
+ return new ContentProcessorPlugin(config);
218
205
  };
package/src/sort.js CHANGED
@@ -1,20 +1,23 @@
1
- function compareEntriesBySlug(a, b) {
2
- return a.slug.localeCompare(b.slug);
1
+ /** Default manifest sort: slug segments in path order. */
2
+ export function compareEntriesBySlug(a, b) {
3
+ return a.slug.localeCompare(b.slug);
3
4
  }
4
- function compareEntriesByField(field) {
5
- return (a, b) => {
6
- const left = a[field];
7
- const right = b[field];
8
- if (typeof left === "number" && typeof right === "number") {
9
- return left - right || compareEntriesBySlug(a, b);
10
- }
11
- if (typeof left === "string" && typeof right === "string") {
12
- return left.localeCompare(right) || compareEntriesBySlug(a, b);
13
- }
14
- return compareEntriesBySlug(a, b);
15
- };
5
+ /**
6
+ * Sort by a validated frontmatter field.
7
+ *
8
+ * @remarks
9
+ * The caller must ensure the field exists on entries validated by the collection schema.
10
+ */
11
+ export function compareEntriesByField(field) {
12
+ return (a, b) => {
13
+ const left = a[field];
14
+ const right = b[field];
15
+ if (typeof left === 'number' && typeof right === 'number') {
16
+ return left - right || compareEntriesBySlug(a, b);
17
+ }
18
+ if (typeof left === 'string' && typeof right === 'string') {
19
+ return left.localeCompare(right) || compareEntriesBySlug(a, b);
20
+ }
21
+ return compareEntriesBySlug(a, b);
22
+ };
16
23
  }
17
- export {
18
- compareEntriesByField,
19
- compareEntriesBySlug
20
- };
package/src/types.js CHANGED
@@ -0,0 +1 @@
1
+ export {};