@klnap/payload-redirect 0.2.0 → 0.3.1

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 (109) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +212 -79
  3. package/dist/core/redirects/auto/create-redirect.d.ts +9 -4
  4. package/dist/core/redirects/auto/create-redirect.js +26 -66
  5. package/dist/core/redirects/auto/create-redirect.js.map +1 -0
  6. package/dist/core/redirects/auto/match-existing-rule.d.ts +1 -1
  7. package/dist/core/redirects/auto/match-existing-rule.js +4 -3
  8. package/dist/core/redirects/auto/match-existing-rule.js.map +1 -0
  9. package/dist/core/redirects/auto/persist-auto-rule.d.ts +5 -4
  10. package/dist/core/redirects/auto/persist-auto-rule.js +12 -11
  11. package/dist/core/redirects/auto/persist-auto-rule.js.map +1 -0
  12. package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +3 -3
  13. package/dist/core/redirects/auto/publication/get-publication-transition.js +22 -37
  14. package/dist/core/redirects/auto/publication/get-publication-transition.js.map +1 -0
  15. package/dist/core/redirects/auto/publication/locales.d.ts +7 -5
  16. package/dist/core/redirects/auto/publication/locales.js +33 -28
  17. package/dist/core/redirects/auto/publication/locales.js.map +1 -0
  18. package/dist/core/redirects/auto/publication/publish-intent.d.ts +2 -4
  19. package/dist/core/redirects/auto/publication/publish-intent.js +6 -29
  20. package/dist/core/redirects/auto/publication/publish-intent.js.map +1 -0
  21. package/dist/core/redirects/auto/publication/versions/document-locale.d.ts +4 -6
  22. package/dist/core/redirects/auto/publication/versions/document-locale.js +10 -18
  23. package/dist/core/redirects/auto/publication/versions/document-locale.js.map +1 -0
  24. package/dist/core/redirects/auto/publication/versions/version-pages.d.ts +4 -12
  25. package/dist/core/redirects/auto/publication/versions/version-pages.js +7 -32
  26. package/dist/core/redirects/auto/publication/versions/version-pages.js.map +1 -0
  27. package/dist/core/redirects/auto/publication/versions/version-rows.d.ts +1 -7
  28. package/dist/core/redirects/auto/publication/versions/version-rows.js +7 -30
  29. package/dist/core/redirects/auto/publication/versions/version-rows.js.map +1 -0
  30. package/dist/core/redirects/auto/types.d.ts +27 -8
  31. package/dist/core/redirects/auto/types.js +1 -0
  32. package/dist/core/redirects/auto/types.js.map +1 -0
  33. package/dist/core/redirects/collection/access.d.ts +1 -1
  34. package/dist/core/redirects/collection/access.js +3 -2
  35. package/dist/core/redirects/collection/access.js.map +1 -0
  36. package/dist/core/redirects/collection/collection.d.ts +2 -2
  37. package/dist/core/redirects/collection/collection.js +10 -9
  38. package/dist/core/redirects/collection/collection.js.map +1 -0
  39. package/dist/core/redirects/collection/duplicate-guard.d.ts +1 -1
  40. package/dist/core/redirects/collection/duplicate-guard.js +35 -34
  41. package/dist/core/redirects/collection/duplicate-guard.js.map +1 -0
  42. package/dist/core/redirects/collection/fields.d.ts +1 -1
  43. package/dist/core/redirects/collection/fields.js +52 -51
  44. package/dist/core/redirects/collection/fields.js.map +1 -0
  45. package/dist/core/redirects/collection/graph-lock.d.ts +1 -1
  46. package/dist/core/redirects/collection/graph-lock.js +8 -7
  47. package/dist/core/redirects/collection/graph-lock.js.map +1 -0
  48. package/dist/core/redirects/collection/origin-hook.d.ts +1 -1
  49. package/dist/core/redirects/collection/origin-hook.js +6 -5
  50. package/dist/core/redirects/collection/origin-hook.js.map +1 -0
  51. package/dist/core/redirects/collection/types.d.ts +2 -2
  52. package/dist/core/redirects/collection/types.js +1 -0
  53. package/dist/core/redirects/collection/types.js.map +1 -0
  54. package/dist/core/redirects/context-keys.d.ts +2 -2
  55. package/dist/core/redirects/context-keys.js +3 -2
  56. package/dist/core/redirects/context-keys.js.map +1 -0
  57. package/dist/core/redirects/model/errors.js +2 -1
  58. package/dist/core/redirects/model/errors.js.map +1 -0
  59. package/dist/core/redirects/model/origin.d.ts +1 -1
  60. package/dist/core/redirects/model/origin.js +4 -3
  61. package/dist/core/redirects/model/origin.js.map +1 -0
  62. package/dist/core/redirects/model/status-code.js +5 -4
  63. package/dist/core/redirects/model/status-code.js.map +1 -0
  64. package/dist/core/redirects/normalize-path.js +23 -22
  65. package/dist/core/redirects/normalize-path.js.map +1 -0
  66. package/dist/core/redirects/queries.d.ts +3 -12
  67. package/dist/core/redirects/queries.js +3 -2
  68. package/dist/core/redirects/queries.js.map +1 -0
  69. package/dist/core/url/published-path.d.ts +4 -16
  70. package/dist/core/url/published-path.js +40 -121
  71. package/dist/core/url/published-path.js.map +1 -0
  72. package/dist/core/url/route-params.d.ts +3 -11
  73. package/dist/core/url/route-params.js +32 -99
  74. package/dist/core/url/route-params.js.map +1 -0
  75. package/dist/exports/index.d.ts +4 -4
  76. package/dist/exports/index.js +2 -1
  77. package/dist/exports/index.js.map +1 -0
  78. package/dist/plugin/payload-plugin.d.ts +2 -3
  79. package/dist/plugin/payload-plugin.js +94 -91
  80. package/dist/plugin/payload-plugin.js.map +1 -0
  81. package/dist/plugin/types.d.ts +9 -35
  82. package/dist/plugin/types.js +1 -0
  83. package/dist/plugin/types.js.map +1 -0
  84. package/docs/FAILURE_SEMANTICS.md +31 -27
  85. package/package.json +29 -20
  86. package/dist/core/redirects/auto/publication/identifier-snapshot.d.ts +0 -2
  87. package/dist/core/redirects/auto/publication/identifier-snapshot.js +0 -27
  88. package/dist/core/redirects/auto/publication/identifier-transitions.d.ts +0 -18
  89. package/dist/core/redirects/auto/publication/identifier-transitions.js +0 -36
  90. package/dist/core/redirects/auto/publication/transition-for-locale.d.ts +0 -12
  91. package/dist/core/redirects/auto/publication/transition-for-locale.js +0 -167
  92. package/dist/core/redirects/auto/publication/transitions-to-pairs.d.ts +0 -9
  93. package/dist/core/redirects/auto/publication/transitions-to-pairs.js +0 -22
  94. package/dist/core/redirects/auto/published-link-config.d.ts +0 -6
  95. package/dist/core/redirects/auto/published-link-config.js +0 -53
  96. package/dist/core/redirects/auto/published-path.d.ts +0 -6
  97. package/dist/core/redirects/auto/published-path.js +0 -28
  98. package/dist/core/redirects/auto/redirect-custom.d.ts +0 -7
  99. package/dist/core/redirects/auto/redirect-custom.js +0 -19
  100. package/dist/core/redirects/identifier-field-path.d.ts +0 -14
  101. package/dist/core/redirects/identifier-field-path.js +0 -94
  102. package/dist/core/redirects/runtime.d.ts +0 -9
  103. package/dist/core/redirects/runtime.js +0 -13
  104. package/dist/core/url/preview-path.d.ts +0 -1
  105. package/dist/core/url/preview-path.js +0 -9
  106. package/dist/core/url/preview-routes.d.ts +0 -3
  107. package/dist/core/url/preview-routes.js +0 -31
  108. package/docs/RELEASING.md +0 -41
  109. package/docs/adr/0002-database-indexes.md +0 -44
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 41b4bce: Include the tested Node.js 22.23.5 range in package support metadata.
8
+
9
+ ## 0.3.0
10
+
11
+ - Simplify automatic redirect configuration to `path`, `paths`, and `getPath`.
12
+ - Compare complete published paths with native Payload localization and no locale fallback.
13
+ - Register the redirects collection automatically and use `statusCode` as its status field.
package/README.md CHANGED
@@ -1,139 +1,272 @@
1
1
  # @klnap/payload-redirect
