@crombolo/server 0.52.2 → 0.54.1

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.52.2",
3
+ "version": "0.54.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,18 +31,18 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.52.2",
35
- "@crombolo/api-management": "0.52.2",
36
- "@crombolo/auth": "0.52.2",
37
- "@crombolo/backoffice-host": "0.52.2",
38
- "@crombolo/common": "0.52.2",
39
- "@crombolo/content": "0.52.2",
40
- "@crombolo/contracts": "0.52.2",
41
- "@crombolo/core": "0.52.2",
42
- "@crombolo/data": "0.52.2",
43
- "@crombolo/render": "0.52.2",
44
- "@crombolo/schema": "0.52.2",
45
- "@crombolo/transfer": "0.52.2",
34
+ "@crombolo/api-delivery": "0.54.1",
35
+ "@crombolo/api-management": "0.54.1",
36
+ "@crombolo/auth": "0.54.1",
37
+ "@crombolo/backoffice-host": "0.54.1",
38
+ "@crombolo/common": "0.54.1",
39
+ "@crombolo/content": "0.54.1",
40
+ "@crombolo/contracts": "0.54.1",
41
+ "@crombolo/core": "0.54.1",
42
+ "@crombolo/data": "0.54.1",
43
+ "@crombolo/render": "0.54.1",
44
+ "@crombolo/schema": "0.54.1",
45
+ "@crombolo/transfer": "0.54.1",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -32,6 +32,7 @@ import {
32
32
  type ContentTypeRepositoryOptions,
33
33
  DataTypeRepository,
34
34
  type Db,
35
+ FORM_LIBRARY_FOLDER,
35
36
  FolderRepository,
36
37
  Locks,
37
38
  type NodeRepository,
@@ -199,6 +200,19 @@ export interface ContentTypePortOptions extends ContentTypeRepositoryOptions {
199
200
  componentFiles?: ComponentFileStore
200
201
  }
201
202
 
203
+ /** Whether a tree item is the folder holding the types made from forms, and nothing else. */
204
+ async function madeFromForms(db: Db, item: TreeItem): Promise<boolean> {
205
+ if (!item.isFolder || item.name !== FORM_LIBRARY_FOLDER) return false
206
+ const rows = await db.q
207
+ .selectFrom('node as folder')
208
+ .innerJoin('node as child', 'child.parent_id', 'folder.id')
209
+ .leftJoin('content_type as type', 'type.node_id', 'child.id')
210
+ .select('type.form_key')
211
+ .where('folder.unique_id', '=', item.key)
212
+ .execute()
213
+ return rows.length > 0 && rows.every((row) => row.form_key)
214
+ }
215
+
202
216
  export function createContentTypePort(
203
217
  db: Db,
204
218
  schemaFiles?: SchemaFiles,
@@ -508,7 +522,15 @@ export function createContentTypePort(
508
522
  'renameFolder',
509
523
  'deleteFolder',
510
524
  ]),
511
- treeRoot: tree.treeRoot,
525
+ async treeRoot(paging: TreePage): Promise<Page<TreeItem>> {
526
+ const page = await tree.treeRoot(paging)
527
+ if (kind !== 'document') return page
528
+ // Forms sit beside content types in Structure, so the types made from them
529
+ // aren't shown twice. Library and the pickers read them directly.
530
+ const shown: TreeItem[] = []
531
+ for (const item of page.items) if (!(await madeFromForms(db, item))) shown.push(item)
532
+ return { total: page.total - (page.items.length - shown.length), items: shown }
533
+ },
512
534
  treeChildren: tree.treeChildren,
513
535
 
514
536
  async root(paging: SkipTake): Promise<Page<TreeItem>> {
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
11
11
  import { dirname, join } from 'node:path'
12
- import type { Principal } from '@crombolo/api-management/domain'
12
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
13
13
  import type { SchemaWorkflow } from '@crombolo/core'
14
14
  import {
15
15
  type ApprovalScheduleEntry,
@@ -51,6 +51,10 @@ export async function syncWorkflowFiles(db: Db, schemaDir: string) {
51
51
  }
52
52
 
53
53
  /** What saving a workflow would do to the requests in flight under it. */
54
+ /** Setting up workflows, which a group can be given (story 296). Deciding on a page is separate. */
55
+ const mayDesignWorkflows = (principal: Principal): boolean =>
56
+ principal.isAdmin || hasSection(principal, 'workflowSetup')
57
+
54
58
  async function changePreview(approvals: Approvals, principal: Principal, workflow: SchemaWorkflow) {
55
59
  const id = workflow.key ?? workflow.alias
56
60
  const stored = (await approvals.workflows()).find(
@@ -141,6 +145,18 @@ export async function handleApprovalsApi(
141
145
  return json(await approvals.finished(principal, skip, take))
142
146
  }
143
147
 
148
+ if (path === 'requests' && request.method === 'GET') {
149
+ const url = new URL(request.url)
150
+ const skip = Math.max(0, Number(url.searchParams.get('skip') ?? 0) || 0)
151
+ const take = Math.min(100, Math.max(1, Number(url.searchParams.get('take') ?? 25) || 25))
152
+ const flag = (name: string, otherwise: boolean) => {
153
+ const value = url.searchParams.get(name)
154
+ return value === null ? otherwise : value === 'true'
155
+ }
156
+ const include = { pending: flag('pending', true), decided: flag('decided', false) }
157
+ return json(await approvals.requests(principal, include, skip, take))
158
+ }
159
+
144
160
  // Whether Approvals and a page's Workflow tab show: a workflow, or a request still open.
145
161
  if (path === 'active' && request.method === 'GET') {
146
162
  const active =
@@ -152,8 +168,8 @@ export async function handleApprovalsApi(
152
168
  file ? folderOf(ctx.schemaDir, 'workflows', file) : ''
153
169
  const folders = /^workflows\/(tree-folders|tree-move)$/.exec(path)
154
170
  if (folders) {
155
- if (!principal.isAdmin)
156
- return json({ ok: false, message: 'Only administrators change workflows.' }, 403)
171
+ if (!mayDesignWorkflows(principal))
172
+ return json({ ok: false, message: 'You do not have access to set up workflows.' }, 403)
157
173
  const response = await folderAction('workflows', folders[1] as string, request, {
158
174
  schemaDir: ctx.schemaDir,
159
175
  writable: ctx.writable,
@@ -171,8 +187,12 @@ export async function handleApprovalsApi(
171
187
  folder: folderIn(loaded.files.get(`workflow:${s.workflow.alias}`)),
172
188
  })),
173
189
  folders: foldersIn(ctx.schemaDir, 'workflows'),
174
- readOnlyBecause: ctx.writable ? (principal.isAdmin ? null : 'permission') : 'site',
175
- editable: ctx.writable && principal.isAdmin,
190
+ readOnlyBecause: ctx.writable
191
+ ? mayDesignWorkflows(principal)
192
+ ? null
193
+ : 'permission'
194
+ : 'site',
195
+ editable: ctx.writable && mayDesignWorkflows(principal),
176
196
  groups: (await new UserGroupRepository(ctx.db).all()).map((g) => ({
177
197
  alias: g.alias,
178
198
  name: g.name,
@@ -183,8 +203,8 @@ export async function handleApprovalsApi(
183
203
 
184
204
  match = /^workflows\/([^/]+)(\/preview)?$/.exec(path)
185
205
  if (match) {
186
- if (!principal.isAdmin)
187
- return json({ ok: false, message: 'Only administrators change workflows.' }, 403)
206
+ if (!mayDesignWorkflows(principal))
207
+ return json({ ok: false, message: 'You do not have access to set up workflows.' }, 403)
188
208
  const alias = decodeURIComponent(match[1] as string)
189
209
  const here = loadSchemaDirectory(ctx.schemaDir).files.get(`workflow:${alias}`)
190
210
  const file = here ?? join(ctx.schemaDir, 'workflows', fileNameFor(alias))
package/src/approvals.ts CHANGED
@@ -203,6 +203,13 @@ export interface Approvals {
203
203
  skip: number,
204
204
  take: number,
205
205
  ): Promise<{ total: number; items: RequestView[] }>
206
+ /** One page of requests: the pending first, oldest first, then the decided, newest first. */
207
+ requests(
208
+ principal: Principal,
209
+ include: { pending: boolean; decided: boolean },
210
+ skip: number,
211
+ take: number,
212
+ ): Promise<{ total: number; items: RequestView[] }>
206
213
  }
207
214
 
208
215
  const SWEEP_GRACE_MS = 5 * 60_000
@@ -1167,6 +1174,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1167
1174
  items: await Promise.all(page.items.map((r) => view(principal, r))),
1168
1175
  }
1169
1176
  },
1177
+
1178
+ async requests(principal, include, skip, take) {
1179
+ const pending = include.pending ? await requests().open() : []
1180
+ const shown = pending.slice(skip, skip + take)
1181
+ const decidedSkip = Math.max(0, skip - pending.length)
1182
+ const decidedTake = take - shown.length
1183
+ // Asked even for none, since its total counts toward the pages.
1184
+ const decided = include.decided
1185
+ ? await requests().finished(decidedSkip, Math.max(1, decidedTake))
1186
+ : { total: 0, items: [] }
1187
+ const page = [...shown, ...(decidedTake > 0 ? decided.items : [])]
1188
+ return {
1189
+ total: pending.length + decided.total,
1190
+ items: await Promise.all(page.map((r) => view(principal, r))),
1191
+ }
1192
+ },
1170
1193
  }
1171
1194
  }
1172
1195
 
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `<backoffice>/crombolo/api/templates` (outside the contract): every component
3
+ * on disk, for a page's template picker, with the template a content type would
4
+ * name it by, where it has one. A component nothing names yet has no template
5
+ * row; registering one makes the row, as the schema sync would when a type first
6
+ * names it, and leaves the file alone.
7
+ */
8
+ import { hasSection, type Principal } from '@crombolo/api-management'
9
+ import { ComponentRepository, type Db } from '@crombolo/data'
10
+ import { listComponents } from './components.ts'
11
+
12
+ export interface ComponentTemplate {
13
+ alias: string
14
+ /** The template's key, or null for a component no template row names yet. */
15
+ id: string | null
16
+ }
17
+
18
+ /** Every component on disk and every template row, joined by alias, by alias. Pure. */
19
+ export function componentTemplates(
20
+ onDisk: readonly string[],
21
+ rows: readonly { key: string; alias: string }[],
22
+ ): ComponentTemplate[] {
23
+ const keys = new Map(rows.map((row) => [row.alias, row.key]))
24
+ const aliases = new Set([...onDisk, ...rows.map((row) => row.alias)])
25
+ return [...aliases].sort().map((alias) => ({ alias, id: keys.get(alias) ?? null }))
26
+ }
27
+
28
+ export async function handleComponentTemplates(
29
+ request: Request,
30
+ principal: Principal,
31
+ options: { db: Db; componentsDir: string },
32
+ ): Promise<Response> {
33
+ const repo = new ComponentRepository(options.db)
34
+ const onDisk = listComponents(options.componentsDir).map((file) => file.alias)
35
+
36
+ if (request.method === 'GET')
37
+ return Response.json({ items: componentTemplates(onDisk, await repo.all()) })
38
+
39
+ if (request.method === 'POST') {
40
+ // As changing which templates a type allows: Structure, which Settings brings.
41
+ if (!hasSection(principal, 'structure') && !hasSection(principal, 'settings'))
42
+ return Response.json(
43
+ { message: 'Making a component a template needs access to Structure.' },
44
+ { status: 403 },
45
+ )
46
+ const body = (await request.json().catch(() => ({}))) as { alias?: unknown }
47
+ const alias = typeof body.alias === 'string' ? body.alias : ''
48
+ if (!onDisk.includes(alias))
49
+ return Response.json({ message: 'There is no component with that name.' }, { status: 404 })
50
+ const existing = await repo.byAlias(alias)
51
+ if (existing) return Response.json({ id: existing.key })
52
+ const saved = await repo.save({ key: crypto.randomUUID(), name: alias, alias, content: null })
53
+ return Response.json({ id: saved.key }, { status: 201 })
54
+ }
55
+ return new Response('Method Not Allowed', { status: 405 })
56
+ }
package/src/config.ts CHANGED
@@ -1091,7 +1091,7 @@ export function describeDatabase(
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
- export const VERSION = '0.52.2'
1094
+ export const VERSION = '0.54.1'
1095
1095
 
1096
1096
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1097
1097
  /** A positive number from a setting, else the default. */
package/src/database.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * Migration and seeding run at startup rather than through the install wizard;
5
5
  * the wizard is story 080. Both are idempotent, so restarting is safe.
6
6
  */
7
+
7
8
  import { hashPassword, passwordConfigJson } from '@crombolo/auth'
8
9
  import {
9
10
  connect,
@@ -25,6 +26,7 @@ import {
25
26
  import { ensureApiClient } from './api-client.ts'
26
27
  import { type CromboloConfig, runsOnLocalhost } from './config.ts'
27
28
  import { migrateTables, pendingTablesSteps, type TablesChain } from './custom-tables.ts'
29
+ import { upgradeFormWords } from './form-word-upgrade.ts'
28
30
  import { logger } from './logging.ts'
29
31
  import { linkMediaFolders } from './media-folders.ts'
30
32
 
@@ -164,6 +166,13 @@ export async function installDatabase(
164
166
  await migrate(db, cromboloPlan, { by: config.nodeId })
165
167
  // Core first, so a bundle step always runs against a core it declared itself compatible with.
166
168
  await migrateTables(db, config, chains, { by: config.nodeId })
169
+ // Forms' `#key` is `{#key}` now (story 297). A shared schema store is left to
170
+ // the designer's next save, which writes it the new way.
171
+ if (config.schemaWritable && !config.schemaStore) {
172
+ const upgraded = await upgradeFormWords(db, config.schemaDir)
173
+ if (upgraded.length > 0)
174
+ logger('install').info(`Wrote dictionary words as {#key} in ${upgraded.length} form file(s)`)
175
+ }
167
176
 
168
177
  // In production a password is never made up: the pipeline supplies one, or
169
178
  // the owner sets the site up in the browser (docs/operations.md). With an API
@@ -0,0 +1,119 @@
1
+ /**
2
+ * `<backoffice>/crombolo/api/dictionary/…` (story 297): what a `{#key}` chip shows
3
+ * and changes. Anyone signed in reads the items and their words; changing them
4
+ * asks for Translation or Settings, as Umbraco's dictionary editor does. Outside
5
+ * the contract.
6
+ */
7
+ import { hasSection, type Principal } from '@crombolo/api-management'
8
+ import {
9
+ appendCacheInstruction,
10
+ type Db,
11
+ DictionaryRepository,
12
+ LanguageRepository,
13
+ } from '@crombolo/data'
14
+
15
+ export interface DictionaryWordsOptions {
16
+ db: Db
17
+ /** Tells this node's cache the dictionary changed. */
18
+ onChange?: () => void
19
+ nodeId?: string
20
+ }
21
+
22
+ /** The words of each language for the editor: every language, '' where none is set. Pure. */
23
+ export function wordsByLanguage(
24
+ languages: readonly { isoCode: string; cultureName: string; isDefault: boolean }[],
25
+ translations: readonly { isoCode: string; translation: string }[],
26
+ ): { isoCode: string; name: string; isDefault: boolean; text: string }[] {
27
+ const text = new Map(translations.map((t) => [t.isoCode.toLowerCase(), t.translation]))
28
+ return [...languages]
29
+ .sort(
30
+ (a, b) =>
31
+ Number(b.isDefault) - Number(a.isDefault) || a.cultureName.localeCompare(b.cultureName),
32
+ )
33
+ .map((l) => ({
34
+ isoCode: l.isoCode,
35
+ name: l.cultureName,
36
+ isDefault: l.isDefault,
37
+ text: text.get(l.isoCode.toLowerCase()) ?? '',
38
+ }))
39
+ }
40
+
41
+ export async function handleDictionaryWords(
42
+ request: Request,
43
+ path: string,
44
+ principal: Principal,
45
+ options: DictionaryWordsOptions,
46
+ ): Promise<Response | undefined> {
47
+ const { db } = options
48
+ const repo = new DictionaryRepository(db)
49
+ const languages = await new LanguageRepository(db).all()
50
+ const defaultIso = languages.find((l) => l.isDefault)?.isoCode.toLowerCase()
51
+
52
+ if (path === '/words' && request.method === 'GET') {
53
+ const items = await repo.all()
54
+ return Response.json({
55
+ words: items
56
+ .map((item) => ({
57
+ name: item.name,
58
+ text:
59
+ item.translations.find((t) => t.isoCode.toLowerCase() === defaultIso)?.translation ??
60
+ '',
61
+ }))
62
+ .sort((a, b) => a.name.localeCompare(b.name)),
63
+ })
64
+ }
65
+
66
+ const match = /^\/words\/([^/]+)$/.exec(path)
67
+ if (!match) return undefined
68
+ const item = await repo.byName(decodeURIComponent(match[1] as string))
69
+ if (!item) return Response.json({ message: 'No dictionary item has this name.' }, { status: 404 })
70
+ // As the Management API's dictionary: Translation, or Settings.
71
+ const mayChange = hasSection(principal, 'translation') || hasSection(principal, 'settings')
72
+
73
+ if (request.method === 'GET')
74
+ return Response.json({
75
+ name: item.name,
76
+ mayChange,
77
+ languages: wordsByLanguage(languages, item.translations),
78
+ })
79
+
80
+ if (request.method === 'PUT') {
81
+ if (!mayChange)
82
+ return Response.json(
83
+ { message: 'Changing the dictionary needs access to Translation.' },
84
+ { status: 403 },
85
+ )
86
+ const body = (await request.json().catch(() => ({}))) as { words?: unknown }
87
+ const given = body.words && typeof body.words === 'object' ? body.words : {}
88
+ const known = new Map(languages.map((l) => [l.isoCode.toLowerCase(), l.isoCode]))
89
+ const next = new Map(item.translations.map((t) => [t.isoCode.toLowerCase(), t]))
90
+ for (const [iso, text] of Object.entries(given as Record<string, unknown>)) {
91
+ const isoCode = known.get(iso.toLowerCase())
92
+ if (!isoCode || typeof text !== 'string')
93
+ return Response.json({ message: `There is no language ${iso}.` }, { status: 400 })
94
+ if (text.trim()) next.set(isoCode.toLowerCase(), { isoCode, translation: text })
95
+ else next.delete(isoCode.toLowerCase())
96
+ }
97
+ const result = await db.transaction(async (tx) => {
98
+ const done = await new DictionaryRepository(tx).update(item.key, {
99
+ name: item.name,
100
+ translations: [...next.values()],
101
+ })
102
+ if (done === 'Success')
103
+ await appendCacheInstruction(tx, {
104
+ kind: 'content',
105
+ payload: { dictionary: true },
106
+ by: options.nodeId,
107
+ })
108
+ return done
109
+ })
110
+ if (result !== 'Success') return Response.json({ message: result }, { status: 400 })
111
+ options.onChange?.()
112
+ return Response.json({
113
+ name: item.name,
114
+ mayChange,
115
+ languages: wordsByLanguage(languages, [...next.values()]),
116
+ })
117
+ }
118
+ return new Response('Method Not Allowed', { status: 405 })
119
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Forms wrote a dictionary item as a whole text of `#key` (story 293); they write
3
+ * `{#key}` now (story 297). On a site whose schema it may write, the server
4
+ * rewrites each such text that names an item, in place, so a file keeps its
5
+ * layout and comments. A `#` naming no item is only text, and is left alone.
6
+ */
7
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { type Db, DictionaryRepository } from '@crombolo/data'
10
+
11
+ /** The keys a form file holds words under: a choice's value is compared, never read. */
12
+ const WORD_KEYS = [
13
+ 'caption',
14
+ 'help-text',
15
+ 'placeholder',
16
+ 'content',
17
+ 'mandatory-message',
18
+ 'pattern-message',
19
+ 'submit-label',
20
+ 'next-label',
21
+ 'previous-label',
22
+ 'message-on-submit',
23
+ ]
24
+
25
+ /** `key = "#name"`, the whole string `#name`, in either kind of quotes. */
26
+ const BARE = new RegExp(
27
+ `^(\\s*(?:${WORD_KEYS.join('|')})\\s*=\\s*)(["'])#([^\\s"'{}]+)\\2(\\s*(?:#.*)?)$`,
28
+ 'gm',
29
+ )
30
+
31
+ /** The file's text with each word written `"#key"` that names an item as `"{#key}"`. Pure. */
32
+ export function braceFormWords(text: string, isItem: (name: string) => boolean): string {
33
+ return text.replace(BARE, (whole, start: string, quote: string, name: string, end: string) =>
34
+ isItem(name) ? `${start}${quote}{#${name}}${quote}${end}` : whole,
35
+ )
36
+ }
37
+
38
+ function tomlFiles(dir: string): string[] {
39
+ let entries: string[]
40
+ try {
41
+ entries = readdirSync(dir)
42
+ } catch {
43
+ return []
44
+ }
45
+ return entries.flatMap((name) => {
46
+ const path = join(dir, name)
47
+ if (statSync(path).isDirectory()) return tomlFiles(path)
48
+ return name.endsWith('.toml') ? [path] : []
49
+ })
50
+ }
51
+
52
+ /** Rewrites the forms under `schemaDir`; the files it changed. */
53
+ export async function upgradeFormWords(db: Db, schemaDir: string): Promise<string[]> {
54
+ const files = tomlFiles(join(schemaDir, 'forms'))
55
+ if (files.length === 0) return []
56
+ const names = new Set(
57
+ (await new DictionaryRepository(db).outline()).map((item) => item.name.toLowerCase()),
58
+ )
59
+ if (names.size === 0) return []
60
+ const changed: string[] = []
61
+ for (const file of files) {
62
+ const text = readFileSync(file, 'utf8')
63
+ const next = braceFormWords(text, (name) => names.has(name.toLowerCase()))
64
+ if (next === text) continue
65
+ writeFileSync(file, next)
66
+ changed.push(file)
67
+ }
68
+ return changed
69
+ }
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ export * from './bundle-reload.ts'
29
29
  export * from './bundle-sections.ts'
30
30
  export * from './bundles.ts'
31
31
  export * from './busy.ts'
32
+ export { componentTemplates } from './component-templates-api.ts'
32
33
  export * from './components.ts'
33
34
  export * from './config.ts'
34
35
  export * from './content-dispatch.ts'
@@ -59,6 +60,7 @@ export * from './file-intake.ts'
59
60
  export * from './form-files.ts'
60
61
  export * from './form-submit.ts'
61
62
  export * from './form-types.ts'
63
+ export { braceFormWords, upgradeFormWords } from './form-word-upgrade.ts'
62
64
  export * from './form-workflows.ts'
63
65
  export * from './forms.ts'
64
66
  export * from './git.ts'
package/src/ports.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  import type { EventSink } from '@crombolo/content'
28
28
  import {
29
29
  CORE_SECTION_ALIASES,
30
+ clientSections,
30
31
  DEFAULT_UPLOAD_SETTINGS,
31
32
  hasAccessToSensitiveData,
32
33
  isUploadAllowed,
@@ -255,7 +256,7 @@ function createCurrentUserPort(
255
256
  hasAccessToSensitiveData: hasAccessToSensitiveData(principal.groups),
256
257
  fallbackPermissions: principal.permissions,
257
258
  permissions,
258
- allowedSections: principal.allowedSections,
259
+ allowedSections: clientSections(principal),
259
260
  userGroupIds: principal.groupKeys.map((id) => ({ id })),
260
261
  }
261
262
  },
@@ -8,8 +8,9 @@
8
8
  import { createHash } from 'node:crypto'
9
9
  import { extname } from 'node:path'
10
10
  import {
11
+ bareFormWords,
12
+ bracedFormWordNames,
11
13
  type ContentTypeAggregate,
12
- formWordNames,
13
14
  IMAGE_CROPPER_EDITOR_ALIAS,
14
15
  normaliseUuid,
15
16
  ObjectTypes,
@@ -35,6 +36,7 @@ import {
35
36
  type BundleNode,
36
37
  type BundleValue,
37
38
  type ContentSet,
39
+ ELEMENT_FOLDER_TYPE,
38
40
  referenceCandidates,
39
41
  writeBundle,
40
42
  writeBundlePackage,
@@ -47,6 +49,7 @@ import { lineOf } from './lines.ts'
47
49
  import {
48
50
  DICTIONARY_FILE,
49
51
  kindDir,
52
+ nameFromSegment,
50
53
  readSeed,
51
54
  readSeedDictionary,
52
55
  type SeedFinding,
@@ -67,12 +70,6 @@ export interface SeedBuild {
67
70
  dictionary?: DictionaryEntry[]
68
71
  }
69
72
 
70
- /** A word for a file name: `about-us` → `About us`. */
71
- const nameFromSegment = (segment: string) => {
72
- const words = segment.replace(/[-_]+/g, ' ').trim()
73
- return words.charAt(0).toUpperCase() + words.slice(1)
74
- }
75
-
76
73
  const isRecord = (value: unknown): value is Record<string, unknown> =>
77
74
  typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
78
75
 
@@ -102,15 +99,26 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
102
99
  }
103
100
  }
104
101
  collect(dictionary.entries)
105
- for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? [])
106
- for (const name of formWordNames(form))
102
+ for (const form of loadSchemaDirectory(config.schemaDir).set.forms ?? []) {
103
+ const file = `schema/forms/${form.alias}.toml`
104
+ for (const name of bracedFormWordNames(form))
107
105
  if (!names.has(name.toLowerCase()))
108
106
  findings.push({
109
- file: `schema/forms/${form.alias}.toml`,
107
+ file,
110
108
  line: 1,
111
109
  code: 'unknown-dictionary-item',
112
- message: `the form "${form.alias}" names #${name}, which is not in ${DICTIONARY_FILE}`,
110
+ message: `the form "${form.alias}" names {#${name}}, which is not in ${DICTIONARY_FILE}`,
111
+ })
112
+ // Forms wrote `#key` before story 297; the server rewrites it when it starts.
113
+ for (const name of bareFormWords(form))
114
+ if (names.has(name.toLowerCase()))
115
+ findings.push({
116
+ file,
117
+ line: 1,
118
+ code: 'bare-dictionary-word',
119
+ message: `the form "${form.alias}" writes #${name}; write it as {#${name}}`,
113
120
  })
121
+ }
114
122
  }
115
123
 
116
124
  const state = await currentSchemaState(db)
@@ -214,16 +222,42 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
214
222
  }
215
223
  const libraryKey = async (ref: string, why: string) => {
216
224
  const seeded = libraryByPath.get(trimPath(ref))
217
- if (seeded) return keyOf.get(seeded)
225
+ if (seeded) return seeded.folder ? undefined : keyOf.get(seeded)
218
226
  if (looksLikeKey(ref)) return normaliseUuid(ref)
219
227
  return siteNode(ref, ObjectTypes.Element, why)
220
228
  }
229
+ const forms = loadSchemaDirectory(config.schemaDir).set.forms ?? []
230
+ /** A Library form by its path, else a form by its alias: what a form picker stores. */
231
+ const formKey = async (ref: string, why: string) => {
232
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
233
+ const seeded = libraryByPath.get(trimPath(ref))
234
+ if (seeded && !seeded.folder) {
235
+ const type =
236
+ typeof seeded.data.type === 'string'
237
+ ? await typeOf(documentTypes, seeded.data.type)
238
+ : undefined
239
+ return type?.formKey ? keyOf.get(seeded) : undefined
240
+ }
241
+ const form = forms.find((f) => f.alias.toLowerCase() === trimPath(ref))
242
+ if (form) return form.key ?? form.alias
243
+ const key = await siteNode(ref, ObjectTypes.Element, why)
244
+ if (!key) return undefined
245
+ const rows = await db.q
246
+ .selectFrom('node as n')
247
+ .innerJoin('content as c', 'c.node_id', 'n.id')
248
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
249
+ .select('ct.form_key')
250
+ .where('n.unique_id', '=', key)
251
+ .execute()
252
+ return rows[0]?.form_key ? key : undefined
253
+ }
221
254
 
222
255
  // ---------------------------------------------------------------- values
223
256
  const { convert } = valueWriter(lookup, {
224
257
  content: contentKey,
225
258
  media: mediaRef,
226
259
  library: libraryKey,
260
+ form: formKey,
227
261
  linkedMedia: async (path) => {
228
262
  const media = mediaByPath.get(path.toLowerCase())
229
263
  return media ? keyOf.get(media) : undefined
@@ -292,6 +326,29 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
292
326
  for (const item of tree.items) {
293
327
  const key = keyOf.get(item) as string
294
328
  let type = typeOfItem.get(item)
329
+ if (item.kind === 'library' && item.folder) {
330
+ // A Library folder: a name and a place, as story 283 carries it.
331
+ bundleNodes.push({
332
+ key,
333
+ kind: 'element-folder',
334
+ contentType: { ...ELEMENT_FOLDER_TYPE },
335
+ parent: item.parent
336
+ ? (keyOf.get(libraryByPath.get(item.parent.toLowerCase()) as SeedItem) ?? null)
337
+ : null,
338
+ sortOrder: 0,
339
+ template: null,
340
+ variants: [
341
+ {
342
+ culture: null,
343
+ segment: null,
344
+ name: nameOf(item)[0]?.name ?? item.path,
345
+ published: false,
346
+ },
347
+ ],
348
+ values: [],
349
+ })
350
+ continue
351
+ }
295
352
  if (item.kind !== 'media') {
296
353
  if (typeof item.data.type !== 'string') {
297
354
  find(item, [], 'no-type', 'an item names its content type: type = "<alias>"')
@@ -444,14 +501,16 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
444
501
  if (template) usedComponents.add(template)
445
502
  // Media has no published state: it is live as soon as it lands.
446
503
  const published = item.kind !== 'media' && item.data.published !== false
447
- const parent =
448
- item.kind === 'library' || !item.parent
449
- ? null
450
- : (keyOf.get(
451
- (item.kind === 'media' ? mediaByPath : contentByPath).get(
452
- item.parent.toLowerCase(),
453
- ) as SeedItem,
454
- ) ?? null)
504
+ const parent = !item.parent
505
+ ? null
506
+ : (keyOf.get(
507
+ (item.kind === 'media'
508
+ ? mediaByPath
509
+ : item.kind === 'library'
510
+ ? libraryByPath
511
+ : contentByPath
512
+ ).get(item.parent.toLowerCase()) as SeedItem,
513
+ ) ?? null)
455
514
  const names = nameOf(item)
456
515
  // A renamed file is a new key: say so where a page of that name is already here.
457
516
  if (item.kind === 'content') {
@@ -22,7 +22,14 @@ import {
22
22
  } from '@crombolo/data'
23
23
  import type { MediaFileStore } from '../media-files.ts'
24
24
  import { seedKey } from './keys.ts'
25
- import { CONTENT_FILES_DIR, KIND_DIRS, kindDir, type SeedKind } from './read.ts'
25
+ import {
26
+ CONTENT_FILES_DIR,
27
+ KIND_DIRS,
28
+ kindDir,
29
+ LIBRARY_FOLDER_FILE,
30
+ nameFromSegment,
31
+ type SeedKind,
32
+ } from './read.ts'
26
33
  import { schemaLookup, shorthandReader } from './values.ts'
27
34
 
28
35
  /** A URL segment from a name: `About us` → `about-us`. */
@@ -150,10 +157,31 @@ export async function exportSeed(
150
157
  }
151
158
  for (const [index, root] of options.pages.entries()) await walkPages(root, null, index)
152
159
 
160
+ /** Library folders, which are directories rather than files (story 242). */
161
+ const libraryFolders = new Set<string>()
153
162
  if (options.library) {
154
- const roots = await nodes.children(-1, ObjectTypes.Element, 0, Number.MAX_SAFE_INTEGER)
155
- for (const [index, element] of roots.items.entries())
156
- place('library', element, null, index, segmentOf(element.text ?? element.key))
163
+ const walkLibrary = async (parentId: number, parent: string | null) => {
164
+ const folders = await nodes.children(
165
+ parentId,
166
+ ObjectTypes.ElementContainer,
167
+ 0,
168
+ Number.MAX_SAFE_INTEGER,
169
+ )
170
+ for (const [index, folder] of folders.items.entries()) {
171
+ libraryFolders.add(folder.key)
172
+ const path = place('library', folder, parent, index, segmentOf(folder.text ?? folder.key))
173
+ await walkLibrary(folder.id, path)
174
+ }
175
+ const elements = await nodes.children(
176
+ parentId,
177
+ ObjectTypes.Element,
178
+ 0,
179
+ Number.MAX_SAFE_INTEGER,
180
+ )
181
+ for (const [index, element] of elements.items.entries())
182
+ place('library', element, parent, index, segmentOf(element.text ?? element.key))
183
+ }
184
+ await walkLibrary(-1, null)
157
185
  }
158
186
 
159
187
  const mediaFile = new Map<string, string>()
@@ -237,8 +265,19 @@ export async function exportSeed(
237
265
  }
238
266
 
239
267
  for (const { kind, node, path, order } of entries) {
240
- const doc = await repos[kind].byKey(node.key)
241
268
  const derived = seedKey(`${kind}/${path}`)
269
+ if (kind === 'library' && libraryFolders.has(node.key)) {
270
+ // A folder is its directory; `.folder.toml` only for what the directory can't say.
271
+ mkdirSync(under(`library/${path}`), { recursive: true })
272
+ const own: string[] = []
273
+ if (normaliseUuid(node.key) !== derived) own.push(`key = ${JSON.stringify(node.key)}`)
274
+ const segment = path.split('/').at(-1) as string
275
+ if ((node.text ?? '') !== nameFromSegment(segment))
276
+ own.push(`name = ${JSON.stringify(node.text ?? '')}`)
277
+ if (own.length > 0) write(`library/${path}/${LIBRARY_FOLDER_FILE}`, `${own.join('\n')}\n`)
278
+ continue
279
+ }
280
+ const doc = await repos[kind].byKey(node.key)
242
281
  const lines: string[] = []
243
282
  if (kind === 'media') {
244
283
  const src = mediaFile.get(node.key)
package/src/seed/read.ts CHANGED
@@ -40,7 +40,7 @@ export interface SeedItem {
40
40
  data: Record<string, unknown>
41
41
  /** A media file's bytes. */
42
42
  bytes?: Uint8Array
43
- /** A media folder: a directory under `content/media/`. */
43
+ /** A folder: a directory under `content/media/` or `content/library/`. */
44
44
  folder?: boolean
45
45
  }
46
46
 
@@ -58,6 +58,9 @@ export interface SeedTree {
58
58
 
59
59
  const SKIPPED = (name: string) => name.startsWith('.')
60
60
 
61
+ /** What keeps a Library folder's key, when it isn't the one its path gives. */
62
+ export const LIBRARY_FOLDER_FILE = '.folder.toml'
63
+
61
64
  /**
62
65
  * The line a TOML syntax error is on: the first prefix of the file that does
63
66
  * not parse. The parser's own position is not always the file's.
@@ -118,12 +121,20 @@ export function readSeed(siteDir: string): SeedTree {
118
121
  const path = join(dir, name)
119
122
  if (statSync(path).isDirectory()) {
120
123
  if (kind === 'library') {
121
- findings.push({
122
- file: shown(path),
123
- line: 1,
124
- code: 'library-folder',
125
- message: 'Library elements sit at the top of content/library: folders are not read yet',
124
+ // A Library folder (story 242). `.folder.toml` in it keeps a key of its own.
125
+ const itemPath = parent ? `${parent}/${name}` : name
126
+ const own = join(path, LIBRARY_FOLDER_FILE)
127
+ const parsed = existsSync(own) ? parse(own) : undefined
128
+ items.push({
129
+ kind,
130
+ path: itemPath,
131
+ parent,
132
+ file: parsed ? shown(own) : null,
133
+ text: parsed?.text ?? '',
134
+ data: parsed?.data ?? {},
135
+ folder: true,
126
136
  })
137
+ content(kind, path, itemPath)
127
138
  continue
128
139
  }
129
140
  if (!names.includes(`${name}.toml`))
@@ -216,3 +227,9 @@ export function readSeedDictionary(siteDir: string) {
216
227
  /** Whether a site has content files at all, where they are or where they were. */
217
228
  export const hasSeed = (siteDir: string) =>
218
229
  existsSync(join(siteDir, CONTENT_FILES_DIR)) || existsSync(join(siteDir, 'seed'))
230
+
231
+ /** A word for a file name: `about-us` → `About us`. */
232
+ export const nameFromSegment = (segment: string) => {
233
+ const words = segment.replace(/[-_]+/g, ' ').trim()
234
+ return words.charAt(0).toUpperCase() + words.slice(1)
235
+ }
@@ -82,6 +82,8 @@ export interface ValueRefs {
82
82
  content(ref: string, why: string): Promise<string | undefined>
83
83
  media(ref: string, why: string): Promise<{ key: string; typeAlias: string } | undefined>
84
84
  library(ref: string, why: string): Promise<string | undefined>
85
+ /** A form picker's value: a Library form's path, or a form's alias or key (story 242). */
86
+ form(ref: string, why: string): Promise<string | undefined>
85
87
  /** A link's path as media, before it is tried as a page. */
86
88
  linkedMedia(ref: string): Promise<string | undefined>
87
89
  }
@@ -296,6 +298,16 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
296
298
  }
297
299
  return { ok: true, value: keys }
298
300
  }
301
+ case 'Crombolo.FormPicker': {
302
+ if (typeof raw !== 'string')
303
+ return fail("a form picker takes a Library form's path, or a form's alias")
304
+ const key = await refs.form(raw, why)
305
+ if (!key)
306
+ return fail(
307
+ `"${raw}" is not a Library form or a form, in the content files or on the site`,
308
+ )
309
+ return { ok: true, value: key }
310
+ }
299
311
  case 'Umbraco.MultiUrlPicker': {
300
312
  const links: unknown[] = []
301
313
  for (const entry of list(raw)) {
@@ -404,6 +416,10 @@ export function shorthandReader(
404
416
  if (paths.length === 0 || paths.some((p) => p === undefined)) return value
405
417
  return paths.length === 1 ? paths[0] : paths
406
418
  }
419
+ case 'Crombolo.FormPicker': {
420
+ if (typeof value !== 'string') return value
421
+ return (await where(value, 'library')) ?? value
422
+ }
407
423
  case 'Umbraco.MultiUrlPicker': {
408
424
  if (!Array.isArray(value)) return value
409
425
  const out: unknown[] = []
package/src/server.ts CHANGED
@@ -170,6 +170,7 @@ import { CommandError, installBundleContent } from './bundle-install.ts'
170
170
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
171
171
  import { bundleRouteGroups } from './bundles.ts'
172
172
  import { busyResponse } from './busy.ts'
173
+ import { handleComponentTemplates } from './component-templates-api.ts'
173
174
  import { checkTypes, listEmailTemplates } from './components.ts'
174
175
  import {
175
176
  type CromboloConfig,
@@ -184,6 +185,7 @@ import { closeTables, tablesReport } from './custom-tables.ts'
184
185
  import { folderAction, folderOf, foldersIn } from './definition-folders.ts'
185
186
  import { createDeliveryMediaPort } from './delivery-media.ts'
186
187
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
188
+ import { handleDictionaryWords } from './dictionary-words-api.ts'
187
189
  import { syncDomainsFile } from './domains.ts'
188
190
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
189
191
  import { emailAvailability } from './email.ts'
@@ -1927,6 +1929,29 @@ export async function createServer(
1927
1929
  if (response) return response
1928
1930
  }
1929
1931
 
1932
+ // Non-contract, signed-in: every component, for a page's template picker.
1933
+ if (pathname === `${paths.pluginPath}/api/templates`) {
1934
+ const principal = await authenticate(request)
1935
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1936
+ return handleComponentTemplates(request, principal, {
1937
+ db,
1938
+ componentsDir: config.componentsDir,
1939
+ })
1940
+ }
1941
+
1942
+ // Non-contract, signed-in: a dictionary item's words, for a `{#key}` chip (story 297).
1943
+ if (pathname.startsWith(`${paths.pluginPath}/api/dictionary/`)) {
1944
+ const principal = await authenticate(request)
1945
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1946
+ const response = await handleDictionaryWords(
1947
+ request,
1948
+ pathname.slice(`${paths.pluginPath}/api/dictionary`.length),
1949
+ principal,
1950
+ { db, onChange: () => cache.invalidate(), nodeId: schema.nodeId },
1951
+ )
1952
+ if (response) return response
1953
+ }
1954
+
1930
1955
  // Non-contract, signed-in: import the schema files into this database. A GET
1931
1956
  // asks what would happen and changes nothing; a POST applies it. Never
1932
1957
  // automatic — see `importSchema`.