@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
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
|
|
285
|
+
setProp(props, name, true)
|
|
280
286
|
continue
|
|
281
287
|
}
|
|
282
288
|
i++ // skip '='
|
|
@@ -286,13 +292,21 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
|
|
|
286
292
|
if (ch === '"' || ch === '\'') {
|
|
287
293
|
const quote = ch
|
|
288
294
|
i++
|
|
289
|
-
|
|
295
|
+
let val = ''
|
|
290
296
|
while (i < len && attrSrc[i] !== quote) {
|
|
291
|
-
if (attrSrc[i] === '\\')
|
|
297
|
+
if (attrSrc[i] === '\\' && i + 1 < len) {
|
|
298
|
+
const next = attrSrc[i + 1]!
|
|
299
|
+
if (next === quote || next === '\\') {
|
|
300
|
+
val += next
|
|
301
|
+
i += 2
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
val += attrSrc[i]!
|
|
292
306
|
i++
|
|
293
307
|
}
|
|
294
|
-
props
|
|
295
|
-
i++
|
|
308
|
+
setProp(props, name, val)
|
|
309
|
+
if (i < len) i++
|
|
296
310
|
}
|
|
297
311
|
else if (ch === '{') {
|
|
298
312
|
let depth = 0
|
|
@@ -317,25 +331,62 @@ function parseComponentProps(attrSrc: string): Record<string, unknown> {
|
|
|
317
331
|
const expr = attrSrc.slice(exprStart, i).trim()
|
|
318
332
|
i++ // skip closing '}'
|
|
319
333
|
try {
|
|
320
|
-
props
|
|
334
|
+
setProp(props, name, parseLiteralValue(expr))
|
|
321
335
|
}
|
|
322
336
|
catch {
|
|
323
|
-
|
|
337
|
+
throw new Error(`@prunellejs/content: the prop "${name}" of <${tag}> in "${file ?? 'the markdown source'}" is not a literal (${expr}): write a string, number, boolean, array or object literal, or compute the value inside the component.`)
|
|
324
338
|
}
|
|
325
339
|
}
|
|
326
340
|
}
|
|
327
341
|
return props
|
|
328
342
|
}
|
|
329
343
|
|
|
344
|
+
// What one expansion pass has learnt about the source, so no scan is run twice over the same ground.
|
|
345
|
+
export interface ScanMemo {
|
|
346
|
+
// Per-offset 4-bit mask of failed tag-end states at braceDepth === 0: bit 0 none, bit 1 `"`, bit 2 `'`, bit 3 `` ` ``.
|
|
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
|
+
|
|
358
|
+
function strStateBit(inStr: string | null): number {
|
|
359
|
+
if (inStr === null)
|
|
360
|
+
return 1
|
|
361
|
+
if (inStr === '"')
|
|
362
|
+
return 2
|
|
363
|
+
return inStr === '\'' ? 4 : 8
|
|
364
|
+
}
|
|
365
|
+
|
|
330
366
|
// Find the end of an opening JSX tag (`>` or `/>`), respecting strings and balanced `{...}` expressions.
|
|
331
|
-
function findTagEnd(src: string, start: number): { end: number, selfClosing: boolean } | undefined {
|
|
367
|
+
function findTagEnd(src: string, start: number, memo: ScanMemo): { end: number, selfClosing: boolean } | undefined {
|
|
332
368
|
let i = start
|
|
333
369
|
const len = src.length
|
|
334
370
|
let braceDepth = 0
|
|
335
371
|
let inStr: string | null = null
|
|
372
|
+
const crossed: number[] = []
|
|
373
|
+
const fail = (): undefined => {
|
|
374
|
+
const failedAt = memo.failedAt ??= new Uint8Array(len)
|
|
375
|
+
for (let k = 0; k < crossed.length; k += 2) {
|
|
376
|
+
const at = crossed[k]!
|
|
377
|
+
failedAt[at] = (failedAt[at] ?? 0) | crossed[k + 1]!
|
|
378
|
+
}
|
|
379
|
+
return undefined
|
|
380
|
+
}
|
|
336
381
|
|
|
337
382
|
while (i < len) {
|
|
338
383
|
const c = src[i]!
|
|
384
|
+
if (braceDepth === 0) {
|
|
385
|
+
const bit = strStateBit(inStr)
|
|
386
|
+
if (((memo.failedAt?.[i] ?? 0) & bit) !== 0)
|
|
387
|
+
return fail()
|
|
388
|
+
crossed.push(i, bit)
|
|
389
|
+
}
|
|
339
390
|
if (inStr !== null) {
|
|
340
391
|
if (c === '\\') { i += 2; continue }
|
|
341
392
|
if (c === inStr) inStr = null
|
|
@@ -348,7 +399,8 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
|
|
|
348
399
|
continue
|
|
349
400
|
}
|
|
350
401
|
if (c === '{') {
|
|
351
|
-
braceDepth
|
|
402
|
+
if (++braceDepth > MAX_BRACE_DEPTH)
|
|
403
|
+
return fail()
|
|
352
404
|
i++
|
|
353
405
|
continue
|
|
354
406
|
}
|
|
@@ -365,7 +417,7 @@ function findTagEnd(src: string, start: number): { end: number, selfClosing: boo
|
|
|
365
417
|
}
|
|
366
418
|
i++
|
|
367
419
|
}
|
|
368
|
-
return
|
|
420
|
+
return fail()
|
|
369
421
|
}
|
|
370
422
|
|
|
371
423
|
// Returns true when the character at `idx` is escaped by an odd number of preceding backslashes.
|
|
@@ -398,10 +450,17 @@ function matchInlineCodeSpan(src: string, start: number): number {
|
|
|
398
450
|
return -1
|
|
399
451
|
}
|
|
400
452
|
|
|
401
|
-
|
|
453
|
+
// 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.
|
|
454
|
+
function findMatchingCloseTag(md: string, tagName: string, start: number, memo: ScanMemo): number {
|
|
455
|
+
let closes = memo.closes.get(tagName)
|
|
456
|
+
const known = closes?.get(start)
|
|
457
|
+
if (known !== undefined)
|
|
458
|
+
return known
|
|
459
|
+
closes ??= new Map()
|
|
460
|
+
memo.closes.set(tagName, closes)
|
|
402
461
|
const closeTag = `</${tagName}>`
|
|
403
462
|
const len = md.length
|
|
404
|
-
|
|
463
|
+
const open = [start]
|
|
405
464
|
let pos = start
|
|
406
465
|
while (pos < len) {
|
|
407
466
|
const ch = md[pos]!
|
|
@@ -416,17 +475,17 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
|
|
|
416
475
|
}
|
|
417
476
|
if (ch === '<') {
|
|
418
477
|
if (md.startsWith(closeTag, pos)) {
|
|
419
|
-
|
|
420
|
-
if (
|
|
478
|
+
closes.set(open.pop()!, pos)
|
|
479
|
+
if (open.length === 0)
|
|
421
480
|
return pos
|
|
422
481
|
pos += closeTag.length
|
|
423
482
|
continue
|
|
424
483
|
}
|
|
425
484
|
if (md.startsWith(`<${tagName}`, pos) && /[\s/>]/.test(md[pos + 1 + tagName.length] ?? '')) {
|
|
426
|
-
const innerEnd = findTagEnd(md, pos + 1 + tagName.length)
|
|
485
|
+
const innerEnd = findTagEnd(md, pos + 1 + tagName.length, memo)
|
|
427
486
|
if (innerEnd !== undefined) {
|
|
428
487
|
if (!innerEnd.selfClosing)
|
|
429
|
-
|
|
488
|
+
open.push(innerEnd.end)
|
|
430
489
|
pos = innerEnd.end
|
|
431
490
|
continue
|
|
432
491
|
}
|
|
@@ -434,6 +493,8 @@ function findMatchingCloseTag(md: string, tagName: string, start: number): numbe
|
|
|
434
493
|
}
|
|
435
494
|
pos++
|
|
436
495
|
}
|
|
496
|
+
for (const unclosed of open)
|
|
497
|
+
closes.set(unclosed, -1)
|
|
437
498
|
return -1
|
|
438
499
|
}
|
|
439
500
|
|
|
@@ -448,6 +509,7 @@ export function expandComponents(
|
|
|
448
509
|
const names = Object.keys(components)
|
|
449
510
|
if (names.length === 0)
|
|
450
511
|
return md
|
|
512
|
+
const memo = createScanMemo()
|
|
451
513
|
|
|
452
514
|
let out = ''
|
|
453
515
|
let i = 0
|
|
@@ -480,14 +542,16 @@ export function expandComponents(
|
|
|
480
542
|
}
|
|
481
543
|
|
|
482
544
|
const match = /^<([A-Z][\w]*)(?=[\s/>])/.exec(md.slice(lt))
|
|
483
|
-
if (
|
|
545
|
+
if (match && !Object.hasOwn(components, match[1]!))
|
|
546
|
+
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.`)
|
|
547
|
+
if (!match) {
|
|
484
548
|
out += md.slice(i, lt + 1)
|
|
485
549
|
i = lt + 1
|
|
486
550
|
continue
|
|
487
551
|
}
|
|
488
552
|
|
|
489
553
|
const tagName = match[1]!
|
|
490
|
-
const tagEnd = findTagEnd(md, lt + match[0].length)
|
|
554
|
+
const tagEnd = findTagEnd(md, lt + match[0].length, memo)
|
|
491
555
|
if (!tagEnd) {
|
|
492
556
|
out += md.slice(i, lt + 1)
|
|
493
557
|
i = lt + 1
|
|
@@ -496,12 +560,12 @@ export function expandComponents(
|
|
|
496
560
|
|
|
497
561
|
out += md.slice(i, lt)
|
|
498
562
|
const attrSrc = md.slice(lt + match[0].length, tagEnd.selfClosing ? tagEnd.end - 2 : tagEnd.end - 1)
|
|
499
|
-
const props = parseComponentProps(attrSrc)
|
|
563
|
+
const props = parseComponentProps(attrSrc, tagName, options.file)
|
|
500
564
|
let afterIndex = tagEnd.end
|
|
501
565
|
|
|
502
566
|
if (!tagEnd.selfClosing) {
|
|
503
567
|
const closeTag = `</${tagName}>`
|
|
504
|
-
const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end)
|
|
568
|
+
const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end, memo)
|
|
505
569
|
if (closeIdx !== -1) {
|
|
506
570
|
const innerMd = md.slice(tagEnd.end, closeIdx).trim()
|
|
507
571
|
const innerRendered = renderMarkdown(innerMd, options)
|
package/src/entry.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Shared entry construction, lazy Markdown render-config resolution, sorting, and filtering helpers.
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
BaseCollectionOptions,
|
|
5
|
+
CollectionRenderConfig,
|
|
6
|
+
ContentEntry,
|
|
7
|
+
RenderedMarkdown,
|
|
8
|
+
RenderMarkdownOptions,
|
|
9
|
+
} from './types'
|
|
10
|
+
import { devFromEnv } from 'prunelle/internal/server'
|
|
11
|
+
import { currentApp } from './app'
|
|
12
|
+
import { renderMarkdown } from './markdown'
|
|
13
|
+
import { shouldWrapCmsBody, wrapCmsBodyHtml } from './tracking'
|
|
14
|
+
|
|
15
|
+
export interface RenderConfigLoader {
|
|
16
|
+
ensureSync: () => RenderMarkdownOptions
|
|
17
|
+
ensureAsync: () => Promise<RenderMarkdownOptions>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type RenderConfigOptions = Pick<
|
|
21
|
+
BaseCollectionOptions<never>,
|
|
22
|
+
'highlight' | 'components' | 'headingLinks' | 'resolveImage' | 'trusted' | 'render'
|
|
23
|
+
>
|
|
24
|
+
|
|
25
|
+
export function createRenderConfigLoader(
|
|
26
|
+
label: string,
|
|
27
|
+
options: RenderConfigOptions,
|
|
28
|
+
): RenderConfigLoader {
|
|
29
|
+
const baseRenderOpts: RenderMarkdownOptions = {
|
|
30
|
+
highlight: options.highlight,
|
|
31
|
+
components: options.components,
|
|
32
|
+
headingLinks: options.headingLinks,
|
|
33
|
+
resolveImage: options.resolveImage,
|
|
34
|
+
trusted: options.trusted,
|
|
35
|
+
}
|
|
36
|
+
let resolvedRenderOpts: RenderMarkdownOptions | undefined = options.render === undefined ? baseRenderOpts : undefined
|
|
37
|
+
let pendingRenderOpts: Promise<RenderMarkdownOptions> | undefined
|
|
38
|
+
|
|
39
|
+
function mergeRenderConfig(cfg: CollectionRenderConfig): RenderMarkdownOptions {
|
|
40
|
+
return {
|
|
41
|
+
highlight: cfg.highlight ?? baseRenderOpts.highlight,
|
|
42
|
+
components: cfg.components ?? baseRenderOpts.components,
|
|
43
|
+
headingLinks: cfg.headingLinks ?? baseRenderOpts.headingLinks,
|
|
44
|
+
resolveImage: cfg.resolveImage !== undefined ? cfg.resolveImage : baseRenderOpts.resolveImage,
|
|
45
|
+
trusted: cfg.trusted !== undefined ? cfg.trusted : baseRenderOpts.trusted,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function ensureSync(): RenderMarkdownOptions {
|
|
50
|
+
if (resolvedRenderOpts !== undefined)
|
|
51
|
+
return resolvedRenderOpts
|
|
52
|
+
const loaded = options.render!()
|
|
53
|
+
if (loaded instanceof Promise) {
|
|
54
|
+
pendingRenderOpts ??= loaded.then((cfg) => {
|
|
55
|
+
resolvedRenderOpts = mergeRenderConfig(cfg)
|
|
56
|
+
return resolvedRenderOpts
|
|
57
|
+
}).catch((err) => {
|
|
58
|
+
pendingRenderOpts = undefined
|
|
59
|
+
throw err
|
|
60
|
+
})
|
|
61
|
+
throw new Error(
|
|
62
|
+
`@prunellejs/content: collection "${label}" uses an async "render" loader; call \`await entry.render()\` (e.g. in \`load()\`) before reading \`entry.html\` or \`entry.headings\`.`,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
resolvedRenderOpts = mergeRenderConfig(loaded)
|
|
66
|
+
return resolvedRenderOpts
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function ensureAsync(): Promise<RenderMarkdownOptions> {
|
|
70
|
+
if (resolvedRenderOpts !== undefined)
|
|
71
|
+
return resolvedRenderOpts
|
|
72
|
+
pendingRenderOpts ??= Promise.resolve(options.render!()).then((cfg) => {
|
|
73
|
+
resolvedRenderOpts = mergeRenderConfig(cfg)
|
|
74
|
+
return resolvedRenderOpts
|
|
75
|
+
}).catch((err) => {
|
|
76
|
+
pendingRenderOpts = undefined
|
|
77
|
+
throw err
|
|
78
|
+
})
|
|
79
|
+
return pendingRenderOpts
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { ensureSync, ensureAsync }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface BuildContentEntryParams<TData> {
|
|
86
|
+
slug: string
|
|
87
|
+
locale?: string | undefined
|
|
88
|
+
file: string
|
|
89
|
+
data: TData
|
|
90
|
+
body: string
|
|
91
|
+
renderLoader: RenderConfigLoader
|
|
92
|
+
/** Set for file-backed collections so dev inline CMS can anchor rendered Markdown bodies. */
|
|
93
|
+
collectionName?: string | undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function buildContentEntry<TData>(params: BuildContentEntryParams<TData>): ContentEntry<TData> {
|
|
97
|
+
const { slug, locale, file, data, body, renderLoader, collectionName } = params
|
|
98
|
+
const wordCount = body.trim().split(/\s+/).filter(Boolean).length
|
|
99
|
+
const readingMinutes = Math.max(1, Math.ceil(wordCount / 220))
|
|
100
|
+
let renderedCache: RenderedMarkdown | undefined
|
|
101
|
+
|
|
102
|
+
const getRenderedSync = (): RenderedMarkdown => {
|
|
103
|
+
renderedCache ??= renderMarkdown(body, { ...renderLoader.ensureSync(), locale, file })
|
|
104
|
+
return renderedCache
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const renderAsync = async (): Promise<RenderedMarkdown> => {
|
|
108
|
+
if (renderedCache === undefined) {
|
|
109
|
+
const opts = await renderLoader.ensureAsync()
|
|
110
|
+
renderedCache ??= renderMarkdown(body, { ...opts, locale, file })
|
|
111
|
+
}
|
|
112
|
+
if (shouldWrapCmsBody(collectionName)) {
|
|
113
|
+
return {
|
|
114
|
+
...renderedCache,
|
|
115
|
+
html: wrapCmsBodyHtml(collectionName, slug, locale, renderedCache.html),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return renderedCache
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
slug,
|
|
123
|
+
...(locale !== undefined ? { locale } : {}),
|
|
124
|
+
file,
|
|
125
|
+
data,
|
|
126
|
+
body,
|
|
127
|
+
get html() {
|
|
128
|
+
const raw = getRenderedSync().html
|
|
129
|
+
return shouldWrapCmsBody(collectionName)
|
|
130
|
+
? wrapCmsBodyHtml(collectionName, slug, locale, raw)
|
|
131
|
+
: raw
|
|
132
|
+
},
|
|
133
|
+
get headings() {
|
|
134
|
+
return getRenderedSync().headings
|
|
135
|
+
},
|
|
136
|
+
wordCount,
|
|
137
|
+
readingMinutes,
|
|
138
|
+
render: renderAsync,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function isDevMode(): boolean {
|
|
143
|
+
return currentApp.dev() ?? devFromEnv()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function isDraft(data: unknown): boolean {
|
|
147
|
+
return data !== null && typeof data === 'object' && (data as Record<string, unknown>).draft === true
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function defaultSort<T>(a: ContentEntry<T>, b: ContentEntry<T>): number {
|
|
151
|
+
const ad = a.data !== null && typeof a.data === 'object' ? (a.data as Record<string, unknown>).date : undefined
|
|
152
|
+
const bd = b.data !== null && typeof b.data === 'object' ? (b.data as Record<string, unknown>).date : undefined
|
|
153
|
+
const at = ad instanceof Date ? ad.getTime() : (typeof ad === 'string' || typeof ad === 'number' ? Date.parse(String(ad)) : Number.NaN)
|
|
154
|
+
const bt = bd instanceof Date ? bd.getTime() : (typeof bd === 'string' || typeof bd === 'number' ? Date.parse(String(bd)) : Number.NaN)
|
|
155
|
+
if (!Number.isNaN(at) && !Number.isNaN(bt) && at !== bt)
|
|
156
|
+
return bt - at
|
|
157
|
+
return a.slug.localeCompare(b.slug)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function filterByTag<T>(entries: readonly ContentEntry<T>[], tag: string): ContentEntry<T>[] {
|
|
161
|
+
const needle = tag.toLowerCase()
|
|
162
|
+
return entries.filter((e) => {
|
|
163
|
+
const tags = e.data !== null && typeof e.data === 'object' ? (e.data as Record<string, unknown>).tags : undefined
|
|
164
|
+
return Array.isArray(tags) && tags.some(t => String(t).toLowerCase() === needle)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function formatPaths<T>(entries: readonly ContentEntry<T>[], prefix = ''): string[] {
|
|
169
|
+
const base = prefix.replace(/\/$/, '')
|
|
170
|
+
return entries.map(e => `${base}/${e.slug}`)
|
|
171
|
+
}
|