@prunellejs/content 0.6.0 → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -17,13 +17,15 @@ Shared options:
17
17
  - `schema`: optional Standard Schema v1 (`Zod`, `Valibot`, `ArkType`, custom) validating frontmatter / loaded `data` into `entry.data` (file-backed is synchronous; loader-backed supports both sync and async validators).
18
18
  - `localized`: `true` reads `<dir>/<locale>/<slug>.md` for file collections, or passes `{ locale }` to `load()` and filters entries whose `entry.locale` is set for loaded collections; `defaultLocale` defaults to the app's i18n default or `'en'`; `locales` lists known locales for `prunelle check`, search, and CMS.
19
19
  - `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.
20
- - Direct options: `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` (defaults to `true` in `prunelle dev` / `testApp({ dev: true })` and `false` in `prunelle build` / production; RSS feeds always leave drafts out), `sort(a, b)` (default newest `date` first, then `slug`).
20
+ - Direct options: `highlight(code, lang)`, `components` (MDX-lite TSX components usable inside Markdown; a non-literal prop like `tone={someVar}` and an unregistered `<Foo />` tag throw naming the file, and `__proto__`, `constructor` and `prototype` props are dropped), `headingLinks` (`true` wraps `h2`–`h6` in `#id` anchor links), `resolveImage` (auto-wired with `@prunellejs/images`; pass `false` to disable; the first image gets `loading="eager"`, the others `lazy`, unless it returns a `loading`), `trusted` (default `false`; HTML is sanitized unless `true`), `includeDrafts` (defaults to `true` in `prunelle dev` / `testApp({ dev: true })` and `false` in `prunelle build` / production; RSS feeds always leave drafts out), `sort(a, b)` (default newest `date` first, then `slug`).
21
21
 
22
22
  ## Caching (Loader-Backed Collections)
23
23
 
24
24
  - During `prunelle build` / prerendering: `load()` is cached per `(build, locale)` so it runs **once** across `paths()`, prerendered pages, and feeds.
25
- - At runtime: `load()` is cached per request (`currentRequest()?.ctx`), so layout, `load()`, and page share one fetch while the next request gets fresh data.
26
- - Call `col.clearCache()` to drop cached entries.
25
+ - At runtime: `load()` is cached per request (`currentRequest()?.ctx`), so layout, `load()`, and page share one fetch while the next request gets fresh data. Requests arriving while a load of the same locale runs share it.
26
+ - `ttlMs` keeps the entries of a finished load for every request that long, per locale (default `0`; `Infinity` until `clearCache()`); a failed load is not kept.
27
+ - `load({ locale, signal })`: pass `signal` to `fetch()` or the database client. It aborts after `timeoutMs` (default `30000`) or on `clearCache()`, and the load then fails even if the loader ignores it. `ttlMs < 0` or a `timeoutMs` that is not a positive finite number throws at `defineCollection`.
28
+ - Call `col.clearCache()` to drop cached entries. In production a file collection trusts its first scan: a file added afterwards is seen after `clearCache()` (the CMS plugin calls it on every write).
27
29
 
28
30
  ## Collection & Entry API
29
31
 
@@ -36,8 +38,8 @@ Shared options:
36
38
 
37
39
  ## Plugin Setup (`content({ feeds?, collections? })`)
38
40
 
39
- - Register `content(...)` in `prunelle.config.ts` to auto-discover file-backed and loader-backed collections for `prunelle check`, `prunelle dev` file watching, and `CONTENT_COLLECTIONS_SERVICE` (provided in `build`, `afterPrerender`, `server`, and `check` for downstream plugins).
40
- - `feeds`: array of `RssFeedConfig` (`{ path? ('/rss.xml'), title, description, site? (inherits PrunelleConfig.site), collection, locale?, linkPrefix?, mapItem? }`), supporting both file-backed and loader-backed collections. Emitted as static public files in `build()` and served with `ETag`/`304` on `GET <path>` in `server()`. Use `renderRss()` for synchronous file collections and `await renderRssAsync()` for either.
41
+ - Register `content(...)` in `prunelle.config.ts` to auto-discover file-backed and loader-backed collections for `prunelle check`, `prunelle dev` file watching, and `CONTENT_COLLECTIONS_SERVICE` (provided in `build`, `afterPrerender`, `server`, and `check` for downstream plugins). A `src/` file that calls `defineCollection` but fails to import is reported once with its error, and tried again when it changes.
42
+ - `feeds`: array of `RssFeedConfig` (`{ path? ('/rss.xml'), title, description, site? (inherits PrunelleConfig.site), collection, locale?, linkPrefix?, mapItem? }`), supporting both file-backed and loader-backed collections. Emitted as static public files in `build()`. A production server serves the built file of a file-backed feed (the static server's `ETag`/`304`); a loader-backed feed and `prunelle dev` keep the live route on `GET <path>` with its own `ETag`/`304`. Use `renderRss()` for synchronous file collections and `await renderRssAsync()` for either.
41
43
 
42
44
  ## Snippets
43
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/content",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Zero-dependency Bun.markdown collections, YAML frontmatter, TOC, and RSS plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-content"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.6.0"
24
+ "prunelle": "^0.7.1"
25
25
  }
26
26
  }
package/src/collection.ts CHANGED
@@ -25,7 +25,6 @@ export {
25
25
  COLLECTION_META_KEY,
26
26
  COLLECTION_OWNER_ROOT_KEY,
27
27
  COLLECTION_VALIDATE_KEY,
28
- COLLECTION_VERSION_KEY,
29
28
  } from './types'
30
29
 
31
30
  export type {
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 '='
@@ -299,8 +305,7 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
299
305
  val += attrSrc[i]!
300
306
  i++
301
307
  }
302
- if (name !== '__proto__' && name !== 'constructor' && name !== 'prototype')
303
- props[name] = val
308
+ setProp(props, name, val)
304
309
  if (i < len) i++
305
310
  }
306
311
  else if (ch === '{') {
@@ -326,25 +331,51 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
326
331
  const expr = attrSrc.slice(exprStart, i).trim()
327
332
  i++ // skip closing '}'
328
333
  try {
329
- props[name] = parseLiteralValue(expr)
334
+ setProp(props, name, parseLiteralValue(expr))
330
335
  }
331
336
  catch {
332
- // 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.`)
333
338
  }
334
339
  }
