@klnap/payload-redirect 0.4.1 → 0.4.2
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/CHANGELOG.md +6 -0
- package/README.md +254 -323
- package/dist/core/redirects/auto/create-redirect.js +2 -4
- package/dist/core/redirects/auto/create-redirect.js.map +1 -1
- package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +5 -0
- package/dist/core/redirects/auto/publication/get-publication-transition.js +20 -8
- package/dist/core/redirects/auto/publication/get-publication-transition.js.map +1 -1
- package/dist/core/redirects/auto/publication/global-transition.js +9 -7
- package/dist/core/redirects/auto/publication/global-transition.js.map +1 -1
- package/dist/core/redirects/auto/publication/locales.d.ts +0 -1
- package/dist/core/redirects/auto/publication/locales.js +0 -28
- package/dist/core/redirects/auto/publication/locales.js.map +1 -1
- package/dist/core/redirects/auto/publication/versions/version-rows.d.ts +2 -0
- package/dist/core/redirects/auto/publication/versions/version-rows.js +2 -0
- package/dist/core/redirects/auto/publication/versions/version-rows.js.map +1 -1
- package/docs/FAILURE_SEMANTICS.md +5 -4
- package/package.json +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 3dc1473: Fix automatic redirects for republished documents and Local API publishing. Republishing a path that has not changed no longer recreates a rule an editor deleted. Publishing one locale or all locales through the Local API links each locale whose path changed. Global publications follow the same rules. The README is rewritten and its TypeScript examples are checked against the package types.
|
|
8
|
+
|
|
3
9
|
## 0.4.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,40 +1,51 @@
|
|
|
1
1
|
# `@klnap/payload-redirect`
|
|
2
2
|
|
|
3
|
-
Redirect management for Payload CMS.
|
|
3
|
+
Redirect management for Payload CMS.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
Register the plugin once in `payload.config.ts`:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { redirects } from "@klnap/payload-redirect";
|
|
11
|
+
import { buildConfig } from "payload";
|
|
12
|
+
|
|
13
|
+
export default buildConfig({
|
|
14
|
+
// ...your database, editor, and collections
|
|
15
|
+
plugins: [
|
|
16
|
+
redirects({
|
|
17
|
+
collections: {
|
|
18
|
+
articles: { path: "/articles/[slug]" },
|
|
19
|
+
},
|
|
20
|
+
}),
|
|
21
|
+
],
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Publish an article, then change its slug and publish again:
|
|
6
26
|
|
|
7
27
|
```text
|
|
8
|
-
/articles/
|
|
9
|
-
→ /articles/
|
|
28
|
+
/articles/hello-world
|
|
29
|
+
→ /articles/introduction-to-payload (301)
|
|
10
30
|
```
|
|
11
31
|
|
|
32
|
+
The plugin stores the rule. Your application looks it up and sends the response; see [Application integration](#application-integration). Draft edits alone create no rule.
|
|
33
|
+
|
|
34
|
+
## Why?
|
|
35
|
+
|
|
36
|
+
Published URLs change when editors update content. A changed slug breaks links from search results, social posts, and other sites. Moved pages and campaign links need redirects too, and maintaining each one by hand is easy to forget.
|
|
37
|
+
|
|
38
|
+
This plugin records the change automatically when a published path moves. It also gives editors a place in the Payload Admin to manage redirects for moved pages and campaign links.
|
|
39
|
+
|
|
12
40
|
## Features
|
|
13
41
|
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
- **No runtime dependencies** beyond the Payload peer.
|
|
22
|
-
|
|
23
|
-
## Contents
|
|
24
|
-
|
|
25
|
-
- [Installation](#installation)
|
|
26
|
-
- [Complete example](#complete-example)
|
|
27
|
-
- [How it works](#how-it-works)
|
|
28
|
-
- [Configuration](#configuration)
|
|
29
|
-
- [Localization](#localization)
|
|
30
|
-
- [Globals](#globals)
|
|
31
|
-
- [Manual redirects](#manual-redirects)
|
|
32
|
-
- [Serving redirects](#serving-redirects)
|
|
33
|
-
- [Overrides and access](#overrides-and-access)
|
|
34
|
-
- [Reference](#reference)
|
|
35
|
-
- [Compatibility](#compatibility)
|
|
36
|
-
- [Limitations](#limitations)
|
|
37
|
-
- [Documentation](#documentation)
|
|
42
|
+
- Automatic `301` rules when a published path changes, including changes to other fields in the path, such as a category.
|
|
43
|
+
- Configuration next to the schema with `custom.redirect`, or centrally in `redirects()`.
|
|
44
|
+
- Collections and Globals with the same rules.
|
|
45
|
+
- Native Payload localization with one template per locale, or one shared template with locale prefixes.
|
|
46
|
+
- Manual `301` and `302` rules, enabled or disabled, with query strings and fragments.
|
|
47
|
+
- Duplicate sources and loops are rejected. Manual rules are never overwritten by automatic ones.
|
|
48
|
+
- No runtime dependencies beyond the Payload peer.
|
|
38
49
|
|
|
39
50
|
## Installation
|
|
40
51
|
|
|
@@ -46,34 +57,118 @@ bun add @klnap/payload-redirect
|
|
|
46
57
|
npm install @klnap/payload-redirect
|
|
47
58
|
```
|
|
48
59
|
|
|
49
|
-
`payload` is a required peer. `@payloadcms/db-postgres` is an optional peer
|
|
60
|
+
`payload` is a required peer dependency. `@payloadcms/db-postgres` is an optional peer dependency; install it when you use PostgreSQL. Node.js versions are listed in [Compatibility](#compatibility-and-documentation).
|
|
50
61
|
|
|
51
|
-
##
|
|
62
|
+
## Usage
|
|
52
63
|
|
|
53
|
-
|
|
64
|
+
### Automatic redirects
|
|
54
65
|
|
|
55
|
-
|
|
66
|
+
Add `custom.redirect` to any Collection with drafts enabled:
|
|
56
67
|
|
|
57
68
|
```ts
|
|
58
|
-
|
|
59
|
-
import {
|
|
60
|
-
import {
|
|
61
|
-
import { redirects } from "@klnap/payload-redirect";
|
|
62
|
-
import { Articles } from "./collections/Articles";
|
|
63
|
-
import { About } from "./globals/About";
|
|
69
|
+
// src/collections/Articles.ts
|
|
70
|
+
import type { CollectionConfig } from "payload";
|
|
71
|
+
import type { RedirectCollectionOptions } from "@klnap/payload-redirect";
|
|
64
72
|
|
|
73
|
+
export const Articles: CollectionConfig = {
|
|
74
|
+
slug: "articles",
|
|
75
|
+
versions: { drafts: true },
|
|
76
|
+
admin: { useAsTitle: "title" },
|
|
77
|
+
fields: [
|
|
78
|
+
{ name: "title", type: "text", required: true },
|
|
79
|
+
{ name: "slug", type: "text", required: true },
|
|
80
|
+
],
|
|
81
|
+
custom: {
|
|
82
|
+
redirect: {
|
|
83
|
+
path: "/articles/[slug]",
|
|
84
|
+
} satisfies RedirectCollectionOptions<"articles">,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Register the plugin without options:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
plugins: [redirects()],
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Central configuration does the same job. Use either pattern, not both. A central entry replaces the entity's `custom.redirect` for that entity.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
redirects({
|
|
99
|
+
collections: {
|
|
100
|
+
articles: { path: "/articles/[slug]" },
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
A route is one of three strategies:
|
|
106
|
+
|
|
107
|
+
| Option | Use when |
|
|
108
|
+
| --------- | ------------------------------------------------------------------------------------- |
|
|
109
|
+
| `path` | The route is a template over top-level fields, such as `/articles/[slug]`. |
|
|
110
|
+
| `paths` | Each locale has its own template. See [Localization](#localization). |
|
|
111
|
+
| `getPath` | The route depends on logic a template cannot express. Return `null` to skip a locale. |
|
|
112
|
+
|
|
113
|
+
Prefer `path` and `paths`. Use `getPath` only when you need it:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
custom: {
|
|
117
|
+
redirect: {
|
|
118
|
+
getPath: ({ doc }) => (doc.category === "interviews" ? `/interviews/${doc.slug}` : null),
|
|
119
|
+
} satisfies RedirectCollectionOptions<"articles">,
|
|
120
|
+
},
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Values in `getPath` are not encoded for you. Encode dynamic segments with `encodeURIComponent` when they can contain spaces or reserved characters.
|
|
124
|
+
|
|
125
|
+
A rule is created only when a publication changes the published path. Draft saves, unchanged republications, and unpublishing create nothing. Existing rules stay when a document is unpublished or deleted. A first publication creates nothing either, because there is no previous path.
|
|
126
|
+
|
|
127
|
+
Full-path tracking uses several fields. A category change then creates a redirect even when the slug stays the same:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
path: "/articles/[category]/[slug]",
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Globals
|
|
134
|
+
|
|
135
|
+
Globals work the same way. Give the Global drafts and a `custom.redirect` entry. This About page is a familiar example:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
// src/globals/About.ts
|
|
139
|
+
import type { GlobalConfig } from "payload";
|
|
140
|
+
import type { RedirectGlobalOptions } from "@klnap/payload-redirect";
|
|
141
|
+
|
|
142
|
+
export const About: GlobalConfig = {
|
|
143
|
+
slug: "about",
|
|
144
|
+
versions: { drafts: true },
|
|
145
|
+
fields: [{ name: "slug", type: "text", required: true }],
|
|
146
|
+
custom: {
|
|
147
|
+
redirect: {
|
|
148
|
+
path: "/[slug]",
|
|
149
|
+
} satisfies RedirectGlobalOptions<"about">,
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Publishing a new slug `about-us` creates this redirect:
|
|
155
|
+
|
|
156
|
+
```text
|
|
157
|
+
/about → /about-us (301)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Localization
|
|
161
|
+
|
|
162
|
+
The plugin uses Payload's native content localization. Configure locales in `buildConfig`, make the slug field localized, and give each locale its path in `paths`:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
// payload.config.ts
|
|
65
166
|
export default buildConfig({
|
|
66
|
-
secret: process.env.PAYLOAD_SECRET ?? "",
|
|
67
|
-
editor: lexicalEditor(),
|
|
68
|
-
db: postgresAdapter({
|
|
69
|
-
pool: { connectionString: process.env.DATABASE_URI },
|
|
70
|
-
}),
|
|
71
167
|
localization: {
|
|
72
168
|
locales: ["en", "fr", "de"],
|
|
73
169
|
defaultLocale: "en",
|
|
74
170
|
},
|
|
75
|
-
|
|
76
|
-
globals: [About],
|
|
171
|
+
// ...
|
|
77
172
|
plugins: [
|
|
78
173
|
redirects({
|
|
79
174
|
localePrefixes: { en: "", fr: "/fr", de: "/de" },
|
|
@@ -82,28 +177,20 @@ export default buildConfig({
|
|
|
82
177
|
});
|
|
83
178
|
```
|
|
84
179
|
|
|
85
|
-
`redirects()` is called once. It adds the `redirects` collection, the publication hooks, and the locale prefixes.
|
|
86
|
-
|
|
87
|
-
### 2. `src/collections/Articles.ts`
|
|
88
|
-
|
|
89
180
|
```ts
|
|
90
|
-
|
|
91
|
-
import type { RedirectCollectionOptions } from "@klnap/payload-redirect";
|
|
92
|
-
|
|
181
|
+
// src/collections/Articles.ts
|
|
93
182
|
export const Articles: CollectionConfig = {
|
|
94
183
|
slug: "articles",
|
|
95
184
|
versions: { drafts: true },
|
|
96
|
-
admin: { useAsTitle: "title" },
|
|
97
185
|
fields: [
|
|
98
186
|
{ name: "title", type: "text", required: true, localized: true },
|
|
99
187
|
{ name: "slug", type: "text", required: true, localized: true },
|
|
100
|
-
{ name: "category", type: "text", required: true },
|
|
101
188
|
],
|
|
102
189
|
custom: {
|
|
103
190
|
redirect: {
|
|
104
191
|
paths: {
|
|
105
192
|
en: "/articles/[slug]",
|
|
106
|
-
fr: "/
|
|
193
|
+
fr: "/articles/[slug]",
|
|
107
194
|
de: "/artikel/[slug]",
|
|
108
195
|
},
|
|
109
196
|
} satisfies RedirectCollectionOptions<"articles">,
|
|
@@ -111,33 +198,73 @@ export const Articles: CollectionConfig = {
|
|
|
111
198
|
};
|
|
112
199
|
```
|
|
113
200
|
|
|
114
|
-
|
|
201
|
+
With these settings the same article has one path per locale:
|
|
115
202
|
|
|
116
|
-
|
|
203
|
+
| Locale | Slug | Public path |
|
|
204
|
+
| ------ | ----------------- | ---------------------------- |
|
|
205
|
+
| `en` | `getting-started` | `/articles/getting-started` |
|
|
206
|
+
| `fr` | `premiers-pas` | `/fr/articles/premiers-pas` |
|
|
207
|
+
| `de` | `erste-schritte` | `/de/artikel/erste-schritte` |
|
|
117
208
|
|
|
118
|
-
|
|
119
|
-
import type { GlobalConfig } from "payload";
|
|
120
|
-
import type { RedirectGlobalOptions } from "@klnap/payload-redirect";
|
|
209
|
+
Changing the French slug to `bien-demarrer` and publishing creates only the French redirect:
|
|
121
210
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
fields: [{ name: "slug", type: "text", required: true, localized: true }],
|
|
126
|
-
custom: {
|
|
127
|
-
redirect: {
|
|
128
|
-
getPath: ({ doc, locale }) => `${locale === "fr" ? "/fr" : ""}/${doc.slug}`,
|
|
129
|
-
} satisfies RedirectGlobalOptions<"about">,
|
|
130
|
-
},
|
|
131
|
-
};
|
|
211
|
+
```text
|
|
212
|
+
/fr/articles/premiers-pas
|
|
213
|
+
→ /fr/articles/bien-demarrer (301)
|
|
132
214
|
```
|
|
133
215
|
|
|
134
|
-
|
|
216
|
+
Rules for localized paths:
|
|
217
|
+
|
|
218
|
+
- `path` is one template for every locale. `paths` gives one template per locale and must list every locale in `localization.locales`.
|
|
219
|
+
- `localePrefixes` adds a prefix to `path` and `paths`. It must list every locale. Use `""` for the default locale.
|
|
220
|
+
- A locale without a slug is skipped. Generation never uses another locale's slug, even when Payload's fallback is enabled for reads.
|
|
221
|
+
- Redirect rules have no locale. Different locales need different source paths.
|
|
222
|
+
- Payload's experimental localized publication status (`localizeStatus`) is supported at the level described in [Compatibility](#compatibility-and-documentation).
|
|
223
|
+
|
|
224
|
+
For Globals, the same `localePrefixes` apply to the template. `/about` becomes `/fr/about` in French; use a localized slug field for the translated page name, such as `/fr/a-propos` and `/de/uber-uns`.
|
|
225
|
+
|
|
226
|
+
### Manual redirects
|
|
135
227
|
|
|
136
|
-
|
|
228
|
+
`redirects()` registers a Payload collection named `redirects`. Editors create and edit rules in the Payload Admin. Manual rules need no automatic configuration and no tracked Collection or Global.
|
|
137
229
|
|
|
138
|
-
|
|
230
|
+
| From | To | Status |
|
|
231
|
+
| -------------- | -------------------------------------- | ------ |
|
|
232
|
+
| `/old-page` | `/new-page` | `301` |
|
|
233
|
+
| `/old-guide` | `/guides/getting-started#installation` | `301` |
|
|
234
|
+
| `/summer-sale` | `/offers` | `302` |
|
|
235
|
+
|
|
236
|
+
Use `301` for a permanent move. Use `302` for a temporary destination, such as a seasonal offer. Destinations may include a fragment. Sources may not.
|
|
237
|
+
|
|
238
|
+
### Campaign links
|
|
239
|
+
|
|
240
|
+
Share short, readable URLs in SMS campaigns, newsletters, or promotional materials. A manual rule sends visitors to the landing page with campaign parameters:
|
|
241
|
+
|
|
242
|
+
| Field | Value |
|
|
243
|
+
| ------------ | --------------------------------------------------------------------- |
|
|
244
|
+
| `from` | `/summer-2027` |
|
|
245
|
+
| `to` | `/summer-2027?utm_source=sms&utm_medium=sms&utm_campaign=summer_2027` |
|
|
246
|
+
| `statusCode` | `302` |
|
|
247
|
+
| `enabled` | `true` |
|
|
248
|
+
|
|
249
|
+
The public pathname stays the same. Only the destination carries the parameters.
|
|
250
|
+
|
|
251
|
+
Query strings follow these rules:
|
|
252
|
+
|
|
253
|
+
- Sources and destinations may contain a query string. Matching is exact: `/campaign?ref=sms` is different from `/campaign` and from `/campaign?ref=email`.
|
|
254
|
+
- A source and destination can share a pathname when their query strings differ. The application must include the query string in its lookup, shown in [Application integration](#application-integration). Otherwise the landing request matches the campaign rule again.
|
|
255
|
+
- Parameters are not merged, reordered, or forwarded. The destination is the stored `to`.
|
|
256
|
+
- Automatic routes have no query strings. Campaign rules are ordinary manual rules.
|
|
257
|
+
|
|
258
|
+
Editing or disabling an automatic rule in the Payload Admin turns it into a manual rule, and later publications no longer change it. A manual rule that already owns a source path is never overwritten by an automatic one.
|
|
259
|
+
|
|
260
|
+
The plugin stores these rules only. It does not collect attribution data or connect to analytics or advertising tools.
|
|
261
|
+
|
|
262
|
+
## Application integration
|
|
263
|
+
|
|
264
|
+
The plugin stores rules and never sends a response. The example below is illustrative: the plugin does not run it in a Next.js app, and how your application serves redirects is up to you. Your application looks each request up and redirects. The example below is for Next.js 16 (`src/proxy.ts`); the same logic works in any framework that can call the Payload Local API.
|
|
139
265
|
|
|
140
266
|
```ts
|
|
267
|
+
// src/proxy.ts
|
|
141
268
|
import { NextResponse, type NextRequest } from "next/server";
|
|
142
269
|
import { getPayload } from "payload";
|
|
143
270
|
import payloadConfig from "@payload-config";
|
|
@@ -166,8 +293,8 @@ export async function proxy(request: NextRequest) {
|
|
|
166
293
|
const rule = docs[0];
|
|
167
294
|
if (!rule) return NextResponse.next();
|
|
168
295
|
|
|
296
|
+
// Never redirect a request to the URL it already has.
|
|
169
297
|
const target = new URL(rule.to, request.url);
|
|
170
|
-
// A rule that points at the current path and query would redirect forever. Fragments are not sent to the server.
|
|
171
298
|
if (target.pathname + target.search === from) return NextResponse.next();
|
|
172
299
|
|
|
173
300
|
return NextResponse.redirect(target, Number(rule.statusCode) as 301 | 302);
|
|
@@ -178,295 +305,99 @@ export const config = {
|
|
|
178
305
|
};
|
|
179
306
|
```
|
|
180
307
|
|
|
181
|
-
`@payload-config` is the alias that the Payload Next.js template sets up. It points to your `payload.config.ts`.
|
|
182
|
-
|
|
183
|
-
## How it works
|
|
184
|
-
|
|
185
|
-
The plugin compares the complete public path of the newly published version with the path of the previously published version. It does not compare slugs alone.
|
|
186
|
-
|
|
187
|
-
| Event | Result |
|
|
188
|
-
| ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
|
|
189
|
-
| First publication | No rule. |
|
|
190
|
-
| Draft save | No rule. |
|
|
191
|
-
| Republication, path unchanged | An identical enabled automatic rule is left as is. |
|
|
192
|
-
| Republication, path changed | A `301` from the old path to the new one is created or updated and enabled. |
|
|
193
|
-
| Previous published version has no resolvable path in a locale | That locale is skipped. |
|
|
194
|
-
| A manual rule already owns the source path | The automatic write is skipped and the manual rule stays unchanged. |
|
|
195
|
-
| Editor edits or manually disables an automatic rule | Its origin becomes `manual`, and later publications no longer manage it. |
|
|
196
|
-
| Unpublish or delete | No new rule. Existing rules stay. |
|
|
197
|
-
| Return to an earlier path that would close a loop in enabled rules | The write is rejected and the publication fails. |
|
|
198
|
-
|
|
199
|
-
Route changes do not migrate historical URLs. Add manual rules for older paths if you need them.
|
|
200
|
-
|
|
201
|
-
## Configuration
|
|
202
|
-
|
|
203
|
-
You can configure automatic redirects in two places. Use `custom.redirect` by default.
|
|
204
|
-
|
|
205
|
-
### `custom.redirect` on the entity
|
|
206
|
-
|
|
207
|
-
Each Collection or Global gets its own `custom.redirect` object. The plugin reads it when Payload builds the config, so the route sits next to the fields it uses.
|
|
208
|
-
|
|
209
|
-
| Option | Type | Description |
|
|
210
|
-
| --------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
211
|
-
| `path` | `string` | One site-relative template for all locales. Starts with `/`; no query string or fragment. |
|
|
212
|
-
| `paths` | `Record<Locale, string>` | One template per Payload locale. Requires `localization`. Must cover every locale exactly. |
|
|
213
|
-
| `getPath` | `({ doc, locale }) => string \| null` | Synchronous callback for conditional routes. Returns a complete site-relative path, or `null` to skip a locale. |
|
|
214
|
-
| `enabled` | `boolean` | Defaults to `true` when a strategy is set. `false` alone keeps manual redirects and stops generation. |
|
|
215
|
-
|
|
216
|
-
Use exactly one of `path`, `paths`, or `getPath`. `enabled: false` cannot be combined with a strategy.
|
|
217
|
-
|
|
218
|
-
Type the option with `RedirectCollectionOptions<"articles">` for a Collection or `RedirectGlobalOptions<"about">` for a Global. Both are generic over the slug, so `doc` in `getPath` has that entity's fields.
|
|
219
|
-
|
|
220
|
-
**`path`** uses top-level field names in brackets. Each value must be a non-empty string or finite number. The plugin encodes it as one path segment:
|
|
221
|
-
|
|
222
|
-
```ts
|
|
223
|
-
// src/collections/Articles.ts (custom only)
|
|
224
|
-
custom: {
|
|
225
|
-
redirect: {
|
|
226
|
-
path: "/articles/[category]/[slug]",
|
|
227
|
-
} satisfies RedirectCollectionOptions<"articles">,
|
|
228
|
-
},
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
A missing or unsafe value skips path resolution for that locale.
|
|
232
|
-
|
|
233
|
-
**`getPath`** handles conditional routes. Here is a complete collection with it:
|
|
234
|
-
|
|
235
|
-
```ts
|
|
236
|
-
// src/collections/Articles.ts
|
|
237
|
-
import type { CollectionConfig } from "payload";
|
|
238
|
-
import type { RedirectCollectionOptions } from "@klnap/payload-redirect";
|
|
239
|
-
|
|
240
|
-
export const Articles: CollectionConfig = {
|
|
241
|
-
slug: "articles",
|
|
242
|
-
versions: { drafts: true },
|
|
243
|
-
admin: { useAsTitle: "title" },
|
|
244
|
-
fields: [
|
|
245
|
-
{ name: "title", type: "text", required: true },
|
|
246
|
-
{ name: "slug", type: "text", required: true },
|
|
247
|
-
{ name: "category", type: "text", required: true },
|
|
248
|
-
],
|
|
249
|
-
custom: {
|
|
250
|
-
redirect: {
|
|
251
|
-
getPath: ({ doc }) => {
|
|
252
|
-
if (!doc.category || !doc.slug) return null;
|
|
253
|
-
|
|
254
|
-
const category = encodeURIComponent(doc.category);
|
|
255
|
-
const slug = encodeURIComponent(doc.slug);
|
|
256
|
-
|
|
257
|
-
return doc.category === "interviews"
|
|
258
|
-
? `/interviews/${slug}`
|
|
259
|
-
: `/articles/${category}/${slug}`;
|
|
260
|
-
},
|
|
261
|
-
} satisfies RedirectCollectionOptions<"articles">,
|
|
262
|
-
},
|
|
263
|
-
};
|
|
264
|
-
```
|
|
265
|
-
|
|
266
|
-
The callback is synchronous. The plugin does not add locale prefixes to its result, so add them yourself when you need them. Return `null` to skip a locale. An exception thrown by the callback is not converted to a skip.
|
|
267
|
-
|
|
268
|
-
### Central configuration: `redirects()`
|
|
269
|
-
|
|
270
|
-
You can also configure entities in the plugin call. This is useful when you cannot edit the Collection or Global, or when the route is a site-wide decision:
|
|
271
|
-
|
|
272
|
-
```ts
|
|
273
|
-
redirects({
|
|
274
|
-
localePrefixes: { en: "", fr: "/fr", de: "/de" },
|
|
275
|
-
collections: {
|
|
276
|
-
articles: { path: "/articles/[category]/[slug]" },
|
|
277
|
-
},
|
|
278
|
-
globals: {
|
|
279
|
-
about: { path: "/[slug]" },
|
|
280
|
-
},
|
|
281
|
-
});
|
|
282
|
-
```
|
|
283
|
-
|
|
284
|
-
**Precedence.** A central entry replaces that entity's `custom.redirect`. The two are never merged. Central `collections` and `globals` maps are independent, even when their slugs match.
|
|
308
|
+
`@payload-config` is the alias that the Payload Next.js template sets up. It points to your `payload.config.ts`. If you renamed the redirects collection with `overrides.slug`, use that slug here.
|
|
285
309
|
|
|
286
|
-
|
|
310
|
+
How the lookup matches:
|
|
287
311
|
|
|
288
|
-
The
|
|
312
|
+
- The lookup is exact. It joins the normalized pathname and the query string (`request.nextUrl.search`, which includes the leading `?`). `/campaign?ref=sms` matches only that query string.
|
|
313
|
+
- The path is not decoded. A browser always sends encoded characters, so store the encoded form of a path: a rule for `/café` must be stored as `/caf%C3%A9`.
|
|
314
|
+
- Trailing slashes and repeated slashes are normalized the same way the plugin stores paths, so `/articles/hello-world/` matches `/articles/hello-world`.
|
|
315
|
+
- Next.js may already redirect some URLs before `proxy.ts` runs, for example to add or remove a trailing slash.
|
|
289
316
|
|
|
290
|
-
|
|
317
|
+
A pathname-only rule does not match a request with extra query parameters. If you want generic pathname rules to apply to any query string, add a second lookup in your application after the exact one, and make sure the redirect cannot repeat. Keep the exact match first. The plugin does not provide this fallback.
|
|
291
318
|
|
|
292
|
-
|
|
293
|
-
| ------ | ------------------------------ | ------------------------------------------ |
|
|
294
|
-
| `en` | `getting-started-with-payload` | `/articles/getting-started-with-payload` |
|
|
295
|
-
| `fr` | `premiers-pas-avec-payload` | `/fr/actualites/premiers-pas-avec-payload` |
|
|
296
|
-
| `de` | `erste-schritte-mit-payload` | `/de/artikel/erste-schritte-mit-payload` |
|
|
297
|
-
|
|
298
|
-
Publishing a new French slug `introduction-a-payload` creates only this redirect:
|
|
299
|
-
|
|
300
|
-
```text
|
|
301
|
-
/fr/actualites/premiers-pas-avec-payload
|
|
302
|
-
→ /fr/actualites/introduction-a-payload (301)
|
|
303
|
-
```
|
|
319
|
+
## Configuration and access control
|
|
304
320
|
|
|
305
|
-
|
|
321
|
+
### Plugin options
|
|
306
322
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
- Payload content localization translates article data. Payload `i18n` translates the Admin UI. Plugin labels and validation messages are English.
|
|
323
|
+
| Option | Default | Description |
|
|
324
|
+
| ---------------- | ----------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
325
|
+
| `collections` | None | Central configuration for Collections. Replaces the entity's `custom.redirect`. |
|
|
326
|
+
| `globals` | None | Central configuration for Globals. Replaces the entity's `custom.redirect`. |
|
|
327
|
+
| `localePrefixes` | No prefixes | One prefix per locale, applied to `path` and `paths`. Must list every locale. |
|
|
328
|
+
| `overrides` | Plugin-owned `redirects` collection | Native Payload collection options, plus `fields` to add fields. Required fields are kept. |
|
|
314
329
|
|
|
315
|
-
|
|
330
|
+
### Overrides
|
|
316
331
|
|
|
317
|
-
|
|
332
|
+
`overrides` passes options to the plugin-owned collection. This example renames it and adds a note field:
|
|
318
333
|
|
|
319
334
|
```ts
|
|
320
335
|
redirects({
|
|
321
|
-
|
|
322
|
-
|
|
336
|
+
overrides: {
|
|
337
|
+
slug: "url-redirects",
|
|
338
|
+
admin: { group: "Settings" },
|
|
339
|
+
fields: ({ defaultFields }) => [...defaultFields, { name: "editorNote", type: "textarea" }],
|
|
323
340
|
},
|
|
324
341
|
});
|
|
325
342
|
```
|
|
326
343
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
`redirects()` registers the plugin-owned `redirects` collection. Create, edit, enable, or disable manual rules in the Payload Admin. Manual rules need no automatic configuration.
|
|
344
|
+
Then change `collection: "redirects"` to `collection: "url-redirects"` in your application lookup.
|
|
330
345
|
|
|
331
|
-
|
|
332
|
-
- `to` is a normalized site-relative path that differs from `from`. Absolute URLs are not accepted here.
|
|
333
|
-
- `statusCode` is `301` (default) or `302`.
|
|
334
|
-
- `enabled` defaults to `true`. `origin` is `manual` for rules you create and `auto` for generated ones.
|
|
346
|
+
### Access control
|
|
335
347
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
Share short, readable URLs in SMS campaigns, newsletters, or promotional materials. A manual rule redirects visitors to the landing page with campaign parameters:
|
|
339
|
-
|
|
340
|
-
| Field | Value |
|
|
341
|
-
| ------------ | --------------------------------------------------------------------- |
|
|
342
|
-
| `from` | `/summer-2027` |
|
|
343
|
-
| `to` | `/summer-2027?utm_source=sms&utm_medium=sms&utm_campaign=summer_2027` |
|
|
344
|
-
| `statusCode` | `302` |
|
|
345
|
-
| `enabled` | `true` |
|
|
346
|
-
|
|
347
|
-
Rules for query strings:
|
|
348
|
-
|
|
349
|
-
- Sources and destinations may contain a query string. Source matching is exact, so `/campaign?ref=sms` is distinct from `/campaign` and from `/campaign?ref=email`.
|
|
350
|
-
- A source and destination may share a pathname when their query strings differ. The lookup in [Serving redirects](#serving-redirects) includes `search`, so the landing request does not match the campaign rule again.
|
|
351
|
-
- The plugin does not forward or merge incoming query parameters. The destination is the stored `to`.
|
|
352
|
-
- Automatic content paths have no query strings. Campaign rules are ordinary manual rules.
|
|
353
|
-
|
|
354
|
-
The plugin stores these rules only. It does not collect attribution data or integrate with analytics or advertising tools.
|
|
355
|
-
|
|
356
|
-
Register `redirects()` once. A second registration throws. The collection slug defaults to `redirects`. Change it with `overrides.slug` if that slug is taken.
|
|
357
|
-
|
|
358
|
-
## Serving redirects
|
|
348
|
+
The redirects collection uses Payload's native access defaults. Anyone who is not logged in cannot read or write rules.
|
|
359
349
|
|
|
360
|
-
|
|
350
|
+
Automatic generation runs inside the publication hook with trusted Local API calls (`overrideAccess: true`). Editors who publish content therefore create redirects without holding redirect permissions. REST, GraphQL, and user-scoped Local API calls follow your access rules.
|
|
361
351
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
| Input | Stored source |
|
|
365
|
-
| ------------------------ | ------------------------------------ |
|
|
366
|
-
| `/articles/old/` | `/articles/old` |
|
|
367
|
-
| `/articles//old` | `/articles/old` |
|
|
368
|
-
| `/a/../b` | `/b` |
|
|
369
|
-
| `/café` | `/café` (distinct from `/caf%C3%A9`) |
|
|
370
|
-
| `/articles/old?ref=mail` | `/articles/old?ref=mail` |
|
|
371
|
-
|
|
372
|
-
Normalization trims whitespace, adds a leading slash, collapses repeated slashes, resolves `.` and `..` segments (including percent-encoded forms), and removes a trailing slash except at `/`. It preserves Unicode, percent encoding, and query strings. Fragments are rejected.
|
|
373
|
-
|
|
374
|
-
Lookup is exact. The request path is not decoded, so a browser request for `/caf%C3%A9` matches only a rule stored as `/caf%C3%A9`, and a rule stored as `/café` never matches a browser request. Store the percent-encoded form for paths that browsers request. Query parameters are not reordered, merged, or forwarded: the destination is the stored `to`.
|
|
375
|
-
|
|
376
|
-
A pathname-only rule does not match a request that has extra query parameters. Add a second rule with the exact query string if needed. Automatic rules use paths without query strings.
|
|
377
|
-
|
|
378
|
-
## Overrides and access
|
|
379
|
-
|
|
380
|
-
`overrides` passes native Payload collection options to the plugin-owned collection. This example renames it, moves it into a group, adds a field, and makes it readable:
|
|
352
|
+
Public read access is opt-in:
|
|
381
353
|
|
|
382
354
|
```ts
|
|
383
|
-
// payload.config.ts
|
|
384
355
|
redirects({
|
|
385
|
-
localePrefixes: { en: "", fr: "/fr", de: "/de" },
|
|
386
356
|
overrides: {
|
|
387
|
-
slug: "url-redirects",
|
|
388
|
-
admin: { group: "Settings" },
|
|
389
357
|
access: {
|
|
390
358
|
read: () => true,
|
|
391
359
|
},
|
|
392
|
-
fields: ({ defaultFields }) => [...defaultFields, { name: "editorNote", type: "textarea" }],
|
|
393
360
|
},
|
|
394
361
|
});
|
|
395
362
|
```
|
|
396
363
|
|
|
397
|
-
|
|
364
|
+
Public reads return every field the rule allows, including disabled rules and editor notes. Use field-level `access` to hide fields you do not want public.
|
|
398
365
|
|
|
399
|
-
|
|
366
|
+
Your application's lookup in [Application integration](#application-integration) uses trusted server-side access and does not need public read access.
|
|
400
367
|
|
|
401
|
-
|
|
368
|
+
## Compatibility and documentation
|
|
402
369
|
|
|
403
|
-
|
|
370
|
+
| Requirement | Support |
|
|
371
|
+
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
372
|
+
| Node.js | `^22.23.5`, `^24.22.3`, or `>=26.13.1`, as declared in `engines`. |
|
|
373
|
+
| Payload | Declared peer range `>=3.94.1 <4`. The test suite runs against Payload `3.94.1`, the version in the development dependencies. Other 3.x versions are not tested. |
|
|
374
|
+
| PostgreSQL | `@payloadcms/db-postgres` peer `>=3.94.1 <4`. The integration tests run against PostgreSQL 16. Redirect graph writes are serialized with a transaction-scoped advisory lock. |
|
|
375
|
+
| Other database adapters | Not tested. No concurrency guarantee is claimed for them. |
|
|
376
|
+
| Localized publication status | Payload's experimental `localizeStatus`. The plugin follows the per-locale publication status Payload stores; see [Limitations](#limitations). |
|
|
377
|
+
| Application framework | The rule store is framework-independent. The lookup example targets Next.js 16. |
|
|
404
378
|
|
|
405
|
-
###
|
|
379
|
+
### Limitations
|
|
406
380
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
| `from` | `string` | Required | Unique normalized site-relative source path. No fragment. |
|
|
419
|
-
| `to` | `string` | Required | Normalized site-relative destination. Must differ from `from`. |
|
|
420
|
-
| `statusCode` | `"301" \| "302"` | `"301"` | Redirect status. |
|
|
421
|
-
| `enabled` | `boolean` | `true` | Disabled rules are not used for lookup or loop checks. |
|
|
422
|
-
| `origin` | `"manual" \| "auto"` | `manual` | Whether the plugin manages the rule. |
|
|
423
|
-
|
|
424
|
-
Enabled rules are checked for loops and for chains longer than 1,000 hops at write time. The check does not see loops created by host routing, external redirects, or browser URL equivalence.
|
|
425
|
-
|
|
426
|
-
### Exports
|
|
427
|
-
|
|
428
|
-
| Export | Kind | Purpose |
|
|
429
|
-
| --------------------------- | ----- | ----------------------------------------------------------- |
|
|
430
|
-
| `redirects` | Value | Returns the Payload plugin. |
|
|
431
|
-
| `RedirectsOptions` | Type | Options for `redirects()`. |
|
|
432
|
-
| `RedirectCollectionOptions` | Type | Options for a Collection, generic over the collection slug. |
|
|
433
|
-
| `RedirectGlobalOptions` | Type | Options for a Global, generic over the global slug. |
|
|
434
|
-
| `RedirectOrigin` | Type | `"manual" \| "auto"`. |
|
|
435
|
-
| `RedirectStatusCode` | Type | `301 \| 302`. |
|
|
436
|
-
|
|
437
|
-
## Compatibility
|
|
438
|
-
|
|
439
|
-
| Requirement | Support |
|
|
440
|
-
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
441
|
-
| Node.js | `^22.23.5`, `^24.22.3`, or `>=26.13.1`. |
|
|
442
|
-
| Payload | Tested with Payload `3.94.1` and `3.93.0`: unit and integration tests pass on both. Declared peer range is `>=3.94.1 <4`. Older 3.x versions should work too, but this repository has not tested them. |
|
|
443
|
-
| PostgreSQL | Optional `@payloadcms/db-postgres` peer, `>=3.94.1 <4`. Integration tests run against PostgreSQL 16. Rule-graph writes run in a Payload transaction at `READ COMMITTED`. |
|
|
444
|
-
| Other database adapters | Not verified. No equivalent concurrency guarantee is claimed. |
|
|
445
|
-
| Automatic redirects | Require `versions.drafts` on each configured Collection or Global. |
|
|
446
|
-
| Content localization | Requires `localization.locales` and `localization.defaultLocale`. Each locale resolves without fallback. |
|
|
447
|
-
| Localized publication status | Opt-in with `experimental.localizeStatus: true` and `versions.drafts.localizeStatus: true`. Payload marks this feature experimental; this package's per-locale coverage is basic. |
|
|
448
|
-
| Frontend framework | The rule store is framework-independent. The serving example targets Next.js 16. |
|
|
449
|
-
|
|
450
|
-
## Limitations
|
|
451
|
-
|
|
452
|
-
- Route changes do not migrate historical URLs. Add manual rules for older paths.
|
|
453
|
-
- Rules have no locale, domain, or host scope.
|
|
454
|
-
- Cycle detection covers enabled stored rules only.
|
|
455
|
-
- Request matching, caching, and HTTP responses are the application's responsibility. The lookup in `proxy.ts` runs on every matched request.
|
|
456
|
-
|
|
457
|
-
## Documentation
|
|
381
|
+
- Route changes do not migrate old URLs. Add manual rules for paths you changed before the plugin was installed.
|
|
382
|
+
- Automatic rules follow the published history that Payload keeps. If retention removes the version that held the previous path, no rule is created for that change.
|
|
383
|
+
- Restoring an older version publishes it and creates a rule. The restore is rejected when that rule would close a loop with enabled rules.
|
|
384
|
+
- Changes to the route configuration are not compared with old content paths. Edit manual rules for those.
|
|
385
|
+
- Source paths are unique across all Collections and Globals, and rules have no locale, domain, or host scope.
|
|
386
|
+
- Loop detection covers enabled stored rules. It cannot see loops created by host routing, external redirects, or browser URL equivalence.
|
|
387
|
+
- Request matching, caching, and HTTP responses belong to your application. Lookups run on every matched request, so keep the matcher narrow.
|
|
388
|
+
- Localized publication status depends on Payload's experimental feature. This package's coverage of it is limited to the cases described in its tests.
|
|
389
|
+
- Fragments are not allowed on source paths. Destinations may include them.
|
|
390
|
+
|
|
391
|
+
### Documentation
|
|
458
392
|
|
|
459
393
|
- [Failure semantics](./docs/FAILURE_SEMANTICS.md): exact behavior for each configuration and write error.
|
|
460
|
-
- [Releasing](
|
|
394
|
+
- [Releasing](https://github.com/klnap/payload-redirect/blob/main/docs/RELEASING.md): release process for maintainers.
|
|
395
|
+
- [Contributing](https://github.com/klnap/payload-redirect/blob/main/CONTRIBUTING.md): development setup and checks.
|
|
396
|
+
- [Security policy](https://github.com/klnap/payload-redirect/blob/main/SECURITY.md): how to report vulnerabilities.
|
|
461
397
|
- [Payload content localization](https://payloadcms.com/docs/configuration/localization)
|
|
462
|
-
- [Payload localized publication status](https://payloadcms.com/docs/configuration/localization#status-localization)
|
|
463
398
|
- [Payload drafts and versions](https://payloadcms.com/docs/versions/drafts)
|
|
464
399
|
- [Payload Local API](https://payloadcms.com/docs/local-api/overview)
|
|
465
400
|
|
|
466
|
-
## Contributing
|
|
467
|
-
|
|
468
|
-
See [CONTRIBUTING.md](./CONTRIBUTING.md). Report security issues through [SECURITY.md](./SECURITY.md).
|
|
469
|
-
|
|
470
401
|
## License
|
|
471
402
|
|
|
472
|
-
[
|
|
403
|
+
MIT. See [LICENSE](./LICENSE).
|
|
@@ -9,10 +9,8 @@ export const createRedirectsFromTransitions = async ({ req, redirectCollectionSl
|
|
|
9
9
|
if (!currentPath)
|
|
10
10
|
continue;
|
|
11
11
|
const to = normalizePathOrUrl(currentPath);
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return !path || normalizePathOrUrl(path) !== to;
|
|
15
|
-
});
|
|
12
|
+
// publishedDocs is newest first and starts with the publication that just ran.
|
|
13
|
+
const previousPublishedDoc = publishedDocs[1];
|
|
16
14
|
if (!previousPublishedDoc)
|
|
17
15
|
continue;
|
|
18
16
|
const previousPath = buildPublishedPath(pathOptions, previousPublishedDoc, locale, localePrefixes);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-redirect.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/create-redirect.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AACrF,OAAO,EAAE,wBAAwB,EAAE,MAAM,sEAAsE,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAuB,MAAM,mCAAmC,CAAC;AAS5F,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,EAAa,EAC9D,GAAG,EACH,sBAAsB,EACtB,WAAW,EACX,cAAc,EACd,WAAW,GAIZ,EAAiB,EAAE;IAClB,KAAK,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,EAAE,IAAI,WAAW,EAAE,CAAC;QAChE,MAAM,WAAW,GAAG,kBAAkB,CAAC,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;QACxF,IAAI,CAAC,WAAW;YAAE,SAAS;QAE3B,MAAM,EAAE,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC3C,MAAM,oBAAoB,GAAG,aAAa,CAAC,
|
|
1
|
+
{"version":3,"file":"create-redirect.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/create-redirect.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AACrF,OAAO,EAAE,wBAAwB,EAAE,MAAM,sEAAsE,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAuB,MAAM,mCAAmC,CAAC;AAS5F,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,EAAa,EAC9D,GAAG,EACH,sBAAsB,EACtB,WAAW,EACX,cAAc,EACd,WAAW,GAIZ,EAAiB,EAAE;IAClB,KAAK,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,EAAE,IAAI,WAAW,EAAE,CAAC;QAChE,MAAM,WAAW,GAAG,kBAAkB,CAAC,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;QACxF,IAAI,CAAC,WAAW;YAAE,SAAS;QAE3B,MAAM,EAAE,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC3C,+EAA+E;QAC/E,MAAM,oBAAoB,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC;QAC9C,IAAI,CAAC,oBAAoB;YAAE,SAAS;QAEpC,MAAM,YAAY,GAAG,kBAAkB,CACrC,WAAW,EACX,oBAAoB,EACpB,MAAM,EACN,cAAc,CACf,CAAC;QACF,IAAI,CAAC,YAAY;YAAE,SAAS;QAE5B,MAAM,IAAI,GAAG,kBAAkB,CAAC,YAAY,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,EAAE;YAAE,SAAS;QAE1B,MAAM,kBAAkB,CAAC;YACvB,GAAG;YACH,cAAc,EAAE,sBAAsB;YACtC,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;YAClB,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GACzB,CAAsC,EACpC,sBAAsB,EACtB,WAAW,EACX,cAAc,GACmB,EAA6B,EAAE,CAClE,KAAK,EAAE,IAAI,EAAE,EAAE;IACb,IAAI,WAAW,CAAC,OAAO,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC;IACnD,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,qBAAqB,CAAC,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC;IAExE,MAAM,WAAW,GAAG,MAAM,wBAAwB,CAAC,IAAI,CAAC,CAAC;IACzD,MAAM,8BAA8B,CAAC;QACnC,GAAG,EAAE,IAAI,CAAC,GAAG;QACb,sBAAsB;QACtB,WAAW;QACX,cAAc;QACd,WAAW;KACZ,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC,GAAG,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import type { CollectionAfterChangeHook, PayloadRequest } from \"payload\";\nimport { ensureAutoRedirect } from \"#redirect/core/redirects/auto/persist-auto-rule\";\nimport { getPublicationTransition } from \"#redirect/core/redirects/auto/publication/get-publication-transition\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport { normalizePathOrUrl } from \"#redirect/core/redirects/normalize-path\";\nimport { buildPublishedPath, type LocalePrefixes } from \"#redirect/core/url/published-path\";\nimport type { PublicationTransition, RedirectPathOptions } from \"./types.js\";\n\ntype CreateRedirectOptions<TDocument = Record<string, unknown>> = {\n redirectCollectionSlug: string;\n pathOptions: RedirectPathOptions<TDocument>;\n localePrefixes?: LocalePrefixes;\n};\n\nexport const createRedirectsFromTransitions = async <TDocument>({\n req,\n redirectCollectionSlug,\n pathOptions,\n localePrefixes,\n transitions,\n}: CreateRedirectOptions<TDocument> & {\n req: PayloadRequest;\n transitions: PublicationTransition[];\n}): Promise<void> => {\n for (const { currentDoc, publishedDocs, locale } of transitions) {\n const currentPath = buildPublishedPath(pathOptions, currentDoc, locale, localePrefixes);\n if (!currentPath) continue;\n\n const to = normalizePathOrUrl(currentPath);\n // publishedDocs is newest first and starts with the publication that just ran.\n const previousPublishedDoc = publishedDocs[1];\n if (!previousPublishedDoc) continue;\n\n const previousPath = buildPublishedPath(\n pathOptions,\n previousPublishedDoc,\n locale,\n localePrefixes,\n );\n if (!previousPath) continue;\n\n const from = normalizePathOrUrl(previousPath);\n if (from === to) continue;\n\n await ensureAutoRedirect({\n req,\n collectionSlug: redirectCollectionSlug,\n rule: { from, to },\n context: req.context,\n });\n }\n};\n\nexport const createRedirect =\n <TDocument = Record<string, unknown>>({\n redirectCollectionSlug,\n pathOptions,\n localePrefixes,\n }: CreateRedirectOptions<TDocument>): CollectionAfterChangeHook =>\n async (args) => {\n if (pathOptions.enabled === false) return args.doc;\n if (args.req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]) return args.doc;\n\n const transitions = await getPublicationTransition(args);\n await createRedirectsFromTransitions({\n req: args.req,\n redirectCollectionSlug,\n pathOptions,\n localePrefixes,\n transitions,\n });\n\n return args.doc;\n };\n"]}
|
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
import type { CollectionAfterChangeHook } from "payload";
|
|
2
2
|
import type { PublicationTransition } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* A locale takes part only when its newest published version was saved by this operation. That version
|
|
5
|
+
* carries the operation's `updatedAt`; unchanged locales keep an older one, so republishing them creates
|
|
6
|
+
* nothing and never relinks an earlier change.
|
|
7
|
+
*/
|
|
3
8
|
export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0]) => Promise<PublicationTransition[]>;
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import { REDIRECT_CONTEXT_KEYS } from "../../context-keys.js";
|
|
2
|
-
import {
|
|
2
|
+
import { getConfiguredLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from "./locales.js";
|
|
3
3
|
import { isDraftSave, isLocalePublished } from "./publish-intent.js";
|
|
4
4
|
import { fetchLocalePublishedDoc } from "./versions/document-locale.js";
|
|
5
5
|
import { fetchPublishedVersionPages } from "./versions/version-pages.js";
|
|
6
|
+
import { isThisPublication } from "./versions/version-rows.js";
|
|
7
|
+
/**
|
|
8
|
+
* A locale takes part only when its newest published version was saved by this operation. That version
|
|
9
|
+
* carries the operation's `updatedAt`; unchanged locales keep an older one, so republishing them creates
|
|
10
|
+
* nothing and never relinks an earlier change.
|
|
11
|
+
*/
|
|
6
12
|
export const getPublicationTransition = async (args) => {
|
|
7
13
|
const { req, doc, collection } = args;
|
|
8
14
|
if (!collection.versions?.drafts)
|
|
@@ -10,24 +16,30 @@ export const getPublicationTransition = async (args) => {
|
|
|
10
16
|
if (isDraftSave(req) || req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
|
|
11
17
|
return [];
|
|
12
18
|
const docId = doc.id;
|
|
13
|
-
const locales = getRequestLocales(req, doc._status);
|
|
14
19
|
const localizeStatus = hasLocalizedDraftStatus(collection);
|
|
15
20
|
const defaultLocale = resolveDefaultLocale(req);
|
|
16
21
|
const transitions = [];
|
|
17
|
-
for (const locale of
|
|
22
|
+
for (const locale of getConfiguredLocales(req)) {
|
|
18
23
|
const currentDoc = await fetchLocalePublishedDoc({ req, collection, docId, locale });
|
|
19
24
|
if (!currentDoc || !isLocalePublished(currentDoc._status, locale ?? ""))
|
|
20
25
|
continue;
|
|
21
|
-
const
|
|
26
|
+
const rows = await fetchPublishedVersionPages({
|
|
22
27
|
req,
|
|
23
28
|
collectionSlug: collection.slug,
|
|
24
29
|
docId,
|
|
25
30
|
locale,
|
|
26
31
|
versionFilter: { localizeStatus, defaultLocale },
|
|
27
|
-
})
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
});
|
|
33
|
+
// currentDoc is re-read from the database, so hook changes and Local API selects cannot hide updatedAt.
|
|
34
|
+
if (!isThisPublication(rows[0], currentDoc.updatedAt))
|
|
35
|
+
continue;
|
|
36
|
+
transitions.push({
|
|
37
|
+
locale,
|
|
38
|
+
currentDoc,
|
|
39
|
+
publishedDocs: rows
|
|
40
|
+
.map((row) => row.version)
|
|
41
|
+
.filter((version) => Boolean(version)),
|
|
42
|
+
});
|
|
31
43
|
}
|
|
32
44
|
return transitions;
|
|
33
45
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-publication-transition.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/get-publication-transition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"get-publication-transition.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/get-publication-transition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAmB,MAAM,4BAA4B,CAAC;AAEhF;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,KAAK,EAC3C,IAA8C,EACZ,EAAE;IACpC,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACtC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,MAAM;QAAE,OAAO,EAAE,CAAC;IAC5C,IAAI,WAAW,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC,qBAAqB,CAAC,QAAQ,CAAC;QAAE,OAAO,EAAE,CAAC;IAEjF,MAAM,KAAK,GAAG,GAAG,CAAC,EAAE,CAAC;IACrB,MAAM,cAAc,GAAG,uBAAuB,CAAC,UAAU,CAAC,CAAC;IAC3D,MAAM,aAAa,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;IAChD,MAAM,WAAW,GAA4B,EAAE,CAAC;IAEhD,KAAK,MAAM,MAAM,IAAI,oBAAoB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,uBAAuB,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;QACrF,IAAI,CAAC,UAAU,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,IAAI,EAAE,CAAC;YAAE,SAAS;QAElF,MAAM,IAAI,GAAG,MAAM,0BAA0B,CAAC;YAC5C,GAAG;YACH,cAAc,EAAE,UAAU,CAAC,IAAI;YAC/B,KAAK;YACL,MAAM;YACN,aAAa,EAAE,EAAE,cAAc,EAAE,aAAa,EAAE;SACjD,CAAC,CAAC;QACH,wGAAwG;QACxG,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,SAAS,CAAC;YAAE,SAAS;QAEhE,WAAW,CAAC,IAAI,CAAC;YACf,MAAM;YACN,UAAU;YACV,aAAa,EAAE,IAAI;iBAChB,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC;iBACzB,MAAM,CAAC,CAAC,OAAO,EAAsC,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;SAC7E,CAAC,CAAC;IACL,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC","sourcesContent":["import type { CollectionAfterChangeHook } from \"payload\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport type { PublicationTransition } from \"../types.js\";\nimport { getConfiguredLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from \"./locales.js\";\nimport { isDraftSave, isLocalePublished } from \"./publish-intent.js\";\nimport { fetchLocalePublishedDoc } from \"./versions/document-locale.js\";\nimport { fetchPublishedVersionPages } from \"./versions/version-pages.js\";\nimport { isThisPublication, type VersionRow } from \"./versions/version-rows.js\";\n\n/**\n * A locale takes part only when its newest published version was saved by this operation. That version\n * carries the operation's `updatedAt`; unchanged locales keep an older one, so republishing them creates\n * nothing and never relinks an earlier change.\n */\nexport const getPublicationTransition = async (\n args: Parameters<CollectionAfterChangeHook>[0],\n): Promise<PublicationTransition[]> => {\n const { req, doc, collection } = args;\n if (!collection.versions?.drafts) return [];\n if (isDraftSave(req) || req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]) return [];\n\n const docId = doc.id;\n const localizeStatus = hasLocalizedDraftStatus(collection);\n const defaultLocale = resolveDefaultLocale(req);\n const transitions: PublicationTransition[] = [];\n\n for (const locale of getConfiguredLocales(req)) {\n const currentDoc = await fetchLocalePublishedDoc({ req, collection, docId, locale });\n if (!currentDoc || !isLocalePublished(currentDoc._status, locale ?? \"\")) continue;\n\n const rows = await fetchPublishedVersionPages({\n req,\n collectionSlug: collection.slug,\n docId,\n locale,\n versionFilter: { localizeStatus, defaultLocale },\n });\n // currentDoc is re-read from the database, so hook changes and Local API selects cannot hide updatedAt.\n if (!isThisPublication(rows[0], currentDoc.updatedAt)) continue;\n\n transitions.push({\n locale,\n currentDoc,\n publishedDocs: rows\n .map((row) => row.version)\n .filter((version): version is Record<string, unknown> => Boolean(version)),\n });\n }\n\n return transitions;\n};\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { REDIRECT_CONTEXT_KEYS } from "../../context-keys.js";
|
|
2
2
|
import { getConfiguredLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from "./locales.js";
|
|
3
3
|
import { isDraftSave, isLocalePublished } from "./publish-intent.js";
|
|
4
|
-
import { isPublishedVersionRow } from "./versions/version-rows.js";
|
|
4
|
+
import { isPublishedVersionRow, isThisPublication, } from "./versions/version-rows.js";
|
|
5
5
|
const VERSION_PAGE_SIZE = 50;
|
|
6
6
|
export const getGlobalPublicationTransition = async ({ req, globalSlug, }) => {
|
|
7
7
|
if (isDraftSave(req) ||
|
|
@@ -30,7 +30,7 @@ export const getGlobalPublicationTransition = async ({ req, globalSlug, }) => {
|
|
|
30
30
|
continue;
|
|
31
31
|
if (!isLocalePublished(currentDoc._status, locale ?? ""))
|
|
32
32
|
continue;
|
|
33
|
-
const
|
|
33
|
+
const rows = [];
|
|
34
34
|
let page = 1;
|
|
35
35
|
while (true) {
|
|
36
36
|
const result = await req.payload.findGlobalVersions({
|
|
@@ -44,18 +44,20 @@ export const getGlobalPublicationTransition = async ({ req, globalSlug, }) => {
|
|
|
44
44
|
overrideAccess: true,
|
|
45
45
|
req,
|
|
46
46
|
});
|
|
47
|
-
|
|
48
|
-
.filter((row) => isPublishedVersionRow(row, locale, { localizeStatus, defaultLocale }))
|
|
49
|
-
.map((row) => row.version)
|
|
50
|
-
.filter((version) => Boolean(version)));
|
|
47
|
+
rows.push(...result.docs.filter((row) => isPublishedVersionRow(row, locale, { localizeStatus, defaultLocale })));
|
|
51
48
|
if (!result.hasNextPage)
|
|
52
49
|
break;
|
|
53
50
|
page += 1;
|
|
54
51
|
}
|
|
52
|
+
// Only a locale whose newest published version is this operation's takes part; see getPublicationTransition.
|
|
53
|
+
if (!isThisPublication(rows[0], currentDoc.updatedAt))
|
|
54
|
+
continue;
|
|
55
55
|
transitions.push({
|
|
56
56
|
locale,
|
|
57
57
|
currentDoc: currentDoc,
|
|
58
|
-
publishedDocs
|
|
58
|
+
publishedDocs: rows
|
|
59
|
+
.map((row) => row.version)
|
|
60
|
+
.filter((version) => Boolean(version)),
|
|
59
61
|
});
|
|
60
62
|
}
|
|
61
63
|
return transitions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global-transition.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/global-transition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,
|
|
1
|
+
{"version":3,"file":"global-transition.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/global-transition.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AAEpC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,EAAE,EACnD,GAAG,EACH,UAAU,GAIX,EAAoC,EAAE;IACrC,IACE,WAAW,CAAC,GAAG,CAAC;QAChB,GAAG,CAAC,KAAK,EAAE,QAAQ,KAAK,MAAM;QAC9B,GAAG,CAAC,KAAK,EAAE,QAAQ,KAAK,IAAI;QAC5B,GAAG,CAAC,OAAO,EAAE,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAC7C,CAAC;QACD,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC;IAClF,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM;QAAE,OAAO,EAAE,CAAC;IAEzC,MAAM,IAAI,GAAG,UAAwB,CAAC;IACtC,MAAM,cAAc,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;IAChD,MAAM,WAAW,GAA4B,EAAE,CAAC;IAEhD,KAAK,MAAM,MAAM,IAAI,oBAAoB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC;YAC9C,IAAI;YACJ,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAqB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACpD,cAAc,EAAE,KAAK;YACrB,KAAK,EAAE,CAAC;YACR,cAAc,EAAE,IAAI;YACpB,GAAG;SACJ,CAAC,CAAC;QACH,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAClE,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,IAAI,EAAE,CAAC;YAAE,SAAS;QAEnE,MAAM,IAAI,GAAiB,EAAE,CAAC;QAC9B,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,OAAO,IAAI,EAAE,CAAC;YACZ,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC;gBAClD,IAAI;gBACJ,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAqB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACpD,IAAI,EAAE,YAAY;gBAClB,IAAI;gBACJ,KAAK,EAAE,iBAAiB;gBACxB,KAAK,EAAE,CAAC;gBACR,cAAc,EAAE,KAAK;gBACrB,cAAc,EAAE,IAAI;gBACpB,GAAG;aACJ,CAAC,CAAC;YAEH,IAAI,CAAC,IAAI,CACP,GAAI,MAAM,CAAC,IAAqB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9C,qBAAqB,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,cAAc,EAAE,aAAa,EAAE,CAAC,CACtE,CACF,CAAC;YACF,IAAI,CAAC,MAAM,CAAC,WAAW;gBAAE,MAAM;YAC/B,IAAI,IAAI,CAAC,CAAC;QACZ,CAAC;QACD,6GAA6G;QAC7G,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,SAAS,CAAC;YAAE,SAAS;QAEhE,WAAW,CAAC,IAAI,CAAC;YACf,MAAM;YACN,UAAU,EAAE,UAAqC;YACjD,aAAa,EAAE,IAAI;iBAChB,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC;iBACzB,MAAM,CAAC,CAAC,OAAO,EAAsC,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;SAC7E,CAAC,CAAC;IACL,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC","sourcesContent":["import type { GlobalSlug, PayloadRequest, TypedLocale } from \"payload\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport type { PublicationTransition } from \"../types.js\";\nimport { getConfiguredLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from \"./locales.js\";\nimport { isDraftSave, isLocalePublished } from \"./publish-intent.js\";\nimport {\n isPublishedVersionRow,\n isThisPublication,\n type VersionRow,\n} from \"./versions/version-rows.js\";\n\nconst VERSION_PAGE_SIZE = 50;\n\nexport const getGlobalPublicationTransition = async ({\n req,\n globalSlug,\n}: {\n req: PayloadRequest;\n globalSlug: string;\n}): Promise<PublicationTransition[]> => {\n if (\n isDraftSave(req) ||\n req.query?.autosave === \"true\" ||\n req.query?.autosave === true ||\n req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]\n ) {\n return [];\n }\n\n const global = req.payload.globals.config.find(({ slug }) => slug === globalSlug);\n if (!global?.versions?.drafts) return [];\n\n const slug = globalSlug as GlobalSlug;\n const localizeStatus = hasLocalizedDraftStatus(global);\n const defaultLocale = resolveDefaultLocale(req);\n const transitions: PublicationTransition[] = [];\n\n for (const locale of getConfiguredLocales(req)) {\n const currentDoc = await req.payload.findGlobal({\n slug,\n ...(locale ? { locale: locale as TypedLocale } : {}),\n fallbackLocale: false,\n depth: 0,\n overrideAccess: true,\n req,\n });\n if (!currentDoc || Object.keys(currentDoc).length === 0) continue;\n if (!isLocalePublished(currentDoc._status, locale ?? \"\")) continue;\n\n const rows: VersionRow[] = [];\n let page = 1;\n while (true) {\n const result = await req.payload.findGlobalVersions({\n slug,\n ...(locale ? { locale: locale as TypedLocale } : {}),\n sort: \"-updatedAt\",\n page,\n limit: VERSION_PAGE_SIZE,\n depth: 0,\n fallbackLocale: false,\n overrideAccess: true,\n req,\n });\n\n rows.push(\n ...(result.docs as VersionRow[]).filter((row) =>\n isPublishedVersionRow(row, locale, { localizeStatus, defaultLocale }),\n ),\n );\n if (!result.hasNextPage) break;\n page += 1;\n }\n // Only a locale whose newest published version is this operation's takes part; see getPublicationTransition.\n if (!isThisPublication(rows[0], currentDoc.updatedAt)) continue;\n\n transitions.push({\n locale,\n currentDoc: currentDoc as Record<string, unknown>,\n publishedDocs: rows\n .map((row) => row.version)\n .filter((version): version is Record<string, unknown> => Boolean(version)),\n });\n }\n\n return transitions;\n};\n"]}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { PayloadRequest } from "payload";
|
|
2
|
-
export declare const getRequestLocales: (req: PayloadRequest, status: unknown) => Array<string | undefined>;
|
|
3
2
|
export declare const getConfiguredLocales: (req: PayloadRequest) => Array<string | undefined>;
|
|
4
3
|
export declare const hasLocalizedDraftStatus: (collection: {
|
|
5
4
|
versions?: {
|
|
@@ -4,34 +4,6 @@ const listLocales = (req) => {
|
|
|
4
4
|
return [];
|
|
5
5
|
return localization.locales.map((locale) => (typeof locale === "string" ? locale : locale.code));
|
|
6
6
|
};
|
|
7
|
-
export const getRequestLocales = (req, status) => {
|
|
8
|
-
const localization = listLocales(req);
|
|
9
|
-
if (localization.length === 0)
|
|
10
|
-
return [undefined];
|
|
11
|
-
const specificLocale = typeof req.query?.publishSpecificLocale === "string"
|
|
12
|
-
? req.query.publishSpecificLocale
|
|
13
|
-
: undefined;
|
|
14
|
-
if (specificLocale && specificLocale !== "all")
|
|
15
|
-
return [specificLocale];
|
|
16
|
-
if (specificLocale === "all" ||
|
|
17
|
-
req.query?.publishAllLocales === "true" ||
|
|
18
|
-
req.query?.publishAllLocales === true) {
|
|
19
|
-
return localization;
|
|
20
|
-
}
|
|
21
|
-
const requestedLocale = typeof req.query?.locale === "string" ? req.query.locale : undefined;
|
|
22
|
-
if (requestedLocale && requestedLocale !== "all")
|
|
23
|
-
return [requestedLocale];
|
|
24
|
-
if (requestedLocale === "all")
|
|
25
|
-
return localization;
|
|
26
|
-
if (status && typeof status === "object" && !Array.isArray(status)) {
|
|
27
|
-
return Object.entries(status)
|
|
28
|
-
.filter(([, value]) => value === "published")
|
|
29
|
-
.map(([locale]) => locale);
|
|
30
|
-
}
|
|
31
|
-
if (typeof req.locale === "string")
|
|
32
|
-
return [req.locale];
|
|
33
|
-
return status === "published" ? localization : [];
|
|
34
|
-
};
|
|
35
7
|
export const getConfiguredLocales = (req) => {
|
|
36
8
|
const locales = listLocales(req);
|
|
37
9
|
return locales.length > 0 ? locales : [undefined];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"locales.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/locales.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,GAAG,CAAC,GAAmB,EAAY,EAAE;IACpD,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC;IACrD,IAAI,YAAY,KAAK,KAAK,IAAI,CAAC,YAAY;QAAE,OAAO,EAAE,CAAC;IACvD,OAAO,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACnG,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"locales.js","sourceRoot":"","sources":["../../../../../src/core/redirects/auto/publication/locales.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,GAAG,CAAC,GAAmB,EAAY,EAAE;IACpD,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC;IACrD,IAAI,YAAY,KAAK,KAAK,IAAI,CAAC,YAAY;QAAE,OAAO,EAAE,CAAC;IACvD,OAAO,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACnG,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAmB,EAA6B,EAAE;IACrF,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IACjC,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AACpD,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,UAEvC,EAAW,EAAE;IACZ,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC;IACvF,OAAO,OAAO,CACZ,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,gBAAgB,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,CAC5F,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAmB,EAAsB,EAAE;IAC9E,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC;IACrD,OAAO,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC;AAC/D,CAAC,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\n\nconst listLocales = (req: PayloadRequest): string[] => {\n const localization = req.payload.config.localization;\n if (localization === false || !localization) return [];\n return localization.locales.map((locale) => (typeof locale === \"string\" ? locale : locale.code));\n};\n\nexport const getConfiguredLocales = (req: PayloadRequest): Array<string | undefined> => {\n const locales = listLocales(req);\n return locales.length > 0 ? locales : [undefined];\n};\n\nexport const hasLocalizedDraftStatus = (collection: {\n versions?: { drafts?: unknown } | false;\n}): boolean => {\n const drafts = collection.versions === false ? undefined : collection.versions?.drafts;\n return Boolean(\n drafts && typeof drafts === \"object\" && \"localizeStatus\" in drafts && drafts.localizeStatus,\n );\n};\n\nexport const resolveDefaultLocale = (req: PayloadRequest): string | undefined => {\n const localization = req.payload.config.localization;\n return localization ? localization.defaultLocale : undefined;\n};\n"]}
|
|
@@ -11,3 +11,5 @@ export declare const isPublishedVersionRow: (row: VersionRow, locale: string | u
|
|
|
11
11
|
localizeStatus?: boolean;
|
|
12
12
|
defaultLocale?: string;
|
|
13
13
|
}) => boolean;
|
|
14
|
+
/** True when `row` is the publication saved by the operation that produced `updatedAt`. */
|
|
15
|
+
export declare const isThisPublication: (row: VersionRow | undefined, updatedAt: unknown) => boolean;
|
|
@@ -15,4 +15,6 @@ export const isPublishedVersionRow = (row, locale, options) => {
|
|
|
15
15
|
}
|
|
16
16
|
return false;
|
|
17
17
|
};
|
|
18
|
+
/** True when `row` is the publication saved by the operation that produced `updatedAt`. */
|
|
19
|
+
export const isThisPublication = (row, updatedAt) => row !== undefined && typeof updatedAt === "string" && row.version?.updatedAt === updatedAt;
|
|
18
20
|
//# sourceMappingURL=version-rows.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-rows.js","sourceRoot":"","sources":["../../../../../../src/core/redirects/auto/publication/versions/version-rows.ts"],"names":[],"mappings":"AAUA,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,GAAe,EACf,MAA0B,EAC1B,OAA8D,EACrD,EAAE;IACX,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE/C,MAAM,eAAe,GAAG,GAAG,CAAC,eAAe,IAAI,GAAG,CAAC,gBAAgB,CAAC;IACpE,IAAI,eAAe;QAAE,OAAO,eAAe,KAAK,MAAM,CAAC;IAEvD,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC;IACpC,IAAI,MAAM,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACrC,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,MAAM,KAAK,SAAS,IAAK,MAAkC,CAAC,MAAM,CAAC,KAAK,WAAW,CAAC;IAC7F,CAAC;IACD,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;QAC3B,OAAO,CAAC,OAAO,EAAE,cAAc,IAAI,MAAM,KAAK,SAAS,CAAC;IAC1D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC","sourcesContent":["export type VersionRow = {\n id?: string | number;\n updatedAt?: string;\n snapshot?: boolean;\n autosave?: boolean;\n publishedLocale?: string;\n published_locale?: string;\n version?: Record<string, unknown>;\n};\n\nexport const isPublishedVersionRow = (\n row: VersionRow,\n locale: string | undefined,\n options?: { localizeStatus?: boolean; defaultLocale?: string },\n): boolean => {\n if (row.snapshot || row.autosave) return false;\n\n const publishedLocale = row.publishedLocale ?? row.published_locale;\n if (publishedLocale) return publishedLocale === locale;\n\n const status = row.version?._status;\n if (status === \"draft\") return false;\n if (status && typeof status === \"object\" && !Array.isArray(status)) {\n return locale !== undefined && (status as Record<string, unknown>)[locale] === \"published\";\n }\n if (status === \"published\") {\n return !options?.localizeStatus || locale !== undefined;\n }\n return false;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"version-rows.js","sourceRoot":"","sources":["../../../../../../src/core/redirects/auto/publication/versions/version-rows.ts"],"names":[],"mappings":"AAUA,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,GAAe,EACf,MAA0B,EAC1B,OAA8D,EACrD,EAAE;IACX,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE/C,MAAM,eAAe,GAAG,GAAG,CAAC,eAAe,IAAI,GAAG,CAAC,gBAAgB,CAAC;IACpE,IAAI,eAAe;QAAE,OAAO,eAAe,KAAK,MAAM,CAAC;IAEvD,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC;IACpC,IAAI,MAAM,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACrC,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,MAAM,KAAK,SAAS,IAAK,MAAkC,CAAC,MAAM,CAAC,KAAK,WAAW,CAAC;IAC7F,CAAC;IACD,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;QAC3B,OAAO,CAAC,OAAO,EAAE,cAAc,IAAI,MAAM,KAAK,SAAS,CAAC;IAC1D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEF,2FAA2F;AAC3F,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAA2B,EAAE,SAAkB,EAAW,EAAE,CAC5F,GAAG,KAAK,SAAS,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,GAAG,CAAC,OAAO,EAAE,SAAS,KAAK,SAAS,CAAC","sourcesContent":["export type VersionRow = {\n id?: string | number;\n updatedAt?: string;\n snapshot?: boolean;\n autosave?: boolean;\n publishedLocale?: string;\n published_locale?: string;\n version?: Record<string, unknown>;\n};\n\nexport const isPublishedVersionRow = (\n row: VersionRow,\n locale: string | undefined,\n options?: { localizeStatus?: boolean; defaultLocale?: string },\n): boolean => {\n if (row.snapshot || row.autosave) return false;\n\n const publishedLocale = row.publishedLocale ?? row.published_locale;\n if (publishedLocale) return publishedLocale === locale;\n\n const status = row.version?._status;\n if (status === \"draft\") return false;\n if (status && typeof status === \"object\" && !Array.isArray(status)) {\n return locale !== undefined && (status as Record<string, unknown>)[locale] === \"published\";\n }\n if (status === \"published\") {\n return !options?.localizeStatus || locale !== undefined;\n }\n return false;\n};\n\n/** True when `row` is the publication saved by the operation that produced `updatedAt`. */\nexport const isThisPublication = (row: VersionRow | undefined, updatedAt: unknown): boolean =>\n row !== undefined && typeof updatedAt === \"string\" && row.version?.updatedAt === updatedAt;\n"]}
|
|
@@ -59,10 +59,11 @@ Automatic rules use one of `path`, `paths`, or `getPath`, configured centrally o
|
|
|
59
59
|
Draft saves, first publications, unpublishes, and deletions create no automatic rules. Existing
|
|
60
60
|
redirects remain when a document is unpublished or deleted.
|
|
61
61
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
A publication writes a rule only when it changes the published path. The source is the path of
|
|
63
|
+
the published version immediately before it. Republishing an unchanged path writes nothing: a rule
|
|
64
|
+
an editor deleted stays deleted, and an enabled rule is left as it is. Editing or disabling an
|
|
65
|
+
automatic rule changes its origin to `manual`, so the plugin never re-enables a rule an editor
|
|
66
|
+
turned off.
|
|
66
67
|
|
|
67
68
|
An automatic write skips a source path owned by a manual rule. Editing an automatic rule changes
|
|
68
69
|
its origin to `manual`, so later publications do not update it. A path-template change does not
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@klnap/payload-redirect",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "Redirect management for Payload CMS.",
|
|
5
5
|
"homepage": "https://github.com/klnap/payload-redirect#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
],
|
|
40
40
|
"scripts": {
|
|
41
41
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
42
|
-
"typecheck:consumer": "tsc -p tsconfig.type-fixture.json && tsc -p tsconfig.type-fixture.no-generated.json",
|
|
42
|
+
"typecheck:consumer": "tsc -p tsconfig.type-fixture.json && tsc -p tsconfig.type-fixture.no-generated.json && tsc -p tsconfig.type-fixture.readme.json",
|
|
43
43
|
"test": "bun test src tests/unit",
|
|
44
44
|
"test:int": "bun scripts/with-ephemeral-postgres.mjs scripts/ephemeral-postgres.config.mjs -- bun test tests/integration tests/security --max-concurrency 1 --timeout=15000",
|
|
45
45
|
"check:boundaries": "depcruise --config dependency-cruiser.config.mjs --output-type err-long src",
|
|
@@ -69,10 +69,12 @@
|
|
|
69
69
|
"@changesets/cli": "3.0.3",
|
|
70
70
|
"@swc/core": "1.16.22",
|
|
71
71
|
"@payloadcms/db-postgres": "3.94.1",
|
|
72
|
+
"@payloadcms/graphql": "3.94.1",
|
|
72
73
|
"@payloadcms/richtext-lexical": "3.94.1",
|
|
73
74
|
"@types/bun": "1.4.5",
|
|
74
75
|
"@types/pg": "^8.23.1",
|
|
75
76
|
"dependency-cruiser": "^18.8.0",
|
|
77
|
+
"graphql": "16.15.0",
|
|
76
78
|
"npm": "12.2.3",
|
|
77
79
|
"publint": "0.3.25",
|
|
78
80
|
"payload": "3.94.1",
|