@prunellejs/content 0.1.1 → 0.5.2

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.
@@ -0,0 +1,80 @@
1
+ // Dev-only per-request entry tracking and zero-impact HTML comment anchors for @prunellejs/cms in-page editing.
2
+
3
+ import type { AccessedContentEntry } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import { currentRequest } from 'prunelle/internal/server'
6
+ import { currentApp } from './app'
7
+
8
+ const MAX_TRACKED_ENTRIES = 50
9
+
10
+ interface RequestEntryBucket {
11
+ readonly primary: Map<string, AccessedContentEntry>
12
+ readonly secondary: Map<string, AccessedContentEntry>
13
+ }
14
+
15
+ const ACCESSED_STORAGE_KEY = Symbol.for('pru.content.accessedByRequest')
16
+ // Shared across bundled server routes and the host plugin instance; WeakMap releases entries once the request ends.
17
+ const accessedByRequest: WeakMap<RequestContext, RequestEntryBucket> = ((globalThis as Record<symbol, WeakMap<RequestContext, RequestEntryBucket> | undefined>)[ACCESSED_STORAGE_KEY] ??= new WeakMap())
18
+
19
+ function entryKey(entry: AccessedContentEntry): string {
20
+ return `${entry.collection}\0${entry.locale ?? ''}\0${entry.slug}`
21
+ }
22
+
23
+ function encodeCmsAnchorPart(value: string): string {
24
+ // Encode `-` as `%2D` so `--` can never appear inside an HTML5 comment node.
25
+ return encodeURIComponent(value).replaceAll('-', '%2D')
26
+ }
27
+
28
+ function isDevActive(): boolean {
29
+ return currentApp.dev() ?? (process.env.PRUNELLE_DEV === '1')
30
+ }
31
+
32
+ /** Records a file-backed entry read during the active dev request (`primary: true` for `.get()`, `false` for `.all()`). */
33
+ export function recordAccessedEntry(entry: AccessedContentEntry, primary: boolean): void {
34
+ if (!isDevActive())
35
+ return
36
+ const reqCtx = currentRequest()?.ctx
37
+ if (reqCtx === undefined)
38
+ return
39
+ let bucket = accessedByRequest.get(reqCtx)
40
+ if (bucket === undefined) {
41
+ bucket = { primary: new Map(), secondary: new Map() }
42
+ accessedByRequest.set(reqCtx, bucket)
43
+ }
44
+ const key = entryKey(entry)
45
+ if (primary) {
46
+ bucket.secondary.delete(key)
47
+ if (!bucket.primary.has(key) && bucket.primary.size < MAX_TRACKED_ENTRIES)
48
+ bucket.primary.set(key, entry)
49
+ }
50
+ else if (!bucket.primary.has(key) && !bucket.secondary.has(key) && bucket.secondary.size < MAX_TRACKED_ENTRIES) {
51
+ bucket.secondary.set(key, entry)
52
+ }
53
+ }
54
+
55
+ /** Returns file-backed entries accessed during `ctx`, with direct `.get()` reads ordered before `.all()` reads. */
56
+ export function getAccessedEntries(ctx: RequestContext): readonly AccessedContentEntry[] {
57
+ const bucket = accessedByRequest.get(ctx)
58
+ if (bucket === undefined)
59
+ return []
60
+ return [...bucket.primary.values(), ...bucket.secondary.values()]
61
+ }
62
+
63
+ /** True only when rendering a file-backed entry during an active dev request with `@prunellejs/cms` inline mode enabled. */
64
+ export function shouldWrapCmsBody(collectionName: string | undefined): collectionName is string {
65
+ return collectionName !== undefined
66
+ && isDevActive()
67
+ && currentApp.cmsInline()
68
+ && currentRequest() !== undefined
69
+ }
70
+
71
+ /** Wraps rendered Markdown HTML in zero-impact HTML comment anchors for in-page CMS body editing. */
72
+ export function wrapCmsBodyHtml(
73
+ collection: string,
74
+ slug: string,
75
+ locale: string | undefined,
76
+ html: string,
77
+ ): string {
78
+ const token = `${encodeCmsAnchorPart(collection)}:${encodeCmsAnchorPart(slug)}:${encodeCmsAnchorPart(locale ?? '')}:__body`
79
+ return `<!--pru-cms:${token}-->${html}<!--/pru-cms-->`
80
+ }
package/src/types.ts ADDED
@@ -0,0 +1,198 @@
1
+ // Shared public and internal types and symbol keys for @prunellejs/content.
2
+
3
+ import type { ContentImageResolver, ContentImageResult } from 'prunelle/config'
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+
6
+ export const COLLECTION_VERSION_KEY = Symbol.for('pru.content.collectionVersion')
7
+ export const COLLECTION_VALIDATE_KEY = Symbol.for('pru.content.validateAll')
8
+ export const COLLECTION_DIR_FOR_ROOT_KEY = Symbol.for('pru.content.dirForRoot')
9
+ export const COLLECTION_OWNER_ROOT_KEY = Symbol.for('pru.content.ownerRoot')
10
+ export const COLLECTION_META_KEY = Symbol.for('pru.content.meta')
11
+
12
+ export interface InternalCollectionMeta {
13
+ readonly name: string
14
+ readonly dir?: string | undefined
15
+ readonly localized: boolean
16
+ readonly defaultLocale: string
17
+ readonly locales?: readonly string[] | undefined
18
+ readonly schema?: StandardSchemaV1 | undefined
19
+ readonly isAsync: boolean
20
+ }
21
+
22
+ export interface ContentHeading {
23
+ level: number
24
+ id: string
25
+ text: string
26
+ }
27
+
28
+ export interface RenderedMarkdown {
29
+ readonly html: string
30
+ readonly headings: readonly ContentHeading[]
31
+ readonly wordCount: number
32
+ readonly readingMinutes: number
33
+ }
34
+
35
+ export interface ContentEntry<TData = Record<string, unknown>> {
36
+ readonly slug: string
37
+ readonly locale?: string | undefined
38
+ readonly file: string
39
+ readonly data: TData
40
+ readonly body: string
41
+ readonly html: string
42
+ readonly headings: readonly ContentHeading[]
43
+ readonly wordCount: number
44
+ readonly readingMinutes: number
45
+ /** Lazily resolves async collection renderers (`highlight`, `components`) and renders Markdown once. */
46
+ render(): Promise<RenderedMarkdown>
47
+ }
48
+
49
+ export type MarkdownComponent = (props: never) => unknown
50
+ export type CodeHighlighter = (code: string, language: string | undefined) => string
51
+ export type MarkdownImageResult = ContentImageResult
52
+ export type MarkdownImageResolver = ContentImageResolver
53
+
54
+ export interface CollectionRenderConfig {
55
+ /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
56
+ highlight?: CodeHighlighter | undefined
57
+ /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
58
+ components?: Record<string, MarkdownComponent> | undefined
59
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
60
+ headingLinks?: boolean | undefined
61
+ /** Optional image resolver (set to `false` to disable automatic `@prunellejs/images` optimization). */
62
+ resolveImage?: MarkdownImageResolver | false | undefined
63
+ /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
64
+ trusted?: boolean | undefined
65
+ }
66
+
67
+ export interface RenderMarkdownOptions {
68
+ highlight?: CodeHighlighter | undefined
69
+ components?: Record<string, MarkdownComponent> | undefined
70
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
71
+ headingLinks?: boolean | undefined
72
+ /** Active locale passed into embedded components as `props.locale`. */
73
+ locale?: string | undefined
74
+ /** Optional image resolver for rewriting `<img src="...">` (defaults to auto-wired `@prunellejs/images` when active; `false` disables). */
75
+ resolveImage?: MarkdownImageResolver | false | undefined
76
+ /** Source file path passed to `resolveImage`. */
77
+ file?: string | undefined
78
+ /** Opt out of default Markdown HTML sanitization for fully trusted content (default: false). */
79
+ trusted?: boolean | undefined
80
+ }
81
+
82
+ export interface CollectionLoadContext {
83
+ /** Requested locale when `localized: true`; `undefined` otherwise. */
84
+ readonly locale?: string | undefined
85
+ }
86
+
87
+ export interface LoadedEntryInput {
88
+ /** Entry slug used for `.get(slug)` and `.paths(prefix)`. */
89
+ readonly slug: string
90
+ /** Raw entry metadata validated against `schema` when configured. */
91
+ readonly data: unknown
92
+ /** Optional Markdown body rendered through the standard content pipeline. */
93
+ readonly body?: string | undefined
94
+ /** Optional locale tag; when `localized: true`, entries with a non-matching locale are filtered out. */
95
+ readonly locale?: string | undefined
96
+ /** Optional upstream identifier (e.g. CMS record ID) surfaced as `entry.file`. */
97
+ readonly id?: string | undefined
98
+ }
99
+
100
+ export type CollectionLoader = (
101
+ ctx?: CollectionLoadContext,
102
+ ) => LoadedEntryInput[] | Promise<LoadedEntryInput[]>
103
+
104
+ export interface BaseCollectionOptions<TData = Record<string, unknown>> {
105
+ /** Collection identifier for diagnostics, CMS, and search (defaults to `dir` basename or `'collection'`). */
106
+ name?: string | undefined
107
+ /** When true, queries are scoped by locale. */
108
+ localized?: boolean | undefined
109
+ /** Default locale when `localized: true` and no locale is passed (default: app defaultLocale or `'en'`). */
110
+ defaultLocale?: string | undefined
111
+ /** Known locales for localized collections (used by `prunelle check`, search, and CMS). */
112
+ locales?: readonly string[] | undefined
113
+ /** Optional Standard Schema (Zod, Valibot, ArkType, custom) to validate entry metadata. */
114
+ schema?: StandardSchemaV1<unknown, TData> | undefined
115
+ /** Custom syntax highlighter for fenced code blocks (e.g. Shiki). */
116
+ highlight?: CodeHighlighter | undefined
117
+ /** Embedded Prunelle TSX components usable directly inside Markdown (`<Note>`, `<BarChart rows={[...]} />`). */
118
+ components?: Record<string, MarkdownComponent> | undefined
119
+ /** Wrap h2-h6 headings in self-referencing `<a href="#id">` links. */
120
+ headingLinks?: boolean | undefined
121
+ /** Optional image resolver for rewriting Markdown images (defaults to auto-wired `@prunellejs/images`; `false` disables). */
122
+ resolveImage?: MarkdownImageResolver | false | undefined
123
+ /** Opt out of default Markdown HTML sanitization for fully trusted collections (default: false). */
124
+ trusted?: boolean | undefined
125
+ /** Lazy renderer loader (`async () => ({ highlight, components })`) so config/index/RSS never load Shiki or TSX components. */
126
+ render?: (() => CollectionRenderConfig | Promise<CollectionRenderConfig>) | undefined
127
+ /** Include entries with `draft: true` (default: `true` in dev, `false` in production/build). */
128
+ includeDrafts?: boolean | undefined
129
+ /** Custom comparator for `all()` (defaults to newest `date` first, then alphabetical `slug`). */
130
+ sort?: ((a: ContentEntry<TData>, b: ContentEntry<TData>) => number) | undefined
131
+ }
132
+
133
+ export interface CollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
134
+ /** Directory containing `.md` / `.markdown` files (or `<locale>/*.md` when `localized: true`). */
135
+ dir: string
136
+ load?: undefined
137
+ }
138
+
139
+ export interface CollectionOptionsWithSchema<TData> extends Omit<CollectionOptions<TData>, 'schema'> {
140
+ /** Standard Schema (Zod, Valibot, ArkType, custom) validating frontmatter into `TData`. */
141
+ schema: StandardSchemaV1<unknown, TData>
142
+ }
143
+
144
+ export interface CollectionOptionsWithoutSchema extends Omit<CollectionOptions<Record<string, unknown>>, 'schema'> {
145
+ schema?: undefined
146
+ }
147
+
148
+ export interface LoaderCollectionOptions<TData = Record<string, unknown>> extends BaseCollectionOptions<TData> {
149
+ dir?: undefined
150
+ /** Async or sync loader returning entries from a headless CMS, database, or API. */
151
+ load: CollectionLoader
152
+ }
153
+
154
+ export interface LoaderCollectionOptionsWithSchema<TData> extends Omit<LoaderCollectionOptions<TData>, 'schema'> {
155
+ /** Standard Schema (Zod, Valibot, ArkType, custom) validating loaded entry data into `TData`. */
156
+ schema: StandardSchemaV1<unknown, TData>
157
+ }
158
+
159
+ export interface LoaderCollectionOptionsWithoutSchema extends Omit<LoaderCollectionOptions<Record<string, unknown>>, 'schema'> {
160
+ schema?: undefined
161
+ }
162
+
163
+ export interface Collection<TData = Record<string, unknown>> {
164
+ readonly dir: string
165
+ readonly name: string
166
+ all(locale?: string): ContentEntry<TData>[]
167
+ get(slug: string, locale?: string): ContentEntry<TData> | undefined
168
+ byTag(tag: string, locale?: string): ContentEntry<TData>[]
169
+ /** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
170
+ paths(prefix?: string, locale?: string): string[]
171
+ clearCache(): void
172
+ }
173
+
174
+ export interface AsyncCollection<TData = Record<string, unknown>> {
175
+ readonly dir?: undefined
176
+ readonly name: string
177
+ all(locale?: string): Promise<ContentEntry<TData>[]>
178
+ get(slug: string, locale?: string): Promise<ContentEntry<TData> | undefined>
179
+ byTag(tag: string, locale?: string): Promise<ContentEntry<TData>[]>
180
+ /** Returns URL paths for `export const prerender = true; export const paths = () => col.paths('/blog')`. */
181
+ paths(prefix?: string, locale?: string): Promise<string[]>
182
+ clearCache(): void
183
+ }
184
+
185
+ export type AnyCollection<TData = Record<string, unknown>> = Collection<TData> | AsyncCollection<TData>
186
+
187
+ export interface InternalCollection {
188
+ readonly dir?: string | undefined
189
+ readonly name?: string | undefined
190
+ all(locale?: string): ContentEntry<unknown>[] | Promise<ContentEntry<unknown>[]>
191
+ get(slug: string, locale?: string): ContentEntry<unknown> | undefined | Promise<ContentEntry<unknown> | undefined>
192
+ clearCache(): void
193
+ [COLLECTION_VERSION_KEY]?: () => number
194
+ [COLLECTION_VALIDATE_KEY]?: (root: string) => string[] | Promise<string[]>
195
+ [COLLECTION_DIR_FOR_ROOT_KEY]?: (root?: string) => string | undefined
196
+ [COLLECTION_OWNER_ROOT_KEY]?: string | undefined
197
+ [COLLECTION_META_KEY]?: (root?: string) => InternalCollectionMeta
198
+ }