@crombolo/api-management 0.22.0 → 0.24.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/api-management",
3
- "version": "0.22.0",
3
+ "version": "0.24.1",
4
4
  "description": "Umbraco-compatible Management API handlers for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,8 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.22.0",
32
- "@crombolo/contracts": "0.22.0"
31
+ "@crombolo/content": "0.24.1",
32
+ "@crombolo/contracts": "0.24.1",
33
+ "@crombolo/core": "0.24.1"
33
34
  }
34
35
  }
@@ -7,6 +7,7 @@
7
7
  * involved, which their port enforces. See docs/backoffice-hosting.md for the
8
8
  * tables' provenance.
9
9
  */
10
+ import { WRITE_VERBS as W } from '@crombolo/content/rules'
10
11
  import type { OperationInfo } from '@crombolo/contracts'
11
12
  import {
12
13
  type AppAlias,
@@ -17,12 +18,13 @@ import {
17
18
  hasPathAccess,
18
19
  MediaPermissions as M,
19
20
  permissionsForPath,
20
- propertyValuePermissions,
21
21
  type StartNodes,
22
22
  sectionKey,
23
23
  } from '@crombolo/core'
24
24
  import type { Principal } from './router.ts'
25
25
 
26
+ export { deniedPropertyWrite, type PropertyValueRef } from '@crombolo/content/rules'
27
+
26
28
  /**
27
29
  * Operations behind Umbraco's `DenyLocalLoginIfConfigured` policy: the contract
28
30
  * marks them secured, but while local login is allowed the policy lets anyone
@@ -241,6 +243,7 @@ interface DocumentRule {
241
243
  }
242
244
 
243
245
  const id: NodeRef = { param: 'id' }
246
+ // The writes take their verbs from the operations' table, which applies them again.
244
247
  const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
245
248
  GetDocumentById: [{ verbs: [D.Read], node: id }],
246
249
  GetDocumentByIdPublished: [{ verbs: [D.Read], node: id }],
@@ -259,48 +262,48 @@ const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
259
262
  // the parent is the same boundary expressed once: a caller who cannot reach the
260
263
  // parent's path cannot reach anything below it either.
261
264
  GetCollectionDocumentById: [{ verbs: [D.Read], node: id }],
262
- PostDocument: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
265
+ PostDocument: [{ verbs: W.create, node: { body: ['parent', 'id'] } }],
263
266
  PostDocumentValidate: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
264
- PutDocumentById: [{ verbs: [D.Update], node: id }],
265
- PatchDocumentByIdPatch: [{ verbs: [D.Update], node: id }],
267
+ PutDocumentById: [{ verbs: W.save, node: id }],
268
+ PatchDocumentByIdPatch: [{ verbs: W.save, node: id }],
266
269
  PutDocumentByIdValidate: [{ verbs: [D.Update], node: id }],
267
270
  PostDocumentCreateAndPublish: [
268
- { verbs: [D.Publish], node: { body: ['parent', 'id'] }, cultures: true },
271
+ { verbs: W.publish, node: { body: ['parent', 'id'] }, cultures: true },
269
272
  ],
270
- PutDocumentByIdUpdateAndPublish: [{ verbs: [D.Publish], node: id, cultures: true }],
271
- PutDocumentByIdPublish: [{ verbs: [D.Publish], node: id, cultures: true }],
273
+ PutDocumentByIdUpdateAndPublish: [{ verbs: W.publish, node: id, cultures: true }],
274
+ PutDocumentByIdPublish: [{ verbs: W.publish, node: id, cultures: true }],
272
275
  PutDocumentByIdPublishWithDescendants: [
273
- { verbs: [D.Publish], node: id, branch: true, cultures: true },
276
+ { verbs: W.publish, node: id, branch: true, cultures: true },
274
277
  ],
275
- PutDocumentByIdUnpublish: [{ verbs: [D.Unpublish], node: id, cultures: true }],
276
- DeleteDocumentById: [{ verbs: [D.Delete], node: id }],
277
- PutDocumentByIdMoveToRecycleBin: [{ verbs: [D.Delete], node: id }],
278
+ PutDocumentByIdUnpublish: [{ verbs: W.unpublish, node: id, cultures: true }],
279
+ DeleteDocumentById: [{ verbs: W.delete, node: id }],
280
+ PutDocumentByIdMoveToRecycleBin: [{ verbs: W.trash, node: id }],
278
281
  PutDocumentByIdMove: [
279
- { verbs: [D.Move], node: id },
280
- { verbs: [D.Create], node: { body: ['target', 'id'] } },
282
+ { verbs: W.move, node: id },
283
+ { verbs: W.intoTarget, node: { body: ['target', 'id'] } },
281
284
  ],
282
285
  PostDocumentByIdCopy: [
283
- { verbs: [D.Duplicate], node: id },
284
- { verbs: [D.Create], node: { body: ['target', 'id'] } },
286
+ { verbs: W.copy, node: id },
287
+ { verbs: W.intoTarget, node: { body: ['target', 'id'] } },
285
288
  ],
286
289
  PutDocumentSort: [
287
- { verbs: [D.Sort], node: { body: ['parent', 'id'] } },
288
- { verbs: [D.Sort], node: { body: ['sorting', '*', 'id'] } },
290
+ { verbs: W.sort, node: { body: ['parent', 'id'] } },
291
+ { verbs: W.sort, node: { body: ['sorting', '*', 'id'] } },
289
292
  ],
290
- PutDocumentByIdSortChildren: [{ verbs: [D.Sort], node: id }],
291
- PutDocumentRootSortChildren: [{ verbs: [D.Sort], node: 'root' }],
293
+ PutDocumentByIdSortChildren: [{ verbs: W.sort, node: id }],
294
+ PutDocumentRootSortChildren: [{ verbs: W.sort, node: 'root' }],
292
295
  GetDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
293
- PostDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
294
- PutDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
295
- DeleteDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
296
- PutDocumentByIdDomains: [{ verbs: [D.CultureAndHostnames], node: id }],
297
- PostDocumentVersionByIdRollback: [{ verbs: [D.Rollback], node: { version: 'id' } }],
296
+ PostDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
297
+ PutDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
298
+ DeleteDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
299
+ PutDocumentByIdDomains: [{ verbs: W.domains, node: id }],
300
+ PostDocumentVersionByIdRollback: [{ verbs: W.rollback, node: { version: 'id' } }],
298
301
  PostDocumentBlueprintFromDocument: [
299
302
  { verbs: [D.CreateBlueprint], node: { body: ['document', 'id'] } },
300
303
  ],
301
- DeleteRecycleBinDocument: [{ verbs: [D.Delete], node: 'bin' }],
302
- DeleteRecycleBinDocumentById: [{ verbs: [D.Delete], node: 'bin' }],
303
- PutRecycleBinDocumentByIdRestore: [{ verbs: [D.Move], node: 'bin' }],
304
+ DeleteRecycleBinDocument: [{ verbs: W.emptyBin, node: 'bin' }],
305
+ DeleteRecycleBinDocumentById: [{ verbs: W.delete, node: 'bin' }],
306
+ PutRecycleBinDocumentByIdRestore: [{ verbs: W.restore, node: 'bin' }],
304
307
  GetRecycleBinDocumentByIdOriginalParent: [{ verbs: [D.Read], node: 'bin' }],
305
308
  }
306
309
 
@@ -462,61 +465,6 @@ export function deniedChildren(principal: Principal, parentChain: readonly strin
462
465
  )
463
466
  }
464
467
 
465
- /** One property value as a save carries it. */
466
- export interface PropertyValueRef {
467
- alias: string
468
- culture: string | null
469
- segment: string | null
470
- value: unknown
471
- }
472
-
473
- /** JSON with object keys in order, so equal values compare equal however they were built. */
474
- const canonical = (value: unknown): string =>
475
- JSON.stringify(value ?? null, (_key, v) =>
476
- v && typeof v === 'object' && !Array.isArray(v)
477
- ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
478
- : v,
479
- )
480
-
481
- /** Each property's values by culture and segment, nulls left out: what a save would leave stored. */
482
- function valuesByAlias(values: readonly PropertyValueRef[]): Map<string, Map<string, string>> {
483
- const out = new Map<string, Map<string, string>>()
484
- for (const v of values) {
485
- if (v.value === null || v.value === undefined) continue
486
- const alias = v.alias.toLowerCase()
487
- const variants = out.get(alias) ?? new Map<string, string>()
488
- const where = `${v.culture?.toLowerCase() ?? ''}|${v.segment ?? ''}`
489
- if (!variants.has(where)) variants.set(where, canonical(v.value))
490
- out.set(alias, variants)
491
- }
492
- return out
493
- }
494
-
495
- /**
496
- * The first property a save would change that the caller's groups may not
497
- * write (`Umb.Document.PropertyValue.Write`, per property type), or undefined.
498
- * A value sent back as it was is not a change; one left out that was stored is.
499
- */
500
- export function deniedPropertyWrite<P extends { alias: string; key: string }>(
501
- principal: Principal,
502
- properties: readonly P[],
503
- before: readonly PropertyValueRef[],
504
- after: readonly PropertyValueRef[],
505
- ): P | undefined {
506
- const old = valuesByAlias(before)
507
- const next = valuesByAlias(after)
508
- for (const property of properties) {
509
- const alias = property.alias.toLowerCase()
510
- const a = old.get(alias) ?? new Map<string, string>()
511
- const b = next.get(alias) ?? new Map<string, string>()
512
- const changed = a.size !== b.size || [...a].some(([where, value]) => b.get(where) !== value)
513
- if (!changed) continue
514
- if (!propertyValuePermissions(principal.groups, property.key).has(D.PropertyValueWrite))
515
- return property
516
- }
517
- return undefined
518
- }
519
-
520
468
  /** Whether the caller may read a document's draft: the Content section, its path, and Read on it. */
521
469
  export async function canReadDocument(
522
470
  principal: Principal,
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The operations whose document writes go through `@crombolo/content` (story
3
+ * 170). Each announces itself — audit entry, webhook, notification, live event —
4
+ * from the operation, the same way the command line and the jobs do, so the
5
+ * router must not announce them a second time from the operation's name.
6
+ */
7
+ export const DOCUMENT_WRITE_OPERATIONS: ReadonlySet<string> = new Set([
8
+ 'PostDocument',
9
+ 'PutDocumentById',
10
+ 'PatchDocumentByIdPatch',
11
+ 'PostDocumentCreateAndPublish',
12
+ 'PutDocumentByIdUpdateAndPublish',
13
+ 'PutDocumentByIdPublish',
14
+ 'PutDocumentByIdUnpublish',
15
+ 'PutDocumentByIdPublishWithDescendants',
16
+ 'PutDocumentByIdMoveToRecycleBin',
17
+ 'DeleteDocumentById',
18
+ 'DeleteRecycleBinDocumentById',
19
+ 'DeleteRecycleBinDocument',
20
+ 'PutRecycleBinDocumentByIdRestore',
21
+ 'PutDocumentByIdMove',
22
+ 'PostDocumentByIdCopy',
23
+ 'PutDocumentSort',
24
+ 'PutDocumentByIdSortChildren',
25
+ 'PutDocumentRootSortChildren',
26
+ 'PostDocumentVersionByIdRollback',
27
+ 'PutDocumentByIdDomains',
28
+ 'PostDocumentByIdPublicAccess',
29
+ 'PutDocumentByIdPublicAccess',
30
+ 'DeleteDocumentByIdPublicAccess',
31
+ ])
@@ -2,6 +2,8 @@
2
2
  * Documents: the tree, the editor's read/write cycle, publishing and versions.
3
3
  */
4
4
 
5
+ import type { DocumentOperations, Precondition, Refusal } from '@crombolo/content'
6
+ import { userActor } from '@crombolo/content/rules'
5
7
  import type {
6
8
  DocumentAggregate,
7
9
  DocumentTreeItem,
@@ -19,9 +21,9 @@ import {
19
21
  problemResponse,
20
22
  ROOT_ACCESS,
21
23
  } from '@crombolo/core'
22
- import { deniedChildren, deniedPropertyWrite } from '../authorization.ts'
24
+ import { deniedChildren } from '../authorization.ts'
23
25
  import { APP_PREVIEW_PROVIDER, type PreviewPort } from '../ports.ts'
24
- import type { ApprovalGatePort, DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
26
+ import type { DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
25
27
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
26
28
  import { created, paging } from './content-type.ts'
27
29
  import {
@@ -274,48 +276,66 @@ export function toDocumentTreeItemResponse(item: DocumentTreeItem, noAccess = fa
274
276
  }
275
277
  }
276
278
 
279
+ /** A revision as an entity tag. */
280
+ const etag = (revision: string) => `"${revision}"`
281
+
282
+ /** Refusals about the copy being saved, titled as a save even when a publish followed. */
283
+ const SAVE_REFUSALS: ReadonlySet<Refusal['kind']> = new Set([
284
+ 'forbidden',
285
+ 'stale',
286
+ 'revisionRequired',
287
+ ])
288
+
289
+ const STALE_PATCH =
290
+ 'The page changed after the copy this patch was based on was read. Read it again, then patch that.'
291
+
277
292
  export function registerDocumentHandlers(
278
293
  router: ManagementApiRouter,
279
294
  port: DocumentPort,
295
+ operations: DocumentOperations,
280
296
  preview?: PreviewPort,
281
- approvals?: ApprovalGatePort,
282
297
  ): void {
283
298
  /** A page a workflow covers goes through it: the gate's refusal, as a problem. */
284
299
  const needsApproval = (title: string, detail: string) =>
285
300
  problemResponse(
286
301
  problemDetails({ title, status: 400, detail, operationStatus: 'NeedsApproval' }),
287
302
  )
288
- const principalOf = (ctx: RequestContext) => ctx.principal as NonNullable<typeof ctx.principal>
289
-
290
303
  /**
291
- * A 403 naming the first property the save would change that the caller's
292
- * groups may not write. Skipped when a group writes every property anyway.
304
+ * What the sender's copy was based on (story 172): `If-Match` names the
305
+ * revision a read answered with as its `ETag`; `*` says to replace whatever
306
+ * is there.
293
307
  */
294
- const propertyWriteRefusal = async (
295
- ctx: RequestContext,
296
- key: string,
297
- existing: DocumentAggregate | undefined,
298
- values: readonly DocumentValue[],
299
- ): Promise<Response | undefined> => {
300
- const principal = ctx.principal
301
- if (!principal || !existing || !port.propertyTypes) return undefined
302
- const writesAll = principal.groups.some(
303
- (group) =>
304
- !group.properties?.size && group.defaults.includes(DocumentPermissions.PropertyValueWrite),
305
- )
306
- if (writesAll) return undefined
307
- const denied = deniedPropertyWrite(
308
- principal,
309
- (await port.propertyTypes(key)) ?? [],
310
- existing.values,
311
- values,
312
- )
313
- if (!denied) return undefined
308
+ const preconditionOf = (ctx: RequestContext): Precondition => {
309
+ const header = ctx.request.headers.get('if-match')?.trim()
310
+ if (!header) return {}
311
+ if (header === '*') return { overwrite: true }
312
+ const first = (header.split(',')[0] ?? '').trim().replace(/^W\//, '')
313
+ return { expectedRevision: first.replace(/^"|"$/g, '') }
314
+ }
315
+ /** A 200 that tells the client which revision it now holds. */
316
+ const okWith = (revision: string | undefined) =>
317
+ new Response(null, { status: 200, headers: revision ? { ETag: etag(revision) } : {} })
318
+
319
+ /** The signed-in user, as the operations know them: their rules apply (story 170). */
320
+ const actorOf = (ctx: RequestContext) =>
321
+ userActor(ctx.principal as NonNullable<typeof ctx.principal>, ctx.client ?? {})
322
+
323
+ /** An operation's refusal as the problem the client reads; `approval` titles a gate refusal. */
324
+ const refused = (
325
+ result: Refusal,
326
+ title: string,
327
+ options: { sent?: readonly DocumentValue[]; approval?: string; operationStatus?: string } = {},
328
+ ) => {
329
+ if (result.kind === 'needsApproval')
330
+ return needsApproval(options.approval ?? title, result.reason)
331
+ if (result.kind === 'validation' && result.errors)
332
+ return problemResponse(validationProblem(result.errors, options.sent ?? []))
314
333
  return problemResponse(
315
334
  problemDetails({
316
- title: 'Could not save the document',
317
- status: 403,
318
- detail: `You may not change "${denied.name}" (${denied.alias}).`,
335
+ title,
336
+ status: result.status,
337
+ detail: result.reason,
338
+ ...(options.operationStatus ? { operationStatus: options.operationStatus } : {}),
319
339
  }),
320
340
  )
321
341
  }
@@ -329,7 +349,9 @@ export function registerDocumentHandlers(
329
349
  router.handle('GetDocumentById', async ({ params }) => {
330
350
  const aggregate = await port.byKey(params.id as string)
331
351
  if (!aggregate) return problemResponse(notFound('The document could not be found'))
332
- return Response.json(toDocumentResponse(aggregate))
352
+ return Response.json(toDocumentResponse(aggregate), {
353
+ headers: aggregate.revision ? { ETag: etag(aggregate.revision) } : {},
354
+ })
333
355
  })
334
356
 
335
357
  router.handle('GetDocumentByIdPublished', async ({ params }) => {
@@ -371,18 +393,12 @@ export function registerDocumentHandlers(
371
393
  const body = await readBody(ctx)
372
394
  const key = typeof body.id === 'string' && body.id ? body.id : crypto.randomUUID()
373
395
  const input = toSaveDocument(key, body)
374
- const refusal = await approvals?.newPageRefusal(
375
- principalOf(ctx),
376
- input.parentKey,
377
- input.contentTypeKey,
378
- )
379
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
380
- const result = await port.createAndPublish(
381
- input,
382
- readCultures(body),
383
- ctx.principal as NonNullable<typeof ctx.principal>,
384
- )
385
- if (!result.ok) return failureResponse('Could not create the document', result, input.values)
396
+ const result = await operations.createAndPublish(actorOf(ctx), input, readCultures(body))
397
+ if (!result.ok)
398
+ return refused(result, 'Could not create the document', {
399
+ sent: input.values,
400
+ approval: 'The document needs approval before it is published',
401
+ })
386
402
  return created(
387
403
  `${ctx.url.pathname.replace(/\/create-and-publish$/, '')}/${result.key}`,
388
404
  result.key,
@@ -393,25 +409,24 @@ export function registerDocumentHandlers(
393
409
  const body = await readBody(ctx)
394
410
  const key = ctx.params.id as string
395
411
  const input = toSaveDocument(key, body)
396
- const denied = await propertyWriteRefusal(ctx, key, await port.byKey(key), input.values)
397
- if (denied) return denied
398
- const refusal =
399
- (await approvals?.beforeSave(principalOf(ctx), key)) ??
400
- (await approvals?.publishRefusal(principalOf(ctx), key, 'publish'))
401
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
402
- const result = await port.updateAndPublish(
412
+ const result = await operations.saveAndPublish(
413
+ actorOf(ctx),
403
414
  key,
404
415
  input,
405
416
  readCultures(body),
406
- ctx.principal as NonNullable<typeof ctx.principal>,
417
+ preconditionOf(ctx),
407
418
  )
408
419
  if (!result.ok) {
409
- if (result.reason === 'The document could not be found.')
410
- return problemResponse(notFound(result.reason))
411
- return failureResponse('Could not publish the document', result, input.values)
420
+ if (result.kind === 'notFound') return problemResponse(notFound(result.reason))
421
+ return refused(
422
+ result,
423
+ SAVE_REFUSALS.has(result.kind)
424
+ ? 'Could not save the document'
425
+ : 'Could not publish the document',
426
+ { sent: input.values, approval: 'The document needs approval before it is published' },
427
+ )
412
428
  }
413
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
414
- return new Response(null, { status: 200 })
429
+ return okWith(result.revision)
415
430
  })
416
431
 
417
432
  router.handle('GetTreeDocumentAncestors', async (ctx) => {
@@ -510,19 +525,8 @@ export function registerDocumentHandlers(
510
525
  router.handle('PostDocument', async (ctx) => {
511
526
  const body = await readBody(ctx)
512
527
  const key = typeof body.id === 'string' && body.id ? body.id : crypto.randomUUID()
513
- const result = await port.create(
514
- toSaveDocument(key, body),
515
- ctx.principal as NonNullable<typeof ctx.principal>,
516
- )
517
- if (!result.ok) {
518
- return problemResponse(
519
- problemDetails({
520
- title: 'Could not create the document',
521
- status: result.status ?? 400,
522
- detail: result.reason,
523
- }),
524
- )
525
- }
528
+ const result = await operations.create(actorOf(ctx), toSaveDocument(key, body))
529
+ if (!result.ok) return refused(result, 'Could not create the document')
526
530
  ctx.notifications.push({ message: 'Document created', category: 'Content', type: 'Success' })
527
531
  return created(`${ctx.url.origin}/umbraco/management/api/v1/document/${result.key}`, result.key)
528
532
  })
@@ -532,39 +536,31 @@ export function registerDocumentHandlers(
532
536
  key: string,
533
537
  existing: DocumentAggregate,
534
538
  body: Record<string, unknown>,
539
+ precondition: Precondition,
535
540
  ) => {
536
- const denied = await propertyWriteRefusal(ctx, key, existing, readValues(body))
537
- if (denied) return denied
538
- const refusal = await approvals?.beforeSave(principalOf(ctx), key)
539
- if (refusal) return needsApproval('The document is waiting for approval', refusal)
540
- const result = await port.update(
541
+ const result = await operations.save(
542
+ actorOf(ctx),
541
543
  key,
542
544
  {
543
545
  ...toSaveDocument(key, body),
544
546
  // The content type never changes on update.
545
547
  contentTypeKey: existing.contentTypeKey,
546
548
  },
547
- ctx.principal as NonNullable<typeof ctx.principal>,
549
+ precondition,
548
550
  )
549
- if (!result.ok) {
550
- return problemResponse(
551
- problemDetails({
552
- title: 'Could not save the document',
553
- status: result.status ?? 400,
554
- detail: result.reason,
555
- }),
556
- )
557
- }
558
- await approvals?.afterSave(principalOf(ctx), key)
551
+ if (!result.ok)
552
+ return refused(result, 'Could not save the document', {
553
+ approval: 'The document is waiting for approval',
554
+ })
559
555
  ctx.notifications.push({ message: 'Document saved', category: 'Content', type: 'Success' })
560
- return new Response(null, { status: 200 })
556
+ return okWith(result.revision)
561
557
  }
562
558
 
563
559
  router.handle('PutDocumentById', async (ctx) => {
564
560
  const key = ctx.params.id as string
565
561
  const existing = await port.byKey(key)
566
562
  if (!existing) return problemResponse(notFound('The document could not be found'))
567
- return saveUpdate(ctx, key, existing, await readBody(ctx))
563
+ return saveUpdate(ctx, key, existing, await readBody(ctx), preconditionOf(ctx))
568
564
  })
569
565
 
570
566
  // JSON Patch over the update model, Umbraco's filter segments included; the
@@ -599,7 +595,18 @@ export function registerDocumentHandlers(
599
595
  )
600
596
  if (unknown)
601
597
  return invalid(`This document's type has no property "${String(unknown.alias)}".`, 422)
602
- return saveUpdate(ctx, key, existing, body)
598
+ // The patch applied to the copy read above, so the save is checked against
599
+ // that copy's revision: a change in between refuses it rather than being lost.
600
+ const sent = preconditionOf(ctx)
601
+ if (sent.expectedRevision !== undefined && sent.expectedRevision !== existing.revision)
602
+ return refused(
603
+ { ok: false, kind: 'stale', status: 412, reason: STALE_PATCH },
604
+ 'Could not save the document',
605
+ )
606
+ return saveUpdate(ctx, key, existing, body, {
607
+ ...sent,
608
+ expectedRevision: sent.expectedRevision ?? (sent.overwrite ? existing.revision : undefined),
609
+ })
603
610
  })
604
611
 
605
612
  router.handle('PutDocumentByIdPublish', async (ctx) => {
@@ -607,73 +614,50 @@ export function registerDocumentHandlers(
607
614
  if (!(await port.byKey(key)))
608
615
  return problemResponse(notFound('The document could not be found'))
609
616
  const body = await readBody(ctx)
610
- const refusal = await approvals?.publishRefusal(principalOf(ctx), key, 'publish')
611
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
612
617
  const schedules = readSchedules(body)
613
618
  if (schedules === 'invalid')
614
619
  return problemResponse(
615
620
  problemDetails({ title: 'A schedule date is not a valid date', status: 400 }),
616
621
  )
617
- const now = Date.now()
618
622
  // A future publish time schedules the variant instead of publishing it now.
619
- const later = (s: (typeof schedules)[number]) =>
620
- s.publishTime !== null && s.publishTime.getTime() > now
621
- if (schedules.length > 0)
622
- await port.schedule(
623
- key,
624
- schedules.map((s) => ({ ...s, publishTime: later(s) ? s.publishTime : null })),
625
- )
626
- const immediate = schedules.filter((s) => !later(s))
627
- if (schedules.length > 0 && immediate.length === 0) {
628
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'rescheduled it')
623
+ const result = await operations.publish(actorOf(ctx), key, {
624
+ cultures: readCultures(body),
625
+ schedules,
626
+ expectedRevision: preconditionOf(ctx).expectedRevision,
627
+ })
628
+ if (!result.ok)
629
+ return refused(result, 'Could not publish the document', {
630
+ approval: 'The document needs approval before it is published',
631
+ operationStatus: 'PathNotPublished',
632
+ })
633
+ if (result.scheduledOnly)
629
634
  ctx.notifications.push({
630
635
  message: 'Publishing scheduled',
631
636
  category: 'Content',
632
637
  type: 'Success',
633
638
  })
634
- return new Response(null, { status: 200 })
635
- }
636
- const cultures = immediate.some((s) => s.culture !== null)
637
- ? immediate.flatMap((s) => (s.culture === null ? [] : [s.culture]))
638
- : readCultures(body)
639
- const result = await port.publish(key, cultures)
640
- if (!result.ok) {
641
- return problemResponse(
642
- problemDetails({
643
- title: 'Could not publish the document',
644
- status: result.status ?? 400,
645
- detail: result.reason,
646
- operationStatus: 'PathNotPublished',
647
- }),
648
- )
649
- }
650
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
651
- return new Response(null, { status: 200 })
639
+ return okWith(result.revision)
652
640
  })
653
641
 
654
642
  router.handle('PutDocumentByIdUnpublish', async (ctx) => {
655
643
  const key = ctx.params.id as string
656
644
  if (!(await port.byKey(key)))
657
645
  return problemResponse(notFound('The document could not be found'))
658
- const refusal = await approvals?.publishRefusal(principalOf(ctx), key, 'unpublish')
659
- if (refusal) return needsApproval('Taking the document down needs approval', refusal)
660
- const result = await port.unpublish(key, readCultures(await readBody(ctx)))
661
- if (!result.ok) {
662
- return problemResponse(
663
- problemDetails({
664
- title: 'Could not unpublish the document',
665
- status: result.status ?? 400,
666
- detail: result.reason,
667
- }),
668
- )
669
- }
670
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'took it down')
646
+ const result = await operations.unpublish(actorOf(ctx), key, readCultures(await readBody(ctx)))
647
+ if (!result.ok)
648
+ return refused(result, 'Could not unpublish the document', {
649
+ approval: 'Taking the document down needs approval',
650
+ })
671
651
  return new Response(null, { status: 200 })
672
652
  })
673
653
 
674
654
  router.handle('PutDocumentByIdMoveToRecycleBin', async (ctx) => {
675
- const moved = await port.moveToRecycleBin(ctx.params.id as string)
676
- if (!moved) return problemResponse(notFound('The document could not be found'))
655
+ const moved = await operations.trash(actorOf(ctx), ctx.params.id as string)
656
+ if (!moved.ok) {
657
+ if (moved.kind === 'notFound')
658
+ return problemResponse(notFound('The document could not be found'))
659
+ return refused(moved, 'Could not move the document to the recycle bin')
660
+ }
677
661
  ctx.notifications.push({
678
662
  message: 'Moved to the recycle bin',
679
663
  category: 'Content',
@@ -683,8 +667,12 @@ export function registerDocumentHandlers(
683
667
  })
684
668
 
685
669
  router.handle('DeleteDocumentById', async (ctx) => {
686
- const removed = await port.remove(ctx.params.id as string)
687
- if (!removed) return problemResponse(notFound('The document could not be found'))
670
+ const removed = await operations.delete(actorOf(ctx), ctx.params.id as string)
671
+ if (!removed.ok) {
672
+ if (removed.kind === 'notFound')
673
+ return problemResponse(notFound('The document could not be found'))
674
+ return refused(removed, 'Could not delete the document')
675
+ }
688
676
  return new Response(null, { status: 200 })
689
677
  })
690
678
 
@@ -693,7 +681,7 @@ export function registerDocumentHandlers(
693
681
  const id = (value as Record<string, unknown>).id
694
682
  return typeof id === 'string' && id ? id : null
695
683
  }
696
- const failed = (title: string, result: PortFailure) =>
684
+ const failed = (title: string, result: PortFailure | Refusal) =>
697
685
  problemResponse(problemDetails({ title, status: result.status ?? 400, detail: result.reason }))
698
686
  const done = (ctx: RequestContext, message: string) => {
699
687
  ctx.notifications.push({ message, category: 'Content', type: 'Success' })
@@ -701,17 +689,23 @@ export function registerDocumentHandlers(
701
689
  }
702
690
 
703
691
  router.handle('PutDocumentByIdMove', async (ctx) => {
704
- const result = await port.move(ctx.params.id as string, refId((await readBody(ctx)).target))
692
+ const result = await operations.move(
693
+ actorOf(ctx),
694
+ ctx.params.id as string,
695
+ refId((await readBody(ctx)).target),
696
+ )
705
697
  return result.ok ? done(ctx, 'Document moved') : failed('Could not move the document', result)
706
698
  })
707
699
 
708
700
  router.handle('PostDocumentByIdCopy', async (ctx) => {
709
701
  const body = await readBody(ctx)
710
- const result = await port.copy(
702
+ const result = await operations.copy(
703
+ actorOf(ctx),
711
704
  ctx.params.id as string,
712
705
  refId(body.target),
713
- { includeDescendants: body.includeDescendants === true },
714
- ctx.principal as NonNullable<typeof ctx.principal>,
706
+ {
707
+ includeDescendants: body.includeDescendants === true,
708
+ },
715
709
  )
716
710
  if (!result.ok) return failed('Could not copy the document', result)
717
711
  ctx.notifications.push({ message: 'Document copied', category: 'Content', type: 'Success' })
@@ -726,7 +720,7 @@ export function registerDocumentHandlers(
726
720
  key: String(item.id ?? ''),
727
721
  sortOrder: Number(item.sortOrder ?? 0),
728
722
  }))
729
- const result = await port.sort(refId(body.parent), sorting)
723
+ const result = await operations.sort(actorOf(ctx), refId(body.parent), sorting)
730
724
  return result.ok ? done(ctx, 'Sort order saved') : failed('Could not sort', result)
731
725
  })
732
726
 
@@ -738,7 +732,8 @@ export function registerDocumentHandlers(
738
732
  return problemResponse(problemDetails({ title: 'Unknown sort field', status: 400 }))
739
733
  if (!['Ascending', 'Descending'].includes(direction))
740
734
  return problemResponse(problemDetails({ title: 'Unknown sort direction', status: 400 }))
741
- const result = await port.sortChildrenBy(
735
+ const result = await operations.sortChildrenBy(
736
+ actorOf(ctx),
742
737
  parentKey,
743
738
  field as 'Name' | 'CreateDate' | 'UpdateDate',
744
739
  direction as 'Ascending' | 'Descending',
@@ -751,24 +746,29 @@ export function registerDocumentHandlers(
751
746
  router.handle('PutRecycleBinDocumentByIdRestore', async (ctx) => {
752
747
  const body = await readBody(ctx)
753
748
  const target = 'target' in body ? refId(body.target) : undefined
754
- const result = await port.restore(ctx.params.id as string, target ?? undefined)
749
+ const result = await operations.restore(
750
+ actorOf(ctx),
751
+ ctx.params.id as string,
752
+ target ?? undefined,
753
+ )
755
754
  return result.ok ? done(ctx, 'Document restored') : failed('Could not restore', result)
756
755
  })
757
756
 
758
757
  router.handle('DeleteRecycleBinDocumentById', async (ctx) => {
759
- const key = ctx.params.id as string
760
- const document = await port.byKey(key)
761
- if (!document) return problemResponse(notFound('The document could not be found'))
762
- if (!document.isTrashed)
763
- return problemResponse(
764
- problemDetails({ title: 'The document is not in the recycle bin', status: 400 }),
765
- )
766
- await port.remove(key)
758
+ const result = await operations.delete(actorOf(ctx), ctx.params.id as string, { fromBin: true })
759
+ if (!result.ok) {
760
+ if (result.kind === 'notFound')
761
+ return problemResponse(notFound('The document could not be found'))
762
+ if (result.kind === 'invalid')
763
+ return problemResponse(problemDetails({ title: result.reason, status: 400 }))
764
+ return refused(result, 'Could not delete the document')
765
+ }
767
766
  return done(ctx, 'Document deleted')
768
767
  })
769
768
 
770
769
  router.handle('DeleteRecycleBinDocument', async (ctx) => {
771
- await port.emptyRecycleBin()
770
+ const result = await operations.emptyBin(actorOf(ctx))
771
+ if (!result.ok) return refused(result, 'Could not empty the recycle bin')
772
772
  return done(ctx, 'Recycle bin emptied')
773
773
  })
774
774
 
@@ -776,19 +776,18 @@ export function registerDocumentHandlers(
776
776
  const branchTasks = new Map<string, { documentKey: string }>()
777
777
  router.handle('PutDocumentByIdPublishWithDescendants', async (ctx) => {
778
778
  const key = ctx.params.id as string
779
- const refusal = await approvals?.branchRefusal(principalOf(ctx), key)
780
- if (refusal)
781
- return needsApproval('Part of this branch needs approval before it is published', refusal)
782
779
  const body = await readBody(ctx)
783
780
  const cultures = Array.isArray(body.cultures) ? (body.cultures as unknown[]).map(String) : []
784
- const result = await port.publishBranch(
781
+ const result = await operations.publishBranch(
782
+ actorOf(ctx),
785
783
  key,
786
784
  cultures.length > 0 ? cultures : null,
787
785
  body.includeUnpublishedDescendants === true,
788
786
  )
789
- if (!result.ok) return failed('Could not publish the branch', result)
790
- for (const published of result.published)
791
- await approvals?.afterDirectPublish?.(principalOf(ctx), published, 'published its branch')
787
+ if (!result.ok)
788
+ return refused(result, 'Could not publish the branch', {
789
+ approval: 'Part of this branch needs approval before it is published',
790
+ })
792
791
  const taskId = crypto.randomUUID()
793
792
  branchTasks.set(taskId, { documentKey: key })
794
793
  ctx.notifications.push({
@@ -823,7 +822,7 @@ export function registerDocumentHandlers(
823
822
  isoCode: String(d.isoCode ?? ''),
824
823
  }))
825
824
  : []
826
- const result = await port.setDomains(ctx.params.id as string, {
825
+ const result = await operations.setDomains(actorOf(ctx), ctx.params.id as string, {
827
826
  defaultIsoCode: typeof body.defaultIsoCode === 'string' ? body.defaultIsoCode : null,
828
827
  domains,
829
828
  })
@@ -842,6 +841,10 @@ export function registerDocumentHandlers(
842
841
  )
843
842
  case 'notFound':
844
843
  return problemResponse(notFound('The document could not be found'))
844
+ case 'forbidden':
845
+ return problemResponse(
846
+ problemDetails({ title: 'Could not save culture and hostnames', status: 403 }),
847
+ )
845
848
  case 'conflict':
846
849
  return problemResponse(
847
850
  problemDetails({
@@ -1035,9 +1038,16 @@ export function registerDocumentHandlers(
1035
1038
  })
1036
1039
 
1037
1040
  router.handle('PostDocumentVersionByIdRollback', async (ctx) => {
1038
- const rolled = await port.rollback(ctx.params.id as string)
1039
- if (!rolled) return problemResponse(notFound('The version could not be found'))
1040
- return new Response(null, { status: 200 })
1041
+ const rolled = await operations.rollback(actorOf(ctx), ctx.params.id as string, {
1042
+ expectedRevision: preconditionOf(ctx).expectedRevision,
1043
+ overwrite: true,
1044
+ })
1045
+ if (!rolled.ok) {
1046
+ if (rolled.kind === 'notFound')
1047
+ return problemResponse(notFound('The version could not be found'))
1048
+ return refused(rolled, 'Could not roll the document back')
1049
+ }
1050
+ return okWith(rolled.revision)
1041
1051
  })
1042
1052
 
1043
1053
  router.handle('PutDocumentVersionByIdPreventCleanup', async (ctx) => {
@@ -5,6 +5,8 @@
5
5
  * calls the mixture ambiguous and refuses it, and so do we, because the two are
6
6
  * different intentions and the editor offers them as a choice.
7
7
  */
8
+ import type { DocumentOperations } from '@crombolo/content'
9
+ import { userActor } from '@crombolo/content/rules'
8
10
  import { notFound, problemDetails, problemResponse } from '@crombolo/core'
9
11
  import type { PublicAccessPort, PublicAccessStatus } from '../ports-members.ts'
10
12
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
@@ -22,10 +24,14 @@ const names = (value: unknown): string[] =>
22
24
  : []
23
25
 
24
26
  /** Umbraco's `PublicAccessOperationStatus`, as the problem details the client reads. */
25
- function statusResponse(status: PublicAccessStatus, ok: () => Response): Response {
27
+ function statusResponse(status: PublicAccessStatus | 'forbidden', ok: () => Response): Response {
26
28
  switch (status) {
27
29
  case 'ok':
28
30
  return ok()
31
+ case 'forbidden':
32
+ return problemResponse(
33
+ problemDetails({ title: 'Could not change public access', status: 403 }),
34
+ )
29
35
  case 'content-not-found':
30
36
  return problemResponse(notFound('The document could not be found'))
31
37
  case 'login-node-not-found':
@@ -46,7 +52,11 @@ function statusResponse(status: PublicAccessStatus, ok: () => Response): Respons
46
52
  export function registerPublicAccessHandlers(
47
53
  router: ManagementApiRouter,
48
54
  port: PublicAccessPort,
55
+ /** Writes go through these when present, so they are announced as any document write is (story 170). */
56
+ operations?: DocumentOperations,
49
57
  ): void {
58
+ const actorOf = (ctx: RequestContext) =>
59
+ userActor(ctx.principal as NonNullable<typeof ctx.principal>, ctx.client ?? {})
50
60
  router.handle('GetDocumentByIdPublicAccess', async (ctx) => {
51
61
  const result = await port.entry(
52
62
  ctx.params.id as string,
@@ -57,7 +67,7 @@ export function registerPublicAccessHandlers(
57
67
  return Response.json(result.entry)
58
68
  })
59
69
 
60
- const write = async (ctx: RequestContext, ok: () => Response) => {
70
+ const write = async (ctx: RequestContext, ok: () => Response, change: 'added' | 'set') => {
61
71
  const body = await readBody(ctx)
62
72
  const login = refId(body.loginDocument)
63
73
  const error = refId(body.errorDocument)
@@ -82,25 +92,30 @@ export function registerPublicAccessHandlers(
82
92
  status: 400,
83
93
  }),
84
94
  )
85
- const status = await port.save(ctx.params.id as string, {
95
+ const input = {
86
96
  loginDocumentKey: login,
87
97
  errorDocumentKey: error,
88
98
  memberGroupNames,
89
99
  memberUserNames,
90
- })
100
+ }
101
+ const status = operations
102
+ ? await operations.setPublicAccess(actorOf(ctx), ctx.params.id as string, input, change)
103
+ : await port.save(ctx.params.id as string, input)
91
104
  return statusResponse(status, ok)
92
105
  }
93
106
 
94
107
  router.handle('PostDocumentByIdPublicAccess', (ctx) =>
95
- write(ctx, () => new Response(null, { status: 201 })),
108
+ write(ctx, () => new Response(null, { status: 201 }), 'added'),
96
109
  )
97
110
  router.handle('PutDocumentByIdPublicAccess', (ctx) =>
98
- write(ctx, () => new Response(null, { status: 200 })),
111
+ write(ctx, () => new Response(null, { status: 200 }), 'set'),
99
112
  )
100
113
 
101
114
  router.handle('DeleteDocumentByIdPublicAccess', async (ctx) =>
102
115
  statusResponse(
103
- await port.remove(ctx.params.id as string),
116
+ operations
117
+ ? await operations.removePublicAccess(actorOf(ctx), ctx.params.id as string)
118
+ : await port.remove(ctx.params.id as string),
104
119
  () => new Response(null, { status: 200 }),
105
120
  ),
106
121
  )
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './audit.ts'
2
2
  export * from './authorization.ts'
3
3
  export * from './divergences.ts'
4
+ export * from './document-writes.ts'
4
5
  export * from './handlers/content-type.ts'
5
6
  export * from './handlers/package.ts'
6
7
  export * from './handlers/settings-stubs.ts'
package/src/ports.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * drifts from the wire shape fails to compile.
8
8
  */
9
9
 
10
+ import type { DocumentOperations } from '@crombolo/content'
10
11
  import type { ResponseOf } from '@crombolo/contracts'
11
12
  import type { UploadSettings } from '@crombolo/core'
12
13
  import type {
@@ -280,6 +281,8 @@ export interface ManagementApiDeps {
280
281
  documents?: DocumentPort
281
282
  /** Approval workflows: the gate on publishing and saving a page a workflow covers. */
282
283
  approvals?: ApprovalGatePort
284
+ /** Every document write, with its rules and its events (story 170); required alongside `documents`. */
285
+ documentOperations?: DocumentOperations
283
286
  dictionary?: DictionaryPort
284
287
  userManagement?: UserPort
285
288
  userGroups?: UserGroupPort
package/src/router.ts CHANGED
@@ -25,13 +25,13 @@ import {
25
25
  auditReadsBody,
26
26
  } from './audit.ts'
27
27
  import { authorize, LOCAL_LOGIN_OPERATIONS, type NodeLookup } from './authorization.ts'
28
+ import { DOCUMENT_WRITE_OPERATIONS } from './document-writes.ts'
28
29
  import {
29
30
  changeReadsBody,
30
31
  contentChangeFor,
31
32
  type RaisedContentChange,
32
33
  } from './notification-events.ts'
33
34
  import { type ServerEvent, serverEventFor } from './server-events.ts'
34
- import { type RaisedWebhookEvent, webhookEventFor } from './webhook-events.ts'
35
35
 
36
36
  /**
37
37
  * Resolved back-office identity, assembled from a reference token plus the
@@ -77,6 +77,8 @@ export interface RequestContext {
77
77
  principal: Principal | undefined
78
78
  /** Node positions, for a handler that filters what it returns per node. */
79
79
  nodes?: NodeLookup
80
+ /** Where the request came from, for an operation's audit entry. */
81
+ client?: ClientAddress
80
82
  }
81
83
 
82
84
  export type Authenticator = (request: Request) => Promise<Principal | undefined>
@@ -99,8 +101,6 @@ export interface RouterOptions {
99
101
  clientAddress?: (request: Request) => ClientAddress
100
102
  /** Answers an error a handler threw; undefined lets it propagate. */
101
103
  onError?: (error: unknown) => Response | undefined
102
- /** Told about every webhook event a successful operation raises. */
103
- onWebhookEvent?: (event: RaisedWebhookEvent) => void
104
104
  /** A change to a page that people can subscribe to, and who made it (story 045). */
105
105
  onContentChange?: (change: RaisedContentChange, principal: Principal | undefined) => void
106
106
  }
@@ -138,7 +138,6 @@ export class ManagementApiRouter {
138
138
  readonly #audit: AuditSink | undefined
139
139
  readonly #clientAddress: (request: Request) => ClientAddress
140
140
  readonly #onError: RouterOptions['onError']
141
- readonly #onWebhookEvent: RouterOptions['onWebhookEvent']
142
141
  readonly #onContentChange: RouterOptions['onContentChange']
143
142
 
144
143
  constructor(options: RouterOptions = {}) {
@@ -152,7 +151,6 @@ export class ManagementApiRouter {
152
151
  this.#audit = options.audit
153
152
  this.#clientAddress = options.clientAddress ?? forwardedOnly
154
153
  this.#onError = options.onError
155
- this.#onWebhookEvent = options.onWebhookEvent
156
154
  this.#onContentChange = options.onContentChange
157
155
  for (const operation of operations) {
158
156
  const segments = operation.path.split('/').filter((s) => s.length > 0)
@@ -251,7 +249,10 @@ export class ManagementApiRouter {
251
249
 
252
250
  const handler = this.#handlers.get(operation.operationId)
253
251
  if (!handler) this.#onNotImplemented?.(operation, request)
254
- const plan = handler && this.#audit ? auditPlanFor(operation.operationId) : undefined
252
+ // A document write announces itself from its operation (story 170).
253
+ const announces = !DOCUMENT_WRITE_OPERATIONS.has(operation.operationId)
254
+ const plan =
255
+ handler && this.#audit && announces ? auditPlanFor(operation.operationId) : undefined
255
256
  const audit = plan ? await this.#beforeAudit(plan, params, request) : undefined
256
257
  const changeBody =
257
258
  handler && this.#onContentChange && changeReadsBody(operation.operationId)
@@ -269,19 +270,16 @@ export class ManagementApiRouter {
269
270
  notifications,
270
271
  principal,
271
272
  nodes: this.#nodes,
273
+ client: this.#clientAddress(request),
272
274
  })
273
275
  : problemResponse(notImplemented(operation.operationId))
274
276
  if (plan && audit && response.status >= 200 && response.status < 300)
275
277
  await this.#recordAudit(plan, audit, params, request, response, principal)
276
- if (handler && this.#onServerEvent) {
278
+ if (handler && announces && this.#onServerEvent) {
277
279
  const event = serverEventFor(operation, params, response)
278
280
  if (event) this.#onServerEvent(event)
279
281
  }
280
- if (handler && this.#onWebhookEvent) {
281
- const event = webhookEventFor(operation.operationId, params, response)
282
- if (event) this.#onWebhookEvent(event)
283
- }
284
- if (handler && this.#onContentChange) {
282
+ if (handler && announces && this.#onContentChange) {
285
283
  const change = contentChangeFor(operation.operationId, params, response, changeBody)
286
284
  if (change) this.#onContentChange(change, principal)
287
285
  }
package/src/routes.ts CHANGED
@@ -56,7 +56,6 @@ export interface ManagementApiOptions {
56
56
  audit?: RouterOptions['audit']
57
57
  clientAddress?: RouterOptions['clientAddress']
58
58
  onError?: RouterOptions['onError']
59
- onWebhookEvent?: RouterOptions['onWebhookEvent']
60
59
  onContentChange?: RouterOptions['onContentChange']
61
60
  }
62
61
 
@@ -70,7 +69,6 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
70
69
  audit: options.audit,
71
70
  clientAddress: options.clientAddress,
72
71
  onError: options.onError,
73
- onWebhookEvent: options.onWebhookEvent,
74
72
  onContentChange: options.onContentChange,
75
73
  })
76
74
  const { deps } = options
@@ -98,7 +96,8 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
98
96
  if (deps.dataTypes) registerDataTypeHandlers(router, deps.dataTypes)
99
97
  if (deps.templates) registerTemplateHandlers(router, deps.templates)
100
98
  if (deps.templateQuery) registerTemplateQueryHandlers(router, deps.templateQuery)
101
- if (deps.documents) registerDocumentHandlers(router, deps.documents, deps.preview, deps.approvals)
99
+ if (deps.documents && deps.documentOperations)
100
+ registerDocumentHandlers(router, deps.documents, deps.documentOperations, deps.preview)
102
101
  if (deps.blueprints) registerDocumentBlueprintHandlers(router, deps.blueprints)
103
102
  if (deps.temporaryFiles) registerTemporaryFileHandlers(router, deps.temporaryFiles)
104
103
  if (deps.media) registerMediaHandlers(router, deps.media)
@@ -121,7 +120,8 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
121
120
  if (deps.temporaryFiles) registerImportHandlers(router, deps.temporaryFiles)
122
121
  if (deps.memberGroups) registerMemberGroupHandlers(router, deps.memberGroups)
123
122
  if (deps.members) registerMemberHandlers(router, deps.members)
124
- if (deps.publicAccess) registerPublicAccessHandlers(router, deps.publicAccess)
123
+ if (deps.publicAccess)
124
+ registerPublicAccessHandlers(router, deps.publicAccess, deps.documentOperations)
125
125
  if (deps.elements) registerElementHandlers(router, deps.elements, deps.references)
126
126
  registerAuditLogHandlers(
127
127
  router,
@@ -24,6 +24,12 @@ export const WEBHOOK_EVENTS: readonly WebhookEventInfo[] = [
24
24
  },
25
25
  { alias: 'Umbraco.ContentMoved', eventName: 'Content Moved', eventType: 'Content' },
26
26
  { alias: 'Umbraco.ContentCopied', eventName: 'Content Copied', eventType: 'Content' },
27
+ { alias: 'Umbraco.ContentSorted', eventName: 'Content Sorted', eventType: 'Content' },
28
+ {
29
+ alias: 'Umbraco.ContentRolledBack',
30
+ eventName: 'Content Rolled Back',
31
+ eventType: 'Content',
32
+ },
27
33
  { alias: 'Umbraco.MediaSave', eventName: 'Media Saved', eventType: 'Media' },
28
34
  { alias: 'Umbraco.MediaDelete', eventName: 'Media Deleted', eventType: 'Media' },
29
35
  ]
@@ -37,38 +43,3 @@ export interface RaisedWebhookEvent {
37
43
  alias: string
38
44
  key: string
39
45
  }
40
-
41
- const BY_OPERATION: Record<string, string> = {
42
- PostDocument: 'Umbraco.ContentSaved',
43
- PutDocumentById: 'Umbraco.ContentSaved',
44
- PutDocumentByIdPublish: 'Umbraco.ContentPublish',
45
- PutDocumentByIdPublishWithDescendants: 'Umbraco.ContentPublish',
46
- PostDocumentCreateAndPublish: 'Umbraco.ContentPublish',
47
- PutDocumentByIdUpdateAndPublish: 'Umbraco.ContentPublish',
48
- PutDocumentByIdUnpublish: 'Umbraco.ContentUnpublish',
49
- DeleteDocumentById: 'Umbraco.ContentDelete',
50
- DeleteRecycleBinDocumentById: 'Umbraco.ContentDelete',
51
- PutDocumentByIdMoveToRecycleBin: 'Umbraco.ContentMovedToRecycleBin',
52
- PutDocumentByIdMove: 'Umbraco.ContentMoved',
53
- PostDocumentByIdCopy: 'Umbraco.ContentCopied',
54
- PostMedia: 'Umbraco.MediaSave',
55
- PutMediaById: 'Umbraco.MediaSave',
56
- DeleteMediaById: 'Umbraco.MediaDelete',
57
- DeleteRecycleBinMediaById: 'Umbraco.MediaDelete',
58
- }
59
-
60
- /**
61
- * The event a successful operation raises, if any. Pure. The item is the one
62
- * the operation created (its generated-resource header) or the one it names.
63
- */
64
- export function webhookEventFor(
65
- operationId: string,
66
- params: Readonly<Record<string, string>>,
67
- response: Pick<Response, 'status' | 'headers'>,
68
- ): RaisedWebhookEvent | undefined {
69
- if (response.status < 200 || response.status >= 300) return undefined
70
- const alias = BY_OPERATION[operationId]
71
- if (!alias) return undefined
72
- const key = response.headers.get('umb-generated-resource') ?? params.id
73
- return key ? { alias, key: key.toLowerCase() } : undefined
74
- }