@crombolo/api-management 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/api-management",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. Umbraco-compatible Management API handlers for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,8 +29,8 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/content": "0.47.0",
33
- "@crombolo/contracts": "0.47.0",
34
- "@crombolo/core": "0.47.0"
32
+ "@crombolo/content": "0.48.0",
33
+ "@crombolo/contracts": "0.48.0",
34
+ "@crombolo/core": "0.48.0"
35
35
  }
36
36
  }
@@ -12,6 +12,16 @@ import {
12
12
  toTreeItemResponse,
13
13
  } from './content-type.ts'
14
14
 
15
+ /** The editors whose settings offer "Ignore user start nodes" (story 270). */
16
+ const START_NODE_EDITORS = new Set([
17
+ 'Umbraco.ContentPicker',
18
+ 'Umbraco.MultiNodeTreePicker',
19
+ 'Umbraco.MediaPicker3',
20
+ 'Umbraco.MultiUrlPicker',
21
+ 'Umbraco.RichText',
22
+ 'Umbraco.ElementPicker',
23
+ ])
24
+
15
25
  function toResponse(model: DataTypeModel): ResponseOf<'GetDataTypeById'> {
16
26
  return {
17
27
  id: model.key,
@@ -20,7 +30,7 @@ function toResponse(model: DataTypeModel): ResponseOf<'GetDataTypeById'> {
20
30
  editorUiAlias: model.editorUiAlias,
21
31
  values: model.values.map((value) => ({ alias: value.alias, value: value.value })),
22
32
  isDeletable: true,
23
- canIgnoreStartNodes: false,
33
+ canIgnoreStartNodes: START_NODE_EDITORS.has(model.editorAlias),
24
34
  } as ResponseOf<'GetDataTypeById'>
25
35
  }
26
36
 
@@ -26,6 +26,7 @@ import { APP_PREVIEW_PROVIDER, type PreviewPort } from '../ports.ts'
26
26
  import type { DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
27
27
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
28
28
  import { created, paging } from './content-type.ts'
29
+ import { itemFlags, variantFlags } from './flags.ts'
29
30
  import {
30
31
  type TreeSource,
31
32
  visibleChildren,
@@ -40,7 +41,7 @@ const ref = (value: unknown): string | null =>
40
41
  function toVariantResponse(aggregate: DocumentAggregate) {
41
42
  return aggregate.variants.map((variant) => ({
42
43
  id: aggregate.key,
43
- flags: [],
44
+ flags: variantFlags(variant),
44
45
  state: variant.state,
45
46
  publishDate: variant.publishDate?.toISOString() ?? null,
46
47
  scheduledPublishDate: variant.scheduledPublishDate?.toISOString() ?? null,
@@ -65,7 +66,7 @@ export function toDocumentResponse(aggregate: DocumentAggregate) {
65
66
  : null,
66
67
  },
67
68
  template: aggregate.componentKey ? { id: aggregate.componentKey } : null,
68
- flags: [],
69
+ flags: itemFlags(aggregate.variants),
69
70
  values: aggregate.values.map((value) => ({
70
71
  editorAlias: value.editorAlias ?? '',
71
72
  culture: value.culture,
@@ -81,7 +82,7 @@ function toDocumentItemResponse(item: DocumentTreeItem) {
81
82
  return {
82
83
  id: item.key,
83
84
  isTrashed: item.isTrashed,
84
- isProtected: false,
85
+ isProtected: item.isProtected ?? false,
85
86
  hasChildren: item.hasChildren,
86
87
  parent: item.parentKey ? { id: item.parentKey } : null,
87
88
  documentType: {
@@ -94,9 +95,9 @@ function toDocumentItemResponse(item: DocumentTreeItem) {
94
95
  name: v.name,
95
96
  culture: v.culture,
96
97
  state: v.state,
97
- flags: [],
98
+ flags: variantFlags(v),
98
99
  })),
99
- flags: [],
100
+ flags: itemFlags(item.variants),
100
101
  }
101
102
  }
102
103
 
@@ -171,7 +172,7 @@ function readCultures(body: unknown): string[] | null {
171
172
  }
172
173
 
173
174
  /** `publishSchedules` as dates, or 'invalid' when one does not parse. */
174
- function readSchedules(
175
+ export function readSchedules(
175
176
  body: Record<string, unknown>,
176
177
  ):
177
178
  | Array<{ culture: string | null; publishTime: Date | null; unpublishTime: Date | null }>
@@ -256,7 +257,7 @@ export function toDocumentTreeItemResponse(item: DocumentTreeItem, noAccess = fa
256
257
  parent: item.parentKey ? { id: item.parentKey } : null,
257
258
  hasChildren: item.hasChildren,
258
259
  noAccess,
259
- isProtected: false,
260
+ isProtected: item.isProtected ?? false,
260
261
  isTrashed: item.isTrashed,
261
262
  createDate: item.createDate.toISOString(),
262
263
  ancestors: item.ancestorKeys.map((id) => ({ id })),
@@ -270,9 +271,9 @@ export function toDocumentTreeItemResponse(item: DocumentTreeItem, noAccess = fa
270
271
  name: v.name,
271
272
  culture: v.culture,
272
273
  state: v.state,
273
- flags: [],
274
+ flags: variantFlags(v),
274
275
  })),
275
- flags: [],
276
+ flags: itemFlags(item.variants),
276
277
  }
277
278
  }
278
279
 
@@ -967,7 +968,7 @@ export function registerDocumentHandlers(
967
968
  documentType: document.documentType,
968
969
  values: document.values,
969
970
  variants: document.variants,
970
- flags: [],
971
+ flags: document.flags,
971
972
  })
972
973
  })
973
974
 
@@ -1081,20 +1082,27 @@ export function registerDocumentHandlers(
1081
1082
  principal && ctx.nodes
1082
1083
  ? (await ctx.nodes.documents([parent])).get(parent.toLowerCase())?.chain
1083
1084
  : undefined
1085
+ const q = ctx.url.searchParams
1084
1086
  const result = await port.collection(
1085
1087
  parent,
1086
- page,
1088
+ {
1089
+ ...page,
1090
+ filter: q.get('filter') ?? undefined,
1091
+ orderBy: q.get('orderBy') ?? undefined,
1092
+ orderDirection: q.get('orderDirection') === 'Descending' ? 'Descending' : 'Ascending',
1093
+ orderCulture: q.get('orderCulture') ?? undefined,
1094
+ },
1087
1095
  principal && chain ? deniedChildren(principal, chain) : [],
1088
1096
  )
1089
1097
  return Response.json({
1090
1098
  total: result.total,
1091
1099
  items: result.items.map((aggregate) => ({
1092
1100
  ...toDocumentResponse(aggregate),
1093
- creator: null,
1101
+ creator: aggregate.creator,
1094
1102
  sortOrder: aggregate.sortOrder,
1095
- hasChildren: false,
1096
- updater: null,
1097
- isProtected: false,
1103
+ hasChildren: aggregate.hasChildren,
1104
+ updater: aggregate.updater,
1105
+ isProtected: aggregate.isProtected,
1098
1106
  ancestors: [],
1099
1107
  })),
1100
1108
  })
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * An element is publishable, versioned content with no URL and no template, so
5
5
  * this mirrors the document handlers without the parts a route needs — no URLs,
6
- * no preview, no schedules, no domains. The contract keys an element's type as
6
+ * no preview, no domains. The contract keys an element's type as
7
7
  * `documentType`, because an element type *is* a content type carrying
8
8
  * `isElement`; the Library offers the ones that also carry `allowedInLibrary`,
9
9
  * which `document-type/allowed-in-library` answers.
@@ -17,7 +17,8 @@ import { invalidSkipTake, notFound, problemDetails, problemResponse } from '@cro
17
17
  import type { ElementPort, PortFailure, ReferencePort } from '../ports-content.ts'
18
18
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
19
19
  import { created, paging, registerFolderHandlers } from './content-type.ts'
20
- import { failureResponse, readBody, toSaveDocument } from './document.ts'
20
+ import { failureResponse, readBody, readSchedules, toSaveDocument } from './document.ts'
21
+ import { itemFlags, variantFlags } from './flags.ts'
21
22
 
22
23
  const API = '/umbraco/management/api/v1'
23
24
 
@@ -52,11 +53,11 @@ export function toElementResponse(element: DocumentAggregate) {
52
53
  createDate: v.createDate.toISOString(),
53
54
  updateDate: v.updateDate.toISOString(),
54
55
  publishDate: v.publishDate?.toISOString() ?? null,
55
- scheduledPublishDate: null,
56
- scheduledUnpublishDate: null,
57
- flags: [],
56
+ scheduledPublishDate: v.scheduledPublishDate?.toISOString() ?? null,
57
+ scheduledUnpublishDate: v.scheduledUnpublishDate?.toISOString() ?? null,
58
+ flags: variantFlags(v),
58
59
  })),
59
- flags: [],
60
+ flags: itemFlags(element.variants),
60
61
  }
61
62
  }
62
63
 
@@ -66,7 +67,7 @@ const variantItems = (item: ElementTreeItem) =>
66
67
  name: v.name,
67
68
  culture: v.culture,
68
69
  state: v.state,
69
- flags: [],
70
+ flags: variantFlags(v),
70
71
  }))