2
2
 
3
- Payload plugin for manual and publication-generated redirects.
3
+ Redirect management for Payload CMS.
4
4
 
5
- ## Install
5
+ Manage redirects directly in Payload and automatically preserve existing URLs when published content paths change.
6
+
7
+ Define your public URL structure, enable automatic redirects for selected collections, and let your application's routing layer handle redirect responses.
8
+
9
+ ## Overview
10
+
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.
12
+
13
+ ## Installation
6
14
 
7
15
  ```sh
8
- npm install @klnap/payload-redirect
16
+ bun add @klnap/payload-redirect
9
17
  ```
10
18
 
11
- Requires Payload `>=3.94.1 <4`. PostgreSQL is the supported adapter for transaction-safe
12
- duplicate and redirect-chain checks.
19
+ Requires Node.js `^22.23.5 || ^24.22.3 || >=26.13.1` and Payload `>=3.94.1 <4`.
20
+ PostgreSQL is the supported database adapter.
21
+
22
+ ## Manual redirects
13
23
 
14
- ## Configure
24
+ Register the plugin with no options:
15
25
 
16
26
  ```ts
17
- import { buildConfig } from 'payload'
18
- import { redirects } from '@klnap/payload-redirect'
27
+ import { buildConfig } from "payload";
28
+ import { postgresAdapter } from "@payloadcms/db-postgres";
29
+ import { redirects } from "@klnap/payload-redirect";
19
30
 
20
31
  export default buildConfig({
32
+ secret: process.env.PAYLOAD_SECRET!,
33
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
34
+ plugins: [redirects()],
35
+ });
36
+ ```
37
+
38
+ The plugin adds the `redirects` collection. Add, edit, enable, or disable rules in Payload Admin. Manual rules work without automatic redirect configuration.
39
+
40
+ ## Automatic redirects
41
+
42
+ Automatic generation is enabled for each collection configured in `redirects({ collections })`. Those collections must use Payload drafts so the plugin can compare published snapshots.
43
+
44
+ ```ts
45
+ import { buildConfig } from "payload";
46
+ import { postgresAdapter } from "@payloadcms/db-postgres";
47
+ import { redirects } from "@klnap/payload-redirect";
48
+
49
+ export default buildConfig({
50
+ secret: process.env.PAYLOAD_SECRET!,
51
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
52
+ localization: {
53
+ locales: ["pl", "en", "de"],
54
+ defaultLocale: "pl",
55
+ },
21
56
  collections: [
22
57
  {
23
- slug: 'articles',
58
+ slug: "articles",
24
59
  versions: { drafts: true },
25
- fields: [{ name: 'slug', type: 'text', required: true }],
26
- custom: {
27
- redirect: {
28
- identifier: 'slug',
29
- publishedLink: { path: '/articles/[slug]' },
30
- },
31
- },
60
+ fields: [
61
+ { name: "title", type: "text", required: true },
62
+ { name: "slug", type: "text", required: true, localized: true },
63
+ ],
64
+ },
65
+ {
66
+ slug: "projects",
67
+ versions: { drafts: true },
68
+ fields: [{ name: "slug", type: "text", required: true, localized: true }],
32
69
  },
33
70
  ],
34
71
  plugins: [
35
72
  redirects({
36
- localePrefix: { en: '', pl: '/pl' },
73
+ localePrefixes: {
74
+ pl: "",
75
+ en: "/en",
76
+ de: "/de",
77
+ },
78
+ collections: {
79
+ articles: { path: "/[slug]" },
80
+ projects: {
81
+ paths: {
82
+ pl: "/realizacje/[slug]",
83
+ en: "/work/[slug]",
84
+ de: "/projekte/[slug]",
85
+ },
86
+ },
87
+ },
37
88
  }),
38
89
  ],
39
- })
90
+ });
40
91
  ```
