@prunellejs/content 0.0.0-stage → 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/llms.txt +81 -0
- package/package.json +24 -4
- package/src/app.ts +15 -0
- package/src/collection.ts +68 -0
- package/src/components.ts +533 -0
- package/src/entry.ts +170 -0
- package/src/file-collection.ts +302 -0
- package/src/frontmatter.ts +43 -0
- package/src/index.ts +215 -0
- package/src/loader-collection.ts +263 -0
- package/src/markdown.ts +183 -0
- package/src/registry.ts +135 -0
- package/src/rss.ts +105 -0
- package/src/sanitize.ts +309 -0
- package/src/service.ts +88 -0
- package/src/tracking.ts +80 -0
- package/src/types.ts +198 -0
- package/README.md +0 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// YAML frontmatter parsing (via Bun.YAML) and source line lookup for diagnostics.
|
|
2
|
+
|
|
3
|
+
/** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
|
|
4
|
+
export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
|
|
5
|
+
const normalized = source.replace(/\r\n/g, '\n')
|
|
6
|
+
if (!normalized.startsWith('---\n'))
|
|
7
|
+
return { data: {}, body: normalized }
|
|
8
|
+
|
|
9
|
+
const end = normalized.indexOf('\n---', 4)
|
|
10
|
+
if (end === -1)
|
|
11
|
+
return { data: {}, body: normalized }
|
|
12
|
+
|
|
13
|
+
const rawYaml = normalized.slice(4, end)
|
|
14
|
+
const restStart = normalized.indexOf('\n', end + 4)
|
|
15
|
+
const body = restStart === -1 ? '' : normalized.slice(restStart + 1)
|
|
16
|
+
|
|
17
|
+
const parsed = rawYaml.trim() === '' ? {} : Bun.YAML.parse(rawYaml)
|
|
18
|
+
const data = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
19
|
+
? (parsed as Record<string, unknown>)
|
|
20
|
+
: {}
|
|
21
|
+
return { data, body }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Finds the 1-based line number of a top-level frontmatter key for `prunelle check` diagnostics. */
|
|
25
|
+
export function findFrontmatterFieldLine(rawSource: string, fieldPath: string | undefined): number {
|
|
26
|
+
const normalized = rawSource.replace(/\r\n/g, '\n')
|
|
27
|
+
if (!normalized.startsWith('---\n'))
|
|
28
|
+
return 1
|
|
29
|
+
const end = normalized.indexOf('\n---', 4)
|
|
30
|
+
if (end === -1)
|
|
31
|
+
return 1
|
|
32
|
+
if (!fieldPath)
|
|
33
|
+
return 2
|
|
34
|
+
const topKey = fieldPath.split('.')[0] ?? fieldPath
|
|
35
|
+
const escaped = topKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
36
|
+
const keyRe = new RegExp(`^\\s*${escaped}\\s*:`)
|
|
37
|
+
const lines = normalized.slice(4, end).split('\n')
|
|
38
|
+
for (let i = 0; i < lines.length; i++) {
|
|
39
|
+
if (keyRe.test(lines[i]!))
|
|
40
|
+
return i + 2
|
|
41
|
+
}
|
|
42
|
+
return 2
|
|
43
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
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
|
+
|
|
4
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
5
|
+
import type { AnyCollection, InternalCollection } from './types'
|
|
6
|
+
import type { ContentFeed, RssFeedConfig } from './rss'
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
8
|
+
import { resolve } from 'node:path'
|
|
9
|
+
import { CONTENT_COLLECTIONS_SERVICE, definePlugin, isInside } from 'prunelle/config'
|
|
10
|
+
import { currentApp } from './app'
|
|
11
|
+
import {
|
|
12
|
+
COLLECTION_DIR_FOR_ROOT_KEY,
|
|
13
|
+
COLLECTION_OWNER_ROOT_KEY,
|
|
14
|
+
COLLECTION_VALIDATE_KEY,
|
|
15
|
+
COLLECTION_VERSION_KEY,
|
|
16
|
+
DEFINE_COLLECTION_RE,
|
|
17
|
+
discoverAppCollections,
|
|
18
|
+
registeredCollections,
|
|
19
|
+
walkCollectionDefFiles,
|
|
20
|
+
} from './collection'
|
|
21
|
+
import { etagMatches, renderRssAsync } from './rss'
|
|
22
|
+
import { CONTENT_PRERENDER_SERVICE, createCollectionsService } from './service'
|
|
23
|
+
|
|
24
|
+
export { defineCollection } from './collection'
|
|
25
|
+
export type {
|
|
26
|
+
AnyCollection,
|
|
27
|
+
AsyncCollection,
|
|
28
|
+
BaseCollectionOptions,
|
|
29
|
+
CodeHighlighter,
|
|
30
|
+
Collection,
|
|
31
|
+
CollectionLoadContext,
|
|
32
|
+
CollectionLoader,
|
|
33
|
+
CollectionOptions,
|
|
34
|
+
CollectionOptionsWithoutSchema,
|
|
35
|
+
CollectionOptionsWithSchema,
|
|
36
|
+
CollectionRenderConfig,
|
|
37
|
+
ContentEntry,
|
|
38
|
+
ContentHeading,
|
|
39
|
+
LoadedEntryInput,
|
|
40
|
+
LoaderCollectionOptions,
|
|
41
|
+
LoaderCollectionOptionsWithoutSchema,
|
|
42
|
+
LoaderCollectionOptionsWithSchema,
|
|
43
|
+
MarkdownComponent,
|
|
44
|
+
MarkdownImageResolver,
|
|
45
|
+
MarkdownImageResult,
|
|
46
|
+
RenderedMarkdown,
|
|
47
|
+
RenderMarkdownOptions,
|
|
48
|
+
} from './collection'
|
|
49
|
+
export { parseFrontmatter } from './frontmatter'
|
|
50
|
+
export { renderMarkdown } from './markdown'
|
|
51
|
+
export { renderRss, renderRssAsync } from './rss'
|
|
52
|
+
export type { ContentFeed, RssFeedConfig } from './rss'
|
|
53
|
+
|
|
54
|
+
const STATIC_COLLECTION_DIR_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(\s*\{[\s\S]*?\bdir\s*:\s*(['"`])([^'"`]+)\1/g
|
|
55
|
+
|
|
56
|
+
function discoverStaticCollectionDirs(root: string): string[] {
|
|
57
|
+
const absRoot = resolve(root)
|
|
58
|
+
const srcDir = resolve(absRoot, 'src')
|
|
59
|
+
const found: string[] = []
|
|
60
|
+
for (const file of walkCollectionDefFiles(srcDir)) {
|
|
61
|
+
let text: string
|
|
62
|
+
try {
|
|
63
|
+
text = readFileSync(file, 'utf8')
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
if (!DEFINE_COLLECTION_RE.test(text))
|
|
69
|
+
continue
|
|
70
|
+
STATIC_COLLECTION_DIR_RE.lastIndex = 0
|
|
71
|
+
let m: RegExpExecArray | null
|
|
72
|
+
while ((m = STATIC_COLLECTION_DIR_RE.exec(text)) !== null) {
|
|
73
|
+
const dir = resolve(absRoot, m[2]!)
|
|
74
|
+
if (existsSync(dir) && isInside(absRoot, dir, { orSame: true }))
|
|
75
|
+
found.push(dir)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return found
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
|
|
82
|
+
feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
|
|
83
|
+
collections?: readonly AnyCollection<unknown>[] | undefined
|
|
84
|
+
}): PrunellePlugin
|
|
85
|
+
export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly AnyCollection<unknown>[] | undefined } = {}): PrunellePlugin {
|
|
86
|
+
const feeds = options.feeds ?? []
|
|
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
|
+
}
|
|
94
|
+
|
|
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
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function activeCollections(root?: string): InternalCollection[] {
|
|
103
|
+
const out = new Set<InternalCollection>()
|
|
104
|
+
for (const f of feeds)
|
|
105
|
+
out.add(f.collection as InternalCollection)
|
|
106
|
+
for (const c of extraCollections)
|
|
107
|
+
out.add(c as InternalCollection)
|
|
108
|
+
const absRoot = root !== undefined ? resolve(root) : currentApp.root()
|
|
109
|
+
for (const c of registeredCollections.values()) {
|
|
110
|
+
const owner = c[COLLECTION_OWNER_ROOT_KEY]
|
|
111
|
+
if (owner !== undefined && absRoot !== undefined && owner !== absRoot)
|
|
112
|
+
continue
|
|
113
|
+
const dir = dirOf(c, absRoot)
|
|
114
|
+
if (dir === undefined) {
|
|
115
|
+
if (owner !== undefined || absRoot === undefined)
|
|
116
|
+
out.add(c)
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
if (!existsSync(dir))
|
|
120
|
+
continue
|
|
121
|
+
if (absRoot === undefined || isInside(absRoot, dir, { orSame: true }))
|
|
122
|
+
out.add(c)
|
|
123
|
+
}
|
|
124
|
+
return [...out]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const collectionsService = createCollectionsService(
|
|
128
|
+
activeCollections,
|
|
129
|
+
col => feedLinkPrefixes.get(col),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
return definePlugin({
|
|
133
|
+
name: '@prunellejs/content',
|
|
134
|
+
after: ['@prunellejs/i18n', '@prunellejs/images'],
|
|
135
|
+
watchPaths: (root) => {
|
|
136
|
+
const dirs = new Set<string>()
|
|
137
|
+
for (const c of activeCollections(root)) {
|
|
138
|
+
const dir = dirOf(c, root)
|
|
139
|
+
if (dir !== undefined)
|
|
140
|
+
dirs.add(dir)
|
|
141
|
+
}
|
|
142
|
+
for (const dir of discoverStaticCollectionDirs(root))
|
|
143
|
+
dirs.add(dir)
|
|
144
|
+
return [...dirs]
|
|
145
|
+
},
|
|
146
|
+
requires(ctx) {
|
|
147
|
+
return feeds
|
|
148
|
+
.filter(feed => (feed.site ?? ctx.site) === undefined)
|
|
149
|
+
.map(feed => `the feed at ${feed.path ?? '/rss.xml'} has no \`site\`, so its links are relative and feed readers cannot open them: set \`site\` in \`prunelle.config.ts\` (or on the feed).`)
|
|
150
|
+
},
|
|
151
|
+
async check(ctx) {
|
|
152
|
+
await discoverAppCollections(ctx.root)
|
|
153
|
+
ctx.provide?.(CONTENT_COLLECTIONS_SERVICE, collectionsService)
|
|
154
|
+
const seen = new Set<string>()
|
|
155
|
+
for (const c of activeCollections(ctx.root)) {
|
|
156
|
+
const validate = c[COLLECTION_VALIDATE_KEY]
|
|
157
|
+
if (validate === undefined)
|
|
158
|
+
continue
|
|
159
|
+
for (const err of await validate(ctx.root)) {
|
|
160
|
+
if (seen.has(err))
|
|
161
|
+
continue
|
|
162
|
+
seen.add(err)
|
|
163
|
+
ctx.error(err)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
async build(ctx) {
|
|
168
|
+
ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
|
|
169
|
+
for (const feed of feeds) {
|
|
170
|
+
const rel = (feed.path ?? '/rss.xml').replace(/^\/+/, '')
|
|
171
|
+
ctx.emitPublic(rel, await renderRssAsync({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown, AnyCollection<unknown>>))
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
afterPrerender(ctx) {
|
|
175
|
+
ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
|
|
176
|
+
},
|
|
177
|
+
server(api) {
|
|
178
|
+
api.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
|
|
179
|
+
if (api.config?.prerender === true)
|
|
180
|
+
api.provide(CONTENT_PRERENDER_SERVICE, true)
|
|
181
|
+
for (const feed of feeds) {
|
|
182
|
+
const path = feed.path ?? '/rss.xml'
|
|
183
|
+
const isFileBacked = feed.collection.dir !== undefined
|
|
184
|
+
let memo: { xml: string, etag: string, version: number } | undefined
|
|
185
|
+
api.route('GET', path, async (ctx) => {
|
|
186
|
+
const versionFn = (feed.collection as unknown as Record<symbol, (() => number) | undefined>)[COLLECTION_VERSION_KEY]
|
|
187
|
+
const version = versionFn ? versionFn() : -1
|
|
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>>)
|
|
194
|
+
const etag = `"${Bun.hash(xml).toString(36)}"`
|
|
195
|
+
current = { xml, etag }
|
|
196
|
+
if (isFileBacked)
|
|
197
|
+
memo = { xml, etag, version }
|
|
198
|
+
}
|
|
199
|
+
if (etagMatches(ctx.request.headers.get('if-none-match'), current.etag)) {
|
|
200
|
+
return new Response(null, {
|
|
201
|
+
status: 304,
|
|
202
|
+
headers: { etag: current.etag },
|
|
203
|
+
})
|
|
204
|
+
}
|
|
205
|
+
return new Response(current.xml, {
|
|
206
|
+
headers: {
|
|
207
|
+
'content-type': 'application/rss+xml; charset=utf-8',
|
|
208
|
+
'etag': current.etag,
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
})
|
|
215
|
+
}
|