@prunellejs/content 0.1.1 → 0.7.0

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/components.ts CHANGED
@@ -256,8 +256,14 @@ function parseLiteralValue(src: string): unknown {
256
256
  return value
257
257
  }
258
258
 
259
+ // Prop names that would reach the prototype chain are dropped, however the value is written.
260
+ function setProp(props: Record<string, unknown>, name: string, value: unknown): void {
261
+ if (name !== '__proto__' && name !== 'constructor' && name !== 'prototype')
262
+ props[name] = value
263
+ }
264
+
259
265
  // Parse JSX-style attributes inside embedded Markdown components: title="hi" count={42} rows={[...]} flag
260
- function parseComponentProps(attrSrc: string): Record<string, unknown> {
266
+ function parseComponentProps(attrSrc: string, tag: string, file: string | undefined): Record<string, unknown> {
261
267
  const props: Record<string, unknown> = {}
262
268
  let i = 0
263
269
  const len = attrSrc.length
@@ -276,7 +282,7 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
276
282
 
277
283
  while (i < len && /\s/.test(attrSrc[i]!)) i++
278
284
  if (attrSrc[i] !== '=') {
279
- props[name] = true
285
+ setProp(props, name, true)
280
286
  continue
281
287
  }
282
288
  i++ // skip '='
@@ -286,13 +292,21 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
286
292
  if (ch === '"' || ch === '\'') {
287
293
  const quote = ch
288
294
  i++
289
- const valStart = i
295
+ let val = ''
290
296
  while (i < len && attrSrc[i] !== quote) {
291
- if (attrSrc[i] === '\\') i++
297
+ if (attrSrc[i] === '\\' && i + 1 < len) {
298
+ const next = attrSrc[i + 1]!
299
+ if (next === quote || next === '\\') {
300
+ val += next
301
+ i += 2
302
+ continue
303
+ }
304
+ }
305
+ val += attrSrc[i]!
292
306
  i++
293
307
  }
294
- props[name] = attrSrc.slice(valStart, i)
295
- i++
308
+ setProp(props, name, val)
309
+ if (i < len) i++
296
310
  }
297
311
  else if (ch === '{') {
298
312
  let depth = 0
@@ -317,25 +331,51 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
317
331
  const expr = attrSrc.slice(exprStart, i).trim()
318
332
  i++ // skip closing '}'
319
333
  try {
320
- props[name] = parseLiteralValue(expr)
334
+ setProp(props, name, parseLiteralValue(expr))
321
335
  }
322
336
  catch {
323
- // Reject/ignore arbitrary non-literal JS expressions
337
+ throw new Error(`@prunellejs/content: the prop "${name}" of <${tag}> in "${file ?? 'the markdown source'}" is not a literal (${expr}): write a string, number, boolean, array or object literal, or compute the value inside the component.`)
324
338
  }
325
339
  }
326
340
  }
327
341
  return props
328
342
  }
329
343
 
344
+ // What one expansion pass has learnt about the source, so no scan is run twice over the same ground.
345
+ export interface ScanMemo {
346
+ // Offsets a failed tag-end scan crossed outside any string or brace: a scan reaching one fails the same way.
347
+ failedAt?: Uint8Array
348
+ // Per tag name, the offset of the matching close tag (-1 for none), keyed by the end of the opening tag.
349
+ closes: Map<string, Map<number, number>>
350
+ }
351
+
352
+ export function createScanMemo(): ScanMemo {
353
+ return { closes: new Map() }
354
+ }
355
+
356
+ const MAX_BRACE_DEPTH = 32
357
+
330
358
  // Find the end of an opening JSX tag (`>` or `/>`), respecting strings and balanced `{...}` expressions.
