@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,214 @@
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 = /^("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.$@-]+)[ \t]*:(?=\s|$)/
6
+ const FRONTMATTER_RE = /^---\n(?:([\s\S]*?)\n)?---[ \t]*(?:\n|$)/
7
+
8
+ function serializeYamlScalar(value: unknown): string {
9
+ if (value === null || value === undefined)
10
+ return 'null'
11
+ if (typeof value === 'boolean')
12
+ return value ? 'true' : 'false'
13
+ if (typeof value === 'number')
14
+ return Number.isFinite(value) ? String(value) : 'null'
15
+ if (value instanceof Date)
16
+ return JSON.stringify(value.toISOString())
17
+ const str = String(value)
18
+ if (str.length === 0)
19
+ return '""'
20
+ if (str.includes('\n') || str.includes('\r'))
21
+ return JSON.stringify(str)
22
+ if (str.trim() !== str || YAML_RESERVED_RE.test(str) || !YAML_PLAIN_SAFE_RE.test(str))
23
+ return JSON.stringify(str)
24
+ return str
25
+ }
26
+
27
+ function isRecord(value: unknown): value is Record<string, unknown> {
28
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
29
+ }
30
+
31
+ function serializeYamlObject(obj: Record<string, unknown>, indent: number): string[] {
32
+ const pad = ' '.repeat(indent)
33
+ const lines: string[] = []
34
+ for (const [key, value] of Object.entries(obj)) {
35
+ if (value === undefined)
36
+ continue
37
+ const yamlKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : JSON.stringify(key)
38
+ if (Array.isArray(value)) {
39
+ if (value.length === 0) {
40
+ lines.push(`${pad}${yamlKey}: []`)
41
+ }
42
+ else {
43
+ lines.push(`${pad}${yamlKey}:`)
44
+ lines.push(...serializeYamlArray(value, indent + 2))
45
+ }
46
+ }
47
+ else if (isRecord(value)) {
48
+ const inner = serializeYamlObject(value, indent + 2)
49
+ if (inner.length === 0) {
50
+ lines.push(`${pad}${yamlKey}: {}`)
51
+ }
52
+ else {
53
+ lines.push(`${pad}${yamlKey}:`)
54
+ lines.push(...inner)
55
+ }
56
+ }
57
+ else {
58
+ lines.push(`${pad}${yamlKey}: ${serializeYamlScalar(value)}`)
59
+ }
60
+ }
61
+ return lines
62
+ }
63
+
64
+ function serializeYamlArray(arr: readonly unknown[], indent: number): string[] {
65
+ const pad = ' '.repeat(indent)
66
+ const lines: string[] = []
67
+ for (const item of arr) {
68
+ if (isRecord(item)) {
69
+ const inner = serializeYamlObject(item, indent + 2)
70
+ if (inner.length === 0) {
71
+ lines.push(`${pad}- {}`)
72
+ }
73
+ else {
74
+ lines.push(`${pad}- ${inner[0]!.slice(indent + 2)}`)
75
+ for (let i = 1; i < inner.length; i++)
76
+ lines.push(inner[i]!)
77
+ }
78
+ }
79
+ else if (Array.isArray(item)) {
80
+ lines.push(`${pad}- ${JSON.stringify(item)}`)
81
+ }
82
+ else {
83
+ lines.push(`${pad}- ${serializeYamlScalar(item)}`)
84
+ }
85
+ }
86
+ return lines
87
+ }
88
+
89
+ /** Serializes a frontmatter object into clean YAML text. */
90
+ export function serializeFrontmatterYaml(data: Record<string, unknown>): string {
91
+ return serializeYamlObject(data, 0).join('\n')
92
+ }
93
+
94
+ interface Segment {
95
+ readonly key: string
96
+ readonly lead: string[]
97
+ readonly lines: string[]
98
+ }
99
+
100
+ function decodeKey(raw: string): string {
101
+ if (raw.startsWith('"')) {
102
+ try {
103
+ return JSON.parse(raw) as string
104
+ }
105
+ catch {
106
+ return raw
107
+ }
108
+ }
109
+ return raw.startsWith('\'') ? raw.slice(1, -1) : raw
110
+ }
111
+
112
+ // A top-level key owns the indented lines under it; comment and blank lines before the next key lead that key.
113
+ function splitSegments(lines: readonly string[]): { segments: Segment[], tail: string[] } {
114
+ const segments: Segment[] = []
115
+ let pending: string[] = []
116
+ for (const line of lines) {
117
+ const keyMatch = TOP_KEY_RE.exec(line)
118
+ const current = segments.at(-1)
119
+ if (keyMatch !== null) {
120
+ segments.push({ key: decodeKey(keyMatch[1]!), lead: pending, lines: [line] })
121
+ pending = []
122
+ }
123
+ else if (current === undefined || line.trim() === '' || line.startsWith('#')) {
124
+ pending.push(line)
125
+ }
126
+ else {
127
+ current.lines.push(...pending, line)
128
+ pending = []
129
+ }
130
+ }
131
+ return { segments, tail: pending }
132
+ }
133
+
134
+ function sameValue(a: unknown, b: unknown): boolean {
135
+ if (Array.isArray(a) || Array.isArray(b))
136
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => sameValue(v, b[i]))
137
+ if (isRecord(a) && isRecord(b)) {
138
+ const keys = Object.keys(a).filter(k => a[k] !== undefined)
139
+ return keys.length === Object.keys(b).filter(k => b[k] !== undefined).length
140
+ && keys.every(k => Object.hasOwn(b, k) && sameValue(a[k], b[k]))
141
+ }
142
+ return a === b
143
+ }
144
+
145
+ // Keeps a `# note` after a plain one-line scalar when its value changes.
146
+ function trailingComment(oldLines: readonly string[], value: unknown): string {
147
+ if (oldLines.length !== 1 || value === null || typeof value === 'object')
148
+ return ''
149
+ const line = oldLines[0]!
150
+ const match = /\s+#.*$/.exec(line)
151
+ if (match === null || /["'[{]/.test(line.slice(line.indexOf(':') + 1, match.index)))
152
+ return ''
153
+ return match[0]
154
+ }
155
+
156
+ function rewriteSegment(segment: Segment, value: unknown): string[] {
157
+ const fresh = serializeYamlObject({ [segment.key]: value }, 0)
158
+ if (fresh.length === 1)
159
+ fresh[0] += trailingComment(segment.lines, value)
160
+ return [...segment.lead, ...fresh]
161
+ }
162
+
163
+ function readYamlBlock(source: string): string | undefined {
164
+ const match = FRONTMATTER_RE.exec(source.replace(/\r\n/g, '\n'))
165
+ return match === null ? undefined : (match[1] ?? '')
166
+ }
167
+
168
+ function parseYamlMapping(yaml: string): Record<string, unknown> | undefined {
169
+ if (yaml.trim() === '')
170
+ return {}
171
+ try {
172
+ const parsed: unknown = Bun.YAML.parse(yaml)
173
+ return isRecord(parsed) ? parsed : undefined
174
+ }
175
+ catch {
176
+ return undefined
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Edits the frontmatter of `source` to hold `data`: untouched keys keep their lines and comments, changed keys keep their leading comments,
182
+ * keys outside `owned` are left alone, new keys are appended. Returns undefined when the source has no readable frontmatter.
183
+ */
184
+ export function mergeFrontmatterYaml(
185
+ source: string,
186
+ data: Record<string, unknown>,
187
+ owned: ReadonlySet<string> | undefined,
188
+ ): string | undefined {
189
+ const block = readYamlBlock(source)
190
+ const oldData = block === undefined ? undefined : parseYamlMapping(block)
191
+ if (block === undefined || oldData === undefined)
192
+ return undefined
193
+ const { segments, tail } = splitSegments(block.split('\n'))
194
+ const out: string[] = []
195
+ const seen = new Set<string>()
196
+ for (const segment of segments) {
197
+ seen.add(segment.key)
198
+ const value = Object.hasOwn(data, segment.key) ? data[segment.key] : undefined
199
+ if (owned !== undefined && !owned.has(segment.key))
200
+ out.push(...segment.lead, ...segment.lines)
201
+ else if (value === undefined)
202
+ continue
203
+ else if (sameValue(oldData[segment.key], value))
204
+ out.push(...segment.lead, ...segment.lines)
205
+ else
206
+ out.push(...rewriteSegment(segment, value))
207
+ }
208
+ for (const [key, value] of Object.entries(data)) {
209
+ if (!seen.has(key) && value !== undefined)
210
+ out.push(...serializeYamlObject({ [key]: value }, 0))
211
+ }
212
+ out.push(...tail)
213
+ return out.join('\n').replace(/\n+$/, '')
214
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.