@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.
@@ -1,18 +1,33 @@
1
1
  // YAML frontmatter parsing (via Bun.YAML) and source line lookup for diagnostics.
2
2
 
3
+ const CLOSING_LINE_RE = /^---[ \t]*$/
4
+
5
+ // The YAML between the opening `---` line and the first line that is exactly `---` (the empty block included), and where the body starts.
6
+ function splitFrontmatter(normalized: string): { yaml: string, bodyStart: number } | undefined {
7
+ if (!normalized.startsWith('---\n'))
8
+ return undefined
9
+ let lineStart = 4
10
+ while (lineStart <= normalized.length) {
11
+ const newline = normalized.indexOf('\n', lineStart)
12
+ const lineEnd = newline === -1 ? normalized.length : newline
13
+ if (CLOSING_LINE_RE.test(normalized.slice(lineStart, lineEnd)))
14
+ return { yaml: normalized.slice(4, lineStart - 1), bodyStart: lineEnd + 1 }
15
+ if (newline === -1)
16
+ return undefined
17
+ lineStart = newline + 1
18
+ }
19
+ return undefined
20
+ }
21
+
3
22
  /** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
4
23
  export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
5
24
  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)
25
+ const split = splitFrontmatter(normalized)
26
+ if (split === undefined)
11
27
  return { data: {}, body: normalized }
12
28
 
13
- const rawYaml = normalized.slice(4, end)
14
- const restStart = normalized.indexOf('\n', end + 4)
15
- const body = restStart === -1 ? '' : normalized.slice(restStart + 1)
29
+ const rawYaml = split.yaml
30
+ const body = normalized.slice(split.bodyStart)
16
31
 
17
32
  const parsed = rawYaml.trim() === '' ? {} : Bun.YAML.parse(rawYaml)
18
33
  const data = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
@@ -24,17 +39,15 @@ export function parseFrontmatter(source: string): { data: Record<string, unknown
24
39
  /** Finds the 1-based line number of a top-level frontmatter key for `prunelle check` diagnostics. */
25
40
  export function findFrontmatterFieldLine(rawSource: string, fieldPath: string | undefined): number {
26
41
  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)
42
+ const split = splitFrontmatter(normalized)
43
+ if (split === undefined)
31
44
  return 1
32
45
  if (!fieldPath)
33
46
  return 2
34
47
  const topKey = fieldPath.split('.')[0] ?? fieldPath
35
48
  const escaped = topKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
36
49
  const keyRe = new RegExp(`^\\s*${escaped}\\s*:`)
