@crombolo/server 0.26.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.
@@ -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'))