npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@klnap/cache-invalidation

v0.4.2

Published

Declarative, type-safe cache invalidation across applications with a framework-independent event protocol and native Payload CMS, HTTP, and Next.js integrations.

Readme

@klnap/cache-invalidation

Event-driven cache invalidation for independent applications, with CloudEvents, signed HTTP delivery, and optional Payload CMS and Next.js integrations.

Pre-1.0: The public API may change before version 1.0. Pin an exact package version and review the changelog before upgrading. When upgrading producer and consumer applications independently, verify their event and transport compatibility.

Contents

Features

  • Framework-independent CloudEvents producers and dispatcher contracts.
  • Automatic public-content change detection in Payload CMS.
  • Support for drafts, publication, localization, and media dependencies.
  • Named HTTP destinations with event filtering, batching, retries, and signed requests.
  • Authenticated HTTP consumers with Standard Schema validation.
  • Declarative, type-safe Next.js cache tags and paths.
  • Automatic invalidation of previous and current resource representations.
  • Programmable cache rules and application-owned executors.
  • Explicit transaction-aware deferral for application-owned Payload transactions.
  • Bounded request processing and structured delivery outcomes.

The package does not provide a cache store, durable message queue, event broker, or workflow engine.

Installation

bun add --exact @klnap/cache-invalidation

Or with npm:

npm install --save-exact @klnap/cache-invalidation

@klnap/revalidation is the former name of this package. It is deprecated on npm; install @klnap/cache-invalidation instead.

Compatibility

| Dependency | Supported versions | | --- | --- | | Node.js | ^22.23.5 \|\| ^24.22.3 \|\| >=26.13.1 | | Payload CMS | >=3.94.1 <4 | | Next.js | >=16.4.5 <17 |

Payload and Next.js are optional peer dependencies. Install them only in applications using their respective integrations.

The package is ESM. Bun is used for repository development but is not required by the package.

Architecture

Producer
    |
    | CloudEvents
    v
Dispatcher
    |
    | Signed HTTP or application-owned transport
    v
Consumer
    |
    | Application-specific operations
    v
Cache

A producer describes a change. A dispatcher delivers the event. A consumer determines which of its own cache resources need invalidation.

The package separates these responsibilities so that applications can evolve their cache strategies without coupling producers to consumer implementations.

| Entrypoint | Responsibility | | --- | --- | | @klnap/cache-invalidation | Generic producer, protocol contracts, schemas, errors, and delivery outcomes | | @klnap/cache-invalidation/producers/payload | Payload CMS producer | | @klnap/cache-invalidation/dispatchers | Dispatcher implementations | | @klnap/cache-invalidation/dispatchers/http | Signed HTTP dispatcher | | @klnap/cache-invalidation/consumers/http | Framework-independent HTTP consumer | | @klnap/cache-invalidation/consumers/next | Next.js cache definitions and Route Handler |

Generic producers, HTTP dispatchers, and generic HTTP consumers do not require Payload or Next.js.

Quick start

Payload CMS to Next.js

This integration connects independently deployed Payload and Next.js applications.

1. Configure a signing secret

Generate a Standard Webhooks secret:

printf 'whsec_%s\n' "$(openssl rand -base64 32 | tr -d '\n')"

Store the generated value as CACHE_INVALIDATION_SECRET in both applications.

In Payload, also configure CACHE_INVALIDATION_URL with the full URL of the Next.js invalidation endpoint, for example:

CACHE_INVALIDATION_URL=https://www.example.com/api/invalidate

Keep signing secrets in server-side environment configuration.

2. Configure Payload

Add the producer plugin to your existing Payload configuration:

import { cacheInvalidation } from '@klnap/cache-invalidation/producers/payload'
import { http } from '@klnap/cache-invalidation/dispatchers/http'

const plugin = cacheInvalidation({
  source: 'https://cms.example.com',
  collections: {
    products: true,
  },
  dispatcher: http({
    targets: {
      website: {
        url: process.env.CACHE_INVALIDATION_URL!,
        secret: process.env.CACHE_INVALIDATION_SECRET!,
      },
    },
  }),
})

Include plugin in the plugins array of your Payload configuration.

The products collection must already exist in your application.

Only opted-in resources produce ordinary collection or global change events.

3. Define the Next.js cache

Create src/cache.ts:

import 'server-only'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'

export const cache = defineCache({
  tags: {
    products: 'products',
    product: 'product:[id]',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [
      tags.products,
      tags.product,
    ],
  }),
})

This definition invalidates the product listing and the affected product detail cache when public product content changes.

4. Create the Route Handler

Create app/api/invalidate/route.ts:

import { createCacheInvalidationHandler } from '@klnap/cache-invalidation/consumers/next'
import { cache } from '@/cache'

export const POST = createCacheInvalidationHandler({
  config: cache.config,
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://cms.example.com'],
})

The handler authenticates the request, validates its events, plans cache operations, and invokes native Next.js cache APIs.

5. Tag cached data

Use the same cache helpers when attaching tags:

import { cacheTag } from 'next/cache'
import { cache } from '@/cache'
import { loadProduct, loadProducts } from '@/data/products'

export async function getProducts() {
  'use cache'

  cacheTag(cache.tags.products())
  return loadProducts()
}

export async function getProduct(id: string) {
  'use cache'

  cacheTag(cache.tags.product({ id }))
  return loadProduct(id)
}

The data-loading functions are application-owned.

Enable Cache Components in your Next.js configuration:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

Configure additional Next.js options, including partialPrefetching, according to your application's Next.js version and requirements. They are not cache-invalidation package options.

6. Verify invalidation

Load a product page to populate its cache. Update and publish the product in Payload, then revisit the page after the invalidation request has been processed.

The product listing and affected product cache should reflect the changed public content.

Automatic Payload delivery is asynchronous and best effort. It is not a database commit notification. Applications requiring confirmed commit ordering must use the transaction deferral workflow.

A successful webhook response does not imply that every affected route has already regenerated.

Framework-independent integration

Neither Payload nor Next.js is required.

Create a producer in the application that owns the data:

import { createCacheInvalidationProducer } from '@klnap/cache-invalidation'
import { http } from '@klnap/cache-invalidation/dispatchers/http'

export const producer = createCacheInvalidationProducer({
  source: 'https://catalog.example.com',
  dispatcher: http({
    targets: {
      website: {
        url: process.env.CACHE_INVALIDATION_URL!,
        secret: process.env.CACHE_INVALIDATION_SECRET!,
        filter: {
          type: 'catalog.product.updated',
        },
      },
    },
  }),
})