335
340
  }
336
341
  return props
337
342
  }
338
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
+
339
358
  // Find the end of an opening JSX tag (`>` or `/>`), respecting strings and balanced `{...}` expressions.
340
- 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 {
341
360
  let i = start
342
361
  const len = src.length
343
362
  let braceDepth = 0
344
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
+ }
345
371
 
346
372
  while (i < len) {
347
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
+ }
348
379
  if (inStr !== null) {
349
380
  if (c === '\\') { i += 2; continue }
350
381
  if (c === inStr) inStr = null
@@ -357,7 +388,8 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
357
388
  continue
358
389
  }
359
390
  if (c === '{') {
360
- braceDepth++
391
+ if (++braceDepth > MAX_BRACE_DEPTH)
392
+ return fail()
361
393
  i++
362
394
  continue
363
395
  }
@@ -374,7 +406,7 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
374
406
  }
375
407
  i++
376
408
  }
377
- return undefined
409
+ return fail()
378
410
  }
379
411
 
380
412
  // Returns true when the character at `idx` is escaped by an odd number of preceding backslashes.
@@ -407,10 +439,17 @@ function matchInlineCodeSpan(src: string, start: number): number {
407
439
  return -1
408
440
  }
409
441
 
410
- 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)
411
450
  const closeTag = `</${tagName}>`
412
451
  const len = md.length
413
- let depth = 1
452
+ const open = [start]
414
453
  let pos = start
415
454
  while (pos < len) {
416
455
  const ch = md[pos]!
@@ -425,17 +464,17 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
425
464
  }
426
465
  if (ch === '<') {
427
466
  if (md.startsWith(closeTag, pos)) {
428
- depth--
429
- if (depth === 0)
467
+ closes.set(open.pop()!, pos)
468
+ if (open.length === 0)
430
469
  return pos
431
470
  pos += closeTag.length
432
471
  continue
433
472
  }
434
473
  if (md.startsWith(`<${tagName}`, pos) && /[\s/>]/.test(md[pos + 1 + tagName.length] ?? '')) {
435
- const innerEnd = findTagEnd(md, pos + 1 + tagName.length)
474
+ const innerEnd = findTagEnd(md, pos + 1 + tagName.length, memo)
436
475
  if (innerEnd !== undefined) {
437
476
  if (!innerEnd.selfClosing)
438
- depth++
477
+ open.push(innerEnd.end)
439
478
  pos = innerEnd.end
440
479
  continue
441
480
  }
@@ -443,6 +482,8 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
443
482
  }
444
483
  pos++
445
484
  }
485
+ for (const unclosed of open)
486
+ closes.set(unclosed, -1)
446
487
  return -1
447
488
  }
448
489
 
