@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.
package/src/schema.ts ADDED
@@ -0,0 +1,487 @@
1
+ // JSON Schema extraction and field-model builder for @prunellejs/cms.
2
+ // Maps Standard Schema JSON Schema output into typed form fields and reports unsupported constructs in `prunelle check`.
3
+
4
+ import type { StandardSchemaV1 } from 'prunelle/server'
5
+
6
+ export type CmsFieldKind =
7
+ | 'text'
8
+ | 'textarea'
9
+ | 'date'
10
+ | 'datetime'
11
+ | 'email'
12
+ | 'url'
13
+ | 'number'
14
+ | 'integer'
15
+ | 'boolean'
16
+ | 'enum'
17
+ | 'tags'
18
+ | 'object'
19
+ | 'object-array'
20
+
21
+ export interface CmsField {
22
+ readonly key: string
23
+ readonly path: string
24
+ readonly label: string
25
+ readonly kind: CmsFieldKind
26
+ readonly required: boolean
27
+ readonly nullable: boolean
28
+ readonly description?: string | undefined
29
+ readonly defaultValue?: unknown
30
+ readonly min?: number | undefined
31
+ readonly max?: number | undefined
32
+ readonly step?: string | undefined
33
+ readonly minLength?: number | undefined
34
+ readonly maxLength?: number | undefined
35
+ readonly pattern?: string | undefined
36
+ readonly options?: readonly (string | number)[] | undefined
37
+ readonly enumType?: 'string' | 'number' | undefined
38
+ readonly fields?: readonly CmsField[] | undefined
39
+ }
40
+
41
+ export interface CmsSchemaIssue {
42
+ readonly path: string
43
+ readonly message: string
44
+ }
45
+
46
+ export interface ParsedCmsSchema {
47
+ readonly fields: readonly CmsField[]
48
+ readonly issues: readonly CmsSchemaIssue[]
49
+ }
50
+
51
+ interface JsonSchemaLike {
52
+ type?: string | readonly string[] | undefined
53
+ format?: string | undefined
54
+ title?: string | undefined
55
+ description?: string | undefined
56
+ default?: unknown
57
+ enum?: readonly unknown[] | undefined
58
+ const?: unknown
59
+ contentMediaType?: string | undefined
60
+ minimum?: number | undefined
61
+ maximum?: number | undefined
62
+ minLength?: number | undefined
63
+ maxLength?: number | undefined
64
+ pattern?: string | undefined
65
+ properties?: Record<string, unknown> | undefined
66
+ required?: readonly string[] | undefined
67
+ items?: unknown
68
+ anyOf?: readonly unknown[] | undefined
69
+ oneOf?: readonly unknown[] | undefined
70
+ allOf?: readonly unknown[] | undefined
71
+ $ref?: string | undefined
72
+ $defs?: Record<string, unknown> | undefined
73
+ definitions?: Record<string, unknown> | undefined
74
+ }
75
+
76
+ interface SchemaCandidate {
77
+ '~standard'?: {
78
+ jsonSchema?: {
79
+ input?: (opts: { target: string }) => unknown
80
+ } | undefined
81
+ } | undefined
82
+ toJSONSchema?: (() => unknown) | undefined
83
+ jsonSchema?: unknown
84
+ }
85
+
86
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
87
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
88
+ }
89
+
90
+ /** Extracts a raw JSON Schema object from a Standard Schema, returning `undefined` when unavailable. */
91
+ export function extractJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
92
+ const candidate = schema as unknown as SchemaCandidate
93
+ const stdInput = candidate['~standard']?.jsonSchema?.input
94
+ if (typeof stdInput === 'function') {
95
+ for (const target of ['draft-2020-12', 'draft-07']) {
96
+ let result: unknown
97
+ try {
98
+ result = stdInput({ target })
99
+ }
100
+ catch (err) {
101
+ result = err instanceof Error ? undefined : undefined
102
+ }
103
+ if (isPlainRecord(result))
104
+ return result
105
+ }
106
+ }
107
+
108
+ if (typeof candidate.toJSONSchema === 'function') {
109
+ let result: unknown
110
+ try {
111
+ result = candidate.toJSONSchema()
112
+ }
113
+ catch (err) {
114
+ result = err instanceof Error ? undefined : undefined
115
+ }
116
+ if (isPlainRecord(result))
117
+ return result
118
+ }
119
+
120
+ if (isPlainRecord(candidate.jsonSchema))
121
+ return candidate.jsonSchema
122
+
123
+ return undefined
124
+ }
125
+
126
+ /** Formats a property key into a readable label (e.g. `publishedAt` -> `Published At`, `seo_title` -> `Seo Title`). */
127
+ export function humanizeKey(key: string): string {
128
+ const spaced = key
129
+ .replace(/[_-]+/g, ' ')
130
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
131
+ .trim()
132
+ if (spaced.length === 0)
133
+ return key
134
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
135
+ }
136
+
137
+ function isNullSchema(node: unknown): boolean {
138
+ return isPlainRecord(node) && (node.type === 'null' || node.const === null)
139
+ }
140
+
141
+ function resolveRef(ref: string, root: JsonSchemaLike): JsonSchemaLike | undefined {
142
+ if (!ref.startsWith('#/'))
143
+ return undefined
144
+ const parts = ref.slice(2).split('/')
145
+ let cur: unknown = root
146
+ for (const part of parts) {
147
+ if (!isPlainRecord(cur))
148
+ return undefined
149
+ cur = cur[part.replace(/~1/g, '/').replace(/~0/g, '~')]
150
+ }
151
+ return isPlainRecord(cur) ? (cur as JsonSchemaLike) : undefined
152
+ }
153
+
154
+ interface UnwrapResult {
155
+ schema?: JsonSchemaLike | undefined
156
+ nullable: boolean
157
+ error?: string | undefined
158
+ }
159
+
160
+ function unwrapSchema(raw: unknown, root: JsonSchemaLike, seenRefs: Set<string>): UnwrapResult {
161
+ if (!isPlainRecord(raw))
162
+ return { nullable: false, error: 'schema definition is not an object' }
163
+
164
+ let node = raw as JsonSchemaLike
165
+ let nullable = false
166
+
167
+ if (typeof node.$ref === 'string') {
168
+ if (seenRefs.has(node.$ref))
169
+ return { nullable: false, error: `recursive $ref "${node.$ref}" is not supported` }
170
+ const resolved = resolveRef(node.$ref, root)
171
+ if (resolved === undefined)
172
+ return { nullable: false, error: `unresolvable $ref "${node.$ref}"` }
173
+ const nextRefs = new Set(seenRefs)
174
+ nextRefs.add(node.$ref)
175
+ const inner = unwrapSchema(resolved, root, nextRefs)
176
+ if (inner.error !== undefined || inner.schema === undefined)
177
+ return inner
178
+ node = {
179
+ ...inner.schema,
180
+ ...(node.title !== undefined ? { title: node.title } : {}),
181
+ ...(node.description !== undefined ? { description: node.description } : {}),
182
+ ...(node.default !== undefined ? { default: node.default } : {}),
183
+ }
184
+ nullable = nullable || inner.nullable
185
+ }
186
+
187
+ const union = node.anyOf ?? node.oneOf
188
+ if (Array.isArray(union)) {
189
+ const keyword = node.anyOf !== undefined ? 'anyOf' : 'oneOf'
190
+ const nonNull = union.filter(branch => !isNullSchema(branch))
191
+ if (nonNull.length < union.length)
192
+ nullable = true
193
+ if (nonNull.length !== 1)
194
+ return { nullable, error: `unsupported ${keyword} union with ${nonNull.length} non-null branches` }
195
+ const inner = unwrapSchema(nonNull[0], root, seenRefs)
196
+ if (inner.error !== undefined || inner.schema === undefined)
197
+ return inner
198
+ node = {
199
+ ...inner.schema,
200
+ ...(node.title !== undefined ? { title: node.title } : {}),
201
+ ...(node.description !== undefined ? { description: node.description } : {}),
202
+ ...(node.default !== undefined ? { default: node.default } : {}),
203
+ }
204
+ nullable = nullable || inner.nullable
205
+ }
206
+
207
+ if (Array.isArray(node.allOf)) {
208
+ if (node.allOf.length !== 1)
209
+ return { nullable, error: `unsupported allOf intersection with ${node.allOf.length} branches` }
210
+ const inner = unwrapSchema(node.allOf[0], root, seenRefs)
211
+ if (inner.error !== undefined || inner.schema === undefined)
212
+ return inner
213
+ node = { ...inner.schema, ...(node.title !== undefined ? { title: node.title } : {}), ...(node.description !== undefined ? { description: node.description } : {}) }
214
+ nullable = nullable || inner.nullable
215
+ }
216
+
217
+ if (Array.isArray(node.type)) {
218
+ const nonNull = node.type.filter(t => t !== 'null')
219
+ if (nonNull.length < node.type.length)
220
+ nullable = true
221
+ if (nonNull.length !== 1)
222
+ return { nullable, error: `unsupported multi-type union [${node.type.join(', ')}]` }
223
+ node = { ...node, type: nonNull[0] }
224
+ }
225
+
226
+ return { schema: node, nullable }
227
+ }
228
+
229
+ function resolveStringKind(node: JsonSchemaLike): CmsFieldKind {
230
+ if (node.contentMediaType === 'text/markdown')
231
+ return 'textarea'
232
+ if (node.format === 'date')
233
+ return 'date'
234
+ if (node.format === 'date-time')
235
+ return 'datetime'
236
+ if (node.format === 'email')
237
+ return 'email'
238
+ if (node.format === 'uri' || node.format === 'url')
239
+ return 'url'
240
+ return 'text'
241
+ }
242
+
243
+ function buildEnumField(
244
+ key: string,
245
+ path: string,
246
+ node: JsonSchemaLike,
247
+ required: boolean,
248
+ nullable: boolean,
249
+ issues: CmsSchemaIssue[],
250
+ ): CmsField | undefined {
251
+ const rawValues = node.enum ?? (node.const !== undefined ? [node.const] : [])
252
+ const nonNull = rawValues.filter(v => v !== null)
253
+ const isNullable = nullable || nonNull.length < rawValues.length
254
+ if (nonNull.length === 0) {
255
+ issues.push({ path, message: 'enum has no selectable values' })
256
+ return undefined
257
+ }
258
+ const allStrings = nonNull.every(v => typeof v === 'string')
259
+ const allNumbers = nonNull.every(v => typeof v === 'number' && Number.isFinite(v))
260
+ if (!allStrings && !allNumbers) {
261
+ issues.push({ path, message: 'enum must contain only strings or only finite numbers' })
262
+ return undefined
263
+ }
264
+ return {
265
+ key,
266
+ path,
267
+ label: typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key),
268
+ kind: 'enum',
269
+ required,
270
+ nullable: isNullable,
271
+ description: typeof node.description === 'string' ? node.description : undefined,
272
+ defaultValue: node.default,
273
+ options: nonNull as (string | number)[],
274
+ enumType: allNumbers ? 'number' : 'string',
275
+ }
276
+ }
277
+
278
+ function buildArrayField(
279
+ key: string,
280
+ path: string,
281
+ node: JsonSchemaLike,
282
+ required: boolean,
283
+ nullable: boolean,
284
+ root: JsonSchemaLike,
285
+ seenRefs: Set<string>,
286
+ issues: CmsSchemaIssue[],
287
+ depth: number,
288
+ ): CmsField | undefined {
289
+ if (node.items === undefined || Array.isArray(node.items)) {
290
+ issues.push({ path, message: 'array field must declare a single `items` schema (tuples are unsupported)' })
291
+ return undefined
292
+ }
293
+ const itemUnwrap = unwrapSchema(node.items, root, seenRefs)
294
+ if (itemUnwrap.error !== undefined || itemUnwrap.schema === undefined) {
295
+ issues.push({ path, message: `array item schema is unsupported (${itemUnwrap.error ?? 'unknown'})` })
296
+ return undefined
297
+ }
298
+ const item = itemUnwrap.schema
299
+ const label = typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key)
300
+ const description = typeof node.description === 'string' ? node.description : undefined
301
+
302
+ if (item.type === 'string' || (Array.isArray(item.enum) && item.enum.every(v => typeof v === 'string'))) {
303
+ return {
304
+ key,
305
+ path,
306
+ label,
307
+ kind: 'tags',
308
+ required,
309
+ nullable,
310
+ description,
311
+ defaultValue: node.default,
312
+ }
313
+ }
314
+
315
+ if (item.type === 'object' && isPlainRecord(item.properties)) {
316
+ if (depth > 0) {
317
+ issues.push({ path, message: 'nested arrays of objects are not supported' })
318
+ return undefined
319
+ }
320
+ const childFields = parseObjectProperties(item, `${path}[]`, root, seenRefs, issues, depth + 1)
321
+ return {
322
+ key,
323
+ path,
324
+ label,
325
+ kind: 'object-array',
326
+ required,
327
+ nullable,
328
+ description,
329
+ defaultValue: node.default,
330
+ fields: childFields,
331
+ }
332
+ }
333
+
334
+ const itemDesc = typeof item.type === 'string' ? `array of ${item.type}` : 'array of unsupported items'
335
+ issues.push({ path, message: `${itemDesc} is not supported (only string[] and object[] with properties are supported)` })
336
+ return undefined
337
+ }
338
+
339
+ function buildField(
340
+ key: string,
341
+ path: string,
342
+ rawProp: unknown,
343
+ required: boolean,
344
+ root: JsonSchemaLike,
345
+ seenRefs: Set<string>,
346
+ issues: CmsSchemaIssue[],
347
+ depth: number,
348
+ ): CmsField | undefined {
349
+ const unwrapped = unwrapSchema(rawProp, root, seenRefs)
350
+ if (unwrapped.error !== undefined || unwrapped.schema === undefined) {
351
+ issues.push({ path, message: unwrapped.error ?? 'unsupported schema construct' })
352
+ return undefined
353
+ }
354
+ const node = unwrapped.schema
355
+ const { nullable } = unwrapped
356
+ const label = typeof node.title === 'string' && node.title.length > 0 ? node.title : humanizeKey(key)
357
+ const description = typeof node.description === 'string' ? node.description : undefined
358
+
359
+ if (Array.isArray(node.enum) || node.const !== undefined)
360
+ return buildEnumField(key, path, node, required, nullable, issues)
361
+
362
+ if (node.type === 'string') {
363
+ return {
364
+ key,
365
+ path,
366
+ label,
367
+ kind: resolveStringKind(node),
368
+ required,
369
+ nullable,
370
+ description,
371
+ defaultValue: node.default,
372
+ minLength: typeof node.minLength === 'number' ? node.minLength : undefined,
373
+ maxLength: typeof node.maxLength === 'number' ? node.maxLength : undefined,
374
+ pattern: typeof node.pattern === 'string' ? node.pattern : undefined,
375
+ }
376
+ }
377
+
378
+ if (node.type === 'boolean') {
379
+ return {
380
+ key,
381
+ path,
382
+ label,
383
+ kind: 'boolean',
384
+ required,
385
+ nullable,
386
+ description,
387
+ defaultValue: node.default,
388
+ }
389
+ }
390
+
391
+ if (node.type === 'number' || node.type === 'integer') {
392
+ return {
393
+ key,
394
+ path,
395
+ label,
396
+ kind: node.type,
397
+ required,
398
+ nullable,
399
+ description,
400
+ defaultValue: node.default,
401
+ min: typeof node.minimum === 'number' ? node.minimum : undefined,
402
+ max: typeof node.maximum === 'number' ? node.maximum : undefined,
403
+ step: node.type === 'integer' ? '1' : 'any',
404
+ }
405
+ }
406
+
407
+ if (node.type === 'array')
408
+ return buildArrayField(key, path, node, required, nullable, root, seenRefs, issues, depth)
409
+
410
+ if (node.type === 'object' || isPlainRecord(node.properties)) {
411
+ if (!isPlainRecord(node.properties)) {
412
+ issues.push({ path, message: 'object field must declare explicit `properties`' })
413
+ return undefined
414
+ }
415
+ const childFields = parseObjectProperties(node, path, root, seenRefs, issues, depth)
416
+ return {
417
+ key,
418
+ path,
419
+ label,
420
+ kind: 'object',
421
+ required,
422
+ nullable,
423
+ description,
424
+ defaultValue: node.default,
425
+ fields: childFields,
426
+ }
427
+ }
428
+
429
+ issues.push({ path, message: `unsupported or untyped field schema (type: ${String(node.type ?? 'none')})` })
430
+ return undefined
431
+ }
432
+
433
+ function parseObjectProperties(
434
+ node: JsonSchemaLike,
435
+ prefix: string,
436
+ root: JsonSchemaLike,
437
+ seenRefs: Set<string>,
438
+ issues: CmsSchemaIssue[],
439
+ depth: number,
440
+ ): CmsField[] {
441
+ const props = isPlainRecord(node.properties) ? node.properties : {}
442
+ const requiredSet = new Set(Array.isArray(node.required) ? node.required.filter((r): r is string => typeof r === 'string') : [])
443
+ const fields: CmsField[] = []
444
+ for (const [key, rawProp] of Object.entries(props)) {
445
+ const fieldPath = prefix === '' ? key : `${prefix}.${key}`
446
+ const field = buildField(key, fieldPath, rawProp, requiredSet.has(key), root, seenRefs, issues, depth)
447
+ if (field !== undefined)
448
+ fields.push(field)
449
+ }
450
+ return fields
451
+ }
452
+
453
+ /** Parses a root JSON Schema object into CMS fields and collects any unsupported construct issues. */
454
+ export function parseJsonSchemaFields(rawSchema: Record<string, unknown>): ParsedCmsSchema {
455
+ const issues: CmsSchemaIssue[] = []
456
+ const root = rawSchema as JsonSchemaLike
457
+ const unwrapped = unwrapSchema(root, root, new Set())
458
+ if (unwrapped.error !== undefined || unwrapped.schema === undefined) {
459
+ issues.push({ path: '$', message: unwrapped.error ?? 'root schema is invalid' })
460
+ return { fields: [], issues }
461
+ }
462
+ const node = unwrapped.schema
463
+ if (node.type !== undefined && node.type !== 'object') {
464
+ issues.push({ path: '$', message: `root frontmatter schema must be an object (got "${String(node.type)}")` })
465
+ return { fields: [], issues }
466
+ }
467
+ if (!isPlainRecord(node.properties)) {
468
+ issues.push({ path: '$', message: 'root frontmatter schema must declare `properties`' })
469
+ return { fields: [], issues }
470
+ }
471
+ const fields = parseObjectProperties(node, '', root, new Set(), issues, 0)
472
+ return { fields, issues }
473
+ }
474
+
475
+ /** Validates a collection's Standard Schema for CMS compatibility, returning human-readable errors naming collection & field. */
476
+ export function checkCollectionSchema(collectionName: string, schema: StandardSchemaV1): string[] {
477
+ const jsonSchema = extractJsonSchema(schema)
478
+ if (jsonSchema === undefined) {
479
+ return [
480
+ `prunelle check (@prunellejs/cms): collection "${collectionName}" schema does not expose JSON Schema output (~standard.jsonSchema, toJSONSchema(), or jsonSchema). Use a Standard JSON Schema validator (Zod 4, Valibot, ArkType) or attach a jsonSchema object.`,
481
+ ]
482
+ }
483
+ const { issues } = parseJsonSchemaFields(jsonSchema)
484
+ return issues.map(issue =>
485
+ `prunelle check (@prunellejs/cms): collection "${collectionName}" field "${issue.path}" is not supported by the CMS: ${issue.message}.`,
486
+ )
487
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,108 @@
1
+ // Shared helpers for @prunellejs/cms HTTP routes (full-page CMS and dev in-page editing API).
2
+
3
+ import type { ContentCollectionDescriptor, ContentCollectionsService } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { CmsGuard } from './guard'
6
+ import { runGuard } from './guard'
7
+ import type { CmsField } from './schema'
8
+ import { formatIssuePath } from 'prunelle/server'
9
+ import { normalizeFieldErrorPath } from './form-data'
10
+ import { extractJsonSchema, parseJsonSchemaFields } from './schema'
11
+
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'
16
+
17
+ export interface CmsHandlerConfig {
18
+ readonly basePath: string
19
+ readonly guard?: CmsGuard | undefined
20
+ }
21
+
22
+ export function htmlResponse(html: string, status = 200): Response {
23
+ return new Response(html, {
24
+ status,
25
+ headers: { 'content-type': 'text/html; charset=utf-8' },
26
+ })
27
+ }
28
+
29
+
30
+
31
+ export function wrapGuarded(
32
+ guard: CmsGuard | undefined,
33
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
34
+ ): (ctx: RequestContext) => Promise<Response> {
35
+ return async (ctx) => {
36
+ const blocked = await runGuard(guard, ctx)
37
+ if (blocked !== undefined)
38
+ return blocked
39
+ return await handler(ctx)
40
+ }
41
+ }
42
+
43
+ export async function loadCollections(
44
+ service: ContentCollectionsService | undefined,
45
+ root: string,
46
+ ): Promise<readonly ContentCollectionDescriptor[]> {
47
+ if (service === undefined)
48
+ return []
49
+ return service.discover !== undefined
50
+ ? await service.discover(root)
51
+ : await service.list(root)
52
+ }
53
+
54
+ export function resolveSchemaFields(col: ContentCollectionDescriptor): {
55
+ fields?: readonly CmsField[] | undefined
56
+ warning?: string | undefined
57
+ } {
58
+ if (col.schema === undefined)
59
+ return {}
60
+ const jsonSchema = extractJsonSchema(col.schema)
61
+ if (jsonSchema === undefined) {
62
+ return {
63
+ warning: `Collection "${col.name}" schema does not expose JSON Schema output; editing raw YAML frontmatter (schema validation still runs on save).`,
64
+ }
65
+ }
66
+ const parsed = parseJsonSchemaFields(jsonSchema)
67
+ if (parsed.issues.length > 0) {
68
+ const details = parsed.issues.map(i => `${i.path}: ${i.message}`).join('; ')
69
+ return {
70
+ fields: parsed.fields,
71
+ warning: `Some schema fields are unsupported by the CMS: ${details}`,
72
+ }
73
+ }
74
+ return { fields: parsed.fields }
75
+ }
76
+
77
+ export function parseRawFrontmatterYaml(
78
+ rawYaml: string,
79
+ ): { ok: true, data: Record<string, unknown> } | { ok: false, message: string } {
80
+ if (rawYaml.trim().length === 0)
81
+ return { ok: true, data: {} }
82
+ let parsed: unknown
83
+ try {
84
+ parsed = Bun.YAML.parse(rawYaml)
85
+ }
86
+ catch (err) {
87
+ return { ok: false, message: err instanceof Error ? err.message : 'Invalid YAML frontmatter.' }
88
+ }
89
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
90
+ return { ok: false, message: 'Frontmatter YAML must be a mapping (key: value object).' }
91
+ return { ok: true, data: parsed as Record<string, unknown> }
92
+ }
93
+
94
+ export function collectValidationErrors(
95
+ issues: ReadonlyArray<{
96
+ readonly message: string
97
+ readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
98
+ }>,
99
+ ): Record<string, string> {
100
+ const errors: Record<string, string> = {}
101
+ for (const issue of issues) {
102
+ const rawPath = formatIssuePath(issue)
103
+ const key = normalizeFieldErrorPath(rawPath)
104
+ if (!Object.hasOwn(errors, key))
105
+ errors[key] = issue.message
106
+ }
107
+ return errors
108
+ }
@@ -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
+ }