const outcome = await producer.emit({
  type: 'catalog.product.updated',
  data: {
    id: '42',
  },
})

In the receiving application:

import { createWebhookHandler } from '@klnap/cache-invalidation/consumers/http'
import { invalidateApplicationCache } from './cache'

export const webhook = createWebhookHandler({
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://catalog.example.com'],
  async onEvents(events) {
    await invalidateApplicationCache(events)
  },
})

invalidateApplicationCache is application-owned.

The returned handler accepts a standard Request and returns a Promise<Response>. Mount it in your server or framework.

For example, using Bun:

Bun.serve({
  port: 8080,
  fetch(request) {
    if (new URL(request.url).pathname !== '/events') {
      return new Response('Not found', { status: 404 })
    }

    return webhook(request)
  },
})

Configure the producer to send events to the receiving application's /events endpoint.

Without a configured schema, custom event data is unknown. Validate it before using it in application-specific operations.

Persistent deduplication and crash-safe processing are application responsibilities.

Producer configuration

| Option | Description | | --- | --- | | source | Required stable absolute URI identifying the producer | | dispatcher | Required object implementing Dispatcher |

Each call to emit() creates one new CloudEvent and returns a Promise<DispatchOutcome>.

It accepts:

| Property | Description | | --- | --- | | type | Required nonempty event type | | data | Optional JSON-compatible application data | | subject | Optional event subject | | datacontenttype | Optional data media type | | dataschema | Optional schema URI metadata | | extensions | Optional CloudEvents extension attributes |

The producer generates a new rev_-prefixed identifier, a timestamp, and CloudEvents version 1.0.

Provided data defaults to application/json unless another data content type is supplied.

Producer data must consist of JSON-compatible values. Non-finite numbers, cycles, accessors, symbol properties, non-plain records, and unsupported array shapes are rejected.

Extension names must consist of 1–20 lowercase alphanumeric characters and must not replace standard attributes. Values may be strings, booleans, or finite numbers.

Invalid configuration or event input throws.

If a custom dispatcher throws, the producer returns unknown with the event's identity because the exception does not establish whether a receiver acted.

A new call to emit() creates a new logical event. It is not a retry of an earlier logical event.

Custom dispatchers

Applications can implement their own transport or durable delivery policy using the public dispatcher contract:

import type {
  DispatchInput,
  DispatchOutcome,
  Dispatcher,
} from '@klnap/cache-invalidation'

type CustomDispatcher = {
  dispatch(input: DispatchInput): Promise<DispatchOutcome>
}

DispatchInput contains:

{
  events: readonly CloudEvent[]
}

A custom dispatcher can be supplied to either the generic producer or the Payload plugin.

Custom dispatchers own their persistence, transport, retry, and delivery guarantees.

There is no implicit default transport or fallback dispatcher.

When durable delivery is required, persist the event itself or sufficient recovery state before performing delivery according to your application's consistency requirements.

Payload CMS producer

Import from:

import { cacheInvalidation } from '@klnap/cache-invalidation/producers/payload'

Configuration

| Option | Required | Default | Description | | --- | --- | --- | --- | | source | Yes | — | Stable absolute CloudEvents source URI | | dispatcher | Yes | — | Dispatcher implementation | | dataschema | No | Omitted | Application-owned absolute schema URI | | enabled | No | true | Enable the plugin | | collections | No | No ordinary collection opt-ins | Per-collection configuration | | globals | No | No ordinary global opt-ins | Per-global configuration | | excludeFields | No | [] | Default configured comparison exclusions | | media | No | Automatic upload collection selection when possible | Media dependency tracking configuration |

Setting plugin-level enabled: false returns the incoming Payload configuration without installing plugin hooks.

Resource configuration

Collections and globals are opt-in:

cacheInvalidation({
  source: 'https://cms.example.com',
  dispatcher,
  collections: {
    products: true,
    categories: true,
    articles: {
      excludeFields: ['internalNote'],
    },
  },
  globals: {
    navigation: true,
    homepage: true,
  },
})

Configuration can also be attached directly to an existing collection or global:

custom: {
  cacheInvalidation: {
    excludeFields: ['internalNote', 'seo.internalNotes'],
  },
}

Resource-level options:

| Option | Description | | --- | --- | | enabled | Enable or disable the resource | | hooks | Select supported lifecycle hooks | | excludeFields | Exclude fields from public-state comparison | | filter | Decide whether a detected public change should emit an event | | projection | Transform the outgoing public snapshots |

Collections use afterChange and afterDelete by default. Globals support afterChange.

Local custom.cacheInvalidation configuration takes precedence over central configuration:

  • false disables the resource.
  • true enables it while retaining inherited options.
  • An options object overrides the supplied properties and inherits unspecified properties.
  • An options object with enabled: false disables the resource.

The plugin-wide enabled: false disables all plugin behavior regardless of resource configuration.

Public snapshots

Payload events describe public resource changes, not arbitrary database mutations.

The producer obtains public representations before and after the operation using Payload's anonymous Local API access pipeline.

These reads use:

  • overrideAccess: false.
  • showHiddenFields: false.
  • depth: 0.
  • draft: false.
  • Anonymous user context.
  • Configured locale and fallback behavior.
  • The active transaction context when available.

The producer does not substitute privileged hook documents when a public read fails.

Relationships remain unpopulated representations according to Payload's depth-zero behavior, normally identifiers rather than complete related documents.

A genuinely absent public representation is represented by null. Other read failures are logged and do not become deletion events.

Payload mutations remain fail-open when invalidation event preparation or delivery fails.

The public-read mechanism preserves Payload's access-control behavior. It is not a universal sanitizer for arbitrary application data. Review your public collection and field access policies before enabling event delivery.

Drafts and publication

| Change | Public before | Public after | | --- | --- | --- | | Draft-only creation | Absent | Absent | | Draft-only edit without public change | Unchanged | Unchanged | | First publication | null | Published representation | | Published update | Previous representation | Current representation | | Unpublication | Published representation | null | | Published resource deletion | Published representation | null |

Draft-only changes and unchanged public representations do not emit ordinary change events.

Consumers can invalidate both previous and current identifiers, slugs, or dependencies without having to reconstruct earlier resource state.

Localization

The producer compares effective public representations across configured Payload locales.

When fallback is enabled, it uses Payload's configured default locale for fallback reads. Otherwise, fallback is disabled.

Localized snapshots include their locale.

