@extantape/payload-plugin-cache-refresh 0.1.0 → 0.2.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.
- package/README.md +20 -5
- package/dist/client/CacheRefreshButton.d.ts +11 -0
- package/dist/client/CacheRefreshButton.js +40 -19
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/index.js +105 -16
- package/dist/types.d.ts +12 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Cache refresh for Payload: a dashboard button that refreshes your Next.js site's cache tags, for the people you choose, after a confirmation.
|
|
4
4
|
|
|
5
|
-
**Status:** early
|
|
5
|
+
**Status:** early. Version 0.2.0, a security release, is on npm; see the changelog. The plugin is covered by 110 unit tests with `next/cache.js` mocked: who may refresh, the same-site check and the allowed origins, the lock and cooldown, the confirmation step, a failing tag list, a tag that fails to refresh, a logger or hook that throws something other than an error, the audit hook, stale or expire, changed tags or everything, warming, and the words the button shows for each reply. It has not been run against a real Next.js app yet, the button has not been rendered in a browser, and the screen reader behavior is untested.
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
@@ -16,12 +16,27 @@ Cache refresh for Payload: a dashboard button that refreshes your Next.js site's
|
|
|
16
16
|
|
|
17
17
|
Signed-out requests get 401. A signed-in user your rule refuses gets 403, and a rule that throws counts as a no. Payload's own auth applies to the endpoint.
|
|
18
18
|
|
|
19
|
-
Payload's CSRF check does not cover this endpoint: a form on another site can post `text/plain` with the admin's cookie and no preflight. So the plugin checks the request itself. The refresh needs `Content-Type: application/json` (415 otherwise), and the browser must show it came from this site: `Sec-Fetch-Site` must be `same-origin` if sent, and `Origin` must match the allowed origins if sent. A request with neither header gets 403.
|
|
19
|
+
Payload's CSRF check does not cover this endpoint: a form on another site can post `text/plain` with the admin's cookie and no preflight. So the plugin checks the request itself. The refresh needs `Content-Type: application/json` (415 otherwise), and the browser must show it came from this site: `Sec-Fetch-Site` must be `same-origin` if sent, and `Origin` must match the allowed origins if sent. A request with neither header gets 403. An `Origin` of `null` is always refused.
|
|
20
|
+
|
|
21
|
+
When the browser sends `Origin`, it is checked against the allowed origins. Those are `allowedOrigins` when you set it, and then only that list, never the request's own origin. It must hold at least one entry, and every entry must be an http or https address such as `https://admin.example.org`, or the plugin refuses to start with an error saying which entry to fix. Leave it unset to use Payload's `serverURL`, or the origin of the request URL when `serverURL` is empty (Payload's default) or isn't an http or https address. Set one of the two if a proxy changes the request URL.
|
|
20
22
|
|
|
21
23
|
A second press while a refresh runs, or within `cooldownMs` after one, gets 429.
|
|
22
24
|
|
|
23
25
|
If the tag list can't be read (a function throws, or a tag is empty or longer than 256 characters), nothing is refreshed.
|
|
24
26
|
|
|
27
|
+
If Next.js fails to refresh a tag, the plugin still tries the rest, so as much of the site as possible is fresh. The reply is then a 500 with `refreshed: false`, `count` (the tags that refreshed) and `failed` (the ones that didn't). Each failure is written to Payload's log. The reply never carries the error text. `onRefresh` gets only the tags that refreshed, with the `failed` count, so if you clear recorded tags there you clear only those. Nothing is warmed after a failure. The button says how many tags refreshed and how many didn't, and suggests trying again.
|
|
28
|
+
|
|
29
|
+
## On its own, and with others
|
|
30
|
+
|
|
31
|
+
**On its own:** Cache Refresh needs only Payload and Next.js. It adds one endpoint and a dashboard button, and refreshes the tags your site records. It doesn't depend on any other plugin.
|
|
32
|
+
|
|
33
|
+
**Needs:** Payload `^3.80.0` and Next.js `>=16.0.0` as peer dependencies, with React `^19.0.0` optional. No other EXTANT APE plugin is required.
|
|
34
|
+
|
|
35
|
+
**Works with:**
|
|
36
|
+
- **Audit Trail:** your `onRefresh` can call Audit Trail's `recordEvent`, so each refresh is kept with who ran it and how many tags it refreshed. That's your own code, and neither plugin imports the other.
|
|
37
|
+
|
|
38
|
+
**Color Theory:** no direct link. The dashboard button uses its own `--cache-refresh-*` variables, which fall back to Payload's `--theme-*` colors, so it follows Color Theory's admin colors when its `applyToAdmin` option is on. Its focus ring falls back to a fixed orange.
|
|
39
|
+
|
|
25
40
|
## Install
|
|
26
41
|
|
|
27
42
|
```sh
|
|
@@ -59,14 +74,14 @@ Regenerate Payload's import map after adding it, so the button is found.
|
|
|
59
74
|
| `warmTimeoutMs` | Time for each warming fetch. Default 5000. |
|
|
60
75
|
| `warmDeadlineMs` | Total time for all warming. Pages left when it passes are skipped and reported. Default 15000. |
|
|
61
76
|
| `cooldownMs` | Time after a refresh before the next is accepted. Default 5000. |
|
|
62
|
-
| `allowedOrigins` | Origins a refresh may come from. Default Payload's `serverURL`, else the request's origin. |
|
|
63
|
-
| `onRefresh(report)` | Gets `who` (id, collection, email), `at`, `count`, `scope`, `mode` and `tags`. If it throws, the refresh stays and the response says `audited: false`. It isn't called when zero tags were refreshed. |
|
|
77
|
+
| `allowedOrigins` | Origins a refresh may come from, checked when the browser sends `Origin`. When set, only this list is used, and it needs at least one entry, each an http or https address, or the plugin refuses to start. Default Payload's `serverURL`, else the request's origin. |
|
|
78
|
+
| `onRefresh(report)` | Gets `who` (id, collection, email), `at`, `count`, `failed`, `scope`, `mode` and `tags`. `tags` holds only the tags that refreshed, and `failed` counts the ones that didn't. If it throws, the refresh stays and the response says `audited: false`. It isn't called when zero tags were refreshed. |
|
|
64
79
|
| `endpointPath` | Default `/cache-refresh`. |
|
|
65
80
|
| `adminButton` | Default true. Set false and import `CacheRefreshButton` from `@extantape/payload-plugin-cache-refresh/client` to place it yourself. |
|
|
66
81
|
|
|
67
82
|
The plugin never clears your recorded changed tags. Do that in `onRefresh`, which receives the tags it refreshed.
|
|
68
83
|
|
|
69
|
-
The button's words can be replaced with the `text` prop, and its colors with `--cache-refresh-ink`, `--cache-refresh-paper`, `--cache-refresh-line` and `--cache-refresh-focus`.
|
|
84
|
+
The button's words can be replaced with the `text` prop (its `partial`, `noneRefreshed` and `partialNotAudited` entries cover a refresh that only partly went through), and its colors with `--cache-refresh-ink`, `--cache-refresh-paper`, `--cache-refresh-line` and `--cache-refresh-focus`.
|
|
70
85
|
|
|
71
86
|
## Limits
|
|
72
87
|
|
|
@@ -15,9 +15,20 @@ export type CacheRefreshText = {
|
|
|
15
15
|
warmSkipped: (n: number) => string;
|
|
16
16
|
busy: string;
|
|
17
17
|
notAudited: string;
|
|
18
|
+
partial: (refreshed: number, failed: number) => string;
|
|
19
|
+
noneRefreshed: string;
|
|
20
|
+
partialNotAudited: string;
|
|
18
21
|
failed: string;
|
|
19
22
|
};
|
|
20
23
|
export declare const defaultText: CacheRefreshText;
|
|
24
|
+
/**
|
|
25
|
+
* What the button says about a refresh reply. `done` is true only for a full refresh, which closes the panel; after
|
|
26
|
+
* a partial or failed refresh the panel stays open so the admin can try again.
|
|
27
|
+
*/
|
|
28
|
+
export declare function replyMessage(status: number, body: unknown, text?: CacheRefreshText): {
|
|
29
|
+
message: string;
|
|
30
|
+
done: boolean;
|
|
31
|
+
};
|
|
21
32
|
/**
|
|
22
33
|
* The dashboard button. Renders nothing for anyone the host does not allow. Pressing it opens a confirmation
|
|
23
34
|
* panel; nothing is refreshed until "Refresh now". Escape or Cancel closes the panel and returns focus.
|
|
@@ -18,8 +18,42 @@ export const defaultText = {
|
|
|
18
18
|
warmSkipped: (n) => `${n} ${n === 1 ? 'page was' : 'pages were'} not warmed.`,
|
|
19
19
|
busy: 'A refresh is running or just finished. Try again in a few seconds.',
|
|
20
20
|
notAudited: 'The refresh went through, but the record of it could not be saved.',
|
|
21
|
+
partial: (n, f) => `Only part of the refresh went through: ${n} ${n === 1 ? 'tag was' : 'tags were'} refreshed and ${f} ${f === 1 ? 'was' : 'were'} not. Try again in a few seconds.`,
|
|
22
|
+
noneRefreshed: 'The refresh did not go through. No tags were refreshed. Try again in a few seconds.',
|
|
23
|
+
partialNotAudited: 'The record of the tags that were refreshed could not be saved.',
|
|
21
24
|
failed: 'The refresh did not happen. Nothing was changed.',
|
|
22
25
|
};
|
|
26
|
+
/**
|
|
27
|
+
* What the button says about a refresh reply. `done` is true only for a full refresh, which closes the panel; after
|
|
28
|
+
* a partial or failed refresh the panel stays open so the admin can try again.
|
|
29
|
+
*/
|
|
30
|
+
export function replyMessage(status, body, text = defaultText) {
|
|
31
|
+
const t = text;
|
|
32
|
+
const out = (body && typeof body === 'object' ? body : {});
|
|
33
|
+
if (status === 429)
|
|
34
|
+
return { message: t.busy, done: false };
|
|
35
|
+
if (status < 200 || status >= 300) {
|
|
36
|
+
if (out.reason !== 'revalidate' || typeof out.count !== 'number' || typeof out.failed !== 'number')
|
|
37
|
+
return { message: t.failed, done: false };
|
|
38
|
+
const parts = [out.count > 0 ? t.partial(out.count, out.failed) : t.noneRefreshed];
|
|
39
|
+
if (out.count > 0 && out.audited === false)
|
|
40
|
+
parts.push(t.partialNotAudited);
|
|
41
|
+
return { message: parts.join(' '), done: false };
|
|
42
|
+
}
|
|
43
|
+
if (typeof out.count !== 'number')
|
|
44
|
+
return { message: t.failed, done: false };
|
|
45
|
+
const parts = [out.count === 0 ? t.nothing : t.done(out.count)];
|
|
46
|
+
const w = out.warmed;
|
|
47
|
+
if (w?.failed)
|
|
48
|
+
parts.push(t.warmFailed(w.failed));
|
|
49
|
+
if (w?.timedOut)
|
|
50
|
+
parts.push(t.warmTimedOut(w.timedOut));
|
|
51
|
+
if (w?.skipped)
|
|
52
|
+
parts.push(t.warmSkipped(w.skipped));
|
|
53
|
+
if (out.audited === false)
|
|
54
|
+
parts.push(t.notAudited);
|
|
55
|
+
return { message: parts.join(' '), done: true };
|
|
56
|
+
}
|
|
23
57
|
const v = (name, fallback) => `var(--cache-refresh-${name}, ${fallback})`;
|
|
24
58
|
const ink = v('ink', 'currentColor');
|
|
25
59
|
const paper = v('paper', 'var(--theme-elevation-0, Canvas)');
|
|
@@ -73,26 +107,13 @@ export function CacheRefreshButton({ apiRoute = '/api', endpointPath = '/cache-r
|
|
|
73
107
|
setMessage(t.working);
|
|
74
108
|
try {
|
|
75
109
|
const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ confirm: true, scope: status?.hasChanged ? scope : 'all' }) });
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
110
|
+
const body = await res.json().catch(() => null);
|
|
111
|
+
const said = replyMessage(res.status, body, t);
|
|
112
|
+
setMessage(said.message);
|
|
113
|
+
if (said.done) {
|
|
114
|
+
setOpen(false);
|
|
115
|
+
trigger.current?.focus();
|
|
79
116
|
}
|
|
80
|
-
if (!res.ok)
|
|
81
|
-
throw new Error('refused');
|
|
82
|
-
const out = (await res.json());
|
|
83
|
-
const parts = [out.count === 0 ? t.nothing : t.done(out.count)];
|
|
84
|
-
const w = out.warmed;
|
|
85
|
-
if (w && w.failed > 0)
|
|
86
|
-
parts.push(t.warmFailed(w.failed));
|
|
87
|
-
if (w?.timedOut)
|
|
88
|
-
parts.push(t.warmTimedOut(w.timedOut));
|
|
89
|
-
if (w?.skipped)
|
|
90
|
-
parts.push(t.warmSkipped(w.skipped));
|
|
91
|
-
if (out.audited === false)
|
|
92
|
-
parts.push(t.notAudited);
|
|
93
|
-
setMessage(parts.join(' '));
|
|
94
|
-
setOpen(false);
|
|
95
|
-
trigger.current?.focus();
|
|
96
117
|
}
|
|
97
118
|
catch {
|
|
98
119
|
setMessage(t.failed);
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { CacheRefreshButton, defaultText, type CacheRefreshText } from './CacheRefreshButton.js';
|
|
1
|
+
export { CacheRefreshButton, defaultText, replyMessage, type CacheRefreshText } from './CacheRefreshButton.js';
|
package/dist/client/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
export { CacheRefreshButton, defaultText } from './CacheRefreshButton.js';
|
|
2
|
+
export { CacheRefreshButton, defaultText, replyMessage } from './CacheRefreshButton.js';
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,39 @@ const json = (body, status = 200) => new Response(JSON.stringify(body), { status
|
|
|
10
10
|
const refuse = (message, status, reason) => {
|
|
11
11
|
throw new APIError(message, status, { reason }, true);
|
|
12
12
|
};
|
|
13
|
+
/** Text for anything a catch receives, whatever was thrown. Never throws. */
|
|
14
|
+
const describeThrown = (err) => {
|
|
15
|
+
try {
|
|
16
|
+
if (typeof err === 'string')
|
|
17
|
+
return err;
|
|
18
|
+
const message = err !== null && typeof err === 'object' ? err.message : undefined;
|
|
19
|
+
if (typeof message === 'string')
|
|
20
|
+
return message;
|
|
21
|
+
return err === null || err === undefined ? String(err) : `a thrown ${typeof err}`;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return 'an unreadable error';
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** The name of a thrown value, such as `TimeoutError`, or an empty string. Never throws. */
|
|
28
|
+
const nameOf = (err) => {
|
|
29
|
+
try {
|
|
30
|
+
const name = err !== null && typeof err === 'object' ? err.name : undefined;
|
|
31
|
+
return typeof name === 'string' ? name : '';
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Writes to Payload's logger. A missing or failing logger never changes what the plugin does. */
|
|
38
|
+
const log = (req, level, message) => {
|
|
39
|
+
try {
|
|
40
|
+
req.payload?.logger?.[level]?.(message);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Logging is best effort.
|
|
44
|
+
}
|
|
45
|
+
};
|
|
13
46
|
/** Sign-in first (401), then the host's rule (403). A rule that throws is a no. */
|
|
14
47
|
async function guard(req, opts) {
|
|
15
48
|
const user = req.user;
|
|
@@ -66,7 +99,7 @@ async function warm(req, opts, tags, scope) {
|
|
|
66
99
|
origin = new URL(opts.warmBaseUrl).origin;
|
|
67
100
|
}
|
|
68
101
|
catch {
|
|
69
|
-
req
|
|
102
|
+
log(req, 'warn', 'cache-refresh: warmBaseUrl is not a valid address, so nothing was warmed.');
|
|
70
103
|
return result;
|
|
71
104
|
}
|
|
72
105
|
let paths;
|
|
@@ -74,7 +107,7 @@ async function warm(req, opts, tags, scope) {
|
|
|
74
107
|
paths = typeof opts.warmPaths === 'function' ? await opts.warmPaths({ req, tags, scope }) : opts.warmPaths;
|
|
75
108
|
}
|
|
76
109
|
catch (err) {
|
|
77
|
-
req
|
|
110
|
+
log(req, 'warn', `cache-refresh: the warm path list failed: ${describeThrown(err)}`);
|
|
78
111
|
return result;
|
|
79
112
|
}
|
|
80
113
|
const each = opts.warmTimeoutMs ?? 5000;
|
|
@@ -109,7 +142,7 @@ async function warm(req, opts, tags, scope) {
|
|
|
109
142
|
result.failed += 1;
|
|
110
143
|
}
|
|
111
144
|
catch (err) {
|
|
112
|
-
if (err
|
|
145
|
+
if (nameOf(err) === 'TimeoutError' || nameOf(err) === 'AbortError')
|
|
113
146
|
result.timedOut += 1;
|
|
114
147
|
else
|
|
115
148
|
result.failed += 1;
|
|
@@ -138,14 +171,44 @@ function checkSameSite(req, allowed) {
|
|
|
138
171
|
return refuse('The request did not say where it came from.', 403, 'crossSite');
|
|
139
172
|
}
|
|
140
173
|
}
|
|
141
|
-
|
|
174
|
+
/** The origin of an http or https address, or null. Any other scheme has an opaque origin, which browsers send as `null`. */
|
|
175
|
+
const webOrigin = (u) => {
|
|
176
|
+
if (typeof u !== 'string' || u.length === 0)
|
|
177
|
+
return null;
|
|
142
178
|
try {
|
|
143
|
-
|
|
179
|
+
const url = new URL(u);
|
|
180
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
181
|
+
return null;
|
|
182
|
+
return url.origin === 'null' ? null : url.origin;
|
|
144
183
|
}
|
|
145
184
|
catch {
|
|
146
185
|
return null;
|
|
147
186
|
}
|
|
148
187
|
};
|
|
188
|
+
/**
|
|
189
|
+
* The origins a refresh may come from. A list the host set is the only one that counts, and every entry must be an
|
|
190
|
+
* http or https address. Unset, it is Payload's `serverURL` when that is one, else null (the request's own origin).
|
|
191
|
+
*/
|
|
192
|
+
function resolveAllowedOrigins(allowedOrigins, serverURL) {
|
|
193
|
+
if (allowedOrigins === undefined) {
|
|
194
|
+
const own = webOrigin(serverURL);
|
|
195
|
+
return own ? [own] : null;
|
|
196
|
+
}
|
|
197
|
+
const prefix = 'payload-plugin-cache-refresh: `allowedOrigins`';
|
|
198
|
+
if (!Array.isArray(allowedOrigins))
|
|
199
|
+
throw new Error(`${prefix} must be a list of addresses such as https://admin.example.org, or left unset.`);
|
|
200
|
+
if (allowedOrigins.length === 0)
|
|
201
|
+
throw new Error(`${prefix} is empty. List at least one address such as https://admin.example.org, or leave it unset.`);
|
|
202
|
+
const out = new Set();
|
|
203
|
+
for (const [i, entry] of allowedOrigins.entries()) {
|
|
204
|
+
const origin = webOrigin(entry);
|
|
205
|
+
if (!origin)
|
|
206
|
+
throw new Error(`${prefix} entry ${i + 1} is not an http or https address. List addresses such as https://admin.example.org, or leave it unset.`);
|
|
207
|
+
out.add(origin);
|
|
208
|
+
}
|
|
209
|
+
return [...out];
|
|
210
|
+
}
|
|
211
|
+
const NO_WARM = { attempted: 0, ok: 0, failed: 0, timedOut: 0, skipped: 0, deadlineReached: false };
|
|
149
212
|
const profileFor = (mode, profile) => (mode === 'expire' ? { expire: 0 } : (profile ?? 'max'));
|
|
150
213
|
export function makeEndpoints(opts, serverURL) {
|
|
151
214
|
const path = opts.endpointPath ?? DEFAULT_PATH;
|
|
@@ -153,7 +216,7 @@ export function makeEndpoints(opts, serverURL) {
|
|
|
153
216
|
const cooldown = opts.cooldownMs ?? 5000;
|
|
154
217
|
let running = false;
|
|
155
218
|
let lastEnd = 0;
|
|
156
|
-
const configured = (opts.allowedOrigins
|
|
219
|
+
const configured = resolveAllowedOrigins(opts.allowedOrigins, serverURL);
|
|
157
220
|
/** GET: what the button shows. Same guard as the refresh. */
|
|
158
221
|
const status = {
|
|
159
222
|
path,
|
|
@@ -178,7 +241,8 @@ export function makeEndpoints(opts, serverURL) {
|
|
|
178
241
|
method: 'post',
|
|
179
242
|
handler: async (req) => {
|
|
180
243
|
const who = await guard(req, opts);
|
|
181
|
-
|
|
244
|
+
const own = configured ? null : webOrigin(req.url);
|
|
245
|
+
checkSameSite(req, configured ?? (own ? [own] : []));
|
|
182
246
|
const body = await readBody(req);
|
|
183
247
|
if (body.confirm !== true)
|
|
184
248
|
return refuse('Confirm the refresh first.', 400, 'confirm');
|
|
@@ -194,28 +258,53 @@ export function makeEndpoints(opts, serverURL) {
|
|
|
194
258
|
tags = await resolveTags(req, opts, scope);
|
|
195
259
|
}
|
|
196
260
|
catch (err) {
|
|
197
|
-
req
|
|
261
|
+
log(req, 'error', `cache-refresh: the tag list failed, nothing was refreshed: ${describeThrown(err)}`);
|
|
198
262
|
return refuse('The list of tags could not be read, so nothing was refreshed.', 500, 'tags');
|
|
199
263
|
}
|
|
264
|
+
// Every tag is tried, so one failure leaves as much of the site fresh as possible. Only the tags that
|
|
265
|
+
// refreshed go to onRefresh, so a host clearing what it recorded clears just those.
|
|
266
|
+
const done = [];
|
|
267
|
+
let failed = 0;
|
|
200
268
|
if (tags.length > 0) {
|
|
201
|
-
|
|
269
|
+
let revalidateTag;
|
|
270
|
+
try {
|
|
271
|
+
;
|
|
272
|
+
({ revalidateTag } = await import('next/cache.js'));
|
|
273
|
+
}
|
|
274
|
+
catch (err) {
|
|
275
|
+
log(req, 'error', `cache-refresh: next/cache could not be loaded, nothing was refreshed: ${describeThrown(err)}`);
|
|
276
|
+
return refuse('The site cache could not be reached, so nothing was refreshed.', 500, 'revalidate');
|
|
277
|
+
}
|
|
202
278
|
const profile = profileFor(mode, opts.profile);
|
|
203
|
-
for (const tag of tags)
|
|
204
|
-
|
|
279
|
+
for (const tag of tags) {
|
|
280
|
+
try {
|
|
281
|
+
await revalidateTag(tag, profile);
|
|
282
|
+
done.push(tag);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
failed += 1;
|
|
286
|
+
log(req, 'error', `cache-refresh: refreshing the tag ${JSON.stringify(tag)} failed: ${describeThrown(err)}`);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
205
289
|
}
|
|
206
290
|
const at = new Date().toISOString();
|
|
207
291
|
let audited = true;
|
|
208
|
-
if (
|
|
292
|
+
if (done.length > 0 && opts.onRefresh) {
|
|
209
293
|
try {
|
|
210
|
-
await opts.onRefresh({ who, at, count:
|
|
294
|
+
await opts.onRefresh({ who, at, count: done.length, failed, scope, mode, tags: done });
|
|
211
295
|
}
|
|
212
296
|
catch (err) {
|
|
213
297
|
audited = false;
|
|
214
|
-
req
|
|
298
|
+
log(req, 'error', `cache-refresh: onRefresh failed after the refresh: ${describeThrown(err)}`);
|
|
215
299
|
}
|
|
216
300
|
}
|
|
217
|
-
|
|
218
|
-
|
|
301
|
+
if (failed > 0) {
|
|
302
|
+
// Warming is skipped: a page list can't say which pages belong to the tags that failed.
|
|
303
|
+
const message = done.length > 0 ? `${done.length} of ${tags.length} tags were refreshed and ${failed} failed.` : 'No tags could be refreshed.';
|
|
304
|
+
return json({ refreshed: false, error: message, reason: 'revalidate', count: done.length, failed, scope, mode, at, audited, warmed: { ...NO_WARM } }, 500);
|
|
305
|
+
}
|
|
306
|
+
const warmed = done.length > 0 ? await warm(req, opts, done, scope) : { ...NO_WARM };
|
|
307
|
+
return json({ refreshed: true, count: done.length, failed: 0, scope, mode, at, audited, warmed });
|
|
219
308
|
}
|
|
220
309
|
finally {
|
|
221
310
|
running = false;
|
package/dist/types.d.ts
CHANGED
|
@@ -32,9 +32,11 @@ export type RefreshReport = {
|
|
|
32
32
|
at: string;
|
|
33
33
|
/** How many tags were refreshed. */
|
|
34
34
|
count: number;
|
|
35
|
+
/** How many tags failed to refresh. 0 for a full refresh. The failed tags are not in `tags`. */
|
|
36
|
+
failed: number;
|
|
35
37
|
scope: Scope;
|
|
36
38
|
mode: RefreshMode;
|
|
37
|
-
/** The tags
|
|
39
|
+
/** The tags that were refreshed, and only those, so the host can clear what it recorded for `changedTags`. */
|
|
38
40
|
tags: string[];
|
|
39
41
|
};
|
|
40
42
|
export type WarmResult = {
|
|
@@ -72,9 +74,16 @@ export type CacheRefreshOptions = {
|
|
|
72
74
|
warmDeadlineMs?: number;
|
|
73
75
|
/** Minimum time between refreshes, in milliseconds. A second press during a refresh or this wait gets 429. Default 5000. */
|
|
74
76
|
cooldownMs?: number;
|
|
75
|
-
/**
|
|
77
|
+
/**
|
|
78
|
+
* Origins a refresh may come from, such as `https://admin.example.org`, checked when the browser sends `Origin`. When set, only this list is used: it must hold
|
|
79
|
+
* at least one entry and every entry must be an http or https address, or the plugin refuses to start.
|
|
80
|
+
* Unset: Payload's `serverURL`, else the request's own origin.
|
|
81
|
+
*/
|
|
76
82
|
allowedOrigins?: string[];
|
|
77
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* Called after a refresh with who, when, how many and which tags. After a partial failure it gets only the tags
|
|
85
|
+
* that refreshed. It isn't called when no tag refreshed. A failure here is logged and reported, and never undoes the refresh.
|
|
86
|
+
*/
|
|
78
87
|
onRefresh?: (report: RefreshReport) => void | Promise<void>;
|
|
79
88
|
/** The endpoint's path under Payload's API route. Default `/cache-refresh`. */
|
|
80
89
|
endpointPath?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-cache-refresh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Cache refresh for Payload: an admin button that refreshes the host's Next.js cache tags for the people the host allows, with a confirmation step, stale-while-revalidate by default, a targeted or full refresh, optional page warming and an audit hook.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload",
|