@crombolo/api-management 0.23.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.23.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,8 +28,8 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/content": "0.23.0",
32
- "@crombolo/contracts": "0.23.0",
33
- "@crombolo/core": "0.23.0"
31
+ "@crombolo/content": "0.24.1",
32
+ "@crombolo/contracts": "0.24.1",
33
+ "@crombolo/core": "0.24.1"
34
34
  }
35
35
  }
@@ -2,7 +2,7 @@
2
2
  * Documents: the tree, the editor's read/write cycle, publishing and versions.
3
3
  */
4
4
 
5
- import type { DocumentOperations, Refusal } from '@crombolo/content'
5
+ import type { DocumentOperations, Precondition, Refusal } from '@crombolo/content'
6
6
  import { userActor } from '@crombolo/content/rules'
7
7
  import type {
8
8
  DocumentAggregate,
@@ -276,6 +276,19 @@ export function toDocumentTreeItemResponse(item: DocumentTreeItem, noAccess = fa
276
276
  }
277
277
  }
278
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
+
279
292
  export function registerDocumentHandlers(
280
293
  router: ManagementApiRouter,
281
294
  port: DocumentPort,
@@ -287,6 +300,22 @@ export function registerDocumentHandlers(
287
300
  problemResponse(
288
301
  problemDetails({ title, status: 400, detail, operationStatus: 'NeedsApproval' }),
289
302
  )
303
+ /**
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.
307
+ */
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
+
290
319
  /** The signed-in user, as the operations know them: their rules apply (story 170). */
291
320
  const actorOf = (ctx: RequestContext) =>
292
321
  userActor(ctx.principal as NonNullable<typeof ctx.principal>, ctx.client ?? {})
@@ -320,7 +349,9 @@ export function registerDocumentHandlers(
320
349
  router.handle('GetDocumentById', async ({ params }) => {
321
350
  const aggregate = await port.byKey(params.id as string)
322
351
  if (!aggregate) return problemResponse(notFound('The document could not be found'))
323
- return Response.json(toDocumentResponse(aggregate))
352
+ return Response.json(toDocumentResponse(aggregate), {
353
+ headers: aggregate.revision ? { ETag: etag(aggregate.revision) } : {},
354
+ })
324
355
  })
325
356
 
326
357
  router.handle('GetDocumentByIdPublished', async ({ params }) => {
@@ -378,18 +409,24 @@ export function registerDocumentHandlers(
378
409
  const body = await readBody(ctx)
379
410
  const key = ctx.params.id as string
380
411
  const input = toSaveDocument(key, body)
381
- const result = await operations.saveAndPublish(actorOf(ctx), key, input, readCultures(body))
412
+ const result = await operations.saveAndPublish(
413
+ actorOf(ctx),
414
+ key,
415
+ input,
416
+ readCultures(body),
417
+ preconditionOf(ctx),
418
+ )
382
419
  if (!result.ok) {
383
420
  if (result.kind === 'notFound') return problemResponse(notFound(result.reason))
384
421
  return refused(
385
422
  result,
386
- result.kind === 'forbidden'
423
+ SAVE_REFUSALS.has(result.kind)
387
424
  ? 'Could not save the document'
388
425
  : 'Could not publish the document',
389
426
  { sent: input.values, approval: 'The document needs approval before it is published' },
390
427
  )
391
428
  }
392
- return new Response(null, { status: 200 })
429
+ return okWith(result.revision)
393
430
  })
394
431
 
395
432
  router.handle('GetTreeDocumentAncestors', async (ctx) => {
@@ -499,25 +536,31 @@ export function registerDocumentHandlers(
499
536
  key: string,
500
537
  existing: DocumentAggregate,
501
538
  body: Record<string, unknown>,
539
+ precondition: Precondition,
502
540
  ) => {
503
- const result = await operations.save(actorOf(ctx), key, {
504
- ...toSaveDocument(key, body),
505
- // The content type never changes on update.
506
- contentTypeKey: existing.contentTypeKey,
507
- })
541
+ const result = await operations.save(
542
+ actorOf(ctx),
543
+ key,
544
+ {
545
+ ...toSaveDocument(key, body),
546
+ // The content type never changes on update.
547
+ contentTypeKey: existing.contentTypeKey,
548
+ },
549
+ precondition,
550
+ )
508
551
  if (!result.ok)
509
552
  return refused(result, 'Could not save the document', {
510
553
  approval: 'The document is waiting for approval',
511
554
  })
512
555
  ctx.notifications.push({ message: 'Document saved', category: 'Content', type: 'Success' })
513
- return new Response(null, { status: 200 })
556
+ return okWith(result.revision)
514
557
  }
515
558
 
516
559
  router.handle('PutDocumentById', async (ctx) => {
517
560
  const key = ctx.params.id as string
518
561
  const existing = await port.byKey(key)
519
562
  if (!existing) return problemResponse(notFound('The document could not be found'))
520
- return saveUpdate(ctx, key, existing, await readBody(ctx))
563
+ return saveUpdate(ctx, key, existing, await readBody(ctx), preconditionOf(ctx))
521
564
  })
522
565
 
523
566
  // JSON Patch over the update model, Umbraco's filter segments included; the
@@ -552,7 +595,18 @@ export function registerDocumentHandlers(
552
595
  )
553
596
  if (unknown)
554
597
  return invalid(`This document's type has no property "${String(unknown.alias)}".`, 422)
555
- 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
+ })
556
610
  })
557
611
 
558
612
  router.handle('PutDocumentByIdPublish', async (ctx) => {
@@ -569,6 +623,7 @@ export function registerDocumentHandlers(
569
623
  const result = await operations.publish(actorOf(ctx), key, {
570
624
  cultures: readCultures(body),
571
625
  schedules,
626
+ expectedRevision: preconditionOf(ctx).expectedRevision,
572
627
  })
573
628
  if (!result.ok)
574
629
  return refused(result, 'Could not publish the document', {
@@ -581,7 +636,7 @@ export function registerDocumentHandlers(
581
636
  category: 'Content',
582
637
  type: 'Success',
583
638
  })
584
- return new Response(null, { status: 200 })
639
+ return okWith(result.revision)
585
640
  })
586
641
 
587
642
  router.handle('PutDocumentByIdUnpublish', async (ctx) => {
@@ -983,13 +1038,16 @@ export function registerDocumentHandlers(
983
1038
  })
984
1039
 
985
1040
  router.handle('PostDocumentVersionByIdRollback', async (ctx) => {
986
- const rolled = await operations.rollback(actorOf(ctx), ctx.params.id as string)
1041
+ const rolled = await operations.rollback(actorOf(ctx), ctx.params.id as string, {
1042
+ expectedRevision: preconditionOf(ctx).expectedRevision,
1043
+ overwrite: true,
1044
+ })
987
1045
  if (!rolled.ok) {
988
1046
  if (rolled.kind === 'notFound')
989
1047
  return problemResponse(notFound('The version could not be found'))
990
1048
  return refused(rolled, 'Could not roll the document back')
991
1049
  }
992
- return new Response(null, { status: 200 })
1050
+ return okWith(rolled.revision)
993
1051
  })
994
1052
 
995
1053
  router.handle('PutDocumentVersionByIdPreventCleanup', async (ctx) => {
package/src/router.ts CHANGED
@@ -32,7 +32,6 @@ import {
32
32
  type RaisedContentChange,
33
33
  } from './notification-events.ts'
34
34
  import { type ServerEvent, serverEventFor } from './server-events.ts'
35
- import { type RaisedWebhookEvent, webhookEventFor } from './webhook-events.ts'
36
35
 
37
36
  /**
38
37
  * Resolved back-office identity, assembled from a reference token plus the
@@ -102,8 +101,6 @@ export interface RouterOptions {
102
101
  clientAddress?: (request: Request) => ClientAddress
103
102
  /** Answers an error a handler threw; undefined lets it propagate. */
104
103
  onError?: (error: unknown) => Response | undefined
105
- /** Told about every webhook event a successful operation raises. */
106
- onWebhookEvent?: (event: RaisedWebhookEvent) => void
107
104
  /** A change to a page that people can subscribe to, and who made it (story 045). */
108
105
  onContentChange?: (change: RaisedContentChange, principal: Principal | undefined) => void
109
106
  }
@@ -141,7 +138,6 @@ export class ManagementApiRouter {
141
138
  readonly #audit: AuditSink | undefined
142
139
  readonly #clientAddress: (request: Request) => ClientAddress
143
140
  readonly #onError: RouterOptions['onError']
144
- readonly #onWebhookEvent: RouterOptions['onWebhookEvent']
145
141
  readonly #onContentChange: RouterOptions['onContentChange']
146
142
 
147
143
  constructor(options: RouterOptions = {}) {
@@ -155,7 +151,6 @@ export class ManagementApiRouter {
155
151
  this.#audit = options.audit
156
152
  this.#clientAddress = options.clientAddress ?? forwardedOnly
157
153
  this.#onError = options.onError
158
- this.#onWebhookEvent = options.onWebhookEvent
159
154
  this.#onContentChange = options.onContentChange
160
155
  for (const operation of operations) {
161
156
  const segments = operation.path.split('/').filter((s) => s.length > 0)
@@ -284,10 +279,6 @@ export class ManagementApiRouter {
284
279
  const event = serverEventFor(operation, params, response)
285
280
  if (event) this.#onServerEvent(event)
286
281
  }
287
- if (handler && announces && this.#onWebhookEvent) {
288
- const event = webhookEventFor(operation.operationId, params, response)
289
- if (event) this.#onWebhookEvent(event)
290
- }
291
282
  if (handler && announces && this.#onContentChange) {
292
283
  const change = contentChangeFor(operation.operationId, params, response, changeBody)
293
284
  if (change) this.#onContentChange(change, principal)
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
@@ -43,38 +43,3 @@ export interface RaisedWebhookEvent {
43
43
  alias: string
44
44
  key: string
45
45
  }
46
-
47
- const BY_OPERATION: Record<string, string> = {
48
- PostDocument: 'Umbraco.ContentSaved',
49
- PutDocumentById: 'Umbraco.ContentSaved',
50
- PutDocumentByIdPublish: 'Umbraco.ContentPublish',
51
- PutDocumentByIdPublishWithDescendants: 'Umbraco.ContentPublish',
52
- PostDocumentCreateAndPublish: 'Umbraco.ContentPublish',
53
- PutDocumentByIdUpdateAndPublish: 'Umbraco.ContentPublish',
54
- PutDocumentByIdUnpublish: 'Umbraco.ContentUnpublish',
55
- DeleteDocumentById: 'Umbraco.ContentDelete',
56
- DeleteRecycleBinDocumentById: 'Umbraco.ContentDelete',
57
- PutDocumentByIdMoveToRecycleBin: 'Umbraco.ContentMovedToRecycleBin',
58
- PutDocumentByIdMove: 'Umbraco.ContentMoved',
59
- PostDocumentByIdCopy: 'Umbraco.ContentCopied',
60
- PostMedia: 'Umbraco.MediaSave',
61
- PutMediaById: 'Umbraco.MediaSave',
62
- DeleteMediaById: 'Umbraco.MediaDelete',
63
- DeleteRecycleBinMediaById: 'Umbraco.MediaDelete',
64
- }
65
-
66
- /**
67
- * The event a successful operation raises, if any. Pure. The item is the one
68
- * the operation created (its generated-resource header) or the one it names.
69
- */
70
- export function webhookEventFor(
71
- operationId: string,
72
- params: Readonly<Record<string, string>>,
73
- response: Pick<Response, 'status' | 'headers'>,
74
- ): RaisedWebhookEvent | undefined {
75
- if (response.status < 200 || response.status >= 300) return undefined
76
- const alias = BY_OPERATION[operationId]
77
- if (!alias) return undefined
78
- const key = response.headers.get('umb-generated-resource') ?? params.id
79
- return key ? { alias, key: key.toLowerCase() } : undefined
80
- }