37
- const lines = normalized.slice(4, end).split('\n')
50
+ const lines = split.yaml.split('\n')
38
51
  for (let i = 0; i < lines.length; i++) {
39
52
  if (keyRe.test(lines[i]!))
40
53
  return i + 2
package/src/index.ts CHANGED
@@ -1,36 +1,45 @@
1
- // @prunellejs/content — Zero-dependency Bun-native Markdown collections, nested YAML frontmatter (Bun.YAML),
2
- // Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
1
+ // @prunellejs/content — Zero-dependency Bun-native Markdown collections (file-backed or headless CMS loaders),
2
+ // nested YAML frontmatter (Bun.YAML), Shiki/custom highlight hook, MDX-lite embedded TSX components, localized collections, TOC, and RSS (`0 KB` client JS).
3
3
 
4
4
  import type { PrunellePlugin } from 'prunelle/config'
5
- import type { Collection, InternalCollection } from './collection'
5
+ import type { AnyCollection, InternalCollection } from './types'
6
6
  import type { ContentFeed, RssFeedConfig } from './rss'
7
7
  import { existsSync, readFileSync } from 'node:fs'
8
8
  import { resolve } from 'node:path'
9
- import { definePlugin, isInside } from 'prunelle/config'
9
+ import { CONTENT_COLLECTIONS_SERVICE, definePlugin, isInside } from 'prunelle/config'
10
10
  import { currentApp } from './app'
11
11
  import {
12
12
  COLLECTION_DIR_FOR_ROOT_KEY,
13
13
  COLLECTION_OWNER_ROOT_KEY,
14
14
  COLLECTION_VALIDATE_KEY,
15
- COLLECTION_VERSION_KEY,
15
+
16
16
  DEFINE_COLLECTION_RE,
17
17
  discoverAppCollections,
18
-
19
18
  registeredCollections,
20
19
  walkCollectionDefFiles,
21
20
  } from './collection'
22
- import { etagMatches, renderRss } from './rss'
21
+ import { etagMatches, renderRssAsync } from './rss'
22
+ import { CONTENT_PRERENDER_SERVICE, createCollectionsService } from './service'
23
23
 
24
24
  export { defineCollection } from './collection'
25
25
  export type {
26
+ AnyCollection,
27
+ AsyncCollection,
28
+ BaseCollectionOptions,
26
29
  CodeHighlighter,
27
30
  Collection,
31
+ CollectionLoadContext,
32
+ CollectionLoader,
28
33
  CollectionOptions,
29
34
  CollectionOptionsWithoutSchema,
30
35
  CollectionOptionsWithSchema,
31
36
  CollectionRenderConfig,
32
37
  ContentEntry,
33
38
  ContentHeading,
39
+ LoadedEntryInput,
40
+ LoaderCollectionOptions,
41
+ LoaderCollectionOptionsWithoutSchema,
42
+ LoaderCollectionOptionsWithSchema,
34
43
  MarkdownComponent,
35
44
  MarkdownImageResolver,
36
45
  MarkdownImageResult,
@@ -39,7 +48,7 @@ export type {
39
48
  } from './collection'
40
49
  export { parseFrontmatter } from './frontmatter'
41
50
  export { renderMarkdown } from './markdown'
42
- export { renderRss } from './rss'
51
+ export { renderRss, renderRssAsync } from './rss'
43
52
  export type { ContentFeed, RssFeedConfig } from './rss'
44
53
 
45
54
  const STATIC_COLLECTION_DIR_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(\s*\{[\s\S]*?\bdir\s*:\s*(['"`])([^'"`]+)\1/g
@@ -69,16 +78,29 @@ function discoverStaticCollectionDirs(root: string): string[] {
69
78
  return found
70
79
  }
71
80
 
81
+ function feedFile(feed: ContentFeed): string {
82
+ return (feed.path ?? '/rss.xml').replace(/^\/+/, '')
83
+ }
84
+
72
85
  export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
73
- feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K]> } | undefined
74
- collections?: readonly Collection<unknown>[] | undefined
86
+ feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
87
+ collections?: readonly AnyCollection<unknown>[] | undefined
75
88
  }): PrunellePlugin
76
- export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly Collection<unknown>[] | undefined } = {}): PrunellePlugin {
89
+ export function content(options: { feeds?: readonly ContentFeed[] | undefined, collections?: readonly AnyCollection<unknown>[] | undefined } = {}): PrunellePlugin {
77
90
  const feeds = options.feeds ?? []
78
91
  const extraCollections = options.collections ?? []
92
+ const feedLinkPrefixes = new Map<InternalCollection, string>()
93
+ for (const f of feeds) {
94
+ const col = f.collection as InternalCollection
95
+ if (f.linkPrefix !== undefined && !feedLinkPrefixes.has(col))
96
+ feedLinkPrefixes.set(col, f.linkPrefix)
97
+ }
79
98
 
80
- function dirOf(c: InternalCollection, root?: string): string {
81
- return c[COLLECTION_DIR_FOR_ROOT_KEY]?.(root) ?? c.dir
99
+ function dirOf(c: InternalCollection, root?: string): string | undefined {
100
+ const resolver = c[COLLECTION_DIR_FOR_ROOT_KEY]
101
+ if (resolver !== undefined)
102
+ return resolver(root)
103
+ return c.dir
82
104
  }
83
105
 
84
106
  function activeCollections(root?: string): InternalCollection[] {
@@ -93,6 +115,11 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
93
115
  if (owner !== undefined && absRoot !== undefined && owner !== absRoot)
94
116
  continue
95
117
  const dir = dirOf(c, absRoot)
118
+ if (dir === undefined) {
119
+ if (owner !== undefined || absRoot === undefined)
120
+ out.add(c)
121
+ continue
122
+ }
96
123
  if (!existsSync(dir))
97
124
  continue
98
125
  if (absRoot === undefined || isInside(absRoot, dir, { orSame: true }))
@@ -101,13 +128,21 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
101
128
  return [...out]
102
129
  }
103
130
 
131
+ const collectionsService = createCollectionsService(
132
+ activeCollections,
133
+ col => feedLinkPrefixes.get(col),
134
+ )
135
+
104
136
  return definePlugin({
105
137
  name: '@prunellejs/content',
106
138
  after: ['@prunellejs/i18n', '@prunellejs/images'],
107
139
  watchPaths: (root) => {
108
140
  const dirs = new Set<string>()
109
- for (const c of activeCollections(root))
110
- dirs.add(dirOf(c, root))
141
+ for (const c of activeCollections(root)) {
142
+ const dir = dirOf(c, root)
143
+ if (dir !== undefined)
144
+ dirs.add(dir)
145
+ }
111
146
  for (const dir of discoverStaticCollectionDirs(root))
112
147
  dirs.add(dir)
113
148
  return [...dirs]
@@ -119,12 +154,13 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
119
154
  },
120
155
  async check(ctx) {
121
156
  await discoverAppCollections(ctx.root)
157
+ ctx.provide?.(CONTENT_COLLECTIONS_SERVICE, collectionsService)
122
158
  const seen = new Set<string>()
123
159
  for (const c of activeCollections(ctx.root)) {
124
160
  const validate = c[COLLECTION_VALIDATE_KEY]
125
161
  if (validate === undefined)
126
162
  continue
127
- for (const err of validate(ctx.root)) {
163
+ for (const err of await validate(ctx.root)) {
128
164
  if (seen.has(err))
129
165
  continue
130
166
  seen.add(err)
@@ -132,34 +168,44 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
132
168
  }
133
169
  }
134
170
  },
135
- build(ctx) {
171
+ async build(ctx) {
172
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
173
+ const emittedFeeds: string[] = []
136
174
  for (const feed of feeds) {
137
- const rel = (feed.path ?? '/rss.xml').replace(/^\/+/, '')
138
- ctx.emitPublic(rel, renderRss({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown>))
175
+ const rel = feedFile(feed)
176
+ ctx.emitPublic(rel, await renderRssAsync({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown, AnyCollection<unknown>>))
177
+ // A loader-backed feed changes without a rebuild, so it keeps its runtime route over the built file.
178
+ if (feed.collection.dir !== undefined)
179
+ emittedFeeds.push(rel)
139
180
  }
181
+ ctx.setData({ emittedFeeds })
182
+ },
183
+ afterPrerender(ctx) {
184
+ ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
140
185
  },
141
186
  server(api) {
187
+ api.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
188
+ if (api.config?.prerender === true)
189
+ api.provide(CONTENT_PRERENDER_SERVICE, true)
190
+ const emitted = new Set(api.getBuildData<{ emittedFeeds?: string[] }>()?.emittedFeeds ?? [])
142
191
  for (const feed of feeds) {
143
192
  const path = feed.path ?? '/rss.xml'
144
- let memo: { xml: string, etag: string, version: number } | undefined
145
- api.route('GET', path, (ctx) => {
146
- const versionFn = (feed.collection as unknown as Record<symbol, (() => number) | undefined>)[COLLECTION_VERSION_KEY]
147
- const version = versionFn ? versionFn() : -1
148
- if (api.dev || memo === undefined || memo.version !== version) {
149
- const xml = renderRss({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown>)
150
- const etag = `"${Bun.hash(xml).toString(36)}"`
151
- memo = { xml, etag, version }
152
- }
153
- if (etagMatches(ctx.request.headers.get('if-none-match'), memo.etag)) {
193
+ // Plugin routes shadow public files: a production server serves the file the build already wrote.
194
+ if (!api.dev && emitted.has(feedFile(feed)))
195
+ continue
196
+ api.route('GET', path, async (ctx) => {
197
+ const xml = await renderRssAsync({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown, AnyCollection<unknown>>)
198
+ const current = { xml, etag: `"${Bun.hash(xml).toString(36)}"` }
199
+ if (etagMatches(ctx.request.headers.get('if-none-match'), current.etag)) {
154
200
  return new Response(null, {
155
201
  status: 304,
156
- headers: { etag: memo.etag },
202
+ headers: { etag: current.etag },
157
203
  })
158
204
  }
159
- return new Response(memo.xml, {
205
+ return new Response(current.xml, {
160
206
  headers: {
161
207
  'content-type': 'application/rss+xml; charset=utf-8',
162
- 'etag': memo.etag,
208
+ 'etag': current.etag,
163
209
  },
164
210
  })
165
211
  })
@@ -0,0 +1,333 @@
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
+ } from './types'
32
+
33
+ function cleanSlug(rawSlug: unknown, collectionName: string): string {
34
+ if (typeof rawSlug !== 'string' || rawSlug.trim() === '')
35
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" is missing a non-empty string "slug".`)
36
+ const cleaned = rawSlug.trim().replace(/^\/+|\/+$/g, '')
37
+ if (cleaned === '')
38
+ throw new Error(`@prunellejs/content: entry in collection "${collectionName}" has an empty "slug".`)
39
+ return cleaned
40
+ }
41
+
42
+ function getOrCreateLocaleMap<K extends object, T>(
43
+ store: WeakMap<K, Map<string, Promise<ContentEntry<T>[]>>>,
44
+ key: K,
45
+ ): Map<string, Promise<ContentEntry<T>[]>> {
46
+ let map = store.get(key)
47
+ if (map === undefined) {
48
+ map = new Map()
49
+ store.set(key, map)
50
+ }
51
+ return map
52
+ }
53
+
54
+ function formatCheckPrefix(root: string, sourceFile: string | undefined): string {
55
+ if (sourceFile === undefined)
56
+ return ''
57
+ const rel = relative(root, sourceFile).replace(/\\/g, '/')
58
+ return `${rel}:1:1: error: `
59
+ }
60
+
61
+ async function validateLoadedEntriesForCheck(params: {
62
+ name: string
63
+ root: string
64
+ sourceFile: string | undefined
65
+ localized: boolean
66
+ defaultLocale: string
67
+ locales: readonly string[] | undefined
68
+ schema: StandardSchemaV1 | undefined
69
+ load: (ctx: { locale?: string | undefined }) => Promise<LoadedEntryInput[]>
70
+ }): Promise<string[]> {
71
+ const { name, root, sourceFile, localized, defaultLocale, locales, schema, load } = params
72
+ const prefix = formatCheckPrefix(root, sourceFile)
73
+ const errors: string[] = []
74
+ const seenEntries = new Set<string>()
75
+
76
+ const configuredLocales = localized ? (locales ?? currentApp.locales()) : undefined
77
+ const runs: Array<{ locale: string | undefined, filterByLocale: boolean }> = !localized
78
+ ? [{ locale: undefined, filterByLocale: false }]
79
+ : configuredLocales !== undefined && configuredLocales.length > 0
80
+ ? [...new Set(configuredLocales)].map(locale => ({ locale, filterByLocale: true }))
81
+ : [{ locale: defaultLocale, filterByLocale: false }]
82
+
83
+ for (const run of runs) {
84
+ let rawEntries: LoadedEntryInput[]
85
+ try {
86
+ rawEntries = await load(localized ? { locale: run.locale } : {})
87
+ }
88
+ catch (err) {
89
+ const msg = err instanceof Error ? err.message : String(err)
90
+ const locNote = run.locale !== undefined ? ` (locale "${run.locale}")` : ''
91
+ errors.push(`${prefix}@prunellejs/content: collection "${name}"${locNote} loader failed: ${msg}`)
92
+ continue
93
+ }
94
+
95
+ for (const raw of rawEntries) {
96
+ if (run.filterByLocale && raw.locale !== undefined && raw.locale !== run.locale)
97
+ continue
98
+ if (typeof raw.slug !== 'string' || raw.slug.trim() === '') {
99
+ errors.push(`${prefix}@prunellejs/content: collection "${name}": entry is missing a non-empty string "slug"`)
100
+ continue
101
+ }
102
+ const slug = raw.slug.trim().replace(/^\/+|\/+$/g, '')
103
+ const entryLocale = localized ? (raw.locale ?? run.locale) : raw.locale
104
+ const dedupeKey = `${entryLocale ?? ''}\0${slug}`
105
+ if (seenEntries.has(dedupeKey))
106
+ continue
107
+ seenEntries.add(dedupeKey)
108
+
109
+ if (schema === undefined)
110
+ continue
111
+ const checked = await validateSchema(schema, raw.data)
112
+ if (!checked.ok) {
113
+ const locSuffix = entryLocale !== undefined ? ` (${entryLocale})` : ''
114
+ for (const issue of checked.issues) {
115
+ const path = formatIssuePath(issue)
116
+ errors.push(`${prefix}@prunellejs/content: collection "${name}" entry "${slug}"${locSuffix}: ${path ? `${path}: ` : ''}${issue.message}`)
117
+ }
118
+ }
119
+ }
120
+ }
121
+ return errors
122
+ }
123
+
124
+ const DEFAULT_TIMEOUT_MS = 30_000
125
+
126
+ function checkDurations(name: string, { ttlMs, timeoutMs }: { ttlMs?: number | undefined, timeoutMs?: number | undefined }): void {
127
+ if (ttlMs !== undefined && !(ttlMs >= 0))
128
+ throw new Error(`@prunellejs/content: collection "${name}" has ttlMs ${ttlMs}: give 0 or a positive number of milliseconds.`)
129
+ if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0))
130
+ throw new Error(`@prunellejs/content: collection "${name}" has timeoutMs ${timeoutMs}: give a positive number of milliseconds.`)
131
+ }
132
+
133
+ interface SharedLoad<TData> {
134
+ pending: Promise<ContentEntry<TData>[]>
135
+ // When the load finished, once it did: from then on it is reused for ttlMs.
136
+ doneAt?: number
137
+ }
138
+
139
+ // Runs a collection's loader with a signal, and fails when the signal aborts even if the loader ignores it.
140
+ function createLoadRunner(name: string, timeoutMs: number, load: LoaderCollectionOptions<unknown>['load']) {
141
+ const running = new Set<AbortController>()
142
+ async function run(ctx: { locale?: string | undefined }): Promise<LoadedEntryInput[]> {
143
+ const controller = new AbortController()
144
+ running.add(controller)
145
+ const timer = setTimeout(() => controller.abort(new Error(`@prunellejs/content: collection "${name}" loader took over ${timeoutMs} ms: raise timeoutMs, or make the source answer sooner.`)), timeoutMs)
146
+ try {
147
+ return await new Promise<LoadedEntryInput[]>((resolve, reject) => {
148
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true })
149
+ Promise.resolve(load({ ...ctx, signal: controller.signal })).then(resolve, reject)
150
+ })
151
+ }
152
+ finally {
153
+ clearTimeout(timer)
154
+ running.delete(controller)
155
+ }
156
+ }
157
+ function cancelAll(): void {
158
+ for (const controller of running)
159
+ controller.abort(new Error(`@prunellejs/content: collection "${name}" load was cancelled: its cache was cleared.`))
160
+ }
161
+ return { run, cancelAll }
162
+ }
163
+
164
+ // At runtime, per locale, the load every request shares while it runs and for ttlMs after.
165
+ function createSharedLoads<TData>(ttlMs: number) {
166
+ let shared = new Map<string, SharedLoad<TData>>()
167
+ function get(key: string, start: () => Promise<ContentEntry<TData>[]>): Promise<ContentEntry<TData>[]> {
168
+ const hit = shared.get(key)
169
+ if (hit !== undefined && (hit.doneAt === undefined || Date.now() - hit.doneAt < ttlMs))
170
+ return hit.pending
171
+ // A load cleared while it ran forgets itself from its own map, never from the one that replaced it.
172
+ const map = shared
173
+ const load: SharedLoad<TData> = { pending: start() }
174
+ const forget = (): void => {
175
+ map.delete(key)
176
+ }
177
+ map.set(key, load)
178
+ load.pending.then(() => {
179
+ if (ttlMs > 0)
180
+ load.doneAt = Date.now()
181
+ else
182
+ forget()
183
+ }, forget)
184
+ return load.pending
185
+ }
186
+ return { get, clear: () => { shared = new Map() } }
187
+ }
188
+
189
+ export function createLoaderCollection<TData = Record<string, unknown>>(
190
+ options: LoaderCollectionOptions<TData>,
191
+ ): AsyncCollection<TData> {
192
+ const name = options.name ?? 'collection'
193
+ checkDurations(name, options)
194
+ const ttlMs = options.ttlMs ?? 0
195
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
196
+ const localized = options.localized ?? false
197
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
198
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
199
+ const renderLoader = createRenderConfigLoader(name, options)
200
+ const sourceFile = currentDiscoverFile()
201
+
202
+ let buildCache = new WeakMap<AppRuntimeContext, Map<string, Promise<ContentEntry<TData>[]>>>()
203
+ let requestCache = new WeakMap<RequestContext, Map<string, Promise<ContentEntry<TData>[]>>>()
204
+ let lastBuildCtx: WeakRef<AppRuntimeContext> | undefined
205
+ const runner = createLoadRunner(name, timeoutMs, options.load)
206
+ const shared = createSharedLoads<TData>(ttlMs)
207
+
208
+ // The cache of the build, or of the request (`runtime`), the current code runs in.
209
+ function resolveCacheMap(): { bucket: Map<string, Promise<ContentEntry<TData>[]>>, runtime: boolean } | undefined {
210
+ const reqCtx = currentRequest()?.ctx
211
+ const appCtx = getAppContext()
212
+ if (reqCtx === undefined && appCtx !== undefined) {
213
+ lastBuildCtx = new WeakRef(appCtx)
214
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
215
+ }
216
+ if (reqCtx !== undefined) {
217
+ const buildCtx = lastBuildCtx?.deref()
218
+ if (
219
+ buildCtx !== undefined
220
+ && appCtx !== undefined
221
+ && appCtx.root === buildCtx.root
222
+ && appCtx.outDir === buildCtx.outDir
223
+ )
224
+ return { bucket: getOrCreateLocaleMap(buildCache, buildCtx), runtime: false }
225
+ if (appCtx?.inject(CONTENT_PRERENDER_SERVICE) === true)
226
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
227
+ return { bucket: getOrCreateLocaleMap(requestCache, reqCtx), runtime: true }
228
+ }
229
+ return undefined
230
+ }
231
+
232
+
233
+ async function loadValidatedEntries(targetLocale: string | undefined): Promise<ContentEntry<TData>[]> {
234
+ const rawEntries = await runner.run(localized ? { locale: targetLocale } : {})
235
+ const entries: ContentEntry<TData>[] = []
236
+ for (const raw of rawEntries) {
237
+ if (localized && raw.locale !== undefined && raw.locale !== targetLocale)
238
+ continue
239
+ const slug = cleanSlug(raw.slug, name)
240
+ let data: TData
241
+ if (options.schema !== undefined) {
242
+ const checked = await validateSchema(options.schema, raw.data)
243
+ if (!checked.ok) {
244
+ throw new Error(
245
+ `@prunellejs/content: invalid entry "${slug}" in collection "${name}": ${formatSchemaIssues(checked.issues)}`,
246
+ )
247
+ }
248
+ data = checked.value
249
+ }
250
+ else {
251
+ data = (raw.data !== null && typeof raw.data === 'object' ? raw.data : {}) as TData
252
+ }
253
+ const entryLocale = localized ? (raw.locale ?? targetLocale) : raw.locale
254
+ const file = raw.id ?? `${name}:${slug}`
255
+ entries.push(buildContentEntry({
256
+ slug,
257
+ locale: entryLocale,
258
+ file,
259
+ data,
260
+ body: raw.body ?? '',
261
+ renderLoader,
262
+ }))
263
+ }
264
+ entries.sort(options.sort ?? defaultSort)
265
+ return entries
266
+ }
267
+
268
+ function loadCached(locale?: string): Promise<ContentEntry<TData>[]> {
269
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
270
+ const cacheKey = targetLocale ?? ''
271
+ const scope = resolveCacheMap()
272
+ if (scope === undefined)
273
+ return loadValidatedEntries(targetLocale)
274
+ const { bucket, runtime } = scope
275
+ const hit = bucket.get(cacheKey)
276
+ if (hit !== undefined)
277
+ return hit
278
+ const pending = (runtime ? shared.get(cacheKey, () => loadValidatedEntries(targetLocale)) : loadValidatedEntries(targetLocale)).catch((err) => {
279
+ bucket.delete(cacheKey)
280
+ throw err
281
+ })
282
+ bucket.set(cacheKey, pending)
283
+ return pending
284
+ }
285
+
286
+ async function all(locale?: string): Promise<ContentEntry<TData>[]> {
287
+ const entries = await loadCached(locale)
288
+ return allowsDrafts() ? entries.slice() : entries.filter(e => !isDraft(e.data))
289
+ }
290
+
291
+ async function get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined> {
292
+ const clean = slug.replace(/^\/+|\/+$/g, '')
293
+ const entries = await all(locale)
294
+ return entries.find(e => e.slug === clean)
295
+ }
296
+
297
+ const col: AsyncCollection<TData> & InternalCollection = {
298
+ name,
299
+ all,
300
+ get,
301
+ byTag: async (tag, locale) => filterByTag(await all(locale), tag),
302
+ paths: async (prefix = '', locale) => formatPaths(await all(locale), prefix),
303
+ clearCache() {
304
+ buildCache = new WeakMap()
305
+ requestCache = new WeakMap()
306
+ lastBuildCtx = undefined
307
+ shared.clear()
308
+ runner.cancelAll()
309
+ },
310
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateLoadedEntriesForCheck({
311
+ name,
312
+ root,
313
+ sourceFile,
314
+ localized,
315
+ defaultLocale: getDefaultLocale(),
316
+ locales: options.locales,
317
+ schema: options.schema,
318
+ load: runner.run,
319
+ }),
320
+ [COLLECTION_DIR_FOR_ROOT_KEY]: () => undefined,
321
+ [COLLECTION_META_KEY]: () => ({
322
+ name,
323
+ localized,
324
+ defaultLocale: getDefaultLocale(),
325
+ locales: options.locales ?? (localized ? currentApp.locales() : undefined),
326
+ schema: options.schema,
327
+ isAsync: true,
328
+ }),
329
+ }
330
+
331
+ registerLoadedCollection(col, options.name, localized)
332
+ return col
333
+ }