@@ -457,6 +498,7 @@ export function expandComponents(
457
498
  const names = Object.keys(components)
458
499
  if (names.length === 0)
459
500
  return md
501
+ const memo = createScanMemo()
460
502
 
461
503
  let out = ''
462
504
  let i = 0
@@ -489,14 +531,16 @@ export function expandComponents(
489
531
  }
490
532
 
491
533
  const match = /^<([A-Z][\w]*)(?=[\s/>])/.exec(md.slice(lt))
492
- if (!match || !Object.hasOwn(components, match[1]!)) {
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) {
493
537
  out += md.slice(i, lt + 1)
494
538
  i = lt + 1
495
539
  continue
496
540
  }
497
541
 
498
542
  const tagName = match[1]!
499
- const tagEnd = findTagEnd(md, lt + match[0].length)
543
+ const tagEnd = findTagEnd(md, lt + match[0].length, memo)
500
544
  if (!tagEnd) {
501
545
  out += md.slice(i, lt + 1)
502
546
  i = lt + 1
@@ -505,12 +549,12 @@ export function expandComponents(
505
549
 
506
550
  out += md.slice(i, lt)
507
551
  const attrSrc = md.slice(lt + match[0].length, tagEnd.selfClosing ? tagEnd.end - 2 : tagEnd.end - 1)
508
- const props = parseComponentProps(attrSrc)
552
+ const props = parseComponentProps(attrSrc, tagName, options.file)
509
553
  let afterIndex = tagEnd.end
510
554
 
511
555
  if (!tagEnd.selfClosing) {
512
556
  const closeTag = `</${tagName}>`
513
- const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end)
557
+ const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end, memo)
514
558
  if (closeIdx !== -1) {
515
559
  const innerMd = md.slice(tagEnd.end, closeIdx).trim()
516
560
  const innerRendered = renderMarkdown(innerMd, options)
package/src/entry.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  RenderedMarkdown,
8
8
  RenderMarkdownOptions,
9
9
  } from './types'
10
+ import { devFromEnv } from 'prunelle/internal/server'
10
11
  import { currentApp } from './app'
11
12
  import { renderMarkdown } from './markdown'
12
13
  import { shouldWrapCmsBody, wrapCmsBodyHtml } from './tracking'
@@ -139,7 +140,7 @@ export function buildContentEntry<TData>(params: BuildContentEntryParams<TData>)
139
140
  }
140
141
 
141
142
  export function isDevMode(): boolean {
142
- return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
143
+ return currentApp.dev() ?? devFromEnv()
143
144
  }
144
145
 
145
146
  export function isDraft(data: unknown): boolean {
@@ -10,7 +10,7 @@ import type {
10
10
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
11
11
  import { basename, isAbsolute, join, relative, resolve } from 'node:path'
12
12
  import { isInside } from 'prunelle/config'
13
- import { formatIssuePath, validateSchemaSync } from 'prunelle/server'
13
+ import { formatIssuePath, formatSchemaIssues, validateSchemaSync } from 'prunelle/server'
14
14
  import { currentApp } from './app'
15
15
  import {
16
16
  buildContentEntry,
@@ -28,7 +28,6 @@ import {
28
28
  COLLECTION_DIR_FOR_ROOT_KEY,
29
29
  COLLECTION_META_KEY,
30
30
  COLLECTION_VALIDATE_KEY,
31
- COLLECTION_VERSION_KEY,
32
31
  } from './types'
33
32
 
34
33
  export function resolveCollectionDir(dir: string, explicitRoot?: string): string {
@@ -125,13 +124,20 @@ function validateFileFrontmatter<TData>(
125
124
  rawData,
126
125
  `@prunellejs/content: async frontmatter schema is not supported (${slug})`,
127
126
  )
128
- if (!checked.ok) {
129
- const msg = checked.issues.map(i => i.message).join('; ')
130
- throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${msg}`)
131
- }
127
+ if (!checked.ok)
128
+ throw new Error(`@prunellejs/content: invalid frontmatter in "${absFile}": ${formatSchemaIssues(checked.issues)}`)
132
129
  return checked.value
133
130
  }
134
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
+
135
141
  function findEntryFileCandidate(scanDir: string, clean: string): string | undefined {
136
142
  for (const candidate of [
137
143
  join(scanDir, `${clean}.md`),
@@ -166,7 +172,6 @@ export function createFileCollection<TData = Record<string, unknown>>(
166
172
  const cache = new Map<string, { mtimeMs: number, entry: ContentEntry<TData> }>()
167
173
  const allCache = new Map<string, ContentEntry<TData>[]>()
168
174
  const slugCache = new Map<string, Map<string, ContentEntry<TData>>>()
169
- let cacheVersion = 0
170
175
 
171
176
  const visible = (entry: ContentEntry<TData>): ContentEntry<TData> | null =>
172
177
  !allowsDrafts() && isDraft(entry.data) ? null : entry
@@ -182,7 +187,7 @@ export function createFileCollection<TData = Record<string, unknown>>(
182
187
  return visible(cached.entry)
183
188
 
184
189
  const rawSource = readFileSync(absFile, 'utf8')
185
- const { data: rawData, body } = parseFrontmatter(rawSource)
190
+ const { data: rawData, body } = parseFileFrontmatter(rawSource, absFile)
186
191
  const slug = relative(baseDir, absFile)
187
192
  .replace(/\\/g, '/')
188
193
  .replace(/\.(?:md|markdown)$/, '')
@@ -244,6 +249,9 @@ export function createFileCollection<TData = Record<string, unknown>>(
244
249
  const cachedSlug = slugCache.get(scanDir)?.get(clean)
245
250
  if (cachedSlug !== undefined)
246
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
247
255
  }
248
256
  const candidate = findEntryFileCandidate(scanDir, clean)
249
257
  let found: ContentEntry<TData> | undefined
@@ -279,9 +287,7 @@ export function createFileCollection<TData = Record<string, unknown>>(
279
287
  cache.clear()
280
288
  allCache.clear()
281
289
  slugCache.clear()
282
- cacheVersion++
283
290
  },
284
- [COLLECTION_VERSION_KEY]: () => cacheVersion,
285
291
  [COLLECTION_VALIDATE_KEY]: (root: string) => validateCollectionFiles(resolveCollectionDir(options.dir, root), root, options.schema),
286
292
  [COLLECTION_DIR_FOR_ROOT_KEY]: (root?: string) => resolveCollectionDir(options.dir, root),
287
293
  [COLLECTION_META_KEY]: (root?: string) => {
@@ -1,18 +1,33 @@
1
1
  // YAML frontmatter parsing (via Bun.YAML) and source line lookup for diagnostics.
2
2
 
3
+ const CLOSING_LINE_RE = /^---[ \t]*$/
4
+
5
+ // The YAML between the opening `---` line and the first line that is exactly `---` (the empty block included), and where the body starts.
6
+ function splitFrontmatter(normalized: string): { yaml: string, bodyStart: number } | undefined {
7
+ if (!normalized.startsWith('---\n'))
8
+ return undefined
9
+ let lineStart = 4
10
+ while (lineStart <= normalized.length) {
11
+ const newline = normalized.indexOf('\n', lineStart)
12
+ const lineEnd = newline === -1 ? normalized.length : newline
13
+ if (CLOSING_LINE_RE.test(normalized.slice(lineStart, lineEnd)))
14
+ return { yaml: normalized.slice(4, lineStart - 1), bodyStart: lineEnd + 1 }
15
+ if (newline === -1)
16
+ return undefined
17
+ lineStart = newline + 1
18
+ }
19
+ return undefined
20
+ }
21
+
3
22
  /** Parses full nested YAML frontmatter using Bun's native Zig `Bun.YAML.parse`. */
4
23
  export function parseFrontmatter(source: string): { data: Record<string, unknown>, body: string } {
5
24
  const normalized = source.replace(/\r\n/g, '\n')
6
- if (!normalized.startsWith('---\n'))
7
- return { data: {}, body: normalized }
8
-
9
- const end = normalized.indexOf('\n---', 4)
10
- if (end === -1)
25
+ const split = splitFrontmatter(normalized)
26
+ if (split === undefined)
11
27
  return { data: {}, body: normalized }
12
28
 
13
- const rawYaml = normalized.slice(4, end)
14
- const restStart = normalized.indexOf('\n', end + 4)
15
- const body = restStart === -1 ? '' : normalized.slice(restStart + 1)
29
+ const rawYaml = split.yaml
30
+ const body = normalized.slice(split.bodyStart)
16
31
 
17
32
  const parsed = rawYaml.trim() === '' ? {} : Bun.YAML.parse(rawYaml)
18
33
  const data = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
@@ -24,17 +39,15 @@ export function parseFrontmatter(source: string): { data: Record<string, unknown
24
39
  /** Finds the 1-based line number of a top-level frontmatter key for `prunelle check` diagnostics. */
25
40
  export function findFrontmatterFieldLine(rawSource: string, fieldPath: string | undefined): number {
26
41
  const normalized = rawSource.replace(/\r\n/g, '\n')
27
- if (!normalized.startsWith('---\n'))
28
- return 1
29
- const end = normalized.indexOf('\n---', 4)
30
- if (end === -1)
42
+ const split = splitFrontmatter(normalized)
43
+ if (split === undefined)
31
44
  return 1
32
45
  if (!fieldPath)
33
46
  return 2
34
47
  const topKey = fieldPath.split('.')[0] ?? fieldPath
35
48
  const escaped = topKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
36
49
  const keyRe = new RegExp(`^\\s*${escaped}\\s*:`)
37
- const lines = normalized.slice(4, end).split('\n')
50
+ const lines = split.yaml.split('\n')
38
51
  for (let i = 0; i < lines.length; i++) {
39
52
  if (keyRe.test(lines[i]!))
40
53
  return i + 2
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  COLLECTION_DIR_FOR_ROOT_KEY,
13
13
  COLLECTION_OWNER_ROOT_KEY,
14
14
  COLLECTION_VALIDATE_KEY,
15
- COLLECTION_VERSION_KEY,
15
+
16
16
  DEFINE_COLLECTION_RE,
17
17
  discoverAppCollections,
18
18
  registeredCollections,
@@ -78,6 +78,10 @@ function discoverStaticCollectionDirs(root: string): string[] {
78
78
  return found
79
79
  }
80
80
 
81
+ function feedFile(feed: ContentFeed): string {
82
+ return (feed.path ?? '/rss.xml').replace(/^\/+/, '')
83
+ }
84
+
81
85
  export function content<const TDataList extends readonly unknown[] = readonly unknown[]>(options?: {
82
86
  feeds?: { [K in keyof TDataList]: RssFeedConfig<TDataList[K], AnyCollection<TDataList[K]>> } | undefined
83
87
  collections?: readonly AnyCollection<unknown>[] | undefined
@@ -166,10 +170,15 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
166
170
  },
167
171
  async build(ctx) {
168
172
  ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
173
+ const emittedFeeds: string[] = []
169
174
  for (const feed of feeds) {
170
- const rel = (feed.path ?? '/rss.xml').replace(/^\/+/, '')
175
+ const rel = feedFile(feed)
171
176
  ctx.emitPublic(rel, await renderRssAsync({ ...feed, site: feed.site ?? ctx.site } as RssFeedConfig<unknown, AnyCollection<unknown>>))
177
+ // A loader-backed feed changes without a rebuild, so it keeps its runtime route over the built file.
178
+ if (feed.collection.dir !== undefined)
179
+ emittedFeeds.push(rel)
172
180
  }
181
+ ctx.setData({ emittedFeeds })
173
182
  },
174
183
  afterPrerender(ctx) {
175
184
  ctx.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
@@ -178,24 +187,15 @@ export function content(options: { feeds?: readonly ContentFeed[] | undefined, c
178
187
  api.provide(CONTENT_COLLECTIONS_SERVICE, collectionsService)
179
188
  if (api.config?.prerender === true)
180
189
  api.provide(CONTENT_PRERENDER_SERVICE, true)
190
+ const emitted = new Set(api.getBuildData<{ emittedFeeds?: string[] }>()?.emittedFeeds ?? [])
181
191
  for (const feed of feeds) {
182
192
  const path = feed.path ?? '/rss.xml'
183
- const isFileBacked = feed.collection.dir !== undefined
184
- let memo: { xml: string, etag: string, version: number } | undefined
193
+ // Plugin routes shadow public files: a production server serves the file the build already wrote.
194
+ if (!api.dev && emitted.has(feedFile(feed)))
195
+ continue
185
196
  api.route('GET', path, async (ctx) => {
186
- const versionFn = (feed.collection as unknown as Record<symbol, (() => number) | undefined>)[COLLECTION_VERSION_KEY]
187
- const version = versionFn ? versionFn() : -1
188
- let current: { xml: string, etag: string }
189
- if (isFileBacked && !api.dev && memo !== undefined && memo.version === version) {
190
- current = memo
191
- }
192
- else {
193
- const xml = await renderRssAsync({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown, AnyCollection<unknown>>)
194
- const etag = `"${Bun.hash(xml).toString(36)}"`
195
- current = { xml, etag }
196
- if (isFileBacked)
197
- memo = { xml, etag, version }
198
- }
197
+ const xml = await renderRssAsync({ ...feed, site: feed.site ?? api.site } as RssFeedConfig<unknown, AnyCollection<unknown>>)
198
+ const current = { xml, etag: `"${Bun.hash(xml).toString(36)}"` }
199
199
  if (etagMatches(ctx.request.headers.get('if-none-match'), current.etag)) {
200
200
  return new Response(null, {
201
201
  status: 304,
@@ -28,7 +28,6 @@ import {
28
28
  COLLECTION_DIR_FOR_ROOT_KEY,
29
29
  COLLECTION_META_KEY,
30
30
  COLLECTION_VALIDATE_KEY,
31
- COLLECTION_VERSION_KEY,
32
31
  } from './types'
33
32
 
34
33
  function cleanSlug(rawSlug: unknown, collectionName: string): string {
@@ -67,7 +66,7 @@ async function validateLoadedEntriesForCheck(params: {
67
66
  defaultLocale: string
68
67
  locales: readonly string[] | undefined
69
68
  schema: StandardSchemaV1 | undefined
70
- load: LoaderCollectionOptions<unknown>['load']
69
+ load: (ctx: { locale?: string | undefined }) => Promise<LoadedEntryInput[]>
71
70
  }): Promise<string[]> {
72
71
  const { name, root, sourceFile, localized, defaultLocale, locales, schema, load } = params
73
72
  const prefix = formatCheckPrefix(root, sourceFile)
@@ -122,10 +121,78 @@ async function validateLoadedEntriesForCheck(params: {
122
121
  return errors
123
122
  }
124
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
+
125
189
  export function createLoaderCollection<TData = Record<string, unknown>>(
126
190
  options: LoaderCollectionOptions<TData>,
127
191
  ): AsyncCollection<TData> {
128
192
  const name = options.name ?? 'collection'
193
+ checkDurations(name, options)
194
+ const ttlMs = options.ttlMs ?? 0
195
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
129
196
  const localized = options.localized ?? false
130
197
  const getDefaultLocale = (): string => options.defaultLocale ?? currentApp.defaultLocale() ?? 'en'
131
198
  const allowsDrafts = (): boolean => options.includeDrafts ?? isDevMode()
@@ -135,14 +202,16 @@ export function createLoaderCollection<TData = Record<string, unknown>>(
135
202
  let buildCache = new WeakMap<AppRuntimeContext, Map<string, Promise<ContentEntry<TData>[]>>>()
136
203
  let requestCache = new WeakMap<RequestContext, Map<string, Promise<ContentEntry<TData>[]>>>()
137
204
  let lastBuildCtx: WeakRef<AppRuntimeContext> | undefined
138
- let cacheVersion = 0
205
+ const runner = createLoadRunner(name, timeoutMs, options.load)
206
+ const shared = createSharedLoads<TData>(ttlMs)
139
207
 
140
- function resolveCacheMap(): Map<string, Promise<ContentEntry<TData>[]>> | undefined {
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 {
141
210
  const reqCtx = currentRequest()?.ctx
142
211
  const appCtx = getAppContext()
143
212
  if (reqCtx === undefined && appCtx !== undefined) {
144
213
  lastBuildCtx = new WeakRef(appCtx)
145
- return getOrCreateLocaleMap(buildCache, appCtx)
214
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
146
215
  }
147
216
  if (reqCtx !== undefined) {
148
217
  const buildCtx = lastBuildCtx?.deref()
@@ -152,16 +221,17 @@ export function createLoaderCollection<TData = Record<string, unknown>>(
152
221
  && appCtx.root === buildCtx.root
153
222
  && appCtx.outDir === buildCtx.outDir
154
223
  )
155
- return getOrCreateLocaleMap(buildCache, buildCtx)
224
+ return { bucket: getOrCreateLocaleMap(buildCache, buildCtx), runtime: false }
156
225
  if (appCtx?.inject(CONTENT_PRERENDER_SERVICE) === true)
157
- return getOrCreateLocaleMap(buildCache, appCtx)
158
- return getOrCreateLocaleMap(requestCache, reqCtx)
226
+ return { bucket: getOrCreateLocaleMap(buildCache, appCtx), runtime: false }
227
+ return { bucket: getOrCreateLocaleMap(requestCache, reqCtx), runtime: true }
159
228
  }
160
229
  return undefined
161
230
  }
162
231
 
232
+
163
233
  async function loadValidatedEntries(targetLocale: string | undefined): Promise<ContentEntry<TData>[]> {
164
- const rawEntries = await options.load(localized ? { locale: targetLocale } : {})
234
+ const rawEntries = await runner.run(localized ? { locale: targetLocale } : {})
165
235
  const entries: ContentEntry<TData>[] = []
166
236
  for (const raw of rawEntries) {
167
237
  if (localized && raw.locale !== undefined && raw.locale !== targetLocale)
@@ -198,19 +268,19 @@ export function createLoaderCollection<TData = Record<string, unknown>>(
198
268
  function loadCached(locale?: string): Promise<ContentEntry<TData>[]> {
199
269
  const targetLocale = localized ? (locale ?? getDefaultLocale()) : undefined
200
270
  const cacheKey = targetLocale ?? ''
201
- const bucket = resolveCacheMap()
202
- if (bucket !== undefined) {
203
- const hit = bucket.get(cacheKey)
204
- if (hit !== undefined)
205
- return hit
206
- const pending = loadValidatedEntries(targetLocale).catch((err) => {
207
- bucket.delete(cacheKey)
208
- throw err
209
- })
210
- bucket.set(cacheKey, pending)
211
- return pending
212
- }
213
- return loadValidatedEntries(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
214
284
  }
215
285
 
216
286
  async function all(locale?: string): Promise<ContentEntry<TData>[]> {
@@ -234,9 +304,9 @@ export function createLoaderCollection<TData = Record<string, unknown>>(
234
304
  buildCache = new WeakMap()
235
305
  requestCache = new WeakMap()
236
306
  lastBuildCtx = undefined
237
- cacheVersion++
307
+ shared.clear()
308
+ runner.cancelAll()
238
309
  },
239
- [COLLECTION_VERSION_KEY]: () => cacheVersion,
240
310
  [COLLECTION_VALIDATE_KEY]: (root: string) => validateLoadedEntriesForCheck({
241
311
  name,
242
312
  root,
@@ -245,7 +315,7 @@ export function createLoaderCollection<TData = Record<string, unknown>>(
245
315
  defaultLocale: getDefaultLocale(),
246
316
  locales: options.locales,
247
317
  schema: options.schema,
248
- load: options.load,
318
+ load: runner.run,
249
319
  }),
250
320
  [COLLECTION_DIR_FOR_ROOT_KEY]: () => undefined,
251
321
  [COLLECTION_META_KEY]: () => ({
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
@@ -34,7 +34,8 @@ function findDefaultImageResolver(file: string | undefined): MarkdownImageResolv
34
34
  }
35
35
 
36
36
  // CommonMark §4.5: backtick fence info strings cannot contain backticks; fences cannot mix ` and ~.
37
- const FENCE_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))\n([\s\S]*?)^\1\3[ \t]*$/gm
37
+ const FENCE_OPEN_RE = /^(?:(`{3,})([^`\n]*)|(~{3,})([^\n]*))$/
38
+ const FENCE_CLOSE_RE = /^(`{3,}|~{3,})[ \t]*\r?$/
38
39
  let slotBatchId = 0
39
40
 
40
41
  function renderMarkdownInternal(
@@ -56,15 +57,7 @@ function renderMarkdownInternal(
56
57
 
57
58
  // 1. Extract fenced code blocks before component expansion so `<Tag>` inside ```code``` is never treated as a component
58
59
  if (options.highlight !== undefined || options.components !== undefined) {
59
- processed = processed.replace(FENCE_RE, (
60
- full,
61
- btFence: string | undefined,
62
- btInfo: string | undefined,
63
- _tildeFence: string | undefined,
64
- tildeInfo: string | undefined,
65
- code: string,
66
- ) => {
67
- const info = btFence !== undefined ? (btInfo ?? '') : (tildeInfo ?? '')
60
+ processed = replaceFences(processed, (full, info, code) => {
68
61
  if (options.highlight !== undefined) {
69
62
  const lang = info.trim().split(/\s+/)[0] || undefined
70
63
  const idx = slots.length
@@ -128,7 +121,10 @@ function renderMarkdownInternal(
128
121
  ? undefined
129
122
  : (options.resolveImage ?? findDefaultImageResolver(options.file))
130
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
131
126
  html = html.replace(/<img\b([^>]*?)>/gi, (full, attrs: string) => {
127
+ const first = seen++ === 0
132
128
  const srcMatch = /\bsrc="([^"]+)"/i.exec(attrs)
133
129
  if (!srcMatch)
134
130
  return full
@@ -147,7 +143,7 @@ function renderMarkdownInternal(
147
143
  parts.push(`width="${info.width}"`)
148
144
  if (info.height !== undefined && info.height > 0)
149
145
  parts.push(`height="${info.height}"`)
150
- parts.push(`loading="${info.loading ?? 'lazy'}"`, 'decoding="async"')
146
+ parts.push(`loading="${info.loading ?? (first ? 'eager' : 'lazy')}"`, 'decoding="async"')
151
147
  const imgTag = `<img ${parts.join(' ')}>`
152
148
  if (info.avifSrcset) {
153
149
  const sizesAttr = info.sizes ? ` sizes="${escAttr(info.sizes)}"` : ''
@@ -181,3 +177,42 @@ export function renderMarkdown(body: string, options: RenderMarkdownOptions = {}
181
177
  } {
182
178
  return renderMarkdownInternal(body, options)
183
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 CHANGED
@@ -1,8 +1,8 @@
1
1
  // Process-level collection registry and `src/` file discovery for `prunelle check` and `CONTENT_COLLECTIONS_SERVICE`.
2
2
 
3
3
  import type { InternalCollection } from './types'
4
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
- import { isAbsolute, join, resolve } from 'node:path'
4
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
5
+ import { isAbsolute, join, relative, resolve } from 'node:path'
6
6
  import { currentApp } from './app'
7
7
  import { COLLECTION_OWNER_ROOT_KEY, COLLECTION_VALIDATE_KEY } from './types'
8
8
 
@@ -87,6 +87,9 @@ function importAppTsxWithPrunelleJsx(root: string): void {
87
87
  })
88
88
  }
89
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
+
90
93
  export async function discoverAppCollections(root: string): Promise<void> {
91
94
  const absRoot = resolve(root)
92
95
  const prevDiscoverRoot = discoverRoot
@@ -97,19 +100,27 @@ export async function discoverAppCollections(root: string): Promise<void> {
97
100
  importAppTsxWithPrunelleJsx(absRoot)
98
101
  const srcDir = resolve(absRoot, 'src')
99
102
  for (const file of walkCollectionDefFiles(srcDir)) {
103
+ const seenKey = `${absRoot}\0${file}`
100
104
  let text: string
105
+ let mtimeMs: number
101
106
  try {
107
+ mtimeMs = statSync(file).mtimeMs
108
+ if (seenFiles.get(seenKey)?.mtimeMs === mtimeMs)
109
+ continue
102
110
  text = readFileSync(file, 'utf8')
103
111
  }
104
112
  catch {
105
113
  continue
106
114
  }
115
+ const failedBefore = seenFiles.get(seenKey)?.failed === true
116
+ seenFiles.set(seenKey, { mtimeMs, failed: false })
107
117
  if (!DEFINE_COLLECTION_RE.test(text))
108
118
  continue
109
119
  discoverFile = file
110
120
  discoverIndex = 0
111
121
  try {
112
- const mod = await import(file) as Record<string, unknown>
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>
113
124
  for (const val of Object.values(mod)) {
114
125
  if (val !== null && typeof val === 'object' && COLLECTION_VALIDATE_KEY in val) {
115
126
  const col = val as InternalCollection
@@ -121,9 +132,10 @@ export async function discoverAppCollections(root: string): Promise<void> {
121
132
  }
122
133
  }
123
134
  }
124
- catch {
125
- // Route/TSX files may import virtual modules (~icons) or CSS outside Bun.build; skip unimportable files.
126
- continue
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}`)
127
139
  }
128
140
  }
129
141
  }
