@prunellejs/cms 0.0.0-stage → 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.
@@ -0,0 +1,356 @@
1
+ // HTTP route handlers and CRUD lifecycle for @prunellejs/cms (dev-only).
2
+
3
+ import type { ContentCollectionDescriptor, ContentCollectionEntrySummary, ServerPluginAPI } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { CmsField } from './schema'
6
+ import type { CmsHandlerConfig } from './shared'
7
+ import { existsSync } from 'node:fs'
8
+ import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
9
+ import { safeRedirect, validateSchema } from 'prunelle/server'
10
+ import { CMS_CSS, CMS_JS } from './assets'
11
+ import {
12
+ applyRowAction,
13
+ parseFormSubmission,
14
+ parseRowAction,
15
+ resolveEntryFilePath,
16
+ serializeMarkdownEntry,
17
+ validateLocale,
18
+ } from './form-data'
19
+ import {
20
+ encodeSlugPath,
21
+ localeQueryString,
22
+ renderCollectionsPage,
23
+ renderEditorPage,
24
+ renderEntriesPage,
25
+ } from './render'
26
+ import { renderMarkdownPreview } from './sanitize'
27
+ import {
28
+ collectValidationErrors,
29
+ htmlResponse,
30
+ loadCollections,
31
+ parseRawFrontmatterYaml,
32
+ resolveSchemaFields,
33
+ textResponse,
34
+ wrapGuarded,
35
+ } from './shared'
36
+ import { createEntryFile, readEntrySource, replaceEntryFile } from './write-file'
37
+
38
+ export type { CmsGuard, CmsHandlerConfig } from './shared'
39
+
40
+ function collectionLocales(col: ContentCollectionDescriptor): readonly string[] {
41
+ if (!col.localized)
42
+ return []
43
+ if (col.locales !== undefined && col.locales.length > 0)
44
+ return col.locales
45
+ return [col.defaultLocale]
46
+ }
47
+
48
+ async function countCollectionEntries(col: ContentCollectionDescriptor): Promise<number> {
49
+ if (!col.localized)
50
+ return (await col.all()).length
51
+ const locales = collectionLocales(col)
52
+ let total = 0
53
+ for (const loc of locales)
54
+ total += (await col.all(loc)).length
55
+ return total
56
+ }
57
+
58
+ function buildDefaultData(fields: readonly CmsField[] | undefined): Record<string, unknown> {
59
+ const out: Record<string, unknown> = {}
60
+ if (fields === undefined)
61
+ return out
62
+ for (const field of fields) {
63
+ if (field.defaultValue !== undefined) {
64
+ out[field.key] = field.defaultValue
65
+ }
66
+ else if (field.kind === 'object') {
67
+ const nested = buildDefaultData(field.fields)
68
+ if (Object.keys(nested).length > 0)
69
+ out[field.key] = nested
70
+ }
71
+ }
72
+ return out
73
+ }
74
+
75
+ function matchesSearchQuery(entry: ContentCollectionEntrySummary, needle: string): boolean {
76
+ if (entry.slug.toLowerCase().includes(needle))
77
+ return true
78
+ for (const val of Object.values(entry.data)) {
79
+ if (typeof val === 'string' && val.toLowerCase().includes(needle))
80
+ return true
81
+ if (Array.isArray(val) && val.some(item => typeof item === 'string' && item.toLowerCase().includes(needle)))
82
+ return true
83
+ }
84
+ return false
85
+ }
86
+
87
+ async function readPreviewMarkdown(request: Request): Promise<string> {
88
+ const ct = request.headers.get('content-type')?.toLowerCase() ?? ''
89
+ if (ct.includes('application/json')) {
90
+ const parsed = await request.json() as { markdown?: unknown }
91
+ return typeof parsed?.markdown === 'string' ? parsed.markdown : ''
92
+ }
93
+ if (ct.includes('multipart/form-data') || ct.includes('application/x-www-form-urlencoded')) {
94
+ const form = await request.formData()
95
+ const raw = form.get('markdown')
96
+ return typeof raw === 'string' ? raw : ''
97
+ }
98
+ return await request.text()
99
+ }
100
+
101
+ async function handleEditorPost(options: {
102
+ ctx: RequestContext
103
+ basePath: string
104
+ collection: ContentCollectionDescriptor
105
+ mode: 'new' | 'edit'
106
+ routeSlug?: string | undefined
107
+ }): Promise<Response> {
108
+ const { ctx, basePath, collection, mode, routeSlug } = options
109
+ if (collection.dir === undefined)
110
+ return textResponse(`Collection "${collection.name}" is read-only.`, 403)
111
+
112
+ const formData = await ctx.request.formData()
113
+ const rawLocaleField = formData.get('__locale')
114
+ const rawLocale = typeof rawLocaleField === 'string'
115
+ ? rawLocaleField
116
+ : (ctx.url.searchParams.get('locale') ?? undefined)
117
+ const localeCheck = validateLocale(collection, rawLocale)
118
+ if (!localeCheck.ok)
119
+ return textResponse(localeCheck.message, 400)
120
+
121
+ const rawSlugField = formData.get('__slug')
122
+ const slug = mode === 'new'
123
+ ? (typeof rawSlugField === 'string' ? rawSlugField : '')
124
+ : (routeSlug ?? '')
125
+ const rawBody = formData.get('__body')
126
+ const body = typeof rawBody === 'string' ? rawBody : ''
127
+
128
+ const { fields, warning } = resolveSchemaFields(collection)
129
+ let data: Record<string, unknown>
130
+ let rawFrontmatterYaml: string | undefined
131
+
132
+ const render = (status: number, errors: Record<string, string>, pageData: Record<string, unknown> = data): Response => htmlResponse(renderEditorPage({
133
+ basePath,
134
+ collection,
135
+ mode,
136
+ slug,
137
+ locale: localeCheck.locale,
138
+ fields,
139
+ data: pageData,
140
+ rawFrontmatterYaml,
141
+ body,
142
+ errors,
143
+ schemaWarning: warning,
144
+ }), status)
145
+
146
+ if (fields !== undefined) {
147
+ data = parseFormSubmission(formData, fields)
148
+ }
149
+ else {
150
+ const rawYamlField = formData.get('__frontmatter_yaml')
151
+ rawFrontmatterYaml = typeof rawYamlField === 'string' ? rawYamlField : ''
152
+ const yamlRes = parseRawFrontmatterYaml(rawFrontmatterYaml)
153
+ if (!yamlRes.ok)
154
+ return render(422, { __frontmatter_yaml: yamlRes.message }, {})
155
+ data = yamlRes.data
156
+ }
157
+
158
+ const rawAction = formData.get('__cms_action')
159
+ const rowAction = parseRowAction(typeof rawAction === 'string' ? rawAction : null)
160
+ if (rowAction !== undefined && fields !== undefined) {
161
+ applyRowAction(data, rowAction)
162
+ return render(200, {})
163
+ }
164
+
165
+ if (mode === 'new' && slug.trim().length === 0)
166
+ return render(422, { __slug: 'Slug is required.' })
167
+
168
+ const existingEntry = mode === 'edit'
169
+ ? await collection.get(slug, localeCheck.locale)
170
+ : undefined
171
+ if (mode === 'edit' && existingEntry === undefined)
172
+ return textResponse(`Entry "${slug}" not found in collection "${collection.name}".`, 404)
173
+
174
+ const pathRes = resolveEntryFilePath(collection, slug, localeCheck.locale, existingEntry?.file)
175
+ if (!pathRes.ok)
176
+ return mode === 'new' && pathRes.tooLong ? render(422, { __slug: pathRes.message }) : textResponse(pathRes.message, pathRes.status)
177
+
178
+ const slugTaken = { __slug: 'An entry with this slug already exists.' }
179
+ if (mode === 'new' && existsSync(pathRes.filePath))
180
+ return render(422, slugTaken)
181
+
182
+ let dataToWrite = data
183
+ if (collection.schema !== undefined) {
184
+ const validated = await validateSchema(collection.schema, data)
185
+ if (!validated.ok)
186
+ return render(422, collectValidationErrors(validated.issues))
187
+ if (validated.value !== null && typeof validated.value === 'object' && !Array.isArray(validated.value))
188
+ dataToWrite = validated.value as Record<string, unknown>
189
+ }
190
+
191
+ if (mode === 'new') {
192
+ if (createEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body)) === 'exists')
193
+ return render(422, slugTaken)
194
+ }
195
+ else {
196
+ const source = readEntrySource(pathRes.filePath)
197
+ const owned = fields === undefined ? undefined : new Set(fields.map(field => field.key))
198
+ replaceEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body, source === undefined ? undefined : { source, owned }))
199
+ }
200
+ collection.clearCache()
201
+
202
+ const target = safeRedirect(
203
+ `${basePath}/${encodeURIComponent(collection.name)}/${encodeSlugPath(pathRes.slug)}${localeQueryString(pathRes.locale, 'saved=1')}`,
204
+ basePath,
205
+ )
206
+ return new Response(null, { status: 303, headers: { location: target } })
207
+ }
208
+
209
+ /** Registers all dev-only CMS routes on `api`. */
210
+ export function registerCmsRoutes(api: ServerPluginAPI, config: CmsHandlerConfig): void {
211
+ const { basePath, guard } = config
212
+
213
+ const guarded = (
214
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
215
+ ): ((ctx: RequestContext) => Promise<Response>) => wrapGuarded(guard, handler)
216
+
217
+ const findCollection = async (name: string): Promise<ContentCollectionDescriptor | undefined> => {
218
+ const cols = await loadCollections(api.inject(CONTENT_COLLECTIONS_SERVICE), api.root)
219
+ return cols.find(c => c.name === name)
220
+ }
221
+
222
+ api.route('GET', `${basePath}/_assets/cms.css`, guarded(() => new Response(CMS_CSS, {
223
+ headers: {
224
+ 'content-type': 'text/css; charset=utf-8',
225
+ 'cache-control': 'no-store',
226
+ },
227
+ })))
228
+
229
+ api.route('GET', `${basePath}/_assets/cms.js`, guarded(() => new Response(CMS_JS, {
230
+ headers: {
231
+ 'content-type': 'application/javascript; charset=utf-8',
232
+ 'cache-control': 'no-store',
233
+ },
234
+ })))
235
+
236
+ api.route('POST', `${basePath}/_preview`, guarded(async (ctx) => {
237
+ const markdown = await readPreviewMarkdown(ctx.request)
238
+ const html = renderMarkdownPreview(markdown)
239
+ const accept = ctx.request.headers.get('accept') ?? ''
240
+ if (accept.includes('application/json'))
241
+ return ctx.json({ html })
242
+ return htmlResponse(html)
243
+ }), { csrf: true })
244
+
245
+ api.route('GET', basePath, guarded(async () => {
246
+ const service = api.inject(CONTENT_COLLECTIONS_SERVICE)
247
+ const cols = await loadCollections(service, api.root)
248
+ const cards = await Promise.all(cols.map(async col => ({
249
+ name: col.name,
250
+ entryCount: await countCollectionEntries(col),
251
+ editable: col.dir !== undefined,
252
+ localized: col.localized,
253
+ defaultLocale: col.defaultLocale,
254
+ hasSchema: col.schema !== undefined,
255
+ })))
256
+ return htmlResponse(renderCollectionsPage(basePath, cards, service === undefined))
257
+ }))
258
+
259
+ api.route('GET', `${basePath}/:collection`, guarded(async (ctx) => {
260
+ const col = await findCollection(ctx.params.collection ?? '')
261
+ if (col === undefined)
262
+ return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
263
+ const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
264
+ if (!localeCheck.ok)
265
+ return textResponse(localeCheck.message, 400)
266
+ const query = (ctx.url.searchParams.get('q') ?? '').trim()
267
+ const allEntries = await col.all(localeCheck.locale)
268
+ const needle = query.toLowerCase()
269
+ const entries = needle.length > 0
270
+ ? allEntries.filter(entry => matchesSearchQuery(entry, needle))
271
+ : allEntries
272
+ return htmlResponse(renderEntriesPage({
273
+ basePath,
274
+ collection: col,
275
+ entries,
276
+ activeLocale: localeCheck.locale,
277
+ locales: collectionLocales(col),
278
+ query,
279
+ }))
280
+ }))
281
+
282
+ api.route('GET', `${basePath}/:collection/new`, guarded(async (ctx) => {
283
+ const col = await findCollection(ctx.params.collection ?? '')
284
+ if (col === undefined)
285
+ return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
286
+ if (col.dir === undefined)
287
+ return textResponse(`Collection "${col.name}" is read-only.`, 403)
288
+ const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
289
+ if (!localeCheck.ok)
290
+ return textResponse(localeCheck.message, 400)
291
+ const { fields, warning } = resolveSchemaFields(col)
292
+ return htmlResponse(renderEditorPage({
293
+ basePath,
294
+ collection: col,
295
+ mode: 'new',
296
+ slug: '',
297
+ locale: localeCheck.locale,
298
+ fields,
299
+ data: buildDefaultData(fields),
300
+ body: '',
301
+ errors: {},
302
+ schemaWarning: warning,
303
+ }))
304
+ }))
305
+
306
+ api.route('POST', `${basePath}/:collection/new`, guarded(async (ctx) => {
307
+ const col = await findCollection(ctx.params.collection ?? '')
308
+ if (col === undefined)
309
+ return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
310
+ return await handleEditorPost({ ctx, basePath, collection: col, mode: 'new' })
311
+ }), { csrf: true })
312
+
313
+ api.route('GET', `${basePath}/:collection/*slug`, guarded(async (ctx) => {
314
+ const col = await findCollection(ctx.params.collection ?? '')
315
+ if (col === undefined)
316
+ return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
317
+ const slug = ctx.params.slug ?? ''
318
+ if (slug.length === 0)
319
+ return textResponse('Missing entry slug.', 400)
320
+ const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
321
+ if (!localeCheck.ok)
322
+ return textResponse(localeCheck.message, 400)
323
+ const entry = await col.get(slug, localeCheck.locale)
324
+ if (entry === undefined)
325
+ return textResponse(`Entry "${slug}" not found in collection "${col.name}".`, 404)
326
+ if (col.dir !== undefined && entry.file !== undefined) {
327
+ const pathRes = resolveEntryFilePath(col, slug, localeCheck.locale, entry.file)
328
+ if (!pathRes.ok)
329
+ return textResponse(pathRes.message, pathRes.status)
330
+ }
331
+ const { fields, warning } = resolveSchemaFields(col)
332
+ return htmlResponse(renderEditorPage({
333
+ basePath,
334
+ collection: col,
335
+ mode: 'edit',
336
+ slug: entry.slug,
337
+ locale: localeCheck.locale,
338
+ fields,
339
+ data: entry.data,
340
+ body: entry.body,
341
+ errors: {},
342
+ saved: ctx.url.searchParams.get('saved') === '1',
343
+ schemaWarning: warning,
344
+ }))
345
+ }))
346
+
347
+ api.route('POST', `${basePath}/:collection/*slug`, guarded(async (ctx) => {
348
+ const col = await findCollection(ctx.params.collection ?? '')
349
+ if (col === undefined)
350
+ return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
351
+ const slug = ctx.params.slug ?? ''
352
+ if (slug.length === 0)
353
+ return textResponse('Missing entry slug.', 400)
354
+ return await handleEditorPost({ ctx, basePath, collection: col, mode: 'edit', routeSlug: slug })
355
+ }), { csrf: true })
356
+ }
package/src/index.ts ADDED
@@ -0,0 +1,101 @@
1
+ // @prunellejs/cms — Schema-driven dev-only CMS plugin for Prunelle Markdown content collections.
2
+
3
+ import type { ContentCollectionsService, PrunellePlugin } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { CmsGuard } from './guard'
6
+ import { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, definePlugin } from 'prunelle/config'
7
+ import { escAttr } from 'prunelle/server'
8
+ import { checkCollectionSchema } from './schema'
9
+ import { runGuard } from './guard'
10
+
11
+ export type { CmsGuard } from './guard'
12
+ export type { CmsField, CmsFieldKind, CmsSchemaIssue, ParsedCmsSchema } from './schema'
13
+
14
+ export interface CmsOptions {
15
+ /** Access guard run on every CMS route and in-page overlay injection. Return `false` for 403 Forbidden, or return a `Response` (e.g. a login redirect). */
16
+ guard?: CmsGuard | undefined
17
+ /** Base URL path where the dev CMS is mounted (default: `'/_pru/cms'`). */
18
+ basePath?: string | undefined
19
+ /** Inject the dev-only Shadow DOM in-page editing overlay on pages rendering file-backed collections (default: `true`). */
20
+ inline?: boolean | undefined
21
+ }
22
+
23
+ interface InlineRequestState {
24
+ readonly service: ContentCollectionsService | undefined
25
+ }
26
+
27
+ function normalizeBasePath(raw: string | undefined): string {
28
+ const trimmed = (raw ?? '/_pru/cms').trim()
29
+ if (trimmed.length === 0 || trimmed === '/')
30
+ return '/_pru/cms'
31
+ const withLead = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
32
+ return withLead.endsWith('/') ? withLead.slice(0, -1) : withLead
33
+ }
34
+
35
+ function isUnderBasePath(pathname: string, basePath: string): boolean {
36
+ return pathname === basePath || pathname.startsWith(`${basePath}/`)
37
+ }
38
+
39
+ /**
40
+ * Registers the dev-only schema-driven CMS for `@prunellejs/content` collections.
41
+ * Mounts zero routes in production (`dev: false`), emits nothing on `--static`, and ships 0 B to production pages.
42
+ */
43
+ export function cms(options: CmsOptions = {}): PrunellePlugin {
44
+ const basePath = normalizeBasePath(options.basePath)
45
+ const inlineEnabled = options.inline !== false
46
+ const devInlineRequests = new WeakMap<RequestContext, InlineRequestState>()
47
+
48
+ return definePlugin({
49
+ name: '@prunellejs/cms',
50
+ after: ['@prunellejs/content'],
51
+ async check(ctx) {
52
+ const service = ctx.inject?.(CONTENT_COLLECTIONS_SERVICE)
53
+ if (service === undefined)
54
+ return
55
+ const collections = service.discover !== undefined
56
+ ? await service.discover(ctx.root)
57
+ : await service.list(ctx.root)
58
+ for (const col of collections) {
59
+ if (col.dir === undefined || col.schema === undefined)
60
+ continue
61
+ for (const err of checkCollectionSchema(col.name, col.schema))
62
+ ctx.error(err)
63
+ }
64
+ },
65
+ async server(api) {
66
+ if (!api.dev)
67
+ return
68
+ if (api.devExposed && options.guard === undefined)
69
+ throw new Error('@prunellejs/cms: prunelle dev --host binds an address other machines reach, and the CMS would let them read drafts and write content files: pass cms({ guard: ctx => ... }) to let only you in, or run prunelle dev without --host.')
70
+ // Loaded in dev only: a production server never pays for the editor's handlers, pages and scripts.
71
+ const [{ registerCmsRoutes }, { registerInlineCmsRoutes }] = await Promise.all([import('./handlers'), import('./inline-handlers')])
72
+ if (inlineEnabled) {
73
+ api.provide(CMS_INLINE_ENABLED_SERVICE, true)
74
+ registerInlineCmsRoutes(api, { basePath, guard: options.guard })
75
+ api.use((ctx, next) => {
76
+ devInlineRequests.set(ctx, { service: api.inject(CONTENT_COLLECTIONS_SERVICE) })
77
+ return next()
78
+ }, { scope: 'rendered' })
79
+ }
80
+ registerCmsRoutes(api, { basePath, guard: options.guard })
81
+ },
82
+ async head(docHead, ctx) {
83
+ if (!inlineEnabled)
84
+ return
85
+ const state = devInlineRequests.get(ctx)
86
+ if (state === undefined || isUnderBasePath(ctx.url.pathname, basePath))
87
+ return
88
+ const accessed = state.service?.accessedEntries?.(ctx) ?? []
89
+ if (accessed.length === 0)
90
+ return
91
+ const blocked = await runGuard(options.guard, ctx)
92
+ if (blocked !== undefined)
93
+ return
94
+ const payload = JSON.stringify({ basePath, entries: accessed })
95
+ docHead.add(
96
+ `<meta name="pru-cms-config" content="${escAttr(payload)}">`
97
+ + `<script type="module" src="${escAttr(`${basePath}/_assets/inline.js`)}" defer></script>`,
98
+ )
99
+ },
100
+ })
101
+ }