@klnap/payload-redirect 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +179 -158
  3. package/dist/core/redirects/auto/create-redirect.d.ts +8 -3
  4. package/dist/core/redirects/auto/create-redirect.js +20 -45
  5. package/dist/core/redirects/auto/match-existing-rule.js +1 -1
  6. package/dist/core/redirects/auto/persist-auto-rule.d.ts +3 -2
  7. package/dist/core/redirects/auto/persist-auto-rule.js +5 -4
  8. package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +2 -2
  9. package/dist/core/redirects/auto/publication/get-publication-transition.js +20 -36
  10. package/dist/core/redirects/auto/publication/locales.d.ts +7 -5
  11. package/dist/core/redirects/auto/publication/locales.js +32 -28
  12. package/dist/core/redirects/auto/publication/publish-intent.d.ts +1 -3
  13. package/dist/core/redirects/auto/publication/publish-intent.js +2 -26
  14. package/dist/core/redirects/auto/publication/versions/document-locale.d.ts +4 -6
  15. package/dist/core/redirects/auto/publication/versions/document-locale.js +9 -18
  16. package/dist/core/redirects/auto/publication/versions/version-pages.d.ts +2 -10
  17. package/dist/core/redirects/auto/publication/versions/version-pages.js +4 -30
  18. package/dist/core/redirects/auto/publication/versions/version-rows.d.ts +1 -7
  19. package/dist/core/redirects/auto/publication/versions/version-rows.js +4 -28
  20. package/dist/core/redirects/auto/types.d.ts +27 -6
  21. package/dist/core/redirects/collection/access.d.ts +6 -11
  22. package/dist/core/redirects/collection/access.js +7 -24
  23. package/dist/core/redirects/collection/collection.d.ts +2 -10
  24. package/dist/core/redirects/collection/collection.js +20 -23
  25. package/dist/core/redirects/collection/duplicate-guard.d.ts +1 -1
  26. package/dist/core/redirects/collection/duplicate-guard.js +6 -9
  27. package/dist/core/redirects/collection/fields.d.ts +1 -0
  28. package/dist/core/redirects/collection/fields.js +77 -77
  29. package/dist/core/redirects/collection/origin-hook.js +7 -14
  30. package/dist/core/redirects/collection/types.d.ts +7 -0
  31. package/dist/core/redirects/collection/types.js +1 -0
  32. package/dist/core/redirects/model/errors.d.ts +0 -6
  33. package/dist/core/redirects/model/errors.js +0 -6
  34. package/dist/core/redirects/model/status-code.js +5 -8
  35. package/dist/core/redirects/queries.d.ts +4 -18
  36. package/dist/core/redirects/queries.js +6 -10
  37. package/dist/core/url/published-path.d.ts +5 -16
  38. package/dist/core/url/published-path.js +42 -95
  39. package/dist/core/url/route-params.d.ts +3 -11
  40. package/dist/core/url/route-params.js +31 -99
  41. package/dist/exports/index.d.ts +1 -7
  42. package/dist/exports/index.js +0 -4
  43. package/dist/plugin/payload-plugin.d.ts +3 -3
  44. package/dist/plugin/payload-plugin.js +142 -43
  45. package/dist/plugin/types.d.ts +17 -0
  46. package/dist/plugin/types.js +1 -0
  47. package/docs/FAILURE_SEMANTICS.md +50 -94
  48. package/package.json +11 -9
  49. package/dist/core/redirects/auto/publication/identifier-snapshot.d.ts +0 -2
  50. package/dist/core/redirects/auto/publication/identifier-snapshot.js +0 -27
  51. package/dist/core/redirects/auto/publication/identifier-transitions.d.ts +0 -18
  52. package/dist/core/redirects/auto/publication/identifier-transitions.js +0 -36
  53. package/dist/core/redirects/auto/publication/transition-for-locale.d.ts +0 -12
  54. package/dist/core/redirects/auto/publication/transition-for-locale.js +0 -163
  55. package/dist/core/redirects/auto/publication/transitions-to-pairs.d.ts +0 -7
  56. package/dist/core/redirects/auto/publication/transitions-to-pairs.js +0 -16
  57. package/dist/core/redirects/auto/published-link-config.d.ts +0 -6
  58. package/dist/core/redirects/auto/published-link-config.js +0 -49
  59. package/dist/core/redirects/auto/published-path.d.ts +0 -6
  60. package/dist/core/redirects/auto/published-path.js +0 -11
  61. package/dist/core/redirects/identifier-field-path.d.ts +0 -14
  62. package/dist/core/redirects/identifier-field-path.js +0 -94
  63. package/dist/core/redirects/resolution/resolve.d.ts +0 -7
  64. package/dist/core/redirects/resolution/resolve.js +0 -27
  65. package/dist/core/redirects/resolution/resolved.d.ts +0 -17
  66. package/dist/core/redirects/resolution/resolved.js +0 -18
  67. package/dist/core/redirects/runtime.d.ts +0 -9
  68. package/dist/core/redirects/runtime.js +0 -13
  69. package/dist/core/url/preview-path.d.ts +0 -1
  70. package/dist/core/url/preview-path.js +0 -9
  71. package/dist/core/url/preview-routes.d.ts +0 -3
  72. package/dist/core/url/preview-routes.js +0 -31
  73. package/dist/plugin/redirect-custom.d.ts +0 -9
  74. package/dist/plugin/redirect-custom.js +0 -18
  75. package/dist/plugin/resolve-config.d.ts +0 -17
  76. package/dist/plugin/resolve-config.js +0 -20
  77. package/dist/plugin/validate-config.d.ts +0 -3
  78. package/dist/plugin/validate-config.js +0 -40
  79. package/docs/RELEASING.md +0 -41
  80. package/docs/adr/0002-database-indexes.md +0 -45
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0
4
+
5
+ - Simplify automatic redirect configuration to `path`, `paths`, and `getPath`.
6
+ - Compare complete published paths with native Payload localization and no locale fallback.
7
+ - Register the redirects collection automatically and use `statusCode` as its status field.
package/README.md CHANGED
@@ -1,250 +1,271 @@
1
1
  # @klnap/payload-redirect