package/src/rss.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // RSS 2.0 XML feed generation and ETag matching for @prunellejs/content.
2
2
 
3
3
  import type { AnyCollection, Collection, ContentEntry } from './types'
4
- import { escAttr } from 'prunelle/server'
4
+ import { escXml } from 'prunelle/server'
5
5
  import { currentApp } from './app'
6
6
 
7
7
  export interface RssFeedConfig<
@@ -69,15 +69,15 @@ function buildRssXml<TData>(
69
69
  }
70
70
  const link = mapped.link ?? `${site}${prefix}/${entry.slug}`
71
71
  const pubDate = formatPubDate(mapped.date)
72
- const desc = mapped.description ? `<description>${escAttr(mapped.description)}</description>` : ''
73
- return `<item><title>${escAttr(mapped.title)}</title><link>${escAttr(link)}</link><guid>${escAttr(link)}</guid>${pubDate}${desc}</item>`
72
+ const desc = mapped.description ? `<description>${escXml(mapped.description)}</description>` : ''
73
+ return `<item><title>${escXml(mapped.title)}</title><link>${escXml(link)}</link><guid>${escXml(link)}</guid>${pubDate}${desc}</item>`
74
74
  }).join('')
75
75
 
76
76
  return `<?xml version="1.0" encoding="UTF-8"?>`
