@crombolo/server 0.27.0 → 0.28.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.27.0",
34
- "@crombolo/api-management": "0.27.0",
35
- "@crombolo/auth": "0.27.0",
36
- "@crombolo/backoffice-host": "0.27.0",
37
- "@crombolo/content": "0.27.0",
38
- "@crombolo/contracts": "0.27.0",
39
- "@crombolo/core": "0.27.0",
40
- "@crombolo/data": "0.27.0",
41
- "@crombolo/render": "0.27.0",
42
- "@crombolo/schema": "0.27.0",
43
- "@crombolo/transfer": "0.27.0",
33
+ "@crombolo/api-delivery": "0.28.0",
34
+ "@crombolo/api-management": "0.28.0",
35
+ "@crombolo/auth": "0.28.0",
36
+ "@crombolo/backoffice-host": "0.28.0",
37
+ "@crombolo/content": "0.28.0",
38
+ "@crombolo/contracts": "0.28.0",
39
+ "@crombolo/core": "0.28.0",
40
+ "@crombolo/data": "0.28.0",
41
+ "@crombolo/render": "0.28.0",
42
+ "@crombolo/schema": "0.28.0",
43
+ "@crombolo/transfer": "0.28.0",
44
44
  "@logtape/logtape": "^2.3.8",
45
45
  "jose": "^6.2.12"
46
46
  }
package/src/config.ts CHANGED
@@ -813,7 +813,7 @@ export function describeDatabase(
813
813
  }
814
814
  }
815
815
 
816
- export const VERSION = '0.27.0'
816
+ export const VERSION = '0.28.0'
817
817
 
818
818
  /** A whole number of seconds from the environment; undefined when unset or not one. */
819
819
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
package/src/index.ts CHANGED
@@ -79,6 +79,7 @@ export * from './remote-media.ts'
79
79
  export * from './schema.ts'
80
80
  export * from './schema-store.ts'
81
81
  export * from './secrets.ts'
82
+ export * from './seed/index.ts'
82
83
  export * from './seo.ts'
83
84
  export * from './server.ts'
84
85
  export * from './server-events.ts'
