@prunellejs/cms 0.6.0 → 0.7.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -10,11 +10,11 @@
10
10
 
11
11
  Register `cms()` in `prunelle.config.ts` alongside `content()` from `@prunellejs/content`. Collections are discovered automatically via the shared `CONTENT_COLLECTIONS_SERVICE` — never declare fields twice.
12
12
 
13
- - `guard?: (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>`: runs on every CMS route and gates in-page overlay injection. Return `false` for `403 Forbidden`, or return a `Response` (e.g. a login redirect).
13
+ - `guard?: (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>`: runs on every CMS route and gates in-page overlay injection. Return `false` for `403 Forbidden`, or return a `Response` (e.g. a login redirect). Optional on a loopback `prunelle dev`; with `prunelle dev --host` on an address other machines reach, the CMS throws at start without one.
14
14
  - `basePath?: string`: URL prefix where the dev CMS is mounted (default `'/_pru/cms'`).
15
15
  - `inline?: boolean`: inject the dev-only Shadow DOM in-page editing overlay on pages that read file-backed collections (default `true`; set `false` for `/_pru/cms`-only editing).
16
16
 
17
- ## Mounted Routes (dev-only — never mounted when `dev: false` or on `--static`)
17
+ ## Mounted Routes (dev-only — never mounted when `dev: false` or on `--static`, and their code is not even loaded then)
18
18
 
19
19
  - `GET /_pru/cms` — list all collections with entry counts and links to create entries.
20
20
  - `GET /_pru/cms/:collection` — list entries with optional `?locale=...` switching and `?q=...` filtering.
@@ -22,9 +22,16 @@ Register `cms()` in `prunelle.config.ts` alongside `content()` from `@prunellejs
22
22
  - `GET /_pru/cms/:collection/*slug` & `POST /_pru/cms/:collection/*slug` — edit an existing entry (supports nested slugs and `?locale=...`).
23
23
  - `GET /_pru/cms/_entry?collection=...&slug=...&locale=...` — JSON metadata, schema fields, frontmatter, and Markdown body for the in-page overlay.
24
24
  - `PATCH /_pru/cms/_inline` — CSRF-protected, Standard Schema-validated JSON patch/save endpoint used by the in-page overlay (`422` returns `{ ok: false, errors }`).
25
- - `POST /_pru/cms/_preview` — renders sanitized Markdown preview HTML via `Bun.markdown.html()`.
25
+ - `POST /_pru/cms/_preview` — renders Markdown preview HTML via `Bun.markdown.html()`, sanitized with the allowlist `@prunellejs/content` applies to the published page.
26
26
  - `GET /_pru/cms/_assets/cms.css`, `cms.js`, `inline.css`, `inline.js` — self-contained RGAA-accessible stylesheets and scripts (0 B in production/`--static`).
27
27
 
28
+ ## Saving and slugs
29
+
30
+ - Slugs follow `@prunellejs/content`: `_index`, `café`, `my post`, nested `a/b c`. Refused: empty, `.`, `..` and `__proto__` segments, backslash, control characters, lone surrogates. A segment over 252 bytes or a path over 4000 bytes is a `422` field error on the slug ("too long").
31
+ - Create is exclusive (`wx`): a concurrent second create of one slug gets `422` "An entry with this slug already exists.". Update writes a temp file in the entry's folder and renames it (a symlinked entry keeps its link).
32
+ - Frontmatter is edited in place: comments, order and keys the form has no field for are kept, only changed keys are rewritten (a trailing `# note` on a plain one-line value stays), new keys are appended. Comments inside a changed nested value or list are dropped.
33
+ - `PATCH /_pru/cms/_inline` answers `422` with `errors` naming the field when a value or key holds a lone UTF-16 surrogate.
34
+
28
35
  ## In-Page Editing (dev-only, zero app markup)
29
36
 
30
37
  When `inline` is enabled (the default), `@prunellejs/content` tracks file-backed entries read during each dev request and wraps rendered `entry.html` in zero-impact HTML comment anchors (`<!--pru-cms:...-->`). Pages that render a collection entry automatically receive a Shadow DOM floating toolbar (`Alt+Shift+E` toggles Edit-on-Page mode, `Cmd/Ctrl+S` saves, `Escape` cancels):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/cms",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Schema-driven dev-only CMS plugin for Prunelle Markdown content collections",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-cms"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.6.0"
24
+ "prunelle": "^0.7.1"
25
25
  }
26
26
  }
package/src/form-data.ts CHANGED
@@ -5,13 +5,15 @@ import type { CmsField } from './schema'
5
5
  import { existsSync, lstatSync, readlinkSync, realpathSync } from 'node:fs'
6
6
  import { dirname, resolve } from 'node:path'
7
7
  import { isInside } from 'prunelle/config'
8
+ import { mergeFrontmatterYaml, serializeFrontmatterYaml } from './yaml-serialize'
8
9
 
9
10
  const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
10
11
 
11
12
  const SAFE_LOCALE_RE = /^[a-zA-Z0-9_-]{1,32}$/
12
- const SAFE_SLUG_SEG_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
13
- const YAML_PLAIN_SAFE_RE = /^[a-zA-Z0-9][a-zA-Z0-9 _./@+-]*$/
14
- const YAML_RESERVED_RE = /^(?:true|false|yes|no|on|off|null|~|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?|0x[0-9a-f]+|0o[0-7]+|\.inf|-\.inf|\.nan)$/i
13
+ // Content serves any file name in the collection folder, so a segment only refuses what could escape or break it.
14
+ const UNSAFE_SLUG_CHAR_RE = /[\0-\x1F\x7F\\]/
15
+ const MAX_SLUG_SEGMENT_BYTES = 252 // 255 minus the `.md` suffix
16
+ const MAX_ENTRY_PATH_BYTES = 4000 // PATH_MAX 4096 minus room for the temp file of a save
15
17
  const MAX_REPEATABLE_ROWS = 500
16
18
 
17
19
  export interface ParsedRowAction {
@@ -31,20 +33,24 @@ export interface EntryPathError {
31
33
  readonly ok: false
32
34
  readonly status: 400 | 403
33
35
  readonly message: string
36
+ /** Set when the slug is too long: shown as a field error on the slug. */
37
+ readonly tooLong?: true | undefined
34
38
  }
