@prunellejs/content 0.1.1 → 0.5.3

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/src/entry.ts ADDED
@@ -0,0 +1,170 @@
1
+ // Shared entry construction, lazy Markdown render-config resolution, sorting, and filtering helpers.
2
+
3
+ import type {
4
+ BaseCollectionOptions,
5
+ CollectionRenderConfig,
6
+ ContentEntry,
7
+ RenderedMarkdown,
8
+ RenderMarkdownOptions,
9
+ } from './types'
10
+ import { currentApp } from './app'
11
+ import { renderMarkdown } from './markdown'
12
+ import { shouldWrapCmsBody, wrapCmsBodyHtml } from './tracking'
13
+
14
+ export interface RenderConfigLoader {
15
+ ensureSync: () => RenderMarkdownOptions
16
+ ensureAsync: () => Promise<RenderMarkdownOptions>
17
+ }
18
+
19
+ export type RenderConfigOptions = Pick<
20
+ BaseCollectionOptions<never>,
21
+ 'highlight' | 'components' | 'headingLinks' | 'resolveImage' | 'trusted' | 'render'
22
+ >
23
+
24
+ export function createRenderConfigLoader(
25
+ label: string,
26
+ options: RenderConfigOptions,
27
+ ): RenderConfigLoader {
28
+ const baseRenderOpts: RenderMarkdownOptions = {
29
+ highlight: options.highlight,
30
+ components: options.components,
31
+ headingLinks: options.headingLinks,
32
+ resolveImage: options.resolveImage,
33
+ trusted: options.trusted,
34
+ }
35
+ let resolvedRenderOpts: RenderMarkdownOptions | undefined = options.render === undefined ? baseRenderOpts : undefined
36
+ let pendingRenderOpts: Promise<RenderMarkdownOptions> | undefined
37
+
38
+ function mergeRenderConfig(cfg: CollectionRenderConfig): RenderMarkdownOptions {
39
+ return {
40
+ highlight: cfg.highlight ?? baseRenderOpts.highlight,
41
+ components: cfg.components ?? baseRenderOpts.components,
42
+ headingLinks: cfg.headingLinks ?? baseRenderOpts.headingLinks,
43
+ resolveImage: cfg.resolveImage !== undefined ? cfg.resolveImage : baseRenderOpts.resolveImage,
44
+ trusted: cfg.trusted !== undefined ? cfg.trusted : baseRenderOpts.trusted,
45
+ }
46
+ }
47
+
48
+ function ensureSync(): RenderMarkdownOptions {
49
+ if (resolvedRenderOpts !== undefined)
50
+ return resolvedRenderOpts
51
+ const loaded = options.render!()
52
+ if (loaded instanceof Promise) {
53
+ pendingRenderOpts ??= loaded.then((cfg) => {
54
+ resolvedRenderOpts = mergeRenderConfig(cfg)
55
+ return resolvedRenderOpts
56
+ }).catch((err) => {
57
+ pendingRenderOpts = undefined
58
+ throw err
59
+ })
60
+ throw new Error(
61
+ `@prunellejs/content: collection "${label}" uses an async "render" loader; call \`await entry.render()\` (e.g. in \`load()\`) before reading \`entry.html\` or \`entry.headings\`.`,
62
+ )
63
+ }
64
+ resolvedRenderOpts = mergeRenderConfig(loaded)
65
+ return resolvedRenderOpts
66
+ }
67
+
68
+ async function ensureAsync(): Promise<RenderMarkdownOptions> {
69
+ if (resolvedRenderOpts !== undefined)
70
+ return resolvedRenderOpts
71
+ pendingRenderOpts ??= Promise.resolve(options.render!()).then((cfg) => {
72
+ resolvedRenderOpts = mergeRenderConfig(cfg)
73
+ return resolvedRenderOpts
74
+ }).catch((err) => {
75
+ pendingRenderOpts = undefined
76
+ throw err
77
+ })
78
+ return pendingRenderOpts
79
+ }
80
+
81
+ return { ensureSync, ensureAsync }
82
+ }
83
+
84
+ export interface BuildContentEntryParams<TData> {
85
+ slug: string
86
+ locale?: string | undefined
87
+ file: string
88
+ data: TData
89
+ body: string
90
+ renderLoader: RenderConfigLoader
91
+ /** Set for file-backed collections so dev inline CMS can anchor rendered Markdown bodies. */
92
+ collectionName?: string | undefined
93
+ }
94
+
95
+ export function buildContentEntry<TData>(params: BuildContentEntryParams<TData>): ContentEntry<TData> {
96
+ const { slug, locale, file, data, body, renderLoader, collectionName } = params
97
+ const wordCount = body.trim().split(/\s+/).filter(Boolean).length
98
+ const readingMinutes = Math.max(1, Math.ceil(wordCount / 220))
99
+ let renderedCache: RenderedMarkdown | undefined
100
+
101
+ const getRenderedSync = (): RenderedMarkdown => {
102
+ renderedCache ??= renderMarkdown(body, { ...renderLoader.ensureSync(), locale, file })
103
+ return renderedCache
104
+ }
105
+
106
+ const renderAsync = async (): Promise<RenderedMarkdown> => {
107
+ if (renderedCache === undefined) {
108
+ const opts = await renderLoader.ensureAsync()
109
+ renderedCache ??= renderMarkdown(body, { ...opts, locale, file })
110
+ }
111
+ if (shouldWrapCmsBody(collectionName)) {
112
+ return {
113
+ ...renderedCache,
114
+ html: wrapCmsBodyHtml(collectionName, slug, locale, renderedCache.html),
115
+ }
116
+ }
117
+ return renderedCache
118
+ }
119
+
120
+ return {
121
+ slug,
122
+ ...(locale !== undefined ? { locale } : {}),
123
+ file,
124
+ data,
125
+ body,
126
+ get html() {
127
+ const raw = getRenderedSync().html
128
+ return shouldWrapCmsBody(collectionName)
129
+ ? wrapCmsBodyHtml(collectionName, slug, locale, raw)
130
+ : raw
131
+ },
132
+ get headings() {
133
+ return getRenderedSync().headings
134
+ },
135
+ wordCount,
136
+ readingMinutes,
137
+ render: renderAsync,
138
+ }
139
+ }
140
+
141
+ export function isDevMode(): boolean {
142
+ return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
143
+ }
144
+
145
+ export function isDraft(data: unknown): boolean {
146
+ return data !== null && typeof data === 'object' && (data as Record<string, unknown>).draft === true
147
+ }
148
+
149
+ export function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
150
+ const ad = a.data !== null && typeof a.data === 'object' ? (a.data as Record<string, unknown>).date : undefined
151
+ const bd = b.data !== null && typeof b.data === 'object' ? (b.data as Record<string, unknown>).date : undefined
152
+ const at = ad instanceof Date ? ad.getTime() : (typeof ad === 'string' || typeof ad === 'number' ? Date.parse(String(ad)) : Number.NaN)
153
+ const bt = bd instanceof Date ? bd.getTime() : (typeof bd === 'string' || typeof bd === 'number' ? Date.parse(String(bd)) : Number.NaN)
154
+ if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt)
155
+ return bt - at
156
+ return a.slug.localeCompare(b.slug)
157
+ }
158
+
159
+ export function filterByTag<T>(entries: readonly ContentEntry<T>[], tag: string): ContentEntry<T>[] {
160
+ const needle = tag.toLowerCase()
161
+ return entries.filter((e) => {
162
+ const tags = e.data !== null && typeof e.data === 'object' ? (e.data as Record<string, unknown>).tags : undefined
163
+ return Array.isArray(tags) && tags.some(t => String(t).toLowerCase() === needle)
164
+ })
165
+ }
166
+
167
+ export function formatPaths<T>(entries: readonly ContentEntry<T>[], prefix = ''): string[] {
168
+ const base = prefix.replace(/\/$/, '')
169
+ return entries.map(e => `${base}/${e.slug}`)
170
+ }
@@ -0,0 +1,302 @@
1
+ // File-backed Markdown collection implementation (`defineCollection({ dir, ... })`).
2
+
3
+ import type { StandardSchemaV1 } from 'prunelle/server'
4
+ import type {
5
+ Collection,
6
+ CollectionOptions,
7
+ ContentEntry,
8
+ InternalCollection,
9
+ } from './types'
10
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
11
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path'
12
+ import { isInside } from 'prunelle/config'
13
+ import { formatIssuePath, validateSchemaSync } from 'prunelle/server'
14
+ import { currentApp } from './app'
15
+ import {
16
+ buildContentEntry,
17
+ createRenderConfigLoader,
18
+ defaultSort,
19
+ filterByTag,
20
+ formatPaths,
21
+ isDevMode,
22
+ isDraft,
23
+ } from './entry'
24
+ import { findFrontmatterFieldLine, parseFrontmatter } from './frontmatter'
25
+ import { registerFileCollection } from './registry'
26
+ import { recordAccessedEntry } from './tracking'
27
+ import {
28
+ COLLECTION_DIR_FOR_ROOT_KEY,
29
+ COLLECTION_META_KEY,
30
+ COLLECTION_VALIDATE_KEY,
31
+ COLLECTION_VERSION_KEY,
32
+ } from './types'
33
+
34
+ export function resolveCollectionDir(dir: string, explicitRoot?: string): string {
35
+ if (isAbsolute(dir))
36
+ return dir
37
+ const prunelleRoot = explicitRoot ?? currentApp.root()
38
+ if (typeof prunelleRoot === 'string' && prunelleRoot !== '') {
39
+ const candidate = resolve(prunelleRoot, dir)
40
+ if (existsSync(candidate))
41
+ return candidate
42
+ }
43
+ return resolve(dir)
44
+ }
45
+
46
+ function walkMarkdownFiles(dir: string, out: string[] = []): string[] {
47
+ if (!existsSync(dir))
48
+ return out
49
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
50
+ const full = join(dir, ent.name)
51
+ if (ent.isDirectory())
52
+ walkMarkdownFiles(full, out)
53
+ else if (ent.isFile() && (ent.name.endsWith('.md') || ent.name.endsWith('.markdown')))
54
+ out.push(full)
55
+ }
56
+ return out
57
+ }
58
+
59
+ function listLocaleDirs(absDir: string): string[] | undefined {
60
+ if (!existsSync(absDir))
61
+ return undefined
62
+ const locales = readdirSync(absDir, { withFileTypes: true })
63
+ .filter(ent => ent.isDirectory() && !ent.name.startsWith('.'))
64
+ .map(ent => ent.name)
65
+ .sort()
66
+ return locales.length > 0 ? locales : undefined
67
+ }
68
+
69
+ function validateCollectionFiles(
70
+ absDir: string,
71
+ root: string,
72
+ schema: StandardSchemaV1 | undefined,
73
+ ): string[] {
74
+ if (!existsSync(absDir))
75
+ return []
76
+ const errors: string[] = []
77
+ for (const absFile of walkMarkdownFiles(absDir).sort()) {
78
+ const rel = relative(root, absFile).replace(/\\/g, '/')
79
+ const rawSource = readFileSync(absFile, 'utf8')
80
+ let rawData: Record<string, unknown>
81
+ try {
82
+ rawData = parseFrontmatter(rawSource).data
83
+ }
84
+ catch (err) {
85
+ const msg = err instanceof Error ? err.message : String(err)
86
+ errors.push(`${rel}:1:1: error: @prunellejs/content: invalid YAML frontmatter: ${msg}`)
87
+ continue
88
+ }
89
+ if (schema === undefined)
90
+ continue
91
+ const checked = validateSchemaSync(
92
+ schema,
93
+ rawData,
94
+ `@prunellejs/content: async frontmatter schema is not supported (${rel})`,
95
+ )
96
+ if (!checked.ok) {
97
+ for (const issue of checked.issues) {
98
+ const path = formatIssuePath(issue)
99
+ const line = findFrontmatterFieldLine(rawSource, path || undefined)
100
+ errors.push(`${rel}:${line}:1: error: @prunellejs/content: ${path ? `${path}: ` : ''}${issue.message}`)
101
+ }
102
+ }
103
+ }
104
+ return errors
105
+ }
106
+
107
+ // Slugs and locales usually come from URL params: a path built from them must stay inside the collection folder.
108
+ function localeDir(absDir: string, targetLocale: string | undefined): string | undefined {
109
+ if (targetLocale === undefined)
110
+ return absDir
111
+ const scanDir = resolve(absDir, targetLocale)
112
+ return isInside(absDir, scanDir) ? scanDir : undefined
113
+ }
114
+
115
+ function validateFileFrontmatter<TData>(
116
+ schema: StandardSchemaV1<unknown, TData> | undefined,
117
+ rawData: Record<string, unknown>,
118
+ slug: string,
119
+ absFile: string,
120
+ ): TData {
121
+ if (schema === undefined)
122
+ return rawData as TData
123
+ const checked = validateSchemaSync(
124
+ schema,
125
+ rawData,
126
+ `@prunellejs/content: async frontmatter schema is not supported (${slug})`,
127
+ )
128
+ if (!checked.ok) {
129
+ const msg = checked.issues.map(i => i.message).join('; ')
130
+ throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${msg}`)
131
+ }
132
+ return checked.value
133
+ }
134
+
135
+ function findEntryFileCandidate(scanDir: string, clean: string): string | undefined {
136
+ for (const candidate of [
137
+ join(scanDir, `${clean}.md`),
138
+ join(scanDir, `${clean}.markdown`),
139
+ join(scanDir, clean, 'index.md'),
140
+ join(scanDir, clean, 'index.markdown'),
141
+ ]) {
142
+ if (existsSync(candidate))
143
+ return candidate
144
+ }
145
+ return undefined
146
+ }
147
+
148
+ function trackAccessed<TData>(collectionName: string, entry: ContentEntry<TData>, primary: boolean): void {
149
+ recordAccessedEntry({
150
+ collection: collectionName,
151
+ slug: entry.slug,
152
+ ...(entry.locale !== undefined ? { locale: entry.locale } : {}),
153
+ }, primary)
154
+ }
155
+
156
+ export function createFileCollection<TData = Record<string, unknown>>(
157
+ options: CollectionOptions<TData>,
158
+ ): Collection<TData> {
159
+ const getDir = () => resolveCollectionDir(options.dir)
160
+ const getName = (absDir?: string) => options.name ?? (basename(absDir ?? getDir()) || 'collection')
161
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
162
+ const localized = options.localized ?? false
163
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
164
+ const renderLoader = createRenderConfigLoader(options.dir, options)
165
+
166
+ const cache = new Map<string, { mtimeMs: number, entry: ContentEntry<TData> }>()
167
+ const allCache = new Map<string, ContentEntry<TData>[]>()
168
+ const slugCache = new Map<string, Map<string, ContentEntry<TData>>>()
169
+ let cacheVersion = 0
170
+
171
+ const visible = (entry: ContentEntry<TData>): ContentEntry<TData> | null =>
172
+ !allowsDrafts() && isDraft(entry.data) ? null : entry
173
+
174
+ function loadFile(absFile: string, baseDir: string, collectionName: string, entryLocale?: string): ContentEntry<TData> | null {
175
+ const dev = isDevMode()
176
+ const cached = cache.get(absFile)
177
+ if (!dev && cached !== undefined)
178
+ return visible(cached.entry)
179
+
180
+ const mtimeMs = statSync(absFile).mtimeMs
181
+ if (cached !== undefined && cached.mtimeMs === mtimeMs)
182
+ return visible(cached.entry)
183
+
184
+ const rawSource = readFileSync(absFile, 'utf8')
185
+ const { data: rawData, body } = parseFrontmatter(rawSource)
186
+ const slug = relative(baseDir, absFile)
187
+ .replace(/\\/g, '/')
188
+ .replace(/\.(?:md|markdown)$/, '')
189
+ .replace(/\/index$/, '')
190
+
191
+ const data = validateFileFrontmatter(options.schema, rawData, slug, absFile)
192
+ const entry = buildContentEntry({ slug, locale: entryLocale, file: absFile, data, body, renderLoader, collectionName })
193
+ cache.set(absFile, { mtimeMs, entry })
194
+ return visible(entry)
195
+ }
196
+
197
+ function scanAllEntries(locale?: string): { entries: ContentEntry<TData>[], collectionName: string } {
198
+ const absDir = getDir()
199
+ const collectionName = getName(absDir)
200
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
201
+ const scanDir = localeDir(absDir, targetLocale)
202
+ if (scanDir === undefined)
203
+ return { entries: [], collectionName }
204
+ const dev = isDevMode()
205
+ if (!dev) {
206
+ const hit = allCache.get(scanDir)
207
+ if (hit !== undefined)
208
+ return { entries: hit.slice(), collectionName }
209
+ }
210
+ const entries: ContentEntry<TData>[] = []
211
+ const bySlug = new Map<string, ContentEntry<TData>>()
212
+ for (const f of walkMarkdownFiles(scanDir)) {
213
+ const entry = loadFile(f, scanDir, collectionName, targetLocale)
214
+ if (entry === null)
215
+ continue
216
+ entries.push(entry)
217
+ bySlug.set(entry.slug, entry)
218
+ }
219
+ entries.sort(options.sort ?? defaultSort)
220
+ if (!dev) {
221
+ allCache.set(scanDir, entries)
222
+ slugCache.set(scanDir, bySlug)
223
+ }
224
+ return { entries: entries.slice(), collectionName }
225
+ }
226
+
227
+ function all(locale?: string): ContentEntry<TData>[] {
228
+ const { entries, collectionName } = scanAllEntries(locale)
229
+ for (const entry of entries)
230
+ trackAccessed(collectionName, entry, false)
231
+ return entries
232
+ }
233
+
234
+ function get(slug: string, locale?: string): ContentEntry<TData> | undefined {
235
+ const absDir = getDir()
236
+ const collectionName = getName(absDir)
237
+ const clean = slug.replace(/^\/+|\/+$/g, '')
238
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
239
+ const scanDir = localeDir(absDir, targetLocale)
240
+ if (scanDir === undefined || !isInside(scanDir, resolve(scanDir, clean), { orSame: true }))
241
+ return undefined
242
+ const dev = isDevMode()
243
+ if (!dev) {
244
+ const cachedSlug = slugCache.get(scanDir)?.get(clean)
245
+ if (cachedSlug !== undefined)
246
+ return cachedSlug
247
+ }
248
+ const candidate = findEntryFileCandidate(scanDir, clean)
249
+ let found: ContentEntry<TData> | undefined
250
+ if (candidate !== undefined) {
251
+ found = loadFile(candidate, scanDir, collectionName, targetLocale) ?? undefined
252
+ if (!dev && found !== undefined) {
253
+ let map = slugCache.get(scanDir)
254
+ if (map === undefined) {
255
+ map = new Map()
256
+ slugCache.set(scanDir, map)
257
+ }
258
+ map.set(clean, found)
259
+ }
260
+ }
261
+ found ??= scanAllEntries(locale).entries.find(e => e.slug === clean)
262
+ if (found !== undefined)
263
+ trackAccessed(collectionName, found, true)
264
+ return found
265
+ }
266
+
267
+ const col: Collection<TData> & InternalCollection = {
268
+ get dir() {
269
+ return getDir()
270
+ },
271
+ get name() {
272
+ return getName()
273
+ },
274
+ all,
275
+ get,
276
+ byTag: (tag, locale) => filterByTag(all(locale), tag),
277
+ paths: (prefix = '', locale) => formatPaths(all(locale), prefix),
278
+ clearCache() {
279
+ cache.clear()
280
+ allCache.clear()
281
+ slugCache.clear()
282
+ cacheVersion++
283
+ },
284
+ [COLLECTION_VERSION_KEY]: () => cacheVersion,
285
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateCollectionFiles(resolveCollectionDir(options.dir, root), root, options.schema),
286
+ [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => resolveCollectionDir(options.dir, root),
287
+ [COLLECTION_META_KEY]: (root?: string) => {
288
+ const absDir = resolveCollectionDir(options.dir, root)
289
+ return {
290
+ name: getName(absDir),
291
+ dir: absDir,
292
+ localized,
293
+ defaultLocale: getDefaultLocale(),
294
+ locales: options.locales ?? (localized ? listLocaleDirs(absDir) : undefined),
295
+ schema: options.schema,
296
+ isAsync: false,
297
+ }
298
+ },
299
+ }
300
+ registerFileCollection(col, options.dir, localized)
301
+ return col
302
+ }
package/src/index.ts CHANGED
@@ -1,12 +1,12 @@
1
- // @prunellejs/content — Zero-dependency Bun-native Markdown collections, nested YAML frontmatter (Bun.YAML),
2
- // Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
1
+ // @prunellejs/content — Zero-dependency Bun-native Markdown collections (file-backed or headless CMS loaders),
2
+ // nested YAML frontmatter (Bun.YAML), Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
3
3
 
4
4
  import type { PrunellePlugin } from 'prunelle/config'
5
- import type { Collection, InternalCollection } from './collection'
5
+ import type { AnyCollection, InternalCollection } from './types'
6
6
  import type { ContentFeed, RssFeedConfig } from './rss'
7
7
  import { existsSync, readFileSync } from 'node:fs'
8
8
  import { resolve } from 'node:path'
9
- import { definePlugin, isInside } from 'prunelle/config'
9
+ import { CONTENT_COLLECTIONS_SERVICE, definePlugin, isInside } from 'prunelle/config'
10
10
  import { currentApp } from './app'
11
11
  import {
12
12
  COLLECTION_DIR_FOR_ROOT_KEY,
@@ -15,22 +15,31 @@ import {
15
15
  COLLECTION_VERSION_KEY,
16
16
  DEFINE_COLLECTION_RE,
17
17
  discoverAppCollections,
18
-
19
18
  registeredCollections,
20
19
  walkCollectionDefFiles,
21
20
  } from './collection'
22
- import { etagMatches, renderRss } from './rss'
21
+ import { etagMatches, renderRssAsync } from './rss'
22
+ import { CONTENT_PRERENDER_SERVICE, createCollectionsService } from './service'
23
23
 
24
24
  export { defineCollection } from './collection'
25
25
  export type {
26
+ AnyCollection,
27
+ AsyncCollection,
28
+ BaseCollectionOptions,
26
29
  CodeHighlighter,
27
30
  Collection,
31
+ CollectionLoadContext,
32
+ CollectionLoader,
28
33
  CollectionOptions,
29
34
  CollectionOptionsWithoutSchema,
30
35
  CollectionOptionsWithSchema,
31
36
  CollectionRenderConfig,
32
37
  ContentEntry,
33
38
  ContentHeading,
39
+ LoadedEntryInput,
40
+ LoaderCollectionOptions,
41
+ LoaderCollectionOptionsWithoutSchema,
42
+ LoaderCollectionOptionsWithSchema,
34
43
  MarkdownComponent,
35
44
  MarkdownImageResolver,
36
45
  MarkdownImageResult,
@@ -39,7 +48,7 @@ export type {
39
48
  } from './collection'
40
49
  export { parseFrontmatter } from './frontmatter'
41
50
  export { renderMarkdown } from './markdown'
42
- export { renderRss } from './rss'
51
+ export { renderRss, renderRssAsync } from './rss'
43
52
  export type { ContentFeed, RssFeedConfig } from './rss'
44
53
 
45
54
  const STATIC_COLLECTION_DIR_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(\s*\{[\s\S]*?\bdir\s*:\s*(['"`])([^'"`]+)\1/g
@@ -70,15 +79,24 @@ function discoverStaticCollectionDirs(root: string): string[] {
70
79
  }
71
80
 
72
81
  export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
73
- feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K]> } | undefined
74
- collections?: readonly Collection<unknown>[] | undefined
82
+ feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
83
+ collections?: readonly AnyCollection<unknown>[] | undefined
75
84
  }): PrunellePlugin