2
2
 
3
- Use this plugin when redirect rules must track published identifier changes, including localized paths. It adds a managed redirects collection, optional automatic rules on publish, validation, and a resolver for your application to call.
3
+ Redirect management for Payload CMS.
4
4
 
5
- Rules use HTTP `301` or `302`. The resolver returns `ResolvedRedirect | null`; it does **not** ship HTTP middleware, caching, or framework integrations. Your application applies the HTTP redirect after lookup.
5
+ Manage redirects directly in Payload and automatically preserve existing URLs when published content paths change.
6
6
 
7
- ```ts
8
- import { redirects } from '@klnap/payload-redirect'
7
+ Define your public URL structure, enable automatic redirects for selected collections, and let your application's routing layer handle redirect responses.
9
8
 
10
- // Redirects is your host application's collection configuration.
11
- // Add to your Payload config:
12
- const plugins = [redirects({ collection: Redirects })]
13
- ```
9
+ ## Overview
14
10
 
15
- ## Install
11
+ The plugin owns its Payload collection, so manual redirects need no collection stub or automatic-generation setup. Automatic generation is optional and compares complete published paths.
16
12
 
17
- Install the package in your Payload application:
13
+ ## Installation
18
14
 
19
15
  ```sh
20
- npm install @klnap/payload-redirect
21
- # or
22
16
  bun add @klnap/payload-redirect
23
17
  ```
24
18
 