A single mutation can produce zero, one, or multiple locale-specific changes. Shared-field modifications and fallback-source changes can affect several locale representations.

Configure locale-specific tags or paths when the consumer caches localized resources independently:

tags: {
  product: 'product:[locale]:[id]',
  products: 'products:[locale]',
}

Globals receive an identifier corresponding to their global slug.

Comparison exclusions

Comparison exclusions prevent changes to selected fields from triggering an event on their own.

The configured default exclusion list is empty. Independently of that list, the comparison implementation ignores these technical root-level fields:

  • id
  • createdAt
  • updatedAt
  • _status
  • globalType

Lexical node identifiers are also ignored recursively in Lexical-shaped data.

Publication and public-resource existence transitions are handled separately from ordinary field comparison.

Additional exclusions support dot-separated paths:

excludeFields: [
  'internalNote',
  'seo.internalNotes',
]

Nested exclusion paths traverse plain objects, not individual array elements.

For ordinary resources, exclusion precedence is:

  1. Explicit local resource exclusions, including an empty array.
  2. Plugin configuration for that collection or global.
  3. Plugin-wide exclusions.
  4. No additional configured exclusions.

Exclusions affect comparison only. Excluded fields can still appear in emitted public snapshots.

Do not use excludeFields as a security or data-redaction mechanism.

Filtering and projection

filter receives:

{
  before,
  after,
  locale,
  operation,
  resource,
}

It runs after public-state acquisition and comparison. Returning false suppresses the event.

projection receives:

{
  data,
  locale,
  operation,
  resource,
}

It transforms the outgoing snapshots after comparison.

For example, a consumer that depends only on resource identity, slug, and category can use:

custom: {
  cacheInvalidation: {
    projection: ({ data }) => ({
      id: data.id,
      slug: data.slug,
      category: data.category,
    }),
  },
}

Projection must return a non-array object.

If projection omits the resource identifier, the producer restores it from the public input. For localized resources, it preserves the snapshot's locale.

Keep identifiers and fields required by consumer rules stable.

Filtering and projection failures are handled by the producer's fail-open error path. They do not make a failed public read equivalent to deletion.

Projection controls the event representation; Payload access control remains responsible for deciding which fields are publicly readable.

Media dependencies

The plugin can discover opted-in resources that reference a changed or deleted upload.

Media collection selection follows this order:

  1. Explicit media configuration.
  2. The only upload collection.
  3. An upload collection with the slug media.

If multiple upload collections exist and none is selected explicitly or named media, automatic selection is unavailable.

The selected upload collection does not need to be separately enabled in collections for media dependency tracking.

Dependent collections and globals must be opted in.

To select an upload collection explicitly, pass its existing Payload collection configuration:

import { Media } from './collections/Media'

cacheInvalidation({
  source: 'https://cms.example.com',
  dispatcher,
  collections: {
    articles: true,
  },
  media: {
    collection: Media,
    excludeFields: ['internalNote'],
  },
})

A collection configuration object can also be passed directly as media.

Discovery supports upload and relationship fields targeting the selected upload collection through:

  • Groups.
  • Rows.
  • Collapsible fields.
  • Tabs.
  • Arrays in collections.
  • Supported direct and has-many references in collections.

It does not provide a general relationship graph.

Blocks, polymorphic relationships, arbitrary JSON, rich-text references, and relationships targeting unrelated collections are outside the discovery contract.

Global dependencies inside arrays or has-many fields are not supported by the global discovery path.

Collection discovery uses stable identifier pagination with pages of 500 documents.

Candidate discovery uses internal privileged queries to identify references. Emitted dependent data is subsequently acquired through anonymous public reads.

Discovery errors can produce incomplete affected-resource coverage. Successful earlier results are retained, and failures are logged. There is no durable discovery retry system or transactionally consistent reverse-reference index.

Media dependency tracking responds to relevant media updates and deletions. Initial media creation does not trigger dependent-resource discovery.

Media comparison exclusions are resolved from media-local exclusions, applicable dependent collection exclusions, media-specific plugin exclusions, and plugin-wide exclusions.

Affected resources are carried inside the top-level media event.

HTTP target filters therefore match the media event's own type and source, not the types of its affected resources.

A consumer requiring media-driven article invalidation must receive the relevant media events.

Transaction timing

Ordinary Payload lifecycle hooks run before the database transaction has necessarily committed.

The automatic delivery path schedules events after a fixed one-second delay. That delay is not a commit notification.

A consumer can invalidate its cache, read the previous database state, and refill the cache before the mutation commits. Automatic delivery can also occur before rollback.

Process interruption can lose scheduled events.

Each ordinary hook schedules its own event set; there is no cross-hook automatic batch coalescer.

Explicit deferral

Applications that own the outermost transaction can register deferral before performing its mutations:

import { deferCacheInvalidationUntilCommit } from '@klnap/cache-invalidation/producers/payload'

const pending = deferCacheInvalidationUntilCommit(req)

Pass the exact same request object to all mutations participating in that transaction.

For example, within the application-owned transaction:

await payload.update({
  collection: 'products',
  id: productId,
  data: {
    title,
  },
  req,
  overrideAccess: false,
})

After the application has authoritatively resolved the outermost transaction outcome:

switch (outcome) {
  case 'committed': {
    const result = await pending.flush()
    // Retain result if recovery or delivery reporting is required.
    break
  }

  case 'rolled-back':
    pending.discard()
    break

  case 'unknown':
    // Preserve unresolved state privately.
    // Do not flush, discard, or repeat the mutation.
    break
}

Here, outcome is the authoritative result supplied by the application's transaction owner:

type TransactionOutcome =
  | 'committed'
  | 'rolled-back'
  | 'unknown'

The transaction owner is application-specific. This package does not create, commit, roll back, or inspect the transaction.

It must not replace an existing transaction identifier owned by another operation.

PostgreSQL transaction acknowledgement

In Payload PostgreSQL 3.94.1, the underlying Drizzle transaction adapter can catch a transaction promise rejection while settling its transaction methods.

A fulfilled commitTransaction() promise alone is therefore not sufficient proof that the database committed.

Use authoritative adapter-specific transaction evidence. If the result cannot be established, retain an unknown outcome.

Do not treat an exception or an ambiguous acknowledgement as permission to repeat a business mutation.

Applications needing durable resolution of ambiguous transactions can store a unique operation receipt within the same transaction. Receipt presence on the primary database can establish that the transaction committed. Receipt absence alone is not proof of rollback while the original transaction may still be open.