331
- function findTagEnd(src: string, start: number): { end: number, selfClosing: boolean } | undefined {
359
+ function findTagEnd(src: string, start: number, memo: ScanMemo): { end: number, selfClosing: boolean } | undefined {
332
360
  let i = start
333
361
  const len = src.length
334
362
  let braceDepth = 0
335
363
  let inStr: string | null = null
364
+ const crossed: number[] = []
365
+ const fail = (): undefined => {
366
+ const failedAt = memo.failedAt ??= new Uint8Array(len)
367
+ for (const at of crossed)
368
+ failedAt[at] = 1
369
+ return undefined
370
+ }
336
371
 
337
372
  while (i < len) {
338
373
  const c = src[i]!
374
+ if (inStr === null && braceDepth === 0) {
375
+ if (memo.failedAt?.[i] === 1)
376
+ return fail()
377
+ crossed.push(i)
378
+ }
339
379
  if (inStr !== null) {
340
380
  if (c === '\\') { i += 2; continue }
341
381
  if (c === inStr) inStr = null
@@ -348,7 +388,8 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
348
388
  continue
349
389
  }
350
390
  if (c === '{') {
351
- braceDepth++
391
+ if (++braceDepth > MAX_BRACE_DEPTH)
392
+ return fail()
352
393
  i++
353
394
  continue
354
395
  }
@@ -365,7 +406,7 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
365
406
  }
366
407
  i++
367
408
  }
368
- return undefined
409
+ return fail()
369
410
  }
370
411
 
371
412
  // Returns true when the character at `idx` is escaped by an odd number of preceding backslashes.
@@ -398,10 +439,17 @@ function matchInlineCodeSpan(src: string, start: number): number {
398
439
  return -1
399
440
  }
400
441
 
