@prunellejs/content 0.1.1 → 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.
package/src/markdown.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // renderMarkdown: Bun's native Markdown renderer plus highlight hook, embedded components, heading ids and TOC.
2
2
 
3
3
  import type { ContentHeading, MarkdownImageResolver, MarkdownImageResult, RenderMarkdownOptions } from './index'
4
+ import { sanitizeMarkdownHtml } from 'prunelle/internal/server'
4
5
  import { escAttr } from 'prunelle/server'
5
6
  import { currentApp } from './app'
6
7
  import { expandComponents } from './components'
7
- import { sanitizeMarkdownHtml } from './sanitize'
8
8
 
9
9
  function slugifyHeading(text: string): string {
10
10
  return text
@@ -33,7 +33,9 @@ function findDefaultImageResolver(file: string | undefined): MarkdownImageResolv
33
33
  return currentApp.imageResolver()
34
34
  }
35
35
 
36
- const FENCE_RE = /^([`~]{3,})([^\n]*)\n([\s\S]*?)^\1[ \t]*$/gm
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?$/
37
39
  let slotBatchId = 0
38
40
 
39
41
  function renderMarkdownInternal(
@@ -55,7 +57,7 @@ function renderMarkdownInternal(
55
57
 
56
58
  // 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
57
59
  if (options.highlight !== undefined || options.components !== undefined) {
58
- processed = processed.replace(FENCE_RE, (full, _fence: string, info: string, code: string) => {
60
+ processed = replaceFences(processed, (full, info, code) => {
59
61
  if (options.highlight !== undefined) {
60
62
  const lang = info.trim().split(/\s+/)[0] || undefined
61
63
  const idx = slots.length
@@ -64,7 +66,10 @@ function renderMarkdownInternal(
64
66
  }
65
67
  // Protect code fences from component expansion when only components are configured
66
68
  const idx = slots.length
67
- slots.push(Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true }))
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)
68
73
  return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
69
74
  })
70
75
  }
@@ -116,7 +121,10 @@ function renderMarkdownInternal(
116
121
  ? undefined
117
122
  : (options.resolveImage ?? findDefaultImageResolver(options.file))
118
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
119
126
  html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
127
+ const first = seen++ === 0
120
128
  const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
121
129
  if (!srcMatch)
122
130
  return full
@@ -135,7 +143,7 @@ function renderMarkdownInternal(
135
143
  parts.push(`width="${info.width}"`)
136
144
  if (info.height !== undefined && info.height > 0)
137
145
  parts.push(`height="${info.height}"`)
138
- parts.push(`loading="${info.loading ?? 'lazy'}"`, 'decoding="async"')
146
+ parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
139
147
  const imgTag = `<img ${parts.join(' ')}>`
140
148
  if (info.avifSrcset) {
141
149
  const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
@@ -169,3 +177,42 @@ export function renderMarkdown(body: string, options: RenderMarkdownOptions = {}
169
177
  } {
170
178
  return renderMarkdownInternal(body, options)
171
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 CHANGED
@@ -1,17 +1,20 @@
1
1
  // RSS 2.0 XML feed generation and ETag matching for @prunellejs/content.
2
2
 
3
- import type { Collection, ContentEntry } from './collection'
4
- import { escAttr } from 'prunelle/server'
3
+ import type { AnyCollection, Collection, ContentEntry } from './types'
4
+ import { escXml } from 'prunelle/server'
5
5
  import { currentApp } from './app'
6
6
 
7
- export interface RssFeedConfig<TData = Record<string, unknown>> {
7
+ export interface RssFeedConfig<
8
+ TData = Record<string, unknown>,
9
+ TCol extends AnyCollection<TData> = Collection<TData>,
10
+ > {
8
11
  /** Public path for the RSS XML file (default: '/rss.xml'). */
9
12
  path?: string | undefined
10
13
  title: string
11
14
  description: string
12
15
  /** Public site origin; defaults to `PrunelleConfig.site` when registered via `content()`. */
13
16
  site?: string | undefined
14
- collection: Collection<TData>
17
+ collection: TCol
15
18
  locale?: string | undefined
16
19
  /** URL prefix prepended to each entry's slug (e.g. '/blog'). */
17
20
  linkPrefix?: string | undefined
@@ -28,7 +31,7 @@ export interface ContentFeed {
28
31
  readonly title: string
29
32
  readonly description: string
30
33
  readonly site?: string | undefined
31
- readonly collection: Collection<unknown>
34
+ readonly collection: AnyCollection<unknown>
32
35
  readonly locale?: string | undefined
33
36
  readonly linkPrefix?: string | undefined
34
37
  readonly mapItem?: ((entry: ContentEntry<never>) => {
@@ -46,34 +49,51 @@ function formatPubDate(value: string | Date | undefined): string {
46
49
  return Number.isNaN(date.getTime()) ? '' : `<pubDate>${date.toUTCString()}</pubDate>`
47
50
  }
48
51
 
49
- export function renderRss<TData>(feed: RssFeedConfig<TData>): string {
52
+ function buildRssXml<TData>(
53
+ feed: Pick<RssFeedConfig<TData, AnyCollection<TData>>, 'title' | 'description' | 'site' | 'linkPrefix' | 'mapItem'>,
54
+ entries: readonly ContentEntry<TData>[],
55
+ ): string {
50
56
  const site = (feed.site ?? currentApp.site() ?? '').replace(/\/$/, '')
51
57
  const prefix = (feed.linkPrefix ?? '').replace(/\/$/, '')
52
- const items = feed.collection.all(feed.locale).map((entry) => {
53
- const rawData = entry.data as Record<string, unknown>
54
- const mapped = feed.mapItem
55
- ? feed.mapItem(entry)
56
- : {
57
- title: String(rawData.title ?? entry.slug),
58
- description: typeof rawData.description === 'string' ? rawData.description : undefined,
59
- date: rawData.date as string | Date | undefined,
60
- link: `${site}${prefix}/${entry.slug}`,
61
- }
62
- const link = mapped.link ?? `${site}${prefix}/${entry.slug}`
63
- const pubDate = formatPubDate(mapped.date)
64
- const desc = mapped.description ? `<description>${escAttr(mapped.description)}</description>` : ''
65
- return `<item><title>${escAttr(mapped.title)}</title><link>${escAttr(link)}</link><guid>${escAttr(link)}</guid>${pubDate}${desc}</item>`
66
- }).join('')
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('')
67
75
 
68
76
  return `<?xml version="1.0" encoding="UTF-8"?>`
69
77
  + `<rss version="2.0"><channel>`
70
- + `<title>${escAttr(feed.title)}</title>`
71
- + `<link>${escAttr(site)}</link>`
72
- + `<description>${escAttr(feed.description)}</description>`
78
+ + `<title>${escXml(feed.title)}</title>`
79
+ + `<link>${escXml(site)}</link>`
80
+ + `<description>${escXml(feed.description)}</description>`
73
81
  + items
74
82
  + `</channel></rss>`
75
83
  }
76
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
+
77
97
  export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
78
98
  if (!ifNoneMatch)
79
99
  return false
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
+ }