Such receipts must be protected from ordinary application access and retained until no unresolved operation depends on them.

Transaction receipts establish transaction evidence; they do not persist CloudEvents.

Crash-safe delivery requires separate application-owned durable storage of events or sufficient recovery data.

Deferral lifecycle

Deferral is associated with the exact request-object identity.

  • Register before the participating mutations.
  • Repeated registration while a deferral is active throws.
  • Nested operations using the same request join the active queue.
  • Pending work is deduplicated only when change type, collection or global slug, locale, document, operation, and before/after snapshots are identical. Two transitions of one document are kept separately, so both the old and new slugs can be invalidated.
  • Flush groups deliveries by dispatcher identity, source, and optional schema URI.
  • Concurrent calls to flush() share the in-progress promise.
  • After discard, flush() reports discarded.
  • Repeated discard is a no-op.
  • Discard cannot retract a flush that has already started.
  • An empty flush reports accepted with no deliveries.
  • Repeated flush after completion returns an empty accepted result.
  • New work collected while a flush is in progress falls back to automatic delivery.
  • A resolved deferral does not capture later work on the same request.

Retain the first completed flush result when delivery identities or outcomes are required for recovery.

Each delivery record contains the source, optional schema URI, generated CloudEvents, and dispatch outcome.

The helper is process-local. It does not resolve database transaction outcomes, persist events, guarantee process survival, or provide an outbox.

A dispatch failure after a confirmed commit does not undo the committed mutation.

Next.js consumer

Import from:

import {
  createCacheInvalidationHandler,
  defineCache,
} from '@klnap/cache-invalidation/consumers/next'

Cache definitions

defineCache() accepts:

| Property | Description | | --- | --- | | config | Global tag profile configuration | | tags | Recursive tag declarations | | paths | Recursive path declarations | | schemas | Standard Schema validators keyed by event type | | rules | Required rule-definition function | | execute | Named application-owned executors |

The returned object contains:

  • config: normalized handler configuration.
  • tags: typed tag helpers.
  • paths: typed path helpers.

Create the Route Handler separately with createCacheInvalidationHandler({ config: cache.config, secret }).

Keep cache definitions and signing secrets in server-side modules.

Tag and path declarations

Declarations support nested groups, static strings, and parameterized templates.

export const cache = defineCache({
  tags: {
    products: {
      listing: 'products:[locale]',
      detail: 'product:[locale]:[id]',
    },
  },
  paths: {
    products: {
      listing: '/[locale]/products',
      detail: '/[locale]/products/[slug]',
    },
  },
  rules: ({ tags, paths }) => ({
    'payload.collection.products': {
      tags: [
        tags.products.listing,
        tags.products.detail,
      ],
      paths: [
        paths.products.listing,
        paths.products.detail,
      ],
    },
  }),
})

Call a helper to obtain a concrete value:

cache.tags.products.detail({
  locale: 'en',
  id: '42',
})

cache.paths.products.detail({
  locale: 'en',
  slug: 'example-product',
})

Group names organize helpers; they do not automatically become part of the rendered value.

Placeholders use the form [name]. Names start with an ASCII letter and may contain ASCII letters, digits, and underscores.

For automatic snapshot expansion, values are obtained from the corresponding snapshot fields. String values are supported, and numeric resource identifiers are converted to strings.

Missing, null, empty, or invalid required template values fail planning.

Generated tag helpers fit overlong tag values to 256 characters using a stable hash suffix. Literal tag strings supplied directly to rules must not exceed 256 characters.

Paths are limited to 1024 characters.

Dynamic path values reject unsafe path separators, dot segments, control characters, malformed percent encoding, query delimiters, and fragment delimiters. Brackets in values are percent-encoded.

Declarative rules

Rules match exact CloudEvents event types.

Rules may be grouped under arbitrary organizational labels, but duplicate leaf event types are invalid.

Array shorthand is exclusively for tags:

rules: ({ tags }) => ({
  'payload.collection.products': [
    tags.products,
    tags.product,
  ],
})

An explicit tag-only descriptor is also valid:

rules: ({ tags }) => ({
  'payload.collection.products': {
    tags: [tags.product],
  },
})

Path-only rules use an explicit paths property:

rules: ({ paths }) => ({
  'payload.collection.products': {
    paths: [paths.product],
  },
})

Combined rules use both properties:

rules: ({ tags, paths }) => ({
  'payload.collection.products': {
    tags: [tags.product],
    paths: [paths.product],
  },
})

Do not mix path references into tag arrays or tag references into path arrays.

Pass a declared helper reference without invoking it when automatic snapshot expansion is required.

Scoped route patterns

A string path template expands to a concrete URL.

A tuple declaration represents a native Next.js route pattern with a page or layout scope:

const cache = defineCache({
  paths: {
    productPages: ['/products/[slug]', 'page'],
  },
  rules: ({ paths }) => ({
    'payload.collection.products': {
      paths: [paths.productPages],
    },
  }),
})

Pass the uncalled helper reference to preserve its native route scope.

Calling paths.productPages() returns a string without that scope metadata.

Use concrete paths when only specific old and new URLs need invalidation. Use scoped route patterns when intentionally invalidating the broader route pattern.

Tag profiles

The default tag profile is:

{ expire: 0 }

Configure a different default:

const cache = defineCache({
  config: {
    tags: {
      profile: 'max',
    },
  },
  tags: {
    products: 'products',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [tags.products],
  }),
})

Override the profile for a group of tags within a rule:

const cache = defineCache({
  config: {
    tags: {
      profile: { expire: 0 },
    },
  },
  tags: {
    products: 'products',
    product: 'product:[id]',
  },
  rules: ({ tags }) => ({
    'payload.collection.products': [
      ['max', [tags.products]],
      tags.product,
    ],
  }),
})

Profile precedence:

  1. Rule-level profile group.
  2. Global config.tags.profile.
  3. { expire: 0 }.

Profiles use Next.js's native revalidateTag() profile type.

Conflicting profiles for the same rendered tag fail planning before cache operations execute.

Paths do not accept tag profiles.

Resource Change V1 expansion

The consumer automatically recognizes event types beginning with:

  • payload.collection.
  • payload.global.

The prefix must have a nonempty suffix.

These events are validated against the built-in Resource Change V1 contract.

Declarative rules expand independently against each non-null before and after snapshot.

This allows a slug change to invalidate both old and new paths, and a relationship change to invalidate both previous and current dependencies.

An absent snapshot does not produce its own snapshot operations.