401
- function findMatchingCloseTag(md: string, tagName: string, start: number): number {
442
+ // One pass pairs every opening tag it meets with its close, so the next unclosed tag of the same name is answered from the memo.
443
+ function findMatchingCloseTag(md: string, tagName: string, start: number, memo: ScanMemo): number {
444
+ let closes = memo.closes.get(tagName)
445
+ const known = closes?.get(start)
446
+ if (known !== undefined)
447
+ return known
448
+ closes ??= new Map()
449
+ memo.closes.set(tagName, closes)
402
450
  const closeTag = `</${tagName}>`
403
451
  const len = md.length
404
- let depth = 1
452
+ const open = [start]
405
453
  let pos = start
406
454
  while (pos < len) {
407
455
  const ch = md[pos]!
@@ -416,17 +464,17 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
416
464
  }
417
465
  if (ch === '<') {
418
466
  if (md.startsWith(closeTag, pos)) {
419
- depth--
420
- if (depth === 0)
467
+ closes.set(open.pop()!, pos)
468
+ if (open.length === 0)
421
469
  return pos
422
470
  pos += closeTag.length
423
471
  continue
424
472
  }
425
473
  if (md.startsWith(`<${tagName}`, pos) && /[\s/>]/.test(md[pos + 1 + tagName.length] ?? '')) {
426
- const innerEnd = findTagEnd(md, pos + 1 + tagName.length)
474
+ const innerEnd = findTagEnd(md, pos + 1 + tagName.length, memo)
427
475
  if (innerEnd !== undefined) {
428
476
  if (!innerEnd.selfClosing)
429
- depth++
477
+ open.push(innerEnd.end)
430
478
  pos = innerEnd.end
431
479
  continue
432
480
  }
@@ -434,6 +482,8 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
434
482
  }
435
483
  pos++
436
484
  }
485
+ for (const unclosed of open)
486
+ closes.set(unclosed, -1)
437
487
  return -1
438
488
  }
439
489
 
@@ -448,6 +498,7 @@ export function expandComponents(
448
498
  const names = Object.keys(components)
449
499
  if (names.length === 0)
450
500
  return md
501
+ const memo = createScanMemo()
451
502
 
452
503
  let out = ''
453
504
  let i = 0
@@ -480,14 +531,16 @@ export function expandComponents(
480
531
  }
481
532
 
482
533
  const match = /^<([A-Z][\w]*)(?=[\s/>])/.exec(md.slice(lt))
483
- if (!match || !(match[1]! in components)) {
534
+ if (match && !Object.hasOwn(components, match[1]!))
535
+ throw new Error(`@prunellejs/content: unknown component <${match[1]}> in "${options.file ?? 'the markdown source'}": registered components are ${names.join(', ')}; register it in the \`components\` option, or wrap the text in backticks if it is not a component.`)
536
+ if (!match) {
484
537
  out += md.slice(i, lt + 1)
485
538
  i = lt + 1
486
539
  continue
487
540
  }
488
541
 
489
542
  const tagName = match[1]!
490
- const tagEnd = findTagEnd(md, lt + match[0].length)
543
+ const tagEnd = findTagEnd(md, lt + match[0].length, memo)
491
544
  if (!tagEnd) {
492
545
  out += md.slice(i, lt + 1)
493
546
  i = lt + 1
@@ -496,12 +549,12 @@ export function expandComponents(
496
549
 
497
550
  out += md.slice(i, lt)
498
551
  const attrSrc = md.slice(lt + match[0].length, tagEnd.selfClosing ? tagEnd.end - 2 : tagEnd.end - 1)
499
- const props = parseComponentProps(attrSrc)
552
+ const props = parseComponentProps(attrSrc, tagName, options.file)
500
553
  let afterIndex = tagEnd.end
501
554
 
502
555
  if (!tagEnd.selfClosing) {
503
556
  const closeTag = `</${tagName}>`
504
- const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end)
557
+ const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end, memo)
505
558
  if (closeIdx !== -1) {
506
559
  const innerMd = md.slice(tagEnd.end, closeIdx).trim()
507
560
  const innerRendered = renderMarkdown(innerMd, options)
package/src/entry.ts ADDED
@@ -0,0 +1,171 @@
1
+ // Shared entry construction, lazy Markdown render-config resolution, sorting, and filtering helpers.
2
+
3
+ import type {
4
+ BaseCollectionOptions,
5
+ CollectionRenderConfig,
6
+ ContentEntry,
7
+ RenderedMarkdown,
8
+ RenderMarkdownOptions,
9
+ } from './types'
10
+ import { devFromEnv } from 'prunelle/internal/server'
11
+ import { currentApp } from './app'
12
+ import { renderMarkdown } from './markdown'
13
+ import { shouldWrapCmsBody, wrapCmsBodyHtml } from './tracking'
14
+
15
+ export interface RenderConfigLoader {
16
+ ensureSync: () => RenderMarkdownOptions
17
+ ensureAsync: () => Promise<RenderMarkdownOptions>
18
+ }
19
+
20
+ export type RenderConfigOptions = Pick<
21
+ BaseCollectionOptions<never>,
22
+ 'highlight' | 'components' | 'headingLinks' | 'resolveImage' | 'trusted' | 'render'
23
+ >
24
+
25
+ export function createRenderConfigLoader(
26
+ label: string,
27
+ options: RenderConfigOptions,
28
+ ): RenderConfigLoader {
29
+ const baseRenderOpts: RenderMarkdownOptions = {
30
+ highlight: options.highlight,
31
+ components: options.components,
32
+ headingLinks: options.headingLinks,
33
+ resolveImage: options.resolveImage,
34
+ trusted: options.trusted,
35
+ }
36
+ let resolvedRenderOpts: RenderMarkdownOptions | undefined = options.render === undefined ? baseRenderOpts : undefined
37
+ let pendingRenderOpts: Promise<RenderMarkdownOptions> | undefined
38
+
39
+ function mergeRenderConfig(cfg: CollectionRenderConfig): RenderMarkdownOptions {
40
+ return {
41
+ highlight: cfg.highlight ?? baseRenderOpts.highlight,
42
+ components: cfg.components ?? baseRenderOpts.components,
43
+ headingLinks: cfg.headingLinks ?? baseRenderOpts.headingLinks,
44
+ resolveImage: cfg.resolveImage !== undefined ? cfg.resolveImage : baseRenderOpts.resolveImage,
45
+ trusted: cfg.trusted !== undefined ? cfg.trusted : baseRenderOpts.trusted,
46
+ }
47
+ }
48
+
49
+ function ensureSync(): RenderMarkdownOptions {
50
+ if (resolvedRenderOpts !== undefined)
51
+ return resolvedRenderOpts
52
+ const loaded = options.render!()
53
+ if (loaded instanceof Promise) {
54
+ pendingRenderOpts ??= loaded.then((cfg) => {
55
+ resolvedRenderOpts = mergeRenderConfig(cfg)
56
+ return resolvedRenderOpts
57
+ }).catch((err) => {
58
+ pendingRenderOpts = undefined
59
+ throw err
60
+ })
61
+ throw new Error(
62
+ `@prunellejs/content: collection "${label}" uses an async "render" loader; call \`await entry.render()\` (e.g. in \`load()\`) before reading \`entry.html\` or \`entry.headings\`.`,
63
+ )
64
+ }
65
+ resolvedRenderOpts = mergeRenderConfig(loaded)
66
+ return resolvedRenderOpts
67
+ }
68
+
69
+ async function ensureAsync(): Promise<RenderMarkdownOptions> {
70
+ if (resolvedRenderOpts !== undefined)
71
+ return resolvedRenderOpts
72
+ pendingRenderOpts ??= Promise.resolve(options.render!()).then((cfg) => {
73
+ resolvedRenderOpts = mergeRenderConfig(cfg)
74
+ return resolvedRenderOpts
75
+ }).catch((err) => {
76
+ pendingRenderOpts = undefined
77
+ throw err
78
+ })
79
+ return pendingRenderOpts
80
+ }
81
+
82
+ return { ensureSync, ensureAsync }
83
+ }
84
+
85
+ export interface BuildContentEntryParams<TData> {
86
+ slug: string
87
+ locale?: string | undefined
88
+ file: string
89
+ data: TData
90
+ body: string
91
+ renderLoader: RenderConfigLoader
92
+ /** Set for file-backed collections so dev inline CMS can anchor rendered Markdown bodies. */
93
+ collectionName?: string | undefined
94
+ }
95
+
96
+ export function buildContentEntry<TData>(params: BuildContentEntryParams<TData>): ContentEntry<TData> {
97
+ const { slug, locale, file, data, body, renderLoader, collectionName } = params
98
+ const wordCount = body.trim().split(/\s+/).filter(Boolean).length
99
+ const readingMinutes = Math.max(1, Math.ceil(wordCount / 220))
100
+ let renderedCache: RenderedMarkdown | undefined
101
+
102
+ const getRenderedSync = (): RenderedMarkdown => {
103
+ renderedCache ??= renderMarkdown(body, { ...renderLoader.ensureSync(), locale, file })
104
+ return renderedCache
105
+ }
106
+
107
+ const renderAsync = async (): Promise<RenderedMarkdown> => {
108
+ if (renderedCache === undefined) {
109
+ const opts = await renderLoader.ensureAsync()
110
+ renderedCache ??= renderMarkdown(body, { ...opts, locale, file })
111
+ }
112
+ if (shouldWrapCmsBody(collectionName)) {
113
+ return {
114
+ ...renderedCache,
115
+ html: wrapCmsBodyHtml(collectionName, slug, locale, renderedCache.html),
116
+ }
117
+ }
118
+ return renderedCache
119
+ }
120
+
121
+ return {
122
+ slug,
123
+ ...(locale !== undefined ? { locale } : {}),
124
+ file,
125
+ data,
126
+ body,
127
+ get html() {
128
+ const raw = getRenderedSync().html
129
+ return shouldWrapCmsBody(collectionName)
130
+ ? wrapCmsBodyHtml(collectionName, slug, locale, raw)
131
+ : raw
132
+ },
133
+ get headings() {
134
+ return getRenderedSync().headings
135
+ },
136
+ wordCount,
137
+ readingMinutes,
138
+ render: renderAsync,
139
+ }
140
+ }
141
+
142
+ export function isDevMode(): boolean {
143
+ return currentApp.dev() ?? devFromEnv()
144
+ }
145
+
146
+ export function isDraft(data: unknown): boolean {
147
+ return data !== null && typeof data === 'object' && (data as Record<string, unknown>).draft === true
148
+ }
149
+
150
+ export function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
151
+ const ad = a.data !== null && typeof a.data === 'object' ? (a.data as Record<string, unknown>).date : undefined
152
+ const bd = b.data !== null && typeof b.data === 'object' ? (b.data as Record<string, unknown>).date : undefined
153
+ const at = ad instanceof Date ? ad.getTime() : (typeof ad === 'string' || typeof ad === 'number' ? Date.parse(String(ad)) : Number.NaN)
154
+ const bt = bd instanceof Date ? bd.getTime() : (typeof bd === 'string' || typeof bd === 'number' ? Date.parse(String(bd)) : Number.NaN)
155
+ if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt)
156
+ return bt - at
157
+ return a.slug.localeCompare(b.slug)
158
+ }
159
+
160
+ export function filterByTag<T>(entries: readonly ContentEntry<T>[], tag: string): ContentEntry<T>[] {
161
+ const needle = tag.toLowerCase()
162
+ return entries.filter((e) => {
163
+ const tags = e.data !== null && typeof e.data === 'object' ? (e.data as Record<string, unknown>).tags : undefined
164
+ return Array.isArray(tags) && tags.some(t => String(t).toLowerCase() === needle)
165
+ })
166
+ }
167
+
168
+ export function formatPaths<T>(entries: readonly ContentEntry<T>[], prefix = ''): string[] {
169
+ const base = prefix.replace(/\/$/, '')
170
+ return entries.map(e => `${base}/${e.slug}`)
171
+ }
@@ -0,0 +1,308 @@
1
+ // File-backed Markdown collection implementation (`defineCollection({ dir, ... })`).
2
+
3
+ import type { StandardSchemaV1 } from 'prunelle/server'
4
+ import type {
5
+ Collection,
6
+ CollectionOptions,
7
+ ContentEntry,
8
+ InternalCollection,
9
+ } from './types'
10
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
11
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path'
12
+ import { isInside } from 'prunelle/config'
13
+ import { formatIssuePath, formatSchemaIssues, validateSchemaSync } from 'prunelle/server'
14
+ import { currentApp } from './app'
15
+ import {
16
+ buildContentEntry,
17
+ createRenderConfigLoader,
18
+ defaultSort,
19
+ filterByTag,
20
+ formatPaths,
21
+ isDevMode,
22
+ isDraft,
23
+ } from './entry'
24
+ import { findFrontmatterFieldLine, parseFrontmatter } from './frontmatter'
25
+ import { registerFileCollection } from './registry'
26
+ import { recordAccessedEntry } from './tracking'
27
+ import {
28
+ COLLECTION_DIR_FOR_ROOT_KEY,
29
+ COLLECTION_META_KEY,
30
+ COLLECTION_VALIDATE_KEY,
31
+ } from './types'
32
+
33
+ export function resolveCollectionDir(dir: string, explicitRoot?: string): string {
34
+ if (isAbsolute(dir))
35
+ return dir
36
+ const prunelleRoot = explicitRoot ?? currentApp.root()
37
+ if (typeof prunelleRoot === 'string' && prunelleRoot !== '') {
38
+ const candidate = resolve(prunelleRoot, dir)
39
+ if (existsSync(candidate))
40
+ return candidate
41
+ }
42
+ return resolve(dir)
43
+ }
44
+
45
+ function walkMarkdownFiles(dir: string, out: string[] = []): string[] {
46
+ if (!existsSync(dir))
47
+ return out
48
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
49
+ const full = join(dir, ent.name)
50
+ if (ent.isDirectory())
51
+ walkMarkdownFiles(full, out)
52
+ else if (ent.isFile() && (ent.name.endsWith('.md') || ent.name.endsWith('.markdown')))
53
+ out.push(full)
54
+ }
55
+ return out
56
+ }
57
+
58
+ function listLocaleDirs(absDir: string): string[] | undefined {
59
+ if (!existsSync(absDir))
60
+ return undefined
61
+ const locales = readdirSync(absDir, { withFileTypes: true })
62
+ .filter(ent => ent.isDirectory() && !ent.name.startsWith('.'))
63
+ .map(ent => ent.name)
64
+ .sort()
65
+ return locales.length > 0 ? locales : undefined
66
+ }
67
+
68
+ function validateCollectionFiles(
69
+ absDir: string,
70
+ root: string,
71
+ schema: StandardSchemaV1 | undefined,
72
+ ): string[] {
73
+ if (!existsSync(absDir))
74
+ return []
75
+ const errors: string[] = []
76
+ for (const absFile of walkMarkdownFiles(absDir).sort()) {
77
+ const rel = relative(root, absFile).replace(/\\/g, '/')
78
+ const rawSource = readFileSync(absFile, 'utf8')
79
+ let rawData: Record<string, unknown>
80
+ try {
81
+ rawData = parseFrontmatter(rawSource).data
82
+ }
83
+ catch (err) {
84
+ const msg = err instanceof Error ? err.message : String(err)
85
+ errors.push(`${rel}:1:1: error: @prunellejs/content: invalid YAML frontmatter: ${msg}`)
86
+ continue
87
+ }
88
+ if (schema === undefined)
89
+ continue
90
+ const checked = validateSchemaSync(
91
+ schema,
92
+ rawData,
93
+ `@prunellejs/content: async frontmatter schema is not supported (${rel})`,
94
+ )
95
+ if (!checked.ok) {
96
+ for (const issue of checked.issues) {
97
+ const path = formatIssuePath(issue)
98
+ const line = findFrontmatterFieldLine(rawSource, path || undefined)
99
+ errors.push(`${rel}:${line}:1: error: @prunellejs/content: ${path ? `${path}: ` : ''}${issue.message}`)
100
+ }
101
+ }
102
+ }
103
+ return errors
104
+ }
105
+
106
+ // Slugs and locales usually come from URL params: a path built from them must stay inside the collection folder.
107
+ function localeDir(absDir: string, targetLocale: string | undefined): string | undefined {
108
+ if (targetLocale === undefined)
109
+ return absDir
110
+ const scanDir = resolve(absDir, targetLocale)
111
+ return isInside(absDir, scanDir) ? scanDir : undefined
112
+ }
113
+
114
+ function validateFileFrontmatter<TData>(
115
+ schema: StandardSchemaV1<unknown, TData> | undefined,
116
+ rawData: Record<string, unknown>,
117
+ slug: string,
118
+ absFile: string,
119
+ ): TData {
120
+ if (schema === undefined)
121
+ return rawData as TData
122
+ const checked = validateSchemaSync(
123
+ schema,
124
+ rawData,
125
+ `@prunellejs/content: async frontmatter schema is not supported (${slug})`,
126
+ )
127
+ if (!checked.ok)
128
+ throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${formatSchemaIssues(checked.issues)}`)
129
+ return checked.value
130
+ }
131
+
132
+ function parseFileFrontmatter(rawSource: string, absFile: string): ReturnType<typeof parseFrontmatter> {
133
+ try {
134
+ return parseFrontmatter(rawSource)
135
+ }
136
+ catch (err) {
137
+ throw new Error(`@prunellejs/content: invalid YAML frontmatter in "${absFile}": ${err instanceof Error ? err.message : String(err)}`, { cause: err })
138
+ }
139
+ }
140
+
141
+ function findEntryFileCandidate(scanDir: string, clean: string): string | undefined {
142
+ for (const candidate of [
143
+ join(scanDir, `${clean}.md`),
144
+ join(scanDir, `${clean}.markdown`),
145
+ join(scanDir, clean, 'index.md'),
146
+ join(scanDir, clean, 'index.markdown'),
147
+ ]) {
148
+ if (existsSync(candidate))
149
+ return candidate
150
+ }
151
+ return undefined
152
+ }
153
+
154
+ function trackAccessed<TData>(collectionName: string, entry: ContentEntry<TData>, primary: boolean): void {
155
+ recordAccessedEntry({
156
+ collection: collectionName,
157
+ slug: entry.slug,
158
+ ...(entry.locale !== undefined ? { locale: entry.locale } : {}),
159
+ }, primary)
160
+ }
161
+
162
+ export function createFileCollection<TData = Record<string, unknown>>(
163
+ options: CollectionOptions<TData>,
164
+ ): Collection<TData> {
165
+ const getDir = () => resolveCollectionDir(options.dir)
166
+ const getName = (absDir?: string) => options.name ?? (basename(absDir ?? getDir()) || 'collection')
167
+ const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
168
+ const localized = options.localized ?? false
169
+ const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
170
+ const renderLoader = createRenderConfigLoader(options.dir, options)
171
+
172
+ const cache = new Map<string, { mtimeMs: number, entry: ContentEntry<TData> }>()
173
+ const allCache = new Map<string, ContentEntry<TData>[]>()
174
+ const slugCache = new Map<string, Map<string, ContentEntry<TData>>>()
175
+
176
+ const visible = (entry: ContentEntry<TData>): ContentEntry<TData> | null =>
177
+ !allowsDrafts() && isDraft(entry.data) ? null : entry
178
+
179
+ function loadFile(absFile: string, baseDir: string, collectionName: string, entryLocale?: string): ContentEntry<TData> | null {
180
+ const dev = isDevMode()
181
+ const cached = cache.get(absFile)
182
+ if (!dev && cached !== undefined)
183
+ return visible(cached.entry)
184
+
185
+ const mtimeMs = statSync(absFile).mtimeMs
186
+ if (cached !== undefined && cached.mtimeMs === mtimeMs)
187
+ return visible(cached.entry)
188
+
189
+ const rawSource = readFileSync(absFile, 'utf8')
190
+ const { data: rawData, body } = parseFileFrontmatter(rawSource, absFile)
191
+ const slug = relative(baseDir, absFile)
192
+ .replace(/\\/g, '/')
193
+ .replace(/\.(?:md|markdown)$/, '')
194
+ .replace(/\/index$/, '')
195
+
196
+ const data = validateFileFrontmatter(options.schema, rawData, slug, absFile)
197
+ const entry = buildContentEntry({ slug, locale: entryLocale, file: absFile, data, body, renderLoader, collectionName })
198
+ cache.set(absFile, { mtimeMs, entry })
199
+ return visible(entry)
200
+ }
201
+
202
+ function scanAllEntries(locale?: string): { entries: ContentEntry<TData>[], collectionName: string } {
203
+ const absDir = getDir()
204
+ const collectionName = getName(absDir)
205
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
206
+ const scanDir = localeDir(absDir, targetLocale)
207
+ if (scanDir === undefined)
208
+ return { entries: [], collectionName }
209
+ const dev = isDevMode()
210
+ if (!dev) {
211
+ const hit = allCache.get(scanDir)
212
+ if (hit !== undefined)
213
+ return { entries: hit.slice(), collectionName }
214
+ }
215
+ const entries: ContentEntry<TData>[] = []
216
+ const bySlug = new Map<string, ContentEntry<TData>>()
217
+ for (const f of walkMarkdownFiles(scanDir)) {
218
+ const entry = loadFile(f, scanDir, collectionName, targetLocale)
219
+ if (entry === null)
220
+ continue
221
+ entries.push(entry)
222
+ bySlug.set(entry.slug, entry)
223
+ }
224
+ entries.sort(options.sort ?? defaultSort)
225
+ if (!dev) {
226
+ allCache.set(scanDir, entries)
227
+ slugCache.set(scanDir, bySlug)
228
+ }
229
+ return { entries: entries.slice(), collectionName }
230
+ }
231
+
232
+ function all(locale?: string): ContentEntry<TData>[] {
233
+ const { entries, collectionName } = scanAllEntries(locale)
234
+ for (const entry of entries)
235
+ trackAccessed(collectionName, entry, false)
236
+ return entries
237
+ }
238
+
239
+ function get(slug: string, locale?: string): ContentEntry<TData> | undefined {
240
+ const absDir = getDir()
241
+ const collectionName = getName(absDir)
242
+ const clean = slug.replace(/^\/+|\/+$/g, '')
243
+ const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
244
+ const scanDir = localeDir(absDir, targetLocale)
245
+ if (scanDir === undefined || !isInside(scanDir, resolve(scanDir, clean), { orSame: true }))
246
+ return undefined
247
+ const dev = isDevMode()
248
+ if (!dev) {
249
+ const cachedSlug = slugCache.get(scanDir)?.get(clean)
250
+ if (cachedSlug !== undefined)
251
+ return cachedSlug
252
+ // The scan listed every entry: a slug absent from it has no file, so there is nothing to probe.
253
+ if (allCache.has(scanDir))
254
+ return undefined
255
+ }
256
+ const candidate = findEntryFileCandidate(scanDir, clean)
257
+ let found: ContentEntry<TData> | undefined
258
+ if (candidate !== undefined) {
259
+ found = loadFile(candidate, scanDir, collectionName, targetLocale) ?? undefined
260
+ if (!dev && found !== undefined) {
261
+ let map = slugCache.get(scanDir)
262
+ if (map === undefined) {
263
+ map = new Map()
264
+ slugCache.set(scanDir, map)
265
+ }
266
+ map.set(clean, found)
267
+ }
268
+ }
269
+ found ??= scanAllEntries(locale).entries.find(e => e.slug === clean)
270
+ if (found !== undefined)
271
+ trackAccessed(collectionName, found, true)
272
+ return found
273
+ }
274
+
275
+ const col: Collection<TData> & InternalCollection = {
276
+ get dir() {
277
+ return getDir()
278
+ },
279
+ get name() {
280
+ return getName()
281
+ },
282
+ all,
283
+ get,
284
+ byTag: (tag, locale) => filterByTag(all(locale), tag),
285
+ paths: (prefix = '', locale) => formatPaths(all(locale), prefix),
286
+ clearCache() {
287
+ cache.clear()
288
+ allCache.clear()
289
+ slugCache.clear()
290
+ },
291
+ [COLLECTION_VALIDATE_KEY]: (root: string) => validateCollectionFiles(resolveCollectionDir(options.dir, root), root, options.schema),
292
+ [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => resolveCollectionDir(options.dir, root),
293
+ [COLLECTION_META_KEY]: (root?: string) => {
294
+ const absDir = resolveCollectionDir(options.dir, root)
295
+ return {
296
+ name: getName(absDir),
297
+ dir: absDir,
298
+ localized,
299
+ defaultLocale: getDefaultLocale(),
300
+ locales: options.locales ?? (localized ? listLocaleDirs(absDir) : undefined),
301
+ schema: options.schema,
302
+ isAsync: false,
303
+ }
304
+ },
305
+ }
306
+ registerFileCollection(col, options.dir, localized)
307
+ return col
308
+ }