@prunellejs/cms 0.0.0-stage → 0.6.0
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/llms.txt +67 -0
- package/package.json +24 -4
- package/src/assets-js.ts +101 -0
- package/src/assets.ts +576 -0
- package/src/form-data.ts +464 -0
- package/src/handlers.ts +397 -0
- package/src/index.ts +99 -0
- package/src/inline-css.ts +621 -0
- package/src/inline-dom-js.ts +166 -0
- package/src/inline-form-js.ts +465 -0
- package/src/inline-handlers.ts +243 -0
- package/src/inline-js.ts +547 -0
- package/src/render.ts +583 -0
- package/src/sanitize.ts +150 -0
- package/src/schema.ts +487 -0
- package/src/shared.ts +119 -0
- package/README.md +0 -3
package/src/handlers.ts
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
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, mkdirSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { dirname } from 'node:path'
|
|
9
|
+
import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
|
|
10
|
+
import { safeRedirect, validateSchema } from 'prunelle/server'
|
|
11
|
+
import { CMS_CSS, CMS_JS } from './assets'
|
|
12
|
+
import {
|
|
13
|
+
applyRowAction,
|
|
14
|
+
parseFormSubmission,
|
|
15
|
+
parseRowAction,
|
|
16
|
+
resolveEntryFilePath,
|
|
17
|
+
serializeMarkdownEntry,
|
|
18
|
+
validateLocale,
|
|
19
|
+
} from './form-data'
|
|
20
|
+
import {
|
|
21
|
+
encodeSlugPath,
|
|
22
|
+
localeQueryString,
|
|
23
|
+
renderCollectionsPage,
|
|
24
|
+
renderEditorPage,
|
|
25
|
+
renderEntriesPage,
|
|
26
|
+
} from './render'
|
|
27
|
+
import { renderMarkdownPreview } from './sanitize'
|
|
28
|
+
import {
|
|
29
|
+
collectValidationErrors,
|
|
30
|
+
htmlResponse,
|
|
31
|
+
loadCollections,
|
|
32
|
+
parseRawFrontmatterYaml,
|
|
33
|
+
resolveSchemaFields,
|
|
34
|
+
textResponse,
|
|
35
|
+
wrapGuarded,
|
|
36
|
+
} from './shared'
|
|
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
|
+
if (fields !== undefined) {
|
|
133
|
+
data = parseFormSubmission(formData, fields)
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
const rawYamlField = formData.get('__frontmatter_yaml')
|
|
137
|
+
rawFrontmatterYaml = typeof rawYamlField === 'string' ? rawYamlField : ''
|
|
138
|
+
const yamlRes = parseRawFrontmatterYaml(rawFrontmatterYaml)
|
|
139
|
+
if (!yamlRes.ok) {
|
|
140
|
+
return htmlResponse(renderEditorPage({
|
|
141
|
+
basePath,
|
|
142
|
+
collection,
|
|
143
|
+
mode,
|
|
144
|
+
slug,
|
|
145
|
+
locale: localeCheck.locale,
|
|
146
|
+
fields,
|
|
147
|
+
data: {},
|
|
148
|
+
rawFrontmatterYaml,
|
|
149
|
+
body,
|
|
150
|
+
errors: { __frontmatter_yaml: yamlRes.message },
|
|
151
|
+
schemaWarning: warning,
|
|
152
|
+
}), 422)
|
|
153
|
+
}
|
|
154
|
+
data = yamlRes.data
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const rawAction = formData.get('__cms_action')
|
|
158
|
+
const rowAction = parseRowAction(typeof rawAction === 'string' ? rawAction : null)
|
|
159
|
+
if (rowAction !== undefined && fields !== undefined) {
|
|
160
|
+
applyRowAction(data, rowAction)
|
|
161
|
+
return htmlResponse(renderEditorPage({
|
|
162
|
+
basePath,
|
|
163
|
+
collection,
|
|
164
|
+
mode,
|
|
165
|
+
slug,
|
|
166
|
+
locale: localeCheck.locale,
|
|
167
|
+
fields,
|
|
168
|
+
data,
|
|
169
|
+
body,
|
|
170
|
+
errors: {},
|
|
171
|
+
schemaWarning: warning,
|
|
172
|
+
}), 200)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (mode === 'new' && slug.trim().length === 0) {
|
|
176
|
+
return htmlResponse(renderEditorPage({
|
|
177
|
+
basePath,
|
|
178
|
+
collection,
|
|
179
|
+
mode,
|
|
180
|
+
slug,
|
|
181
|
+
locale: localeCheck.locale,
|
|
182
|
+
fields,
|
|
183
|
+
data,
|
|
184
|
+
rawFrontmatterYaml,
|
|
185
|
+
body,
|
|
186
|
+
errors: { __slug: 'Slug is required.' },
|
|
187
|
+
schemaWarning: warning,
|
|
188
|
+
}), 422)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const existingEntry = mode === 'edit'
|
|
192
|
+
? await collection.get(slug, localeCheck.locale)
|
|
193
|
+
: undefined
|
|
194
|
+
if (mode === 'edit' && existingEntry === undefined)
|
|
195
|
+
return textResponse(`Entry "${slug}" not found in collection "${collection.name}".`, 404)
|
|
196
|
+
|
|
197
|
+
const pathRes = resolveEntryFilePath(collection, slug, localeCheck.locale, existingEntry?.file)
|
|
198
|
+
if (!pathRes.ok)
|
|
199
|
+
return textResponse(pathRes.message, pathRes.status)
|
|
200
|
+
|
|
201
|
+
if (mode === 'new' && existsSync(pathRes.filePath)) {
|
|
202
|
+
return htmlResponse(renderEditorPage({
|
|
203
|
+
basePath,
|
|
204
|
+
collection,
|
|
205
|
+
mode,
|
|
206
|
+
slug,
|
|
207
|
+
locale: localeCheck.locale,
|
|
208
|
+
fields,
|
|
209
|
+
data,
|
|
210
|
+
rawFrontmatterYaml,
|
|
211
|
+
body,
|
|
212
|
+
errors: { __slug: 'An entry with this slug already exists.' },
|
|
213
|
+
schemaWarning: warning,
|
|
214
|
+
}), 422)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
let dataToWrite = data
|
|
218
|
+
if (collection.schema !== undefined) {
|
|
219
|
+
const validated = await validateSchema(collection.schema, data)
|
|
220
|
+
if (!validated.ok) {
|
|
221
|
+
return htmlResponse(renderEditorPage({
|
|
222
|
+
basePath,
|
|
223
|
+
collection,
|
|
224
|
+
mode,
|
|
225
|
+
slug,
|
|
226
|
+
locale: localeCheck.locale,
|
|
227
|
+
fields,
|
|
228
|
+
data,
|
|
229
|
+
rawFrontmatterYaml,
|
|
230
|
+
body,
|
|
231
|
+
errors: collectValidationErrors(validated.issues),
|
|
232
|
+
schemaWarning: warning,
|
|
233
|
+
}), 422)
|
|
234
|
+
}
|
|
235
|
+
if (validated.value !== null && typeof validated.value === 'object' && !Array.isArray(validated.value))
|
|
236
|
+
dataToWrite = validated.value as Record<string, unknown>
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
mkdirSync(dirname(pathRes.filePath), { recursive: true })
|
|
240
|
+
writeFileSync(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body), 'utf8')
|
|
241
|
+
collection.clearCache()
|
|
242
|
+
|
|
243
|
+
const target = safeRedirect(
|
|
244
|
+
`${basePath}/${encodeURIComponent(collection.name)}/${encodeSlugPath(pathRes.slug)}${localeQueryString(pathRes.locale, 'saved=1')}`,
|
|
245
|
+
basePath,
|
|
246
|
+
)
|
|
247
|
+
return new Response(null, { status: 303, headers: { location: target } })
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Registers all dev-only CMS routes on `api`. */
|
|
251
|
+
export function registerCmsRoutes(api: ServerPluginAPI, config: CmsHandlerConfig): void {
|
|
252
|
+
const { basePath, guard } = config
|
|
253
|
+
|
|
254
|
+
const guarded = (
|
|
255
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>,
|
|
256
|
+
): ((ctx: RequestContext) => Promise<Response>) => wrapGuarded(guard, handler)
|
|
257
|
+
|
|
258
|
+
const findCollection = async (name: string): Promise<ContentCollectionDescriptor | undefined> => {
|
|
259
|
+
const cols = await loadCollections(api.inject(CONTENT_COLLECTIONS_SERVICE), api.root)
|
|
260
|
+
return cols.find(c => c.name === name)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
api.route('GET', `${basePath}/_assets/cms.css`, guarded(() => new Response(CMS_CSS, {
|
|
264
|
+
headers: {
|
|
265
|
+
'content-type': 'text/css; charset=utf-8',
|
|
266
|
+
'cache-control': 'no-store',
|
|
267
|
+
},
|
|
268
|
+
})))
|
|
269
|
+
|
|
270
|
+
api.route('GET', `${basePath}/_assets/cms.js`, guarded(() => new Response(CMS_JS, {
|
|
271
|
+
headers: {
|
|
272
|
+
'content-type': 'application/javascript; charset=utf-8',
|
|
273
|
+
'cache-control': 'no-store',
|
|
274
|
+
},
|
|
275
|
+
})))
|
|
276
|
+
|
|
277
|
+
api.route('POST', `${basePath}/_preview`, guarded(async (ctx) => {
|
|
278
|
+
const markdown = await readPreviewMarkdown(ctx.request)
|
|
279
|
+
const html = renderMarkdownPreview(markdown)
|
|
280
|
+
const accept = ctx.request.headers.get('accept') ?? ''
|
|
281
|
+
if (accept.includes('application/json'))
|
|
282
|
+
return ctx.json({ html })
|
|
283
|
+
return htmlResponse(html)
|
|
284
|
+
}), { csrf: true })
|
|
285
|
+
|
|
286
|
+
api.route('GET', basePath, guarded(async () => {
|
|
287
|
+
const service = api.inject(CONTENT_COLLECTIONS_SERVICE)
|
|
288
|
+
const cols = await loadCollections(service, api.root)
|
|
289
|
+
const cards = await Promise.all(cols.map(async col => ({
|
|
290
|
+
name: col.name,
|
|
291
|
+
entryCount: await countCollectionEntries(col),
|
|
292
|
+
editable: col.dir !== undefined,
|
|
293
|
+
localized: col.localized,
|
|
294
|
+
defaultLocale: col.defaultLocale,
|
|
295
|
+
hasSchema: col.schema !== undefined,
|
|
296
|
+
})))
|
|
297
|
+
return htmlResponse(renderCollectionsPage(basePath, cards, service === undefined))
|
|
298
|
+
}))
|
|
299
|
+
|
|
300
|
+
api.route('GET', `${basePath}/:collection`, guarded(async (ctx) => {
|
|
301
|
+
const col = await findCollection(ctx.params.collection ?? '')
|
|
302
|
+
if (col === undefined)
|
|
303
|
+
return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
|
|
304
|
+
const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
|
|
305
|
+
if (!localeCheck.ok)
|
|
306
|
+
return textResponse(localeCheck.message, 400)
|
|
307
|
+
const query = (ctx.url.searchParams.get('q') ?? '').trim()
|
|
308
|
+
const allEntries = await col.all(localeCheck.locale)
|
|
309
|
+
const needle = query.toLowerCase()
|
|
310
|
+
const entries = needle.length > 0
|
|
311
|
+
? allEntries.filter(entry => matchesSearchQuery(entry, needle))
|
|
312
|
+
: allEntries
|
|
313
|
+
return htmlResponse(renderEntriesPage({
|
|
314
|
+
basePath,
|
|
315
|
+
collection: col,
|
|
316
|
+
entries,
|
|
317
|
+
activeLocale: localeCheck.locale,
|
|
318
|
+
locales: collectionLocales(col),
|
|
319
|
+
query,
|
|
320
|
+
}))
|
|
321
|
+
}))
|
|
322
|
+
|
|
323
|
+
api.route('GET', `${basePath}/:collection/new`, guarded(async (ctx) => {
|
|
324
|
+
const col = await findCollection(ctx.params.collection ?? '')
|
|
325
|
+
if (col === undefined)
|
|
326
|
+
return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
|
|
327
|
+
if (col.dir === undefined)
|
|
328
|
+
return textResponse(`Collection "${col.name}" is read-only.`, 403)
|
|
329
|
+
const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
|
|
330
|
+
if (!localeCheck.ok)
|
|
331
|
+
return textResponse(localeCheck.message, 400)
|
|
332
|
+
const { fields, warning } = resolveSchemaFields(col)
|
|
333
|
+
return htmlResponse(renderEditorPage({
|
|
334
|
+
basePath,
|
|
335
|
+
collection: col,
|
|
336
|
+
mode: 'new',
|
|
337
|
+
slug: '',
|
|
338
|
+
locale: localeCheck.locale,
|
|
339
|
+
fields,
|
|
340
|
+
data: buildDefaultData(fields),
|
|
341
|
+
body: '',
|
|
342
|
+
errors: {},
|
|
343
|
+
schemaWarning: warning,
|
|
344
|
+
}))
|
|
345
|
+
}))
|
|
346
|
+
|
|
347
|
+
api.route('POST', `${basePath}/:collection/new`, 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
|
+
return await handleEditorPost({ ctx, basePath, collection: col, mode: 'new' })
|
|
352
|
+
}), { csrf: true })
|
|
353
|
+
|
|
354
|
+
api.route('GET', `${basePath}/:collection/*slug`, guarded(async (ctx) => {
|
|
355
|
+
const col = await findCollection(ctx.params.collection ?? '')
|
|
356
|
+
if (col === undefined)
|
|
357
|
+
return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
|
|
358
|
+
const slug = ctx.params.slug ?? ''
|
|
359
|
+
if (slug.length === 0)
|
|
360
|
+
return textResponse('Missing entry slug.', 400)
|
|
361
|
+
const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
|
|
362
|
+
if (!localeCheck.ok)
|
|
363
|
+
return textResponse(localeCheck.message, 400)
|
|
364
|
+
const entry = await col.get(slug, localeCheck.locale)
|
|
365
|
+
if (entry === undefined)
|
|
366
|
+
return textResponse(`Entry "${slug}" not found in collection "${col.name}".`, 404)
|
|
367
|
+
if (col.dir !== undefined && entry.file !== undefined) {
|
|
368
|
+
const pathRes = resolveEntryFilePath(col, slug, localeCheck.locale, entry.file)
|
|
369
|
+
if (!pathRes.ok)
|
|
370
|
+
return textResponse(pathRes.message, pathRes.status)
|
|
371
|
+
}
|
|
372
|
+
const { fields, warning } = resolveSchemaFields(col)
|
|
373
|
+
return htmlResponse(renderEditorPage({
|
|
374
|
+
basePath,
|
|
375
|
+
collection: col,
|
|
376
|
+
mode: 'edit',
|
|
377
|
+
slug: entry.slug,
|
|
378
|
+
locale: localeCheck.locale,
|
|
379
|
+
fields,
|
|
380
|
+
data: entry.data,
|
|
381
|
+
body: entry.body,
|
|
382
|
+
errors: {},
|
|
383
|
+
saved: ctx.url.searchParams.get('saved') === '1',
|
|
384
|
+
schemaWarning: warning,
|
|
385
|
+
}))
|
|
386
|
+
}))
|
|
387
|
+
|
|
388
|
+
api.route('POST', `${basePath}/:collection/*slug`, guarded(async (ctx) => {
|
|
389
|
+
const col = await findCollection(ctx.params.collection ?? '')
|
|
390
|
+
if (col === undefined)
|
|
391
|
+
return textResponse(`Collection "${ctx.params.collection ?? ''}" not found.`, 404)
|
|
392
|
+
const slug = ctx.params.slug ?? ''
|
|
393
|
+
if (slug.length === 0)
|
|
394
|
+
return textResponse('Missing entry slug.', 400)
|
|
395
|
+
return await handleEditorPost({ ctx, basePath, collection: col, mode: 'edit', routeSlug: slug })
|
|
396
|
+
}), { csrf: true })
|
|
397
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
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 './shared'
|
|
6
|
+
import { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, definePlugin } from 'prunelle/config'
|
|
7
|
+
import { escAttr } from 'prunelle/server'
|
|
8
|
+
import { registerCmsRoutes } from './handlers'
|
|
9
|
+
import { registerInlineCmsRoutes } from './inline-handlers'
|
|
10
|
+
import { checkCollectionSchema } from './schema'
|
|
11
|
+
import { runGuard } from './shared'
|
|
12
|
+
|
|
13
|
+
export type { CmsGuard } from './shared'
|
|
14
|
+
export type { CmsField, CmsFieldKind, CmsSchemaIssue, ParsedCmsSchema } from './schema'
|
|
15
|
+
|
|
16
|
+
export interface CmsOptions {
|
|
17
|
+
/** 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). */
|
|
18
|
+
guard?: CmsGuard | undefined
|
|
19
|
+
/** Base URL path where the dev CMS is mounted (default: `'/_pru/cms'`). */
|
|
20
|
+
basePath?: string | undefined
|
|
21
|
+
/** Inject the dev-only Shadow DOM in-page editing overlay on pages rendering file-backed collections (default: `true`). */
|
|
22
|
+
inline?: boolean | undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface InlineRequestState {
|
|
26
|
+
readonly service: ContentCollectionsService | undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function normalizeBasePath(raw: string | undefined): string {
|
|
30
|
+
const trimmed = (raw ?? '/_pru/cms').trim()
|
|
31
|
+
if (trimmed.length === 0 || trimmed === '/')
|
|
32
|
+
return '/_pru/cms'
|
|
33
|
+
const withLead = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
|
|
34
|
+
return withLead.endsWith('/') ? withLead.slice(0, -1) : withLead
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isUnderBasePath(pathname: string, basePath: string): boolean {
|
|
38
|
+
return pathname === basePath || pathname.startsWith(`${basePath}/`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Registers the dev-only schema-driven CMS for `@prunellejs/content` collections.
|
|
43
|
+
* Mounts zero routes in production (`dev: false`), emits nothing on `--static`, and ships 0 B to production pages.
|
|
44
|
+
*/
|
|
45
|
+
export function cms(options: CmsOptions = {}): PrunellePlugin {
|
|
46
|
+
const basePath = normalizeBasePath(options.basePath)
|
|
47
|
+
const inlineEnabled = options.inline !== false
|
|
48
|
+
const devInlineRequests = new WeakMap<RequestContext, InlineRequestState>()
|
|
49
|
+
|
|
50
|
+
return definePlugin({
|
|
51
|
+
name: '@prunellejs/cms',
|
|
52
|
+
after: ['@prunellejs/content'],
|
|
53
|
+
async check(ctx) {
|
|
54
|
+
const service = ctx.inject?.(CONTENT_COLLECTIONS_SERVICE)
|
|
55
|
+
if (service === undefined)
|
|
56
|
+
return
|
|
57
|
+
const collections = service.discover !== undefined
|
|
58
|
+
? await service.discover(ctx.root)
|
|
59
|
+
: await service.list(ctx.root)
|
|
60
|
+
for (const col of collections) {
|
|
61
|
+
if (col.dir === undefined || col.schema === undefined)
|
|
62
|
+
continue
|
|
63
|
+
for (const err of checkCollectionSchema(col.name, col.schema))
|
|
64
|
+
ctx.error(err)
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
server(api) {
|
|
68
|
+
if (!api.dev)
|
|
69
|
+
return
|
|
70
|
+
if (inlineEnabled) {
|
|
71
|
+
api.provide(CMS_INLINE_ENABLED_SERVICE, true)
|
|
72
|
+
registerInlineCmsRoutes(api, { basePath, guard: options.guard })
|
|
73
|
+
api.use((ctx, next) => {
|
|
74
|
+
devInlineRequests.set(ctx, { service: api.inject(CONTENT_COLLECTIONS_SERVICE) })
|
|
75
|
+
return next()
|
|
76
|
+
}, { scope: 'rendered' })
|
|
77
|
+
}
|
|
78
|
+
registerCmsRoutes(api, { basePath, guard: options.guard })
|
|
79
|
+
},
|
|
80
|
+
async head(docHead, ctx) {
|
|
81
|
+
if (!inlineEnabled)
|
|
82
|
+
return
|
|
83
|
+
const state = devInlineRequests.get(ctx)
|
|
84
|
+
if (state === undefined || isUnderBasePath(ctx.url.pathname, basePath))
|
|
85
|
+
return
|
|
86
|
+
const accessed = state.service?.accessedEntries?.(ctx) ?? []
|
|
87
|
+
if (accessed.length === 0)
|
|
88
|
+
return
|
|
89
|
+
const blocked = await runGuard(options.guard, ctx)
|
|
90
|
+
if (blocked !== undefined)
|
|
91
|
+
return
|
|
92
|
+
const payload = JSON.stringify({ basePath, entries: accessed })
|
|
93
|
+
docHead.add(
|
|
94
|
+
`<meta name="pru-cms-config" content="${escAttr(payload)}">`
|
|
95
|
+
+ `<script type="module" src="${escAttr(`${basePath}/_assets/inline.js`)}" defer></script>`,
|
|
96
|
+
)
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
}
|