A custom event type can also use this expansion behavior by registering the exported resourceChangeV1DataSchema object as its local schema.

For automatically recognized Payload events with an additional custom schema, the validated output must still satisfy Resource Change V1.

Affected resources

Affected resources are matched against their own exact event types.

Their declarative rules can run even when the top-level event has no corresponding rule.

Only declarative tag and path operations are expanded for affected resources. Programmable rules and custom executors are not invoked for them.

Affected resources form a flat list, not a recursive dependency graph.

The consumer does not infer relationships that the producer did not include.

Custom schemas

Register application-owned Standard Schema V1 validators by exact event type.

The package does not require a particular schema library.

For example, install Valibot in the receiving application if you choose to use it:

bun add valibot

Or:

npm install valibot

Then define the schema and rule:

import * as v from 'valibot'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'

const productChanged = v.object({
  id: v.string(),
  slug: v.string(),
  categoryIds: v.array(v.string()),
})

export const cache = defineCache({
  schemas: {
    'catalog.product.changed': productChanged,
  },
  tags: {
    product: 'product:[id]',
    category: 'category:[id]',
  },
  paths: {
    product: '/products/[slug]',
  },
  rules: ({ tags, paths, on }) => ({
    'catalog.product.changed': on(
      'catalog.product.changed',
      ({ data }) => ({
        tags: [
          tags.product({ id: data.id }),
          ...data.categoryIds.map((id) =>
            tags.category({ id }),
          ),
        ],
        paths: [
          paths.product({ slug: data.slug }),
        ],
      }),
    ),
  }),
})

The resolver's data type is inferred from the configured schema's output.

Schemas may transform data. The consumer uses the validated output.

Schemas are selected from trusted local configuration by event type. Incoming dataschema values are metadata and are never fetched.

Valibot is an example application dependency, not a runtime dependency of this package.

Programmable rules

Use on(type, resolver) for application-specific dependency expansion.

The resolver receives:

{
  event,
  data,
  tags,
  paths,
}

It can return:

{
  tags,
  paths,
  operations,
}

Each property is optional. Returning null or undefined plans no operations.

Resolvers must be synchronous and side-effect-free.

The consumer plans the entire authenticated request before executing cache operations. Returning a Promise from a resolver is invalid.

Unknown event types without applicable rules are ignored.

Custom executors

Use custom executors when a cache operation depends on application-owned work.

For example, a consumer may need to refresh a search index before invalidating cached search results:

import * as v from 'valibot'
import { defineCache } from '@klnap/cache-invalidation/consumers/next'
import { refreshSearchIndex } from '@/search'

const productChanged = v.object({
  id: v.string(),
})

export const cache = defineCache({
  schemas: {
    'catalog.product.changed': productChanged,
  },
  tags: {
    product: 'product:[id]',
  },
  rules: ({ tags, on }) => ({
    'catalog.product.changed': on(
      'catalog.product.changed',
      ({ data }) => ({
        operations: [
          { layer: 'search', value: data.id },
        ],
        tags: [
          tags.product({ id: data.id }),
        ],
      }),
    ),
  }),
  execute: {
    search: async ({ value, signal }) => {
      if (typeof value !== 'string') {
        throw new TypeError('Expected a product ID')
      }

      await refreshSearchIndex(value, { signal })
    },
  },
})

refreshSearchIndex is application-owned.

A custom operation has the form:

{
  layer: 'executorName',
  value: applicationValue,
}

Its layer must identify a configured executor.

Executors receive:

{
  event,
  data,
  value,
  signal,
}

Execution behavior:

  • All event planning completes before execution starts.
  • Custom operations execute sequentially within their plan.
  • Custom operations are not deduplicated.
  • A failed or timed-out executor prevents subsequent custom operations and native cache operations in that plan.
  • Independent plans continue.
  • Eligible native cache operations are deduplicated before execution.
  • Other eligible native operations continue after an individual native failure.
  • Execution failures produce an unsuccessful handler response.
  • Completed application effects are not rolled back.

Execution timeouts apply per custom executor operation.

The provided AbortSignal is aborted on timeout. Cancellation is cooperative; an executor that ignores the signal may continue running.

The signal is not automatically linked to the incoming request's abort signal.

Custom effects that are unsafe to repeat require application-owned idempotency.

Handler configuration

createCacheInvalidationHandler({
  config: cache.config,
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  allowedSources: ['https://cms.example.com'],
})

| Option | Default | Accepted values | | --- | --- | --- | | config | Required | Configuration returned by defineCache() | | secret | Required | Standard Webhooks signing secret | | allowedSources | Omitted | Absolute source URIs | | maxBodyBytes | 256 KiB | Integer from 1 to 16 MiB in bytes | | bodyTimeoutMs | 15,000 | Integer from 1 to 60,000 | | maxEvents | 100 | Integer from 1 to 1,000 | | maxOperations | 1,000 | Integer from 1 to 10,000 | | executionTimeoutMs | 15,000 | Integer from 1 to 60,000 | | logger | Omitted | Optional logger |

The operation budget counts rendered tag, path, and custom operations before deduplication.

Exceeding the operation budget fails planning before cache execution.

Configuration limits are validated when the handler is created.

Native Next.js behavior

The consumer invokes:

  • revalidateTag(tag, profile).
  • revalidatePath(path, type?).

The default { expire: 0 } profile immediately expires matching tagged data. A subsequent read performs regeneration according to Next.js behavior.

The 'max' profile uses stale-while-revalidate behavior.

cacheLife() controls cached-data lifetime independently of on-demand invalidation.

The adapter does not invoke updateTag() from a Route Handler.

Invalidation does not synchronously regenerate every route, refresh open browsers, invalidate an external CDN, or coordinate independent deployments.

Those responsibilities belong to Next.js and the hosting environment.

HTTP dispatcher

import { http } from '@klnap/cache-invalidation/dispatchers/http'

The /dispatchers entrypoint exports the same HTTP implementation.

Named targets

const dispatcher = http({
  targets: {
    website: {
      url: 'https://www.example.com/api/invalidate',
      secret: process.env.WEBSITE_WEBHOOK_SECRET!,
    },
    catalog: {
      url: 'https://catalog.example.com/api/invalidate',
      secret: process.env.CATALOG_WEBHOOK_SECRET!,
      filter: {
        type: [
          'payload.collection.products',
          'payload.collection.categories',
        ],
      },
    },
  },
})

Each target requires a destination URL and signing secret.

Without a filter, a target receives every selected event.

