@crombolo/schema 0.28.0 → 0.29.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/schema",
3
- "version": "0.28.0",
3
+ "version": "0.29.1",
4
4
  "description": "Schema-as-code for crombolo: TOML document, media and member type definitions.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.28.0",
32
- "@crombolo/data": "0.28.0"
31
+ "@crombolo/core": "0.29.1",
32
+ "@crombolo/data": "0.29.1"
33
33
  }
34
34
  }
package/src/blocks.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Block editors' blocks as `[[data-type.block]]` tables (story 161): each
3
+ * names its element and settings types by alias, with its label, size, group
4
+ * and, in a grid, its spans and areas. Sync compiles them into the config the
5
+ * back office reads — `blocks`, and `blockGroups` for named groups — and export
6
+ * turns that config back into tables when every block can be said as one.
7
+ * Group and area keys are derived, so every node computes the same ones.
8
+ */
9
+ import { derivedKey } from '@crombolo/core'
10
+ import type { ConfigReferenceProblem } from './config-references.ts'
11
+ import type { SchemaBlock, SchemaBlockAllowance, SchemaBlockArea } from './model.ts'
12
+
13
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
14
+ typeof value === 'object' && value !== null && !Array.isArray(value)
15
+
16
+ const defined = <T extends Record<string, unknown>>(record: T): Partial<T> =>
17
+ Object.fromEntries(
18
+ Object.entries(record).filter(([, value]) => value !== undefined),
19
+ ) as Partial<T>
20
+
21
+ /**
22
+ * The editor config the tables stand for. `lookup` answers an element type's
23
+ * key by alias; an alias it cannot answer is reported and left out.
24
+ */
25
+ export function compileBlocks(
26
+ dataTypeKey: string,
27
+ blocks: readonly SchemaBlock[],
28
+ lookup: (alias: string) => string | undefined,
29
+ ): { config: Record<string, unknown>; problems: ConfigReferenceProblem[] } {
30
+ const problems: ConfigReferenceProblem[] = []
31
+ const element = (alias: string, path: string): string | undefined => {
32
+ const key = lookup(alias)
33
+ if (!key) problems.push({ path, alias, kind: 'element' })
34
+ return key
35
+ }
36
+ const groupNames = [...new Set(blocks.flatMap((b) => (b.group ? [b.group] : [])))]
37
+ const groupKey = (name: string) => derivedKey(dataTypeKey, 'group', name)
38
+ const allowance = (entry: SchemaBlockAllowance, path: string) =>
39
+ defined({
40
+ elementTypeKey: entry.element ? element(entry.element, path) : undefined,
41
+ groupKey: entry.group ? groupKey(entry.group) : undefined,
42
+ minAllowed: entry.min,
43
+ maxAllowed: entry.max,
44
+ })
45
+ const area = (owner: string, a: SchemaBlockArea, path: string) =>
46
+ defined({
47
+ key: derivedKey(dataTypeKey, owner, a.alias),
48
+ alias: a.alias,
49
+ columnSpan: a.columnSpan,
50
+ rowSpan: a.rowSpan,
51
+ createLabel: a.createLabel,
52
+ minAllowed: a.min,
53
+ maxAllowed: a.max,
54
+ specifiedAllowance: a.allow?.map((entry, index) =>
55
+ allowance(entry, `${path}.allow[${index}]`),
56
+ ),
57
+ })
58
+ const compiled = blocks.map((b, index) => {
59
+ const path = `block[${index}]`
60
+ return defined({
61
+ contentElementTypeKey: element(b.element, `${path}.element`),
62
+ settingsElementTypeKey: b.settings ? element(b.settings, `${path}.settings`) : undefined,
63
+ label: b.label,
64
+ editorSize: b.size,
65
+ backgroundColor: b.background,
66
+ iconColor: b.iconColor,
67
+ thumbnail: b.thumbnail,
68
+ groupKey: b.group ? groupKey(b.group) : undefined,
69
+ allowAtRoot: b.allowAtRoot,
70
+ allowInAreas: b.allowInAreas,
71
+ columnSpanOptions: b.columnSpans?.map((columnSpan) => ({ columnSpan })),
72
+ rowMinSpan: b.rowSpan?.min,
73
+ rowMaxSpan: b.rowSpan?.max,
74
+ areaGridColumns: b.areaColumns,
75
+ areas: b.areas?.map((a, i) => area(b.element, a, `${path}.area[${i}]`)),
76
+ })
77
+ })
78
+ const config: Record<string, unknown> = { blocks: compiled }
79
+ if (groupNames.length > 0)
80
+ config.blockGroups = groupNames.map((name) => ({ key: groupKey(name), name }))
81
+ return { config, problems }
82
+ }
83
+
84
+ const BLOCK_FIELDS = new Set([
85
+ 'contentElementTypeKey',
86
+ 'settingsElementTypeKey',
87
+ 'label',
88
+ 'editorSize',
89
+ 'backgroundColor',
90
+ 'iconColor',
91
+ 'thumbnail',
92
+ 'groupKey',
93
+ 'allowAtRoot',
94
+ 'allowInAreas',
95
+ 'columnSpanOptions',
96
+ 'rowMinSpan',
97
+ 'rowMaxSpan',
98
+ 'areaGridColumns',
99
+ 'areas',
100
+ ])
101
+ const AREA_FIELDS = new Set([
102
+ 'key',
103
+ 'alias',
104
+ 'columnSpan',
105
+ 'rowSpan',
106
+ 'createLabel',
107
+ 'minAllowed',
108
+ 'maxAllowed',
109
+ 'specifiedAllowance',
110
+ ])
111
+
112
+ const str = (value: unknown) => (typeof value === 'string' && value ? value : undefined)
113
+ const num = (value: unknown) => (typeof value === 'number' ? value : undefined)
114
+ const bool = (value: unknown) => (typeof value === 'boolean' ? value : undefined)
115
+
116
+ /**
117
+ * Tables from an editor's config, or undefined when a block uses something a
118
+ * table cannot say, so the raw config is kept rather than half-translated.
119
+ * `reverse` answers a type's alias by key.
120
+ */
121
+ export function decompileBlocks(
122
+ config: Record<string, unknown>,
123
+ reverse: (key: string) => string | undefined,
124
+ ): SchemaBlock[] | undefined {
125
+ if (!Array.isArray(config.blocks) || config.blocks.length === 0) return undefined
126
+ const groups = new Map(
127
+ (Array.isArray(config.blockGroups) ? config.blockGroups : [])
128
+ .filter(isRecord)
129
+ .map((g) => [String(g.key).toLowerCase(), String(g.name)]),
130
+ )
131
+ const groupOf = (key: unknown) =>
132
+ typeof key === 'string' ? groups.get(key.toLowerCase()) : undefined
133
+ const aliasOf = (key: unknown) => (typeof key === 'string' ? reverse(key) : undefined)
134
+ const out: SchemaBlock[] = []
135
+ for (const raw of config.blocks) {
136
+ if (!isRecord(raw) || Object.keys(raw).some((field) => !BLOCK_FIELDS.has(field)))
137
+ return undefined
138
+ const element = aliasOf(raw.contentElementTypeKey)
139
+ if (!element) return undefined
140
+ const settings = raw.settingsElementTypeKey ? aliasOf(raw.settingsElementTypeKey) : undefined
141
+ if (raw.settingsElementTypeKey && !settings) return undefined
142
+ if (raw.groupKey && !groupOf(raw.groupKey)) return undefined
143
+ const areas: SchemaBlockArea[] = []
144
+ for (const a of Array.isArray(raw.areas) ? raw.areas : []) {
145
+ if (!isRecord(a) || Object.keys(a).some((field) => !AREA_FIELDS.has(field))) return undefined
146
+ const allow: SchemaBlockAllowance[] = []
147
+ for (const s of Array.isArray(a.specifiedAllowance) ? a.specifiedAllowance : []) {
148
+ if (!isRecord(s)) return undefined
149
+ const entry: SchemaBlockAllowance = defined({
150
+ element: s.elementTypeKey ? aliasOf(s.elementTypeKey) : undefined,
151
+ group: s.groupKey ? groupOf(s.groupKey) : undefined,
152
+ min: num(s.minAllowed),
153
+ max: num(s.maxAllowed),
154
+ })
155
+ if (!entry.element && !entry.group) return undefined
156
+ allow.push(entry)
157
+ }
158
+ areas.push(
159
+ defined({
160
+ alias: String(a.alias ?? ''),
161
+ columnSpan: num(a.columnSpan),
162
+ rowSpan: num(a.rowSpan),
163
+ createLabel: str(a.createLabel),
164
+ min: num(a.minAllowed),
165
+ max: num(a.maxAllowed),
166
+ allow: allow.length > 0 ? allow : undefined,
167
+ }) as SchemaBlockArea,
168
+ )
169
+ }
170
+ const spans = Array.isArray(raw.columnSpanOptions)
171
+ ? raw.columnSpanOptions.flatMap((o) =>
172
+ isRecord(o) && typeof o.columnSpan === 'number' ? [o.columnSpan] : [],
173
+ )
174
+ : undefined
175
+ out.push(
176
+ defined({
177
+ element,
178
+ settings,
179
+ label: str(raw.label),
180
+ size: str(raw.editorSize),
181
+ background: str(raw.backgroundColor),
182
+ iconColor: str(raw.iconColor),
183
+ thumbnail: str(raw.thumbnail),
184
+ group: groupOf(raw.groupKey),
185
+ allowAtRoot: bool(raw.allowAtRoot),
186
+ allowInAreas: bool(raw.allowInAreas),
187
+ columnSpans: spans && spans.length > 0 ? spans : undefined,
188
+ rowSpan:
189
+ num(raw.rowMinSpan) !== undefined || num(raw.rowMaxSpan) !== undefined
190
+ ? defined({ min: num(raw.rowMinSpan), max: num(raw.rowMaxSpan) })
191
+ : undefined,
192
+ areaColumns: num(raw.areaGridColumns),
193
+ areas: areas.length > 0 ? areas : undefined,
194
+ }) as SchemaBlock,
195
+ )
196
+ }
197
+ return out
198
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Which data-type config fields name types, and how (story 161). A file names a
3
+ * type by alias wherever an editor's config takes a key; sync resolves the
4
+ * alias to the key in the shape the editor reads (a comma-separated string
5
+ * where it expects one), and export writes keys back as aliases. A value shaped
6
+ * like a uuid is a key already and passes through either way.
7
+ */
8
+ import type { SchemaTypeKind } from './model.ts'
9
+
10
+ /** What a reference must name: an element type, or a type of one kind. */
11
+ export type ReferenceKind = 'element' | SchemaTypeKind
12
+
13
+ interface FieldReference {
14
+ /** The path into the config; `*` steps into every item of an array. */
15
+ path: readonly string[]
16
+ /** One alias, or a list (written as a comma-separated string). */
17
+ many: boolean
18
+ /** What it names; `startNode` reads the kind from the picker's start node type. */
19
+ kind: ReferenceKind | 'startNode'
20
+ }
21
+
22
+ const BLOCK_FIELDS: readonly FieldReference[] = [
23
+ { path: ['blocks', '*', 'contentElementTypeKey'], many: false, kind: 'element' },
24
+ { path: ['blocks', '*', 'settingsElementTypeKey'], many: false, kind: 'element' },
25
+ ]
26
+
27
+ export const CONFIG_REFERENCES: Readonly<Record<string, readonly FieldReference[]>> = {
28
+ 'Umbraco.ElementPicker': [{ path: ['allowedContentTypes'], many: true, kind: 'element' }],
29
+ 'Umbraco.MediaPicker3': [{ path: ['filter'], many: true, kind: 'media' }],
30
+ 'Umbraco.MultiNodeTreePicker': [{ path: ['filter'], many: true, kind: 'startNode' }],
31
+ 'Umbraco.BlockList': BLOCK_FIELDS,
32
+ 'Umbraco.RichText': BLOCK_FIELDS,
33
+ 'Umbraco.BlockGrid': [
34
+ ...BLOCK_FIELDS,
35
+ {
36
+ path: ['blocks', '*', 'areas', '*', 'specifiedAllowance', '*', 'elementTypeKey'],
37
+ many: false,
38
+ kind: 'element',
39
+ },
40
+ ],
41
+ }
42
+
43
+ const UUID = /^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i
44
+ export const looksLikeKey = (value: string): boolean => UUID.test(value.trim())
45
+
46
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
47
+ typeof value === 'object' && value !== null && !Array.isArray(value)
48
+
49
+ /** The kind a tree picker's `filter` names, from its start node's type. */
50
+ function startNodeKind(config: Record<string, unknown>): ReferenceKind {
51
+ const type = isRecord(config.startNode) ? String(config.startNode.type ?? '') : ''
52
+ return type === 'media' ? 'media' : type === 'member' ? 'member' : 'document'
53
+ }
54
+
55
+ /** One unresolvable reference, for `types check` to name. */
56
+ export interface ConfigReferenceProblem {
57
+ path: string
58
+ alias: string
59
+ kind: ReferenceKind
60
+ }
61
+
62
+ /** The items of a many-valued field, from a list or a comma-separated string. */
63
+ const itemsOf = (value: unknown): string[] =>
64
+ Array.isArray(value)
65
+ ? value.map(String)
66
+ : typeof value === 'string'
67
+ ? value
68
+ .split(',')
69
+ .map((part) => part.trim())
70
+ .filter(Boolean)
71
+ : []
72
+
73
+ /**
74
+ * Walks every reference field in a config and replaces each value with what
75
+ * `map` makes of it, returning a copy. `map` answers undefined to leave a
76
+ * value as it is.
77
+ */
78
+ function mapReferences(
79
+ editor: string,
80
+ config: Record<string, unknown>,
81
+ map: (value: string, kind: ReferenceKind, path: string) => string | undefined,
82
+ write: (items: string[]) => unknown,
83
+ ): Record<string, unknown> {
84
+ const fields = CONFIG_REFERENCES[editor]
85
+ if (!fields) return config
86
+ const copy = structuredClone(config)
87
+ for (const field of fields) {
88
+ const kind = field.kind === 'startNode' ? startNodeKind(config) : field.kind
89
+ const visit = (node: unknown, rest: readonly string[], at: string): unknown => {
90
+ if (rest.length === 0) {
91
+ if (field.many) {
92
+ const items = itemsOf(node)
93
+ if (items.length === 0) return node
94
+ const mapped = items.map((item) => map(item, kind, at))
95
+ // Nothing to change: left exactly as written, list or string.
96
+ if (mapped.every((value) => value === undefined)) return node
97
+ return write(items.map((item, index) => mapped[index] ?? item))
98
+ }
99
+ return typeof node === 'string' ? (map(node, kind, at) ?? node) : node
100
+ }
101
+ const [step, ...tail] = rest as [string, ...string[]]
102
+ if (step === '*') {
103
+ if (!Array.isArray(node)) return node
104
+ return node.map((item, index) => visit(item, tail, `${at}[${index}]`))
105
+ }
106
+ if (!isRecord(node) || !(step in node)) return node
107
+ node[step] = visit(node[step], tail, at ? `${at}.${step}` : step)
108
+ return node
109
+ }
110
+ visit(copy, field.path, '')
111
+ }
112
+ return copy
113
+ }
114
+
115
+ /**
116
+ * Aliases to keys, in the editor's own shape (story 161). `lookup` answers the
117
+ * key of a type of that kind; what it cannot answer is reported, and left as
118
+ * written.
119
+ */
120
+ export function resolveConfig(
121
+ editor: string,
122
+ config: Record<string, unknown>,
123
+ lookup: (alias: string, kind: ReferenceKind) => string | undefined,
124
+ ): { config: Record<string, unknown>; problems: ConfigReferenceProblem[] } {
125
+ const problems: ConfigReferenceProblem[] = []
126
+ const resolved = mapReferences(
127
+ editor,
128
+ config,
129
+ (value, kind, path) => {
130
+ if (looksLikeKey(value)) return undefined
131
+ const key = lookup(value, kind)
132
+ if (!key) problems.push({ path, alias: value, kind })
133
+ return key
134
+ },
135
+ (items) => items.join(','),
136
+ )
137
+ return { config: resolved, problems }
138
+ }
139
+
140
+ /** Keys to aliases, as a file writes them: lists as lists. A key with no alias stays a key. */
141
+ export function aliasConfig(
142
+ editor: string,
143
+ config: Record<string, unknown>,
144
+ reverse: (key: string) => string | undefined,
145
+ ): Record<string, unknown> {
146
+ return mapReferences(
147
+ editor,
148
+ config,
149
+ (value) => (looksLikeKey(value) ? reverse(value) : undefined),
150
+ (items) => items,
151
+ )
152
+ }
package/src/export.ts CHANGED
@@ -22,7 +22,9 @@ import {
22
22
  SYSTEM_CONTENT_TYPES,
23
23
  SYSTEM_MEDIA_TYPES,
24
24
  } from '@crombolo/data'
25
+ import { decompileBlocks } from './blocks.ts'
25
26
  import { BUILTIN_DATA_TYPES, builtInContentTypeSchema, builtInMediaTypeSchema } from './builtin.ts'
27
+ import { aliasConfig } from './config-references.ts'
26
28
  import type { LoadedSchema } from './load.ts'
27
29
  import type {
28
30
  SchemaContentType,
@@ -157,15 +159,35 @@ export function toSchemaContentType(
157
159
  return type
158
160
  }
159
161
 
160
- export function toSchemaDataType(model: DataTypeModel, alias: string): SchemaDataType {
162
+ /**
163
+ * A data type as a file says it. With `typeAliasOf`, the types its config names
164
+ * are written by alias and its blocks as `[[data-type.block]]` tables, where
165
+ * every block can be said as one (story 161).
166
+ */
167
+ export function toSchemaDataType(
168
+ model: DataTypeModel,
169
+ alias: string,
170
+ typeAliasOf?: (key: string) => string | undefined,
171
+ ): SchemaDataType {
172
+ let config: Record<string, unknown> = Object.fromEntries(
173
+ model.values.map((v) => [v.alias, v.value]),
174
+ )
161
175
  const dataType: SchemaDataType = {
162
176
  key: model.key,
163
177
  alias,
164
178
  name: model.name,
165
179
  editor: model.editorAlias,
166
- config: Object.fromEntries(model.values.map((v) => [v.alias, v.value])),
180
+ config,
167
181
  }
168
182
  if (model.editorUiAlias) dataType.editorUi = model.editorUiAlias
183
+ if (!typeAliasOf) return dataType
184
+ const blocks = decompileBlocks(config, typeAliasOf)
185
+ if (blocks) {
186
+ const { blocks: _blocks, blockGroups: _groups, ...rest } = config
187
+ config = rest
188
+ dataType.blocks = blocks
189
+ }
190
+ dataType.config = aliasConfig(model.editorAlias, config, typeAliasOf)
169
191
  return dataType
170
192
  }
171
193
 
@@ -213,6 +235,14 @@ export async function exportSchemaSet(db: Db, version: string): Promise<SchemaSe
213
235
  const aggregates = await liveTypes(types)
214
236
  const mediaAggregates = await liveTypes(mediaTypeRepo)
215
237
  const memberAggregates = await liveTypes(new ContentTypeRepository(db, { kind: 'member' }))
238
+ // Every type by key, so a data type's config names it by alias (story 161).
239
+ const typeAliasByKey = new Map(
240
+ [...aggregates, ...mediaAggregates, ...memberAggregates].map((a) => [
241
+ a.key.toLowerCase(),
242
+ a.alias,
243
+ ]),
244
+ )
245
+ const typeAliasOf = (key: string) => typeAliasByKey.get(key.toLowerCase())
216
246
 
217
247
  const dataTypeRows = await db.query<{ unique_id: string }>(
218
248
  'SELECT n.unique_id FROM data_type d JOIN node n ON n.id = d.node_id ORDER BY n.text',
@@ -232,8 +262,9 @@ export async function exportSchemaSet(db: Db, version: string): Promise<SchemaSe
232
262
  }
233
263
  taken.add(alias)
234
264
  dataTypeAliasByKey.set(model.key, alias)
235
- const dataType = toSchemaDataType(model, alias)
236
- if (!isUnchangedBuiltin(dataType)) exportedDataTypes.push(dataType)
265
+ // A built-in is compared as stored, before its config is written by alias.
266
+ if (!isUnchangedBuiltin(toSchemaDataType(model, alias)))
267
+ exportedDataTypes.push(toSchemaDataType(model, alias, typeAliasOf))
237
268
  }
238
269
 
239
270
  const templateAliasByKey = new Map<string, string>()
@@ -8,7 +8,13 @@
8
8
  */
9
9
  import { BUILT_IN_MEDIA_TYPES } from '@crombolo/data'
10
10
  import { storageTypeFor } from './builtin.ts'
11
- import { blockElements, dataTypeOf, effectiveProperties, pascal } from './generate.ts'
11
+ import {
12
+ blockElements,
13
+ contentTypeAliasOf,
14
+ dataTypeOf,
15
+ effectiveProperties,
16
+ pascal,
17
+ } from './generate.ts'
12
18
  import type { SchemaContentType, SchemaSet } from './model.ts'
13
19
 
14
20
  export interface DeliveryTypesOptions {
@@ -24,12 +30,12 @@ const key = (alias: string) => (/^[A-Za-z_$][\w$]*$/.test(alias) ? alias : `'${a
24
30
 
25
31
  const byAlias = (a: { alias: string }, b: { alias: string }) => a.alias.localeCompare(b.alias)
26
32
 
27
- const keyAliases = (set: SchemaSet, keys: string): string[] =>
28
- keys
29
- .split(',')
30
- .map((key) => key.trim().toLowerCase())
33
+ /** Types a config names, by key or alias, as a list or a comma-separated string (story 161). */
34
+ const keyAliases = (set: SchemaSet, keys: unknown): string[] =>
35
+ (Array.isArray(keys) ? keys.map(String) : typeof keys === 'string' ? keys.split(',') : [])
36
+ .map((key) => key.trim())
31
37
  .filter(Boolean)
32
- .flatMap((key) => set.contentTypes.find((t) => t.key?.toLowerCase() === key)?.alias ?? [])
38
+ .flatMap((key) => contentTypeAliasOf(set, key) ?? [])
33
39
 
34
40
  export function generateDeliveryTypes(set: SchemaSet, options: DeliveryTypesOptions = {}): string {
35
41
  const serves = options.serves ?? (() => true)
@@ -56,7 +62,7 @@ export function generateDeliveryTypes(set: SchemaSet, options: DeliveryTypesOpti
56
62
 
57
63
  /** The JSON the Delivery API writes for a property of this data type; null when empty. */
58
64
  const typeFor = (dataTypeAlias: string): string => {
59
- const { editor, config } = dataTypeOf(set, dataTypeAlias)
65
+ const { editor, config, blocks } = dataTypeOf(set, dataTypeAlias)
60
66
  switch (editor) {
61
67
  case undefined:
62
68
  return 'unknown'
@@ -85,17 +91,15 @@ export function generateDeliveryTypes(set: SchemaSet, options: DeliveryTypesOpti
85
91
  case 'Umbraco.MultiUrlPicker':
86
92
  return 'ApiLink[]'
87
93
  case 'Umbraco.BlockList': {
88
- const { content, settings } = blockElements(set, config)
94
+ const { content, settings } = blockElements(set, config, blocks)
89
95
  return `ApiBlockList<${elementUnion(content)}, ${elementUnion(settings)}>`
90
96
  }
91
97
  case 'Umbraco.BlockGrid': {
92
- const { content, settings } = blockElements(set, config)
98
+ const { content, settings } = blockElements(set, config, blocks)
93
99
  return `ApiBlockGrid<${elementUnion(content)}, ${elementUnion(settings)}>`
94
100
  }
95
101
  case 'Umbraco.ElementPicker': {
96
- const allowed =
97
- typeof config.allowedContentTypes === 'string' ? config.allowedContentTypes : ''
98
- return `Array<${elementUnion([...new Set(keyAliases(set, allowed))])}>`
102
+ return `Array<${elementUnion([...new Set(keyAliases(set, config.allowedContentTypes))])}>`
99
103
  }
100
104
  case 'Umbraco.DropDown.Flexible':
101
105
  return config.multiple === true ? 'string[]' : 'string'
package/src/generate.ts CHANGED
@@ -10,7 +10,8 @@ import {
10
10
  builtInMediaTypeSchema,
11
11
  storageTypeFor,
12
12
  } from './builtin.ts'
13
- import { allProperties, type SchemaContentType, type SchemaSet } from './model.ts'
13
+ import { typeKeyFor } from './keys.ts'
14
+ import { allProperties, type SchemaBlock, type SchemaContentType, type SchemaSet } from './model.ts'
14
15
 
15
16
  export function pascal(alias: string): string {
16
17
  const cleaned = alias.replace(/[^A-Za-z0-9]+(.)?/g, (_, next: string | undefined) =>
@@ -19,17 +20,36 @@ export function pascal(alias: string): string {
19
20
  return cleaned.charAt(0).toUpperCase() + cleaned.slice(1)
20
21
  }
21
22
 
23
+ /**
24
+ * A content type a data type names: by alias, by the key its file gives, or by
25
+ * the key it derives (story 161).
26
+ */
27
+ export function contentTypeAliasOf(set: SchemaSet, value: unknown): string | undefined {
28
+ if (typeof value !== 'string') return undefined
29
+ const wanted = value.trim().toLowerCase()
30
+ return set.contentTypes.find(
31
+ (t) =>
32
+ t.alias.toLowerCase() === wanted ||
33
+ (t.key ?? typeKeyFor('document', t.alias)).toLowerCase() === wanted,
34
+ )?.alias
35
+ }
36
+
22
37
  /** The element types a block data type allows, by alias, for its content and its settings. */
23
- export function blockElements(set: SchemaSet, config: Record<string, unknown>) {
38
+ export function blockElements(
39
+ set: SchemaSet,
40
+ config: Record<string, unknown>,
41
+ tables?: readonly SchemaBlock[],
42
+ ) {
43
+ if (tables)
44
+ return {
45
+ content: [...new Set(tables.map((b) => b.element))],
46
+ settings: [...new Set(tables.flatMap((b) => (b.settings ? [b.settings] : [])))],
47
+ }
24
48
  const blocks = Array.isArray(config.blocks)
25
49
  ? (config.blocks as Array<Record<string, unknown>>)
26
50
  : []
27
- const aliasOf = (key: unknown) =>
28
- typeof key === 'string'
29
- ? set.contentTypes.find((t) => t.key?.toLowerCase() === key.toLowerCase())?.alias
30
- : undefined
31
- const content = blocks.flatMap((b) => aliasOf(b.contentElementTypeKey) ?? [])
32
- const settings = blocks.flatMap((b) => aliasOf(b.settingsElementTypeKey) ?? [])
51
+ const content = blocks.flatMap((b) => contentTypeAliasOf(set, b.contentElementTypeKey) ?? [])
52
+ const settings = blocks.flatMap((b) => contentTypeAliasOf(set, b.settingsElementTypeKey) ?? [])
33
53
  return { content: [...new Set(content)], settings: [...new Set(settings)] }
34
54
  }
35
55
 
@@ -42,18 +62,23 @@ const elementUnion = (aliases: string[]) =>
42
62
  export function dataTypeOf(
43
63
  set: SchemaSet,
44
64
  dataTypeAlias: string,
45
- ): { editor: string | undefined; config: Record<string, unknown> } {
65
+ ): {
66
+ editor: string | undefined
67
+ config: Record<string, unknown>
68
+ blocks?: readonly SchemaBlock[]
69
+ } {
46
70
  const custom = set.dataTypes.find((d) => d.alias === dataTypeAlias)
47
71
  const builtIn = BUILTIN_DATA_TYPES.find((b) => b.alias === dataTypeAlias)
48
72
  return {
49
73
  editor: custom?.editor ?? builtIn?.editor,
50
74
  config: (custom?.config ?? builtIn?.config ?? {}) as Record<string, unknown>,
75
+ blocks: custom?.blocks,
51
76
  }
52
77
  }
53
78
 
54
79
  /** What a template receives for a property of this data type (see `@crombolo/render` values). */
55
80
  function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
56
- const { editor, config } = dataTypeOf(set, dataTypeAlias)
81
+ const { editor, config, blocks } = dataTypeOf(set, dataTypeAlias)
57
82
  if (!editor) return 'unknown'
58
83
  switch (editor) {
59
84
  case 'Umbraco.TrueFalse':
@@ -68,16 +93,16 @@ function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
68
93
  // `allowedContentTypes` is a comma-separated list of element type keys, as
69
94
  // Umbraco's AllowedContentTypeKeysParser reads it. Narrowing to those types
70
95
  // is what makes `hero.value('body')` typed rather than `unknown`.
71
- const allowed =
72
- typeof config.allowedContentTypes === 'string' ? config.allowedContentTypes : ''
96
+ const raw = config.allowedContentTypes
97
+ const allowed = Array.isArray(raw)
98
+ ? raw.map(String)
99
+ : typeof raw === 'string'
100
+ ? raw.split(',')
101
+ : []
73
102
  const aliases = allowed
74
- .split(',')
75
- .map((key) => key.trim())
103
+ .map((value) => value.trim())
76
104
  .filter(Boolean)
77
- .flatMap(
78
- (key) =>
79
- set.contentTypes.find((t) => t.key?.toLowerCase() === key.toLowerCase())?.alias ?? [],
80
- )
105
+ .flatMap((value) => contentTypeAliasOf(set, value) ?? [])
81
106
  // `Array<>` not `[]`: a union of two element types would otherwise bind as
82
107
  // `A | (B[])`.
83
108
  return `Array<${elementUnion([...new Set(aliases)])}>`
@@ -90,11 +115,11 @@ function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
90
115
  case 'Umbraco.UploadField':
91
116
  return 'string'
92
117
  case 'Umbraco.BlockList': {
93
- const { content, settings } = blockElements(set, config)
118
+ const { content, settings } = blockElements(set, config, blocks)
94
119
  return `Array<BlockItem & { content: ${elementUnion(content)}; settings: ${settings.length ? `${elementUnion(settings)} | null` : 'PublishedElement | null'} }>`
95
120
  }
96
121
  case 'Umbraco.BlockGrid': {
97
- const { content } = blockElements(set, config)
122
+ const { content } = blockElements(set, config, blocks)
98
123
  return `Array<BlockGridItem & { content: ${elementUnion(content)} }>`
99
124
  }
100
125
  }
package/src/index.ts CHANGED
@@ -1,13 +1,17 @@
1
+ export * from './blocks.ts'
1
2
  export * from './builtin.ts'
2
3
  export * from './check.ts'
4
+ export * from './config-references.ts'
3
5
  export * from './export.ts'
4
6
  export * from './forms.ts'
5
7
  export * from './generate.ts'
6
8
  export * from './generate-delivery.ts'
9
+ export * from './keys.ts'
7
10
  export * from './load.ts'
8
11
  export * from './model.ts'
9
12
  export * from './parse.ts'
10
13
  export * from './parse-forms.ts'
14
+ export * from './presets.ts'
11
15
  export * from './reader.ts'
12
16
  export * from './scaffold.ts'
13
17
  export * from './sync.ts'