@prunellejs/content 0.1.1 → 0.7.3
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/LICENSE +21 -0
- package/llms.txt +40 -11
- package/package.json +2 -2
- package/src/app.ts +3 -1
- package/src/collection.ts +63 -530
- package/src/components.ts +85 -21
- package/src/entry.ts +171 -0
- package/src/file-collection.ts +308 -0
- package/src/frontmatter.ts +34 -15
- package/src/index.ts +78 -32
- package/src/loader-collection.ts +333 -0
- package/src/markdown.ts +52 -5
- package/src/registry.ts +147 -0
- package/src/rss.ts +44 -24
- package/src/service.ts +88 -0
- package/src/tracking.ts +80 -0
- package/src/types.ts +202 -0
- package/src/sanitize.ts +0 -309
|
@@ -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
|
+
}
|
package/src/markdown.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// renderMarkdown: Bun's native Markdown renderer plus highlight hook, embedded components, heading ids and TOC.
|
|
2
2
|
|
|
3
3
|
import type { ContentHeading, MarkdownImageResolver, MarkdownImageResult, RenderMarkdownOptions } from './index'
|
|
4
|
+
import { sanitizeMarkdownHtml } from 'prunelle/internal/server'
|
|
4
5
|
import { escAttr } from 'prunelle/server'
|
|
5
6
|
import { currentApp } from './app'
|
|
6
7
|
import { expandComponents } from './components'
|
|
7
|
-
import { sanitizeMarkdownHtml } from './sanitize'
|
|
8
8
|
|
|
9
9
|
function slugifyHeading(text: string): string {
|
|
10
10
|
return text
|
|
@@ -33,7 +33,9 @@ function findDefaultImageResolver(file: string | undefined): MarkdownImageResolv
|
|
|
33
33
|
return currentApp.imageResolver()
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
// CommonMark §4.5: backtick fence info strings cannot contain backticks; fences cannot mix ` and ~.
|
|
37
|
+
const FENCE_OPEN_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))$/
|
|
38
|
+
const FENCE_CLOSE_RE = /^(`{3,}|~{3,})[ \t]*\r?$/
|
|
37
39
|
let slotBatchId = 0
|
|
38
40
|
|
|
39
41
|
function renderMarkdownInternal(
|
|
@@ -55,7 +57,7 @@ function renderMarkdownInternal(
|
|
|
55
57
|
|
|
56
58
|
// 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
|
|
57
59
|
if (options.highlight !== undefined || options.components !== undefined) {
|
|
58
|
-
processed = processed
|
|
60
|
+
processed = replaceFences(processed, (full, info, code) => {
|
|
59
61
|
if (options.highlight !== undefined) {
|
|
60
62
|
const lang = info.trim().split(/\s+/)[0] || undefined
|
|
61
63
|
const idx = slots.length
|
|
@@ -64,7 +66,10 @@ function renderMarkdownInternal(
|
|
|
64
66
|
}
|
|
65
67
|
// Protect code fences from component expansion when only components are configured
|
|
66
68
|
const idx = slots.length
|
|
67
|
-
|
|
69
|
+
let renderedFence = Bun.markdown.html(full, { tables: true, strikethrough: true, tasklists: true, autolinks: true })
|
|
70
|
+
if (options.trusted !== true)
|
|
71
|
+
renderedFence = sanitizeMarkdownHtml(renderedFence)
|
|
72
|
+
slots.push(renderedFence)
|
|
68
73
|
return `\n\n<div data-pru-md-slot="${slotPrefix}${idx}"></div>\n\n`
|
|
69
74
|
})
|
|
70
75
|
}
|
|
@@ -116,7 +121,10 @@ function renderMarkdownInternal(
|
|
|
116
121
|
? undefined
|
|
117
122
|
: (options.resolveImage ?? findDefaultImageResolver(options.file))
|
|
118
123
|
if (resolveImageFn !== undefined) {
|
|
124
|
+
// The first image is often the page's largest paint, which lazy loading would hold back.
|
|
125
|
+
let seen = 0
|
|
119
126
|
html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
|
|
127
|
+
const first = seen++ === 0
|
|
120
128
|
const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
|
|
121
129
|
if (!srcMatch)
|
|
122
130
|
return full
|
|
@@ -135,7 +143,7 @@ function renderMarkdownInternal(
|
|
|
135
143
|
parts.push(`width="${info.width}"`)
|
|
136
144
|
if (info.height !== undefined && info.height > 0)
|
|
137
145
|
parts.push(`height="${info.height}"`)
|
|
138
|
-
parts.push(`loading="${info.loading ?? 'lazy'}"`, 'decoding="async"')
|
|
146
|
+
parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
|
|
139
147
|
const imgTag = `<img ${parts.join(' ')}>`
|
|
140
148
|
if (info.avifSrcset) {
|
|
141
149
|
const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
|
|
@@ -169,3 +177,42 @@ export function renderMarkdown(body: string, options: RenderMarkdownOptions = {}
|
|
|
169
177
|
} {
|
|
170
178
|
return renderMarkdownInternal(body, options)
|
|
171
179
|
}
|
|
180
|
+
|
|
181
|
+
// Fenced blocks in one pass: closing lines are indexed by fence first, so an opener never closed costs one lookup, not a scan to the end.
|
|
182
|
+
function replaceFences(md: string, replace: (full: string, info: string, code: string) => string): string {
|
|
183
|
+
const lines = md.split('\n')
|
|
184
|
+
const closers = new Map<string, number[]>()
|
|
185
|
+
lines.forEach((line, index) => {
|
|
186
|
+
const fence = FENCE_CLOSE_RE.exec(line)?.[1]
|
|
187
|
+
if (fence === undefined)
|
|
188
|
+
return
|
|
189
|
+
const list = closers.get(fence)
|
|
190
|
+
if (list === undefined)
|
|
191
|
+
closers.set(fence, [index])
|
|
192
|
+
else
|
|
193
|
+
list.push(index)
|
|
194
|
+
})
|
|
195
|
+
const cursors = new Map<string, number>()
|
|
196
|
+
const nextCloser = (fence: string, after: number): number => {
|
|
197
|
+
const list = closers.get(fence) ?? []
|
|
198
|
+
let cursor = cursors.get(fence) ?? 0
|
|
199
|
+
while (cursor < list.length && list[cursor]! <= after) cursor++
|
|
200
|
+
cursors.set(fence, cursor)
|
|
201
|
+
return list[cursor] ?? -1
|
|
202
|
+
}
|
|
203
|
+
const out: string[] = []
|
|
204
|
+
for (let i = 0; i < lines.length; i++) {
|
|
205
|
+
const open = FENCE_OPEN_RE.exec(lines[i]!)
|
|
206
|
+
const fence = open?.[1] ?? open?.[3]
|
|
207
|
+
const close = fence === undefined ? -1 : nextCloser(fence, i)
|
|
208
|
+
if (close === -1) {
|
|
209
|
+
out.push(lines[i]!)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
const body = lines.slice(i + 1, close)
|
|
213
|
+
const code = body.length > 0 ? `${body.join('\n')}\n` : ''
|
|
214
|
+
out.push(replace(lines.slice(i, close + 1).join('\n'), open![2] ?? open![4] ?? '', code))
|
|
215
|
+
i = close
|
|
216
|
+
}
|
|
217
|
+
return out.join('\n')
|
|
218
|
+
}
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Process-level collection registry and `src/` file discovery for `prunelle check` and `CONTENT_COLLECTIONS_SERVICE`.
|
|
2
|
+
|
|
3
|
+
import type { InternalCollection } from './types'
|
|
4
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
5
|
+
import { isAbsolute, join, relative, resolve } from 'node:path'
|
|
6
|
+
import { currentApp } from './app'
|
|
7
|
+
import { COLLECTION_OWNER_ROOT_KEY, COLLECTION_VALIDATE_KEY } from './types'
|
|
8
|
+
|
|
9
|
+
// Keyed by (ownerRoot, resolved dir or loader identity, localized) so dev reloads replace the prior instance instead of leaking.
|
|
10
|
+
export const registeredCollections = new Map<string, InternalCollection>()
|
|
11
|
+
|
|
12
|
+
let discoverRoot: string | undefined
|
|
13
|
+
let discoverFile: string | undefined
|
|
14
|
+
let discoverIndex = 0
|
|
15
|
+
let anonLoaderSeq = 0
|
|
16
|
+
|
|
17
|
+
export function currentDiscoverFile(): string | undefined {
|
|
18
|
+
return discoverFile
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function resolveOwnerRoot(rawDir?: string): string | undefined {
|
|
22
|
+
const owner = discoverRoot ?? currentApp.root()
|
|
23
|
+
const explicitOwner = owner !== undefined && owner !== '' ? resolve(owner) : undefined
|
|
24
|
+
if (explicitOwner !== undefined)
|
|
25
|
+
return explicitOwner
|
|
26
|
+
if (rawDir !== undefined && !isAbsolute(rawDir))
|
|
27
|
+
return resolve(process.cwd())
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function registerFileCollection(col: InternalCollection, rawDir: string, localized: boolean): void {
|
|
32
|
+
const absOwner = resolveOwnerRoot(rawDir)
|
|
33
|
+
col[COLLECTION_OWNER_ROOT_KEY] = absOwner
|
|
34
|
+
const resolvedKey = isAbsolute(rawDir)
|
|
35
|
+
? resolve(rawDir)
|
|
36
|
+
: (absOwner !== undefined ? resolve(absOwner, rawDir) : rawDir)
|
|
37
|
+
registeredCollections.set(`${absOwner ?? ''}\0${resolvedKey}\0${localized ? '1' : '0'}`, col)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function registerLoadedCollection(
|
|
41
|
+
col: InternalCollection,
|
|
42
|
+
explicitName: string | undefined,
|
|
43
|
+
localized: boolean,
|
|
44
|
+
): void {
|
|
45
|
+
const absOwner = resolveOwnerRoot()
|
|
46
|
+
col[COLLECTION_OWNER_ROOT_KEY] = absOwner
|
|
47
|
+
const identity = explicitName !== undefined && explicitName !== ''
|
|
48
|
+
? `load:name:${explicitName}`
|
|
49
|
+
: discoverFile !== undefined
|
|
50
|
+
? `load:file:${discoverFile}#${discoverIndex++}`
|
|
51
|
+
: `load:anon:${++anonLoaderSeq}`
|
|
52
|
+
registeredCollections.set(`${absOwner ?? ''}\0${identity}\0${localized ? '1' : '0'}`, col)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function walkCollectionDefFiles(dir: string, out: string[] = []): string[] {
|
|
56
|
+
if (!existsSync(dir))
|
|
57
|
+
return out
|
|
58
|
+
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
|
59
|
+
if (ent.name === 'node_modules' || ent.name === 'dist' || ent.name.startsWith('.'))
|
|
60
|
+
continue
|
|
61
|
+
const full = join(dir, ent.name)
|
|
62
|
+
if (ent.isDirectory())
|
|
63
|
+
walkCollectionDefFiles(full, out)
|
|
64
|
+
else if (ent.isFile() && (ent.name.endsWith('.ts') || ent.name.endsWith('.tsx')) && !ent.name.endsWith('.d.ts') && !/\.(?:test|spec)\.tsx?$/.test(ent.name))
|
|
65
|
+
out.push(full)
|
|
66
|
+
}
|
|
67
|
+
return out
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const DEFINE_COLLECTION_RE = /\bdefineCollection\s*(?:<[^>]*>)?\s*\(/
|
|
71
|
+
const REGEXP_SPECIAL_RE = /[.*+?^${}()|[\]\\]/g
|
|
72
|
+
|
|
73
|
+
const prunelleJsxRoots = new Set<string>()
|
|
74
|
+
|
|
75
|
+
// Bun gives a runtime import the JSX source of the working directory's tsconfig, not the app's, so `prunelle check <dir>` run elsewhere would import its routes as React.
|
|
76
|
+
function importAppTsxWithPrunelleJsx(root: string): void {
|
|
77
|
+
if (prunelleJsxRoots.has(root))
|
|
78
|
+
return
|
|
79
|
+
prunelleJsxRoots.add(root)
|
|
80
|
+
const filter = new RegExp(`^${`${root}/`.replace(REGEXP_SPECIAL_RE, '\\$&')}.*\\.tsx$`)
|
|
81
|
+
Bun.plugin({
|
|
82
|
+
name: `@prunellejs/content: prunelle JSX under ${root}`,
|
|
83
|
+
setup(build) {
|
|
84
|
+
// The pragma goes last, where it moves no line of a stack trace.
|
|
85
|
+
build.onLoad({ filter }, async ({ path }) => ({ contents: `${await Bun.file(path).text()}\n/** @jsxImportSource prunelle */\n`, loader: 'tsx' }))
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Per app root and file: the mtime it was last read at, and whether its import failed, so discovery reads only what changed.
|
|
91
|
+
const seenFiles = new Map<string, { mtimeMs: number, failed: boolean }>()
|
|
92
|
+
|
|
93
|
+
export async function discoverAppCollections(root: string): Promise<void> {
|
|
94
|
+
const absRoot = resolve(root)
|
|
95
|
+
const prevDiscoverRoot = discoverRoot
|
|
96
|
+
const prevDiscoverFile = discoverFile
|
|
97
|
+
const prevDiscoverIndex = discoverIndex
|
|
98
|
+
discoverRoot = absRoot
|
|
99
|
+
try {
|
|
100
|
+
importAppTsxWithPrunelleJsx(absRoot)
|
|
101
|
+
const srcDir = resolve(absRoot, 'src')
|
|
102
|
+
for (const file of walkCollectionDefFiles(srcDir)) {
|
|
103
|
+
const seenKey = `${absRoot}\0${file}`
|
|
104
|
+
let text: string
|
|
105
|
+
let mtimeMs: number
|
|
106
|
+
try {
|
|
107
|
+
mtimeMs = statSync(file).mtimeMs
|
|
108
|
+
if (seenFiles.get(seenKey)?.mtimeMs === mtimeMs)
|
|
109
|
+
continue
|
|
110
|
+
text = readFileSync(file, 'utf8')
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
const failedBefore = seenFiles.get(seenKey)?.failed === true
|
|
116
|
+
seenFiles.set(seenKey, { mtimeMs, failed: false })
|
|
117
|
+
if (!DEFINE_COLLECTION_RE.test(text))
|
|
118
|
+
continue
|
|
119
|
+
discoverFile = file
|
|
120
|
+
discoverIndex = 0
|
|
121
|
+
try {
|
|
122
|
+
// Bun keeps a failed import's error: a file fixed since is imported under a new URL so it runs again.
|
|
123
|
+
const mod = await import(failedBefore ? `${file}?v=${mtimeMs}` : file) as Record<string, unknown>
|
|
124
|
+
for (const val of Object.values(mod)) {
|
|
125
|
+
if (val !== null && typeof val === 'object' && COLLECTION_VALIDATE_KEY in val) {
|
|
126
|
+
const col = val as InternalCollection
|
|
127
|
+
if (col[COLLECTION_OWNER_ROOT_KEY] === undefined) {
|
|
128
|
+
col[COLLECTION_OWNER_ROOT_KEY] = absRoot
|
|
129
|
+
const label = col.name ?? `file:${file}#${discoverIndex++}`
|
|
130
|
+
registeredCollections.set(`${absRoot}\0adopted:${file}:${label}`, col)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
seenFiles.set(seenKey, { mtimeMs, failed: true })
|
|
137
|
+
const reason = err instanceof Error ? err.message : String(err)
|
|
138
|
+
console.warn(`@prunellejs/content: ${relative(absRoot, file)} calls defineCollection but could not be imported, so its collections are left out: ${reason}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
discoverRoot = prevDiscoverRoot
|
|
144
|
+
discoverFile = prevDiscoverFile
|
|
145
|
+
discoverIndex = prevDiscoverIndex
|
|
146
|
+
}
|
|
147
|
+
}
|