77
77
  + `<rss version="2.0"><channel>`
78
- + `<title>${escAttr(feed.title)}</title>`
79
- + `<link>${escAttr(site)}</link>`
80
- + `<description>${escAttr(feed.description)}</description>`
78
+ + `<title>${escXml(feed.title)}</title>`
79
+ + `<link>${escXml(site)}</link>`
80
+ + `<description>${escXml(feed.description)}</description>`
81
81
  + items
82
82
  + `</channel></rss>`
83
83
  }
package/src/tracking.ts CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { AccessedContentEntry } from 'prunelle/config'
4
4
  import type { RequestContext } from 'prunelle/server'
5
- import { currentRequest } from 'prunelle/internal/server'
5
+ import { currentRequest, devFromEnv } from 'prunelle/internal/server'
6
6
  import { currentApp } from './app'
7
7
 
8
8
  const MAX_TRACKED_ENTRIES = 50
@@ -26,7 +26,7 @@ function encodeCmsAnchorPart(value: string): string {
26
26
  }
27
27
 
28
28
  function isDevActive(): boolean {
29
- return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
29
+ return currentApp.dev() ?? devFromEnv()
30
30
  }
31
31
 
32
32
  /** Records a file-backed entry read during the active dev request (`primary: true` for `.get()`, `false` for `.all()`). */
