@prunellejs/cms 0.0.0-stage → 0.7.2

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,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
+ }
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.