@klnap/cache-invalidation 0.0.0-stage → 0.1.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 (143) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/dist/consumers/next/compile-tag-template.d.ts +16 -0
  5. package/dist/consumers/next/compile-tag-template.js +83 -0
  6. package/dist/consumers/next/consumer-types.d.ts +98 -0
  7. package/dist/consumers/next/consumer-types.js +3 -0
  8. package/dist/consumers/next/define-cache.d.ts +4 -0
  9. package/dist/consumers/next/define-cache.js +281 -0
  10. package/dist/consumers/next/host-types.d.ts +44 -0
  11. package/dist/consumers/next/host-types.js +3 -0
  12. package/dist/consumers/next/index.d.ts +5 -0
  13. package/dist/consumers/next/index.js +2 -0
  14. package/dist/consumers/next/param-values.d.ts +8 -0
  15. package/dist/consumers/next/param-values.js +23 -0
  16. package/dist/consumers/next/profile.d.ts +2 -0
  17. package/dist/consumers/next/profile.js +18 -0
  18. package/dist/consumers/next/registry-builders.d.ts +3 -0
  19. package/dist/consumers/next/registry-builders.js +155 -0
  20. package/dist/consumers/next/revalidation-handler.d.ts +6 -0
  21. package/dist/consumers/next/revalidation-handler.js +2 -0
  22. package/dist/consumers/next/runtime.d.ts +5 -0
  23. package/dist/consumers/next/runtime.js +560 -0
  24. package/dist/core/cloudevents.d.ts +27 -0
  25. package/dist/core/cloudevents.js +172 -0
  26. package/dist/core/dispatch-outcome.d.ts +4 -0
  27. package/dist/core/dispatch-outcome.js +17 -0
  28. package/dist/core/errors.d.ts +16 -0
  29. package/dist/core/errors.js +28 -0
  30. package/dist/core/event-limits.d.ts +15 -0
  31. package/dist/core/event-limits.js +20 -0
  32. package/dist/core/event-selector.d.ts +9 -0
  33. package/dist/core/event-selector.js +5 -0
  34. package/dist/core/index.d.ts +10 -0
  35. package/dist/core/index.js +6 -0
  36. package/dist/core/resource-changed-schema.d.ts +35 -0
  37. package/dist/core/resource-changed-schema.js +12 -0
  38. package/dist/core/standard-schema.d.ts +2 -0
  39. package/dist/core/standard-schema.js +7 -0
  40. package/dist/core/types.d.ts +35 -0
  41. package/dist/core/types.js +1 -0
  42. package/dist/core/url-segment.d.ts +2 -0
  43. package/dist/core/url-segment.js +17 -0
  44. package/dist/dispatchers/http/index.d.ts +20 -0
  45. package/dist/dispatchers/http/index.js +274 -0
  46. package/dist/dispatchers/http/targets.d.ts +14 -0
  47. package/dist/dispatchers/http/targets.js +26 -0
  48. package/dist/dispatchers/index.d.ts +1 -0
  49. package/dist/dispatchers/index.js +1 -0
  50. package/dist/producers/payload/exclude-fields.d.ts +19 -0
  51. package/dist/producers/payload/exclude-fields.js +75 -0
  52. package/dist/producers/payload/index.d.ts +4 -0
  53. package/dist/producers/payload/index.js +3 -0
  54. package/dist/producers/payload/lifecycle/deferred.d.ts +55 -0
  55. package/dist/producers/payload/lifecycle/deferred.js +111 -0
  56. package/dist/producers/payload/lifecycle/dispatch.d.ts +18 -0
  57. package/dist/producers/payload/lifecycle/dispatch.js +21 -0
  58. package/dist/producers/payload/lifecycle/doc-content.d.ts +8 -0
  59. package/dist/producers/payload/lifecycle/doc-content.js +88 -0
  60. package/dist/producers/payload/lifecycle/draft-status.d.ts +6 -0
  61. package/dist/producers/payload/lifecycle/draft-status.js +15 -0
  62. package/dist/producers/payload/lifecycle/helpers.d.ts +13 -0
  63. package/dist/producers/payload/lifecycle/helpers.js +12 -0
  64. package/dist/producers/payload/lifecycle/identifier-field.d.ts +8 -0
  65. package/dist/producers/payload/lifecycle/identifier-field.js +48 -0
  66. package/dist/producers/payload/lifecycle/identifiers.d.ts +4 -0
  67. package/dist/producers/payload/lifecycle/identifiers.js +5 -0
  68. package/dist/producers/payload/lifecycle/locale-published.d.ts +7 -0
  69. package/dist/producers/payload/lifecycle/locale-published.js +19 -0
  70. package/dist/producers/payload/lifecycle/locale.d.ts +24 -0
  71. package/dist/producers/payload/lifecycle/locale.js +44 -0
  72. package/dist/producers/payload/lifecycle/log.d.ts +31 -0
  73. package/dist/producers/payload/lifecycle/log.js +67 -0
  74. package/dist/producers/payload/lifecycle/media-equality.d.ts +4 -0
  75. package/dist/producers/payload/lifecycle/media-equality.js +36 -0
  76. package/dist/producers/payload/lifecycle/operation.d.ts +2 -0
  77. package/dist/producers/payload/lifecycle/operation.js +7 -0
  78. package/dist/producers/payload/lifecycle/orderable-hooks.d.ts +21 -0
  79. package/dist/producers/payload/lifecycle/orderable-hooks.js +26 -0
  80. package/dist/producers/payload/lifecycle/orderable-neighbors.d.ts +21 -0
  81. package/dist/producers/payload/lifecycle/orderable-neighbors.js +151 -0
  82. package/dist/producers/payload/lifecycle/public-snapshots.d.ts +16 -0
  83. package/dist/producers/payload/lifecycle/public-snapshots.js +173 -0
  84. package/dist/producers/payload/lifecycle/revalidate.d.ts +16 -0
  85. package/dist/producers/payload/lifecycle/revalidate.js +162 -0
  86. package/dist/producers/payload/lifecycle/skip-rules.d.ts +19 -0
  87. package/dist/producers/payload/lifecycle/skip-rules.js +57 -0
  88. package/dist/producers/payload/lifecycle/types.d.ts +32 -0
  89. package/dist/producers/payload/lifecycle/types.js +1 -0
  90. package/dist/producers/payload/media/media-references.d.ts +31 -0
  91. package/dist/producers/payload/media/media-references.js +127 -0
  92. package/dist/producers/payload/media/resolve-media-affected-locales.d.ts +22 -0
  93. package/dist/producers/payload/media/resolve-media-affected-locales.js +70 -0
  94. package/dist/producers/payload/media/resolve-media-dependents.d.ts +39 -0
  95. package/dist/producers/payload/media/resolve-media-dependents.js +157 -0
  96. package/dist/producers/payload/media/resolve-media-slug.d.ts +7 -0
  97. package/dist/producers/payload/media/resolve-media-slug.js +17 -0
  98. package/dist/producers/payload/media/revalidate-media-dependents.d.ts +14 -0
  99. package/dist/producers/payload/media/revalidate-media-dependents.js +222 -0
  100. package/dist/producers/payload/plugin.d.ts +36 -0
  101. package/dist/producers/payload/plugin.js +235 -0
  102. package/dist/producers/payload/publish-all/context.d.ts +2 -0
  103. package/dist/producers/payload/publish-all/context.js +2 -0
  104. package/dist/producers/payload/publish-all/edited-locale.d.ts +5 -0
  105. package/dist/producers/payload/publish-all/edited-locale.js +5 -0
  106. package/dist/producers/payload/publish-all/index.d.ts +3 -0
  107. package/dist/producers/payload/publish-all/index.js +3 -0
  108. package/dist/producers/payload/publish-all/localization.d.ts +7 -0
  109. package/dist/producers/payload/publish-all/localization.js +1 -0
  110. package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.d.ts +19 -0
  111. package/dist/producers/payload/publish-all/mirror-publish-all-locales-to-req.js +32 -0
  112. package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.d.ts +2 -0
  113. package/dist/producers/payload/publish-all/preserve-locales-on-publish-all.js +145 -0
  114. package/dist/producers/payload/publish-all/read-localized-scalar.d.ts +2 -0
  115. package/dist/producers/payload/publish-all/read-localized-scalar.js +24 -0
  116. package/dist/producers/payload/publish-all/request-flags.d.ts +13 -0
  117. package/dist/producers/payload/publish-all/request-flags.js +9 -0
  118. package/dist/producers/payload/publish-all/restore-guard.d.ts +2 -0
  119. package/dist/producers/payload/publish-all/restore-guard.js +12 -0
  120. package/dist/producers/payload/publish-all/restore-locales-after-publish-all.d.ts +2 -0
  121. package/dist/producers/payload/publish-all/restore-locales-after-publish-all.js +85 -0
  122. package/dist/producers/payload/revalidation-custom.d.ts +37 -0
  123. package/dist/producers/payload/revalidation-custom.js +54 -0
  124. package/dist/producers/payload/schema.d.ts +3 -0
  125. package/dist/producers/payload/schema.js +23 -0
  126. package/docs/concepts/architecture.md +32 -0
  127. package/docs/concepts/cache-tags.md +97 -0
  128. package/docs/concepts/event-contract.md +38 -0
  129. package/docs/consumers/custom.md +19 -0
  130. package/docs/consumers/next.md +277 -0
  131. package/docs/dispatchers/custom.md +38 -0
  132. package/docs/dispatchers/http.md +66 -0
  133. package/docs/extending.md +26 -0
  134. package/docs/migration/0.3.0-to-0.4.0.md +67 -0
  135. package/docs/migration/0.4.0-to-0.5.0.md +60 -0
  136. package/docs/migration/0.5.x-to-0.0.0.md +143 -0
  137. package/docs/producers/custom.md +63 -0
  138. package/docs/producers/payload-media-dependencies.md +45 -0
  139. package/docs/producers/payload.md +140 -0
  140. package/docs/reliability.md +35 -0
  141. package/docs/security.md +34 -0
  142. package/docs/troubleshooting.md +14 -0
  143. package/package.json +120 -4