package/src/types.ts CHANGED
@@ -3,7 +3,6 @@
3
3
  import type { ContentImageResolver, ContentImageResult } from 'prunelle/config'
4
4
  import type { StandardSchemaV1 } from 'prunelle/server'
5
5
 
6
- export const COLLECTION_VERSION_KEY = Symbol.for('pru.content.collectionVersion')
7
6
  export const COLLECTION_VALIDATE_KEY = Symbol.for('pru.content.validateAll')
8
7
  export const COLLECTION_DIR_FOR_ROOT_KEY = Symbol.for('pru.content.dirForRoot')
9
8
  export const COLLECTION_OWNER_ROOT_KEY = Symbol.for('pru.content.ownerRoot')
@@ -82,6 +81,8 @@ export interface RenderMarkdownOptions {
82
81
  export interface CollectionLoadContext {
83
82
  /** Requested locale when `localized: true`; `undefined` otherwise. */
84
83
  readonly locale?: string | undefined
84
+ /** Aborted after `timeoutMs` or when the collection's cache is cleared: pass it to `fetch()` or the database client. */
85
+ readonly signal: AbortSignal
85
86
  }
86
87
 
87
88
  export interface LoadedEntryInput {
@@ -98,7 +99,7 @@ export interface LoadedEntryInput {
98
99
  }
99
100
 
100
101
  export type CollectionLoader = (
101
- ctx?: CollectionLoadContext,
102
+ ctx: CollectionLoadContext,
102
103
  ) => LoadedEntryInput[] | Promise<LoadedEntryInput[]>
103
104
 
104
105
  export interface BaseCollectionOptions<TData = Record<string, unknown>> {
@@ -149,6 +150,10 @@ export interface LoaderCollectionOptions<TData = Record<string, unknown>> extend
149
150
  dir?: undefined
150
151
  /** Async or sync loader returning entries from a headless CMS, database, or API. */
151
152
  load: CollectionLoader
153
+ /** At runtime, how long every request reuses the entries of a finished load, per locale (default: 0, a load per request; `Infinity` keeps them until the cache is cleared). */
154
+ ttlMs?: number | undefined
155
+ /** How long a load may run before its signal aborts and the load fails (default: 30,000). */
156
+ timeoutMs?: number | undefined
152
157
  }
153
158
 
154
159
  export interface LoaderCollectionOptionsWithSchema<TData> extends Omit<LoaderCollectionOptions<TData>, 'schema'> {
@@ -190,7 +195,6 @@ export interface InternalCollection {
190
195
  all(locale?: string): ContentEntry<unknown>[] | Promise<ContentEntry<unknown>[]>
191
196
  get(slug: string, locale?: string): ContentEntry<unknown> | undefined | Promise<ContentEntry<unknown> | undefined>
192
197
  clearCache(): void
193
- [COLLECTION_VERSION_KEY]?: () => number
194
198
  [COLLECTION_VALIDATE_KEY]?: (root: string) => string[] | Promise<string[]>
195
199
  [COLLECTION_DIR_FOR_ROOT_KEY]?: (root?: string) => string | undefined
196
200
  [COLLECTION_OWNER_ROOT_KEY]?: string | undefined
package/src/sanitize.ts DELETED
@@ -1,309 +0,0 @@
1
- // HTML allow-list sanitizer applied to rendered Markdown: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
-
3
- const DROP_CONTENT_TAGS = new Set([
4
- 'script',
5
- 'style',
6
- 'iframe',
7
- 'object',
8
- 'applet',
9
- 'noscript',
10
- 'template',
11
- ])
12
-
13
- const ALLOWED_MD_TAGS = new Set([
14
- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
- 'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
16
- 'a', 'img', 'picture', 'source',
17
- 'pre', 'code', 'kbd', 'samp', 'var',
18
- 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
19
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
20
- 'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
21
- 'details', 'summary', 'figure', 'figcaption',
22
- 'input',
23
- ])
24
-
25
- // Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
26
- const GLOBAL_ALLOWED_ATTRS = new Set([
27
- 'class',
28
- 'title',
29
- 'lang',
30
- 'dir',
31
- 'role',
32
- 'aria-label',
33
- 'aria-hidden',
34
- 'aria-current',
35
- 'aria-expanded',
36
- 'aria-level',
37
- 'aria-description',
38
- 'aria-roledescription',
39
- ])
40
-
41
- const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
42
- a: new Set(['href', 'rel', 'target', 'hreflang']),
43
- img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
44
- source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
45
- blockquote: new Set(['cite']),
46
- q: new Set(['cite']),
47
- del: new Set(['cite', 'datetime']),
48
- ins: new Set(['cite', 'datetime']),
49
- time: new Set(['datetime']),
50
- ol: new Set(['start', 'reversed', 'type']),
51
- li: new Set(['value']),
52
- th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
53
- td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
54
- col: new Set(['span', 'align']),
55
- colgroup: new Set(['span', 'align']),
56
- details: new Set(['open']),
57
- }
58
-
59
- const URL_ATTRS = new Set(['href', 'src', 'cite'])
60
- const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
61
- const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
62
- const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
63
-
64
- function decodeHtmlEntities(rawVal: string): string {
65
- return rawVal
66
- .replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
67
- const cp = Number.parseInt(hex, 16)
68
- return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
69
- })
70
- .replace(/&#([0-9]+);?/g, (_, dec: string) => {
71
- const cp = Number.parseInt(dec, 10)
72
- return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
73
- })
74
- .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
75
- const lower = name.toLowerCase()
76
- if (lower === 'colon') return ':'
77
- if (lower === 'tab') return '\t'
78
- if (lower === 'newline') return '\n'
79
- return '&'
80
- })
81
- }
82
-
83
- function isSafeUrl(val: string): boolean {
84
- const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
85
- if (cleaned === '')
86
- return true
87
- if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
88
- return true
89
- if (HAS_SCHEME_RE.test(cleaned))
90
- return false
91
- return true
92
- }
93
-
94
- function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
95
- const attrs: Array<{ name: string, value: string | null }> = []
96
- let i = 0
97
- const len = attrSrc.length
98
- while (i < len) {
99
- while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
100
- if (i >= len) break
101
- const nameStart = i
102
- while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
103
- const name = attrSrc.slice(nameStart, i).toLowerCase()
104
- if (!name) {
105
- i++
106
- continue
107
- }
108
- while (i < len && /\s/.test(attrSrc[i]!)) i++
109
- if (attrSrc[i] !== '=') {
110
- attrs.push({ name, value: null })
111
- continue
112
- }
113
- i++ // skip '='
114
- while (i < len && /\s/.test(attrSrc[i]!)) i++
115
- if (i >= len) {
116
- attrs.push({ name, value: '' })
117
- break
118
- }
119
- const quote = attrSrc[i]!
120
- if (quote === '"' || quote === '\'') {
121
- i++
122
- const valStart = i
123
- while (i < len && attrSrc[i] !== quote) i++
124
- attrs.push({ name, value: attrSrc.slice(valStart, i) })
125
- if (i < len) i++
126
- }
127
- else {
128
- const valStart = i
129
- while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
130
- attrs.push({ name, value: attrSrc.slice(valStart, i) })
131
- }
132
- }
133
- return attrs
134
- }
135
-
136
- function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
137
- const typeAttr = rawAttrs.find(a => a.name === 'type')
138
- if (typeAttr?.value?.toLowerCase() !== 'checkbox')
139
- return ''
140
- const safeParts = ['type="checkbox"']
141
- for (const a of rawAttrs) {
142
- if (a.name === 'class' && a.value !== null)
143
- safeParts.push(`class="${a.value.replaceAll('"', '&quot;')}"`)
144
- else if (a.name === 'disabled')
145
- safeParts.push('disabled')
146
- else if (a.name === 'checked')
147
- safeParts.push('checked')
148
- }
149
- return `<input ${safeParts.join(' ')}>`
150
- }
151
-
152
- type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
153
-
154
- function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
155
- if (value === null || allowed === undefined)
156
- return false
157
- if (typeof allowed === 'string')
158
- return value.startsWith(allowed)
159
- for (const prefix of allowed) {
160
- if (value.startsWith(prefix))
161
- return true
162
- }
163
- return false
164
- }
165
-
166
- function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
167
- if (tagName === 'div' && name === 'data-pru-md-slot')
168
- return matchesSlotPrefix(value, slotPrefixes)
169
- return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
170
- }
171
-
172
- function sanitizeAttributes(
173
- tagName: string,
174
- rawAttrs: Array<{ name: string, value: string | null }>,
175
- slotPrefixes: AllowedSlotPrefixes,
176
- ): string[] {
177
- const safeParts: string[] = []
178
- for (const a of rawAttrs) {
179
- if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
180
- continue
181
- if (URL_ATTRS.has(a.name)) {
182
- if (a.value === null || !isSafeUrl(a.value))
183
- continue
184
- }
185
- else if (a.name === 'srcset' && a.value !== null) {
186
- const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
187
- if (!candidates.every(isSafeUrl))
188
- continue
189
- }
190
- if (a.value === null)
191
- safeParts.push(a.name)
192
- else
193
- safeParts.push(`${a.name}="${a.value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}"`)
194
- }
195
- return safeParts
196
- }
197
-
198
- function findTagEndOffset(html: string, start: number): number {
199
- let tagEnd = start
200
- const len = html.length
201
- let inQuote: string | null = null
202
- while (tagEnd < len) {
203
- const c = html[tagEnd]!
204
- if (inQuote !== null) {
205
- if (c === inQuote)
206
- inQuote = null
207
- }
208
- else if (c === '"' || c === '\'') {
209
- inQuote = c
210
- }
211
- else if (c === '>') {
212
- return tagEnd
213
- }
214
- tagEnd++
215
- }
216
- return -1
217
- }
218
-
219
- function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
- let out = ''
221
- let i = 0
222
- const len = html.length
223
-
224
- while (i < len) {
225
- const lt = html.indexOf('<', i)
226
- if (lt === -1) {
227
- out += html.slice(i)
228
- break
229
- }
230
- out += html.slice(i, lt)
231
-
232
- // Strip HTML comments (including HTML5 `--!>` closer)
233
- if (html.startsWith('<!--', lt)) {
234
- const endStd = html.indexOf('-->', lt + 4)
235
- const endBang = html.indexOf('--!>', lt + 4)
236
- if (endStd === -1 && endBang === -1)
237
- i = len
238
- else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
239
- i = endBang + 4
240
- else
241
- i = endStd + 3
242
- continue
243
- }
244
-
245
- let pos = lt + 1
246
- const isClosing = html[pos] === '/'
247
- if (isClosing)
248
- pos++
249
-
250
- const nameStart = pos
251
- while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
- const tagName = html.slice(nameStart, pos).toLowerCase()
253
- if (!tagName) {
254
- out += '&lt;'
255
- i = lt + 1
256
- continue
257
- }
258
-
259
- const tagEnd = findTagEndOffset(html, pos)
260
- if (tagEnd === -1)
261
- break
262
-
263
- const attrSrc = html.slice(pos, tagEnd)
264
- const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
- i = tagEnd + 1
266
-
267
- if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
268
- if (!selfClosing) {
269
- const closeRe = new RegExp(`</${tagName}\\b[^>]*>`, 'gi')
270
- closeRe.lastIndex = i
271
- const m = closeRe.exec(html)
272
- i = m ? m.index + m[0].length : len
273
- }
274
- continue
275
- }
276
-
277
- if (!ALLOWED_MD_TAGS.has(tagName))
278
- continue
279
-
280
- if (isClosing) {
281
- if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
- out += `</${tagName}>`
283
- continue
284
- }
285
-
286
- const rawAttrs = parseTagAttributes(attrSrc)
287
- if (tagName === 'input') {
288
- out += sanitizeInputTag(rawAttrs)
289
- continue
290
- }
291
-
292
- const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
- const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
294
- out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
- }
296
-
297
- return out
298
- }
299
-
300
- export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
301
- let current = html
302
- for (let pass = 0; pass < 3; pass++) {
303
- const next = sanitizePass(current, slotPrefixes)
304
- if (next === current)
305
- return next
306
- current = next
307
- }
308
- return current
309
- }