Filters match exact CloudEvents source and type attributes:

filter: {
  source: 'https://cms.example.com',
  type: [
    'payload.collection.products',
    'payload.collection.categories',
  ],
}

Values within one selector are alternatives. When both source and type are supplied, both conditions must match.

Filters operate on individual events before batching. They do not inspect application data or affected-resource records.

Explicit target selection

When dispatching already constructed or persisted events directly:

await dispatcher.dispatch({
  events,
  targets: ['website'],
})

Omitting targets selects all configured destinations.

Explicit selection narrows recipients; it does not bypass their filters.

Duplicate target selections are deduplicated.

Unknown targets are rejected before network delivery. If any selected target is unknown, the whole selection is rejected with no deliveries, including to the valid targets in that selection.

Empty event lists, empty target selections, and selections with no matching events produce explicit skipped outcomes.

Configuration

| Option | Default | Accepted values | | --- | --- | --- | | targets | Required | Named target configuration | | timeoutMs | 15,000 | Integer from 1 to 60,000 | | deadlineMs | 5,000 | Integer from 1 to 300,000 | | retries | 2 | Integer from 0 to 10 | | retryDelayMs | 200 | Integer from 0 to 60,000 | | maxEventItems | 100 | Integer from 1 to 1,000 | | maxBodyBytes | 256 KiB | Integer from 1 to 16 MiB in bytes | | allowInsecure | false | Boolean |

Configuration is validated synchronously.

Target configuration and filters are captured when the dispatcher is created.

At most four deliveries execute concurrently.

The total dispatch deadline includes preparation, filtering, batching, queued work, retry delays, and HTTP delivery.

A shorter remaining deadline can terminate an attempt before its configured attempt timeout expires.

Batching

Events are filtered per target and divided into chunks respecting both event-count and serialized-body limits.

A single-event chunk uses:

application/cloudevents+json

A multiple-event chunk uses:

application/cloudevents-batch+json

An individual event that exceeds the body limit produces a failed result without a network attempt.

Each target chunk receives an independent wh_-prefixed delivery identifier.

Configure receiver limits to accommodate dispatcher chunk sizes.

Retries

retries counts additional attempts after the initial attempt.

The dispatcher retries:

  • HTTP 408.
  • HTTP 429.
  • HTTP 5xx.
  • Network failures.
  • Request timeouts.

Other client errors and redirects are terminal.

Redirects are not followed automatically.

Backoff uses exponential full jitter. A valid Retry-After header can increase the delay.

Both delta-seconds and HTTP-date forms are supported, subject to the retry delay cap and remaining dispatch deadline.

Retries preserve:

  • CloudEvent identity.
  • Serialized request body.
  • Delivery identifier.

Each attempt uses a fresh signature timestamp and signature.

A network error or timeout is an ambiguous outcome: the remote receiver may already have acted.

A subsequent successful attempt does not erase earlier ambiguous attempts from attemptOutcomes.

Delivery outcomes

| Status | Meaning | | --- | --- | | accepted | All attempted deliveries were accepted | | partial | Some attempted deliveries were accepted and others were not | | rejected | All attempted deliveries were rejected | | failed | Delivery failed without acceptance or an unresolved ambiguous outcome | | unknown | Delivery may have caused remote effects, but acceptance is unconfirmed | | skipped | No eligible delivery was attempted |

Intentional no-delivery is not reported as transport success.

Skipped results do not participate in attempted-delivery aggregation.

When no delivery was accepted, an unresolved unknown outcome takes precedence over ordinary failure or rejection.

When some deliveries were accepted, the aggregate status is partial even if another delivery is unknown. Per-target results still report unknown, so callers must inspect per-target results before treating an aggregate partial as fully resolved.

Per-target results contain the target name, status, and attempt count, together with available delivery identifiers, event references, attempt outcomes, skip reasons, and error information.

A target can have multiple results when its events are divided into multiple chunks.

HTTP acceptance means a 2xx response was received. It does not establish durable processing, completed cache regeneration, or absence of duplicate application effects.

Generic HTTP consumer

createWebhookHandler() from @klnap/cache-invalidation/consumers/http authenticates and validates incoming CloudEvents before invoking an application-owned callback. The framework-independent integration example shows a minimal receiver; this section documents its options and behavior.

Configuration

| Option | Default | Accepted values | | --- | --- | --- | | secret | Required | Standard Webhooks signing secret | | allowedSources | Omitted | Absolute source URIs | | schemas | Omitted | Standard Schema validators keyed by event type | | onEvents | Required | Synchronous or asynchronous callback | | maxBodyBytes | 256 KiB | Integer from 1 to 16 MiB in bytes | | bodyTimeoutMs | 15,000 | Integer from 1 to 60,000 | | maxEvents | 100 | Integer from 1 to 1,000 | | logger | Omitted | Optional logger |

Validation

The consumer:

  1. Checks the HTTP method and content type.
  2. Reads the raw request body within configured byte and time limits.
  3. Verifies the Standard Webhooks signature and timestamp.
  4. Parses and validates CloudEvents.
  5. Applies the configured source policy.
  6. Deduplicates identical event identities within the request.
  7. Validates locally configured event schemas.
  8. Invokes the application callback for accepted events.

Conflicting duplicate events with the same (source, id) identity reject the complete request.

When schemas is omitted or empty, event data remains unknown.

A nonempty schema map validates matching event types and ignores unmapped types.

Any configured schema failure rejects the request before the callback executes.

Empty or fully filtered batches do not invoke the callback.

Typed application events

import * as v from 'valibot'
import { createWebhookHandler } from '@klnap/cache-invalidation/consumers/http'
import { invalidateProduct } from './cache'

export const webhook = createWebhookHandler({
  secret: process.env.CACHE_INVALIDATION_SECRET!,
  schemas: {
    'catalog.product.updated': v.object({
      id: v.string(),
    }),
  },
  async onEvents(events) {
    for (const event of events) {
      await invalidateProduct(event.data.id)
    }
  },
})

The callback receives validated schema output.

invalidateProduct is application-owned.

If the callback throws after performing some effects, the handler returns a sanitized error response. It cannot roll back those effects.

A subsequent delivery retry may invoke the callback again.

HTTP responses

Both HTTP consumers accept POST requests with supported structured CloudEvents JSON media types.