35
39
 
36
40
  /** Validates a slug (allowing nested `a/b/c` paths) and rejects traversal, empty segments, and unsafe characters. */
37
- export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string } {
41
+ export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string, tooLong?: true } {
38
42
  const trimmed = raw.trim()
39
43
  if (trimmed.length === 0)
40
44
  return { ok: false, message: 'Slug is required.' }
41
- if (trimmed.startsWith('/') || trimmed.endsWith('/') || trimmed.includes('\\') || trimmed.includes('\0'))
45
+ if (UNSAFE_SLUG_CHAR_RE.test(trimmed) || !trimmed.isWellFormed())
42
46
  return { ok: false, message: 'Slug contains invalid path characters.' }
43
47
  const clean = trimmed.replace(/\.(?:md|markdown)$/i, '')
44
48
  const segments = clean.split('/')
45
49
  for (const seg of segments) {
46
- if (seg.length === 0 || seg === '.' || seg === '..' || !SAFE_SLUG_SEG_RE.test(seg))
50
+ if (seg.length === 0 || seg === '.' || seg === '..' || seg === '__proto__')
47
51
  return { ok: false, message: `Slug segment "${seg}" is invalid.` }
52
+ if (Buffer.byteLength(seg) > MAX_SLUG_SEGMENT_BYTES)
53
+ return { ok: false, message: `Slug segment is too long (${MAX_SLUG_SEGMENT_BYTES} bytes at most).`, tooLong: true }
48
54
  }
49
55
  return { ok: true, slug: segments.join('/') }
50
56
  }
