@crombolo/api-delivery 0.37.0 → 0.38.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 +4 -4
- package/src/handler.ts +1 -0
- package/src/index.ts +1 -0
- package/src/output.ts +15 -2
- package/src/rich-text.ts +274 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/api-delivery",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.1",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. Umbraco's Content Delivery API for crombolo: published content and media as JSON, served from the published cache.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"access": "public"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@crombolo/core": "0.
|
|
32
|
-
"@crombolo/contracts": "0.
|
|
33
|
-
"@crombolo/render": "0.
|
|
31
|
+
"@crombolo/core": "0.38.1",
|
|
32
|
+
"@crombolo/contracts": "0.38.1",
|
|
33
|
+
"@crombolo/render": "0.38.1"
|
|
34
34
|
}
|
|
35
35
|
}
|
package/src/handler.ts
CHANGED
|
@@ -412,6 +412,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
412
412
|
access: (content) =>
|
|
413
413
|
readable(content) ? accessTo(content.path, loadedRules, member) : 'forbidden',
|
|
414
414
|
mediaAccess: (media) => mediaAccessTo(media, mediaRules, member),
|
|
415
|
+
media: async (keys) => (ports.media ? ports.media.byKeys(keys) : []),
|
|
415
416
|
}
|
|
416
417
|
|
|
417
418
|
/** Below a node by URL segments, exactly as stored. */
|
package/src/index.ts
CHANGED
package/src/output.ts
CHANGED
|
@@ -17,10 +17,13 @@ import {
|
|
|
17
17
|
PublishedMedia,
|
|
18
18
|
type PublishedProperty,
|
|
19
19
|
RawHtml,
|
|
20
|
+
RichTextValue,
|
|
21
|
+
richTextSource,
|
|
20
22
|
} from '@crombolo/render'
|
|
21
23
|
import { type ExpansionNode, keeps, nextNode } from './expansion.ts'
|
|
22
24
|
import { apiFormReference } from './forms.ts'
|
|
23
25
|
import type { Access } from './protection.ts'
|
|
26
|
+
import { richTextTree } from './rich-text.ts'
|
|
24
27
|
|
|
25
28
|
export interface ApiRoute {
|
|
26
29
|
path: string
|
|
@@ -41,6 +44,8 @@ export interface OutputContext {
|
|
|
41
44
|
mediaAccess?(media: PublishedMedia): Access
|
|
42
45
|
/** An expanded form picker's form, as `v2/forms/{key}` answers it (story 056). */
|
|
43
46
|
form?(form: SchemaForm): Record<string, unknown>
|
|
47
|
+
/** Media by key, for the links and images rich text names (story 216). */
|
|
48
|
+
media?(keys: readonly string[]): Promise<PublishedMedia[]>
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
const iso = (date: Date): string => date.toISOString()
|
|
@@ -320,8 +325,16 @@ export async function deliveryValue(
|
|
|
320
325
|
const form = converted as SchemaForm
|
|
321
326
|
return expand !== undefined && ctx.form ? ctx.form(form) : apiFormReference(form)
|
|
322
327
|
}
|
|
323
|
-
|
|
324
|
-
|
|
328
|
+
// Always the tree (story 216): there is no markup form.
|
|
329
|
+
case 'Umbraco.RichText': {
|
|
330
|
+
const items = converted instanceof RichTextValue ? converted.blocks : []
|
|
331
|
+
const blocks = await inOrder([...items], (i) => blockItem(i, ctx, expand, include))
|
|
332
|
+
return richTextTree(richTextSource(property.value), blocks, {
|
|
333
|
+
content: (key) => ctx.content(key),
|
|
334
|
+
route: (content) => ctx.route(content),
|
|
335
|
+
media: (keys) => ctx.media?.(keys) ?? Promise.resolve([]),
|
|
336
|
+
})
|
|
337
|
+
}
|
|
325
338
|
case 'Umbraco.ContentPicker': {
|
|
326
339
|
const content = converted instanceof PublishedContent ? converted : undefined
|
|
327
340
|
if (!content || !ctx.allowedType(content.contentType.alias)) return null
|
package/src/rich-text.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rich text as a tree of elements (story 216), as Umbraco's
|
|
3
|
+
* `ApiRichTextElementParser` writes it with `RichTextOutputAsJson` on: the
|
|
4
|
+
* only form this Delivery API answers rich text in. docs/delivery-api.md,
|
|
5
|
+
* "Rich text".
|
|
6
|
+
*
|
|
7
|
+
* Text and attribute values are kept as the stored markup has them, entities
|
|
8
|
+
* and all, as Umbraco's HTML parser keeps them.
|
|
9
|
+
*/
|
|
10
|
+
import type { PublishedContent, PublishedMedia } from '@crombolo/render'
|
|
11
|
+
import type { ApiRoute } from './output.ts'
|
|
12
|
+
|
|
13
|
+
export interface RichTextText {
|
|
14
|
+
$type?: 'RichTextTextElement'
|
|
15
|
+
text: string
|
|
16
|
+
tag: '#text'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RichTextGeneric {
|
|
20
|
+
$type?: 'RichTextGenericElement'
|
|
21
|
+
tag: string
|
|
22
|
+
attributes: Record<string, unknown>
|
|
23
|
+
elements: RichTextNode[]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type RichTextNode = RichTextGeneric | RichTextText
|
|
27
|
+
|
|
28
|
+
export interface RichTextRoot {
|
|
29
|
+
tag: '#root'
|
|
30
|
+
attributes: Record<string, unknown>
|
|
31
|
+
elements: RichTextNode[]
|
|
32
|
+
blocks: unknown[]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What resolving a rich text's links and images needs. */
|
|
36
|
+
export interface RichTextLinks {
|
|
37
|
+
content(key: string): PublishedContent | undefined
|
|
38
|
+
route(content: PublishedContent): ApiRoute | undefined
|
|
39
|
+
/** Media by key, looked up together; missing ones are left out. */
|
|
40
|
+
media(keys: readonly string[]): Promise<PublishedMedia[]>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const VOID = new Set([
|
|
44
|
+
'area',
|
|
45
|
+
'base',
|
|
46
|
+
'br',
|
|
47
|
+
'col',
|
|
48
|
+
'embed',
|
|
49
|
+
'hr',
|
|
50
|
+
'img',
|
|
51
|
+
'input',
|
|
52
|
+
'link',
|
|
53
|
+
'meta',
|
|
54
|
+
'param',
|
|
55
|
+
'source',
|
|
56
|
+
'track',
|
|
57
|
+
'wbr',
|
|
58
|
+
])
|
|
59
|
+
/** Elements whose content is text until their closing tag. */
|
|
60
|
+
const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title'])
|
|
61
|
+
|
|
62
|
+
interface ParsedElement {
|
|
63
|
+
tag: string
|
|
64
|
+
attributes: Array<[string, string]>
|
|
65
|
+
children: Parsed[]
|
|
66
|
+
}
|
|
67
|
+
type Parsed = ParsedElement | { text: string }
|
|
68
|
+
|
|
69
|
+
const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
|
|
70
|
+
|
|
71
|
+
function attributesOf(source: string): Array<[string, string]> {
|
|
72
|
+
const out: Array<[string, string]> = []
|
|
73
|
+
for (const match of source.matchAll(ATTRIBUTE)) {
|
|
74
|
+
const name = (match[1] as string).toLowerCase()
|
|
75
|
+
if (out.some(([existing]) => existing === name)) continue
|
|
76
|
+
out.push([name, match[2] ?? match[3] ?? match[4] ?? ''])
|
|
77
|
+
}
|
|
78
|
+
return out
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Markup as a tree, forgiving as a browser's parser is: unclosed tags close with their parent. */
|
|
82
|
+
export function parseMarkup(markup: string): ParsedElement {
|
|
83
|
+
const root: ParsedElement = { tag: '#root', attributes: [], children: [] }
|
|
84
|
+
const stack: ParsedElement[] = [root]
|
|
85
|
+
const top = () => stack[stack.length - 1] as ParsedElement
|
|
86
|
+
let at = 0
|
|
87
|
+
while (at < markup.length) {
|
|
88
|
+
const lt = markup.indexOf('<', at)
|
|
89
|
+
if (lt === -1) {
|
|
90
|
+
top().children.push({ text: markup.slice(at) })
|
|
91
|
+
break
|
|
92
|
+
}
|
|
93
|
+
if (lt > at) top().children.push({ text: markup.slice(at, lt) })
|
|
94
|
+
if (markup.startsWith('<!--', lt)) {
|
|
95
|
+
const end = markup.indexOf('-->', lt + 4)
|
|
96
|
+
at = end === -1 ? markup.length : end + 3
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
if (markup.startsWith('<!', lt) || markup.startsWith('<?', lt)) {
|
|
100
|
+
const end = markup.indexOf('>', lt)
|
|
101
|
+
at = end === -1 ? markup.length : end + 1
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
const close = /^<\/\s*([A-Za-z][\w:-]*)[^>]*>/.exec(markup.slice(lt))
|
|
105
|
+
if (close) {
|
|
106
|
+
const name = (close[1] as string).toLowerCase()
|
|
107
|
+
const index = stack.map((e) => e.tag).lastIndexOf(name)
|
|
108
|
+
if (index > 0) stack.length = index
|
|
109
|
+
at = lt + close[0].length
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
const open = /^<([A-Za-z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/.exec(markup.slice(lt))
|
|
113
|
+
if (!open) {
|
|
114
|
+
top().children.push({ text: '<' })
|
|
115
|
+
at = lt + 1
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
const tag = (open[1] as string).toLowerCase()
|
|
119
|
+
const rest = open[2] as string
|
|
120
|
+
const selfClosing = rest.trimEnd().endsWith('/')
|
|
121
|
+
const element: ParsedElement = {
|
|
122
|
+
tag,
|
|
123
|
+
attributes: attributesOf(selfClosing ? rest.trimEnd().slice(0, -1) : rest),
|
|
124
|
+
children: [],
|
|
125
|
+
}
|
|
126
|
+
top().children.push(element)
|
|
127
|
+
at = lt + open[0].length
|
|
128
|
+
if (RAW_TEXT.has(tag)) {
|
|
129
|
+
const end = markup.toLowerCase().indexOf(`</${tag}`, at)
|
|
130
|
+
const stop = end === -1 ? markup.length : end
|
|
131
|
+
if (stop > at) element.children.push({ text: markup.slice(at, stop) })
|
|
132
|
+
const gt = end === -1 ? -1 : markup.indexOf('>', end)
|
|
133
|
+
at = gt === -1 ? markup.length : gt + 1
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
if (!selfClosing && !VOID.has(tag)) stack.push(element)
|
|
137
|
+
}
|
|
138
|
+
return root
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Kept unless empty or nothing but line breaks: whitespace between inline
|
|
143
|
+
* elements stays, the new lines between a table's rows do not.
|
|
144
|
+
*/
|
|
145
|
+
const keeps = (text: string) => text.trim() !== '' || /[^\r\n]/.test(text)
|
|
146
|
+
|
|
147
|
+
const LOCAL_LINK =
|
|
148
|
+
/^\/?(?:\{|%7B)localLink:(?:umb:\/\/(document|media)\/)?([0-9a-fA-F-]{32,36})(?:\}|%7D)(.*)$/i
|
|
149
|
+
const MEDIA_UDI = /^umb:\/\/media\/([0-9a-fA-F-]{32,36})$/i
|
|
150
|
+
|
|
151
|
+
/** A key in its dashed form, as Umbraco writes a GUID. */
|
|
152
|
+
function dashed(key: string): string | undefined {
|
|
153
|
+
const hex = key.replaceAll('-', '').toLowerCase()
|
|
154
|
+
if (!/^[0-9a-f]{32}$/.test(hex)) return undefined
|
|
155
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Every media key the markup's links and images name, to look up together. */
|
|
159
|
+
function mediaKeys(element: ParsedElement, out = new Set<string>()): Set<string> {
|
|
160
|
+
const attrs = new Map(element.attributes)
|
|
161
|
+
const href = attrs.get('href')
|
|
162
|
+
const link = href ? LOCAL_LINK.exec(href) : null
|
|
163
|
+
if (link) {
|
|
164
|
+
const key = dashed(link[2] as string)
|
|
165
|
+
if (key) out.add(key)
|
|
166
|
+
}
|
|
167
|
+
const udi = element.tag === 'img' ? MEDIA_UDI.exec(attrs.get('data-udi') ?? '') : null
|
|
168
|
+
if (udi) {
|
|
169
|
+
const key = dashed(udi[1] as string)
|
|
170
|
+
if (key) out.add(key)
|
|
171
|
+
}
|
|
172
|
+
for (const child of element.children) if ('tag' in child) mediaKeys(child, out)
|
|
173
|
+
return out
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** A link's `href` resolved as Umbraco resolves it, or removed when it names nothing. */
|
|
177
|
+
function resolveLink(
|
|
178
|
+
attributes: Record<string, unknown>,
|
|
179
|
+
links: RichTextLinks,
|
|
180
|
+
media: ReadonlyMap<string, PublishedMedia>,
|
|
181
|
+
): void {
|
|
182
|
+
const href = attributes.href
|
|
183
|
+
if (typeof href !== 'string') return
|
|
184
|
+
const match = LOCAL_LINK.exec(href)
|
|
185
|
+
if (!match) return
|
|
186
|
+
const kind = (match[1] ?? String(attributes.type ?? '')).toLowerCase()
|
|
187
|
+
const key = dashed(match[2] as string) ?? ''
|
|
188
|
+
const postfix = (match[3] as string) || ''
|
|
189
|
+
const page = kind === 'media' ? undefined : links.content(key)
|
|
190
|
+
const route = page ? links.route(page) : undefined
|
|
191
|
+
if (page && route) {
|
|
192
|
+
attributes.destinationId = page.key
|
|
193
|
+
attributes.destinationType = page.contentType.alias
|
|
194
|
+
attributes.linkType = 'Content'
|
|
195
|
+
attributes.route = { ...route, queryString: postfix || null }
|
|
196
|
+
delete attributes.href
|
|
197
|
+
return
|
|
198
|
+
}
|
|
199
|
+
const item = kind === 'document' ? undefined : media.get(key)
|
|
200
|
+
if (item?.url) {
|
|
201
|
+
attributes.href = item.url
|
|
202
|
+
attributes.destinationId = item.key
|
|
203
|
+
attributes.destinationType = item.mediaType.alias
|
|
204
|
+
attributes.linkType = 'Media'
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
delete attributes.href
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function toNode(
|
|
211
|
+
element: ParsedElement,
|
|
212
|
+
links: RichTextLinks,
|
|
213
|
+
media: ReadonlyMap<string, PublishedMedia>,
|
|
214
|
+
): Record<string, unknown> {
|
|
215
|
+
const attributes: Record<string, unknown> = Object.fromEntries(element.attributes)
|
|
216
|
+
resolveLink(attributes, links, media)
|
|
217
|
+
if (element.tag === 'img' && typeof attributes['data-udi'] === 'string') {
|
|
218
|
+
const udi = MEDIA_UDI.exec(attributes['data-udi'] as string)
|
|
219
|
+
const item = udi ? media.get(dashed(udi[1] as string) ?? '') : undefined
|
|
220
|
+
if (item?.url) {
|
|
221
|
+
const query = String(attributes.src ?? '').split('?')[1]
|
|
222
|
+
attributes.src = query ? `${item.url}?${query}` : item.url
|
|
223
|
+
delete attributes['data-udi']
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (
|
|
227
|
+
element.tag.startsWith('umb-rte-block') &&
|
|
228
|
+
typeof attributes['data-content-key'] === 'string'
|
|
229
|
+
) {
|
|
230
|
+
const key = dashed(attributes['data-content-key'] as string)
|
|
231
|
+
if (key) {
|
|
232
|
+
attributes['content-id'] = key
|
|
233
|
+
delete attributes['data-content-key']
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// `data-*` loses its prefix, unless an attribute of that name is already there.
|
|
237
|
+
for (const name of Object.keys(attributes)) {
|
|
238
|
+
if (!name.startsWith('data-')) continue
|
|
239
|
+
const bare = name.slice('data-'.length)
|
|
240
|
+
if (!(bare in attributes)) attributes[bare] = attributes[name]
|
|
241
|
+
delete attributes[name]
|
|
242
|
+
}
|
|
243
|
+
const elements = element.children.flatMap((child): RichTextNode[] => {
|
|
244
|
+
if ('text' in child)
|
|
245
|
+
return keeps(child.text)
|
|
246
|
+
? [{ $type: 'RichTextTextElement', text: child.text, tag: '#text' }]
|
|
247
|
+
: []
|
|
248
|
+
return [
|
|
249
|
+
{
|
|
250
|
+
$type: 'RichTextGenericElement',
|
|
251
|
+
...(toNode(child, links, media) as Omit<RichTextGeneric, '$type'>),
|
|
252
|
+
},
|
|
253
|
+
]
|
|
254
|
+
})
|
|
255
|
+
return { tag: element.tag, attributes, elements }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Stored markup as the Delivery API's tree, with `blocks` beside it, or `null`
|
|
260
|
+
* when there is nothing in it.
|
|
261
|
+
*/
|
|
262
|
+
export async function richTextTree(
|
|
263
|
+
markup: string,
|
|
264
|
+
blocks: unknown[],
|
|
265
|
+
links: RichTextLinks,
|
|
266
|
+
): Promise<RichTextRoot | null> {
|
|
267
|
+
if (markup.trim() === '' && blocks.length === 0) return null
|
|
268
|
+
const parsed = parseMarkup(markup)
|
|
269
|
+
const keys = [...mediaKeys(parsed)]
|
|
270
|
+
const found = keys.length > 0 ? await links.media(keys) : []
|
|
271
|
+
const media = new Map(found.map((item) => [item.key.toLowerCase(), item]))
|
|
272
|
+
const root = toNode(parsed, links, media) as Omit<RichTextRoot, 'blocks'>
|
|
273
|
+
return { tag: '#root', attributes: {}, elements: root.elements, blocks }
|
|
274
|
+
}
|