41
92
 
42
- `redirects()` adds the plugin-owned `redirects` collection and wires publication hooks for
43
- collections with `custom.redirect.identifier`. It preserves existing hooks. Do not register a
44
- second redirects collection or add manual publication hooks.
93
+ ### Reading the configuration
45
94
 
46
- The plugin creates a rule when a published identifier changes. Draft saves, first publications,
47
- unpublishes, and unchanged identifiers do not create rules. A manual rule on the same source path
48
- always wins over an automatic rule.
95
+ > When the published path of a document in this collection changes, redirect the previous path to the new one.
49
96
 
50
- ## Published paths
97
+ - Articles use one path template. `localePrefixes` adds each locale's explicit prefix.
98
+ - Projects use a separate public path template for each Payload locale.
99
+ - Collections without redirect configuration remain unaffected.
51
100
 
52
- Put collection-specific settings in `custom.redirect.publishedLink`. `custom.draft.publishedLink`
53
- is also read when `custom.redirect.publishedLink` is absent.
101
+ For a Polish project, a slug change creates this rule:
54
102
 
55
- Use `path` for a shared template, `paths` for locale-specific templates, or `getPath` for custom
56
- logic. Template parameters match top-level collection fields; localized fields resolve for the
57
- published locale. Dynamic values are URL-encoded as single path segments.
103
+ ```text
104
+ Previous published path: /realizacje/stary-projekt
105
+ Current published path: /realizacje/nowy-projekt
106
+ Generated redirect: /realizacje/stary-projekt → /realizacje/nowy-projekt
107
+ ```
108
+
109
+ 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.
110
+
111
+ ### Collection-level configuration
112
+
113
+ Use the same options directly on a collection when central configuration is not convenient:
58
114
 