@@ -0,0 +1,274 @@
1
+ import { Webhook } from 'standardwebhooks';
2
+ import { aggregateDispatchOutcomes, createDispatchError } from '../../core/dispatch-outcome.js';
3
+ import { assertLimit, DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_EVENT_ITEMS, MAX_BODY_BYTES_CEILING, MAX_EVENT_ITEMS_CEILING, } from '../../core/event-limits.js';
4
+ import { CLOUDEVENTS_BATCH_JSON, CLOUDEVENTS_JSON, matchesEventSelector, serializeCloudEvent, serializeCloudEventBatch, } from '../../core/index.js';
5
+ import { toTargetList, validateTarget } from './targets.js';
6
+ const MAX_CONCURRENT_DELIVERIES = 4;
7
+ const MAX_RETRIES = 10;
8
+ const MAX_ATTEMPT_TIMEOUT_MS = 60_000;
9
+ const MAX_DEADLINE_MS = 300_000;
10
+ const MAX_RETRY_DELAY_MS = 60_000;
11
+ const assertIntegerRange = (name, value, min, max) => {
12
+ if (!Number.isInteger(value) || value < min || value > max) {
13
+ throw new RangeError(`${name} must be an integer from ${min} to ${max}; got ${value}`);
14
+ }
15
+ return value;
16
+ };
17
+ const isAllowedUrl = (url, allowInsecure) => {
18
+ try {
19
+ const parsed = new URL(url);
20
+ return (parsed.protocol === 'https:' ||
21
+ (parsed.protocol === 'http:' &&
22
+ (allowInsecure || ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname))));
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ };
28
+ const pause = (ms, deadline) => new Promise((resolve) => {
29
+ if (deadline.aborted)
30
+ return resolve();
31
+ const timer = setTimeout(done, ms);
32
+ function done() {
33
+ clearTimeout(timer);
34
+ deadline.removeEventListener('abort', done);
35
+ resolve();
36
+ }
37
+ deadline.addEventListener('abort', done, { once: true });
38
+ });
39
+ const attemptPost = async (target, options) => {
40
+ if (options.deadline.aborted) {
41
+ return {
42
+ status: 'failed',
43
+ retryable: false,
44
+ error: createDispatchError('HTTP_DISPATCH_ERROR', 'dispatch deadline exceeded'),
45
+ };
46
+ }
47
+ if (!isAllowedUrl(target.url, options.allowInsecure)) {
48
+ return {
49
+ status: 'failed',
50
+ retryable: false,
51
+ error: createDispatchError('HTTP_DISPATCH_ERROR', 'target URL must use https'),
52
+ };
53
+ }
54
+ const attemptController = new AbortController();
55
+ const abortFromDeadline = () => attemptController.abort();
56
+ options.deadline.addEventListener('abort', abortFromDeadline, { once: true });
57
+ const timeout = setTimeout(() => attemptController.abort(), options.timeoutMs);
58
+ const timestamp = options.timestamp;
59
+ const webhook = new Webhook(target.secret);
60
+ const signature = webhook.sign(options.deliveryId, timestamp, options.body);
61
+ try {
62
+ const response = await fetch(target.url, {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': options.contentType,
66
+ 'webhook-id': options.deliveryId,
67
+ 'webhook-timestamp': String(Math.floor(timestamp.getTime() / 1000)),
68
+ 'webhook-signature': signature,
69
+ },
70
+ body: options.body,
71
+ signal: attemptController.signal,
72
+ redirect: 'manual',
73
+ });
74
+ await response.body?.cancel().catch(() => undefined);
75
+ if (response.status >= 200 && response.status < 300) {
76
+ return { status: 'accepted', retryable: false };
77
+ }
78
+ if (response.status === 429) {
79
+ return {
80
+ status: 'rejected',
81
+ retryable: true,
82
+ error: createDispatchError('HTTP_REJECTED', 'HTTP 429'),
83
+ };
84
+ }
85
+ if (response.status >= 500) {
86
+ return {
87
+ status: 'failed',
88
+ retryable: true,
89
+ error: createDispatchError('HTTP_FAILED', `HTTP ${response.status}`),
90
+ };
91
+ }
92
+ if (response.status >= 400) {
93
+ return {
94
+ status: 'rejected',
95
+ retryable: false,
96
+ error: createDispatchError('HTTP_REJECTED', `HTTP ${response.status}`),
97
+ };
98
+ }
99
+ return {
100
+ status: 'failed',
101
+ retryable: false,
102
+ error: createDispatchError('HTTP_REDIRECT', `redirect refused (HTTP ${response.status})`),
103
+ };
104
+ }
105
+ catch {
106
+ const timedOut = attemptController.signal.aborted;
107
+ return {
108
+ status: 'unknown',
109
+ retryable: true,
110
+ error: createDispatchError(timedOut ? 'HTTP_TIMEOUT' : 'HTTP_NETWORK_ERROR', timedOut ? 'HTTP dispatch timed out' : 'HTTP dispatch failed'),
111
+ };
112
+ }
113
+ finally {
114
+ clearTimeout(timeout);
115
+ options.deadline.removeEventListener('abort', abortFromDeadline);
116
+ }
117
+ };
118
+ const postChunk = async (target, events, options) => {
119
+ const isBatch = events.length !== 1;
120
+ const body = isBatch ? serializeCloudEventBatch(events) : serializeCloudEvent(events[0]);
121
+ const contentType = isBatch ? CLOUDEVENTS_BATCH_JSON : CLOUDEVENTS_JSON;
122
+ const deliveryId = `wh_${crypto.randomUUID()}`;
123
+ let last;
124
+ let attempts = 0;
125
+ let lastTimestamp = 0;
126
+ while (attempts <= options.retries) {
127
+ if (attempts > 0) {
128
+ await pause(Math.random() * options.retryDelayMs * 2 ** (attempts - 1), options.deadline);
129
+ }
130
+ if (options.deadline.aborted)
131
+ break;
132
+ attempts += 1;
133
+ const timestampMs = Math.max(Date.now(), lastTimestamp + 1000);
134
+ lastTimestamp = timestampMs;
135
+ last = await attemptPost(target, {
136
+ body,
137
+ contentType,
138
+ deliveryId,
139
+ timestamp: new Date(timestampMs),
140
+ timeoutMs: options.timeoutMs,
141
+ deadline: options.deadline,
142
+ allowInsecure: options.allowInsecure,
143
+ });
144
+ if (!last.retryable || last.status === 'accepted')
145
+ break;
146
+ }
147
+ return {
148
+ target: target.name,
149
+ deliveryId,
150
+ status: last?.status ?? 'failed',
151
+ attempts,
152
+ ...((last?.error || !last) && {
153
+ error: last?.error ?? createDispatchError('HTTP_DISPATCH_ERROR', 'dispatch deadline exceeded'),
154
+ }),
155
+ };
156
+ };
157
+ const chunkEvents = (events, maxItems, maxBytes) => {
158
+ const encoder = new TextEncoder();
159
+ const result = [];
160
+ let current = [];
161
+ let currentEventBytes = 0;
162
+ for (const event of events) {
163
+ const eventBytes = encoder.encode(serializeCloudEvent(event)).byteLength;
164
+ const singleTooLarge = eventBytes > maxBytes;
165
+ if (singleTooLarge) {
166
+ if (current.length)
167
+ result.push({ events: current, tooLarge: false });
168
+ current = [];
169
+ currentEventBytes = 0;
170
+ result.push({ events: [event], tooLarge: true });
171
+ continue;
172
+ }
173
+ const candidateBytes = current.length
174
+ ? currentEventBytes + eventBytes + current.length + 2
175
+ : eventBytes;
176
+ if (current.length && (current.length + 1 > maxItems || candidateBytes > maxBytes)) {
177
+ result.push({ events: current, tooLarge: false });
178
+ current = [event];
179
+ currentEventBytes = eventBytes;
180
+ }
181
+ else {
182
+ current.push(event);
183
+ currentEventBytes += eventBytes;
184
+ }
185
+ }
186
+ if (current.length)
187
+ result.push({ events: current, tooLarge: false });
188
+ return result;
189
+ };
190
+ const runBounded = async (items, worker) => {
191
+ const results = new Array(items.length);
192
+ let next = 0;
193
+ await Promise.all(Array.from({ length: Math.min(MAX_CONCURRENT_DELIVERIES, items.length) }, async () => {
194
+ while (next < items.length) {
195
+ const index = next++;
196
+ results[index] = await worker(items[index]);
197
+ }
198
+ }));
199
+ return results;
200
+ };
201
+ export const http = (config) => {
202
+ if (!Object.keys(config.targets).length)
203
+ throw new Error('http dispatcher requires targets');
204
+ for (const [name, target] of Object.entries(config.targets)) {
205
+ validateTarget(name, target, config.allowInsecure);
206
+ try {
207
+ new Webhook(target.secret);
208
+ }
209
+ catch (cause) {
210
+ throw new TypeError(`HTTP target "${name}" has a malformed signing secret; expected "whsec_" followed by base64`, { cause });
211
+ }
212
+ }
213
+ const maxEventItems = assertLimit('maxEventItems', config.maxEventItems ?? DEFAULT_MAX_EVENT_ITEMS, MAX_EVENT_ITEMS_CEILING);
214
+ const maxBodyBytes = assertLimit('maxBodyBytes', config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES, MAX_BODY_BYTES_CEILING);
215
+ const timeoutMs = assertIntegerRange('timeoutMs', config.timeoutMs ?? 15_000, 1, MAX_ATTEMPT_TIMEOUT_MS);
216
+ const deadlineMs = assertIntegerRange('deadlineMs', config.deadlineMs ?? 5_000, 1, MAX_DEADLINE_MS);
217
+ const retries = assertIntegerRange('retries', config.retries ?? 2, 0, MAX_RETRIES);
218
+ const retryDelayMs = assertIntegerRange('retryDelayMs', config.retryDelayMs ?? 200, 0, MAX_RETRY_DELAY_MS);
219
+ const allowInsecure = config.allowInsecure ?? false;
220
+ return {
221
+ async dispatch(input) {
222
+ const allTargets = toTargetList(config.targets);
223
+ const selectedNames = input.targets ?? allTargets.map(({ name }) => name);
224
+ const unknown = selectedNames.filter((name) => !Object.hasOwn(config.targets, name));
225
+ if (unknown.length) {
226
+ return {
227
+ status: 'rejected',
228
+ results: unknown.map((target) => ({
229
+ target,
230
+ deliveryId: `wh_${crypto.randomUUID()}`,
231
+ status: 'rejected',
232
+ attempts: 0,
233
+ error: createDispatchError('UNKNOWN_TARGET', `unknown target "${target}"`),
234
+ })),
235
+ };
236
+ }
237
+ const selected = new Set(selectedNames);
238
+ const jobs = allTargets
239
+ .filter(({ name }) => selected.has(name))
240
+ .flatMap((target) => {
241
+ const events = input.events.filter((event) => !target.filter || matchesEventSelector(event, target.filter));
242
+ return chunkEvents(events, maxEventItems, maxBodyBytes).map((chunk) => ({
243
+ target,
244
+ ...chunk,
245
+ }));
246
+ });
247
+ if (!jobs.length)
248
+ return { status: 'accepted', results: [] };
249
+ const deadline = new AbortController();
250
+ const timer = setTimeout(() => deadline.abort(), deadlineMs);
251
+ try {
252
+ const results = await runBounded(jobs, ({ target, events, tooLarge }) => tooLarge
253
+ ? Promise.resolve({
254
+ target: target.name,
255
+ deliveryId: `wh_${crypto.randomUUID()}`,
256
+ status: 'failed',
257
+ attempts: 0,
258
+ error: createDispatchError('HTTP_BODY_TOO_LARGE', 'request body exceeds maxBodyBytes'),
259
+ })
260
+ : postChunk(target, events, {
261
+ timeoutMs,
262
+ deadline: deadline.signal,
263
+ allowInsecure,
264
+ retries,
265
+ retryDelayMs,
266
+ }));
267
+ return aggregateDispatchOutcomes(results);
268
+ }
269
+ finally {
270
+ clearTimeout(timer);
271
+ }
272
+ },
273
+ };
274
+ };
@@ -0,0 +1,14 @@
1
+ import type { EventSelector } from '../../core/event-selector.js';
2
+ export type CacheInvalidationTarget = {
3
+ url: string;
4
+ secret: string;
5
+ filter?: EventSelector;
6
+ };
7
+ export type TargetConfig = Record<string, CacheInvalidationTarget>;
8
+ export declare const toTargetList: (config: TargetConfig) => {
9
+ url: string;
10
+ secret: string;
11
+ filter?: EventSelector;
12
+ name: string;
13
+ }[];
14
+ export declare const validateTarget: (name: string, target: CacheInvalidationTarget, allowInsecure?: boolean) => void;
@@ -0,0 +1,26 @@
1
+ export const toTargetList = (config) => Object.entries(config).map(([name, target]) => ({ name, ...target }));
2
+ export const validateTarget = (name, target, allowInsecure = false) => {
3
+ let url;
4
+ try {
5
+ url = new URL(target.url);
6
+ }
7
+ catch {
8
+ throw new TypeError(`HTTP target "${name}" must use a valid HTTPS URL`);
9
+ }
10
+ if (url.protocol !== 'https:' &&
11
+ !(url.protocol === 'http:' &&
12
+ (allowInsecure || ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {
13
+ throw new TypeError(`HTTP target "${name}" must use HTTPS`);
14
+ }
15
+ if (url.username || url.password) {
16
+ throw new TypeError(`HTTP target "${name}" URL must not contain credentials`);
17
+ }
18
+ if (target.secret === undefined || target.secret === '') {
19
+ throw new TypeError(`HTTP target "${name}" is missing its signing secret; set a Standard Webhooks secret ("whsec_" followed by base64)`);
20
+ }
21
+ if (typeof target.secret !== 'string' ||
22
+ !target.secret.startsWith('whsec_') ||
23
+ target.secret.length <= 6) {
24
+ throw new TypeError(`HTTP target "${name}" has a malformed signing secret; expected "whsec_" followed by base64`);
25
+ }
26
+ };
@@ -0,0 +1 @@
1
+ export { type CacheInvalidationTarget, type HttpDispatcher, type HttpDispatcherConfig, type HttpDispatchInput, http, type TargetConfig, } from './http/index.js';
@@ -0,0 +1 @@
1
+ export { http, } from './http/index.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Reads `excludeFields` when explicitly set on `custom.cacheInvalidation` (including `[]`).
3
+ * Ignores `enabled: false` — used for media dependents without lifecycle hooks.
4
+ */
5
+ export declare function readCacheInvalidationExcludeFields(custom: unknown): string[] | undefined;
6
+ export declare const normalizeExcludeFields: (paths: readonly string[]) => string[];
7
+ export type PluginExcludeFieldsBySlug = Readonly<Record<string, readonly string[]>>;
8
+ export type ResolveExcludeFieldsInput = {
9
+ schemaCustom?: unknown;
10
+ pluginExcludeFields?: readonly string[];
11
+ pluginCollectionExcludeFields?: PluginExcludeFieldsBySlug;
12
+ pluginGlobalExcludeFields?: PluginExcludeFieldsBySlug;
13
+ collectionSlug?: string;
14
+ globalSlug?: string;
15
+ mediaSchemaCustom?: unknown;
16
+ mediaPluginExcludeFields?: readonly string[];
17
+ isMediaDependent?: boolean;
18
+ };
19
+ export declare const resolveExcludeFields: ({ schemaCustom, pluginExcludeFields, pluginCollectionExcludeFields, pluginGlobalExcludeFields, collectionSlug, globalSlug, mediaSchemaCustom, mediaPluginExcludeFields, isMediaDependent, }: ResolveExcludeFieldsInput) => string[];
@@ -0,0 +1,75 @@
1
+ const CACHE_INVALIDATION_CUSTOM_KEY = 'cacheInvalidation';
2
+ const cacheInvalidationEntry = (custom) => {
3
+ if (!custom || typeof custom !== 'object')
4
+ return null;
5
+ const entry = custom[CACHE_INVALIDATION_CUSTOM_KEY];
6
+ if (entry === true)
7
+ return {};
8
+ if (!entry || typeof entry !== 'object')
9
+ return null;
10
+ return entry;
11
+ };
12
+ /**
13
+ * Reads `excludeFields` when explicitly set on `custom.cacheInvalidation` (including `[]`).
14
+ * Ignores `enabled: false` — used for media dependents without lifecycle hooks.
15
+ */
16
+ export function readCacheInvalidationExcludeFields(custom) {
17
+ const entry = cacheInvalidationEntry(custom);
18
+ if (!entry || !Object.hasOwn(entry, 'excludeFields'))
19
+ return undefined;
20
+ const raw = entry.excludeFields;
21
+ if (!Array.isArray(raw))
22
+ return undefined;
23
+ return raw.filter((item) => typeof item === 'string');
24
+ }
25
+ export const normalizeExcludeFields = (paths) => {
26
+ const seen = new Set();
27
+ const normalized = [];
28
+ for (const path of paths) {
29
+ if (typeof path !== 'string')
30
+ continue;
31
+ const trimmed = path.trim();
32
+ if (!trimmed || seen.has(trimmed))
33
+ continue;
34
+ seen.add(trimmed);
35
+ normalized.push(trimmed);
36
+ }
37
+ return normalized;
38
+ };
39
+ const pluginSlugExcludeList = (map, slug) => {
40
+ if (!slug || !map || !Object.hasOwn(map, slug))
41
+ return undefined;
42
+ return map[slug];
43
+ };
44
+ export const resolveExcludeFields = ({ schemaCustom, pluginExcludeFields, pluginCollectionExcludeFields, pluginGlobalExcludeFields, collectionSlug, globalSlug, mediaSchemaCustom, mediaPluginExcludeFields, isMediaDependent, }) => {
45
+ if (isMediaDependent) {
46
+ const mediaExplicit = readCacheInvalidationExcludeFields(mediaSchemaCustom);
47
+ if (mediaExplicit !== undefined) {
48
+ return normalizeExcludeFields(mediaExplicit);
49
+ }
50
+ const mediaCollectionSlug = collectionSlug;
51
+ const mediaPluginPerSlug = pluginSlugExcludeList(pluginCollectionExcludeFields, mediaCollectionSlug);
52
+ if (mediaPluginPerSlug !== undefined) {
53
+ return normalizeExcludeFields(mediaPluginPerSlug);
54
+ }
55
+ if (mediaPluginExcludeFields?.length) {
56
+ return normalizeExcludeFields(mediaPluginExcludeFields);
57
+ }
58
+ if (pluginExcludeFields?.length) {
59
+ return normalizeExcludeFields(pluginExcludeFields);
60
+ }
61
+ return [];
62
+ }
63
+ const schemaExplicit = readCacheInvalidationExcludeFields(schemaCustom);
64
+ if (schemaExplicit !== undefined) {
65
+ return normalizeExcludeFields(schemaExplicit);
66
+ }
67
+ const pluginPerSlug = pluginSlugExcludeList(collectionSlug ? pluginCollectionExcludeFields : pluginGlobalExcludeFields, collectionSlug ?? globalSlug);
68
+ if (pluginPerSlug !== undefined) {
69
+ return normalizeExcludeFields(pluginPerSlug);
70
+ }
71
+ if (pluginExcludeFields?.length) {
72
+ return normalizeExcludeFields(pluginExcludeFields);
73
+ }
74
+ return [];
75
+ };
@@ -0,0 +1,4 @@
1
+ export { normalizeExcludeFields, readCacheInvalidationExcludeFields, resolveExcludeFields, } from './exclude-fields.js';
2
+ export { type CacheInvalidationOrderableHooks, cacheInvalidationOrderableHooks, } from './lifecycle/orderable-hooks.js';
3
+ export { cacheInvalidation, type DispatcherConfig, type DispatcherSelection, type MediaPluginConfig, type PayloadCacheInvalidationPluginConfig, type PluginSchemaExcludeConfig, } from './plugin.js';
4
+ export type { PayloadCacheInvalidationCustom, PayloadCacheInvalidationOptions, } from './revalidation-custom.js';
@@ -0,0 +1,3 @@
1
+ export { normalizeExcludeFields, readCacheInvalidationExcludeFields, resolveExcludeFields, } from './exclude-fields.js';
2
+ export { cacheInvalidationOrderableHooks, } from './lifecycle/orderable-hooks.js';
3
+ export { cacheInvalidation, } from './plugin.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A caller that owns the transaction can defer revalidation until commit. It begins deferral, runs its
3
+ * writes, then calls `flush()` after commit or `discard()` after rollback.
4
+ *
5
+ * Changes are deduplicated by (type, collection/global, locale, document, operation) before they are
6
+ * dispatched, so a document in a locale is named once even when several writes in the transaction touched it.
7
+ */
8
+ import type { Dispatcher } from '../../../core/index.js';
9
+ import type { RevalidationChange } from './types.js';
10
+ type DeferredRequest = {
11
+ context?: Record<string, unknown>;
12
+ };
13
+ type RevalidationLogger = {
14
+ error: (message: string) => void;
15
+ warn?: (message: string) => void;
16
+ info?: (message: string) => void;
17
+ };
18
+ type DeferredChanges = {
19
+ changes: RevalidationChange[];
20
+ source: string;
21
+ logger: RevalidationLogger;
22
+ dispatcher: Dispatcher;
23
+ };
24
+ export type RevalidationDeferral = {
25
+ /** Dispatches this request's changes. Call only after commit. */
26
+ flush: () => Promise<void>;
27
+ /** Drops deferred changes after the transaction rolled back. */
28
+ discard: () => void;
29
+ };
30
+ /** Starts deferral for this request. Nested writes in the same request queue into it. */
31
+ export declare const deferRevalidationUntilCommit: (req: DeferredRequest) => RevalidationDeferral;
32
+ /**
33
+ * Defers changes until `flush()` when a transaction owner is active. Otherwise, dispatch is attempted
34
+ * shortly after the hook returns so the Payload write can commit first.
35
+ */
36
+ export declare const dispatchRevalidationChanges: ({ req, changes, source, logger, dispatcher, }: {
37
+ req: DeferredRequest;
38
+ changes: RevalidationChange[];
39
+ source: string;
40
+ logger: RevalidationLogger;
41
+ dispatcher: Dispatcher;
42
+ }) => Promise<void>;
43
+ /** Returns the active deferred queue for this request, if any. */
44
+ export declare const takeDeferredDispatches: (req: DeferredRequest) => DeferredChanges[] | undefined;
45
+ /** Marks this request as a global write: revalidation covers every configured locale. */
46
+ export declare const markRevalidationAllLocales: (req: DeferredRequest) => void;
47
+ export declare const isRevalidationAllLocales: (req: DeferredRequest) => boolean;
48
+ /**
49
+ * Marks this request as writing only the order key (no content, no publication change). Neighbour
50
+ * resolution may then take the previous key from the hook's previous document and derive visibility
51
+ * from the locale's current list.
52
+ */
53
+ export declare const markRevalidationOrderOnly: (req: DeferredRequest) => void;
54
+ export declare const isRevalidationOrderOnly: (req: DeferredRequest) => boolean;
55
+ export {};
@@ -0,0 +1,111 @@
1
+ import { postRevalidationChanges } from './dispatch.js';
2
+ const DEFERRED_KEY = '__revalidationDeferred';
3
+ /** Set by writes that are not locale edits (for example a global reorder): dispatch every locale. */
4
+ const ALL_LOCALES_KEY = '__revalidationAllLocales';
5
+ /** Set by writes that change only `_order`. */
6
+ const ORDER_ONLY_KEY = '__revalidationOrderOnly';
7
+ /** Change keys already staged by this transaction, so repeated writes do not dispatch duplicates. */
8
+ const seenByQueue = new WeakMap();
9
+ /** Starts deferral for this request. Nested writes in the same request queue into it. */
10
+ export const deferRevalidationUntilCommit = (req) => {
11
+ const queue = [];
12
+ req.context = req.context ?? {};
13
+ req.context[DEFERRED_KEY] = queue;
14
+ const release = () => {
15
+ if (req.context?.[DEFERRED_KEY] === queue)
16
+ delete req.context[DEFERRED_KEY];
17
+ };
18
+ return {
19
+ flush: async () => {
20
+ release();
21
+ const pending = queue.splice(0);
22
+ const byDispatcher = new Map();
23
+ for (const entry of pending) {
24
+ const bySource = byDispatcher.get(entry.dispatcher) ?? new Map();
25
+ bySource.set(entry.source, [...(bySource.get(entry.source) ?? []), entry]);
26
+ byDispatcher.set(entry.dispatcher, bySource);
27
+ }
28
+ for (const bySource of byDispatcher.values()) {
29
+ for (const entries of bySource.values()) {
30
+ const [first] = entries;
31
+ if (!first)
32
+ continue;
33
+ await postRevalidationChanges({
34
+ changes: entries.flatMap((entry) => entry.changes),
35
+ source: first.source,
36
+ dispatcher: first.dispatcher,
37
+ logger: first.logger,
38
+ });
39
+ }
40
+ }
41
+ },
42
+ discard: () => {
43
+ release();
44
+ queue.length = 0;
45
+ seenByQueue.delete(queue);
46
+ },
47
+ };
48
+ };
49
+ /**
50
+ * Defers changes until `flush()` when a transaction owner is active. Otherwise, dispatch is attempted
51
+ * shortly after the hook returns so the Payload write can commit first.
52
+ */
53
+ export const dispatchRevalidationChanges = async ({ req, changes, source, logger, dispatcher, }) => {
54
+ const queue = takeDeferredDispatches(req);
55
+ let fresh = changes;
56
+ if (queue) {
57
+ const seen = seenByQueue.get(queue) ?? new Set();
58
+ seenByQueue.set(queue, seen);
59
+ fresh = changes.filter((change) => {
60
+ const key = `${source}\u0000${changeKey(change)}`;
61
+ if (seen.has(key))
62
+ return false;
63
+ seen.add(key);
64
+ return true;
65
+ });
66
+ }
67
+ if (fresh.length === 0)
68
+ return;
69
+ if (queue) {
70
+ queue.push({ changes: fresh, source, logger, dispatcher });
71
+ return;
72
+ }
73
+ scheduleBestEffortDispatch({ changes: fresh, source, dispatcher, logger });
74
+ };
75
+ /** Best-effort dispatch after the hook returns. There is no durable retry or recovery. */
76
+ const scheduleBestEffortDispatch = (args) => {
77
+ const timer = setTimeout(async () => {
78
+ await postRevalidationChanges(args);
79
+ }, 1_000);
80
+ timer.unref?.();
81
+ };
82
+ /** Returns the active deferred queue for this request, if any. */
83
+ export const takeDeferredDispatches = (req) => {
84
+ const queue = req.context?.[DEFERRED_KEY];
85
+ return Array.isArray(queue) ? queue : undefined;
86
+ };
87
+ /** Marks this request as a global write: revalidation covers every configured locale. */
88
+ export const markRevalidationAllLocales = (req) => {
89
+ req.context = req.context ?? {};
90
+ req.context[ALL_LOCALES_KEY] = true;
91
+ };
92
+ export const isRevalidationAllLocales = (req) => req.context?.[ALL_LOCALES_KEY] === true;
93
+ /**
94
+ * Marks this request as writing only the order key (no content, no publication change). Neighbour
95
+ * resolution may then take the previous key from the hook's previous document and derive visibility
96
+ * from the locale's current list.
97
+ */
98
+ export const markRevalidationOrderOnly = (req) => {
99
+ req.context = req.context ?? {};
100
+ req.context[ORDER_ONLY_KEY] = true;
101
+ };
102
+ export const isRevalidationOrderOnly = (req) => req.context?.[ORDER_ONLY_KEY] === true;
103
+ const changeKey = (change) => [
104
+ change.type,
105
+ change.slug,
106
+ change.locale,
107
+ String(change.doc.id),
108
+ change.operation,
109
+ JSON.stringify(change.before ?? null),
110
+ JSON.stringify(change.after ?? null),
111
+ ].join('\u0000');
@@ -0,0 +1,18 @@
1
+ import type { Dispatcher } from '../../../core/index.js';
2
+ import type { RevalidationChange } from './types.js';
3
+ type RevalidationLogger = {
4
+ error: (message: string) => void;
5
+ warn?: (message: string) => void;
6
+ info?: (message: string) => void;
7
+ };
8
+ /**
9
+ * Dispatch source-specific revalidation events via configured dispatcher.
10
+ * Fail-open for Payload saves — log errors, never throw.
11
+ */
12
+ export declare const postRevalidationChanges: ({ changes, source, logger, dispatcher, }: {
13
+ changes: RevalidationChange[];
14
+ source: string;
15
+ logger: RevalidationLogger;
16
+ dispatcher: Dispatcher;
17
+ }) => Promise<void>;
18
+ export {};
@@ -0,0 +1,21 @@
1
+ import { changesToRevalidationEvents } from '../schema.js';
2
+ import { revalidationLogError } from './log.js';
3
+ /**
4
+ * Dispatch source-specific revalidation events via configured dispatcher.
5
+ * Fail-open for Payload saves — log errors, never throw.
6
+ */
7
+ export const postRevalidationChanges = async ({ changes, source, logger, dispatcher, }) => {
8
+ if (!changes.length)
9
+ return;
10
+ try {
11
+ const events = changesToRevalidationEvents(changes, source);
12
+ const outcome = await dispatcher.dispatch({ events });
13
+ if (outcome.status !== 'accepted') {
14
+ const errors = outcome.results.flatMap((result) => result.error?.message ?? []);
15
+ revalidationLogError(logger, `dispatcher ${outcome.status}${errors.length ? ` · ${errors.join('; ')}` : ''}`);
16
+ }
17
+ }
18
+ catch (error) {
19
+ revalidationLogError(logger, error instanceof Error ? error.message : String(error));
20
+ }
21
+ };
@@ -0,0 +1,8 @@
1
+ export type DocsContentEqualOptions = {
2
+ excludeFields?: readonly string[];
3
+ };
4
+ /** Removes top-level or nested field paths before content comparison. */
5
+ export declare const omitFieldPaths: (doc: Record<string, unknown>, paths: readonly string[]) => Record<string, unknown>;
6
+ export declare const hasLocaleData: (doc: Record<string, unknown> | undefined) => boolean;
7
+ /** Content-only equality — ignores timestamps / _status / Lexical node ids / excludeFields. */
8
+ export declare const docsContentEqual: (a: Record<string, unknown>, b: Record<string, unknown>, options?: DocsContentEqualOptions) => boolean;