@crombolo/api-delivery 0.46.1 → 0.47.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.
Files changed (2) hide show
  1. package/package.json +4 -4
  2. package/src/handler.ts +80 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/api-delivery",
3
- "version": "0.46.1",
3
+ "version": "0.47.0",
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.46.1",
32
- "@crombolo/contracts": "0.46.1",
33
- "@crombolo/render": "0.46.1"
31
+ "@crombolo/core": "0.47.0",
32
+ "@crombolo/contracts": "0.47.0",
33
+ "@crombolo/render": "0.47.0"
34
34
  }
35
35
  }
package/src/handler.ts CHANGED
@@ -20,9 +20,15 @@ import {
20
20
  isRightToLeft,
21
21
  lifetimeFor,
22
22
  type MenuItem,
23
+ notModified,
23
24
  PRIVATE_NO_STORE,
25
+ publishedEtag,
26
+ RememberedAnswers,
27
+ rememberedHeaders,
24
28
  resolveCacheSettings,
25
29
  shortest,
30
+ unchanged,
31
+ validatorFor,
26
32
  } from '@crombolo/render'
27
33
  import { corsPolicy, isPreflight, preflightResponse, withCors } from './cors.ts'
28
34
  import {
@@ -79,6 +85,11 @@ export interface DeliveryApiPorts {
79
85
  preview?(request: Request, keyed: boolean): Promise<PreviewAccess | undefined>
80
86
  /** How long answers may be kept (story 057); nothing is kept when absent. */
81
87
  caching?: CacheSettings
88
+ /**
89
+ * What every answer's ETag is made from when it is not the body (story
90
+ * 258): the published content and the CMS, or undefined until it is known.
91
+ */
92
+ validatorBasis?(): string | undefined
82
93
  /**
83
94
  * A page's search and sharing details, worked out as `<SeoHead>` works them
84
95
  * out, for `seo=true` (story 055).
@@ -312,6 +323,47 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
312
323
  value: (alias) => media.value(alias),
313
324
  })
314
325
 
326
+ // Story 258: an answer's ETag from what was published, and the last one each address was given.
327
+ const published =
328
+ caching.validator === 'published' || [...caching.validators.values()].includes('published')
329
+ const remembered = new RememberedAnswers()
330
+ const started = new WeakMap<Request, { basis: string; guard: string }>()
331
+ const addressOf = (request: Request) => {
332
+ const url = new URL(request.url)
333
+ const varied = CONTENT_VARY.split(', ').map((name) => request.headers.get(name) ?? '')
334
+ return [url.pathname, url.search, ...varied].join('\u0000')
335
+ }
336
+ /** Who may see what: a check is answered only while it is as it was. */
337
+ const accessGuard = async () =>
338
+ Bun.hash(
339
+ JSON.stringify([
340
+ (await ports.protection()).map((rule) => JSON.stringify(rule)).sort(),
341
+ ((await ports.mediaRules?.()) ?? []).map((rule) => JSON.stringify(rule)).sort(),
342
+ ]),
343
+ ).toString(36)
344
+
345
+ /** Records what an answer is made from, before it is made; a `304` when that has not changed. */
346
+ async function begin(request: Request): Promise<Response | undefined> {
347
+ if (!published || (request.method !== 'GET' && request.method !== 'HEAD')) return undefined
348
+ if (isPreview(request) || personal(request, true, memberAuthorizationEnabled(settings)))
349
+ return undefined
350
+ const basis = ports.validatorBasis?.()
351
+ if (!basis) return undefined
352
+ const answer = request.headers.has('if-none-match')
353
+ ? remembered.get(addressOf(request))
354
+ : undefined
355
+ const guard = await accessGuard()
356
+ if (
357
+ answer &&
358
+ notModified(request, answer.etag) &&
359
+ answer.etag === publishedEtag([basis, addressOf(request)]) &&
360
+ answer.guard === guard
361
+ )
362
+ return unchanged(answer.headers)
363
+ started.set(request, { basis, guard })
364
+ return undefined
365
+ }
366
+
315
367
  /**
316
368
  * A public answer's lifetime, ETag and tags; a `304` when the caller holds it.
317
369
  * Anything that depends on who asks is never kept.
@@ -332,7 +384,31 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
332
384
  caching.site,
333
385
  )
334
386
  const tags = caching.tagHeader ? [...held.tags, ...keysIn(JSON.parse(body))] : undefined
335
- return cacheable(request, response, body, { lifetime, tags, tagHeader: caching.tagHeader })
387
+ const start = started.get(request)
388
+ // An answer holding a form carries a token signed for now, so its body is its validator.
389
+ const etag =
390
+ start &&
391
+ response.headers.get('cache-control') !== 'no-store' &&
392
+ validatorFor(
393
+ caching,
394
+ held.items.map((item) => item.typeAlias),
395
+ ) === 'published'
396
+ ? publishedEtag([start.basis, addressOf(request)])
397
+ : undefined
398
+ const answer = cacheable(request, response, body, {
399
+ lifetime,
400
+ tags,
401
+ tagHeader: caching.tagHeader,
402
+ etag,
403
+ checkFloor: caching.checkFloor,
404
+ })
405
+ if (start && etag)
406
+ remembered.set(addressOf(request), {
407
+ etag,
408
+ headers: rememberedHeaders(answer.headers, caching.tagHeader),
409
+ guard: start.guard,
410
+ })
411
+ return answer
336
412
  }
337
413
 
338
414
  /** The member a request's token names, when member sign-in is on. */
@@ -760,6 +836,9 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
760
836
  const security = /^v1\/security\/member\/(.+)$/.exec(rest)
761
837
  if (security) return ports.security?.(request, security[1] as string)
762
838
 
839
+ const kept = await begin(request)
840
+ if (kept) return kept
841
+
763
842
  if (/^v2\/search\/?$/.test(rest)) {
764
843
  if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
765
844
  if (!contentAccess(settings, request)) return bare(401)