59
115
  ```ts
60
- custom: {
61
- redirect: {
62
- identifier: 'slug',
63
- publishedLink: {
64
- paths: {
65
- en: '/articles/[slug]',
66
- pl: '/artykuly/[slug]',
67
- },
68
- },
116
+ import type { CollectionConfig } from "payload";
117
+ import type { RedirectCollectionOptions } from "@klnap/payload-redirect";
118
+
119
+ const projectRedirect = {
120
+ paths: {
121
+ pl: "/realizacje/[slug]",
122
+ en: "/work/[slug]",
123
+ de: "/projekte/[slug]",
69
124
  },
125
+ } satisfies RedirectCollectionOptions<"projects">;
126
+
127
+ export const Projects: CollectionConfig = {
128
+ slug: "projects",
129
+ versions: { drafts: true },
130
+ custom: {
131
+ redirect: projectRedirect,
132
+ },
133
+ fields: [{ name: "slug", type: "text", required: true, localized: true }],
134
+ };
135
+ ```
136
+
137
+ Central configuration replaces collection-level configuration for that collection. The plugin does not merge path strategies.
138
+
139
+ Set `custom.redirect.enabled` to `false` to disable automatic generation for that collection. Manual redirect management remains enabled.
140
+
141
+ ## Published paths
142
+
143
+ Choose exactly one path strategy for each configured collection.
144
+
145
+ ### Shared templates
146
+
147
+ Use `path` when every locale has the same route shape:
148
+
149
+ ```ts
150
+ articles: {
151
+ path: "/articles/[slug]";
70
152
  }
71
153
  ```
72
154
 
73
- `getPath` receives the published document snapshot and locale. Return a site path or `null` to skip
74
- that transition:
155
+ Templates use top-level field names in brackets. Use multiple fields when the public route depends on multiple values:
75
156
 
76
157
  ```ts
77
- publishedLink: {
78
- getPath: ({ doc, locale }) =>
79
- `/articles/${String(doc.category)}/${String(doc.slug)}-${locale}`,
158
+ projects: {
159
+ path: "/[category]/[slug]";
80
160
  }
81
161
  ```
82
162
 
83
- Centralized path rules can be set in `redirects()`; collection `publishedLink` settings take precedence:
163
+ Each value is encoded as one URL path segment. Missing, invalid, or unsafe values prevent that transition from creating a redirect.
164
+
165
+ ### Localized templates
166
+
167
+ Use `paths` to give each Payload locale a complete template:
84
168
 
85
169
  ```ts
86
- redirects({
87
- localePrefix: { en: '', pl: '/pl' },
88
- collections: {
89
- articles: {
90
- identifier: 'slug',
91
- path: '/articles/[slug]',
92
- },
170
+ projects: {
171
+ paths: {
172
+ pl: '/realizacje/[slug]',
173
+ en: '/work/[slug]',
174
+ de: '/projekte/[slug]',
93
175
  },
94
- })
176
+ }
95
177
  ```
96
178
 
97
- Payload localization defines the available locales. If you set a prefix map, include every locale.
98
- An empty prefix means no locale segment. Without a prefix map, the builder uses the locale code.
179
+ The map must include every locale configured in Payload. The plugin does not use fallback locale values to resolve a published path.
180
+
181
+ ### Locale prefixes
182
+
183
+ `localePrefixes` maps Payload locale codes to explicit prefixes. An empty string means no prefix. The map must include every Payload locale when provided.
184
+
185
+ Prefixes apply to `path` and `paths`. If `localePrefixes` is omitted, the plugin adds no prefix and does not infer one from the locale code.
186
+
187
+ ### Custom path resolution
188
+
189
+ Use `getPath` when templates cannot express the public route:
190
+
191
+ ```ts
192
+ projects: {
193
+ getPath: ({ doc, locale }) =>
194
+ doc.slug && doc.category
195
+ ? `${locale ? `/${locale}` : ''}/${String(doc.category)}/${String(doc.slug)}`
196
+ : null,
197
+ }
198
+ ```
199
+
200
+ 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.
99
201
 
100
202
  ## Redirect collection
101
203
 