@@ -127,7 +133,7 @@ export function resolveEntryFilePath(
127
133
 
128
134
  const slugCheck = validateSlug(rawSlug)
129
135
  if (!slugCheck.ok)
130
- return { ok: false, status: 400, message: slugCheck.message }
136
+ return { ok: false, status: 400, message: slugCheck.message, tooLong: slugCheck.tooLong }
131
137
 
132
138
  const localeCheck = validateLocale(col, rawLocale)
133
139
  if (!localeCheck.ok)
@@ -144,6 +150,8 @@ export function resolveEntryFilePath(
144
150
 
145
151
  if (!isInside(baseDir, candidate))
146
152
  return { ok: false, status: 400, message: 'Refused path outside collection directory.' }
153
+ if (Buffer.byteLength(candidate) > MAX_ENTRY_PATH_BYTES)
154
+ return { ok: false, status: 400, message: 'Slug is too long for this collection folder.', tooLong: true }
147
155
 
148
156
  if (existsSync(baseDir)) {
149
157
  const realBase = realpathSync(baseDir)
@@ -365,95 +373,38 @@ export function normalizeFieldErrorPath(path: string): string {
365
373
  return path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')
366
374
  }
367
375
 
368
- function serializeYamlScalar(value: unknown): string {
369
- if (value === null || value === undefined)
370
- return 'null'
371
- if (typeof value === 'boolean')
372
- return value ? 'true' : 'false'
373
- if (typeof value === 'number')
374
- return Number.isFinite(value) ? String(value) : 'null'
375
- if (value instanceof Date)
376
- return JSON.stringify(value.toISOString())
377
- const str = String(value)
378
- if (str.length === 0)
379
- return '""'
380
- if (str.includes('\n') || str.includes('\r'))
381
- return JSON.stringify(str)
382
- if (str.trim() !== str || YAML_RESERVED_RE.test(str) || !YAML_PLAIN_SAFE_RE.test(str))
383
- return JSON.stringify(str)
384
- return str
385
- }
386
-
387
- function isRecord(value: unknown): value is Record<string, unknown> {
388
- return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
389
- }
376
+ export { serializeFrontmatterYaml }
390
377
 
391
- function serializeYamlObject(obj: Record<string, unknown>, indent: number): string[] {
392
- const pad = ' '.repeat(indent)
393
- const lines: string[] = []
394
- for (const [key, value] of Object.entries(obj)) {
395
- if (value === undefined)
396
- continue
397
- const yamlKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : JSON.stringify(key)
398
- if (Array.isArray(value)) {
399
- if (value.length === 0) {
400
- lines.push(`${pad}${yamlKey}: []`)
401
- }
402
- else {
403
- lines.push(`${pad}${yamlKey}:`)
404
- lines.push(...serializeYamlArray(value, indent + 2))
405
- }
406
- }
407
- else if (isRecord(value)) {
408
- const inner = serializeYamlObject(value, indent + 2)
409
- if (inner.length === 0) {
410
- lines.push(`${pad}${yamlKey}: {}`)
411
- }
412
- else {
413
- lines.push(`${pad}${yamlKey}:`)
414
- lines.push(...inner)
415
- }
416
- }
417
- else {
418
- lines.push(`${pad}${yamlKey}: ${serializeYamlScalar(value)}`)
419
- }
420
- }
421
- return lines
422
- }
423
-
424
- function serializeYamlArray(arr: readonly unknown[], indent: number): string[] {
425
- const pad = ' '.repeat(indent)
426
- const lines: string[] = []
427
- for (const item of arr) {
428
- if (isRecord(item)) {
429
- const inner = serializeYamlObject(item, indent + 2)
430
- if (inner.length === 0) {
431
- lines.push(`${pad}- {}`)
432
- }
433
- else {
434
- lines.push(`${pad}- ${inner[0]!.slice(indent + 2)}`)
435
- for (let i = 1; i < inner.length; i++)
436
- lines.push(inner[i]!)
437
- }
438
- }
439
- else if (Array.isArray(item)) {
440
- lines.push(`${pad}- ${JSON.stringify(item)}`)
441
- }
442
- else {
443
- lines.push(`${pad}- ${serializeYamlScalar(item)}`)
444
- }
378
+ /** Returns the form path of the first key or string holding a lone UTF-16 surrogate, which would write a file that no longer parses. */
379
+ export function findLoneSurrogate(value: unknown, path = ''): string | undefined {
380
+ if (typeof value === 'string')
381
+ return value.isWellFormed() ? undefined : path
382
+ if (value === null || typeof value !== 'object')
383
+ return undefined
384
+ const entries: [string, unknown][] = Array.isArray(value)
385
+ ? value.map((item, i) => [`[${i}]`, item])
386
+ : Object.entries(value as Record<string, unknown>)
387
+ for (const [key, child] of entries) {
388
+ const childPath = Array.isArray(value) ? `${path}${key}` : (path === '' ? key : `${path}.${key}`)
389
+ if (!Array.isArray(value) && !key.isWellFormed())
390
+ return childPath
391
+ const found = findLoneSurrogate(child, childPath)
392
+ if (found !== undefined)
393
+ return found
445
394
  }
446
- return lines
395
+ return undefined
447
396
  }
448
397
 
449
- /** Serializes a frontmatter object into clean YAML text. */
450
- export function serializeFrontmatterYaml(data: Record<string, unknown>): string {
451
- return serializeYamlObject(data, 0).join('\n')
398
+ export interface ExistingEntrySource {
399
+ readonly source: string
400
+ /** Keys the form edits; others are left untouched. Undefined means every key. */
401
+ readonly owned?: ReadonlySet<string> | undefined
452
402
  }
453
403
 
454
- /** Serializes frontmatter and Markdown body into a `.md` file string. */
455
- export function serializeMarkdownEntry(data: Record<string, unknown>, body: string): string {
456
- const yaml = serializeFrontmatterYaml(data)
404
+ /** Serializes frontmatter and Markdown body into a `.md` file string, editing `existing` in place when given. */
405
+ export function serializeMarkdownEntry(data: Record<string, unknown>, body: string, existing?: ExistingEntrySource): string {
406
+ const merged = existing === undefined ? undefined : mergeFrontmatterYaml(existing.source, data, existing.owned)
407
+ const yaml = merged ?? serializeFrontmatterYaml(data)
457
408
  const normalizedBody = body.replace(/\r\n/g, '\n')
458
409
  const trimmedBody = normalizedBody.endsWith('\n') || normalizedBody.length === 0
459
410
  ? normalizedBody
package/src/guard.ts ADDED
@@ -0,0 +1,23 @@
1
+ // The access guard, kept apart from the editor so the plugin entry loads nothing else outside dev.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+
5
+ export type CmsGuard = (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>
6
+
7
+ export function textResponse(text: string, status: number): Response {
8
+ return new Response(text, {
9
+ status,
10
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
11
+ })
12
+ }
13
+
14
+ export async function runGuard(guard: CmsGuard | undefined, ctx: RequestContext): Promise<Response | undefined> {
15
+ if (guard === undefined)
16
+ return undefined
17
+ const decision = await guard(ctx)
18
+ if (decision instanceof Response)
19
+ return decision
20
+ if (decision === false)
21
+ return textResponse('Forbidden', 403)
22
+ return undefined
23
+ }
package/src/handlers.ts CHANGED
@@ -4,8 +4,7 @@ import type { ContentCollectionDescriptor, ContentCollectionEntrySummary, Server
4
4
  import type { RequestContext } from 'prunelle/server'
5
5
  import type { CmsField } from './schema'
6
6
  import type { CmsHandlerConfig } from './shared'
7
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
8
- import { dirname } from 'node:path'
7
+ import { existsSync } from 'node:fs'
9
8
  import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
10
9
  import { safeRedirect, validateSchema } from 'prunelle/server'
11
10
  import { CMS_CSS, CMS_JS } from './assets'
@@ -34,6 +33,7 @@ import {
34
33
  textResponse,
35
34
  wrapGuarded,
36
35
  } from './shared'
36
+ import { createEntryFile, readEntrySource, replaceEntryFile } from './write-file'
37
37
 
38
38
  export type { CmsGuard, CmsHandlerConfig } from './shared'
39
39
 
@@ -129,6 +129,20 @@ async function handleEditorPost(options: {
129
129
  let data: Record<string, unknown>
130
130
  let rawFrontmatterYaml: string | undefined
131
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
+
132
146
  if (fields !== undefined) {
133
147
  data = parseFormSubmission(formData, fields)
134
148
  }
@@ -136,21 +150,8 @@ async function handleEditorPost(options: {
136
150
  const rawYamlField = formData.get('__frontmatter_yaml')
137
151
  rawFrontmatterYaml = typeof rawYamlField === 'string' ? rawYamlField : ''
138
152
  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
- }
153
+ if (!yamlRes.ok)
154
+ return render(422, { __frontmatter_yaml: yamlRes.message }, {})
154
155
  data = yamlRes.data
155
156
  }
156
157
 
@@ -158,35 +159,11 @@ async function handleEditorPost(options: {
158
159
  const rowAction = parseRowAction(typeof rawAction === 'string' ? rawAction : null)
159
160
  if (rowAction !== undefined && fields !== undefined) {
160
161
  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)
162
+ return render(200, {})
173
163
  }
174
164
 
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
- }
165
+ if (mode === 'new' && slug.trim().length === 0)
166
+ return render(422, { __slug: 'Slug is required.' })
190
167
 
191
168
  const existingEntry = mode === 'edit'
192
169
  ? await collection.get(slug, localeCheck.locale)
@@ -196,48 +173,30 @@ async function handleEditorPost(options: {
196
173
 
197
174
  const pathRes = resolveEntryFilePath(collection, slug, localeCheck.locale, existingEntry?.file)
198
175
  if (!pathRes.ok)
199
- return textResponse(pathRes.message, pathRes.status)
176
+ return mode === 'new' && pathRes.tooLong ? render(422, { __slug: pathRes.message }) : textResponse(pathRes.message, pathRes.status)
200
177
 
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
- }
178
+ const slugTaken = { __slug: 'An entry with this slug already exists.' }
179
+ if (mode === 'new' && existsSync(pathRes.filePath))
180
+ return render(422, slugTaken)
216
181
 
217
182
  let dataToWrite = data
218
183
  if (collection.schema !== undefined) {
219
184
  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
- }
185
+ if (!validated.ok)
186
+ return render(422, collectValidationErrors(validated.issues))
235
187
  if (validated.value !== null && typeof validated.value === 'object' && !Array.isArray(validated.value))
236
188
  dataToWrite = validated.value as Record<string, unknown>
237
189
  }
238
190
 
239
- mkdirSync(dirname(pathRes.filePath), { recursive: true })
240
- writeFileSync(pathRes.filePath, serializeMarkdownEntry(dataToWrite, body), 'utf8')
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
+ }
241
200
  collection.clearCache()
242
201
 
243
202
  const target = safeRedirect(
package/src/index.ts CHANGED
@@ -2,15 +2,13 @@
2
2
 
3
3
  import type { ContentCollectionsService, PrunellePlugin } from 'prunelle/config'
4
4
  import type { RequestContext } from 'prunelle/server'
5
- import type { CmsGuard } from './shared'
5
+ import type { CmsGuard } from './guard'
6
6
  import { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, definePlugin } from 'prunelle/config'
7
7
  import { escAttr } from 'prunelle/server'
8
- import { registerCmsRoutes } from './handlers'
9
- import { registerInlineCmsRoutes } from './inline-handlers'
10
8
  import { checkCollectionSchema } from './schema'
11
- import { runGuard } from './shared'
9
+ import { runGuard } from './guard'
12
10
 
13
- export type { CmsGuard } from './shared'
11
+ export type { CmsGuard } from './guard'
14
12
  export type { CmsField, CmsFieldKind, CmsSchemaIssue, ParsedCmsSchema } from './schema'
15
13
 
16
14
  export interface CmsOptions {
@@ -64,9 +62,13 @@ export function cms(options: CmsOptions = {}): PrunellePlugin {
64
62
  ctx.error(err)
65
63
  }
66
64
  },
67
- server(api) {
65
+ async server(api) {
68
66
  if (!api.dev)
69
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')])
70
72
  if (inlineEnabled) {
71
73
  api.provide(CMS_INLINE_ENABLED_SERVICE, true)
72
74
  registerInlineCmsRoutes(api, { basePath, guard: options.guard })
@@ -3,11 +3,10 @@
3
3
  import type { ContentCollectionDescriptor, ServerPluginAPI } from 'prunelle/config'
4
4
  import type { RequestContext } from 'prunelle/server'
5
5
  import type { CmsHandlerConfig } from './shared'
6
- import { mkdirSync, writeFileSync } from 'node:fs'
7
- import { dirname } from 'node:path'
8
6
  import { CONTENT_COLLECTIONS_SERVICE } from 'prunelle/config'
9
7
  import { validateSchema } from 'prunelle/server'
10
8
  import {
9
+ findLoneSurrogate,
11
10
  resolveEntryFilePath,
12
11
  serializeFrontmatterYaml,
13
12
  serializeMarkdownEntry,
@@ -19,11 +18,13 @@ import { encodeSlugPath, localeQueryString } from './render'
19
18
  import { renderMarkdownPreview } from './sanitize'
20
19
  import {
21
20
  collectValidationErrors,
21
+ LONE_SURROGATE_MESSAGE,
22
22
  loadCollections,
23
23
  parseRawFrontmatterYaml,
24
24
  resolveSchemaFields,
25
25
  wrapGuarded,
26
26
  } from './shared'
27
+ import { readEntrySource, replaceEntryFile } from './write-file'
27
28
 
28
29
  const FORBIDDEN_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
29
30
 
@@ -214,6 +215,10 @@ export function registerInlineCmsRoutes(api: ServerPluginAPI, config: CmsHandler
214
215
  if (!patched.ok)
215
216
  return ctx.json({ ok: false, errors: patched.errors }, { status: patched.status })
216
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
+
217
222
  let dataToWrite = patched.data
218
223
  if (col.schema !== undefined) {
219
224
  const validated = await validateSchema(col.schema, patched.data)
@@ -224,8 +229,8 @@ export function registerInlineCmsRoutes(api: ServerPluginAPI, config: CmsHandler
224
229
  }
225
230
 
226
231
  const nextBody = typeof payload.body === 'string' ? payload.body : existingEntry.body
227
- mkdirSync(dirname(pathRes.filePath), { recursive: true })
228
- writeFileSync(pathRes.filePath, serializeMarkdownEntry(dataToWrite, nextBody), 'utf8')
232
+ const source = readEntrySource(pathRes.filePath)
233
+ replaceEntryFile(pathRes.filePath, serializeMarkdownEntry(dataToWrite, nextBody, source === undefined ? undefined : { source }))
229
234
  col.clearCache()
230
235
 
231
236
  const plainData = clonePlainData(dataToWrite) as Record<string, unknown>
package/src/sanitize.ts CHANGED
@@ -1,140 +1,6 @@
1
- // Self-contained Markdown preview renderer and strict HTML allowlist sanitizer for @prunellejs/cms.
1
+ // Markdown preview renderer for @prunellejs/cms, sanitized like @prunellejs/content renders the published page.
2
2
 
3
- const STRIP_BLOCK_RE = /<(script|style|iframe|object|embed|applet|noscript|template|svg|math|form)(?=[\s/>])[^>]*>[\s\S]*?<\/\1(?:[\s/][^>]*)?>/gi
4
- const STRIP_VOID_DANGEROUS_RE = /<(script|style|iframe|object|embed|applet|noscript|template|svg|math|form|base|link|meta)(?=[\s/>])[^>]*\/?>/gi
5
- const COMMENT_RE = /<!--[\s\S]*?(?:--!?>|$)/g
6
-
7
- const SAFE_TAGS = new Set([
8
- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
9
- 'p', 'br', 'hr', 'blockquote', 'pre', 'code',
10
- 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
11
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
12
- 'a', 'img', 'strong', 'em', 'b', 'i', 'u', 's', 'del', 'ins',
13
- 'sup', 'sub', 'kbd', 'mark', 'abbr', 'small', 'time',
14
- 'details', 'summary', 'figure', 'figcaption', 'div', 'span', 'input',
15
- ])
16
-
17
- const ALLOWED_ATTRS_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {
18
- a: new Set(['href', 'title', 'rel', 'target']),
19
- img: new Set(['src', 'alt', 'title', 'width', 'height']),
20
- th: new Set(['colspan', 'rowspan', 'scope', 'align']),
21
- td: new Set(['colspan', 'rowspan', 'align']),
22
- ol: new Set(['start', 'reversed']),
23
- li: new Set(['value']),
24
- details: new Set(['open']),
25
- time: new Set(['datetime']),
26
- input: new Set(['type', 'checked', 'disabled']),
27
- code: new Set(['class']),
28
- pre: new Set(['class']),
29
- }
30
-
31
- const URL_PROTOCOL_OK = /^(?:https?:|mailto:|tel:|#|\/|\.)/i
32
- const SAFE_DATA_IMG = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
33
- const SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/i
34
-
35
- function safeCodePoint(raw: string, radix: number): string {
36
- const cp = Number.parseInt(raw, radix)
37
- return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
38
- }
39
-
40
- function escapeAttrValue(val: string): string {
41
- return val
42
- .replaceAll('"', '&quot;')
43
- .replaceAll('\'', '&#39;')
44
- .replaceAll('<', '&lt;')
45
- .replaceAll('>', '&gt;')
46
- }
47
-
48
- function isUrlAllowed(raw: string): boolean {
49
- const decoded = raw
50
- .replace(/&#x([0-9a-f]+);?/gi, (_, h: string) => safeCodePoint(h, 16))
51
- .replace(/&#(\d+);?/g, (_, d: string) => safeCodePoint(d, 10))
52
- .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
53
- const lower = name.toLowerCase()
54
- if (lower === 'colon') return ':'
55
- if (lower === 'tab') return '\t'
56
- if (lower === 'newline') return '\n'
57
- return '&'
58
- })
59
- .replace(/[\u0000-\u0020\u007F]+/g, '')
60
- .trim()
61
- if (decoded === '')
62
- return true
63
- if (URL_PROTOCOL_OK.test(decoded) || SAFE_DATA_IMG.test(decoded))
64
- return true
65
- return !SCHEME_PREFIX.test(decoded)
66
- }
67
-
68
- const ATTR_PAIR_RE = /([a-zA-Z_:][a-zA-Z0-9_.:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
69
-
70
- function filterTagAttributes(tag: string, rawAttrs: string): string {
71
- const allowed = ALLOWED_ATTRS_BY_TAG[tag]
72
- if (allowed === undefined || rawAttrs.trim() === '')
73
- return ''
74
-
75
- const kept: string[] = []
76
- ATTR_PAIR_RE.lastIndex = 0
77
- let match = ATTR_PAIR_RE.exec(rawAttrs)
78
- while (match !== null) {
79
- const attrName = match[1]!.toLowerCase()
80
- const attrVal = match[2] ?? match[3] ?? match[4] ?? null
81
- if (allowed.has(attrName)) {
82
- if (tag === 'input' && attrName === 'type' && attrVal?.toLowerCase() !== 'checkbox') {
83
- match = ATTR_PAIR_RE.exec(rawAttrs)
84
- continue
85
- }
86
- if ((attrName === 'href' || attrName === 'src') && attrVal !== null && !isUrlAllowed(attrVal)) {
87
- match = ATTR_PAIR_RE.exec(rawAttrs)
88
- continue
89
- }
90
- kept.push(attrVal === null ? attrName : `${attrName}="${escapeAttrValue(attrVal)}"`)
91
- }
92
- match = ATTR_PAIR_RE.exec(rawAttrs)
93
- }
94
-
95
- if (tag === 'input') {
96
- if (!kept.some(entry => entry.startsWith('type=')))
97
- return ''
98
- if (!kept.includes('disabled'))
99
- kept.push('disabled')
100
- }
101
-
102
- return kept.length > 0 ? ` ${kept.join(' ')}` : ''
103
- }
104
-
105
- function sanitizePreviewPass(html: string): string {
106
- const withoutDangerous = html
107
- .replace(COMMENT_RE, '')
108
- .replace(STRIP_BLOCK_RE, '')
109
- .replace(STRIP_VOID_DANGEROUS_RE, '')
110
-
111
- return withoutDangerous.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([\s/][^>]*?)?(\/?)>/g, (_whole, slash: string, rawTag: string, rawAttrs: string | undefined, selfClose: string) => {
112
- const tag = rawTag.toLowerCase()
113
- if (!SAFE_TAGS.has(tag))
114
- return ''
115
- if (slash === '/')
116
- return `</${tag}>`
117
- const raw = rawAttrs ?? ''
118
- const isSelfClose = selfClose === '/' || /\/\s*$/.test(raw)
119
- const cleanedRaw = selfClose === '' && isSelfClose ? raw.replace(/\/\s*$/, '') : raw
120
- const attrs = filterTagAttributes(tag, cleanedRaw)
121
- if (tag === 'input' && attrs === '')
122
- return ''
123
- return `<${tag}${attrs}${isSelfClose ? ' /' : ''}>`
124
- })
125
- }
126
-
127
- /** Sanitizes HTML rendered from Markdown using a strict element and attribute allowlist. */
128
- export function sanitizePreviewHtml(html: string): string {
129
- let current = html
130
- for (let pass = 0; pass < 3; pass++) {
131
- const next = sanitizePreviewPass(current)
132
- if (next === current)
133
- return next
134
- current = next
135
- }
136
- return current
137
- }
3
+ import { sanitizeMarkdownHtml } from 'prunelle/internal/server'
138
4
 
139
5
  /** Renders Markdown to sanitized HTML using Bun's native Zig Markdown engine. */
140
6
  export function renderMarkdownPreview(markdown: string): string {
@@ -146,5 +12,5 @@ export function renderMarkdownPreview(markdown: string): string {
146
12
  tasklists: true,
147
13
  autolinks: true,
148
14
  })
149
- return sanitizePreviewHtml(rawHtml)
15
+ return sanitizeMarkdownHtml(rawHtml)
150
16
  }
package/src/shared.ts CHANGED
@@ -2,12 +2,17 @@
2
2
 
3
3
  import type { ContentCollectionDescriptor, ContentCollectionsService } from 'prunelle/config'
4
4
  import type { RequestContext } from 'prunelle/server'
5
+ import type { CmsGuard } from './guard'
6
+ import { runGuard } from './guard'
5
7
  import type { CmsField } from './schema'
6
8
  import { formatIssuePath } from 'prunelle/server'
7
9
  import { normalizeFieldErrorPath } from './form-data'
8
10
  import { extractJsonSchema, parseJsonSchemaFields } from './schema'
9
11
 
10
- export type CmsGuard = (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>
12
+ export const LONE_SURROGATE_MESSAGE = 'Contains an unpaired UTF-16 surrogate character; remove it.'
13
+
14
+ export type { CmsGuard } from './guard'
15
+ export { runGuard, textResponse } from './guard'
11
16
 
12
17
  export interface CmsHandlerConfig {
13
18
  readonly basePath: string
@@ -21,23 +26,7 @@ export function htmlResponse(html: string, status = 200): Response {
21
26
  })
22
27
  }
23
28
 
24
- export function textResponse(text: string, status: number): Response {
25
- return new Response(text, {
26
- status,
27
- headers: { 'content-type': 'text/plain; charset=utf-8' },
28
- })
29
- }
30
29
 
31
- export async function runGuard(guard: CmsGuard | undefined, ctx: RequestContext): Promise<Response | undefined> {
32
- if (guard === undefined)
33
- return undefined
34
- const decision = await guard(ctx)
35
- if (decision instanceof Response)
36
- return decision
37
- if (decision === false)
38
- return textResponse('Forbidden', 403)
39
- return undefined
40
- }
41
30
 
42
31
  export function wrapGuarded(
43
32
  guard: CmsGuard | undefined,
@@ -0,0 +1,58 @@
1
+ // Crash-safe entry writes: exclusive create for new entries, temp file plus rename for updates.
2
+
3
+ import { randomUUID } from 'node:crypto'
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+
7
+ function errorCode(err: unknown): string | undefined {
8
+ return (err as NodeJS.ErrnoException).code
9
+ }
10
+
11
+ /** Creates `file` only if nothing is there yet; returns `exists` when another create won the slug. */
12
+ export function createEntryFile(file: string, content: string): 'created' | 'exists' {
13
+ mkdirSync(dirname(file), { recursive: true })
14
+ try {
15
+ writeFileSync(file, content, { encoding: 'utf8', flag: 'wx' })
16
+ return 'created'
17
+ }
18
+ catch (err) {
19
+ if (errorCode(err) === 'EEXIST')
20
+ return 'exists'
21
+ throw err
22
+ }
23
+ }
24
+
25
+ /** Replaces `file` through a temp file in the same folder, so a crash never leaves a half-written entry. */
26
+ export function replaceEntryFile(file: string, content: string): void {
27
+ let target = file
28
+ try {
29
+ // A symlinked entry keeps its link: the rename lands on the real file.
30
+ target = realpathSync(file)
31
+ }
32
+ catch (err) {
33
+ if (errorCode(err) !== 'ENOENT')
34
+ throw err
35
+ }
36
+ mkdirSync(dirname(target), { recursive: true })
37
+ const tmp = join(dirname(target), `.${randomUUID()}.tmp`)
38
+ try {
39
+ writeFileSync(tmp, content, { encoding: 'utf8', flag: 'wx' })
40
+ try {
41
+ chmodSync(tmp, statSync(target).mode & 0o777)
42
+ }
43
+ catch (err) {
44
+ if (errorCode(err) !== 'ENOENT')
45
+ throw err
46
+ }
47
+ renameSync(tmp, target)
48
+ }
49
+ catch (err) {
50
+ rmSync(tmp, { force: true })
51
+ throw err
52
+ }
53
+ }
54
+
55
+ /** Reads the current source of an entry for in-place frontmatter edits; undefined when there is no file yet. */
56
+ export function readEntrySource(file: string): string | undefined {
57
+ return existsSync(file) ? readFileSync(file, 'utf8') : undefined
58
+ }
@@ -0,0 +1,235 @@
1
+ // Frontmatter YAML output: plain serialization, and in-place edits that keep comments and keys the form does not own.
2
+
3
+ const YAML_PLAIN_SAFE_RE = /^[a-zA-Z0-9][a-zA-Z0-9 _./@+-]*$/
4
+ const YAML_RESERVED_RE = /^(?:true|false|yes|no|on|off|null|~|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?|0x[0-9a-f]+|0o[0-7]+|\.inf|-\.inf|\.nan)$/i
5
+ const TOP_KEY_RE = /^("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|(?![-?:](?:[ \t]|$))(?:[^\s#&*!|>'"%@`[\]{},:]|:(?=\S))(?:[^\s:]|:(?=\S))*(?:[ \t]+(?!#)(?:[^\s:]|:(?=\S))+)*)[ \t]*:(?=\s|$)/
6
+ const FRONTMATTER_RE = /^---\n(?:([\s\S]*?)\n)?---[ \t]*(?:\n|$)/
7
+ const COMMENT_ONLY_LINE_RE = /^[ \t]*(?:#.*)?$/
8
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2}))?$/
9
+
10
+ function serializeYamlScalar(value: unknown): string {
11
+ if (value === null || value === undefined)
12
+ return 'null'
13
+ if (typeof value === 'boolean')
14
+ return value ? 'true' : 'false'
15
+ if (typeof value === 'number')
16
+ return Number.isFinite(value) ? String(value) : 'null'
17
+ if (value instanceof Date)
18
+ return JSON.stringify(value.toISOString())
19
+ const str = String(value)
20
+ if (str.length === 0)
21
+ return '""'
22
+ if (str.includes('\n') || str.includes('\r'))
23
+ return JSON.stringify(str)
24
+ if (str.trim() !== str || YAML_RESERVED_RE.test(str) || !YAML_PLAIN_SAFE_RE.test(str))
25
+ return JSON.stringify(str)
26
+ return str
27
+ }
28
+
29
+ function isRecord(value: unknown): value is Record<string, unknown> {
30
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
31
+ }
32
+
33
+ function serializeYamlObject(obj: Record<string, unknown>, indent: number): string[] {
34
+ const pad = ' '.repeat(indent)
35
+ const lines: string[] = []
36
+ for (const [key, value] of Object.entries(obj)) {
37
+ if (value === undefined)
38
+ continue
39
+ const yamlKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : JSON.stringify(key)
40
+ if (Array.isArray(value)) {
41
+ if (value.length === 0) {
42
+ lines.push(`${pad}${yamlKey}: []`)
43
+ }
44
+ else {
45
+ lines.push(`${pad}${yamlKey}:`)
46
+ lines.push(...serializeYamlArray(value, indent + 2))
47
+ }
48
+ }
49
+ else if (isRecord(value)) {
50
+ const inner = serializeYamlObject(value, indent + 2)
51
+ if (inner.length === 0) {
52
+ lines.push(`${pad}${yamlKey}: {}`)
53
+ }
54
+ else {
55
+ lines.push(`${pad}${yamlKey}:`)
56
+ lines.push(...inner)
57
+ }
58
+ }
59
+ else {
60
+ lines.push(`${pad}${yamlKey}: ${serializeYamlScalar(value)}`)
61
+ }
62
+ }
63
+ return lines
64
+ }
65
+
66
+ function serializeYamlArray(arr: readonly unknown[], indent: number): string[] {
67
+ const pad = ' '.repeat(indent)
68
+ const lines: string[] = []
69
+ for (const item of arr) {
70
+ if (isRecord(item)) {
71
+ const inner = serializeYamlObject(item, indent + 2)
72
+ if (inner.length === 0) {
73
+ lines.push(`${pad}- {}`)
74
+ }
75
+ else {
76
+ lines.push(`${pad}- ${inner[0]!.slice(indent + 2)}`)
77
+ for (let i = 1; i < inner.length; i++)
78
+ lines.push(inner[i]!)
79
+ }
80
+ }
81
+ else if (Array.isArray(item)) {
82
+ lines.push(`${pad}- ${JSON.stringify(item)}`)
83
+ }
84
+ else {
85
+ lines.push(`${pad}- ${serializeYamlScalar(item)}`)
86
+ }
87
+ }
88
+ return lines
89
+ }
90
+
91
+ /** Serializes a frontmatter object into clean YAML text. */
92
+ export function serializeFrontmatterYaml(data: Record<string, unknown>): string {
93
+ return serializeYamlObject(data, 0).join('\n')
94
+ }
95
+
96
+ interface Segment {
97
+ readonly key: string
98
+ readonly lead: string[]
99
+ readonly lines: string[]
100
+ }
101
+
102
+ function decodeKey(raw: string): string {
103
+ if (raw.startsWith('"')) {
104
+ try {
105
+ return JSON.parse(raw) as string
106
+ }
107
+ catch {
108
+ return raw
109
+ }
110
+ }
111
+ return raw.startsWith('\'') ? raw.slice(1, -1).replace(/''/g, '\'') : raw
112
+ }
113
+
114
+ // A top-level key owns the indented lines under it; comment and blank lines before the next key lead that key.
115
+ function splitSegments(lines: readonly string[]): { segments: Segment[], tail: string[] } {
116
+ const segments: Segment[] = []
117
+ let pending: string[] = []
118
+ for (const line of lines) {
119
+ const keyMatch = TOP_KEY_RE.exec(line)
120
+ const current = segments.at(-1)
121
+ if (keyMatch !== null) {
122
+ segments.push({ key: decodeKey(keyMatch[1]!), lead: pending, lines: [line] })
123
+ pending = []
124
+ }
125
+ else if (current === undefined || line.trim() === '' || line.startsWith('#')) {
126
+ pending.push(line)
127
+ }
128
+ else {
129
+ current.lines.push(...pending, line)
130
+ pending = []
131
+ }
132
+ }
133
+ return { segments, tail: pending }
134
+ }
135
+
136
+ function toIsoDate(value: unknown): string | undefined {
137
+ if (value instanceof Date)
138
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString()
139
+ if (typeof value === 'string' && ISO_DATE_RE.test(value)) {
140
+ const parsed = new Date(value)
141
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString()
142
+ }
143
+ return undefined
144
+ }
145
+
146
+ function sameValue(a: unknown, b: unknown): boolean {
147
+ if (a instanceof Date || b instanceof Date) {
148
+ const isoA = toIsoDate(a)
149
+ return isoA !== undefined && isoA === toIsoDate(b)
150
+ }
151
+ if (Array.isArray(a) || Array.isArray(b))
152
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => sameValue(v, b[i]))
153
+ if (isRecord(a) && isRecord(b)) {
154
+ const keys = Object.keys(a).filter(k => a[k] !== undefined)
155
+ return keys.length === Object.keys(b).filter(k => b[k] !== undefined).length
156
+ && keys.every(k => Object.hasOwn(b, k) && sameValue(a[k], b[k]))
157
+ }
158
+ return a === b
159
+ }
160
+
161
+ // Keeps a `# note` after a plain one-line scalar when its value changes.
162
+ function trailingComment(oldLines: readonly string[], value: unknown): string {
163
+ if (oldLines.length !== 1 || value === null || (typeof value === 'object' && !(value instanceof Date)))
164
+ return ''
165
+ const line = oldLines[0]!
166
+ const match = /\s+#.*$/.exec(line)
167
+ if (match === null || /["'[{]/.test(line.slice(line.indexOf(':') + 1, match.index)))
168
+ return ''
169
+ return match[0]
170
+ }
171
+
172
+ function rewriteSegment(segment: Segment, value: unknown): string[] {
173
+ const fresh = serializeYamlObject({ [segment.key]: value }, 0)
174
+ if (fresh.length === 1)
175
+ fresh[0] += trailingComment(segment.lines, value)
176
+ return [...segment.lead, ...fresh]
177
+ }
178
+
179
+ function readYamlBlock(source: string): string | undefined {
180
+ const match = FRONTMATTER_RE.exec(source.replace(/\r\n/g, '\n'))
181
+ return match === null ? undefined : (match[1] ?? '')
182
+ }
183
+
184
+ function parseYamlMapping(yaml: string): Record<string, unknown> | undefined {
185
+ if (yaml.trim() === '')
186
+ return {}
187
+ try {
188
+ const parsed: unknown = Bun.YAML.parse(yaml)
189
+ if (parsed === null || parsed === undefined)
190
+ return yaml.split('\n').every(line => COMMENT_ONLY_LINE_RE.test(line)) ? {} : undefined
191
+ return isRecord(parsed) ? parsed : undefined
192
+ }
193
+ catch {
194
+ return undefined
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Edits the frontmatter of `source` to hold `data`: untouched keys keep their lines and comments, changed keys keep their leading comments,
200
+ * keys outside `owned` are left alone, new keys are appended. Returns undefined when the source has no readable frontmatter.
201
+ */
202
+ export function mergeFrontmatterYaml(
203
+ source: string,
204
+ data: Record<string, unknown>,
205
+ owned: ReadonlySet<string> | undefined,
206
+ ): string | undefined {
207
+ const block = readYamlBlock(source)
208
+ const oldData = block === undefined ? undefined : parseYamlMapping(block)
209
+ if (block === undefined || oldData === undefined)
210
+ return undefined
211
+ const { segments, tail } = splitSegments(block.split('\n'))
212
+ const out: string[] = []
213
+ const seen = new Set<string>()
214
+ for (const segment of segments) {
215
+ seen.add(segment.key)
216
+ const value = Object.hasOwn(data, segment.key) ? data[segment.key] : undefined
217
+ if (owned !== undefined && !owned.has(segment.key))
218
+ out.push(...segment.lead, ...segment.lines)
219
+ else if (value === undefined)
220
+ continue
221
+ else if (sameValue(oldData[segment.key], value))
222
+ out.push(...segment.lead, ...segment.lines)
223
+ else
224
+ out.push(...rewriteSegment(segment, value))
225
+ }
226
+ if (segments.length === 0 && tail.some(line => line.trim() !== ''))
227
+ out.push(...tail)
228
+ for (const [key, value] of Object.entries(data)) {
229
+ if (!seen.has(key) && value !== undefined)
230
+ out.push(...serializeYamlObject({ [key]: value }, 0))
231
+ }
232
+ if (segments.length > 0)
233
+ out.push(...tail)
234
+ return out.join('\n').replace(/\n+$/, '')
235
+ }