@@ -0,0 +1,732 @@
1
+ /**
2
+ * Seed files to a bundle (story 163). The items `readSeed` found are checked
3
+ * against the site's own schema, their values written in each property
4
+ * editor's stored shape from the shorthand a person writes, and the result is
5
+ * the bundle format every import already reads. Applying it is `content
6
+ * import`'s job, with its findings, its one transaction and its revert.
7
+ */
8
+ import { createHash } from 'node:crypto'
9
+ import { extname } from 'node:path'
10
+ import {
11
+ type ContentTypeAggregate,
12
+ IMAGE_CROPPER_EDITOR_ALIAS,
13
+ normaliseUuid,
14
+ ObjectTypes,
15
+ SystemNodes,
16
+ } from '@crombolo/core'
17
+ import {
18
+ ComponentRepository,
19
+ ContentTypeRepository,
20
+ currentSchemaState,
21
+ DataTypeRepository,
22
+ type Db,
23
+ LanguageRepository,
24
+ looksLikeKey,
25
+ NodeRepository,
26
+ resolveNodeRef,
27
+ } from '@crombolo/data'
28
+ import {
29
+ type BundleBlob,
30
+ type BundleFile,
31
+ type BundleKind,
32
+ type BundleNode,
33
+ type BundleValue,
34
+ type ContentSet,
35
+ writeBundle,
36
+ writeBundlePackage,
37
+ } from '@crombolo/transfer'
38
+ import { createMediaPort } from '../adapters/media.ts'
39
+ import { type CromboloConfig, VERSION } from '../config.ts'
40
+ import { blockKey, seedKey, uuidV5 } from './keys.ts'
41
+ import { lineOf } from './lines.ts'
42
+ import { readSeed, type SeedFinding, type SeedItem } from './read.ts'
43
+
44
+ export interface SeedBuild {
45
+ findings: SeedFinding[]
46
+ /** The bundle, when nothing found stops it being built. */
47
+ set?: ContentSet
48
+ blobs: Map<string, Uint8Array>
49
+ /** The bundle as the npm package `content import` reads. */
50
+ files?: BundleFile[]
51
+ /** How many items of each kind it holds. */
52
+ counts: Record<'content' | 'library' | 'media', number>
53
+ }
54
+
55
+ /** A word for a file name: `about-us` → `About us`. */
56
+ const nameFromSegment = (segment: string) => {
57
+ const words = segment.replace(/[-_]+/g, ' ').trim()
58
+ return words.charAt(0).toUpperCase() + words.slice(1)
59
+ }
60
+
61
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
62
+ typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
63
+
64
+ const BLOCK_LAYOUT = {
65
+ 'Umbraco.BlockList': 'Umbraco.BlockList',
66
+ 'Umbraco.BlockGrid': 'Umbraco.BlockGrid',
67
+ } as const
68
+
69
+ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedBuild> {
70
+ const tree = readSeed(config.siteDir)
71
+ const findings: SeedFinding[] = [...tree.findings]
72
+ const counts = { content: 0, library: 0, media: 0 }
73
+ for (const item of tree.items) counts[item.kind] += 1
74
+
75
+ const state = await currentSchemaState(db)
76
+ const documentTypes = new ContentTypeRepository(db)
77
+ const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
78
+ const dataTypes = new DataTypeRepository(db)
79
+ const components = new ComponentRepository(db)
80
+ const nodes = new NodeRepository(db)
81
+ const port = createMediaPort(db, {
82
+ nodeState: { version: state.version, revision: state.revision },
83
+ })
84
+ const languages = new Map(
85
+ (await new LanguageRepository(db).all()).map((l) => [l.isoCode.toLowerCase(), l.isoCode]),
86
+ )
87
+
88
+ const find = (item: SeedItem, path: readonly string[], code: string, message: string) =>
89
+ findings.push({
90
+ file: item.file ?? `seed/${item.kind}/${item.path}`,
91
+ line: item.text ? lineOf(item.text, path) : 1,
92
+ code,
93
+ message,
94
+ })
95
+
96
+ // ---------------------------------------------------------------- keys
97
+ const keyOf = new Map<SeedItem, string>()
98
+ const byKey = new Map<string, SeedItem>()
99
+ for (const item of tree.items) {
100
+ const given = item.data.key
101
+ let key = seedKey(`${item.kind}/${item.path}`)
102
+ if (given !== undefined) {
103
+ if (typeof given === 'string' && looksLikeKey(given)) key = normaliseUuid(given)
104
+ else find(item, ['key'], 'bad-key', `key "${String(given)}" is not a uuid`)
105
+ }
106
+ const clash = byKey.get(key)
107
+ if (clash)
108
+ find(item, ['key'], 'duplicate-key', `the key ${key} is also ${clash.file ?? clash.path}'s`)
109
+ byKey.set(key, item)
110
+ keyOf.set(item, key)
111
+ }
112
+ const byPath = (kind: SeedItem['kind']) =>
113
+ new Map(tree.items.filter((i) => i.kind === kind).map((i) => [i.path.toLowerCase(), i]))
114
+ const contentByPath = byPath('content')
115
+ const libraryByPath = byPath('library')
116
+ const mediaByPath = byPath('media')
117
+
118
+ // ------------------------------------------------------ the site's schema
119
+ const typeCache = new Map<string, ContentTypeAggregate | undefined>()
120
+ const typeOf = async (repo: ContentTypeRepository, alias: string) => {
121
+ const cacheKey = `${repo.objectType}:${alias.toLowerCase()}`
122
+ if (!typeCache.has(cacheKey)) typeCache.set(cacheKey, await repo.byAlias(alias))
123
+ return typeCache.get(cacheKey)
124
+ }
125
+ const editorCache = new Map<string, Map<string, { editor: string; variesByCulture: boolean }>>()
126
+ const editorsOf = async (repo: ContentTypeRepository, type: ContentTypeAggregate) => {
127
+ const cached = editorCache.get(type.key)
128
+ if (cached) return cached
129
+ const properties = await repo.resolveProperties(type.key)
130
+ const editorByType = new Map(
131
+ (await dataTypes.byKeys(properties.map((p) => p.dataTypeKey))).map((d) => [
132
+ d.key,
133
+ d.editorAlias,
134
+ ]),
135
+ )
136
+ const out = new Map<string, { editor: string; variesByCulture: boolean }>()
137
+ for (const property of properties) {
138
+ const editor = editorByType.get(property.dataTypeKey)
139
+ if (editor) out.set(property.alias, { editor, variesByCulture: property.variesByCulture })
140
+ }
141
+ editorCache.set(type.key, out)
142
+ return out
143
+ }
144
+
145
+ /** Content on the site the seed does not declare, by path or key, for a reference to point at. */
146
+ const expected = new Map<string, { key: string; objectType: string; name: string; why: string }>()
147
+ const siteNode = async (ref: string, objectType: string, why: string) => {
148
+ const resolved = await resolveNodeRef(db, [objectType], ref)
149
+ if (!resolved.ok || resolved.node.objectType !== objectType) return undefined
150
+ expected.set(resolved.node.key, {
151
+ key: resolved.node.key,
152
+ objectType,
153
+ name: resolved.node.text ?? '',
154
+ why,
155
+ })
156
+ return resolved.node.key
157
+ }
158
+ const trimPath = (ref: string) => ref.replace(/^\/+|\/+$/g, '').toLowerCase()
159
+ const contentKey = async (ref: string, why: string) => {
160
+ const seeded = contentByPath.get(trimPath(ref))
161
+ if (seeded) return keyOf.get(seeded)
162
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
163
+ return siteNode(ref, ObjectTypes.Document, why)
164
+ }
165
+ const mediaRef = async (ref: string, why: string) => {
166
+ const seeded = mediaByPath.get(trimPath(ref))
167
+ if (seeded)
168
+ return { key: keyOf.get(seeded) as string, typeAlias: mediaTypeAlias.get(seeded) ?? 'Image' }
169
+ const key = looksLikeKey(ref) ? normaliseUuid(ref) : await siteNode(ref, ObjectTypes.Media, why)
170
+ if (!key) return undefined
171
+ const rows = await db.query<{ alias: string }>(
172
+ `SELECT ct.alias FROM node n JOIN content c ON c.node_id = n.id
173
+ JOIN content_type ct ON ct.node_id = c.content_type_id WHERE n.unique_id = ?`,
174
+ [key],
175
+ )
176
+ return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
177
+ }
178
+ const libraryKey = async (ref: string, why: string) => {
179
+ const seeded = libraryByPath.get(trimPath(ref))
180
+ if (seeded) return keyOf.get(seeded)
181
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
182
+ return siteNode(ref, ObjectTypes.Element, why)
183
+ }
184
+
185
+ // ---------------------------------------------------------------- values
186
+ type Converted = { ok: true; value: unknown } | { ok: false; message: string }
187
+ const fail = (message: string): Converted => ({ ok: false, message })
188
+
189
+ /** Rich text: Markdown by default, `{ html = … }` as written; links to content paths become local links. */
190
+ const richText = async (raw: unknown, why: string): Promise<Converted> => {
191
+ let html: string
192
+ if (typeof raw === 'string') html = Bun.markdown.html(raw)
193
+ else if (isRecord(raw) && typeof raw.html === 'string') html = raw.html
194
+ else if (isRecord(raw) && typeof raw.markdown === 'string')
195
+ html = Bun.markdown.html(raw.markdown)
196
+ else if (isRecord(raw) && 'markup' in raw) return { ok: true, value: raw }
197
+ else return fail('rich text is Markdown, or { html = "…" }')
198
+ const links = [...html.matchAll(/href="(\/[^"#?]*)"/g)]
199
+ for (const [whole, path] of links) {
200
+ const key = await contentKey(path as string, why)
201
+ if (key) html = html.replace(whole, `href="/{localLink:${key}}"`)
202
+ }
203
+ return { ok: true, value: { markup: html, blocks: null } }
204
+ }
205
+
206
+ const blocks = async (
207
+ editor: keyof typeof BLOCK_LAYOUT,
208
+ raw: unknown,
209
+ owner: string,
210
+ where: string,
211
+ ): Promise<Converted> => {
212
+ if (!Array.isArray(raw)) {
213
+ if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
214
+ return fail('blocks are a list of { type = "<element alias>", values = { … } }')
215
+ }
216
+ const layout: Record<string, unknown>[] = []
217
+ const contentData: unknown[] = []
218
+ const settingsData: unknown[] = []
219
+ for (const [index, entry] of raw.entries()) {
220
+ if (!isRecord(entry) || typeof entry.type !== 'string')
221
+ return fail(`block ${index + 1} has no type`)
222
+ const element = await typeOf(documentTypes, entry.type)
223
+ if (!element?.isElement)
224
+ return fail(`block ${index + 1}: there is no element type "${entry.type}"`)
225
+ const contentKey = blockKey(owner, `${where}/${index}`)
226
+ const values = await elementValues(element, entry.values, owner, `${where}/${index}`)
227
+ if (!values.ok) return fail(`block ${index + 1}: ${values.message}`)
228
+ contentData.push({ key: contentKey, contentTypeKey: element.key, values: values.value })
229
+ const item: Record<string, unknown> = { contentKey }
230
+ if (isRecord(entry.settings)) {
231
+ const settingsType =
232
+ typeof entry.settings.type === 'string'
233
+ ? await typeOf(documentTypes, entry.settings.type)
234
+ : undefined
235
+ if (!settingsType?.isElement)
236
+ return fail(`block ${index + 1}: settings need a type, an element type`)
237
+ const settingsKey = blockKey(owner, `${where}/${index}/settings`)
238
+ const settings = await elementValues(
239
+ settingsType,
240
+ entry.settings.values,
241
+ owner,
242
+ `${where}/${index}/settings`,
243
+ )
244
+ if (!settings.ok) return fail(`block ${index + 1} settings: ${settings.message}`)
245
+ settingsData.push({
246
+ key: settingsKey,
247
+ contentTypeKey: settingsType.key,
248
+ values: settings.value,
249
+ })
250
+ item.settingsKey = settingsKey
251
+ }
252
+ if (editor === 'Umbraco.BlockGrid') {
253
+ item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
254
+ item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
255
+ item.areas = Array.isArray(entry.areas) ? entry.areas : []
256
+ }
257
+ layout.push(item)
258
+ }
259
+ return {
260
+ ok: true,
261
+ value: { layout: { [BLOCK_LAYOUT[editor]]: layout }, contentData, settingsData },
262
+ }
263
+ }
264
+
265
+ const elementValues = async (
266
+ element: ContentTypeAggregate,
267
+ raw: unknown,
268
+ owner: string,
269
+ where: string,
270
+ ): Promise<Converted> => {
271
+ if (raw === undefined) return { ok: true, value: [] }
272
+ if (!isRecord(raw)) return fail('values is a table')
273
+ const editors = await editorsOf(documentTypes, element)
274
+ const out: Array<{ alias: string; value: unknown }> = []
275
+ for (const [alias, value] of Object.entries(raw)) {
276
+ const property = editors.get(alias)
277
+ if (!property) return fail(`"${element.alias}" has no property "${alias}"`)
278
+ const converted = await convert(property.editor, value, owner, `${where}/${alias}`)
279
+ if (!converted.ok) return fail(`${alias}: ${converted.message}`)
280
+ out.push({ alias, value: converted.value })
281
+ }
282
+ return { ok: true, value: out }
283
+ }
284
+
285
+ const list = (raw: unknown) => (Array.isArray(raw) ? raw : [raw])
286
+
287
+ const convert = async (
288
+ editor: string,
289
+ raw: unknown,
290
+ owner: string,
291
+ where: string,
292
+ ): Promise<Converted> => {
293
+ const why = `named by a value in ${where}`
294
+ switch (editor) {
295
+ case 'Umbraco.TextBox':
296
+ case 'Umbraco.TextArea':
297
+ return typeof raw === 'string' || typeof raw === 'number'
298
+ ? { ok: true, value: String(raw) }
299
+ : fail('a text value is a string')
300
+ case 'Umbraco.RichText':
301
+ case 'Umbraco.TinyMCE':
302
+ return richText(raw, why)
303
+ case 'Umbraco.TrueFalse':
304
+ return typeof raw === 'boolean'
305
+ ? { ok: true, value: raw }
306
+ : fail('a toggle is true or false')
307
+ case 'Umbraco.Integer':
308
+ case 'Umbraco.Decimal':
309
+ case 'Umbraco.Slider':
310
+ return typeof raw === 'number' ? { ok: true, value: raw } : fail('a number is a number')
311
+ case 'Umbraco.DateTime':
312
+ case 'Umbraco.DateTimeWithTimeZone':
313
+ if (raw instanceof Date) return { ok: true, value: raw.toISOString() }
314
+ return typeof raw === 'string' && !Number.isNaN(new Date(raw).getTime())
315
+ ? { ok: true, value: raw }
316
+ : fail('a date is a TOML date or an ISO 8601 string')
317
+ case 'Umbraco.Tags':
318
+ return list(raw).every((tag) => typeof tag === 'string')
319
+ ? { ok: true, value: list(raw) }
320
+ : fail('tags are a list of strings')
321
+ case 'Umbraco.ContentPicker': {
322
+ if (typeof raw !== 'string') return fail('a content picker takes a content path')
323
+ const key = await contentKey(raw, why)
324
+ return key
325
+ ? { ok: true, value: `umb://document/${key.replaceAll('-', '')}` }
326
+ : fail(`"${raw}" is not a page in the seed or on the site`)
327
+ }
328
+ case 'Umbraco.MediaPicker3': {
329
+ if (isRecord(raw) || (Array.isArray(raw) && raw.some(isRecord)))
330
+ return { ok: true, value: raw }
331
+ const picks: unknown[] = []
332
+ for (const ref of list(raw)) {
333
+ if (typeof ref !== 'string') return fail('a media picker takes media paths')
334
+ const media = await mediaRef(ref, why)
335
+ if (!media) return fail(`"${ref}" is not media in the seed or on the site`)
336
+ picks.push({
337
+ key: uuidV5(`pick:${media.key}`),
338
+ mediaKey: media.key,
339
+ mediaTypeAlias: media.typeAlias,
340
+ crops: [],
341
+ focalPoint: null,
342
+ })
343
+ }
344
+ return { ok: true, value: picks }
345
+ }
346
+ case 'Umbraco.ElementPicker': {
347
+ const keys: string[] = []
348
+ for (const ref of list(raw)) {
349
+ if (typeof ref !== 'string') return fail('an element picker takes Library paths')
350
+ const key = await libraryKey(ref, why)
351
+ if (!key) return fail(`"${ref}" is not a Library element in the seed or on the site`)
352
+ keys.push(key)
353
+ }
354
+ return { ok: true, value: keys }
355
+ }
356
+ case 'Umbraco.MultiUrlPicker': {
357
+ const links: unknown[] = []
358
+ for (const entry of list(raw)) {
359
+ const link = typeof entry === 'string' ? { path: entry } : entry
360
+ if (!isRecord(link))
361
+ return fail('a link is a path, a URL, or { path | url, name, target }')
362
+ // A link as the editor stores it, as `seed export` writes one.
363
+ if ('unique' in link || 'type' in link) {
364
+ links.push(link)
365
+ continue
366
+ }
367
+ const target = typeof link.target === 'string' ? link.target : null
368
+ const url = typeof link.url === 'string' ? link.url : undefined
369
+ const path = typeof link.path === 'string' ? link.path : undefined
370
+ if (path && /^[a-z]+:\/\//i.test(path)) {
371
+ links.push({
372
+ unique: null,
373
+ type: 'external',
374
+ name: link.name ?? path,
375
+ target,
376
+ url: path,
377
+ })
378
+ continue
379
+ }
380
+ if (url) {
381
+ links.push({ unique: null, type: 'external', name: link.name ?? url, target, url })
382
+ continue
383
+ }
384
+ if (!path) return fail('a link needs a path or a url')
385
+ const media = mediaByPath.get(trimPath(path))
386
+ const key = media ? keyOf.get(media) : await contentKey(path, why)
387
+ if (!key) return fail(`"${path}" is not a page or media in the seed or on the site`)
388
+ links.push({
389
+ unique: key,
390
+ type: media ? 'media' : 'document',
391
+ name: typeof link.name === 'string' ? link.name : null,
392
+ target,
393
+ })
394
+ }
395
+ return { ok: true, value: links }
396
+ }
397
+ case 'Umbraco.BlockList':
398
+ case 'Umbraco.BlockGrid':
399
+ return blocks(editor, raw, owner, where)
400
+ default:
401
+ return { ok: true, value: raw }
402
+ }
403
+ }
404
+
405
+ // ------------------------------------------------------------- the nodes
406
+ const mediaTypeAlias = new Map<SeedItem, string>()
407
+ const bundleNodes: BundleNode[] = []
408
+ const blobs = new Map<string, Uint8Array>()
409
+ const blobList: BundleBlob[] = []
410
+ const usedTypes = new Map<string, string>()
411
+ const usedComponents = new Set<string>()
412
+ const usedLanguages = new Set<string>()
413
+ const typeOfItem = new Map<SeedItem, ContentTypeAggregate>()
414
+
415
+ // Media types first: a content value may pick an item, and names its type.
416
+ const folderType = (await port.folderTypes()).find((t) => t.name === 'Folder')
417
+ for (const item of tree.items.filter((i) => i.kind === 'media')) {
418
+ const alias =
419
+ typeof item.data.type === 'string' ? item.data.type : item.folder ? 'Folder' : undefined
420
+ let type = alias ? await typeOf(mediaTypes, alias) : undefined
421
+ if (!type && !item.folder && !alias) {
422
+ const choices = await port.typesForExtension(extname(item.path))
423
+ const choice = choices.find((c) => c.matched) ?? choices[0]
424
+ type = choice ? await mediaTypes.byKey(choice.key) : undefined
425
+ }
426
+ if (!type && item.folder && folderType) type = await mediaTypes.byKey(folderType.key)
427
+ if (!type) {
428
+ find(
429
+ item,
430
+ ['type'],
431
+ 'unknown-type',
432
+ alias
433
+ ? `there is no media type "${alias}"`
434
+ : `no media type takes a ${extname(item.path) || 'file without an extension'}`,
435
+ )
436
+ continue
437
+ }
438
+ typeOfItem.set(item, type)
439
+ mediaTypeAlias.set(item, type.alias)
440
+ }
441
+
442
+ const nameOf = (item: SeedItem): Array<{ culture: string | null; name: string }> => {
443
+ const segment = item.path.split('/').at(-1) as string
444
+ const given = item.data.name
445
+ if (typeof given === 'string') return [{ culture: null, name: given }]
446
+ if (isRecord(given))
447
+ return Object.entries(given).flatMap(([culture, name]) => {
448
+ const iso = languages.get(culture.toLowerCase())
449
+ if (!iso) {
450
+ find(
451
+ item,
452
+ ['name', culture],
453
+ 'language-missing',
454
+ `there is no language "${culture}" here`,
455
+ )
456
+ return []
457
+ }
458
+ usedLanguages.add(iso)
459
+ return [{ culture: iso, name: String(name) }]
460
+ })
461
+ return [{ culture: null, name: item.kind === 'media' ? segment : nameFromSegment(segment) }]
462
+ }
463
+
464
+ for (const item of tree.items) {
465
+ const key = keyOf.get(item) as string
466
+ let type = typeOfItem.get(item)
467
+ if (item.kind !== 'media') {
468
+ if (typeof item.data.type !== 'string') {
469
+ find(item, [], 'no-type', 'an item names its content type: type = "<alias>"')
470
+ continue
471
+ }
472
+ type = await typeOf(documentTypes, item.data.type)
473
+ if (!type) {
474
+ find(item, ['type'], 'unknown-type', `there is no content type "${item.data.type}"`)
475
+ continue
476
+ }
477
+ if (item.kind === 'library' && !type.isElement) {
478
+ find(
479
+ item,
480
+ ['type'],
481
+ 'not-an-element',
482
+ `"${type.alias}" is not an element type, so it cannot sit in the Library`,
483
+ )
484
+ continue
485
+ }
486
+ if (item.kind === 'content' && type.isElement) {
487
+ find(
488
+ item,
489
+ ['type'],
490
+ 'element-as-page',
491
+ `"${type.alias}" is an element type: put it in seed/library`,
492
+ )
493
+ continue
494
+ }
495
+ typeOfItem.set(item, type)
496
+ }
497
+ if (!type) continue
498
+ usedTypes.set(type.alias, type.key)
499
+
500
+ // Where it sits: its parent's type has to allow it, as an editor's would.
501
+ if (item.kind !== 'library') {
502
+ const parentItem = item.parent
503
+ ? (item.kind === 'media' ? mediaByPath : contentByPath).get(item.parent.toLowerCase())
504
+ : undefined
505
+ const parentType = parentItem ? typeOfItem.get(parentItem) : undefined
506
+ const allowed = parentItem
507
+ ? (parentType?.allowedContentTypes.some(
508
+ (a) => normaliseUuid(a.contentTypeKey) === normaliseUuid(type.key),
509
+ ) ?? true)
510
+ : type.allowedAsRoot
511
+ if (!allowed)
512
+ find(
513
+ item,
514
+ ['type'],
515
+ 'not-allowed-here',
516
+ parentItem
517
+ ? `"${type.name}" isn't allowed under "${parentType?.name ?? item.parent}"`
518
+ : `"${type.name}" isn't allowed at the top level`,
519
+ )
520
+ }
521
+
522
+ const editors = await editorsOf(item.kind === 'media' ? mediaTypes : documentTypes, type)
523
+ const values: BundleValue[] = []
524
+ const addValues = async (
525
+ table: Record<string, unknown>,
526
+ culture: string | null,
527
+ path: string[],
528
+ ) => {
529
+ for (const [alias, raw] of Object.entries(table)) {
530
+ const property = editors.get(alias)
531
+ if (!property) {
532
+ const iso =
533
+ culture === null && isRecord(raw) ? languages.get(alias.toLowerCase()) : undefined
534
+ if (iso) {
535
+ usedLanguages.add(iso)
536
+ await addValues(raw as Record<string, unknown>, iso, [...path, alias])
537
+ continue
538
+ }
539
+ if (culture === null && isRecord(raw) && /^[a-z]{2}(-[a-z]{2,4})?$/i.test(alias)) {
540
+ find(item, [...path, alias], 'language-missing', `there is no language "${alias}" here`)
541
+ continue
542
+ }
543
+ find(
544
+ item,
545
+ [...path, alias],
546
+ 'unknown-property',
547
+ `"${type.alias}" has no property "${alias}"`,
548
+ )
549
+ continue
550
+ }
551
+ const converted = await convert(property.editor, raw, key, alias)
552
+ if (!converted.ok) {
553
+ find(item, [...path, alias], 'bad-value', `${alias}: ${converted.message}`)
554
+ continue
555
+ }
556
+ values.push({
557
+ property: alias,
558
+ culture,
559
+ segment: null,
560
+ editor: property.editor,
561
+ value: converted.value,
562
+ })
563
+ }
564
+ }
565
+ if (item.data.values !== undefined) {
566
+ if (isRecord(item.data.values)) await addValues(item.data.values, null, ['values'])
567
+ else find(item, ['values'], 'bad-values', 'values is a table: [values]')
568
+ }
569
+
570
+ if (item.kind === 'media' && item.bytes) {
571
+ const file = item.path.split('/').at(-1) as string
572
+ const blobKey = `${key.replaceAll('-', '').slice(0, 8)}/${file}`
573
+ const src = `/media/${blobKey}`
574
+ const fileEditor = editors.get('umbracoFile')?.editor
575
+ const focalPoint = isRecord(item.data.focalPoint) ? item.data.focalPoint : null
576
+ const media: Record<string, unknown> = {
577
+ umbracoFile:
578
+ fileEditor === IMAGE_CROPPER_EDITOR_ALIAS ? { src, crops: [], focalPoint } : src,
579
+ umbracoBytes: item.bytes.length,
580
+ umbracoExtension: extname(file).slice(1).toLowerCase(),
581
+ }
582
+ if (fileEditor === IMAGE_CROPPER_EDITOR_ALIAS)
583
+ try {
584
+ const { width, height } = await new Bun.Image(item.bytes).metadata()
585
+ media.umbracoWidth = width
586
+ media.umbracoHeight = height
587
+ } catch {
588
+ find(item, [], 'bad-image', `${file} is not an image this site can read`)
589
+ }
590
+ for (const [alias, value] of Object.entries(media)) {
591
+ const editor = editors.get(alias)?.editor
592
+ if (editor && !values.some((v) => v.property === alias))
593
+ values.push({ property: alias, culture: null, segment: null, editor, value })
594
+ }
595
+ blobs.set(blobKey, item.bytes)
596
+ blobList.push({
597
+ key: blobKey,
598
+ node: key,
599
+ etag: createHash('sha256').update(item.bytes).digest('hex'),
600
+ size: item.bytes.length,
601
+ included: true,
602
+ })
603
+ }
604
+
605
+ const template =
606
+ item.kind !== 'content'
607
+ ? null
608
+ : typeof item.data.template === 'string'
609
+ ? item.data.template
610
+ : type.defaultComponentKey
611
+ ? ((await components.byKey(type.defaultComponentKey))?.alias ?? null)
612
+ : null
613
+ if (template) usedComponents.add(template)
614
+ const published = item.data.published !== false
615
+ const parent =
616
+ item.kind === 'library' || !item.parent
617
+ ? null
618
+ : (keyOf.get(
619
+ (item.kind === 'media' ? mediaByPath : contentByPath).get(
620
+ item.parent.toLowerCase(),
621
+ ) as SeedItem,
622
+ ) ?? null)
623
+ const names = nameOf(item)
624
+ // A renamed file is a new key: say so where a page of that name is already here.
625
+ if (item.kind === 'content') {
626
+ const parentId = parent ? (await nodes.byKey(parent))?.id : SystemNodes.Root
627
+ const name = names[0]?.name ?? ''
628
+ const here =
629
+ parentId === undefined
630
+ ? []
631
+ : await nodes.childrenNamed(parentId, [ObjectTypes.Document], name)
632
+ const other = here.find((node) => node.key !== key)
633
+ if (other)
634
+ find(
635
+ item,
636
+ ['name'],
637
+ 'name-taken',
638
+ `"${name}" is already here as another page (${other.key}). A renamed file is a new page: give it key = "${other.key}" to keep the one that is here`,
639
+ )
640
+ }
641
+ const kind: BundleKind =
642
+ item.kind === 'content' ? 'document' : item.kind === 'library' ? 'element' : 'media'
643
+ bundleNodes.push({
644
+ key,
645
+ kind,
646
+ contentType: { key: type.key, alias: type.alias },
647
+ parent,
648
+ sortOrder: 0,
649
+ template,
650
+ variants: names.map((v) => ({ ...v, segment: null, published })),
651
+ values,
652
+ })
653
+ }
654
+
655
+ // Order among siblings: `order`, then the name.
656
+ const orderOf = (node: BundleNode) => {
657
+ const item = byKey.get(node.key)
658
+ return typeof item?.data.order === 'number' ? item.data.order : Number.MAX_SAFE_INTEGER
659
+ }
660
+ const groups = new Map<string, BundleNode[]>()
661
+ for (const node of bundleNodes) {
662
+ const group = `${node.kind}:${node.parent ?? ''}`
663
+ groups.set(group, [...(groups.get(group) ?? []), node])
664
+ }
665
+ for (const group of groups.values()) {
666
+ group.sort(
667
+ (a, b) =>
668
+ orderOf(a) - orderOf(b) ||
669
+ (a.variants[0]?.name ?? '').localeCompare(b.variants[0]?.name ?? ''),
670
+ )
671
+ for (const [index, node] of group.entries()) node.sortOrder = index
672
+ }
673
+
674
+ if (findings.length > 0) return { findings, blobs, counts }
675
+
676
+ // The seed's identity is its content: a changed seed is a new bundle, which
677
+ // `start --seed` applies and the three-way import takes as a newer one.
678
+ const identity = createHash('sha256')
679
+ for (const item of tree.items) {
680
+ identity.update(`${item.kind}\0${item.path}\0${item.text}\0`)
681
+ if (item.bytes) identity.update(item.bytes)
682
+ }
683
+ const id = uuidV5(`seed:${identity.digest('hex')}`)
684
+ const tally: Partial<Record<BundleKind, number>> = {}
685
+ for (const node of bundleNodes) tally[node.kind] = (tally[node.kind] ?? 0) + 1
686
+ const set: ContentSet = {
687
+ manifest: {
688
+ formatVersion: 1,
689
+ id,
690
+ label: 'Seed',
691
+ createdAt: new Date(0).toISOString(),
692
+ createdBy: 'crombolo seed',
693
+ integrity: '',
694
+ snapshot: 'drafts',
695
+ provenance: {
696
+ siteName: config.siteName,
697
+ schemaVersion: state.version,
698
+ schemaRevision: state.revision,
699
+ schemaHash: state.hash,
700
+ cmsVersion: VERSION,
701
+ },
702
+ selector: {
703
+ roots: bundleNodes.filter((n) => n.parent === null).map((n) => n.key),
704
+ descendants: true,
705
+ asGiven: ['seed/'],
706
+ },
707
+ counts: tally,
708
+ dependencies: {
709
+ carried: bundleNodes.map((n) => n.key),
710
+ expected: [...expected.values()].filter((e) => !byKey.has(e.key)),
711
+ schema: {
712
+ contentTypes: [...usedTypes].map(([alias, key]) => ({ key, alias })),
713
+ components: [...usedComponents],
714
+ languages: [...usedLanguages],
715
+ },
716
+ },
717
+ blobs: blobList,
718
+ },
719
+ nodes: bundleNodes,
720
+ }
721
+ const payload = writeBundle(set, blobs)
722
+ const files = writeBundlePackage(payload, {
723
+ name: 'crombolo-site-seed',
724
+ version: '0.0.0',
725
+ id: 'site-seed',
726
+ label: 'Seed',
727
+ description: `The seed of ${config.siteName}, built by crombolo seed build`,
728
+ private: true,
729
+ peerRange: `>=${VERSION}`,
730
+ })
731
+ return { findings, set, blobs, files, counts }
732
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Content already in a site, written out as seed files (story 163), so an
3
+ * existing site can move to seeds. Text and toggles are written as themselves,
4
+ * a content picker as the page's path where the export carries it, and every
5
+ * other value in its editor's stored shape, which `seed apply` takes back
6
+ * as given. A node keeps its key in the file wherever it is not the one its
7
+ * path would derive, so a round trip names the same nodes.
8
+ */
9
+ import { mkdirSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { normaliseUuid, ObjectTypes } from '@crombolo/core'
12
+ import {
13
+ currentSchemaState,
14
+ type Db,
15
+ DocumentRepository,
16
+ NodeRepository,
17
+ type NodeRow,
18
+ } from '@crombolo/data'
19
+ import { seedKey } from './keys.ts'
20
+
21
+ /** A URL segment from a name: `About us` → `about-us`. */
22
+ export const segmentOf = (name: string) =>
23
+ name
24
+ .normalize('NFKD')
25
+ .replace(/[̀-ͯ]/g, '')
26
+ .toLowerCase()
27
+ .replace(/[^a-z0-9]+/g, '-')
28
+ .replace(/^-+|-+$/g, '') || 'item'
29
+
30
+ const bareKey = (key: string) => (/^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key))
31
+
32
+ /** A value as TOML, inline. Nulls are left out: TOML has none. */
33
+ export function tomlValue(value: unknown): string | undefined {
34
+ if (value === null || value === undefined) return undefined
35
+ if (typeof value === 'string') return JSON.stringify(value)
36
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
37
+ if (value instanceof Date) return value.toISOString()
38
+ if (Array.isArray(value))
39
+ return `[${value
40
+ .map(tomlValue)
41
+ .filter((v) => v !== undefined)
42
+ .join(', ')}]`
43
+ if (typeof value === 'object') {
44
+ const entries = Object.entries(value as Record<string, unknown>).flatMap(([k, v]) => {
45
+ const written = tomlValue(v)
46
+ return written === undefined ? [] : [`${bareKey(k)} = ${written}`]
47
+ })
48
+ return `{ ${entries.join(', ')} }`
49
+ }
50
+ return JSON.stringify(String(value))
51
+ }
52
+
53
+ const PICKER = /^umb:\/\/document\/([0-9a-f]{32})$/i
54
+ const dashed = (hex: string) =>
55
+ `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
56
+
57
+ export interface SeedExportResult {
58
+ written: string[]
59
+ }
60
+
61
+ /** Writes the branches under `roots` as `seed/content/…` files in `siteDir`. */
62
+ export async function exportSeed(
63
+ db: Db,
64
+ siteDir: string,
65
+ roots: readonly NodeRow[],
66
+ ): Promise<SeedExportResult> {
67
+ const state = await currentSchemaState(db)
68
+ const docs = new DocumentRepository(db, {
69
+ nodeState: { version: state.version, revision: state.revision },
70
+ })
71
+ const nodes = new NodeRepository(db)
72
+ const typeAliases = new Map<string, string>()
73
+ const aliasOf = async (typeKey: string) => {
74
+ if (!typeAliases.has(typeKey)) {
75
+ const rows = await db.query<{ alias: string }>(
76
+ `SELECT ct.alias FROM node n JOIN content_type ct ON ct.node_id = n.id WHERE n.unique_id = ?`,
77
+ [normaliseUuid(typeKey)],
78
+ )
79
+ typeAliases.set(typeKey, rows[0] ? String(rows[0].alias) : typeKey)
80
+ }
81
+ return typeAliases.get(typeKey) as string
82
+ }
83
+
84
+ // Every node's seed path first, so a picker can name a page by where it lands.
85
+ const pathOf = new Map<string, string>()
86
+ const branch: Array<{ node: NodeRow; path: string; order: number }> = []
87
+ const walk = async (node: NodeRow, parentPath: string | null, order: number) => {
88
+ const taken = new Set(
89
+ branch
90
+ .filter((b) => b.path.startsWith(parentPath ? `${parentPath}/` : ''))
91
+ .map((b) => b.path),
92
+ )
93
+ let segment = segmentOf(node.text ?? node.key)
94
+ for (let n = 2; taken.has(parentPath ? `${parentPath}/${segment}` : segment); n++)
95
+ segment = `${segmentOf(node.text ?? node.key)}-${n}`
96
+ const path = parentPath ? `${parentPath}/${segment}` : segment
97
+ pathOf.set(node.key, path)
98
+ branch.push({ node, path, order })
99
+ const children = await nodes.children(node.id, ObjectTypes.Document, 0, Number.MAX_SAFE_INTEGER)
100
+ for (const [index, child] of children.items.entries()) await walk(child, path, index)
101
+ }
102
+ for (const [index, root] of roots.entries()) await walk(root, null, index)
103
+
104
+ const written: string[] = []
105
+ for (const { node, path, order } of branch) {
106
+ const doc = await docs.byKey(node.key)
107
+ if (!doc) continue
108
+ const lines: string[] = [`type = ${JSON.stringify(await aliasOf(doc.contentTypeKey))}`]
109
+ if (normaliseUuid(node.key) !== seedKey(`content/${path}`))
110
+ lines.push(`key = ${JSON.stringify(node.key)}`)
111
+ const invariant = doc.variants.find((v) => v.culture === null)
112
+ if (invariant) lines.push(`name = ${JSON.stringify(invariant.name)}`)
113
+ else
114
+ lines.push(
115
+ `name = ${tomlValue(Object.fromEntries(doc.variants.map((v) => [v.culture as string, v.name])))}`,
116
+ )
117
+ lines.push(`order = ${order}`)
118
+ if (!doc.variants.some((v) => v.state === 'Published' || v.state === 'PublishedPendingChanges'))
119
+ lines.push('published = false')
120
+
121
+ const value = (raw: unknown) => {
122
+ if (typeof raw === 'string') {
123
+ const picked = PICKER.exec(raw)
124
+ if (picked) {
125
+ const key = dashed((picked[1] as string).toLowerCase())
126
+ return pathOf.has(key) ? `/${pathOf.get(key)}` : key
127
+ }
128
+ }
129
+ return raw
130
+ }
131
+ const byCulture = new Map<string | null, string[]>()
132
+ for (const v of doc.values) {
133
+ if (v.segment !== null) continue
134
+ const written = tomlValue(value(v.value))
135
+ if (written === undefined) continue
136
+ const list = byCulture.get(v.culture) ?? []
137
+ list.push(`${bareKey(v.alias)} = ${written}`)
138
+ byCulture.set(v.culture, list)
139
+ }
140
+ for (const [culture, entries] of byCulture) {
141
+ lines.push('', culture ? `[values.${bareKey(culture)}]` : '[values]', ...entries)
142
+ }
143
+ const file = join(siteDir, 'seed', 'content', `${path}.toml`)
144
+ mkdirSync(join(file, '..'), { recursive: true })
145
+ writeFileSync(file, `${lines.join('\n')}\n`)
146
+ written.push(`seed/content/${path}.toml`)
147
+ }
148
+ return { written }
149
+ }
@@ -0,0 +1,5 @@
1
+ export * from './compile.ts'
2
+ export * from './export.ts'
3
+ export * from './keys.ts'
4
+ export * from './lines.ts'
5
+ export * from './read.ts'
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Keys for seed items (story 163): RFC 4122 version 5 uuids, named by kind and
3
+ * path under one fixed namespace, so a rebuild names the same node and two
4
+ * sites built from the same seed share keys.
5
+ */
6
+ import { createHash } from 'node:crypto'
7
+
8
+ /** Crombolo's seed namespace. Fixed for ever: changing it re-keys every seeded node. */
9
+ export const SEED_NAMESPACE = '6f1d3c0e-7a52-4b8e-9c41-2e5f8a1b7d63'
10
+
11
+ const bytesOf = (uuid: string) => Buffer.from(uuid.replaceAll('-', ''), 'hex')
12
+
13
+ /** A version 5 uuid for `name` in `namespace`. Pure. */
14
+ export function uuidV5(name: string, namespace = SEED_NAMESPACE): string {
15
+ const hash = createHash('sha1').update(bytesOf(namespace)).update(name, 'utf8').digest()
16
+ const bytes = hash.subarray(0, 16)
17
+ bytes[6] = ((bytes[6] as number) & 0x0f) | 0x50
18
+ bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80
19
+ const hex = bytes.toString('hex')
20
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
21
+ }
22
+
23
+ /** The key a seed item has when its file gives none: `content/about/team`, `media/logos/mark.png`. */
24
+ export const seedKey = (path: string) => uuidV5(path)
25
+
26
+ /** The key of a block inside an item's value: stable for the item, the property and the position. */
27
+ export const blockKey = (owner: string, where: string) => uuidV5(`${owner}#${where}`)
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Where a key sits in a seed file (story 163). `Bun.TOML` parses without
3
+ * positions, so a finding's line is found by reading the file the way TOML is
4
+ * laid out: a `[table]` header, then `key = value` lines under it. Good enough
5
+ * for the shapes seeds use; anything it cannot place is line 1.
6
+ */
7
+
8
+ const unquote = (part: string) =>
9
+ part
10
+ .trim()
11
+ .replace(/^"(.*)"$/, '$1')
12
+ .replace(/^'(.*)'$/, '$1')
13
+
14
+ const splitDotted = (text: string): string[] => {
15
+ const parts: string[] = []
16
+ let current = ''
17
+ let quote: string | null = null
18
+ for (const char of text) {
19
+ if (quote) {
20
+ if (char === quote) quote = null
21
+ current += char
22
+ } else if (char === '"' || char === "'") {
23
+ quote = char
24
+ current += char
25
+ } else if (char === '.') {
26
+ parts.push(unquote(current))
27
+ current = ''
28
+ } else current += char
29
+ }
30
+ parts.push(unquote(current))
31
+ return parts.filter((part) => part.length > 0)
32
+ }
33
+
34
+ /** The 1-based line of a dotted path (`['values', 'en-US', 'title']`) in a TOML text. */
35
+ export function lineOf(text: string, path: readonly string[]): number {
36
+ if (path.length === 0) return 1
37
+ const lines = text.split('\n')
38
+ let table: string[] = []
39
+ let best = 0
40
+ for (const [index, raw] of lines.entries()) {
41
+ const line = raw.trim()
42
+ if (line.startsWith('#') || line === '') continue
43
+ const header = /^\[\[?\s*([^\]]+?)\s*\]\]?$/.exec(line)
44
+ if (header) {
45
+ table = splitDotted(header[1] as string)
46
+ if (table.length <= path.length && table.every((part, i) => part === path[i]))
47
+ if (table.length === path.length) return index + 1
48
+ else if (best === 0) best = index + 1
49
+ continue
50
+ }
51
+ const assignment = /^((?:"[^"]*"|'[^']*'|[^=])+?)\s*=/.exec(line)
52
+ if (!assignment) continue
53
+ const full = [...table, ...splitDotted(assignment[1] as string)]
54
+ if (full.length === path.length && full.every((part, i) => part === path[i])) return index + 1
55
+ if (full.length < path.length && full.every((part, i) => part === path[i])) return index + 1
56
+ }
57
+ return best || 1
58
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Reading a site's `seed/` directory (story 163) into items: the content tree
3
+ * from `seed/content/`, Library elements from `seed/library/`, and media files
4
+ * and their folders from `seed/media/`. A content item is a TOML file named for
5
+ * its URL segment, with its children in a folder of the same name; a media file
6
+ * may have a sidecar, `photo.jpg.toml`.
7
+ */
8
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
9
+ import { join, relative } from 'node:path'
10
+
11
+ export type SeedKind = 'content' | 'library' | 'media'
12
+
13
+ export interface SeedItem {
14
+ kind: SeedKind
15
+ /** Its path in the tree, by segment: `about/team`, `logos/mark.png`. */
16
+ path: string
17
+ /** The parent's path, or null at the top. */
18
+ parent: string | null
19
+ /** The TOML file that describes it, relative to the site; null for a media item with no sidecar. */
20
+ file: string | null
21
+ text: string
22
+ data: Record<string, unknown>
23
+ /** A media file's bytes. */
24
+ bytes?: Uint8Array
25
+ /** A media folder: a directory under `seed/media/`. */
26
+ folder?: boolean
27
+ }
28
+
29
+ export interface SeedFinding {
30
+ file: string
31
+ line: number
32
+ code: string
33
+ message: string
34
+ }
35
+
36
+ export interface SeedTree {
37
+ items: SeedItem[]
38
+ findings: SeedFinding[]
39
+ }
40
+
41
+ const SKIPPED = (name: string) => name.startsWith('.')
42
+
43
+ /**
44
+ * The line a TOML syntax error is on: the first prefix of the file that does
45
+ * not parse. The parser's own position is not always the file's.
46
+ */
47
+ function syntaxLine(text: string): number {
48
+ const lines = text.split('\n')
49
+ for (let n = 1; n <= lines.length; n++) {
50
+ try {
51
+ Bun.TOML.parse(lines.slice(0, n).join('\n'))
52
+ } catch {
53
+ return n
54
+ }
55
+ }
56
+ return 1
57
+ }
58
+
59
+ export function readSeed(siteDir: string): SeedTree {
60
+ const root = join(siteDir, 'seed')
61
+ const items: SeedItem[] = []
62
+ const findings: SeedFinding[] = []
63
+ const shown = (path: string) => relative(siteDir, path)
64
+
65
+ const parse = (path: string): { text: string; data: Record<string, unknown> } | undefined => {
66
+ const text = readFileSync(path, 'utf8')
67
+ try {
68
+ return { text, data: Bun.TOML.parse(text) as Record<string, unknown> }
69
+ } catch (error) {
70
+ const line = syntaxLine(text)
71
+ findings.push({
72
+ file: shown(path),
73
+ line,
74
+ code: 'syntax',
75
+ message: (error as Error).message,
76
+ })
77
+ return undefined
78
+ }
79
+ }
80
+
81
+ const content = (kind: 'content' | 'library', dir: string, parent: string | null) => {
82
+ if (!existsSync(dir)) return
83
+ const names = readdirSync(dir)
84
+ .filter((name) => !SKIPPED(name))
85
+ .sort()
86
+ for (const name of names) {
87
+ const path = join(dir, name)
88
+ if (statSync(path).isDirectory()) {
89
+ if (kind === 'library') {
90
+ findings.push({
91
+ file: shown(path),
92
+ line: 1,
93
+ code: 'library-folder',
94
+ message: 'Library elements sit at the top of seed/library: folders are not read yet',
95
+ })
96
+ continue
97
+ }
98
+ if (!names.includes(`${name}.toml`))
99
+ findings.push({
100
+ file: shown(path),
101
+ line: 1,
102
+ code: 'orphan-folder',
103
+ message: `the folder ${name}/ holds children, but there is no ${name}.toml for the page they sit under`,
104
+ })
105
+ continue
106
+ }
107
+ if (!name.endsWith('.toml')) {
108
+ findings.push({
109
+ file: shown(path),
110
+ line: 1,
111
+ code: 'not-toml',
112
+ message: 'only .toml files describe content; this one is not read',
113
+ })
114
+ continue
115
+ }
116
+ const segment = name.slice(0, -'.toml'.length)
117
+ const itemPath = parent ? `${parent}/${segment}` : segment
118
+ const parsed = parse(path)
119
+ if (parsed) items.push({ kind, path: itemPath, parent, file: shown(path), ...parsed })
120
+ if (kind === 'content') content(kind, join(dir, segment), itemPath)
121
+ }
122
+ }
123
+
124
+ const media = (dir: string, parent: string | null) => {
125
+ if (!existsSync(dir)) return
126
+ const names = readdirSync(dir)
127
+ .filter((name) => !SKIPPED(name))
128
+ .sort()
129
+ for (const name of names) {
130
+ const path = join(dir, name)
131
+ const itemPath = parent ? `${parent}/${name}` : name
132
+ if (statSync(path).isDirectory()) {
133
+ items.push({
134
+ kind: 'media',
135
+ path: itemPath,
136
+ parent,
137
+ file: null,
138
+ text: '',
139
+ data: {},
140
+ folder: true,
141
+ })
142
+ media(path, itemPath)
143
+ continue
144
+ }
145
+ if (name.endsWith('.toml')) {
146
+ if (!names.includes(name.slice(0, -'.toml'.length)))
147
+ findings.push({
148
+ file: shown(path),
149
+ line: 1,
150
+ code: 'orphan-sidecar',
151
+ message: `there is no ${name.slice(0, -'.toml'.length)} beside this sidecar`,
152
+ })
153
+ continue
154
+ }
155
+ const sidecar = names.includes(`${name}.toml`) ? parse(join(dir, `${name}.toml`)) : undefined
156
+ items.push({
157
+ kind: 'media',
158
+ path: itemPath,
159
+ parent,
160
+ file: sidecar ? shown(join(dir, `${name}.toml`)) : null,
161
+ text: sidecar?.text ?? '',
162
+ data: sidecar?.data ?? {},
163
+ bytes: new Uint8Array(readFileSync(path)),
164
+ })
165
+ }
166
+ }
167
+
168
+ content('content', join(root, 'content'), null)
169
+ content('library', join(root, 'library'), null)
170
+ media(join(root, 'media'), null)
171
+ return { items, findings }
172
+ }
173
+
174
+ /** Whether a site has a seed at all. */
175
+ export const hasSeed = (siteDir: string) => existsSync(join(siteDir, 'seed'))