25
- The host must provide Payload and the PostgreSQL adapter. See [Requirements](#requirements) and [Quick start](#quick-start).
26
-
27
- ## Requirements
28
-
29
- | Requirement | Version |
30
- | ----------- | ------------------------------------------------------------- |
31
- | **Node.js** | `^24.22.3 or >=26.13.1` |
32
- | **Payload** | `>=3.94.1 <4` (peer), `@payloadcms/db-postgres` `>=3.94.1 <4` |
19
+ Requires Payload `>=3.94.1 <4`. PostgreSQL is the supported database adapter.
33
20
 
34
- Auto redirects require **drafts/versioning** on content collections.
21
+ ## Manual redirects
35
22
 
36
- ## Quick start
23
+ Register the plugin with no options:
37
24
 
38
25
  ```ts
39
- import type { CollectionConfig } from 'payload'
40
26
  import { buildConfig } from 'payload'
41
- import { redirects } from '@klnap/payload-redirect'
42
27
  import { postgresAdapter } from '@payloadcms/db-postgres'
43
-
44
- export const Redirects: CollectionConfig = {
45
- slug: 'redirects',
46
- fields: [], // host stub — see note below on merge, types, and migrations
47
- }
28
+ import { redirects } from '@klnap/payload-redirect'
48
29
 
49
30
  export default buildConfig({
50
- collections: [Redirects],
51
- db: postgresAdapter({
52
- pool: { connectionString: process.env.DATABASE_URL! },
53
- }),
54
- plugins: [redirects({ collection: Redirects })],
31
+ secret: process.env.PAYLOAD_SECRET!,
32
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
33
+ plugins: [redirects()],
55
34
  })
56
35
  ```
57
36
 
58
- Register `Redirects` in `config.collections` and pass the **same** object reference to `redirects({ collection })`. Do not call `createRedirectsCollection` in the host.
37
+ The plugin adds the `redirects` collection. Add, edit, enable, or disable rules in Payload Admin. Manual rules work without automatic redirect configuration.
59
38
 
60
- **Merge, types, and migrations.** During `buildConfig`, the `redirects()` plugin **replaces** the matching entry in `config.collections` with the merged collection (plugin fields, hooks, access). Payload therefore sees the full schema for admin UI, **`payload generate:types`**, and **`@payloadcms/db-postgres` migrations** — not the empty `fields: []` stub alone. Keep `redirects()` in the same config file you use for type generation and `payload migrate`. If you pre-declare plugin-owned fields on the host collection, preserve their expected types and flags; see [Redirect collection](#redirect-collection).
39
+ ## Automatic redirects
61
40
 
62
- **PostgreSQL.** The package adds no migrations and does not wrap the adapter. The host application owns its migrations. Schema changes go through Payload's migration flow (`payload migrate:create` and `migrate`, or dev push, per project).
41
+ Automatic generation is enabled for each collection configured in `redirects({ collections })`. Those collections must use Payload drafts so the plugin can compare published snapshots.
63
42
 
64
- ## Redirect collection
65
-
66
- The host defines a redirects collection (slug and optional extra fields). The plugin merges required fields, hooks, and default access into that entry before Payload initializes. Incompatible host declarations of plugin-owned fields, including incorrect field types or required index settings, throw **`RedirectConfigError`** at startup.
43
+ ```ts
44
+ import { buildConfig } from 'payload'
45
+ import { postgresAdapter } from '@payloadcms/db-postgres'
46
+ import { redirects } from '@klnap/payload-redirect'
67
47
 
68
- Merged plugin fields: `from`, `to`, `StatusCode`, `enabled`, `origin`.
48
+ export default buildConfig({
49
+ secret: process.env.PAYLOAD_SECRET!,
50
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
51
+ localization: {
52
+ locales: ['pl', 'en', 'de'],
53
+ defaultLocale: 'pl',
54
+ },
55
+ collections: [
56
+ {
57
+ slug: 'articles',
58
+ versions: { drafts: true },
59
+ fields: [
60
+ { name: 'title', type: 'text', required: true },
61
+ { name: 'slug', type: 'text', required: true, localized: true },
62
+ ],
63
+ },
64
+ {
65
+ slug: 'projects',
66
+ versions: { drafts: true },
67
+ fields: [{ name: 'slug', type: 'text', required: true, localized: true }],
68
+ },
69
+ ],
70
+ plugins: [
71
+ redirects({
72
+ localePrefixes: {
73
+ pl: '',
74
+ en: '/en',
75
+ de: '/de',
76
+ },
77
+ collections: {
78
+ articles: { path: '/[slug]' },
79
+ projects: {
80
+ paths: {
81
+ pl: '/realizacje/[slug]',
82
+ en: '/work/[slug]',
83
+ de: '/projekte/[slug]',
84
+ },
85
+ },
86
+ },
87
+ }),
88
+ ],
89
+ })
90
+ ```
69
91
 
70
- ## Configuration
92
+ ### Reading the configuration
71
93
 
72
- ### `redirects(pluginConfig)`
94
+ > When the published path of a document in this collection changes, redirect the previous path to the new one.
73
95
 
74
- | Option | Required | Default | Description |
75
- | -------------- | -------- | ------- | -------------------------------------------------------------------------------------------- |
76
- | `collection` | **Yes** | — | Host redirects `CollectionConfig` (also in `config.collections`). |
77
- | `localePrefix` | No | — | Per-locale URL prefix for Auto path building (`Record<string, string>`). |
78
- | `trash` | No | `true` | Soft delete on merged collection unless host `collection.trash` is set. |
79
- | `access` | No | — | Overrides for `read` / `create` / `update` / `delete`. Host collection access wins when set. |
96
+ - Articles use one path template. `localePrefixes` adds each locale's explicit prefix.
97
+ - Projects use a separate public path template for each Payload locale.
98
+ - Collections without redirect configuration remain unaffected.
80
99
 
81
- Default access: **read** is public. **create** and **update** need a signed-in user or the internal Auto context. **delete** needs a signed-in user. A host collection's own `access` handler takes precedence over the plugin `access` option.
100
+ For a Polish project, a slug change creates this rule:
82
101
 
83
- ### Auto redirects on content collections
102
+ ```text
103
+ Previous published path: /realizacje/stary-projekt
104
+ Current published path: /realizacje/nowy-projekt
105
+ Generated redirect: /realizacje/stary-projekt → /realizacje/nowy-projekt
106
+ ```
84
107
 
85
- Use **one** wiring style per collection — not both. Each style registers the same `createRedirect` `afterChange` logic; combining them would run Auto twice on every publish.
108
+ The plugin tracks the resolved public URL, not a particular slug field. A change to any field used by the path template can create a redirect.
86
109
 
87
- | Style | When to use |
88
- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
89
- | **Declarative** (`custom.redirect`) | Default. The `redirects()` plugin appends `afterChange` when it sees `custom.redirect` on the collection. |
90
- | **Manual hook** (`createRedirect(...)`) | When you cannot use `custom.redirect` (generated configs, shared hook arrays) or you must control exact hook order relative to other hooks. Do **not** set `custom.redirect` on the same collection. |
110
+ ### Collection-level configuration
91
111
 
92
- **Declarative** — identifier on the collection; plugin wires the hook:
112
+ Use the same options directly on a collection when central configuration is not convenient:
93
113
 
94
114
  ```ts
95
- {
96
- slug: 'pages',
115
+ import type { CollectionConfig } from 'payload'
116
+ import type { RedirectCollectionOptions } from '@klnap/payload-redirect'
117
+
118
+ const projectRedirect = {
119
+ paths: {
120
+ pl: '/realizacje/[slug]',
121
+ en: '/work/[slug]',
122
+ de: '/projekte/[slug]',
123
+ },
124
+ } satisfies RedirectCollectionOptions<'projects'>
125
+
126
+ export const Projects: CollectionConfig = {
127
+ slug: 'projects',
97
128
  versions: { drafts: true },
98
129
  custom: {
99
- redirect: {
100
- identifier: 'slug',
101
- enabled: true, // optional; default true
102
- },
130
+ redirect: projectRedirect,
103
131
  },
132
+ fields: [{ name: 'slug', type: 'text', required: true, localized: true }],
104
133
  }
105
134
  ```
106
135
 
107
- **Manual hook** — add the hook yourself; omit `custom.redirect` on that collection:
108
-
109
- ```ts
110
- import { createRedirect } from '@klnap/payload-redirect'
136
+ Central configuration replaces collection-level configuration for that collection. The plugin does not merge path strategies.
111
137
 
112
- hooks: {
113
- afterChange: [createRedirect({ identifier: 'slug' })],
114
- }
115
- ```
138
+ Set `custom.redirect.enabled` to `false` to disable automatic generation for that collection. Manual redirect management remains enabled.
116
139
 
117
- ### Published paths and localization
140
+ ## Published paths
118
141
 
119
- On publish, Auto compares the **previous** and **current** published identifier for each locale. The redirect rule is always **`from` → old public path**, **`to` → new public path** (both normalized). If the two paths are equal after normalization, no rule is created.
142
+ Choose exactly one path strategy for each configured collection.
120
143
 
121
- **Without** a resolvable `publishedLink` template (or when path building returns null for a side), each side falls back to the **normalized identifier value** alone (for example the slug string), not a full URL path — configure `publishedLink` when `from`/`to` must be site paths.
144
+ ### Shared templates
122
145
 
123
- Templates live on the content collection under **`custom.redirect.publishedLink`**, or under **`custom.draft.publishedLink`** (same wire shape — useful when that block already exists on the collection):
146
+ Use `path` when every locale has the same route shape:
124
147
 
125
148
  ```ts
126
- custom: {
127
- redirect: {
128
- identifier: 'slug',
129
- publishedLink: {
130
- path: '/articles/[slug]',
131
- paths: { pl: '/artykuly/[slug]' },
132
- params: { slug: { field: 'slug', localized: true } },
133
- },
134
- },
135
- },
149
+ articles: {
150
+ path: '/articles/[slug]'
151
+ }
136
152
  ```
137
153
 
138
- Set plugin **`localePrefix`** when paths include locale segments (merged with link config):
154
+ Templates use top-level field names in brackets. Use multiple fields when the public route depends on multiple values:
139
155
 
140
156
  ```ts
141
- redirects({
142
- collection: Redirects,
143
- localePrefix: { en: '', pl: '/pl' },
144
- })
157
+ projects: {
158
+ path: '/[category]/[slug]'
159
+ }
145
160
  ```
146
161
 
147
- Redirect **documents** have no locale field; each rule is one path identity. Identifier transitions are evaluated **per locale** on publish.
148
-
149
- ### Request context
162
+ Each value is encoded as one URL path segment. Missing, invalid, or unsafe values prevent that transition from creating a redirect.
150
163
 
151
- Export **`REDIRECT_CONTEXT_KEYS`** from the main entry:
164
+ ### Localized templates
152
165
 
153
- | Key | Value | Effect |
154
- | ---------- | ------------------------- | ------------------------------------- |
155
- | `skipAuto` | `payloadRedirectSkipAuto` | Skips Auto redirect creation |
156
- | `internal` | `payloadRedirectInternal` | Internal writes; sets origin **Auto** |
166
+ Use `paths` to give each Payload locale a complete template:
157
167
 
158
- Set these flags only in **trusted server code** (Local API, background jobs) on `req.context`. Never copy values from request bodies, query strings, or other client-controlled input — a user could otherwise bypass Auto redirect creation or forge internal writes.
159
-
160
- Use **`skipAuto`** when an import or job must not create Auto rules. Use **`internal`** together with server-side redirect writes so origin is recorded as **Auto**.
168
+ ```ts
169
+ projects: {
170
+ paths: {
171
+ pl: '/realizacje/[slug]',
172
+ en: '/work/[slug]',
173
+ de: '/projekte/[slug]',
174
+ },
175
+ }
176
+ ```
161
177
 
162
- ## Admin usage
178
+ The map must include every locale configured in Payload. The plugin does not use fallback locale values to resolve a published path.
163
179
 
164
- | Field | Description |
165
- | -------------- | ------------------------------------------------------ |
166
- | **from** | Site-relative source path; unique. |
167
- | **to** | Site-relative destination; required for `301` / `302`. |
168
- | **StatusCode** | `301` (default) or `302`; both require **to**. |
169
- | **enabled** | Disabled rules are ignored by `resolveRedirect`. |
170
- | **origin** | Read-only **Manual** (`manual`) or **Auto** (`auto`). |
180
+ ### Locale prefixes
171
181
 
172
- Rules created in the admin UI are **Manual**. Duplicate `from`: _A redirect rule already exists for this source path_.
182
+ `localePrefixes` maps Payload locale codes to explicit prefixes. An empty string means no prefix. The map must include every Payload locale when provided.
173
183
 
174
- ## Auto redirects
184
+ Prefixes apply to `path` and `paths`. If `localePrefixes` is omitted, the plugin adds no prefix and does not infer one from the locale code.
175
185
 
176
- Created on publish when a published identifier transition is detected (`origin` **Auto**, `301`, enabled). See [Published paths and localization](#published-paths-and-localization) for how `from`/`to` are computed.
186
+ ### Custom path resolution
177
187
 
178
- **Not created:** draft saves, first publication, `payloadRedirectSkipAuto`, unpublished docs, unchanged identifier, invalid/empty paths, document delete, or when **Manual** rule already owns `from`.
188
+ Use `getPath` when templates cannot express the public route:
179
189
 
180
- **Updated:** existing **Auto** rule on same `from` when `to` changes.
190
+ ```ts
191
+ projects: {
192
+ getPath: ({ doc, locale }) =>
193
+ doc.slug && doc.category
194
+ ? `${locale ? `/${locale}` : ''}/${String(doc.category)}/${String(doc.slug)}`
195
+ : null,
196
+ }
197
+ ```
181
198
 
182
- ## Redirect resolution (host responsibility)
199
+ Payload generated types infer `doc` from the configured collection. The callback receives the locale-specific published snapshot and locale; locale is `undefined` when Payload localization is off. Return a complete site-relative path or `null`. The plugin does not add `localePrefixes` to callback results.
183
200
 
184
- ```ts
185
- import { resolveRedirect } from '@klnap/payload-redirect'
201
+ ## Redirect collection
186
202
 
187
- const result = await resolveRedirect({
188
- payload,
189
- from: requestPathname,
190
- })
191
- // { statusCode: 301 | 302; to: string } | null
192
- ```
203
+ The plugin owns these fields:
193
204
 
194
- Your framework (Next.js, Express, etc.) must call `resolveRedirect` and apply the HTTP redirect response. This package does not intercept requests.
205
+ - `from`: unique source path.
206
+ - `to`: site-relative destination path.
207
+ - `statusCode`: `301` or `302`.
208
+ - `enabled`: whether the rule is active.
209
+ - `origin`: `manual` or `auto`.
195
210
 
196
- - Normalizes `from` before lookup.
197
- - Matching is case-sensitive and does not decode percent escapes; pass the same path representation used when saving the rule.
198
- - Query strings are matched exactly. Source fragments are rejected because HTTP requests do not send them.
199
- - Literal and percent-encoded dot segments normalize to their browser-equivalent path (for example, `/a/../b` becomes `/b`). Other percent escapes and Unicode remain literal.
200
- - Saving an enabled rule rejects destinations whose existing redirect chain loops or exceeds 1,000 hops.
201
- - **`null`:** no enabled rule — serve normal content or 404.
202
- - **`RedirectAmbiguousRuleError`:** more than one match (data issue).
203
- - Does not follow redirect chains; the returned **`to`** is not resolved recursively (your app may call `resolveRedirect` again if you implement chaining yourself).
211
+ The schema uses the camelCase field `statusCode`.
204
212
 
205
- ## Security and access
213
+ ### Collection overrides
206
214
 
207
- - Default **read** on redirect fields is public so `resolveRedirect` and list filters work; tighten with plugin `access` or host collection access if your threat model requires it.
208
- - Auto writes run with `overrideAccess: false` and the internal context (`payloadRedirectInternal`). They pass create and update access only through that context. Delete access still needs a user. See [docs/FAILURE_SEMANTICS.md](docs/FAILURE_SEMANTICS.md).
209
- - Default **create**, **update** and **delete** of manual rules accept only a signed-in human (`req.user` with a type other than `service`). Service principals are refused by default, so automation cannot write manual rules. Package-internal automatic writes are unaffected. A host that deliberately lets a service principal manage manual rules grants it explicitly through the plugin's `access` option, one operation at a time. The override applies only to the operations it names:
215
+ Pass native Payload collection options through `overrides`:
210
216
 
211
217
  ```ts
212
218
  redirects({
213
- access: {
214
- // Automation may create manual rules. Update and delete stay human-only.
215
- create: ({ req }) => (req.user as { type?: string } | null)?.type === 'service',
219
+ overrides: {
220
+ slug: 'url-rules',
221
+ labels: { singular: 'URL rule', plural: 'URL rules' },
222
+ admin: { group: 'Settings' },
223
+ trash: true,
216
224
  },
217
225
  })
218
226
  ```
219
227
 
220
- Keep such a grant as narrow as the automation needs, and check the service identity itself (for example its token holder) inside the function.
228
+ Use `overrides.fields` to customize the plugin fields. Required fields, validation, uniqueness, and indexes remain enforced.
221
229
 
222
- ## Errors
230
+ ## Automatic redirect behavior
223
231
 
224
- See [docs/FAILURE_SEMANTICS.md](docs/FAILURE_SEMANTICS.md).
232
+ - Draft saves, autosaves, first publications, unpublishes, and unchanged paths create no rules.
233
+ - The plugin compares the current published path with the latest earlier published path.
234
+ - A missing or unsafe path on either side skips that locale's redirect.
235
+ - A manual rule that owns the previous path is never overwritten.
236
+ - Automatic writes run through Payload Local API with the active request and transaction.
237
+ - Deleting a document does not create a redirect; configure removal behavior in your application if needed.
225
238
 
226
- ## Public API
239
+ Automatic generation requires `versions.drafts`. It reads published versions with fallback disabled so localized paths never borrow values from another locale.
227
240
 
228
- ### `@klnap/payload-redirect`
241
+ ## Application integration
229
242
 
230
- `redirects`, `RedirectsPluginConfig`, `createRedirect`, `CreateRedirectOptions`, `resolveRedirect`, `ResolveRedirectArgs`, `ResolvedRedirect`, `RedirectOrigin`, `RedirectStatusCode`, `RedirectsCollectionAccess`, `REDIRECT_CONTEXT_KEYS`, `RedirectConfigError`, `RedirectValidationError`, `RedirectAmbiguousRuleError`.
243
+ The package stores rules. Your application retrieves enabled rules, caches them, matches incoming paths, and returns HTTP redirect responses.
231
244
 
232
- ## Troubleshooting
245
+ ```ts
246
+ const { docs } = await payload.find({
247
+ collection: 'redirects',
248
+ where: { enabled: { equals: true } },
249
+ depth: 0,
250
+ })
251
+
252
+ // Match the incoming path and return the selected rule's statusCode and to.
253
+ ```
254
+
255
+ The package does not include a resolver, cache, middleware, proxy, or framework adapter.
233
256
 
234
- | Symptom | Cause |
235
- | -------------------------- | ----------------------------------------------------------------------------------------------- |
236
- | Plugin runtime missing | `redirects()` not in config |
237
- | Requires `collection` | Missing `redirects({ collection })` |
238
- | No Auto rule | Draft/first publish/skip context/no transition |
239
- | Auto skipped | Manual rule on same `from` |
240
- | Auto runs twice on publish | Both `custom.redirect` and `createRedirect` hook on the same collection — pick one wiring style |
241
- | Auto paths are raw slugs | No published-link template or path build returned null — add `publishedLink` or check `params` |
257
+ ## Security and reliability
242
258
 
243
- ## Further reading
259
+ The collection validates site-relative sources, rejects unsafe destinations, prevents duplicate sources, and checks enabled redirect chains for loops. Manual rules are protected from automatic writes.
260
+
261
+ PostgreSQL provides the transaction-scoped advisory lock used to serialize graph validation. This package does not claim equivalent concurrent-write guarantees for other adapters.
262
+
263
+ ## Requirements
244
264
 
245
- - [docs/FAILURE_SEMANTICS.md](docs/FAILURE_SEMANTICS.md)
246
- - [docs/adr/0002-database-indexes.md](docs/adr/0002-database-indexes.md)
265
+ - Payload: `>=3.94.1 <4`.
266
+ - PostgreSQL: supported adapter for transaction-scoped graph locking.
267
+ - Other adapters: no equivalent concurrency guarantee is claimed.
247
268
 
248
269
  ## License
249
270
 
250
- MIT — see [LICENSE](./LICENSE).
271
+ MIT
@@ -1,5 +1,10 @@
1
1
  import type { CollectionAfterChangeHook } from 'payload';
2
- export type CreateRedirectOptions = {
3
- identifier: string;
2
+ import { type LocalePrefixes } from '../../url/published-path.js';
3
+ import type { RedirectPathOptions } from './types.js';
4
+ type CreateRedirectOptions = {
5
+ collectionSlug: string;
6
+ pathOptions: RedirectPathOptions;
7
+ localePrefixes?: LocalePrefixes;
4
8
  };
5
- export declare const createRedirect: (options: CreateRedirectOptions) => CollectionAfterChangeHook;
9
+ export declare const createRedirect: ({ collectionSlug, pathOptions, localePrefixes, }: CreateRedirectOptions) => CollectionAfterChangeHook;
10
+ export {};
@@ -1,61 +1,36 @@
1
1
  import { ensureAutoRedirect } from './persist-auto-rule.js';
2
2
  import { getPublicationTransition } from './publication/get-publication-transition.js';
3
- import { publicationTransitionsToPairs } from './publication/transitions-to-pairs.js';
4
- import { identifierValueForPath, resolveCollectionPublishedPathConfig, } from './published-path.js';
5
3
  import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
6
- import { paramKeyFromIdentifierPath } from '../identifier-field-path.js';
7
4
  import { normalizePathOrUrl } from '../normalize-path.js';
8
- import { getRedirectRuntime } from '../runtime.js';
9
5
  import { buildPublishedPath } from '../../url/published-path.js';
10
- export const createRedirect = (options) => async (args) => {
11
- const { req, collection } = args;
12
- if (req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]) {
6
+ export const createRedirect = ({ collectionSlug, pathOptions, localePrefixes, }) => async (args) => {
7
+ if (pathOptions.enabled === false)
13
8
  return args.doc;
14
- }
15
- const transitions = await getPublicationTransition(args, options);
16
- const pairs = publicationTransitionsToPairs(transitions);
17
- if (pairs.length === 0) {
9
+ if (args.req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
18
10
  return args.doc;
19
- }
20
- const { collectionSlug, localePrefix } = getRedirectRuntime(req.payload.config);
21
- const pathConfig = resolveCollectionPublishedPathConfig(collection, localePrefix);
22
- for (const { previous, current, locale } of pairs) {
23
- const resolvePath = (identifierValue) => {
24
- if (!pathConfig || !locale)
25
- return identifierValue;
26
- const paramKey = paramKeyFromIdentifierPath(options.identifier);
27
- const mapping = pathConfig.params?.[paramKey];
28
- const data = mapping &&
29
- typeof mapping === 'object' &&
30
- 'localized' in mapping &&
31
- mapping.localized === true
32
- ? { [paramKeyFromIdentifierPath(options.identifier)]: { [locale]: identifierValue } }
33
- : identifierValueForPath(options.identifier, identifierValue);
34
- const built = buildPublishedPath(pathConfig, data, locale);
35
- return built;
36
- };
37
- const fromRaw = resolvePath(previous);
38
- const toRaw = resolvePath(current);
39
- if (!fromRaw || !toRaw) {
11
+ const transitions = await getPublicationTransition(args);
12
+ for (const { currentDoc, publishedDocs, locale } of transitions) {
13
+ const currentPath = buildPublishedPath(pathOptions, currentDoc, locale, localePrefixes);
14
+ if (!currentPath)
15
+ continue;
16
+ const to = normalizePathOrUrl(currentPath);
17
+ const previousPublishedDoc = publishedDocs.find((publishedDoc) => {
18
+ const path = buildPublishedPath(pathOptions, publishedDoc, locale, localePrefixes);
19
+ return !path || normalizePathOrUrl(path) !== to;
20
+ });
21
+ if (!previousPublishedDoc)
40
22
  continue;
41
- }
42
- let from;
43
- let to;
44
- try {
45
- from = normalizePathOrUrl(fromRaw);
46
- to = normalizePathOrUrl(toRaw);
47
- }
48
- catch {
23
+ const previousPath = buildPublishedPath(pathOptions, previousPublishedDoc, locale, localePrefixes);
24
+ if (!previousPath)
49
25
  continue;
50
- }
51
- if (from === to) {
26
+ const from = normalizePathOrUrl(previousPath);
27
+ if (from === to)
52
28
  continue;
53
- }
54
29
  await ensureAutoRedirect({
55
- req,
30
+ req: args.req,
56
31
  collectionSlug,
57
32
  rule: { from, to },
58
- context: req.context,
33
+ context: args.req.context,
59
34
  });
60
35
  }
61
36
  return args.doc;
@@ -1,7 +1,7 @@
1
1
  import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, } from '../model/status-code.js';
2
2
  export const isIdenticalAutoRule = (doc, rule) => doc.from === rule.from &&
3
3
  doc.to === rule.to &&
4
- assertRedirectStatusCode(doc.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE) ===
4
+ assertRedirectStatusCode(doc.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE) ===
5
5
  DEFAULT_REDIRECT_STATUS_CODE &&
6
6
  doc.enabled !== false &&
7
7
  doc.origin === 'auto';
@@ -1,9 +1,9 @@
1
1
  import type { PayloadRequest } from 'payload';
2
- export type AutoRedirectRule = {
2
+ type AutoRedirectRule = {
3
3
  from: string;
4
4
  to: string;
5
5
  };
6
- export type EnsureAutoRedirectArgs = {
6
+ type EnsureAutoRedirectArgs = {
7
7
  req: PayloadRequest;
8
8
  collectionSlug: string;
9
9
  rule: AutoRedirectRule;
@@ -13,3 +13,4 @@ export type EnsureAutoRedirectArgs = {
13
13
  * Idempotent create for auto 301 rules. One lookup by unique `from`.
14
14
  */
15
15
  export declare const ensureAutoRedirect: ({ req, collectionSlug, rule, context, }: EnsureAutoRedirectArgs) => Promise<'created' | 'skipped' | 'updated'>;
16
+ export {};
@@ -13,10 +13,11 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
13
13
  const data = {
14
14
  from: rule.from,
15
15
  to: rule.to,
16
- StatusCode: '301',
16
+ statusCode: '301',
17
17
  enabled: true,
18
18
  origin: 'auto',
19
19
  };
20
+ const payload = req.payload;
20
21
  const existing = await findRedirectByFrom(req.payload, {
21
22
  collectionSlug,
22
23
  from: rule.from,
@@ -30,12 +31,12 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
30
31
  return 'skipped';
31
32
  }
32
33
  if (doc.origin === 'auto') {
33
- await req.payload.update({
34
+ await payload.update({
34
35
  collection: collectionSlug,
35
36
  id: doc.id,
36
37
  data: {
37
38
  to: rule.to,
38
- StatusCode: '301',
39
+ statusCode: '301',
39
40
  enabled: true,
40
41
  },
41
42
  context: internalContext,
@@ -46,7 +47,7 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
46
47
  }
47
48
  return 'skipped';
48
49
  }
49
- await req.payload.create({
50
+ await payload.create({
50
51
  collection: collectionSlug,
51
52
  data,
52
53
  context: internalContext,
@@ -1,3 +1,3 @@
1
1
  import type { CollectionAfterChangeHook } from 'payload';
2
- import type { GetPublicationTransitionOptions, PublicationTransition } from '../types.js';
3
- export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0], options: GetPublicationTransitionOptions) => Promise<PublicationTransition[]>;
2
+ import type { PublicationTransition } from '../types.js';
3
+ export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0]) => Promise<PublicationTransition[]>;