71
72
 
72
73
  /** One shape serves the tree and the recycle bin; the contract's models match. */
@@ -83,7 +84,7 @@ function toElementTreeItem(item: ElementTreeItem, noAccess = false) {
83
84
  ? null
84
85
  : typeRef(item.contentTypeKey, item.icon, item.contentTypeCollectionKey),
85
86
  variants: variantItems(item),
86
- flags: [],
87
+ flags: itemFlags(item.variants),
87
88
  }
88
89
  }
89
90
 
@@ -97,12 +98,17 @@ function toElementItem(item: ElementTreeItem) {
97
98
  ? null
98
99
  : typeRef(item.contentTypeKey, item.icon, item.contentTypeCollectionKey),
99
100
  variants: variantItems(item),
100
- flags: [],
101
+ flags: itemFlags(item.variants),
101
102
  }
102
103
  }
103
104
 
104
105
  const readCultures = (body: Record<string, unknown>): string[] | null => {
105
- const raw = body.cultures ?? body.culturesToPublish
106
+ const raw =
107
+ body.cultures ??
108
+ body.culturesToPublish ??
109
+ (Array.isArray(body.publishSchedules)
110
+ ? (body.publishSchedules as Array<Record<string, unknown>>).map((s) => s.culture)
111
+ : undefined)
106
112
  if (!Array.isArray(raw)) return null
107
113
  const cultures = raw.filter((c): c is string => typeof c === 'string' && c.length > 0)
108
114
  return cultures.length > 0 ? cultures : null
@@ -291,10 +297,15 @@ export function registerElementHandlers(
291
297
  handle('PutElementByIdPublish', async (ctx) => {
292
298
  const key = ctx.params.id as string
293
299
  if (!(await port.byKey(key))) return problemResponse(notFound('The element could not be found'))
294
- const result = await port.publish(key, readCultures(await readBody(ctx)))
295
- return result.ok
296
- ? done(ctx, 'Element published')
297
- : failed('Could not publish the element', result)
300
+ const body = await readBody(ctx)
301
+ const schedules = readSchedules(body)
302
+ if (schedules === 'invalid')
303
+ return problemResponse(
304
+ problemDetails({ title: 'A schedule date is not a valid date', status: 400 }),
305
+ )
306
+ const result = await port.publish(key, readCultures(body), schedules)
307
+ if (!result.ok) return failed('Could not publish the element', result)
308
+ return done(ctx, result.scheduledOnly ? 'Publishing scheduled' : 'Element published')
298
309
  })
299
310
 
300
311
  handle('PutElementByIdUnpublish', async (ctx) => {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Flags the back office reads from items and their variants to draw entity
3
+ * signs: today only Umbraco's scheduled-publish sign.
4
+ */
5
+ export const SCHEDULED_FOR_PUBLISH = 'Umb.ScheduledForPublish'
6
+
7
+ type Flag = { alias: string }
8
+
9
+ /** A variant's flags. */
10
+ export const variantFlags = (variant: {
11
+ scheduledForPublish?: boolean
12
+ scheduledPublishDate?: Date | null
13
+ }): Flag[] =>
14
+ variant.scheduledForPublish || variant.scheduledPublishDate
15
+ ? [{ alias: SCHEDULED_FOR_PUBLISH }]
16
+ : []
17
+
18
+ /** An item's flags: what any of its variants carries, once. */
19
+ export const itemFlags = (variants: ReadonlyArray<Parameters<typeof variantFlags>[0]>): Flag[] => {
20
+ const aliases = new Set(variants.flatMap((v) => variantFlags(v).map((f) => f.alias)))
21
+ return [...aliases].map((alias) => ({ alias }))
22
+ }
@@ -19,6 +19,13 @@ import type {
19
19
  } from '@crombolo/core'
20
20
  import type { Principal } from './router.ts'
21
21
 
22
+ /** When a culture (null: the invariant variant) goes live and comes down. */
23
+ export interface PublishSchedule {
24
+ culture: string | null
25
+ publishTime: Date | null
26
+ unpublishTime: Date | null
27
+ }
28
+
22
29
  /** A failed port call; `status` overrides the handler's default 400 (409 for a write gate). */
23
30
  export type PortFailure = {
24
31
  ok: false
@@ -95,7 +102,15 @@ export interface ElementPort {
95
102
  cultures: string[] | null,
96
103
  principal: Principal,
97
104
  ): Promise<{ ok: true } | PortFailure>
98
- publish(key: string, cultures: string[] | null): Promise<{ ok: true } | PortFailure>
105
+ /**
106
+ * Publishes now, or schedules: an entry with a publish time still to come
107
+ * schedules that culture instead of publishing it, as a document's does.
108
+ */
109
+ publish(
110
+ key: string,
111
+ cultures: string[] | null,
112
+ schedules?: readonly PublishSchedule[],
113
+ ): Promise<{ ok: true; scheduledOnly: boolean } | PortFailure>
99
114
  unpublish(key: string, cultures: string[] | null): Promise<{ ok: true } | PortFailure>
100
115
  copy(
101
116
  key: string,
@@ -397,9 +412,27 @@ export interface DocumentPort extends TreePort {
397
412
  /** A page of a document's children, without `excludeKeys` in the page or the total. */
398
413
  collection(
399
414
  parentKey: string | null,
400
- paging: SkipTake,
415
+ options: DocumentCollectionQuery,
401
416
  excludeKeys?: readonly string[],
402
- ): Promise<Page<DocumentAggregate>>
417
+ ): Promise<Page<DocumentCollectionItem>>
418
+ }
419
+
420
+ /** What a list view asks for: a page, searched by name and sorted by a column. */
421
+ export interface DocumentCollectionQuery extends SkipTake {
422
+ filter?: string
423
+ /** A column's alias; one the list cannot sort by keeps the sort order. */
424
+ orderBy?: string
425
+ orderDirection?: 'Ascending' | 'Descending'
426
+ /** The culture whose names are searched and sorted. */
427
+ orderCulture?: string
428
+ }
429
+
430
+ /** A row of a list view: the document, and what the list shows beside it. */
431
+ export type DocumentCollectionItem = DocumentAggregate & {
432
+ isProtected: boolean
433
+ hasChildren: boolean
434
+ creator: string | null
435
+ updater: string | null
403
436
  }
404
437
 
405
438
  export interface SaveDocument {
package/src/router.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  notFound,
13
13
  notImplemented,
14
14
  problemResponse,
15
+ ROOT_ACCESS,
15
16
  type StartNodes,
16
17
  unauthorized,
17
18
  } from '@crombolo/core'
@@ -89,6 +90,27 @@ export interface RequestContext {
89
90
 
90
91
  export type Authenticator = (request: Request) => Promise<Principal | undefined>
91
92
 
93
+ /**
94
+ * The operations a picker calls with its `dataTypeId` (story 270). A data type
95
+ * with `ignoreUserStartNodes` on lets them see the whole tree; nothing else
96
+ * may widen what a user reaches.
97
+ */
98
+ const PICKER_OPERATIONS = new Set([
99
+ 'GetTreeDocumentRoot',
100
+ 'GetTreeDocumentChildren',
101
+ 'GetTreeDocumentSiblings',
102
+ 'GetItemDocumentSearch',
103
+ 'GetCollectionDocumentById',
104
+ 'GetTreeMediaRoot',
105
+ 'GetTreeMediaChildren',
106
+ 'GetTreeMediaSiblings',
107
+ 'GetItemMediaSearch',
108
+ 'GetCollectionMedia',
109
+ 'GetTreeElementRoot',
110
+ 'GetTreeElementChildren',
111
+ 'GetTreeElementSiblings',
112
+ ])
113
+
92
114
  export interface RouterOptions {
93
115
  operations?: readonly OperationInfo[]
94
116
  /** Resolves the caller's identity. Omitted means every request is anonymous. */
@@ -107,6 +129,8 @@ export interface RouterOptions {
107
129
  clientAddress?: (request: Request) => ClientAddress
108
130
  /** Answers an error a handler threw; undefined lets it propagate. */
109
131
  onError?: (error: unknown) => Response | undefined
132
+ /** Whether a data type's picker ignores the user's start nodes. */
133
+ ignoresStartNodes?: (dataTypeId: string) => Promise<boolean>
110
134
  /** A change to a page that people can subscribe to, and who made it (story 045). */
111
135
  onContentChange?: (change: RaisedContentChange, principal: Principal | undefined) => void
112
136
  }
@@ -140,6 +164,7 @@ export class ManagementApiRouter {
140
164
  readonly #onNotImplemented: RouterOptions['onNotImplemented']
141
165
  readonly #onServerEvent: RouterOptions['onServerEvent']
142
166
  readonly #nodes: NodeLookup | undefined
167
+ readonly #ignoresStartNodes: RouterOptions['ignoresStartNodes']
143
168
  readonly #allowLocalLogin: boolean
144
169
  readonly #audit: AuditSink | undefined
145
170
  readonly #clientAddress: (request: Request) => ClientAddress
@@ -157,6 +182,7 @@ export class ManagementApiRouter {
157
182
  this.#audit = options.audit
158
183
  this.#clientAddress = options.clientAddress ?? forwardedOnly
159
184
  this.#onError = options.onError
185
+ this.#ignoresStartNodes = options.ignoresStartNodes
160
186
  this.#onContentChange = options.onContentChange
161
187
  for (const operation of operations) {
162
188
  const segments = operation.path.split('/').filter((s) => s.length > 0)
@@ -226,6 +252,24 @@ export class ManagementApiRouter {
226
252
  return undefined
227
253
  }
228
254
 
255
+ /**
256
+ * The caller as a picker's request sees them: with root access, when the
257
+ * picker's data type ignores start nodes. Their permissions still apply.
258
+ */
259
+ async #forPicker(
260
+ operation: OperationInfo,
261
+ url: URL,
262
+ principal: Principal | undefined,
263
+ ): Promise<Principal | undefined> {
264
+ const dataTypeId = url.searchParams.get('dataTypeId')
265
+ if (!principal || !dataTypeId || !PICKER_OPERATIONS.has(operation.operationId)) return principal
266
+ if (!(await this.#ignoresStartNodes?.(dataTypeId))) return principal
267
+ return {
268
+ ...principal,
269
+ startNodes: { document: ROOT_ACCESS, media: ROOT_ACCESS, element: ROOT_ACCESS },
270
+ }
271
+ }
272
+
229
273
  async dispatch(request: Request): Promise<Response> {
230
274
  const url = new URL(request.url)
231
275
  const matched = this.match(request.method, url.pathname)
@@ -242,7 +286,7 @@ export class ManagementApiRouter {
242
286
 
243
287
  // Authorisation is driven by the contract: the document requires a
244
288
  // back-office user globally, and 10 operations opt out with `security: []`.
245
- const principal = await this.#authenticate?.(request)
289
+ const principal = await this.#forPicker(operation, url, await this.#authenticate?.(request))
246
290
  const anonymous =
247
291
  operation.anonymous ||
248
292
  (this.#allowLocalLogin && LOCAL_LOGIN_OPERATIONS.has(operation.operationId))
package/src/routes.ts CHANGED
@@ -70,6 +70,11 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
70
70
  clientAddress: options.clientAddress,
71
71
  onError: options.onError,
72
72
  onContentChange: options.onContentChange,
73
+ ignoresStartNodes: async (dataTypeId) => {
74
+ const dataType = await options.deps?.dataTypes?.byKey(dataTypeId).catch(() => undefined)
75
+ const setting = dataType?.values.find((v) => v.alias === 'ignoreUserStartNodes')?.value
76
+ return setting === true || setting === 'true' || setting === '1' || setting === 1
77
+ },
73
78
  })
74
79
  const { deps } = options
75
80
  if (!deps) return router