@crombolo/api-delivery 0.34.0 → 0.36.2

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/api-delivery",
3
- "version": "0.34.0",
3
+ "version": "0.36.2",
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.34.0",
32
- "@crombolo/contracts": "0.34.0",
33
- "@crombolo/render": "0.34.0"
31
+ "@crombolo/core": "0.36.2",
32
+ "@crombolo/contracts": "0.36.2",
33
+ "@crombolo/render": "0.36.2"
34
34
  }
35
35
  }
package/src/handler.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Every answer is read from memory, so it scales with the nodes that render.
5
5
  * docs/delivery-api.md.
6
6
  */
7
- import { branchAccess, type SchemaForm } from '@crombolo/core'
7
+ import { branchAccess, type MediaMember, type MediaRule, type SchemaForm } from '@crombolo/core'
8
8
  import type {
9
9
  PublishedCache,
10
10
  PublishedContent,
@@ -37,7 +37,7 @@ import {
37
37
  apiMediaResponse,
38
38
  type OutputContext,
39
39
  } from './output.ts'
40
- import { accessTo, type DeliveryMember, type ProtectionRule } from './protection.ts'
40
+ import { accessTo, type DeliveryMember, mediaAccessTo, type ProtectionRule } from './protection.ts'
41
41
  import {
42
42
  compareBy,
43
43
  parseContentFilters,
@@ -47,6 +47,7 @@ import {
47
47
  passesFilters,
48
48
  QUERY_ERRORS,
49
49
  type QueryError,
50
+ type Sort,
50
51
  } from './query.ts'
51
52
  import {
52
53
  type DeliveryApiSettings,
@@ -63,6 +64,13 @@ export interface DeliveryApiPorts {
63
64
  protection(): Promise<ProtectionRule[]>
64
65
  /** The member an access token names; undefined for none, or one not valid now. */
65
66
  member(token: string): Promise<DeliveryMember | undefined>
67
+ /** Every media rule (story 196): few, one per folder given permissions, read once a request. */
68
+ mediaRules?(): Promise<MediaRule[]>
69
+ /**
70
+ * The media library a page at a time, from the database (story 197); the
71
+ * media endpoints answer nothing without it.
72
+ */
73
+ media?: DeliveryMediaPort
66
74
  /**
67
75
  * Drafts for a `Preview: true` request (story 053): given whether it carries
68
76
  * the API key, the draft cache and, for a preview token, which pages its
@@ -112,6 +120,31 @@ export interface DeliveryApiPorts {
112
120
  ): Promise<{ total: number; items: Array<{ key: string; score: number; text: SearchableText }> }>
113
121
  }
114
122
 
123
+ /** The media tree as the media endpoints read it: by key, by path, and a page of children. */
124
+ export interface DeliveryMediaPort {
125
+ /** Items by key, in the order asked; one gone or in the recycle bin is left out. */
126
+ byKeys(keys: readonly string[]): Promise<PublishedMedia[]>
127
+ /** The item at a path of names below the top level, matched in any case. */
128
+ byPath(path: string): Promise<PublishedMedia | undefined>
129
+ /**
130
+ * A page of a parent's children: those passing every filter and readable by
131
+ * `member`, in `sort` order and then Umbraco's (sort order, then id), with
132
+ * how many there are in all.
133
+ */
134
+ children(
135
+ parent: PublishedMedia | 'root',
136
+ query: {
137
+ filters: ReadonlyArray<{ kind: 'mediaType' | 'name'; value: string }>
138
+ sort: Sort | undefined
139
+ skip: number
140
+ take: number
141
+ readable: { rules: ReadonlyMap<number, MediaRule>; member: MediaMember | undefined }
142
+ },
143
+ ): Promise<{ total: number; items: PublishedMedia[] }>
144
+ /** Each item's path of lowercased names, `/folder/item/`, by id. */
145
+ paths(items: readonly PublishedMedia[]): Promise<Map<number, string>>
146
+ }
147
+
115
148
  export interface PreviewAccess {
116
149
  /** Every page as last saved. */
117
150
  cache: PublishedCache
@@ -297,6 +330,15 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
297
330
  return cacheable(request, response, body, { lifetime, tags, tagHeader: caching.tagHeader })
298
331
  }
299
332
 
333
+ /** The member a request's token names, when member sign-in is on. */
334
+ async function memberOf(request: Request): Promise<DeliveryMember | undefined> {
335
+ const token = bearerToken(request)
336
+ return token && memberAuthorizationEnabled(settings) ? ports.member(token) : undefined
337
+ }
338
+
339
+ const loadMediaRules = async () =>
340
+ new Map(((await ports.mediaRules?.()) ?? []).map((rule) => [rule.nodeId, rule]))
341
+
300
342
  /**
301
343
  * Everything a content request decides once: culture, member, rules, routes.
302
344
  * A preview reads the draft cache, and an editor's sees only what they may read.
@@ -319,10 +361,9 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
319
361
  const roots = nav.root()
320
362
  const rtl = isRightToLeft(culture)
321
363
 
322
- let member: DeliveryMember | undefined
323
- const token = bearerToken(request)
324
- if (token && memberAuthorizationEnabled(settings)) member = await ports.member(token)
364
+ const member = await memberOf(request)
325
365
  const loadedRules = new Map((await ports.protection()).map((rule) => [rule.nodeId, rule]))
366
+ const mediaRules = await loadMediaRules()
326
367
 
327
368
  const routeIn = async (inCulture: string | null) => {
328
369
  const view = await source.navigation(inCulture)
@@ -370,6 +411,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
370
411
  // A page the previewing editor may not read keeps its route in a picker, never its properties.
371
412
  access: (content) =>
372
413
  readable(content) ? accessTo(content.path, loadedRules, member) : 'forbidden',
414
+ mediaAccess: (media) => mediaAccessTo(media, mediaRules, member),
373
415
  }
374
416
 
375
417
  /** Below a node by URL segments, exactly as stored. */
@@ -431,7 +473,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
431
473
  if (expansion instanceof Response) return expansion
432
474
  const routes = new Map<string, (c: PublishedContent) => ApiRoute | undefined>()
433
475
  for (const c of content.cultures) routes.set(c, await routeIn(c))
434
- const body = apiContentResponse(
476
+ const body = await apiContentResponse(
435
477
  content,
436
478
  ctx,
437
479
  (c) => routes.get(c)?.(content),
@@ -575,50 +617,38 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
575
617
  )
576
618
  }
577
619
 
578
- /** Media's tree, by parent, and each item's path of lowercased names. */
579
- async function mediaTree() {
580
- const media = await cache.allMedia()
581
- const byId = new Map(media.map((m) => [m.id, m]))
582
- const childrenOf = new Map<number, PublishedMedia[]>()
583
- for (const m of media) childrenOf.set(m.parentId, [...(childrenOf.get(m.parentId) ?? []), m])
584
- for (const list of childrenOf.values()) list.sort((a, b) => a.sortOrder - b.sortOrder)
585
- const pathOf = (m: PublishedMedia): string => {
586
- const names: string[] = []
587
- for (let at: PublishedMedia | undefined = m; at; at = byId.get(at.parentId))
588
- names.unshift(at.name.toLowerCase())
589
- return `/${names.join('/')}/`
590
- }
591
- const byPath = (raw: string): PublishedMedia | undefined => {
592
- let level = childrenOf.get(-1) ?? []
593
- let found: PublishedMedia | undefined
594
- for (const segment of decodeURIComponent(raw).split('/').filter(Boolean)) {
595
- found = level.find((m) => m.name.toLowerCase() === segment.toLowerCase())
596
- if (!found) return undefined
597
- level = childrenOf.get(found.id) ?? []
598
- }
599
- return found
600
- }
601
- const byKey = new Map(media.map((m) => [m.key.toLowerCase(), m]))
602
- return { media, childrenOf, pathOf, byPath, byKey }
603
- }
604
-
605
620
  async function handleMedia(request: Request, url: URL, rest: string) {
606
621
  if (!mediaAccess(settings, request)) return bare(401)
607
- const tree = await mediaTree()
608
- const answer = (m: PublishedMedia) => apiMediaResponse(m, tree.pathOf(m))
622
+ const library = ports.media
623
+ // A protected item is left out of every list for a caller who cannot read it.
624
+ const member = await memberOf(request)
625
+ const rules = await loadMediaRules()
626
+ const accessOf = (m: PublishedMedia) => mediaAccessTo(m, rules, member)
627
+ const readable = (m: PublishedMedia) => accessOf(m) === 'allowed'
628
+ const answer = async (items: readonly PublishedMedia[]) => {
629
+ const paths = library ? await library.paths(items) : new Map<number, string>()
630
+ const out = []
631
+ for (const m of items) out.push(await apiMediaResponse(m, paths.get(m.id) ?? '/'))
632
+ return out
633
+ }
609
634
  if (rest === 'items') {
610
635
  const ids = [...new Set(url.searchParams.getAll('id').map((id) => id.toLowerCase()))]
611
636
  for (const id of ids) if (!GUID.test(id)) return invalid('id', id)
612
- const found = ids.flatMap((id) => {
613
- const media = tree.byKey.get(id)
614
- return media ? [media] : []
615
- })
616
- return holding(Response.json(found.map(answer)), found.map(mediaItem))
637
+ const found = (library ? await library.byKeys(ids) : []).filter(readable)
638
+ return holding(Response.json(await answer(found)), found.map(mediaItem))
617
639
  }
618
640
  if (rest.startsWith('item/')) {
619
641
  const target = rest.slice('item/'.length)
620
- const found = GUID.test(target) ? tree.byKey.get(target.toLowerCase()) : tree.byPath(target)
621
- return found ? holding(Response.json(answer(found)), [mediaItem(found)]) : bare(404)
642
+ const found = !library
643
+ ? undefined
644
+ : GUID.test(target)
645
+ ? (await library.byKeys([target.toLowerCase()]))[0]
646
+ : await library.byPath(decodeURIComponent(target))
647
+ if (!found) return bare(404)
648
+ const access = accessOf(found)
649
+ if (access !== 'allowed') return bare(access === 'unauthorized' ? 401 : 403)
650
+ const [body] = await answer([found])
651
+ return holding(Response.json(body), [mediaItem(found)])
622
652
  }
623
653
  if (rest !== '') return undefined
624
654
  const query = parseMediaQuery({
@@ -632,27 +662,31 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
632
662
  const take = intParam(url, 'take', 10)
633
663
  if (take instanceof Response) return take
634
664
  let parent: PublishedMedia | 'root' | undefined
635
- if (query.parent === '') parent = undefined
665
+ if (!library || query.parent === '') parent = undefined
636
666
  else if (/^\/+$/.test(query.parent)) parent = 'root'
637
- else if (GUID.test(query.parent)) parent = tree.byKey.get(query.parent.toLowerCase())
638
- else parent = tree.byPath(query.parent)
639
- const children = parent ? (tree.childrenOf.get(parent === 'root' ? -1 : parent.id) ?? []) : []
640
- const filtered = children.filter((m) =>
641
- query.filters.every((f) =>
642
- f.kind === 'mediaType'
643
- ? m.mediaType.alias === f.value
644
- : m.name.toLowerCase().includes(f.value.toLowerCase()),
645
- ),
646
- )
647
- const ordered = query.sort
648
- ? [...filtered].sort(
649
- compareBy([query.sort]) as unknown as (a: PublishedMedia, b: PublishedMedia) => number,
650
- )
651
- : filtered
652
- const shown = ordered.slice(skip, skip + take)
667
+ else if (GUID.test(query.parent))
668
+ parent = (await library.byKeys([query.parent.toLowerCase()]))[0]
669
+ else parent = await library.byPath(decodeURIComponent(query.parent))
670
+ // Paged by the database, readable items only, so `total` counts what this caller may see.
671
+ const page =
672
+ parent && library
673
+ ? await library.children(parent, {
674
+ filters: query.filters,
675
+ sort: query.sort,
676
+ skip,
677
+ take,
678
+ readable: {
679
+ rules,
680
+ member:
681
+ member?.approved && !member.lockedOut
682
+ ? { key: member.key, groups: member.groups }
683
+ : undefined,
684
+ },
685
+ })
686
+ : { total: 0, items: [] }
653
687
  return holding(
654
- Response.json({ total: ordered.length, items: shown.map(answer) }),
655
- shown.map(mediaItem),
688
+ Response.json({ total: page.total, items: await answer(page.items) }),
689
+ page.items.map(mediaItem),
656
690
  )
657
691
  }
658
692
 
package/src/output.ts CHANGED
@@ -37,6 +37,8 @@ export interface OutputContext {
37
37
  allowedType(alias: string): boolean
38
38
  /** Whether the caller may see a page's properties when a reference to it is expanded. */
39
39
  access(content: PublishedContent): Access
40
+ /** Whether the caller may read a media item; a reference to one they may not is its key and name. */
41
+ mediaAccess?(media: PublishedMedia): Access
40
42
  /** An expanded form picker's form, as `v2/forms/{key}` answers it (story 056). */
41
43
  form?(form: SchemaForm): Record<string, unknown>
42
44
  }
@@ -64,13 +66,13 @@ const empty = (value: unknown): boolean =>
64
66
  (Array.isArray(value) && value.length === 0)
65
67
 
66
68
  /** A page as a reference: everything but `cultures`, its properties only when expanded. */
67
- export function apiContent(
69
+ export async function apiContent(
68
70
  content: PublishedContent,
69
71
  ctx: OutputContext,
70
72
  expand: ExpansionNode | undefined,
71
73
  include: ExpansionNode | undefined,
72
74
  topLevel = false,
73
- ): Record<string, unknown> | null {
75
+ ): Promise<Record<string, unknown> | null> {
74
76
  const route = ctx.route(content)
75
77
  if (!route) return null
76
78
  const showProperties = topLevel || (expand !== undefined && ctx.access(content) === 'allowed')
@@ -81,24 +83,27 @@ export function apiContent(
81
83
  updateDate: iso(content.updateDate),
82
84
  route,
83
85
  id: content.key,
84
- properties: showProperties ? properties(content, ctx, expand, include) : {},
86
+ properties: showProperties ? await properties(content, ctx, expand, include) : {},
85
87
  }
86
88
  }
87
89
 
88
- function properties(
90
+ async function properties(
89
91
  item: PublishedContent | PublishedElement,
90
92
  ctx: OutputContext,
91
93
  expand: ExpansionNode | undefined,
92
94
  include: ExpansionNode | undefined,
93
- ): Record<string, unknown> {
95
+ ): Promise<Record<string, unknown>> {
94
96
  const culture = item instanceof PublishedContent ? item.culture : null
95
97
  const out: Record<string, unknown> = {}
96
- const aliases = [...new Set(item.properties.map((p) => p.alias))]
97
- for (const alias of aliases) {
98
- if (!keeps(include, alias)) continue
98
+ const aliases = [...new Set(item.properties.map((p) => p.alias))].filter((alias) =>
99
+ keeps(include, alias),
100
+ )
101
+ // Values that name media are looked up in the media cache together (story 197).
102
+ const values = await Promise.all(aliases.map((alias) => item.value(alias)))
103
+ for (const [index, alias] of aliases.entries()) {
99
104
  const property = propertyOf(item.properties, alias, culture) as PublishedProperty
100
- const converted = item.value(alias)
101
- out[alias] = deliveryValue(
105
+ const converted = values[index]
106
+ out[alias] = await deliveryValue(
102
107
  property,
103
108
  converted,
104
109
  ctx,
@@ -110,18 +115,18 @@ function properties(
110
115
  }
111
116
 
112
117
  /** An element (a block, a library element): its properties are always mapped. */
113
- function apiElement(
118
+ async function apiElement(
114
119
  element: PublishedElement | null,
115
120
  ctx: OutputContext,
116
121
  expand: ExpansionNode | undefined,
117
122
  include: ExpansionNode | undefined,
118
- ): Record<string, unknown> | null {
123
+ ): Promise<Record<string, unknown> | null> {
119
124
  if (!element) return null
120
125
  return {
121
126
  contentType: element.contentType.alias ?? '',
122
127
  id: element.key,
123
128
  name: '',
124
- properties: properties(element, ctx, expand, include ?? { key: '', children: [] }),
129
+ properties: await properties(element, ctx, expand, include ?? { key: '', children: [] }),
125
130
  }
126
131
  }
127
132
 
@@ -131,11 +136,11 @@ const numberOf = (media: PublishedMedia, alias: string): number | null => {
131
136
  }
132
137
 
133
138
  /** Media's own fields; its properties exclude the `umbraco*` ones, and appear only when expanded. */
134
- function mediaCore(
139
+ async function mediaCore(
135
140
  media: PublishedMedia,
136
141
  expand: ExpansionNode | undefined,
137
142
  topLevel: boolean,
138
- ): Record<string, unknown> {
143
+ ): Promise<Record<string, unknown>> {
139
144
  const extension = media.value('umbracoExtension')
140
145
  return {
141
146
  id: media.key,
@@ -146,15 +151,20 @@ function mediaCore(
146
151
  width: numberOf(media, 'umbracoWidth'),
147
152
  height: numberOf(media, 'umbracoHeight'),
148
153
  bytes: numberOf(media, 'umbracoBytes'),
149
- properties: topLevel || expand !== undefined ? mediaProperties(media) : {},
154
+ properties: topLevel || expand !== undefined ? await mediaProperties(media) : {},
150
155
  }
151
156
  }
152
157
 
153
- function mediaProperties(media: PublishedMedia): Record<string, unknown> {
158
+ async function mediaProperties(media: PublishedMedia): Promise<Record<string, unknown>> {
154
159
  const out: Record<string, unknown> = {}
155
160
  for (const property of media.properties) {
156
161
  if (property.alias.toLowerCase().startsWith('umbraco')) continue
157
- const value = convertValue(property.editorAlias, property.value, undefined, property.config)
162
+ const value = await convertValue(
163
+ property.editorAlias,
164
+ property.value,
165
+ undefined,
166
+ property.config,
167
+ )
158
168
  out[property.alias] = empty(value) ? null : plain(value)
159
169
  }
160
170
  return out
@@ -169,22 +179,31 @@ const crops = (value: ImageCropperValue) =>
169
179
  }))
170
180
 
171
181
  /** A media item as a query or item endpoint answers it: its tree path, dates, crops. */
172
- export function apiMediaResponse(media: PublishedMedia, path: string): Record<string, unknown> {
182
+ export async function apiMediaResponse(
183
+ media: PublishedMedia,
184
+ path: string,
185
+ ): Promise<Record<string, unknown>> {
173
186
  const image = media.image
174
187
  return {
175
188
  path,
176
189
  createDate: iso(media.createDate),
177
190
  updateDate: iso(media.updateDate),
178
- ...mediaCore(media, undefined, true),
191
+ ...(await mediaCore(media, undefined, true)),
179
192
  focalPoint: image.focalPoint,
180
193
  crops: image.src || image.crops.length > 0 ? crops(image) : null,
181
194
  }
182
195
  }
183
196
 
184
- function mediaWithCrops(
197
+ /** A media reference the caller may not read: only what names it (story 196). */
198
+ function closedMedia(media: PublishedMedia, ctx: OutputContext): Record<string, unknown> | null {
199
+ if (!ctx.mediaAccess || ctx.mediaAccess(media) === 'allowed') return null
200
+ return { id: media.key, name: media.name }
201
+ }
202
+
203
+ async function mediaWithCrops(
185
204
  pick: MediaWithCrops,
186
205
  expand: ExpansionNode | undefined,
187
- ): Record<string, unknown> {
206
+ ): Promise<Record<string, unknown>> {
188
207
  // The pick's own crops and focal point win; the media's fill in what it lacks.
189
208
  const own = pick.media.image
190
209
  const merged = own.crops.map((crop) => {
@@ -194,7 +213,7 @@ function mediaWithCrops(
194
213
  return {
195
214
  focalPoint: pick.focalPoint ?? own.focalPoint ?? null,
196
215
  crops: crops(new ImageCropperValue({ crops: merged })),
197
- ...mediaCore(pick.media, expand, false),
216
+ ...(await mediaCore(pick.media, expand, false)),
198
217
  }
199
218
  }
200
219
 
@@ -229,39 +248,47 @@ function link(linkValue: Link, ctx: OutputContext): Record<string, unknown> | nu
229
248
  }
230
249
  }
231
250
 
232
- function blockItem(
251
+ async function blockItem(
233
252
  item: BlockItem,
234
253
  ctx: OutputContext,
235
254
  expand: ExpansionNode | undefined,
236
255
  include: ExpansionNode | undefined,
237
256
  ) {
238
257
  return {
239
- content: apiElement(item.content, ctx, expand, include),
240
- settings: apiElement(item.settings, ctx, expand, include),
258
+ content: await apiElement(item.content, ctx, expand, include),
259
+ settings: await apiElement(item.settings, ctx, expand, include),
241
260
  }
242
261
  }
243
262
 
244
- function gridItem(
263
+ async function gridItem(
245
264
  item: BlockGridItem,
246
265
  ctx: OutputContext,
247
266
  columns: number,
248
267
  expand: ExpansionNode | undefined,
249
268
  include: ExpansionNode | undefined,
250
- ): Record<string, unknown> {
269
+ ): Promise<Record<string, unknown>> {
270
+ const areas = []
271
+ for (const area of item.areas) {
272
+ const items = []
273
+ for (const inner of area.items) items.push(await gridItem(inner, ctx, columns, expand, include))
274
+ areas.push({ alias: area.key, rowSpan: 1, columnSpan: columns, items })
275
+ }
251
276
  return {
252
277
  rowSpan: item.rowSpan ?? 1,
253
278
  columnSpan: item.columnSpan ?? columns,
254
279
  areaGridColumns: columns,
255
- areas: item.areas.map((area) => ({
256
- alias: area.key,
257
- rowSpan: 1,
258
- columnSpan: columns,
259
- items: area.items.map((inner) => gridItem(inner, ctx, columns, expand, include)),
260
- })),
261
- ...blockItem(item, ctx, expand, include),
280
+ areas,
281
+ ...(await blockItem(item, ctx, expand, include)),
262
282
  }
263
283
  }
264
284
 
285
+ /** Each item mapped in turn, so the answer keeps its order. */
286
+ async function inOrder<T, U>(items: readonly T[], map: (item: T) => Promise<U>): Promise<U[]> {
287
+ const out: U[] = []
288
+ for (const item of items) out.push(await map(item))
289
+ return out
290
+ }
291
+
265
292
  /** What a value is when nothing more specific applies: dates as ISO, markup as text. */
266
293
  function plain(value: unknown): unknown {
267
294
  if (value instanceof Date) return iso(value)
@@ -276,13 +303,13 @@ const list = <T>(value: unknown): T[] =>
276
303
  Array.isArray(value) ? (value as T[]) : value === null || value === undefined ? [] : [value as T]
277
304
 
278
305
  /** One property's Delivery API value. Empty is `null`, as in Umbraco. */
279
- export function deliveryValue(
306
+ export async function deliveryValue(
280
307
  property: PublishedProperty,
281
308
  converted: unknown,
282
309
  ctx: OutputContext,
283
310
  expand: ExpansionNode | undefined,
284
311
  include: ExpansionNode | undefined,
285
- ): unknown {
312
+ ): Promise<unknown> {
286
313
  if (empty(property.value) || empty(converted)) return null
287
314
  const config = property.config ?? {}
288
315
  switch (property.editorAlias) {
@@ -298,39 +325,45 @@ export function deliveryValue(
298
325
  case 'Umbraco.ContentPicker': {
299
326
  const content = converted instanceof PublishedContent ? converted : undefined
300
327
  if (!content || !ctx.allowedType(content.contentType.alias)) return null
301
- return apiContent(content, ctx, expand, include)
328
+ return await apiContent(content, ctx, expand, include)
302
329
  }
303
330
  case 'Umbraco.MultiNodeTreePicker':
304
- return list<unknown>(converted).flatMap((item) => {
305
- if (item instanceof PublishedContent)
306
- return ctx.allowedType(item.contentType.alias)
307
- ? [apiContent(item, ctx, expand, include)].filter(Boolean)
308
- : []
309
- if (item instanceof PublishedMedia) return [mediaCore(item, expand, false)]
310
- return []
311
- })
331
+ return (
332
+ await inOrder(list<unknown>(converted), async (item) => {
333
+ if (item instanceof PublishedContent)
334
+ return ctx.allowedType(item.contentType.alias)
335
+ ? [await apiContent(item, ctx, expand, include)].filter(Boolean)
336
+ : []
337
+ if (item instanceof PublishedMedia)
338
+ return [closedMedia(item, ctx) ?? (await mediaCore(item, expand, false))]
339
+ return []
340
+ })
341
+ ).flat()
312
342
  case 'Umbraco.MediaPicker3':
313
- return list<MediaWithCrops>(converted)
314
- .filter((pick) => pick instanceof MediaWithCrops)
315
- .map((pick) => mediaWithCrops(pick, expand))
343
+ return inOrder(
344
+ list<MediaWithCrops>(converted).filter((pick) => pick instanceof MediaWithCrops),
345
+ async (pick) => closedMedia(pick.media, ctx) ?? (await mediaWithCrops(pick, expand)),
346
+ )
316
347
  case 'Umbraco.MultiUrlPicker':
317
348
  return list<Link>(converted).flatMap((l) => {
318
349
  const built = link(l, ctx)
319
350
  return built ? [built] : []
320
351
  })
321
352
  case 'Umbraco.BlockList':
322
- return { items: list<BlockItem>(converted).map((i) => blockItem(i, ctx, expand, include)) }
353
+ return {
354
+ items: await inOrder(list<BlockItem>(converted), (i) => blockItem(i, ctx, expand, include)),
355
+ }
323
356
  case 'Umbraco.BlockGrid': {
324
357
  const columns = Number(config.gridColumns) || 12
325
358
  return {
326
359
  gridColumns: columns,
327
- items: list<BlockGridItem>(converted).map((i) =>
360
+ items: await inOrder(list<BlockGridItem>(converted), (i) =>
328
361
  gridItem(i, ctx, columns, expand, include),
329
362
  ),
330
363
  }
331
364
  }
332
365
  case 'Umbraco.ElementPicker':
333
- return list<PublishedElement>(converted).map((e) => apiElement(e, ctx, expand, include))
366
+ return inOrder(list<PublishedElement>(converted), (e) => apiElement(e, ctx, expand, include))
334
367
  case 'Umbraco.DropDown.Flexible': {
335
368
  const values = list<string>(converted)
336
369
  return config.multiple === true ? values : (values[0] ?? null)
@@ -355,14 +388,14 @@ export function deliveryValue(
355
388
  }
356
389
 
357
390
  /** A page as an item or query endpoint answers it: a reference, plus its routes per culture. */
358
- export function apiContentResponse(
391
+ export async function apiContentResponse(
359
392
  content: PublishedContent,
360
393
  ctx: OutputContext,
361
394
  routeIn: (culture: string) => ApiRoute | undefined,
362
395
  expand: ExpansionNode | undefined,
363
396
  include: ExpansionNode | undefined,
364
- ): Record<string, unknown> | null {
365
- const built = apiContent(content, ctx, expand, include, true)
397
+ ): Promise<Record<string, unknown> | null> {
398
+ const built = await apiContent(content, ctx, expand, include, true)
366
399
  if (!built) return null
367
400
  const cultures: Record<string, ApiRoute> = {}
368
401
  for (const culture of content.cultures) {
package/src/protection.ts CHANGED
@@ -4,7 +4,13 @@
4
4
  * (`memberMayOpen`, shared with the site). Umbraco's `PublicAccessChecker`,
5
5
  * over rules read once per request.
6
6
  */
7
- import { memberMayOpen } from '@crombolo/core'
7
+ import {
8
+ type MediaItemAccess,
9
+ type MediaRule,
10
+ memberMay,
11
+ memberMayOpen,
12
+ nearestMediaRule,
13
+ } from '@crombolo/core'
8
14
 
9
15
  export interface ProtectionRule {
10
16
  /** The protected node's id: its own, or the ancestor whose rule covers it. */
@@ -50,3 +56,26 @@ export function accessTo(
50
56
  ? 'allowed'
51
57
  : 'forbidden'
52
58
  }
59
+
60
+ /**
61
+ * What a caller may do with a media item (story 196): its own policy, else the
62
+ * nearest media rule on its path. A member who may not sign in now is nobody. Pure.
63
+ */
64
+ export function mediaAccessTo(
65
+ media: { path: string; access: MediaItemAccess },
66
+ rules: ReadonlyMap<number, MediaRule>,
67
+ member: DeliveryMember | undefined,
68
+ ): Access {
69
+ const signedIn = member?.approved && !member.lockedOut ? member : undefined
70
+ const rule = nearestMediaRule(media.path, rules)
71
+ if (
72
+ memberMay(
73
+ 'read',
74
+ media.access,
75
+ rule,
76
+ signedIn && { key: signedIn.key, groups: signedIn.groups },
77
+ )
78
+ )
79
+ return 'allowed'
80
+ return signedIn ? 'forbidden' : 'unauthorized'
81
+ }