@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/collection.ts CHANGED
@@ -1,534 +1,67 @@
1
- // Typed file-backed Markdown collections with caching, schema validation, localization, and lazy renderers.
2
-
3
- import type { ContentImageResolver, ContentImageResult } from 'prunelle/config'
4
- import { isInside } from 'prunelle/config'
5
- import type { StandardSchemaV1 } from 'prunelle/server'
6
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
- import { isAbsolute, join, relative, resolve } from 'node:path'
8
- import { formatIssuePath, validateSchemaSync } from 'prunelle/server'
9
- import { currentApp } from './app'
10
- import { findFrontmatterFieldLine, parseFrontmatter } from './frontmatter'
11
- import { renderMarkdown } from './markdown'
12
-
13
- export const COLLECTION_VERSION_KEY = Symbol.for('pru.content.collectionVersion')
14
- export const COLLECTION_VALIDATE_KEY = Symbol.for('pru.content.validateAll')
15
- export const COLLECTION_DIR_FOR_ROOT_KEY = Symbol.for('pru.content.dirForRoot')
16
- export const COLLECTION_OWNER_ROOT_KEY = Symbol.for('pru.content.ownerRoot')
17
-
18
- export interface InternalCollection extends Collection<unknown> {
19
- [COLLECTION_VERSION_KEY]?: () => number
20
- [COLLECTION_VALIDATE_KEY]?: (root: string) => string[]
21
- [COLLECTION_DIR_FOR_ROOT_KEY]?: (root?: string) => string
22
- [COLLECTION_OWNER_ROOT_KEY]?: string | undefined
23
- }
24
-
25
- // Keyed by (ownerRoot, resolved dir, localized) so dev reloads replace the prior instance instead of leaking.
26
- export const registeredCollections = new Map<string, InternalCollection>()
27
- let discoverRoot: string | undefined
28
-
29
- function registerCollection(col: InternalCollection, rawDir: string, localized: boolean): void {
30
- const owner = discoverRoot ?? currentApp.root()
31
- const explicitOwner = owner !== undefined && owner !== '' ? resolve(owner) : undefined
32
- const absOwner = explicitOwner ?? (isAbsolute(rawDir) ? undefined : resolve(process.cwd()))
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 interface ContentHeading {
41
- level: number
42
- id: string
43
- text: string
44
- }
45
-
46
- export interface RenderedMarkdown {
47
- readonly html: string
48
- readonly headings: readonly ContentHeading[]
49
- readonly wordCount: number
50
- readonly readingMinutes: number
51
- }
52
-
53
- export interface ContentEntry<TData = Record<string, unknown>> {
54
- readonly slug: string
55
- readonly locale?: string | undefined
56
- readonly file: string
57
- readonly data: TData
58
- readonly body: string
59
- readonly html: string
60
- readonly headings: readonly ContentHeading[]
61
- readonly wordCount: number
62
- readonly readingMinutes: number
63
- /** Lazily resolves async collection renderers (`highlight`, `components`) and renders Markdown once. */
64
- render(): Promise<RenderedMarkdown>
65
- }
66
-
67
- export type MarkdownComponent = (props: never) => unknown
68
- export type CodeHighlighter = (code: string, language: string | undefined) => string
69
- export type MarkdownImageResult = ContentImageResult
70
- export type MarkdownImageResolver = ContentImageResolver
71
-
72
- export interface CollectionRenderConfig {
73
- /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
74
- highlight?: CodeHighlighter | undefined
75
- /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
76
- components?: Record<string, MarkdownComponent> | undefined
77
- /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
78
- headingLinks?: boolean | undefined
79
- /** Optional image resolver (set to `false` to disable automatic `@prunellejs/images` optimization). */
80
- resolveImage?: MarkdownImageResolver | false | undefined
81
- /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
82
- trusted?: boolean | undefined
83
- }
84
-
85
- export interface RenderMarkdownOptions {
86
- highlight?: CodeHighlighter | undefined
87
- components?: Record<string, MarkdownComponent> | undefined
88
- /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
89
- headingLinks?: boolean | undefined
90
- /** Active locale passed into embedded components as `props.locale`. */
91
- locale?: string | undefined
92
- /** Optional image resolver for rewriting `<img src="...">` (defaults to auto-wired `@prunellejs/images` when active; `false` disables). */
93
- resolveImage?: MarkdownImageResolver | false | undefined
94
- /** Source file path passed to `resolveImage`. */
95
- file?: string | undefined
96
- /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
97
- trusted?: boolean | undefined
98
- }
99
-
100
- export interface CollectionOptions<TData = Record<string, unknown>> {
101
- /** Directory containing `.md` / `.markdown` files (or `<locale>/*.md` when `localized: true`). */
102
- dir: string
103
- /** When true, reads `<dir>/<locale>/<slug>.md` and filters queries by locale. */
104
- localized?: boolean | undefined
105
- /** Default locale when `localized: true` and no locale is passed (default: 'en'). */
106
- defaultLocale?: string | undefined
107
- /** Optional Standard Schema (Zod, Valibot, ArkType, custom) to validate frontmatter. */
108
- schema?: StandardSchemaV1<unknown, TData> | undefined
109
- /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
110
- highlight?: CodeHighlighter | undefined
111
- /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
112
- components?: Record<string, MarkdownComponent> | undefined
113
- /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
114
- headingLinks?: boolean | undefined
115
- /** Optional image resolver for rewriting Markdown images (defaults to auto-wired `@prunellejs/images`; `false` disables). */
116
- resolveImage?: MarkdownImageResolver | false | undefined
117
- /** Opt out of default Markdown HTML sanitization for fully trusted collections (default: false). */
118
- trusted?: boolean | undefined
119
- /** Lazy renderer loader (`async () => ({ highlight, components })`) so config/index/RSS never load Shiki or TSX components. */
120
- render?: (() => CollectionRenderConfig | Promise<CollectionRenderConfig>) | undefined
121
- /** Include entries with `draft: true` (default: false). */
122
- includeDrafts?: boolean | undefined
123
- /** Custom comparator for `all()` (defaults to newest `date` first, then alphabetical `slug`). */
124
- sort?: ((a: ContentEntry<TData>, b: ContentEntry<TData>) => number) | undefined
125
- }
126
-
127
- export interface Collection<TData = Record<string, unknown>> {
128
- readonly dir: string
129
- all(locale?: string): ContentEntry<TData>[]
130
- get(slug: string, locale?: string): ContentEntry<TData> | undefined
131
- byTag(tag: string, locale?: string): ContentEntry<TData>[]
132
- /** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
133
- paths(prefix?: string, locale?: string): string[]
134
- clearCache(): void
135
- }
136
-
137
- export interface CollectionOptionsWithSchema<TData> extends Omit<CollectionOptions<TData>, 'schema'> {
138
- /** Standard Schema (Zod, Valibot, ArkType, custom) validating frontmatter into `TData`. */
139
- schema: StandardSchemaV1<unknown, TData>
140
- }
141
-
142
- export interface CollectionOptionsWithoutSchema extends Omit<CollectionOptions<Record<string, unknown>>, 'schema'> {
143
- schema?: undefined
144
- }
145
-
146
-
147
- function resolveCollectionDir(dir: string, explicitRoot?: string): string {
148
- if (isAbsolute(dir))
149
- return dir
150
- const prunelleRoot = explicitRoot ?? currentApp.root()
151
- if (typeof prunelleRoot === 'string' && prunelleRoot !== '') {
152
- const candidate = resolve(prunelleRoot, dir)
153
- if (existsSync(candidate))
154
- return candidate
155
- }
156
- return resolve(dir)
157
- }
158
-
159
- function walkMarkdownFiles(dir: string, out: string[] = []): string[] {
160
- if (!existsSync(dir))
161
- return out
162
- for (const ent of readdirSync(dir, { withFileTypes: true })) {
163
- const full = join(dir, ent.name)
164
- if (ent.isDirectory())
165
- walkMarkdownFiles(full, out)
166
- else if (ent.isFile() && (ent.name.endsWith('.md') || ent.name.endsWith('.markdown')))
167
- out.push(full)
168
- }
169
- return out
170
- }
171
-
172
- function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
173
- const ad = (a.data as Record<string, unknown>).date
174
- const bd = (b.data as Record<string, unknown>).date
175
- const at = ad instanceof Date ? ad.getTime() : (typeof ad === 'string' || typeof ad === 'number' ? Date.parse(String(ad)) : Number.NaN)
176
- const bt = bd instanceof Date ? bd.getTime() : (typeof bd === 'string' || typeof bd === 'number' ? Date.parse(String(bd)) : Number.NaN)
177
- if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt)
178
- return bt - at
179
- return a.slug.localeCompare(b.slug)
180
- }
181
-
182
- function validateCollectionFiles(
183
- absDir: string,
184
- root: string,
185
- schema: StandardSchemaV1 | undefined,
186
- ): string[] {
187
- if (!existsSync(absDir))
188
- return []
189
- const errors: string[] = []
190
- for (const absFile of walkMarkdownFiles(absDir).sort()) {
191
- const rel = relative(root, absFile).replace(/\\/g, '/')
192
- const rawSource = readFileSync(absFile, 'utf8')
193
- let rawData: Record<string, unknown>
194
- try {
195
- rawData = parseFrontmatter(rawSource).data
196
- }
197
- catch (err) {
198
- const msg = err instanceof Error ? err.message : String(err)
199
- errors.push(`${rel}:1:1: error: @prunellejs/content: invalid YAML frontmatter: ${msg}`)
200
- continue
201
- }
202
- if (schema === undefined)
203
- continue
204
- const checked = validateSchemaSync(
205
- schema,
206
- rawData,
207
- `@prunellejs/content: async frontmatter schema is not supported (${rel})`,
208
- )
209
- if (!checked.ok) {
210
- for (const issue of checked.issues) {
211
- const path = formatIssuePath(issue)
212
- const line = findFrontmatterFieldLine(rawSource, path || undefined)
213
- errors.push(`${rel}:${line}:1: error: @prunellejs/content: ${path ? `${path}: ` : ''}${issue.message}`)
214
- }
215
- }
216
- }
217
- return errors
218
- }
219
-
220
- export function walkCollectionDefFiles(dir: string, out: string[] = []): string[] {
221
- if (!existsSync(dir))
222
- return out
223
- for (const ent of readdirSync(dir, { withFileTypes: true })) {
224
- if (ent.name === 'node_modules' || ent.name === 'dist' || ent.name.startsWith('.'))
225
- continue
226
- const full = join(dir, ent.name)
227
- if (ent.isDirectory())
228
- walkCollectionDefFiles(full, out)
229
- else if (ent.isFile() && (ent.name.endsWith('.ts') || ent.name.endsWith('.tsx')) && !ent.name.endsWith('.d.ts') && !/\.(?:test|spec)\.tsx?$/.test(ent.name))
230
- out.push(full)
231
- }
232
- return out
233
- }
234
-
235
- export const DEFINE_COLLECTION_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(/
236
- const REGEXP_SPECIAL_RE = /[.*+?^${}()|[\]\\]/g
237
-
238
- const prunelleJsxRoots = new Set<string>()
239
-
240
- // 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.
241
- function importAppTsxWithPrunelleJsx(root: string): void {
242
- if (prunelleJsxRoots.has(root))
243
- return
244
- prunelleJsxRoots.add(root)
245
- const filter = new RegExp(`^${`${root}/`.replace(REGEXP_SPECIAL_RE, '\\$&')}.*\\.tsx$`)
246
- Bun.plugin({
247
- name: `@prunellejs/content: prunelle JSX under ${root}`,
248
- setup(build) {
249
- // The pragma goes last, where it moves no line of a stack trace.
250
- build.onLoad({ filter }, async ({ path }) => ({ contents: `${await Bun.file(path).text()}\n/** @jsxImportSource prunelle */\n`, loader: 'tsx' }))
251
- },
252
- })
253
- }
254
-
255
- export async function discoverAppCollections(root: string): Promise<void> {
256
- const absRoot = resolve(root)
257
- const prevDiscoverRoot = discoverRoot
258
- discoverRoot = absRoot
259
- try {
260
- importAppTsxWithPrunelleJsx(absRoot)
261
- const srcDir = resolve(absRoot, 'src')
262
- for (const file of walkCollectionDefFiles(srcDir)) {
263
- let text: string
264
- try {
265
- text = readFileSync(file, 'utf8')
266
- }
267
- catch {
268
- continue
269
- }
270
- if (!DEFINE_COLLECTION_RE.test(text))
271
- continue
272
- try {
273
- await import(file)
274
- }
275
- catch {
276
- // Route/TSX files may import virtual modules (~icons) or CSS outside Bun.build; skip unimportable files.
277
- }
278
- }
279
- }
280
- finally {
281
- discoverRoot = prevDiscoverRoot
282
- }
283
- }
1
+ // Typed file-backed and loader-backed Markdown collections with caching, schema validation, localization, and lazy renderers.
2
+
3
+ import type {
4
+ AsyncCollection,
5
+ Collection,
6
+ CollectionOptions,
7
+ CollectionOptionsWithoutSchema,
8
+ CollectionOptionsWithSchema,
9
+ LoaderCollectionOptions,
10
+ LoaderCollectionOptionsWithoutSchema,
11
+ LoaderCollectionOptionsWithSchema,
12
+ } from './types'
13
+ import { createFileCollection } from './file-collection'
14
+ import { createLoaderCollection } from './loader-collection'
15
+
16
+ export {
17
+ DEFINE_COLLECTION_RE,
18
+ discoverAppCollections,
19
+ registeredCollections,
20
+ walkCollectionDefFiles,
21
+ } from './registry'
22
+
23
+ export {
24
+ COLLECTION_DIR_FOR_ROOT_KEY,
25
+ COLLECTION_META_KEY,
26
+ COLLECTION_OWNER_ROOT_KEY,
27
+ COLLECTION_VALIDATE_KEY,
28
+ } from './types'
29
+
30
+ export type {
31
+ AnyCollection,
32
+ AsyncCollection,
33
+ BaseCollectionOptions,
34
+ CodeHighlighter,
35
+ Collection,
36
+ CollectionLoadContext,
37
+ CollectionLoader,
38
+ CollectionOptions,
39
+ CollectionOptionsWithoutSchema,
40
+ CollectionOptionsWithSchema,
41
+ CollectionRenderConfig,
42
+ ContentEntry,
43
+ ContentHeading,
44
+ InternalCollection,
45
+ InternalCollectionMeta,
46
+ LoadedEntryInput,
47
+ LoaderCollectionOptions,
48
+ LoaderCollectionOptionsWithoutSchema,
49
+ LoaderCollectionOptionsWithSchema,
50
+ MarkdownComponent,
51
+ MarkdownImageResolver,
52
+ MarkdownImageResult,
53
+ RenderedMarkdown,
54
+ RenderMarkdownOptions,
55
+ } from './types'
284
56
 
285
57
  export function defineCollection<TData>(options: CollectionOptionsWithSchema<TData>): Collection<TData>
286
58
  export function defineCollection(options: CollectionOptionsWithoutSchema): Collection<Record<string, unknown>>
287
- export function defineCollection<TData = Record<string, unknown>>(options: CollectionOptions<TData>): Collection<TData> {
288
- const getDir = () => resolveCollectionDir(options.dir)
289
- const includeDrafts = options.includeDrafts ?? false
290
- const localized = options.localized ?? false
291
- const getDefaultLocale = (): string =>
292
- options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
293
- const baseRenderOpts: RenderMarkdownOptions = {
294
- highlight: options.highlight,
295
- components: options.components,
296
- headingLinks: options.headingLinks,
297
- resolveImage: options.resolveImage,
298
- trusted: options.trusted,
299
- }
300
- let resolvedRenderOpts: RenderMarkdownOptions | undefined = options.render === undefined ? baseRenderOpts : undefined
301
- let pendingRenderOpts: Promise<RenderMarkdownOptions> | undefined
302
-
303
- function mergeRenderConfig(cfg: CollectionRenderConfig): RenderMarkdownOptions {
304
- return {
305
- highlight: cfg.highlight ?? baseRenderOpts.highlight,
306
- components: cfg.components ?? baseRenderOpts.components,
307
- headingLinks: cfg.headingLinks ?? baseRenderOpts.headingLinks,
308
- resolveImage: cfg.resolveImage !== undefined ? cfg.resolveImage : baseRenderOpts.resolveImage,
309
- trusted: cfg.trusted !== undefined ? cfg.trusted : baseRenderOpts.trusted,
310
- }
311
- }
312
-
313
- function ensureRenderOptsSync(): RenderMarkdownOptions {
314
- if (resolvedRenderOpts !== undefined)
315
- return resolvedRenderOpts
316
- const loaded = options.render!()
317
- if (loaded instanceof Promise) {
318
- pendingRenderOpts ??= loaded.then((cfg) => {
319
- resolvedRenderOpts = mergeRenderConfig(cfg)
320
- return resolvedRenderOpts
321
- }).catch((err) => {
322
- pendingRenderOpts = undefined
323
- throw err
324
- })
325
- throw new Error(
326
- `@prunellejs/content: collection "${options.dir}" uses an async "render" loader; call \`await entry.render()\` (e.g. in \`load()\`) before reading \`entry.html\` or \`entry.headings\`.`,
327
- )
328
- }
329
- resolvedRenderOpts = mergeRenderConfig(loaded)
330
- return resolvedRenderOpts
331
- }
332
-
333
- async function ensureRenderOptsAsync(): Promise<RenderMarkdownOptions> {
334
- if (resolvedRenderOpts !== undefined)
335
- return resolvedRenderOpts
336
- pendingRenderOpts ??= Promise.resolve(options.render!()).then((cfg) => {
337
- resolvedRenderOpts = mergeRenderConfig(cfg)
338
- return resolvedRenderOpts
339
- }).catch((err) => {
340
- pendingRenderOpts = undefined
341
- throw err
342
- })
343
- return pendingRenderOpts
344
- }
345
-
346
- const cache = new Map<string, { mtimeMs: number, entry: ContentEntry<TData> | null }>()
347
- const allCache = new Map<string, ContentEntry<TData>[]>()
348
- const slugCache = new Map<string, Map<string, ContentEntry<TData>>>()
349
- let cacheVersion = 0
350
-
351
- function isDevMode(): boolean {
352
- return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
353
- }
354
-
355
- function loadFile(absFile: string, baseDir: string, entryLocale?: string): ContentEntry<TData> | null {
356
- const dev = isDevMode()
357
- const cached = cache.get(absFile)
358
- if (!dev && cached !== undefined)
359
- return cached.entry
360
-
361
- const mtimeMs = statSync(absFile).mtimeMs
362
- if (cached !== undefined && cached.mtimeMs === mtimeMs)
363
- return cached.entry
364
-
365
- const rawSource = readFileSync(absFile, 'utf8')
366
- const { data: rawData, body } = parseFrontmatter(rawSource)
367
- const slug = relative(baseDir, absFile)
368
- .replace(/\\/g, '/')
369
- .replace(/\.(?:md|markdown)$/, '')
370
- .replace(/\/index$/, '')
371
-
372
- let data: TData
373
- if (options.schema !== undefined) {
374
- const checked = validateSchemaSync(
375
- options.schema,
376
- rawData,
377
- `@prunellejs/content: async frontmatter schema is not supported (${slug})`,
378
- )
379
- if (!checked.ok) {
380
- const msg = checked.issues.map(i => i.message).join('; ')
381
- throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${msg}`)
382
- }
383
- data = checked.value
384
- }
385
- else {
386
- data = rawData as TData
387
- }
388
-
389
- if (!includeDrafts && (data as Record<string, unknown>).draft === true) {
390
- cache.set(absFile, { mtimeMs, entry: null })
391
- return null
392
- }
393
-
394
- const wordCount = body.trim().split(/\s+/).filter(Boolean).length
395
- const readingMinutes = Math.max(1, Math.ceil(wordCount / 220))
396
- let renderedCache: RenderedMarkdown | undefined
397
- const getRenderedSync = (): RenderedMarkdown => {
398
- renderedCache ??= renderMarkdown(body, { ...ensureRenderOptsSync(), locale: entryLocale, file: absFile })
399
- return renderedCache
400
- }
401
- const renderAsync = async (): Promise<RenderedMarkdown> => {
402
- if (renderedCache !== undefined)
403
- return renderedCache
404
- const opts = await ensureRenderOptsAsync()
405
- renderedCache ??= renderMarkdown(body, { ...opts, locale: entryLocale, file: absFile })
406
- return renderedCache
407
- }
408
-
409
- const entry: ContentEntry<TData> = {
410
- slug,
411
- ...(entryLocale !== undefined ? { locale: entryLocale } : {}),
412
- file: absFile,
413
- data,
414
- body,
415
- get html() {
416
- return getRenderedSync().html
417
- },
418
- get headings() {
419
- return getRenderedSync().headings
420
- },
421
- wordCount,
422
- readingMinutes,
423
- render: renderAsync,
424
- }
425
- cache.set(absFile, { mtimeMs, entry })
426
- return entry
427
- }
428
-
429
- // Slugs and locales usually come from URL params: a path built from them must stay inside the collection folder.
430
- function localeDir(absDir: string, targetLocale: string | undefined): string | undefined {
431
- if (targetLocale === undefined)
432
- return absDir
433
- const scanDir = resolve(absDir, targetLocale)
434
- return isInside(absDir, scanDir) ? scanDir : undefined
435
- }
436
-
437
- function all(locale?: string): ContentEntry<TData>[] {
438
- const absDir = getDir()
439
- const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
440
- const scanDir = localeDir(absDir, targetLocale)
441
- if (scanDir === undefined)
442
- return []
443
- const dev = isDevMode()
444
- if (!dev) {
445
- const hit = allCache.get(scanDir)
446
- if (hit !== undefined)
447
- return hit.slice()
448
- }
449
- const files = walkMarkdownFiles(scanDir)
450
- const entries: ContentEntry<TData>[] = []
451
- const bySlug = new Map<string, ContentEntry<TData>>()
452
- for (const f of files) {
453
- const entry = loadFile(f, scanDir, targetLocale)
454
- if (entry === null)
455
- continue
456
- entries.push(entry)
457
- bySlug.set(entry.slug, entry)
458
- }
459
- entries.sort(options.sort ?? defaultSort)
460
- if (!dev) {
461
- allCache.set(scanDir, entries)
462
- slugCache.set(scanDir, bySlug)
463
- }
464
- return entries.slice()
465
- }
466
-
467
- const col: Collection<TData> & {
468
- [COLLECTION_VERSION_KEY]: () => number
469
- [COLLECTION_VALIDATE_KEY]: (root: string) => string[]
470
- [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => string
471
- } = {
472
- get dir() {
473
- return getDir()
474
- },
475
- all,
476
- get(slug, locale) {
477
- const absDir = getDir()
478
- const clean = slug.replace(/^\/+|\/+$/g, '')
479
- const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
480
- const scanDir = localeDir(absDir, targetLocale)
481
- if (scanDir === undefined || !isInside(scanDir, resolve(scanDir, clean), { orSame: true }))
482
- return undefined
483
- const dev = isDevMode()
484
- if (!dev) {
485
- const cachedSlug = slugCache.get(scanDir)?.get(clean)
486
- if (cachedSlug !== undefined)
487
- return cachedSlug
488
- }
489
- // O(1) direct file lookup before falling back to directory scan
490
- for (const candidate of [
491
- join(scanDir, `${clean}.md`),
492
- join(scanDir, `${clean}.markdown`),
493
- join(scanDir, clean, 'index.md'),
494
- join(scanDir, clean, 'index.markdown'),
495
- ]) {
496
- if (existsSync(candidate)) {
497
- const loaded = loadFile(candidate, scanDir, targetLocale) ?? undefined
498
- if (!dev && loaded !== undefined) {
499
- let map = slugCache.get(scanDir)
500
- if (map === undefined) {
501
- map = new Map()
502
- slugCache.set(scanDir, map)
503
- }
504
- map.set(clean, loaded)
505
- }
506
- return loaded
507
- }
508
- }
509
- return all(locale).find(e => e.slug === clean)
510
- },
511
- byTag(tag, locale) {
512
- const needle = tag.toLowerCase()
513
- return all(locale).filter((e) => {
514
- const tags = (e.data as Record<string, unknown>).tags
515
- return Array.isArray(tags) && tags.some(t => String(t).toLowerCase() === needle)
516
- })
517
- },
518
- paths(prefix = '', locale) {
519
- const base = prefix.replace(/\/$/, '')
520
- return all(locale).map(e => `${base}/${e.slug}`)
521
- },
522
- clearCache() {
523
- cache.clear()
524
- allCache.clear()
525
- slugCache.clear()
526
- cacheVersion++
527
- },
528
- [COLLECTION_VERSION_KEY]: () => cacheVersion,
529
- [COLLECTION_VALIDATE_KEY]: (root: string) => validateCollectionFiles(resolveCollectionDir(options.dir, root), root, options.schema),
530
- [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => resolveCollectionDir(options.dir, root),
531
- }
532
- registerCollection(col as InternalCollection, options.dir, localized)
533
- return col
59
+ export function defineCollection<TData>(options: LoaderCollectionOptionsWithSchema<TData>): AsyncCollection<TData>
60
+ export function defineCollection(options: LoaderCollectionOptionsWithoutSchema): AsyncCollection<Record<string, unknown>>
61
+ export function defineCollection<TData = Record<string, unknown>>(
62
+ options: CollectionOptions<TData> | LoaderCollectionOptions<TData>,
63
+ ): Collection<TData> | AsyncCollection<TData> {
64
+ if (typeof options.load === 'function')
65
+ return createLoaderCollection(options as LoaderCollectionOptions<TData>)
66
+ return createFileCollection(options as CollectionOptions<TData>)
534
67
  }