102
- The plugin owns the collection and its required fields: `from`, `to`, `StatusCode`, `enabled`, and
103
- `origin`. `from` is unique. Redirect writes normalize paths and reject duplicate sources and
104
- enabled loops. Manual rules are not overwritten by publication hooks.
204
+ The plugin owns these fields:
205
+
206
+ - `from`: unique source path.
207
+ - `to`: site-relative destination path.
208
+ - `statusCode`: `301` or `302`.
209
+ - `enabled`: whether the rule is active.
210
+ - `origin`: `manual` or `auto`.
211
+
212
+ The schema uses the camelCase field `statusCode`.
105
213
 
106
- Pass native Payload collection settings through `overrides`:
214
+ ### Collection overrides
215
+
216
+ Pass native Payload collection options through `overrides`:
107
217
 
108
218
  ```ts
109
219
  redirects({
110
220
  overrides: {
111
- slug: 'url-rules',
112
- labels: { singular: 'URL rule', plural: 'URL rules' },
113
- admin: { group: 'Content' },
221
+ slug: "url-rules",
222
+ labels: { singular: "URL rule", plural: "URL rules" },
223
+ admin: { group: "Settings" },
224
+ trash: true,
114
225
  },
115
- })
226
+ });
116
227
  ```
117
228
 
118
- Use `overrides.fields` to customize the plugin fields. It receives `defaultFields`; required fields,
119
- validators, uniqueness, and indexes remain enforced.
229
+ Use `overrides.fields` to customize the plugin fields. Required fields, validation, uniqueness, and indexes remain enforced.
120
230
 
121
- `enabled: false` disables automatic generation only. The manual redirects collection remains
122
- available.
231
+ ## Automatic redirect behavior
123
232
 
124
- ## Checks and limits
233
+ - Draft saves, autosaves, first publications, unpublishes, and unchanged paths create no rules.
234
+ - The plugin compares the current published path with the latest earlier published path.
235
+ - A missing or unsafe path on either side skips that locale's redirect.
236
+ - A manual rule that owns the previous path is never overwritten.
237
+ - Automatic writes run through Payload Local API with the active request and transaction.
238
+ - Deleting a document does not create a redirect; configure removal behavior in your application if needed.
125
239
 
126
- - PostgreSQL is required for transaction-scoped advisory locking and race-safe graph validation.
127
- - Other database adapters are not claimed to provide equivalent concurrency guarantees.
128
- - The plugin stores redirect rules; the host application serves them from its routing layer.
129
- - The package does not expose a redirect resolver or HTTP middleware.
240
+ Automatic generation requires `versions.drafts`. It reads published versions with fallback disabled so localized paths never borrow values from another locale.
130
241
 
131
- Run package checks:
242
+ ## Application integration
132
243
 
