@prunellejs/cms 0.0.0-stage → 0.7.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.
@@ -0,0 +1,248 @@
1
+ // Dev-only JSON endpoints and Shadow DOM overlay assets for @prunellejs/cms in-page editing.
2
+
3
+ import type { ContentCollectionDescriptor, ServerPluginAPI } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { CmsHandlerConfig } from './shared'
6
+ import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
7
+ import { validateSchema } from 'prunelle/server'
8
+ import {
9
+ findLoneSurrogate,
10
+ resolveEntryFilePath,
11
+ serializeFrontmatterYaml,
12
+ serializeMarkdownEntry,
13
+ validateLocale,
14
+ } from './form-data'
15
+ import { INLINE_CMS_CSS } from './inline-css'
16
+ import { INLINE_CMS_JS } from './inline-js'
17
+ import { encodeSlugPath, localeQueryString } from './render'
18
+ import { renderMarkdownPreview } from './sanitize'
19
+ import {
20
+ collectValidationErrors,
21
+ LONE_SURROGATE_MESSAGE,
22
+ loadCollections,
23
+ parseRawFrontmatterYaml,
24
+ resolveSchemaFields,
25
+ wrapGuarded,
26
+ } from './shared'
27
+ import { readEntrySource, replaceEntryFile } from './write-file'
28
+
29
+ const FORBIDDEN_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
30
+
31
+ interface InlinePatchPayload {
32
+ collection?: unknown
33
+ slug?: unknown
34
+ locale?: unknown
35
+ data?: unknown
36
+ patch?: unknown
37
+ rawFrontmatterYaml?: unknown
38
+ body?: unknown
39
+ }
40
+
41
+ function clonePlainData(value: unknown): unknown {
42
+ if (value === null || value === undefined || typeof value !== 'object')
43
+ return value
44
+ if (value instanceof Date)
45
+ return value.toISOString()
46
+ if (Array.isArray(value))
47
+ return value.map(clonePlainData)
48
+ const out: Record<string, unknown> = {}
49
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
50
+ if (!FORBIDDEN_SEGMENTS.has(k))
51
+ out[k] = clonePlainData(v)
52
+ }
53
+ return out
54
+ }
55
+
56
+ function applyDottedPatch(target: Record<string, unknown>, patch: Record<string, unknown>): boolean {
57
+ for (const [rawPath, value] of Object.entries(patch)) {
58
+ const segments = rawPath.split('.').filter(Boolean)
59
+ if (segments.length === 0 || segments.some(seg => FORBIDDEN_SEGMENTS.has(seg)))
60
+ return false
61
+ let cur: Record<string, unknown> = target
62
+ for (let i = 0; i < segments.length - 1; i++) {
63
+ const seg = segments[i]!
64
+ const next = Object.hasOwn(cur, seg) ? cur[seg] : undefined
65
+ if (next === null || typeof next !== 'object' || Array.isArray(next)) {
66
+ const created: Record<string, unknown> = {}
67
+ cur[seg] = created
68
+ cur = created
69
+ }
70
+ else {
71
+ cur = next as Record<string, unknown>
72
+ }
73
+ }
74
+ const last = segments[segments.length - 1]!
75
+ if (value === undefined)
76
+ delete cur[last]
77
+ else
78
+ cur[last] = clonePlainData(value)
79
+ }
80
+ return true
81
+ }
82
+
83
+ function resolvePatchedFrontmatter(
84
+ payload: InlinePatchPayload,
85
+ existingData: Record<string, unknown>,
86
+ ): { ok: true, data: Record<string, unknown> } | { ok: false, status: 400 | 422, errors: Record<string, string> } {
87
+ if (typeof payload.rawFrontmatterYaml === 'string') {
88
+ const parsed = parseRawFrontmatterYaml(payload.rawFrontmatterYaml)
89
+ if (!parsed.ok)
90
+ return { ok: false, status: 422, errors: { __frontmatter_yaml: parsed.message } }
91
+ return { ok: true, data: parsed.data }
92
+ }
93
+
94
+ if (payload.data !== undefined) {
95
+ if (payload.data === null || typeof payload.data !== 'object' || Array.isArray(payload.data))
96
+ return { ok: false, status: 400, errors: { '': 'Field "data" must be an object.' } }
97
+ return { ok: true, data: clonePlainData(payload.data) as Record<string, unknown> }
98
+ }
99
+
100
+ if (payload.patch !== undefined) {
101
+ if (payload.patch === null || typeof payload.patch !== 'object' || Array.isArray(payload.patch))
102
+ return { ok: false, status: 400, errors: { '': 'Field "patch" must be an object.' } }
103
+ const merged = clonePlainData(existingData) as Record<string, unknown>
104
+ if (!applyDottedPatch(merged, payload.patch as Record<string, unknown>))
105
+ return { ok: false, status: 400, errors: { '': 'Invalid patch field path.' } }
106
+ return { ok: true, data: merged }
107
+ }
108
+
109
+ return { ok: true, data: clonePlainData(existingData) as Record<string, unknown> }
110
+ }
111
+
112
+ /** Registers dev-only in-page CMS overlay assets and JSON endpoints (`/_entry`, `/_inline`). */
113
+ export function registerInlineCmsRoutes(api: ServerPluginAPI, config: CmsHandlerConfig): void {
114
+ const { basePath, guard } = config
115
+ const guarded = (
116
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
117
+ ): ((ctx: RequestContext) => Promise<Response>) => wrapGuarded(guard, handler)
118
+
119
+ const findCollection = async (name: string): Promise<ContentCollectionDescriptor | undefined> => {
120
+ const cols = await loadCollections(api.inject(CONTENT_COLLECTIONS_SERVICE), api.root)
121
+ return cols.find(c => c.name === name)
122
+ }
123
+
124
+ api.route('GET', `${basePath}/_assets/inline.css`, guarded(() => new Response(INLINE_CMS_CSS, {
125
+ headers: {
126
+ 'content-type': 'text/css; charset=utf-8',
127
+ 'cache-control': 'no-store',
128
+ },
129
+ })))
130
+
131
+ api.route('GET', `${basePath}/_assets/inline.js`, guarded(() => new Response(INLINE_CMS_JS, {
132
+ headers: {
133
+ 'content-type': 'application/javascript; charset=utf-8',
134
+ 'cache-control': 'no-store',
135
+ },
136
+ })))
137
+
138
+ api.route('GET', `${basePath}/_entry`, guarded(async (ctx) => {
139
+ const colName = (ctx.url.searchParams.get('collection') ?? '').trim()
140
+ const slug = (ctx.url.searchParams.get('slug') ?? '').trim()
141
+ if (colName.length === 0 || slug.length === 0)
142
+ return ctx.json({ ok: false, error: 'Missing collection or slug.' }, { status: 400 })
143
+
144
+ const col = await findCollection(colName)
145
+ if (col === undefined)
146
+ return ctx.json({ ok: false, error: `Collection "${colName}" not found.` }, { status: 404 })
147
+ if (col.dir === undefined)
148
+ return ctx.json({ ok: false, error: `Collection "${col.name}" is read-only.` }, { status: 403 })
149
+
150
+ const localeCheck = validateLocale(col, ctx.url.searchParams.get('locale') ?? undefined)
151
+ if (!localeCheck.ok)
152
+ return ctx.json({ ok: false, error: localeCheck.message }, { status: 400 })
153
+
154
+ const entry = await col.get(slug, localeCheck.locale)
155
+ if (entry === undefined)
156
+ return ctx.json({ ok: false, error: `Entry "${slug}" not found in collection "${col.name}".` }, { status: 404 })
157
+ if (entry.file !== undefined) {
158
+ const pathRes = resolveEntryFilePath(col, slug, localeCheck.locale, entry.file)
159
+ if (!pathRes.ok)
160
+ return ctx.json({ ok: false, error: pathRes.message }, { status: pathRes.status })
161
+ }
162
+
163
+ const { fields, warning } = resolveSchemaFields(col)
164
+ const plainData = clonePlainData(entry.data) as Record<string, unknown>
165
+ const editUrl = `${basePath}/${encodeURIComponent(col.name)}/${encodeSlugPath(entry.slug)}${localeQueryString(localeCheck.locale)}`
166
+ return ctx.json({
167
+ ok: true,
168
+ collection: col.name,
169
+ slug: entry.slug,
170
+ ...(localeCheck.locale !== undefined ? { locale: localeCheck.locale } : {}),
171
+ editable: true,
172
+ editUrl,
173
+ ...(fields !== undefined ? { fields } : {}),
174
+ ...(warning !== undefined ? { schemaWarning: warning } : {}),
175
+ data: plainData,
176
+ rawFrontmatterYaml: serializeFrontmatterYaml(plainData),
177
+ body: entry.body,
178
+ })
179
+ }))
180
+
181
+ api.route('PATCH', `${basePath}/_inline`, guarded(async (ctx) => {
182
+ let payload: InlinePatchPayload
183
+ try {
184
+ payload = await ctx.request.json() as InlinePatchPayload
185
+ }
186
+ catch {
187
+ return ctx.json({ ok: false, error: 'Expected JSON request body.' }, { status: 400 })
188
+ }
189
+
190
+ const colName = typeof payload.collection === 'string' ? payload.collection.trim() : ''
191
+ const slug = typeof payload.slug === 'string' ? payload.slug.trim() : ''
192
+ const rawLocale = typeof payload.locale === 'string' ? payload.locale : undefined
193
+ if (colName.length === 0 || slug.length === 0)
194
+ return ctx.json({ ok: false, error: 'Missing collection or slug.' }, { status: 400 })
195
+
196
+ const col = await findCollection(colName)
197
+ if (col === undefined)
198
+ return ctx.json({ ok: false, error: `Collection "${colName}" not found.` }, { status: 404 })
199
+ if (col.dir === undefined)
200
+ return ctx.json({ ok: false, error: `Collection "${col.name}" is read-only.` }, { status: 403 })
201
+
202
+ const localeCheck = validateLocale(col, rawLocale)
203
+ if (!localeCheck.ok)
204
+ return ctx.json({ ok: false, error: localeCheck.message }, { status: 400 })
205
+
206
+ const existingEntry = await col.get(slug, localeCheck.locale)
207
+ if (existingEntry === undefined)
208
+ return ctx.json({ ok: false, error: `Entry "${slug}" not found in collection "${col.name}".` }, { status: 404 })
209
+
210
+ const pathRes = resolveEntryFilePath(col, slug, localeCheck.locale, existingEntry.file)
211
+ if (!pathRes.ok)
212
+ return ctx.json({ ok: false, error: pathRes.message }, { status: pathRes.status })
213
+
214
+ const patched = resolvePatchedFrontmatter(payload, existingEntry.data)
215
+ if (!patched.ok)
216
+ return ctx.json({ ok: false, errors: patched.errors }, { status: patched.status })
217
+
218
+ const badPath = findLoneSurrogate(patched.data)
219
+ if (badPath !== undefined)
220
+ return ctx.json({ ok: false, errors: { [badPath]: LONE_SURROGATE_MESSAGE } }, { status: 422 })
221
+
222
+ let dataToWrite = patched.data
223
+ if (col.schema !== undefined) {
224
+ const validated = await validateSchema(col.schema, patched.data)
225
+ if (!validated.ok)
226
+ return ctx.json({ ok: false, errors: collectValidationErrors(validated.issues) }, { status: 422 })
227
+ if (validated.value !== null && typeof validated.value === 'object' && !Array.isArray(validated.value))
228
+ dataToWrite = validated.value as Record<string, unknown>
229
+ }
230
+
231
+ const nextBody = typeof payload.body === 'string' ? payload.body : existingEntry.body
232
+ const source = readEntrySource(pathRes.filePath)
233
+ replaceEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, nextBody, source === undefined ? undefined : { source }))
234
+ col.clearCache()
235
+
236
+ const plainData = clonePlainData(dataToWrite) as Record<string, unknown>
237
+ return ctx.json({
238
+ ok: true,
239
+ collection: col.name,
240
+ slug: pathRes.slug,
241
+ ...(pathRes.locale !== undefined ? { locale: pathRes.locale } : {}),
242
+ data: plainData,
243
+ rawFrontmatterYaml: serializeFrontmatterYaml(plainData),
244
+ body: nextBody,
245
+ previewHtml: renderMarkdownPreview(nextBody),
246
+ })
247
+ }), { csrf: true })
248
+ }