| Status | Meaning | | --- | --- | | 200 | Request processed without a reported handler failure | | 400 | Invalid event, configured schema, or request; Next.js planning failures also use this status | | 401 | Invalid authentication or signature timestamp | | 403 | Event source not allowed | | 405 | Unsupported HTTP method | | 408 | Request body read timed out | | 413 | Request body, event, or Next.js operation budget limit exceeded | | 415 | Unsupported content type | | 500 | Callback, execution, or unexpected handler failure |

Responses use JSON and include an X-Cache-Request-Id header.

The generic consumer's success response contains:

{
  requestId: string
  accepted: number
  ignored: number
}

The Next.js consumer reports:

{
  requestId: string
  results: Array<{
    layer: string
    operation: string
    status: 'success' | 'failed' | 'skipped'
    error?: {
      code: string
      message: string
    }
  }>
}

Unhandled Next.js events are reported as skipped results.

Next.js execution failures can return per-operation results with HTTP 500. Unexpected handler failures use the generic sanitized error response.

Standard receiver error bodies include a request identifier and a sanitized error string.

The method and content-type rejection bodies contain the error string without a body-level request identifier.

Use the HTTP status, returned results, and request identifier for diagnostics. Do not treat an accepted webhook as proof of cache regeneration.

Logging

Both HTTP consumers accept an optional logger:

type Logger = {
  debug?: (
    entry: Record<string, unknown>,
    message: string,
  ) => void
  info?: (
    entry: Record<string, unknown>,
    message: string,
  ) => void
  warn?: (
    entry: Record<string, unknown>,
    message: string,
  ) => void
  error?: (
    entry: Record<string, unknown>,
    message: string,
  ) => void
}

Receiver diagnostics include request and delivery metadata, status, and error classification.

The HTTP receiver does not log the request body or signing secret. Logger callback failures do not replace the receiver's response.

Payload uses its own logging pipeline. Application-provided errors may contain arbitrary message text, so avoid placing secrets or sensitive data in error messages.

Event protocol

CloudEvents

The package uses CloudEvents 1.0 structured JSON.

A typical event:

{
  "specversion": "1.0",
  "id": "rev_8e64f3ed-95a3-4f4b-8e4d-b92b61c6381a",
  "source": "https://catalog.example.com",
  "type": "catalog.product.updated",
  "time": "2026-12-02T10:00:00.000Z",
  "datacontenttype": "application/json",
  "data": {
    "id": "42"
  }
}

Required envelope attributes:

  • specversion
  • id
  • source
  • type

Event identity is the pair (source, id).

Event types belong to producer applications. Consumers match exact event types according to their own configuration.

Producer helpers require an absolute source URI. The general CloudEvents parser accepts valid URI-reference sources according to its envelope contract.

The envelope supports optional standard attributes and valid extension attributes.

data and data_base64 are mutually exclusive.

The low-level serialization functions support binary Uint8Array data through the structured CloudEvents data_base64 representation. The parser decodes base64 event data.

The generic emit() helper accepts JSON-compatible application data.

Resource Change V1

Resource Change V1 is an optional package-provided data contract used by the Payload adapter.

It is not a Payload-native event format.

type ResourceChangeV1<
  T = Record<string, unknown>,
> = {
  operation: string
  before: T | null
  after: T | null
  affected?: Array<{
    type: string
    data: Record<string, unknown>
  }>
}

For example:

{
  "operation": "update",
  "before": {
    "id": "42",
    "slug": "old-product"
  },
  "after": {
    "id": "42",
    "slug": "new-product"
  }
}

The built-in schema requires:

  • A nonempty operation string.
  • Explicit before and after properties.
  • Plain-object snapshots or null.
  • At least one non-null snapshot.
  • Valid affected-resource entries when supplied.

The snapshot fields remain open application document data.

Affected resources are represented as a flat array of event types and resource data.

The validator excludes prototype-sensitive keys at the outer copied record level. It is not a general-purpose recursive data sanitizer.

Use the exported resourceChangeV1DataSchema to validate this contract in custom integrations.

Standard Schema

Custom event data validation uses Standard Schema V1.

The package implements its built-in Resource Change V1 validator directly.

Consumers may register any compatible Standard Schema implementation.

Validators are resolved exclusively through trusted local event-type configuration.

An event's dataschema attribute is optional metadata. It is never fetched and does not establish trust.

Standard Webhooks

HTTP delivery uses Standard Webhooks.

Requests include:

  • Content-Type
  • webhook-id
  • webhook-timestamp
  • webhook-signature

Signatures authenticate the delivery identifier, timestamp, and exact serialized request body.

The signing key is not transmitted.

The receiver verifies the original body before parsing JSON.

Security and trust

Use independently generated Standard Webhooks signing secrets for separately trusted destinations.

Secrets must use the whsec_ prefix followed by a valid, nonempty Base64-encoded key accepted by the Standard Webhooks implementation.

Generate a 32-byte random key for new integrations.

Keep secrets out of:

  • Browser bundles.
  • Event bodies.
  • URLs.
  • Logs.
  • Public repository files.

HTTPS is required for non-loopback HTTP destinations unless allowInsecure: true is explicitly configured.

The built-in loopback exceptions are localhost, 127.0.0.1, and [::1].

Destination URLs containing username or password components are rejected.

Do not use allowInsecure for public production endpoints. Request signing does not encrypt event content or metadata.

The Standard Webhooks implementation used in the verified release environment applies a five-minute timestamp tolerance in either direction. The package does not expose a tolerance override.

Timestamp verification limits old replay attempts but does not prevent replay within the accepted window.

The package performs request-local duplicate detection, not persistent replay protection.

allowedSources restricts event source values after signature verification. It does not independently authenticate the source URI or distinguish different holders of the same signing secret.

Anyone with the signing secret can create a signed event claiming an allowed source.

Review public Payload access policies, outgoing event fields, custom schema validation, and application-owned effects according to your deployment's trust boundaries.

Report vulnerabilities through the security policy.

Reliability boundaries

The package provides bounded, observable, best-effort event delivery.

It does not guarantee:

  • Durable or exactly-once delivery.
  • Persistent idempotency or replay prevention.
  • Global event ordering.
  • Automatic detection of database transaction commits.
  • Atomic execution across systems.
  • Complete reverse-relationship discovery.
  • Successful regeneration of every invalidated cache entry.
  • Cross-instance cache coordination.
  • External CDN or browser cache invalidation.

Transport retries may duplicate application effects.

A new producer emit() call creates a new event identity. Do not repeat a business mutation solely to retry a failed delivery.

For operations that cannot safely execute more than once, use an application-owned persistent idempotency mechanism keyed by (source, id).

