@prunellejs/content 0.0.0-stage → 0.5.2

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.
@@ -0,0 +1,263 @@
1
+ // Loader-backed async collection implementation (`defineCollection({ load, ... })`) for headless CMSs, databases, and APIs.
2
+
3
+ import type { AppRuntimeContext, RequestContext } from 'prunelle/internal/server'
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+ import type {
6
+ AsyncCollection,
7
+ ContentEntry,
8
+ InternalCollection,
9
+ LoadedEntryInput,
10
+ LoaderCollectionOptions,
11
+ } from './types'
12
+ import { relative } from 'node:path'
13
+ import { currentRequest, getAppContext } from 'prunelle/internal/server'
14
+ import { formatIssuePath, formatSchemaIssues, validateSchema } from 'prunelle/server'
15
+ import { currentApp } from './app'
16
+ import {
17
+ buildContentEntry,
18
+ createRenderConfigLoader,
19
+ defaultSort,
20
+ filterByTag,
21
+ formatPaths,
22
+ isDevMode,
23
+ isDraft,
24
+ } from './entry'
25
+ import { currentDiscoverFile, registerLoadedCollection } from './registry'
26
+ import { CONTENT_PRERENDER_SERVICE } from './service'
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
+ function cleanSlug(rawSlug: unknown, collectionName: string): string {
35
+ if (typeof rawSlug !== 'string' || rawSlug.trim() === '')
36
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" is missing a non-empty string "slug".`)
37
+ const cleaned = rawSlug.trim().replace(/^\/+|\/+$/g, '')
38
+ if (cleaned === '')
39
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" has an empty "slug".`)
40
+ return cleaned
41
+ }
42
+
43
+ function getOrCreateLocaleMap<K extends object, T>(
44
+ store: WeakMap<K, Map<string, Promise<ContentEntry<T>[]>>>,
45
+ key: K,
46
+ ): Map<string, Promise<ContentEntry<T>[]>> {
47
+ let map = store.get(key)
48
+ if (map === undefined) {
49
+ map = new Map()
50
+ store.set(key, map)
51
+ }
52
+ return map
53
+ }
54
+
55
+ function formatCheckPrefix(root: string, sourceFile: string | undefined): string {
56
+ if (sourceFile === undefined)
57
+ return ''
58
+ const rel = relative(root, sourceFile).replace(/\\/g, '/')
59
+ return `${rel}:1:1: error: `
60
+ }
61
+
62
+ async function validateLoadedEntriesForCheck(params: {
63
+ name: string
64
+ root: string
65
+ sourceFile: string | undefined
66
+ localized: boolean
67
+ defaultLocale: string
68
+ locales: readonly string[] | undefined
69
+ schema: StandardSchemaV1 | undefined
70
+ load: LoaderCollectionOptions<unknown>['load']
71
+ }): Promise<string[]> {
72
+ const { name, root, sourceFile, localized, defaultLocale, locales, schema, load } = params
73
+ const prefix = formatCheckPrefix(root, sourceFile)
74
+ const errors: string[] = []
75
+ const seenEntries = new Set<string>()
76
+
77
+ const configuredLocales = localized ? (locales ?? currentApp.locales()) : undefined
78
+ const runs: Array<{ locale: string | undefined, filterByLocale: boolean }> = !localized
79
+ ? [{ locale: undefined, filterByLocale: false }]
80
+ : configuredLocales !== undefined && configuredLocales.length > 0
81
+ ? [...new Set(configuredLocales)].map(locale => ({ locale, filterByLocale: true }))
82
+ : [{ locale: defaultLocale, filterByLocale: false }]
83
+
84
+ for (const run of runs) {
85
+ let rawEntries: LoadedEntryInput[]
86
+ try {
87
+ rawEntries = await load(localized ? { locale: run.locale } : {})
88
+ }
89
+ catch (err) {
90
+ const msg = err instanceof Error ? err.message : String(err)
91
+ const locNote = run.locale !== undefined ? ` (locale "${run.locale}")` : ''
92
+ errors.push(`${prefix}@prunellejs/content: collection "${name}"${locNote} loader failed: ${msg}`)
93
+ continue
94
+ }
95
+
96
+ for (const raw of rawEntries) {
97
+ if (run.filterByLocale && raw.locale !== undefined && raw.locale !== run.locale)
98
+ continue
99
+ if (typeof raw.slug !== 'string' || raw.slug.trim() === '') {
100
+ errors.push(`${prefix}@prunellejs/content: collection "${name}": entry is missing a non-empty string "slug"`)
101
+ continue
102
+ }
103
+ const slug = raw.slug.trim().replace(/^\/+|\/+$/g, '')
104
+ const entryLocale = localized ? (raw.locale ?? run.locale) : raw.locale
105
+ const dedupeKey = `${entryLocale ?? ''}\0${slug}`
106
+ if (seenEntries.has(dedupeKey))
107
+ continue
108
+ seenEntries.add(dedupeKey)
109
+
110
+ if (schema === undefined)
111
+ continue
112
+ const checked = await validateSchema(schema, raw.data)
113
+ if (!checked.ok) {
114
+ const locSuffix = entryLocale !== undefined ? ` (${entryLocale})` : ''
115
+ for (const issue of checked.issues) {
116
+ const path = formatIssuePath(issue)
117
+ errors.push(`${prefix}@prunellejs/content: collection "${name}" entry "${slug}"${locSuffix}: ${path ? `${path}: ` : ''}${issue.message}`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return errors
123
+ }
124
+
125
+ export function createLoaderCollection<TData = Record<string, unknown>>(
126
+ options: LoaderCollectionOptions<TData>,
127
+ ): AsyncCollection<TData> {
128
+ const name = options.name ?? 'collection'
129
+ const localized = options.localized ?? false
130
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
131
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
132
+ const renderLoader = createRenderConfigLoader(name, options)
133
+ const sourceFile = currentDiscoverFile()
134
+
135
+ let buildCache = new WeakMap<AppRuntimeContext, Map<string, Promise<ContentEntry<TData>[]>>>()
136
+ let requestCache = new WeakMap<RequestContext, Map<string, Promise<ContentEntry<TData>[]>>>()
137
+ let lastBuildCtx: WeakRef<AppRuntimeContext> | undefined
138
+ let cacheVersion = 0
139
+
140
+ function resolveCacheMap(): Map<string, Promise<ContentEntry<TData>[]>> | undefined {
141
+ const reqCtx = currentRequest()?.ctx
142
+ const appCtx = getAppContext()
143
+ if (reqCtx === undefined && appCtx !== undefined) {
144
+ lastBuildCtx = new WeakRef(appCtx)
145
+ return getOrCreateLocaleMap(buildCache, appCtx)
146
+ }
147
+ if (reqCtx !== undefined) {
148
+ const buildCtx = lastBuildCtx?.deref()
149
+ if (
150
+ buildCtx !== undefined
151
+ && appCtx !== undefined
152
+ && appCtx.root === buildCtx.root
153
+ && appCtx.outDir === buildCtx.outDir
154
+ )
155
+ return getOrCreateLocaleMap(buildCache, buildCtx)
156
+ if (appCtx?.inject(CONTENT_PRERENDER_SERVICE) === true)
157
+ return getOrCreateLocaleMap(buildCache, appCtx)
158
+ return getOrCreateLocaleMap(requestCache, reqCtx)
159
+ }
160
+ return undefined
161
+ }
162
+
163
+ async function loadValidatedEntries(targetLocale: string | undefined): Promise<ContentEntry<TData>[]> {
164
+ const rawEntries = await options.load(localized ? { locale: targetLocale } : {})
165
+ const entries: ContentEntry<TData>[] = []
166
+ for (const raw of rawEntries) {
167
+ if (localized && raw.locale !== undefined && raw.locale !== targetLocale)
168
+ continue
169
+ const slug = cleanSlug(raw.slug, name)
170
+ let data: TData
171
+ if (options.schema !== undefined) {
172
+ const checked = await validateSchema(options.schema, raw.data)
173
+ if (!checked.ok) {
174
+ throw new Error(
175
+ `@prunellejs/content: invalid entry "${slug}" in collection "${name}": ${formatSchemaIssues(checked.issues)}`,
176
+ )
177
+ }
178
+ data = checked.value
179
+ }
180
+ else {
181
+ data = (raw.data !== null && typeof raw.data === 'object' ? raw.data : {}) as TData
182
+ }
183
+ const entryLocale = localized ? (raw.locale ?? targetLocale) : raw.locale
184
+ const file = raw.id ?? `${name}:${slug}`
185
+ entries.push(buildContentEntry({
186
+ slug,
187
+ locale: entryLocale,
188
+ file,
189
+ data,
190
+ body: raw.body ?? '',
191
+ renderLoader,
192
+ }))
193
+ }
194
+ entries.sort(options.sort ?? defaultSort)
195
+ return entries
196
+ }
197
+
198
+ function loadCached(locale?: string): Promise<ContentEntry<TData>[]> {
199
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
200
+ const cacheKey = targetLocale ?? ''
201
+ const bucket = resolveCacheMap()
202
+ if (bucket !== undefined) {
203
+ const hit = bucket.get(cacheKey)
204
+ if (hit !== undefined)
205
+ return hit
206
+ const pending = loadValidatedEntries(targetLocale).catch((err) => {
207
+ bucket.delete(cacheKey)
208
+ throw err
209
+ })
210
+ bucket.set(cacheKey, pending)
211
+ return pending
212
+ }
213
+ return loadValidatedEntries(targetLocale)
214
+ }
215
+
216
+ async function all(locale?: string): Promise<ContentEntry<TData>[]> {
217
+ const entries = await loadCached(locale)
218
+ return allowsDrafts() ? entries.slice() : entries.filter(e => !isDraft(e.data))
219
+ }
220
+
221
+ async function get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined> {
222
+ const clean = slug.replace(/^\/+|\/+$/g, '')
223
+ const entries = await all(locale)
224
+ return entries.find(e => e.slug === clean)
225
+ }
226
+
227
+ const col: AsyncCollection<TData> & InternalCollection = {
228
+ name,
229
+ all,
230
+ get,
231
+ byTag: async (tag, locale) => filterByTag(await all(locale), tag),
232
+ paths: async (prefix = '', locale) => formatPaths(await all(locale), prefix),
233
+ clearCache() {
234
+ buildCache = new WeakMap()
235
+ requestCache = new WeakMap()
236
+ lastBuildCtx = undefined
237
+ cacheVersion++
238
+ },
239
+ [COLLECTION_VERSION_KEY]: () => cacheVersion,
240
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateLoadedEntriesForCheck({
241
+ name,
242
+ root,
243
+ sourceFile,
244
+ localized,
245
+ defaultLocale: getDefaultLocale(),
246
+ locales: options.locales,
247
+ schema: options.schema,
248
+ load: options.load,
249
+ }),
250
+ [COLLECTION_DIR_FOR_ROOT_KEY]: () => undefined,
251
+ [COLLECTION_META_KEY]: () => ({
252
+ name,
253
+ localized,
254
+ defaultLocale: getDefaultLocale(),
255
+ locales: options.locales ?? (localized ? currentApp.locales() : undefined),
256
+ schema: options.schema,
257
+ isAsync: true,
258
+ }),
259
+ }
260
+
261
+ registerLoadedCollection(col, options.name, localized)
262
+ return col
263
+ }
@@ -0,0 +1,183 @@
1
+ // renderMarkdown: Bun's native Markdown renderer plus highlight hook, embedded components, heading ids and TOC.
2
+
3
+ import type { ContentHeading, MarkdownImageResolver, MarkdownImageResult, RenderMarkdownOptions } from './index'
4
+ import { escAttr } from 'prunelle/server'
5
+ import { currentApp } from './app'
6
+ import { expandComponents } from './components'
7
+ import { sanitizeMarkdownHtml } from './sanitize'
8
+
9
+ function slugifyHeading(text: string): string {
10
+ return text
11
+ .toLowerCase()
12
+ .normalize('NFKD')
13
+ .replace(/[\u0300-\u036F]/g, '')
14
+ .replace(/<[^>]+>/g, '')
15
+ .replace(/[^a-z0-9]+/g, '-')
16
+ .replace(/^-+|-+$/g, '') || 'section'
17
+ }
18
+
19
+ function stripTags(html: string): string {
20
+ return html
21
+ .replace(/<[^>]+>/g, '')
22
+ .replaceAll('&lt;', '<')
23
+ .replaceAll('&gt;', '>')
24
+ .replaceAll('&quot;', '"')
25
+ .replaceAll('&#39;', '\'')
26
+ .replaceAll('&amp;', '&')
27
+ .trim()
28
+ }
29
+
30
+ function findDefaultImageResolver(file: string | undefined): MarkdownImageResolver | undefined {
31
+ if (!file)
32
+ return undefined
33
+ return currentApp.imageResolver()
34
+ }
35
+
36
+ // CommonMark §4.5: backtick fence info strings cannot contain backticks; fences cannot mix ` and ~.
37
+ const FENCE_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))\n([\s\S]*?)^\1\3[ \t]*$/gm
38
+ let slotBatchId = 0
39
+
40
+ function renderMarkdownInternal(
41
+ body: string,
42
+ options: RenderMarkdownOptions,
43
+ inheritedSlotPrefixes?: ReadonlySet<string>,
44
+ ): {
45
+ html: string
46
+ headings: ContentHeading[]
47
+ wordCount: number
48
+ readingMinutes: number
49
+ } {
50
+ const slots: string[] = []
51
+ // Cryptographically unguessable per-render slot prefix so untrusted markdown cannot forge or duplicate component slots.
52
+ const slotPrefix = `b${++slotBatchId}-${crypto.randomUUID().slice(0, 12)}-`
53
+ const allowedSlotPrefixes = new Set<string>(inheritedSlotPrefixes)
54
+ allowedSlotPrefixes.add(slotPrefix)
55
+ let processed = body
56
+
57
+ // 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
58
+ if (options.highlight !== undefined || options.components !== undefined) {
59
+ processed = processed.replace(FENCE_RE, (
60
+ full,
61
+ btFence: string | undefined,
62
+ btInfo: string | undefined,
63
+ _tildeFence: string | undefined,
64
+ tildeInfo: string | undefined,
65
+ code: string,
66
+ ) => {
67
+ const info = btFence !== undefined ? (btInfo ?? '') : (tildeInfo ?? '')
68
+ if (options.highlight !== undefined) {
69
+ const lang = info.trim().split(/\s+/)[0] || undefined
70
+ const idx = slots.length
71
+ slots.push(options.highlight(code.replace(/\n$/, ''), lang))
72
+ return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
73
+ }
74
+ // Protect code fences from component expansion when only components are configured
75
+ const idx = slots.length
76
+ let renderedFence = Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true })
77
+ if (options.trusted !== true)
78
+ renderedFence = sanitizeMarkdownHtml(renderedFence)
79
+ slots.push(renderedFence)
80
+ return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
81
+ })
82
+ }
83
+
84
+ // 2. Expand embedded TSX components
85
+ if (options.components !== undefined) {
86
+ processed = expandComponents(
87
+ processed,
88
+ options.components,
89
+ options,
90
+ slots,
91
+ slotPrefix,
92
+ (innerMd, innerOpts) => renderMarkdownInternal(innerMd, innerOpts, allowedSlotPrefixes),
93
+ )
94
+ }
95
+
96
+ // 3. Render remaining Markdown via native Zig Bun.markdown.html
97
+ let html = Bun.markdown.html(processed, {
98
+ tables: true,
99
+ strikethrough: true,
100
+ tasklists: true,
101
+ autolinks: true,
102
+ })
103
+
104
+ // 3b. Sanitize rendered Markdown HTML by default unless `trusted: true` is opted into.
105
+ // Runs before splicing developer-supplied highlight/component slots so custom components remain intact.
106
+ if (options.trusted !== true)
107
+ html = sanitizeMarkdownHtml(html, allowedSlotPrefixes)
108
+
109
+ // 4. Add unique heading IDs & collect TOC
110
+ const headings: ContentHeading[] = []
111
+ const usedIds = new Map<string, number>()
112
+
113
+ html = html.replace(/<h([1-6])>([\s\S]*?)<\/h\1>/g, (_match, levelStr: string, inner: string) => {
114
+ const level = Number(levelStr)
115
+ const text = stripTags(inner)
116
+ const base = slugifyHeading(text)
117
+ const count = usedIds.get(base) ?? 0
118
+ usedIds.set(base, count + 1)
119
+ const id = count === 0 ? base : `${base}-${count}`
120
+ headings.push({ level, id, text })
121
+ if (options.headingLinks && level >= 2 && !/<a\b/i.test(inner))
122
+ return `<h${level} id="${id}"><a href="#${id}">${inner}</a></h${level}>`
123
+ return `<h${level} id="${id}">${inner}</h${level}>`
124
+ })
125
+
126
+ // 4b. Image rewriting (explicit resolveImage or auto-wired @prunellejs/images; `false` disables)
127
+ const resolveImageFn = options.resolveImage === false
128
+ ? undefined
129
+ : (options.resolveImage ?? findDefaultImageResolver(options.file))
130
+ if (resolveImageFn !== undefined) {
131
+ html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
132
+ const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
133
+ if (!srcMatch)
134
+ return full
135
+ const resolved = resolveImageFn(srcMatch[1]!, options.file)
136
+ if (!resolved)
137
+ return full
138
+ const info: MarkdownImageResult = typeof resolved === 'string' ? { src: resolved } : resolved
139
+ const altMatch = /\balt="([^"]*)"/i.exec(attrs)
140
+ const alt = altMatch ? altMatch[1]! : ''
141
+ const parts = [`src="${escAttr(info.src)}"`, `alt="${alt}"`]
142
+ if (info.srcset)
143
+ parts.push(`srcset="${escAttr(info.srcset)}"`)
144
+ if (info.sizes)
145
+ parts.push(`sizes="${escAttr(info.sizes)}"`)
146
+ if (info.width !== undefined && info.width > 0)
147
+ parts.push(`width="${info.width}"`)
148
+ if (info.height !== undefined && info.height > 0)
149
+ parts.push(`height="${info.height}"`)
150
+ parts.push(`loading="${info.loading ?? 'lazy'}"`, 'decoding="async"')
151
+ const imgTag = `<img ${parts.join(' ')}>`
152
+ if (info.avifSrcset) {
153
+ const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
154
+ return `<picture><source type="image/avif" srcset="${escAttr(info.avifSrcset)}"${sizesAttr}>${imgTag}</picture>`
155
+ }
156
+ return imgTag
157
+ })
158
+ }
159
+
160
+ // 5. Splice this batch's highlighted code blocks & embedded TSX components back in (loop handles components wrapping code fences)
161
+ if (slots.length > 0) {
162
+ const slotRe = new RegExp(`<div data-pru-md-slot="${slotPrefix}(\\d+)"><\\/div>`, 'g')
163
+ let prev = ''
164
+ while (prev !== html) {
165
+ prev = html
166
+ html = html.replace(slotRe, (_m, idxStr: string) => slots[Number(idxStr)] ?? '')
167
+ }
168
+ }
169
+
170
+ const words = body.trim().split(/\s+/).filter(Boolean).length
171
+ const readingMinutes = Math.max(1, Math.ceil(words / 220))
172
+ return { html, headings, wordCount: words, readingMinutes }
173
+ }
174
+
175
+ /** Renders Markdown via Bun's native Zig `Bun.markdown.html()`, with optional Shiki `highlight`, embedded TSX `components`, heading IDs, TOC, and reading time. */
176
+ export function renderMarkdown(body: string, options: RenderMarkdownOptions = {}): {
177
+ html: string
178
+ headings: ContentHeading[]
179
+ wordCount: number
180
+ readingMinutes: number
181
+ } {
182
+ return renderMarkdownInternal(body, options)
183
+ }
@@ -0,0 +1,135 @@
1
+ // Process-level collection registry and `src/` file discovery for `prunelle check` and `CONTENT_COLLECTIONS_SERVICE`.
2
+
3
+ import type { InternalCollection } from './types'
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
+ import { isAbsolute, join, resolve } from 'node:path'
6
+ import { currentApp } from './app'
7
+ import { COLLECTION_OWNER_ROOT_KEY, COLLECTION_VALIDATE_KEY } from './types'
8
+
9
+ // Keyed by (ownerRoot, resolved dir or loader identity, localized) so dev reloads replace the prior instance instead of leaking.
10
+ export const registeredCollections = new Map<string, InternalCollection>()
11
+
12
+ let discoverRoot: string | undefined
13
+ let discoverFile: string | undefined
14
+ let discoverIndex = 0
15
+ let anonLoaderSeq = 0
16
+
17
+ export function currentDiscoverFile(): string | undefined {
18
+ return discoverFile
19
+ }
20
+
21
+ function resolveOwnerRoot(rawDir?: string): string | undefined {
22
+ const owner = discoverRoot ?? currentApp.root()
23
+ const explicitOwner = owner !== undefined && owner !== '' ? resolve(owner) : undefined
24
+ if (explicitOwner !== undefined)
25
+ return explicitOwner
26
+ if (rawDir !== undefined && !isAbsolute(rawDir))
27
+ return resolve(process.cwd())
28
+ return undefined
29
+ }
30
+
31
+ export function registerFileCollection(col: InternalCollection, rawDir: string, localized: boolean): void {
32
+ const absOwner = resolveOwnerRoot(rawDir)
33
+ col[COLLECTION_OWNER_ROOT_KEY] = absOwner
34
+ const resolvedKey = isAbsolute(rawDir)
35
+ ? resolve(rawDir)
36
+ : (absOwner !== undefined ? resolve(absOwner, rawDir) : rawDir)
37
+ registeredCollections.set(`${absOwner ?? ''}\0${resolvedKey}\0${localized ? '1' : '0'}`, col)
38
+ }
39
+
40
+ export function registerLoadedCollection(
41
+ col: InternalCollection,
42
+ explicitName: string | undefined,
43
+ localized: boolean,
44
+ ): void {
45
+ const absOwner = resolveOwnerRoot()
46
+ col[COLLECTION_OWNER_ROOT_KEY] = absOwner
47
+ const identity = explicitName !== undefined && explicitName !== ''
48
+ ? `load:name:${explicitName}`
49
+ : discoverFile !== undefined
50
+ ? `load:file:${discoverFile}#${discoverIndex++}`
51
+ : `load:anon:${++anonLoaderSeq}`
52
+ registeredCollections.set(`${absOwner ?? ''}\0${identity}\0${localized ? '1' : '0'}`, col)
53
+ }
54
+
55
+ export function walkCollectionDefFiles(dir: string, out: string[] = []): string[] {
56
+ if (!existsSync(dir))
57
+ return out
58
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
59
+ if (ent.name === 'node_modules' || ent.name === 'dist' || ent.name.startsWith('.'))
60
+ continue
61
+ const full = join(dir, ent.name)
62
+ if (ent.isDirectory())
63
+ walkCollectionDefFiles(full, out)
64
+ else if (ent.isFile() && (ent.name.endsWith('.ts') || ent.name.endsWith('.tsx')) && !ent.name.endsWith('.d.ts') && !/\.(?:test|spec)\.tsx?$/.test(ent.name))
65
+ out.push(full)
66
+ }
67
+ return out
68
+ }
69
+
70
+ export const DEFINE_COLLECTION_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(/
71
+ const REGEXP_SPECIAL_RE = /[.*+?^${}()|[\]\\]/g
72
+
73
+ const prunelleJsxRoots = new Set<string>()
74
+
75
+ // Bun gives a runtime import the JSX source of the working directory's tsconfig, not the app's, so `prunelle check <dir>` run elsewhere would import its routes as React.
76
+ function importAppTsxWithPrunelleJsx(root: string): void {
77
+ if (prunelleJsxRoots.has(root))
78
+ return
79
+ prunelleJsxRoots.add(root)
80
+ const filter = new RegExp(`^${`${root}/`.replace(REGEXP_SPECIAL_RE, '\\$&')}.*\\.tsx$`)
81
+ Bun.plugin({
82
+ name: `@prunellejs/content: prunelle JSX under ${root}`,
83
+ setup(build) {
84
+ // The pragma goes last, where it moves no line of a stack trace.
85
+ build.onLoad({ filter }, async ({ path }) => ({ contents: `${await Bun.file(path).text()}\n/** @jsxImportSource prunelle */\n`, loader: 'tsx' }))
86
+ },
87
+ })
88
+ }
89
+
90
+ export async function discoverAppCollections(root: string): Promise<void> {
91
+ const absRoot = resolve(root)
92
+ const prevDiscoverRoot = discoverRoot
93
+ const prevDiscoverFile = discoverFile
94
+ const prevDiscoverIndex = discoverIndex
95
+ discoverRoot = absRoot
96
+ try {
97
+ importAppTsxWithPrunelleJsx(absRoot)
98
+ const srcDir = resolve(absRoot, 'src')
99
+ for (const file of walkCollectionDefFiles(srcDir)) {
100
+ let text: string
101
+ try {
102
+ text = readFileSync(file, 'utf8')
103
+ }
104
+ catch {
105
+ continue
106
+ }
107
+ if (!DEFINE_COLLECTION_RE.test(text))
108
+ continue
109
+ discoverFile = file
110
+ discoverIndex = 0
111
+ try {
112
+ const mod = await import(file) as Record<string, unknown>
113
+ for (const val of Object.values(mod)) {
114
+ if (val !== null && typeof val === 'object' && COLLECTION_VALIDATE_KEY in val) {
115
+ const col = val as InternalCollection
116
+ if (col[COLLECTION_OWNER_ROOT_KEY] === undefined) {
117
+ col[COLLECTION_OWNER_ROOT_KEY] = absRoot
118
+ const label = col.name ?? `file:${file}#${discoverIndex++}`
119
+ registeredCollections.set(`${absRoot}\0adopted:${file}:${label}`, col)
120
+ }
121
+ }
122
+ }
123
+ }
124
+ catch {
125
+ // Route/TSX files may import virtual modules (~icons) or CSS outside Bun.build; skip unimportable files.
126
+ continue
127
+ }
128
+ }
129
+ }
130
+ finally {
131
+ discoverRoot = prevDiscoverRoot
132
+ discoverFile = prevDiscoverFile
133
+ discoverIndex = prevDiscoverIndex
134
+ }
135
+ }
package/src/rss.ts ADDED
@@ -0,0 +1,105 @@
1
+ // RSS 2.0 XML feed generation and ETag matching for @prunellejs/content.
2
+
3
+ import type { AnyCollection, Collection, ContentEntry } from './types'
4
+ import { escAttr } from 'prunelle/server'
5
+ import { currentApp } from './app'
6
+
7
+ export interface RssFeedConfig<
8
+ TData = Record<string, unknown>,
9
+ TCol extends AnyCollection<TData> = Collection<TData>,
10
+ > {
11
+ /** Public path for the RSS XML file (default: '/rss.xml'). */
12
+ path?: string | undefined
13
+ title: string
14
+ description: string
15
+ /** Public site origin; defaults to `PrunelleConfig.site` when registered via `content()`. */
16
+ site?: string | undefined
17
+ collection: TCol
18
+ locale?: string | undefined
19
+ /** URL prefix prepended to each entry's slug (e.g. '/blog'). */
20
+ linkPrefix?: string | undefined
21
+ mapItem?: ((entry: ContentEntry<TData>) => {
22
+ title: string
23
+ description?: string | undefined
24
+ date?: string | Date | undefined
25
+ link?: string | undefined
26
+ }) | undefined
27
+ }
28
+
29
+ export interface ContentFeed {
30
+ readonly path?: string | undefined
31
+ readonly title: string
32
+ readonly description: string
33
+ readonly site?: string | undefined
34
+ readonly collection: AnyCollection<unknown>
35
+ readonly locale?: string | undefined
36
+ readonly linkPrefix?: string | undefined
37
+ readonly mapItem?: ((entry: ContentEntry<never>) => {
38
+ title: string
39
+ description?: string | undefined
40
+ date?: string | Date | undefined
41
+ link?: string | undefined
42
+ }) | undefined
43
+ }
44
+
45
+ function formatPubDate(value: string | Date | undefined): string {
46
+ if (value === undefined || value === '')
47
+ return ''
48
+ const date = value instanceof Date ? value : new Date(value)
49
+ return Number.isNaN(date.getTime()) ? '' : `<pubDate>${date.toUTCString()}</pubDate>`
50
+ }
51
+
52
+ function buildRssXml<TData>(
53
+ feed: Pick<RssFeedConfig<TData, AnyCollection<TData>>, 'title' | 'description' | 'site' | 'linkPrefix' | 'mapItem'>,
54
+ entries: readonly ContentEntry<TData>[],
55
+ ): string {
56
+ const site = (feed.site ?? currentApp.site() ?? '').replace(/\/$/, '')
57
+ const prefix = (feed.linkPrefix ?? '').replace(/\/$/, '')
58
+ const items = entries
59
+ .filter(entry => entry.data === null || typeof entry.data !== 'object' || (entry.data as Record<string, unknown>).draft !== true)
60
+ .map((entry) => {
61
+ const rawData = (entry.data !== null && typeof entry.data === 'object' ? entry.data : {}) as Record<string, unknown>
62
+ const mapped = feed.mapItem
63
+ ? feed.mapItem(entry)
64
+ : {
65
+ title: String(rawData.title ?? entry.slug),
66
+ description: typeof rawData.description === 'string' ? rawData.description : undefined,
67
+ date: rawData.date as string | Date | undefined,
68
+ link: `${site}${prefix}/${entry.slug}`,
69
+ }
70
+ const link = mapped.link ?? `${site}${prefix}/${entry.slug}`
71
+ const pubDate = formatPubDate(mapped.date)
72
+ const desc = mapped.description ? `<description>${escAttr(mapped.description)}</description>` : ''
73
+ return `<item><title>${escAttr(mapped.title)}</title><link>${escAttr(link)}</link><guid>${escAttr(link)}</guid>${pubDate}${desc}</item>`
74
+ }).join('')
75
+
76
+ return `<?xml version="1.0" encoding="UTF-8"?>`
77
+ + `<rss version="2.0"><channel>`
78
+ + `<title>${escAttr(feed.title)}</title>`
79
+ + `<link>${escAttr(site)}</link>`
80
+ + `<description>${escAttr(feed.description)}</description>`
81
+ + items
82
+ + `</channel></rss>`
83
+ }
84
+
85
+ export function renderRss<TData>(feed: RssFeedConfig<TData>): string {
86
+ const entries = feed.collection.all(feed.locale) as ContentEntry<TData>[] | Promise<ContentEntry<TData>[]>
87
+ if (entries instanceof Promise)
88
+ throw new TypeError('@prunellejs/content: renderRss() is synchronous; use `await renderRssAsync()` for loader-backed collections.')
89
+ return buildRssXml(feed, entries)
90
+ }
91
+
92
+ export async function renderRssAsync<TData>(feed: RssFeedConfig<TData, AnyCollection<TData>>): Promise<string> {
93
+ const entries = await feed.collection.all(feed.locale)
94
+ return buildRssXml(feed, entries)
95
+ }
96
+
97
+ export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
98
+ if (!ifNoneMatch)
99
+ return false
100
+ const trimmed = ifNoneMatch.trim()
101
+ if (trimmed === '*')
102
+ return true
103
+ const target = etag.replace(/^W\//, '')
104
+ return trimmed.split(',').some(part => part.trim().replace(/^W\//, '') === target)
105
+ }