133
- ```sh
134
- bun run typecheck
135
- bun run typecheck:consumer
136
- bun test src tests/unit
137
- bun run test:int
138
- bun run check:release
244
+ The package stores rules. Your application retrieves enabled rules, caches them, matches incoming paths, and returns HTTP redirect responses.
245
+
246
+ ```ts
247
+ const { docs } = await payload.find({
248
+ collection: "redirects",
249
+ where: { enabled: { equals: true } },
250
+ depth: 0,
251
+ });
252
+
253
+ // Match the incoming path and return the selected rule's statusCode and to.
139
254
  ```
255
+
256
+ The package does not include a resolver, cache, middleware, proxy, or framework adapter.
257
+
258
+ ## Security and reliability
259
+
260
+ 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.
261
+
262
+ PostgreSQL provides the transaction-scoped advisory lock used to serialize graph validation. This package does not claim equivalent concurrent-write guarantees for other adapters.
263
+
264
+ ## Requirements
265
+
266
+ - Payload: `>=3.94.1 <4`.
267
+ - PostgreSQL: supported adapter for transaction-scoped graph locking.
268
+ - Other adapters: no equivalent concurrency guarantee is claimed.
269
+
270
+ ## License
271
+
272
+ MIT
@@ -1,5 +1,10 @@
1
- import type { CollectionAfterChangeHook } from 'payload';
2
- export type CreateRedirectOptions = {
3
- identifier: string;
1
+ import type { CollectionAfterChangeHook } from "payload";
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,78 +1,38 @@
1
- import { ensureAutoRedirect } from './persist-auto-rule.js';
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
- import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
6
- import { paramKeyFromIdentifierPath } from '../identifier-field-path.js';
7
- import { normalizePathOrUrl } from '../normalize-path.js';
8
- import { getRedirectRuntime } from '../runtime.js';
9
- import { buildPublishedPath } from '../../url/published-path.js';
10
- const publishedDataForLocale = (doc, collection, locale) => {
11
- const data = { ...doc };
12
- for (const field of collection.fields) {
13
- if (!('name' in field) || typeof field.name !== 'string' || !('localized' in field))
14
- continue;
15
- const value = data[field.name];
16
- if (field.localized === true && value && typeof value === 'object' && !Array.isArray(value)) {
17
- data[field.name] = value[locale];
18
- }
19
- }
20
- return data;
21
- };
22
- export const createRedirect = (options) => async (args) => {
23
- const { req, collection } = args;
24
- if (req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]) {
1
+ import { ensureAutoRedirect } from "./persist-auto-rule.js";
2
+ import { getPublicationTransition } from "./publication/get-publication-transition.js";
3
+ import { REDIRECT_CONTEXT_KEYS } from "../context-keys.js";
4
+ import { normalizePathOrUrl } from "../normalize-path.js";
5
+ import { buildPublishedPath } from "../../url/published-path.js";
6
+ export const createRedirect = ({ collectionSlug, pathOptions, localePrefixes, }) => async (args) => {
7
+ if (pathOptions.enabled === false)
25
8
  return args.doc;
26
- }
27
- const transitions = await getPublicationTransition(args, options);
28
- const pairs = publicationTransitionsToPairs(transitions);
29
- if (pairs.length === 0) {
9
+ if (args.req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
30
10
  return args.doc;
31
- }
32
- const { collectionSlug, localePrefix } = getRedirectRuntime(req.payload.config);
33
- const pathConfig = resolveCollectionPublishedPathConfig(collection, localePrefix);
34
- for (const { previous, current, locale, previousDoc, currentDoc } of pairs) {
35
- const resolvePath = (identifierValue, publishedDoc) => {
36
- if (!pathConfig || !locale)
37
- return identifierValue;
38
- const paramKey = paramKeyFromIdentifierPath(options.identifier);
39
- const mapping = pathConfig.params?.[paramKey];
40
- const data = publishedDataForLocale(publishedDoc, collection, locale);
41
- if (data[paramKey] === undefined) {
42
- data[paramKey] =
43
- mapping &&
44
- typeof mapping === 'object' &&
45
- 'localized' in mapping &&
46
- mapping.localized === true
47
- ? { [locale]: identifierValue }
48
- : identifierValueForPath(options.identifier, identifierValue)[paramKey];
49
- }
50
- const built = buildPublishedPath(pathConfig, data, locale);
51
- return built;
52
- };
53
- const fromRaw = resolvePath(previous, previousDoc);
54
- const toRaw = resolvePath(current, currentDoc);
55
- 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)
56
22
  continue;
57
- }
58
- let from;
59
- let to;
60
- try {
61
- from = normalizePathOrUrl(fromRaw);
62
- to = normalizePathOrUrl(toRaw);
63
- }
64
- catch {
23
+ const previousPath = buildPublishedPath(pathOptions, previousPublishedDoc, locale, localePrefixes);
24
+ if (!previousPath)
65
25
  continue;
66
- }
67
- if (from === to) {
26
+ const from = normalizePathOrUrl(previousPath);
27
+ if (from === to)
68
28
  continue;
69
- }
70
29
  await ensureAutoRedirect({
71
- req,
30
+ req: args.req,
72
31
  collectionSlug,
73
32
  rule: { from, to },
74
- context: req.context,
33
+ context: args.req.context,
75
34
  });
76
35
  }
77
36
  return args.doc;
78
37
  };
38
+ //# sourceMappingURL=create-redirect.js.map
@@ -0,0 +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,cAAc,GACzB,CAAC,EACC,cAAc,EACd,WAAW,EACX,cAAc,GACQ,EAA6B,EAAE,CACvD,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;IAEzD,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,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE;YAC/D,MAAM,IAAI,GAAG,kBAAkB,CAAC,WAAW,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;YACnF,OAAO,CAAC,IAAI,IAAI,kBAAkB,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;QAClD,CAAC,CAAC,CAAC;QACH,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,EAAE,IAAI,CAAC,GAAG;YACb,cAAc;YACd,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;YAClB,OAAO,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO;SAC1B,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,CAAC,GAAG,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import type { CollectionAfterChangeHook } 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 { RedirectPathOptions } from \"./types.js\";\n\ntype CreateRedirectOptions = {\n collectionSlug: string;\n pathOptions: RedirectPathOptions;\n localePrefixes?: LocalePrefixes;\n};\n\nexport const createRedirect =\n ({\n collectionSlug,\n pathOptions,\n localePrefixes,\n }: CreateRedirectOptions): 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\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 const previousPublishedDoc = publishedDocs.find((publishedDoc) => {\n const path = buildPublishedPath(pathOptions, publishedDoc, locale, localePrefixes);\n return !path || normalizePathOrUrl(path) !== to;\n });\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: args.req,\n collectionSlug,\n rule: { from, to },\n context: args.req.context,\n });\n }\n\n return args.doc;\n };\n"]}
@@ -1,4 +1,4 @@
1
- import type { RedirectLookupDoc } from '../queries.js';
1
+ import type { RedirectLookupDoc } from "../queries.js";
2
2
  export declare const isIdenticalAutoRule: (doc: RedirectLookupDoc, rule: {
3
3
  from: string;
4
4
  to: string;
@@ -1,7 +1,8 @@
1
- import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, } from '../model/status-code.js';
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
- doc.origin === 'auto';
7
+ doc.origin === "auto";
8
+ //# sourceMappingURL=match-existing-rule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"match-existing-rule.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/match-existing-rule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AAGpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,CACjC,GAAsB,EACtB,IAAkC,EACzB,EAAE,CACX,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI;IACtB,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;IAClB,wBAAwB,CAAC,GAAG,CAAC,UAAU,IAAI,4BAA4B,CAAC;QACtE,4BAA4B;IAC9B,GAAG,CAAC,OAAO,KAAK,KAAK;IACrB,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC","sourcesContent":["import {\n assertRedirectStatusCode,\n DEFAULT_REDIRECT_STATUS_CODE,\n} from \"#redirect/core/redirects/model/status-code\";\nimport type { RedirectLookupDoc } from \"#redirect/core/redirects/queries\";\n\nexport const isIdenticalAutoRule = (\n doc: RedirectLookupDoc,\n rule: { from: string; to: string },\n): boolean =>\n doc.from === rule.from &&\n doc.to === rule.to &&\n assertRedirectStatusCode(doc.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE) ===\n DEFAULT_REDIRECT_STATUS_CODE &&\n doc.enabled !== false &&\n doc.origin === \"auto\";\n"]}
@@ -1,9 +1,9 @@
1
- import type { PayloadRequest } from 'payload';
2
- export type AutoRedirectRule = {
1
+ import type { PayloadRequest } from "payload";
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;
@@ -12,4 +12,5 @@ export type EnsureAutoRedirectArgs = {
12
12
  /**
13
13
  * Idempotent create for auto 301 rules. One lookup by unique `from`.
14
14
  */
15
- export declare const ensureAutoRedirect: ({ req, collectionSlug, rule, context, }: EnsureAutoRedirectArgs) => Promise<'created' | 'skipped' | 'updated'>;
15
+ export declare const ensureAutoRedirect: ({ req, collectionSlug, rule, context, }: EnsureAutoRedirectArgs) => Promise<"created" | "skipped" | "updated">;
16
+ export {};
@@ -1,6 +1,6 @@
1
- import { isIdenticalAutoRule } from './match-existing-rule.js';
2
- import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
3
- import { findRedirectByFrom } from '../queries.js';
1
+ import { isIdenticalAutoRule } from "./match-existing-rule.js";
2
+ import { REDIRECT_CONTEXT_KEYS } from "../context-keys.js";
3
+ import { findRedirectByFrom } from "../queries.js";
4
4
  /**
5
5
  * Idempotent create for auto 301 rules. One lookup by unique `from`.
6
6
  */
@@ -13,9 +13,9 @@ 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
- origin: 'auto',
18
+ origin: "auto",
19
19
  };
20
20
  const payload = req.payload;
21
21
  const existing = await findRedirectByFrom(req.payload, {
@@ -28,24 +28,24 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
28
28
  const doc = existing.docs[0];
29
29
  if (doc) {
30
30
  if (isIdenticalAutoRule(doc, rule)) {
31
- return 'skipped';
31
+ return "skipped";
32
32
  }
33
- if (doc.origin === 'auto') {
33
+ if (doc.origin === "auto") {
34
34
  await payload.update({
35
35
  collection: collectionSlug,
36
36
  id: doc.id,
37
37
  data: {
38
38
  to: rule.to,
39
- StatusCode: '301',
39
+ statusCode: "301",
40
40
  enabled: true,
41
41
  },
42
42
  context: internalContext,
43
43
  overrideAccess: false,
44
44
  req,
45
45
  });
46
- return 'updated';
46
+ return "updated";
47
47
  }
48
- return 'skipped';
48
+ return "skipped";
49
49
  }
50
50
  await payload.create({
51
51
  collection: collectionSlug,
@@ -54,5 +54,6 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
54
54
  overrideAccess: false,
55
55
  req,
56
56
  });
57
- return 'created';
57
+ return "created";
58
58
  };
59
+ //# sourceMappingURL=persist-auto-rule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persist-auto-rule.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/persist-auto-rule.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAA0B,MAAM,kCAAkC,CAAC;AAc9F;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EAAE,EACvC,GAAG,EACH,cAAc,EACd,IAAI,EACJ,OAAO,GACgB,EAA8C,EAAE;IACvE,MAAM,eAAe,GAAG;QACtB,GAAG,OAAO;QACV,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,IAAI;QACtC,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,IAAI;KACvC,CAAC;IAEF,MAAM,IAAI,GAAG;QACX,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,UAAU,EAAE,KAAK;QACjB,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,MAAe;KACxB,CAAC;IACF,MAAM,OAAO,GAAG,GAAG,CAAC,OAGnB,CAAC;IAEF,MAAM,QAAQ,GAAG,MAAM,kBAAkB,CAAC,GAAG,CAAC,OAAO,EAAE;QACrD,cAAc;QACd,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,GAAG;QACH,cAAc,EAAE,KAAK;QACrB,OAAO,EAAE,eAAe;KACzB,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAkC,CAAC;IAC9D,IAAI,GAAG,EAAE,CAAC;QACR,IAAI,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC;YACnC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,MAAM,CAAC;gBACnB,UAAU,EAAE,cAAc;gBAC1B,EAAE,EAAE,GAAG,CAAC,EAAE;gBACV,IAAI,EAAE;oBACJ,EAAE,EAAE,IAAI,CAAC,EAAE;oBACX,UAAU,EAAE,KAAK;oBACjB,OAAO,EAAE,IAAI;iBACd;gBACD,OAAO,EAAE,eAAe;gBACxB,cAAc,EAAE,KAAK;gBACrB,GAAG;aACJ,CAAC,CAAC;YACH,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,OAAO,CAAC,MAAM,CAAC;QACnB,UAAU,EAAE,cAAc;QAC1B,IAAI;QACJ,OAAO,EAAE,eAAe;QACxB,cAAc,EAAE,KAAK;QACrB,GAAG;KACJ,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\nimport { isIdenticalAutoRule } from \"#redirect/core/redirects/auto/match-existing-rule\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport { findRedirectByFrom, type RedirectLookupDoc } from \"#redirect/core/redirects/queries\";\n\ntype AutoRedirectRule = {\n from: string;\n to: string;\n};\n\ntype EnsureAutoRedirectArgs = {\n req: PayloadRequest;\n collectionSlug: string;\n rule: AutoRedirectRule;\n context?: Record<string, unknown>;\n};\n\n/**\n * Idempotent create for auto 301 rules. One lookup by unique `from`.\n */\nexport const ensureAutoRedirect = async ({\n req,\n collectionSlug,\n rule,\n context,\n}: EnsureAutoRedirectArgs): Promise<\"created\" | \"skipped\" | \"updated\"> => {\n const internalContext = {\n ...context,\n [REDIRECT_CONTEXT_KEYS.internal]: true,\n [REDIRECT_CONTEXT_KEYS.skipAuto]: true,\n };\n\n const data = {\n from: rule.from,\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n origin: \"auto\" as const,\n };\n const payload = req.payload as unknown as {\n create: (args: Record<string, unknown>) => Promise<unknown>;\n update: (args: Record<string, unknown>) => Promise<unknown>;\n };\n\n const existing = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: rule.from,\n req,\n overrideAccess: false,\n context: internalContext,\n });\n\n const doc = existing.docs[0] as RedirectLookupDoc | undefined;\n if (doc) {\n if (isIdenticalAutoRule(doc, rule)) {\n return \"skipped\";\n }\n if (doc.origin === \"auto\") {\n await payload.update({\n collection: collectionSlug,\n id: doc.id,\n data: {\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n },\n context: internalContext,\n overrideAccess: false,\n req,\n });\n return \"updated\";\n }\n return \"skipped\";\n }\n\n await payload.create({\n collection: collectionSlug,\n data,\n context: internalContext,\n overrideAccess: false,\n req,\n });\n\n return \"created\";\n};\n"]}
@@ -1,3 +1,3 @@
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[]>;
1
+ import type { CollectionAfterChangeHook } from "payload";
2
+ import type { PublicationTransition } from "../types.js";
3
+ export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0]) => Promise<PublicationTransition[]>;