76
- export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly Collection<unknown>[] | undefined } = {}): PrunellePlugin {
85
+ export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly AnyCollection<unknown>[] | undefined } = {}): PrunellePlugin {
77
86
  const feeds = options.feeds ?? []
78
87
  const extraCollections = options.collections ?? []
88
+ const feedLinkPrefixes = new Map<InternalCollection, string>()
89
+ for (const f of feeds) {
90
+ const col = f.collection as InternalCollection
91
+ if (f.linkPrefix !== undefined && !feedLinkPrefixes.has(col))
92
+ feedLinkPrefixes.set(col, f.linkPrefix)
93
+ }
79
94
 
80
- function dirOf(c: InternalCollection, root?: string): string {
81
- return c[COLLECTION_DIR_FOR_ROOT_KEY]?.(root) ?? c.dir
95
+ function dirOf(c: InternalCollection, root?: string): string | undefined {
96
+ const resolver = c[COLLECTION_DIR_FOR_ROOT_KEY]
97
+ if (resolver !== undefined)
98
+ return resolver(root)
99
+ return c.dir
82
100
  }
83
101
 
84
102
  function activeCollections(root?: string): InternalCollection[] {
@@ -93,6 +111,11 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
93
111
  if (owner !== undefined && absRoot !== undefined && owner !== absRoot)
94
112
  continue
95
113
  const dir = dirOf(c, absRoot)
114
+ if (dir === undefined) {
115
+ if (owner !== undefined || absRoot === undefined)
116
+ out.add(c)
117
+ continue
118
+ }
96
119
  if (!existsSync(dir))
97
120
  continue
98
121
  if (absRoot === undefined || isInside(absRoot, dir, { orSame: true }))
@@ -101,13 +124,21 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
101
124
  return [...out]
102
125
  }
103
126
 
127
+ const collectionsService = createCollectionsService(
128
+ activeCollections,
129
+ col => feedLinkPrefixes.get(col),
130
+ )
131
+
104
132
  return definePlugin({
105
133
  name: '@prunellejs/content',
106
134
  after: ['@prunellejs/i18n', '@prunellejs/images'],
107
135
  watchPaths: (root) => {
108
136
  const dirs = new Set<string>()
109
- for (const c of activeCollections(root))
110
- dirs.add(dirOf(c, root))
137
+ for (const c of activeCollections(root)) {
138
+ const dir = dirOf(c, root)
139
+ if (dir !== undefined)
140
+ dirs.add(dir)
141
+ }
111
142
  for (const dir of discoverStaticCollectionDirs(root))
112
143
  dirs.add(dir)
113
144
  return [...dirs]
@@ -119,12 +150,13 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
119
150
  },
120
151
  async check(ctx) {
121
152
  await discoverAppCollections(ctx.root)
153
+ ctx.provide?.(CONTENT_COLLECTIONS_SERVICE, collectionsService)
122
154
  const seen = new Set<string>()
123
155
  for (const c of activeCollections(ctx.root)) {
124
156
  const validate = c[COLLECTION_VALIDATE_KEY]
125
157
  if (validate === undefined)
126
158
  continue
127
- for (const err of validate(ctx.root)) {
159
+ for (const err of await validate(ctx.root)) {
128
160
  if (seen.has(err))
129
161
  continue
130
162
  seen.add(err)
@@ -132,34 +164,48 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
132
164
  }
133
165
  }
134
166
  },
135
- build(ctx) {
167
+ async build(ctx) {
168
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
136
169
  for (const feed of feeds) {
137
170
  const rel = (feed.path ?? '/rss.xml').replace(/^\/+/, '')
138
- ctx.emitPublic(rel, renderRss({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown>))
171
+ ctx.emitPublic(rel, await renderRssAsync({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown, AnyCollection<unknown>>))
139
172
  }
140
173
  },
174
+ afterPrerender(ctx) {
175
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
176
+ },
141
177
  server(api) {
178
+ api.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
179
+ if (api.config?.prerender === true)
180
+ api.provide(CONTENT_PRERENDER_SERVICE, true)
142
181
  for (const feed of feeds) {
143
182
  const path = feed.path ?? '/rss.xml'
183
+ const isFileBacked = feed.collection.dir !== undefined
144
184
  let memo: { xml: string, etag: string, version: number } | undefined
145
- api.route('GET', path, (ctx) => {
185
+ api.route('GET', path, async (ctx) => {
146
186
  const versionFn = (feed.collection as unknown as Record<symbol, (() => number) | undefined>)[COLLECTION_VERSION_KEY]
147
187
  const version = versionFn ? versionFn() : -1
148
- if (api.dev || memo === undefined || memo.version !== version) {
149
- const xml = renderRss({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown>)
188
+ let current: { xml: string, etag: string }
189
+ if (isFileBacked && !api.dev && memo !== undefined && memo.version === version) {
190
+ current = memo
191
+ }
192
+ else {
193
+ const xml = await renderRssAsync({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown, AnyCollection<unknown>>)
150
194
  const etag = `"${Bun.hash(xml).toString(36)}"`
151
- memo = { xml, etag, version }
195
+ current = { xml, etag }
196
+ if (isFileBacked)
197
+ memo = { xml, etag, version }
152
198
  }
153
- if (etagMatches(ctx.request.headers.get('if-none-match'), memo.etag)) {
199
+ if (etagMatches(ctx.request.headers.get('if-none-match'), current.etag)) {
154
200
  return new Response(null, {
155
201
  status: 304,
156
- headers: { etag: memo.etag },
202
+ headers: { etag: current.etag },
157
203
  })
158
204
  }
159
- return new Response(memo.xml, {
205
+ return new Response(current.xml, {
160
206
  headers: {
161
207
  'content-type': 'application/rss+xml; charset=utf-8',
162
- 'etag': memo.etag,
208
+ 'etag': current.etag,
163
209
  },
164
210
  })
165
211
  })