@prunellejs/content 0.0.0-stage → 0.1.1
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/llms.txt +54 -0
- package/package.json +24 -4
- package/src/app.ts +13 -0
- package/src/collection.ts +534 -0
- package/src/components.ts +524 -0
- package/src/frontmatter.ts +43 -0
- package/src/index.ts +169 -0
- package/src/markdown.ts +171 -0
- package/src/rss.ts +85 -0
- package/src/sanitize.ts +309 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @prunellejs/content Reference
|
|
2
|
+
|
|
3
|
+
> Zero-dependency `Bun.markdown` + `Bun.YAML` typed Markdown collections, Standard Schema frontmatter validation, lazy Shiki/TSX rendering, TOC, localized content, and RSS feeds (`0 KB` client JS).
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/content`: `content`, `defineCollection`, `parseFrontmatter`, `renderMarkdown`, `renderRss`; types `Collection`, `CollectionOptions`, `CollectionOptionsWithSchema`, `CollectionOptionsWithoutSchema`, `CollectionRenderConfig`, `ContentEntry`, `ContentHeading`, `RenderedMarkdown`, `RenderMarkdownOptions`, `CodeHighlighter`, `MarkdownComponent`, `MarkdownImageResolver`, `MarkdownImageResult`, `RssFeedConfig`, `ContentFeed`.
|
|
8
|
+
|
|
9
|
+
## Defining a Collection (`defineCollection(options)`)
|
|
10
|
+
|
|
11
|
+
- `dir`: path to `.md`/`.markdown` files (relative to project root or absolute).
|
|
12
|
+
- `schema`: optional Standard Schema v1 (`Zod`, `Valibot`, `ArkType`, custom) validating frontmatter synchronously into `entry.data`.
|
|
13
|
+
- `localized`: `true` reads `<dir>/<locale>/<slug>.md`; `defaultLocale` defaults to `'en'`.
|
|
14
|
+
- `render`: lazy async factory `async () => ({ highlight, components, headingLinks, resolveImage, trusted })` so index pages, config, and RSS never import Shiki or TSX components until `await entry.render()` runs.
|
|
15
|
+
- Direct options (also accepted at top level): `highlight(code, lang)`, `components` (MDX-lite TSX components usable inside Markdown), `headingLinks` (`true` wraps `h2`–`h6` in `#id` anchor links), `resolveImage` (auto-wired with `@prunellejs/images`; pass `false` to disable), `trusted` (default `false`; HTML is sanitized unless `true`), `includeDrafts` (`false`), `sort(a, b)` (default newest `date` first, then `slug`).
|
|
16
|
+
|
|
17
|
+
## Collection & Entry API
|
|
18
|
+
|
|
19
|
+
- `col.all(locale?)`: sorted `ContentEntry<TData>[]`.
|
|
20
|
+
- `col.get(slug, locale?)`: O(1) lookup (`ContentEntry<TData> | undefined`).
|
|
21
|
+
- `col.byTag(tag, locale?)`: entries whose `data.tags` includes `tag`.
|
|
22
|
+
- `col.paths(prefix?, locale?)`: URL list for `export const prerender = true; export const paths = () => col.paths('/blog')`.
|
|
23
|
+
- `col.clearCache()`: drops cached entries.
|
|
24
|
+
- `ContentEntry<TData>`: `slug`, `locale`, `file`, `data`, `body`, `html`, `headings` (`{ level, id, text }[]`), `wordCount`, `readingMinutes`, and `await entry.render()` (memoized).
|
|
25
|
+
|
|
26
|
+
## Plugin Setup (`content({ feeds?, collections? })`)
|
|
27
|
+
|
|
28
|
+
- Register `content(...)` in `prunelle.config.ts` to auto-discover collections for `prunelle check` frontmatter validation and `prunelle dev` file watching.
|
|
29
|
+
- `feeds`: array of `RssFeedConfig` (`{ path? ('/rss.xml'), title, description, site? (inherits PrunelleConfig.site), collection, locale?, linkPrefix?, mapItem? }`). Emitted as static public files in `build()` and served with `ETag`/`304` on `GET <path>` in `server()`. A feed with no `site` of its own or in `PrunelleConfig` refuses a production start (`requires`).
|
|
30
|
+
|
|
31
|
+
## Snippets
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// src/content.ts
|
|
35
|
+
import { defineCollection } from '@prunellejs/content'
|
|
36
|
+
|
|
37
|
+
export const posts = defineCollection({
|
|
38
|
+
dir: 'src/content/posts',
|
|
39
|
+
headingLinks: true,
|
|
40
|
+
render: async () => ({ highlight: (await import('./highlight')).highlight }),
|
|
41
|
+
})
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// prunelle.config.ts
|
|
46
|
+
import { content } from '@prunellejs/content'
|
|
47
|
+
import { defineConfig } from 'prunelle/config'
|
|
48
|
+
import { posts } from './src/content'
|
|
49
|
+
|
|
50
|
+
export default defineConfig({
|
|
51
|
+
site: 'https://example.com',
|
|
52
|
+
plugins: [content({ feeds: [{ collection: posts, title: 'Blog', description: 'Posts', linkPrefix: '/blog' }] })],
|
|
53
|
+
})
|
|
54
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/content",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Zero-dependency Bun.markdown collections, YAML frontmatter, TOC, and RSS plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"bun": ">=1.4.0"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
21
|
+
"directory": "packages/plugin-content"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"prunelle": "^0.1.1"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/app.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// The app a collection renders for. Collections are read from route modules, not through the plugin, so each read asks prunelle which app the current request or build belongs to.
|
|
2
|
+
|
|
3
|
+
import type { ContentImageResolver } from 'prunelle/config'
|
|
4
|
+
import { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE } from 'prunelle/config'
|
|
5
|
+
import { getAppContext } from 'prunelle/internal/server'
|
|
6
|
+
|
|
7
|
+
export const currentApp = {
|
|
8
|
+
root: (): string | undefined => getAppContext()?.root,
|
|
9
|
+
site: (): string | undefined => getAppContext()?.site,
|
|
10
|
+
dev: (): boolean | undefined => getAppContext()?.dev,
|
|
11
|
+
defaultLocale: (): string | undefined => getAppContext()?.inject(I18N_CONFIG_SERVICE)?.defaultLocale,
|
|
12
|
+
imageResolver: (): ContentImageResolver | undefined => getAppContext()?.inject(CONTENT_IMAGE_RESOLVER_SERVICE),
|
|
13
|
+
}
|
|
@@ -0,0 +1,534 @@
|
|
|
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
|
+
}
|
|
284
|
+
|
|
285
|
+
export function defineCollection<TData>(options: CollectionOptionsWithSchema<TData>): Collection<TData>
|
|
286
|
+
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
|
|
534
|
+
}
|