@prunellejs/content 0.0.0-stage → 0.7.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,218 @@
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 { sanitizeMarkdownHtml } from 'prunelle/internal/server'
5
+ import { escAttr } from 'prunelle/server'
6
+ import { currentApp } from './app'
7
+ import { expandComponents } from './components'
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_OPEN_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))$/
38
+ const FENCE_CLOSE_RE = /^(`{3,}|~{3,})[ \t]*\r?$/
39
+ let slotBatchId = 0
40
+
41
+ function renderMarkdownInternal(
42
+ body: string,
43
+ options: RenderMarkdownOptions,
44
+ inheritedSlotPrefixes?: ReadonlySet<string>,
45
+ ): {
46
+ html: string
47
+ headings: ContentHeading[]
48
+ wordCount: number
49
+ readingMinutes: number
50
+ } {
51
+ const slots: string[] = []
52
+ // Cryptographically unguessable per-render slot prefix so untrusted markdown cannot forge or duplicate component slots.
53
+ const slotPrefix = `b${++slotBatchId}-${crypto.randomUUID().slice(0, 12)}-`
54
+ const allowedSlotPrefixes = new Set<string>(inheritedSlotPrefixes)
55
+ allowedSlotPrefixes.add(slotPrefix)
56
+ let processed = body
57
+
58
+ // 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
59
+ if (options.highlight !== undefined || options.components !== undefined) {
60
+ processed = replaceFences(processed, (full, info, code) => {
61
+ if (options.highlight !== undefined) {
62
+ const lang = info.trim().split(/\s+/)[0] || undefined
63
+ const idx = slots.length
64
+ slots.push(options.highlight(code.replace(/\n$/, ''), lang))
65
+ return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
66
+ }
67
+ // Protect code fences from component expansion when only components are configured
68
+ const idx = slots.length
69
+ let renderedFence = Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true })
70
+ if (options.trusted !== true)
71
+ renderedFence = sanitizeMarkdownHtml(renderedFence)
72
+ slots.push(renderedFence)
73
+ return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
74
+ })
75
+ }
76
+
77
+ // 2. Expand embedded TSX components
78
+ if (options.components !== undefined) {
79
+ processed = expandComponents(
80
+ processed,
81
+ options.components,
82
+ options,
83
+ slots,
84
+ slotPrefix,
85
+ (innerMd, innerOpts) => renderMarkdownInternal(innerMd, innerOpts, allowedSlotPrefixes),
86
+ )
87
+ }
88
+
89
+ // 3. Render remaining Markdown via native Zig Bun.markdown.html
90
+ let html = Bun.markdown.html(processed, {
91
+ tables: true,
92
+ strikethrough: true,
93
+ tasklists: true,
94
+ autolinks: true,
95
+ })
96
+
97
+ // 3b. Sanitize rendered Markdown HTML by default unless `trusted: true` is opted into.
98
+ // Runs before splicing developer-supplied highlight/component slots so custom components remain intact.
99
+ if (options.trusted !== true)
100
+ html = sanitizeMarkdownHtml(html, allowedSlotPrefixes)
101
+
102
+ // 4. Add unique heading IDs & collect TOC
103
+ const headings: ContentHeading[] = []
104
+ const usedIds = new Map<string, number>()
105
+
106
+ html = html.replace(/<h([1-6])>([\s\S]*?)<\/h\1>/g, (_match, levelStr: string, inner: string) => {
107
+ const level = Number(levelStr)
108
+ const text = stripTags(inner)
109
+ const base = slugifyHeading(text)
110
+ const count = usedIds.get(base) ?? 0
111
+ usedIds.set(base, count + 1)
112
+ const id = count === 0 ? base : `${base}-${count}`
113
+ headings.push({ level, id, text })
114
+ if (options.headingLinks && level >= 2 && !/<a\b/i.test(inner))
115
+ return `<h${level} id="${id}"><a href="#${id}">${inner}</a></h${level}>`
116
+ return `<h${level} id="${id}">${inner}</h${level}>`
117
+ })
118
+
119
+ // 4b. Image rewriting (explicit resolveImage or auto-wired @prunellejs/images; `false` disables)
120
+ const resolveImageFn = options.resolveImage === false
121
+ ? undefined
122
+ : (options.resolveImage ?? findDefaultImageResolver(options.file))
123
+ if (resolveImageFn !== undefined) {
124
+ // The first image is often the page's largest paint, which lazy loading would hold back.
125
+ let seen = 0
126
+ html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
127
+ const first = seen++ === 0
128
+ const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
129
+ if (!srcMatch)
130
+ return full
131
+ const resolved = resolveImageFn(srcMatch[1]!, options.file)
132
+ if (!resolved)
133
+ return full
134
+ const info: MarkdownImageResult = typeof resolved === 'string' ? { src: resolved } : resolved
135
+ const altMatch = /\balt="([^"]*)"/i.exec(attrs)
136
+ const alt = altMatch ? altMatch[1]! : ''
137
+ const parts = [`src="${escAttr(info.src)}"`, `alt="${alt}"`]
138
+ if (info.srcset)
139
+ parts.push(`srcset="${escAttr(info.srcset)}"`)
140
+ if (info.sizes)
141
+ parts.push(`sizes="${escAttr(info.sizes)}"`)
142
+ if (info.width !== undefined && info.width > 0)
143
+ parts.push(`width="${info.width}"`)
144
+ if (info.height !== undefined && info.height > 0)
145
+ parts.push(`height="${info.height}"`)
146
+ parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
147
+ const imgTag = `<img ${parts.join(' ')}>`
148
+ if (info.avifSrcset) {
149
+ const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
150
+ return `<picture><source type="image/avif" srcset="${escAttr(info.avifSrcset)}"${sizesAttr}>${imgTag}</picture>`
151
+ }
152
+ return imgTag
153
+ })
154
+ }
155
+
156
+ // 5. Splice this batch's highlighted code blocks & embedded TSX components back in (loop handles components wrapping code fences)
157
+ if (slots.length > 0) {
158
+ const slotRe = new RegExp(`<div data-pru-md-slot="${slotPrefix}(\\d+)"><\\/div>`, 'g')
159
+ let prev = ''
160
+ while (prev !== html) {
161
+ prev = html
162
+ html = html.replace(slotRe, (_m, idxStr: string) => slots[Number(idxStr)] ?? '')
163
+ }
164
+ }
165
+
166
+ const words = body.trim().split(/\s+/).filter(Boolean).length
167
+ const readingMinutes = Math.max(1, Math.ceil(words / 220))
168
+ return { html, headings, wordCount: words, readingMinutes }
169
+ }
170
+
171
+ /** Renders Markdown via Bun's native Zig `Bun.markdown.html()`, with optional Shiki `highlight`, embedded TSX `components`, heading IDs, TOC, and reading time. */
172
+ export function renderMarkdown(body: string, options: RenderMarkdownOptions = {}): {
173
+ html: string
174
+ headings: ContentHeading[]
175
+ wordCount: number
176
+ readingMinutes: number
177
+ } {
178
+ return renderMarkdownInternal(body, options)
179
+ }
180
+
181
+ // Fenced blocks in one pass: closing lines are indexed by fence first, so an opener never closed costs one lookup, not a scan to the end.
182
+ function replaceFences(md: string, replace: (full: string, info: string, code: string) => string): string {
183
+ const lines = md.split('\n')
184
+ const closers = new Map<string, number[]>()
185
+ lines.forEach((line, index) => {
186
+ const fence = FENCE_CLOSE_RE.exec(line)?.[1]
187
+ if (fence === undefined)
188
+ return
189
+ const list = closers.get(fence)
190
+ if (list === undefined)
191
+ closers.set(fence, [index])
192
+ else
193
+ list.push(index)
194
+ })
195
+ const cursors = new Map<string, number>()
196
+ const nextCloser = (fence: string, after: number): number => {
197
+ const list = closers.get(fence) ?? []
198
+ let cursor = cursors.get(fence) ?? 0
199
+ while (cursor < list.length && list[cursor]! <= after) cursor++
200
+ cursors.set(fence, cursor)
201
+ return list[cursor] ?? -1
202
+ }
203
+ const out: string[] = []
204
+ for (let i = 0; i < lines.length; i++) {
205
+ const open = FENCE_OPEN_RE.exec(lines[i]!)
206
+ const fence = open?.[1] ?? open?.[3]
207
+ const close = fence === undefined ? -1 : nextCloser(fence, i)
208
+ if (close === -1) {
209
+ out.push(lines[i]!)
210
+ continue
211
+ }
212
+ const body = lines.slice(i + 1, close)
213
+ const code = body.length > 0 ? `${body.join('\n')}\n` : ''
214
+ out.push(replace(lines.slice(i, close + 1).join('\n'), open![2] ?? open![4] ?? '', code))
215
+ i = close
216
+ }
217
+ return out.join('\n')
218
+ }
@@ -0,0 +1,147 @@
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, statSync } from 'node:fs'
5
+ import { isAbsolute, join, relative, 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
+ // Per app root and file: the mtime it was last read at, and whether its import failed, so discovery reads only what changed.
91
+ const seenFiles = new Map<string, { mtimeMs: number, failed: boolean }>()
92
+
93
+ export async function discoverAppCollections(root: string): Promise<void> {
94
+ const absRoot = resolve(root)
95
+ const prevDiscoverRoot = discoverRoot
96
+ const prevDiscoverFile = discoverFile
97
+ const prevDiscoverIndex = discoverIndex
98
+ discoverRoot = absRoot
99
+ try {
100
+ importAppTsxWithPrunelleJsx(absRoot)
101
+ const srcDir = resolve(absRoot, 'src')
102
+ for (const file of walkCollectionDefFiles(srcDir)) {
103
+ const seenKey = `${absRoot}\0${file}`
104
+ let text: string
105
+ let mtimeMs: number
106
+ try {
107
+ mtimeMs = statSync(file).mtimeMs
108
+ if (seenFiles.get(seenKey)?.mtimeMs === mtimeMs)
109
+ continue
110
+ text = readFileSync(file, 'utf8')
111
+ }
112
+ catch {
113
+ continue
114
+ }
115
+ const failedBefore = seenFiles.get(seenKey)?.failed === true
116
+ seenFiles.set(seenKey, { mtimeMs, failed: false })
117
+ if (!DEFINE_COLLECTION_RE.test(text))
118
+ continue
119
+ discoverFile = file
120
+ discoverIndex = 0
121
+ try {
122
+ // Bun keeps a failed import's error: a file fixed since is imported under a new URL so it runs again.
123
+ const mod = await import(failedBefore ? `${file}?v=${mtimeMs}` : file) as Record<string, unknown>
124
+ for (const val of Object.values(mod)) {
125
+ if (val !== null && typeof val === 'object' && COLLECTION_VALIDATE_KEY in val) {
126
+ const col = val as InternalCollection
127
+ if (col[COLLECTION_OWNER_ROOT_KEY] === undefined) {
128
+ col[COLLECTION_OWNER_ROOT_KEY] = absRoot
129
+ const label = col.name ?? `file:${file}#${discoverIndex++}`
130
+ registeredCollections.set(`${absRoot}\0adopted:${file}:${label}`, col)
131
+ }
132
+ }
133
+ }
134
+ }
135
+ catch (err) {
136
+ seenFiles.set(seenKey, { mtimeMs, failed: true })
137
+ const reason = err instanceof Error ? err.message : String(err)
138
+ console.warn(`@prunellejs/content: ${relative(absRoot, file)} calls defineCollection but could not be imported, so its collections are left out: ${reason}`)
139
+ }
140
+ }
141
+ }
142
+ finally {
143
+ discoverRoot = prevDiscoverRoot
144
+ discoverFile = prevDiscoverFile
145
+ discoverIndex = prevDiscoverIndex
146
+ }
147
+ }
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 { escXml } 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>${escXml(mapped.description)}</description>` : ''
73
+ return `<item><title>${escXml(mapped.title)}</title><link>${escXml(link)}</link><guid>${escXml(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>${escXml(feed.title)}</title>`
79
+ + `<link>${escXml(site)}</link>`
80
+ + `<description>${escXml(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
+ }
package/src/service.ts ADDED
@@ -0,0 +1,88 @@
1
+ // `CONTENT_COLLECTIONS_SERVICE` adapter and internal prerender marker service for @prunellejs/content.
2
+
3
+ import type {
4
+ ContentCollectionDescriptor,
5
+ ContentCollectionEntrySummary,
6
+ ContentCollectionsService,
7
+ } from 'prunelle/config'
8
+ import type { ContentEntry, InternalCollection } from './types'
9
+ import { basename } from 'node:path'
10
+ import { serviceKey } from 'prunelle/config'
11
+ import { discoverAppCollections } from './registry'
12
+ import { getAccessedEntries } from './tracking'
13
+ import { COLLECTION_DIR_FOR_ROOT_KEY, COLLECTION_META_KEY } from './types'
14
+
15
+ /** Internal build-time marker provided on the prerender server's AppRuntimeContext so loaded collections cache across prerendered pages. */
16
+ export const CONTENT_PRERENDER_SERVICE = serviceKey<boolean>('prunelle.content.prerender')
17
+
18
+ function toEntrySummary(entry: ContentEntry<unknown>): ContentCollectionEntrySummary {
19
+ const data = entry.data !== null && typeof entry.data === 'object'
20
+ ? entry.data as Record<string, unknown>
21
+ : {}
22
+ return {
23
+ slug: entry.slug,
24
+ ...(entry.locale !== undefined ? { locale: entry.locale } : {}),
25
+ file: entry.file,
26
+ data,
27
+ body: entry.body,
28
+ }
29
+ }
30
+
31
+ export function toCollectionDescriptor(
32
+ col: InternalCollection,
33
+ options: { root?: string | undefined, linkPrefix?: string | undefined } = {},
34
+ ): ContentCollectionDescriptor {
35
+ const meta = col[COLLECTION_META_KEY]?.(options.root)
36
+ const dir = meta !== undefined ? meta.dir : (col[COLLECTION_DIR_FOR_ROOT_KEY]?.(options.root) ?? col.dir)
37
+ const name = meta?.name ?? col.name ?? (dir !== undefined ? (basename(dir) || 'collection') : 'collection')
38
+ const localized = meta?.localized ?? false
39
+ const defaultLocale = meta?.defaultLocale ?? 'en'
40
+ const locales = meta?.locales
41
+ const schema = meta?.schema
42
+
43
+ return {
44
+ name,
45
+ ...(options.linkPrefix !== undefined ? { linkPrefix: options.linkPrefix } : {}),
46
+ ...(dir !== undefined ? { dir } : {}),
47
+ localized,
48
+ defaultLocale,
49
+ ...(locales !== undefined ? { locales } : {}),
50
+ ...(schema !== undefined ? { schema } : {}),
51
+ all(locale?: string): readonly ContentCollectionEntrySummary[] | Promise<readonly ContentCollectionEntrySummary[]> {
52
+ const res = col.all(locale)
53
+ if (res instanceof Promise)
54
+ return res.then(list => list.map(toEntrySummary))
55
+ return res.map(toEntrySummary)
56
+ },
57
+ get(slug: string, locale?: string): ContentCollectionEntrySummary | undefined | Promise<ContentCollectionEntrySummary | undefined> {
58
+ const res = col.get(slug, locale)
59
+ if (res instanceof Promise)
60
+ return res.then(entry => (entry !== undefined ? toEntrySummary(entry) : undefined))
61
+ return res !== undefined ? toEntrySummary(res) : undefined
62
+ },
63
+ clearCache() {
64
+ col.clearCache()
65
+ },
66
+ }
67
+ }
68
+
69
+ export function createCollectionsService(
70
+ getActive: (root?: string) => InternalCollection[],
71
+ linkPrefixFor: (col: InternalCollection) => string | undefined,
72
+ ): ContentCollectionsService {
73
+ const mapAll = (root?: string): ContentCollectionDescriptor[] =>
74
+ getActive(root).map(col => toCollectionDescriptor(col, { root, linkPrefix: linkPrefixFor(col) }))
75
+
76
+ return {
77
+ list(root?: string) {
78
+ return mapAll(root)
79
+ },
80
+ async discover(root: string) {
81
+ await discoverAppCollections(root)
82
+ return mapAll(root)
83
+ },
84
+ accessedEntries(ctx) {
85
+ return getAccessedEntries(ctx)
86
+ },
87
+ }
88
+ }
@@ -0,0 +1,80 @@
1
+ // Dev-only per-request entry tracking and zero-impact HTML comment anchors for @prunellejs/cms in-page editing.
2
+
3
+ import type { AccessedContentEntry } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import { currentRequest, devFromEnv } from 'prunelle/internal/server'
6
+ import { currentApp } from './app'
7
+
8
+ const MAX_TRACKED_ENTRIES = 50
9
+
10
+ interface RequestEntryBucket {
11
+ readonly primary: Map<string, AccessedContentEntry>
12
+ readonly secondary: Map<string, AccessedContentEntry>
13
+ }
14
+
15
+ const ACCESSED_STORAGE_KEY = Symbol.for('pru.content.accessedByRequest')
16
+ // Shared across bundled server routes and the host plugin instance; WeakMap releases entries once the request ends.
17
+ const accessedByRequest: WeakMap<RequestContext, RequestEntryBucket> = ((globalThis as Record<symbol, WeakMap<RequestContext, RequestEntryBucket> | undefined>)[ACCESSED_STORAGE_KEY] ??= new WeakMap())
18
+
19
+ function entryKey(entry: AccessedContentEntry): string {
20
+ return `${entry.collection}\0${entry.locale ?? ''}\0${entry.slug}`
21
+ }
22
+
23
+ function encodeCmsAnchorPart(value: string): string {
24
+ // Encode `-` as `%2D` so `--` can never appear inside an HTML5 comment node.
25
+ return encodeURIComponent(value).replaceAll('-', '%2D')
26
+ }
27
+
28
+ function isDevActive(): boolean {
29
+ return currentApp.dev() ?? devFromEnv()
30
+ }
31
+
32
+ /** Records a file-backed entry read during the active dev request (`primary: true` for `.get()`, `false` for `.all()`). */
33
+ export function recordAccessedEntry(entry: AccessedContentEntry, primary: boolean): void {
34
+ if (!isDevActive())
35
+ return
36
+ const reqCtx = currentRequest()?.ctx
37
+ if (reqCtx === undefined)
38
+ return
39
+ let bucket = accessedByRequest.get(reqCtx)
40
+ if (bucket === undefined) {
41
+ bucket = { primary: new Map(), secondary: new Map() }
42
+ accessedByRequest.set(reqCtx, bucket)
43
+ }
44
+ const key = entryKey(entry)
45
+ if (primary) {
46
+ bucket.secondary.delete(key)
47
+ if (!bucket.primary.has(key) && bucket.primary.size < MAX_TRACKED_ENTRIES)
48
+ bucket.primary.set(key, entry)
49
+ }
50
+ else if (!bucket.primary.has(key) && !bucket.secondary.has(key) && bucket.secondary.size < MAX_TRACKED_ENTRIES) {
51
+ bucket.secondary.set(key, entry)
52
+ }
53
+ }
54
+
55
+ /** Returns file-backed entries accessed during `ctx`, with direct `.get()` reads ordered before `.all()` reads. */
56
+ export function getAccessedEntries(ctx: RequestContext): readonly AccessedContentEntry[] {
57
+ const bucket = accessedByRequest.get(ctx)
58
+ if (bucket === undefined)
59
+ return []
60
+ return [...bucket.primary.values(), ...bucket.secondary.values()]
61
+ }
62
+
63
+ /** True only when rendering a file-backed entry during an active dev request with `@prunellejs/cms` inline mode enabled. */
64
+ export function shouldWrapCmsBody(collectionName: string | undefined): collectionName is string {
65
+ return collectionName !== undefined
66
+ && isDevActive()
67
+ && currentApp.cmsInline()
68
+ && currentRequest() !== undefined
69
+ }
70
+
71
+ /** Wraps rendered Markdown HTML in zero-impact HTML comment anchors for in-page CMS body editing. */
72
+ export function wrapCmsBodyHtml(
73
+ collection: string,
74
+ slug: string,
75
+ locale: string | undefined,
76
+ html: string,
77
+ ): string {
78
+ const token = `${encodeCmsAnchorPart(collection)}:${encodeCmsAnchorPart(slug)}:${encodeCmsAnchorPart(locale ?? '')}:__body`
79
+ return `<!--pru-cms:${token}-->${html}<!--/pru-cms-->`
80
+ }