For crash-safe delivery, use application-owned durable event persistence or an outbox with appropriate transaction boundaries.

For confirmed Payload commit ordering, use explicit deferral and flush only after authoritative commit evidence.

A successful invalidation request is not a substitute for verifying the resulting public content.

Troubleshooting

| Symptom | Check | | --- | --- | | No ordinary Payload event | Resource opt-in, plugin enabled state, public visibility, actual public-state change, exclusions, and filter | | Draft save produces no event | Draft-only changes are intentionally ignored when public content is unchanged | | Media changes do not invalidate related content | Media selection, dependent resource opt-in, supported reference structures, and delivery of the top-level media event | | HTTP 401 | Matching signing secrets, timestamp freshness, and unmodified request body | | HTTP 403 | Exact configured CloudEvents source | | HTTP 400 | Event contract, local schema, required template values, and profile conflicts | | HTTP 413 | Dispatcher and receiver body/event limits, and the Next.js operation budget | | HTTP 500 | Callback or executor failures, native cache errors, and sanitized diagnostics | | Dispatch returns skipped | Target selection and event filters | | Dispatch returns unknown | Ambiguous transport failure; the receiver may already have acted | | Old slug remains cached | Rules must cover the previous and current representations | | Route-pattern invalidation loses scope | Pass the declared path helper reference without calling it | | Cache remains stale after a Payload save | Automatic pre-commit race, delivery failure, cache profile, cache attachment, or deployment coordination | | Custom effects run more than once | Persistent application-level idempotency is required |

Use the local playground to reproduce integration behavior.

Public API reference

Only the package's declared export entrypoints are supported. Do not deep-import internal source or distribution modules.

Root entrypoint

@klnap/cache-invalidation

Runtime exports:

| Export | Purpose | | --- | --- | | createCacheInvalidationProducer | Create a framework-independent event producer | | CLOUDEVENTS_JSON | Structured single-event media type | | CLOUDEVENTS_BATCH_JSON | Structured batch media type | | serializeCloudEvent | Serialize one CloudEvent | | serializeCloudEventBatch | Serialize a CloudEvents batch | | parseCloudEvents | Validate and parse structured CloudEvents values | | CloudEventParseError | CloudEvents parsing error | | resourceChangeV1DataSchema | Built-in Resource Change V1 Standard Schema | | validateStandardSchema | Validate data against a Standard Schema | | matchesEventSelector | Match an event against a source/type selector | | aggregateDispatchOutcomes | Aggregate attempted target delivery results | | createDispatchError | Construct structured dispatch error information | | CacheConfigurationError | Configuration error | | CacheRequestError | Request error | | CacheSchemaError | Schema error | | CacheSourceError | Source-policy error |

Low-level helper signatures:

serializeCloudEvent(event: CloudEvent): string

serializeCloudEventBatch(
  events: readonly CloudEvent[],
): string

parseCloudEvents(
  value: unknown,
  contentType: string,
): CloudEvent[]

matchesEventSelector(
  event: CloudEvent,
  selector: EventSelector,
): boolean

createDispatchError(
  code: string,
  message: string,
): DispatchError

aggregateDispatchOutcomes(
  results: readonly TargetDispatchResult[],
  skippedReason?: DispatchSkippedReason,
): DispatchOutcome

parseCloudEvents() accepts an already parsed value and its content type, not a raw JSON request body.

validateStandardSchema() accepts a Standard Schema and an unknown value, returning a Promise of the validated schema output.

Exported types:

  • CloudEvent
  • CacheInvalidationEventInput
  • CacheInvalidationProducer
  • CacheInvalidationProducerConfig
  • JsonValue
  • EventSelector
  • ResourceChangeV1
  • ResourceChangeV1Data
  • StandardSchemaMap
  • StandardSchemaOutput
  • DeliveryStatus
  • DispatchSkippedReason
  • DispatchError
  • Dispatcher
  • DispatchInput
  • DispatchOutcome
  • EventReference
  • Logger
  • TargetDispatchResult

Payload producer

@klnap/cache-invalidation/producers/payload

Runtime exports:

| Export | Purpose | | --- | --- | | cacheInvalidation | Create the Payload plugin | | deferCacheInvalidationUntilCommit | Register request-scoped delivery deferral | | normalizeExcludeFields | Trim, filter, and deduplicate exclusion paths | | readCacheInvalidationExcludeFields | Read exclusion fields from resource custom configuration | | resolveExcludeFields | Resolve effective comparison exclusions |

Exclusion helper signatures:

normalizeExcludeFields(
  paths: readonly string[],
): string[]

readCacheInvalidationExcludeFields(
  custom: unknown,
): string[] | undefined

resolveExcludeFields() accepts an options object with:

  • schemaCustom
  • pluginExcludeFields
  • pluginCollectionExcludeFields
  • pluginGlobalExcludeFields
  • collectionSlug
  • globalSlug
  • mediaSchemaCustom
  • mediaPluginExcludeFields
  • isMediaDependent

It returns the resolved exclusion paths as string[].

Exported types:

  • CacheInvalidationDeferral
  • CacheInvalidationDeferralResult
  • MediaPluginConfig
  • PayloadCacheInvalidationPluginConfig
  • PluginSchemaExcludeConfig
  • PayloadCacheInvalidationCustom
  • PayloadCacheInvalidationOptions

HTTP dispatcher

@klnap/cache-invalidation/dispatchers

@klnap/cache-invalidation/dispatchers/http

Both entrypoints export:

  • http

Exported types:

  • CacheInvalidationTarget
  • TargetConfig
  • HttpDispatchInput
  • HttpDispatcher
  • HttpDispatcherConfig

Generic HTTP consumer

@klnap/cache-invalidation/consumers/http

Runtime export:

  • createWebhookHandler

Exported type:

  • WebhookHandlerOptions

Next.js consumer

@klnap/cache-invalidation/consumers/next

Runtime exports:

  • defineCache
  • createCacheInvalidationHandler

Exported types:

  • CacheDefinition
  • CacheInvalidationExecutionContext
  • CacheInvalidationExecutor
  • CacheInvalidationHandlerOptions
  • CacheInvalidationRuleContext
  • CacheInvalidationRuleResult
  • CacheProfile
  • DefineCacheInput
  • PathTemplate
  • TagTemplate

The package's TypeScript declarations provide the exact generic contracts and inferred helper types.

Internal supporting declaration types are not additional public named exports.

Performance

See PERFORMANCE.md for measured workloads, methodology, historical provenance, and reproduction commands.

License

MIT.