@klnap/payload-redirect 0.2.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.
- package/CHANGELOG.md +7 -0
- package/README.md +204 -72
- package/dist/core/redirects/auto/create-redirect.d.ts +8 -3
- package/dist/core/redirects/auto/create-redirect.js +20 -61
- package/dist/core/redirects/auto/match-existing-rule.js +1 -1
- package/dist/core/redirects/auto/persist-auto-rule.d.ts +3 -2
- package/dist/core/redirects/auto/persist-auto-rule.js +2 -2
- package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +2 -2
- package/dist/core/redirects/auto/publication/get-publication-transition.js +20 -36
- package/dist/core/redirects/auto/publication/locales.d.ts +7 -5
- package/dist/core/redirects/auto/publication/locales.js +32 -28
- package/dist/core/redirects/auto/publication/publish-intent.d.ts +1 -3
- package/dist/core/redirects/auto/publication/publish-intent.js +2 -26
- package/dist/core/redirects/auto/publication/versions/document-locale.d.ts +4 -6
- package/dist/core/redirects/auto/publication/versions/document-locale.js +9 -18
- package/dist/core/redirects/auto/publication/versions/version-pages.d.ts +2 -10
- package/dist/core/redirects/auto/publication/versions/version-pages.js +4 -30
- package/dist/core/redirects/auto/publication/versions/version-rows.d.ts +1 -7
- package/dist/core/redirects/auto/publication/versions/version-rows.js +4 -28
- package/dist/core/redirects/auto/types.d.ts +27 -8
- package/dist/core/redirects/collection/collection.js +1 -1
- package/dist/core/redirects/collection/duplicate-guard.js +1 -1
- package/dist/core/redirects/collection/fields.js +4 -4
- package/dist/core/redirects/model/status-code.js +1 -1
- package/dist/core/redirects/queries.d.ts +1 -10
- package/dist/core/redirects/queries.js +2 -2
- package/dist/core/url/published-path.d.ts +4 -16
- package/dist/core/url/published-path.js +38 -120
- package/dist/core/url/route-params.d.ts +3 -11
- package/dist/core/url/route-params.js +31 -99
- package/dist/exports/index.d.ts +1 -1
- package/dist/plugin/payload-plugin.d.ts +0 -1
- package/dist/plugin/payload-plugin.js +83 -81
- package/dist/plugin/types.d.ts +8 -34
- package/docs/FAILURE_SEMANTICS.md +15 -11
- package/package.json +10 -9
- package/dist/core/redirects/auto/publication/identifier-snapshot.d.ts +0 -2
- package/dist/core/redirects/auto/publication/identifier-snapshot.js +0 -27
- package/dist/core/redirects/auto/publication/identifier-transitions.d.ts +0 -18
- package/dist/core/redirects/auto/publication/identifier-transitions.js +0 -36
- package/dist/core/redirects/auto/publication/transition-for-locale.d.ts +0 -12
- package/dist/core/redirects/auto/publication/transition-for-locale.js +0 -167
- package/dist/core/redirects/auto/publication/transitions-to-pairs.d.ts +0 -9
- package/dist/core/redirects/auto/publication/transitions-to-pairs.js +0 -22
- package/dist/core/redirects/auto/published-link-config.d.ts +0 -6
- package/dist/core/redirects/auto/published-link-config.js +0 -53
- package/dist/core/redirects/auto/published-path.d.ts +0 -6
- package/dist/core/redirects/auto/published-path.js +0 -28
- package/dist/core/redirects/auto/redirect-custom.d.ts +0 -7
- package/dist/core/redirects/auto/redirect-custom.js +0 -19
- package/dist/core/redirects/identifier-field-path.d.ts +0 -14
- package/dist/core/redirects/identifier-field-path.js +0 -94
- package/dist/core/redirects/runtime.d.ts +0 -9
- package/dist/core/redirects/runtime.js +0 -13
- package/dist/core/url/preview-path.d.ts +0 -1
- package/dist/core/url/preview-path.js +0 -9
- package/dist/core/url/preview-routes.d.ts +0 -3
- package/dist/core/url/preview-routes.js +0 -31
- package/docs/RELEASING.md +0 -41
- package/docs/adr/0002-database-indexes.md +0 -44
|
@@ -1,107 +1,39 @@
|
|
|
1
|
-
import { localeCode } from './preview-path.js';
|
|
2
1
|
const DYNAMIC_SEGMENT = /\[([^\]]+)\]/g;
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
return
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
if (!
|
|
2
|
+
const VALID_FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3
|
+
const FORBIDDEN_FIELD_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
|
|
4
|
+
export const hasControlCharacter = (value) => [...value].some((character) => {
|
|
5
|
+
const code = character.charCodeAt(0);
|
|
6
|
+
return code <= 0x1f || code === 0x7f;
|
|
7
|
+
});
|
|
8
|
+
export const isValidPathTemplate = (template) => {
|
|
9
|
+
if (!template.startsWith('/') ||
|
|
10
|
+
template.startsWith('//') ||
|
|
11
|
+
/[?#\\]/.test(template) ||
|
|
12
|
+
hasControlCharacter(template)) {
|
|
11
13
|
return false;
|
|
12
|
-
if (name.includes('..'))
|
|
13
|
-
return false;
|
|
14
|
-
return true;
|
|
15
|
-
}
|
|
16
|
-
export function extractDynamicSegments(template) {
|
|
17
|
-
if (templateHasUnsupportedDynamicSyntax(template))
|
|
18
|
-
return [];
|
|
19
|
-
const names = [];
|
|
20
|
-
const seen = new Set();
|
|
21
|
-
for (const match of template.matchAll(DYNAMIC_SEGMENT)) {
|
|
22
|
-
const name = match[1];
|
|
23
|
-
if (!name || !isSupportedParamName(name) || seen.has(name))
|
|
24
|
-
continue;
|
|
25
|
-
seen.add(name);
|
|
26
|
-
names.push(name);
|
|
27
14
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return undefined;
|
|
33
|
-
const parts = fieldPath.split('.');
|
|
34
|
-
if (parts.some((part) => part.length === 0 || FORBIDDEN_FIELD_SEGMENTS.has(part))) {
|
|
35
|
-
return undefined;
|
|
15
|
+
const fields = [...template.matchAll(DYNAMIC_SEGMENT)];
|
|
16
|
+
if (template.replace(DYNAMIC_SEGMENT, '').includes('[') ||
|
|
17
|
+
template.replace(DYNAMIC_SEGMENT, '').includes(']')) {
|
|
18
|
+
return false;
|
|
36
19
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
20
|
+
return fields.every(([, name]) => Boolean(name && VALID_FIELD_NAME.test(name) && !FORBIDDEN_FIELD_NAMES.has(name)));
|
|
21
|
+
};
|
|
22
|
+
const extractDynamicSegments = (template) => [...template.matchAll(DYNAMIC_SEGMENT)].flatMap(([, name]) => (name ? [name] : []));
|
|
23
|
+
export const applyDynamicSegments = (template, doc, locale) => {
|
|
24
|
+
if (!isValidPathTemplate(template))
|
|
25
|
+
return null;
|
|
26
|
+
let result = template;
|
|
27
|
+
for (const field of extractDynamicSegments(template)) {
|
|
28
|
+
let value = doc[field];
|
|
29
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
30
|
+
value = locale ? value[locale] : undefined;
|
|
41
31
|
}
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
if (!
|
|
45
|
-
return undefined;
|
|
46
|
-
current = current[part];
|
|
47
|
-
}
|
|
48
|
-
return current;
|
|
49
|
-
}
|
|
50
|
-
function normalizeMapping(mapping) {
|
|
51
|
-
if (typeof mapping === 'string') {
|
|
52
|
-
if (mapping.length === 0)
|
|
32
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
33
|
+
value = String(value);
|
|
34
|
+
if (typeof value !== 'string' || !value || value === '.' || value === '..')
|
|
53
35
|
return null;
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
if (typeof mapping.field !== 'string' || mapping.field.length === 0)
|
|
57
|
-
return null;
|
|
58
|
-
return mapping;
|
|
59
|
-
}
|
|
60
|
-
function coerceParamString(raw, code, localized) {
|
|
61
|
-
if (localized) {
|
|
62
|
-
if (typeof raw === 'string')
|
|
63
|
-
return raw.length > 0 ? raw : null;
|
|
64
|
-
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
65
|
-
const value = raw[code];
|
|
66
|
-
if (typeof value === 'string' && value.length > 0)
|
|
67
|
-
return value;
|
|
68
|
-
}
|
|
69
|
-
return null;
|
|
36
|
+
result = result.replaceAll(`[${field}]`, encodeURIComponent(value));
|
|
70
37
|
}
|
|
71
|
-
if (typeof raw === 'string')
|
|
72
|
-
return raw.length > 0 ? raw : null;
|
|
73
|
-
if (typeof raw === 'number' && Number.isFinite(raw))
|
|
74
|
-
return String(raw);
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
export function resolveRouteParam(paramName, data, locale, routeParams) {
|
|
78
|
-
const code = localeCode(locale);
|
|
79
|
-
if (!code)
|
|
80
|
-
return null;
|
|
81
|
-
const mapping = routeParams?.[paramName];
|
|
82
|
-
if (mapping === undefined)
|
|
83
|
-
return null;
|
|
84
|
-
const spec = normalizeMapping(mapping);
|
|
85
|
-
if (!spec)
|
|
86
|
-
return null;
|
|
87
|
-
const raw = readValueAtPath(data, spec.field);
|
|
88
|
-
return coerceParamString(raw, code, spec.localized === true);
|
|
89
|
-
}
|
|
90
|
-
export function applyDynamicSegments(pattern, data, locale, routeParams) {
|
|
91
|
-
if (templateHasUnsupportedDynamicSyntax(pattern))
|
|
92
|
-
return null;
|
|
93
|
-
const segments = extractDynamicSegments(pattern);
|
|
94
|
-
if (segments.length === 0 && DYNAMIC_SEGMENT.test(pattern))
|
|
95
|
-
return null;
|
|
96
|
-
let result = pattern;
|
|
97
|
-
for (const name of segments) {
|
|
98
|
-
const value = resolveRouteParam(name, data, locale, routeParams);
|
|
99
|
-
// Why: encodeURIComponent leaves dot segments unchanged, so they would rewrite the path.
|
|
100
|
-
if (!value || value === '.' || value === '..')
|
|
101
|
-
return null;
|
|
102
|
-
result = result.replaceAll(`[${name}]`, encodeURIComponent(value));
|
|
103
|
-
}
|
|
104
|
-
if (/\[[^\]]+\]/.test(result))
|
|
105
|
-
return null;
|
|
106
38
|
return result;
|
|
107
|
-
}
|
|
39
|
+
};
|
package/dist/exports/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export type { RedirectOrigin } from '../core/redirects/model/origin.js';
|
|
2
2
|
export type { RedirectStatusCode } from '../core/redirects/model/status-code.js';
|
|
3
3
|
export { redirects } from '../plugin/payload-plugin.js';
|
|
4
|
-
export type { RedirectsOptions } from '../plugin/types.js';
|
|
4
|
+
export type { RedirectCollectionOptions, RedirectsOptions } from '../plugin/types.js';
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { definePlugin } from 'payload';
|
|
2
2
|
import { createRedirect } from '../core/redirects/auto/create-redirect.js';
|
|
3
|
-
import { readRedirectCustom } from '../core/redirects/auto/redirect-custom.js';
|
|
4
3
|
import { createRedirectsCollection } from '../core/redirects/collection/collection.js';
|
|
5
|
-
import {
|
|
4
|
+
import { isValidLocalePrefix } from '../core/url/published-path.js';
|
|
5
|
+
import { isValidPathTemplate } from '../core/url/route-params.js';
|
|
6
6
|
const PLUGIN_SLUG = '@klnap/payload-redirect';
|
|
7
7
|
const DEFAULT_COLLECTION_SLUG = 'redirects';
|
|
8
|
+
const PATH_OPTIONS = new Set(['enabled', 'path', 'paths', 'getPath']);
|
|
8
9
|
const asRecord = (value) => value && typeof value === 'object' && !Array.isArray(value)
|
|
9
10
|
? value
|
|
10
11
|
: undefined;
|
|
@@ -18,10 +19,8 @@ const assertLocaleMap = (value, locales, name) => {
|
|
|
18
19
|
const map = asRecord(value);
|
|
19
20
|
if (!map)
|
|
20
21
|
throw new Error(`payload-redirect: ${name} must be a locale map`);
|
|
21
|
-
const missing = locales.filter((locale) => !(locale
|
|
22
|
-
const unknown = locales.
|
|
23
|
-
? Object.keys(map).filter((locale) => !locales.includes(locale))
|
|
24
|
-
: [];
|
|
22
|
+
const missing = locales.filter((locale) => !Object.hasOwn(map, locale));
|
|
23
|
+
const unknown = Object.keys(map).filter((locale) => !locales.includes(locale));
|
|
25
24
|
if (missing.length || unknown.length) {
|
|
26
25
|
throw new Error(`payload-redirect: ${name} has invalid locales (missing: ${missing.join(', ') || 'none'}; unknown: ${unknown.join(', ') || 'none'})`);
|
|
27
26
|
}
|
|
@@ -32,90 +31,101 @@ const assertLocaleMap = (value, locales, name) => {
|
|
|
32
31
|
}
|
|
33
32
|
return map;
|
|
34
33
|
};
|
|
34
|
+
const validatePathOptions = (value, slug, locales, collection) => {
|
|
35
|
+
const options = asRecord(value);
|
|
36
|
+
if (!options)
|
|
37
|
+
throw new Error(`payload-redirect: redirect config for "${slug}" must be an object`);
|
|
38
|
+
const unsupported = Object.keys(options).filter((key) => !PATH_OPTIONS.has(key));
|
|
39
|
+
if (unsupported.length) {
|
|
40
|
+
throw new Error(`payload-redirect: unsupported redirect option for "${slug}": ${unsupported.join(', ')}`);
|
|
41
|
+
}
|
|
42
|
+
const modes = ['path', 'paths', 'getPath'].filter((key) => Object.hasOwn(options, key));
|
|
43
|
+
if (options.enabled === false) {
|
|
44
|
+
if (modes.length) {
|
|
45
|
+
throw new Error(`payload-redirect: disabled redirect config for "${slug}" cannot define a path`);
|
|
46
|
+
}
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (options.enabled !== undefined && options.enabled !== true) {
|
|
50
|
+
throw new Error(`payload-redirect: redirect config for "${slug}" enabled must be a boolean`);
|
|
51
|
+
}
|
|
52
|
+
if (modes.length !== 1) {
|
|
53
|
+
throw new Error(`payload-redirect: collection "${slug}" must configure exactly one of path, paths, or getPath`);
|
|
54
|
+
}
|
|
55
|
+
if (!collection.versions ||
|
|
56
|
+
typeof collection.versions !== 'object' ||
|
|
57
|
+
!collection.versions.drafts) {
|
|
58
|
+
throw new Error(`payload-redirect: automatic redirects for "${slug}" require versions.drafts`);
|
|
59
|
+
}
|
|
60
|
+
if (Object.hasOwn(options, 'path')) {
|
|
61
|
+
if (typeof options.path !== 'string' || !isValidPathTemplate(options.path)) {
|
|
62
|
+
throw new Error(`payload-redirect: collections.${slug}.path must be a valid site-relative template`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
else if (Object.hasOwn(options, 'paths')) {
|
|
66
|
+
if (locales.length === 0) {
|
|
67
|
+
throw new Error(`payload-redirect: collections.${slug}.paths requires Payload localization`);
|
|
68
|
+
}
|
|
69
|
+
const paths = assertLocaleMap(options.paths, locales, `collections.${slug}.paths`);
|
|
70
|
+
for (const [locale, path] of Object.entries(paths)) {
|
|
71
|
+
if (!isValidPathTemplate(path)) {
|
|
72
|
+
throw new Error(`payload-redirect: collections.${slug}.paths.${locale} must be a valid site-relative template`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
else if (typeof options.getPath !== 'function') {
|
|
77
|
+
throw new Error(`payload-redirect: collections.${slug}.getPath must be a function`);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const selectedCollectionOptions = (collection, options) => {
|
|
81
|
+
const central = asRecord(options.collections);
|
|
82
|
+
if (central && Object.hasOwn(central, collection.slug)) {
|
|
83
|
+
return central[collection.slug];
|
|
84
|
+
}
|
|
85
|
+
return asRecord(collection.custom)?.redirect;
|
|
86
|
+
};
|
|
35
87
|
const validateOptions = (config, options) => {
|
|
36
88
|
const locales = localeCodes(config);
|
|
37
|
-
if (options.
|
|
38
|
-
const prefixes = assertLocaleMap(options.
|
|
89
|
+
if (options.localePrefixes !== undefined) {
|
|
90
|
+
const prefixes = assertLocaleMap(options.localePrefixes, locales, 'localePrefixes');
|
|
39
91
|
for (const [locale, prefix] of Object.entries(prefixes)) {
|
|
40
|
-
if (prefix
|
|
41
|
-
(
|
|
42
|
-
prefix.startsWith('//') ||
|
|
43
|
-
prefix.includes('?') ||
|
|
44
|
-
prefix.includes('#') ||
|
|
45
|
-
prefix.includes('\\') ||
|
|
46
|
-
[...prefix].some((character) => {
|
|
47
|
-
const code = character.charCodeAt(0);
|
|
48
|
-
return code < 32 || code === 127;
|
|
49
|
-
}))) {
|
|
50
|
-
throw new Error(`payload-redirect: localePrefix.${locale} must be a site-relative path`);
|
|
92
|
+
if (!isValidLocalePrefix(prefix)) {
|
|
93
|
+
throw new Error(`payload-redirect: localePrefixes.${locale} must be a site-relative path prefix`);
|
|
51
94
|
}
|
|
52
95
|
}
|
|
53
96
|
}
|
|
54
|
-
for (const
|
|
55
|
-
if (!collectionOptions)
|
|
56
|
-
continue;
|
|
97
|
+
for (const slug of Object.keys(asRecord(options.collections) ?? {})) {
|
|
57
98
|
if (!config.collections?.some((collection) => collection.slug === slug)) {
|
|
58
99
|
throw new Error(`payload-redirect: configured collection "${slug}" is not registered`);
|
|
59
100
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (collectionOptions.enabled === false)
|
|
101
|
+
}
|
|
102
|
+
for (const collection of config.collections ?? []) {
|
|
103
|
+
const selected = selectedCollectionOptions(collection, options);
|
|
104
|
+
if (selected === undefined)
|
|
65
105
|
continue;
|
|
66
|
-
|
|
67
|
-
if (typeof collectionOptions.path !== 'string' || !collectionOptions.path.startsWith('/')) {
|
|
68
|
-
throw new Error(`payload-redirect: collection "${slug}" path must start with "/"`);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
if ('paths' in collectionOptions) {
|
|
72
|
-
if (locales.length === 0) {
|
|
73
|
-
throw new Error(`payload-redirect: collection "${slug}" paths requires Payload localization`);
|
|
74
|
-
}
|
|
75
|
-
const paths = assertLocaleMap(collectionOptions.paths, locales, `collections.${slug}.paths`);
|
|
76
|
-
for (const [locale, path] of Object.entries(paths)) {
|
|
77
|
-
if (!path.startsWith('/')) {
|
|
78
|
-
throw new Error(`payload-redirect: collections.${slug}.paths.${locale} must start with "/"`);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
if ('getPath' in collectionOptions && typeof collectionOptions.getPath !== 'function') {
|
|
83
|
-
throw new Error(`payload-redirect: collection "${slug}" getPath must be a function`);
|
|
84
|
-
}
|
|
106
|
+
validatePathOptions(selected, collection.slug, locales, collection);
|
|
85
107
|
}
|
|
86
108
|
};
|
|
87
|
-
const wireCollectionRedirect = (collection, options) => {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const redirect = asRecord(custom?.redirect);
|
|
92
|
-
const central = options.collections?.[collection.slug];
|
|
93
|
-
const redirectOptions = readRedirectCustom(custom);
|
|
94
|
-
const identifier = central?.identifier ?? redirectOptions?.identifier;
|
|
95
|
-
if (typeof identifier !== 'string' || !identifier.trim())
|
|
96
|
-
return collection;
|
|
97
|
-
if (central?.enabled === false || redirect?.enabled === false)
|
|
109
|
+
const wireCollectionRedirect = (collection, options, collectionSlug) => {
|
|
110
|
+
const selected = selectedCollectionOptions(collection, options);
|
|
111
|
+
const record = asRecord(selected);
|
|
112
|
+
if (!record || record.enabled === false)
|
|
98
113
|
return collection;
|
|
99
|
-
const publishedLink = {
|
|
100
|
-
...(central?.path !== undefined ? { path: central.path } : {}),
|
|
101
|
-
...(central?.paths !== undefined ? { paths: central.paths } : {}),
|
|
102
|
-
...(central?.getPath !== undefined ? { getPath: central.getPath } : {}),
|
|
103
|
-
...asRecord(redirect?.publishedLink),
|
|
104
|
-
};
|
|
105
|
-
const redirectConfig = {
|
|
106
|
-
...redirect,
|
|
107
|
-
identifier: identifier.trim(),
|
|
108
|
-
publishedLink: Object.keys(publishedLink).length > 0 ? publishedLink : redirect?.publishedLink,
|
|
109
|
-
};
|
|
110
114
|
const afterChange = collection.hooks?.afterChange;
|
|
111
115
|
const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];
|
|
112
|
-
const
|
|
116
|
+
const redirectOptions = selected;
|
|
113
117
|
return {
|
|
114
118
|
...collection,
|
|
115
|
-
custom: { ...custom, redirect: redirectConfig },
|
|
116
119
|
hooks: {
|
|
117
120
|
...collection.hooks,
|
|
118
|
-
afterChange: [
|
|
121
|
+
afterChange: [
|
|
122
|
+
...hooks,
|
|
123
|
+
createRedirect({
|
|
124
|
+
collectionSlug,
|
|
125
|
+
pathOptions: redirectOptions,
|
|
126
|
+
localePrefixes: options.localePrefixes,
|
|
127
|
+
}),
|
|
128
|
+
],
|
|
119
129
|
},
|
|
120
130
|
};
|
|
121
131
|
};
|
|
@@ -127,23 +137,15 @@ const definedRedirectsPlugin = definePlugin({
|
|
|
127
137
|
if (registeredCount > 1) {
|
|
128
138
|
throw new Error('payload-redirect: register redirects() only once in config.plugins');
|
|
129
139
|
}
|
|
130
|
-
if (Object.hasOwn(asRecord(config.custom) ?? {}, 'payloadRedirect')) {
|
|
131
|
-
throw new Error('payload-redirect: config.custom.payloadRedirect is reserved');
|
|
132
|
-
}
|
|
133
140
|
const redirectsCollection = createRedirectsCollection(options.overrides);
|
|
134
141
|
const collectionSlug = redirectsCollection.slug || DEFAULT_COLLECTION_SLUG;
|
|
135
|
-
|
|
136
|
-
if (existing) {
|
|
142
|
+
if (config.collections?.some(({ slug }) => slug === collectionSlug)) {
|
|
137
143
|
throw new Error(`payload-redirect: collection slug "${collectionSlug}" is already registered; configure it with redirects({ overrides: { slug } }) instead of defining a host collection`);
|
|
138
144
|
}
|
|
139
145
|
return {
|
|
140
146
|
...config,
|
|
141
|
-
custom: registerRedirectRuntime(config, {
|
|
142
|
-
collectionSlug,
|
|
143
|
-
localePrefix: options.localePrefix,
|
|
144
|
-
}),
|
|
145
147
|
collections: [
|
|
146
|
-
...(config.collections ?? []).map((collection) => wireCollectionRedirect(collection, options)),
|
|
148
|
+
...(config.collections ?? []).map((collection) => wireCollectionRedirect(collection, options, collectionSlug)),
|
|
147
149
|
redirectsCollection,
|
|
148
150
|
],
|
|
149
151
|
};
|
package/dist/plugin/types.d.ts
CHANGED
|
@@ -1,39 +1,13 @@
|
|
|
1
|
-
import type { CollectionSlug
|
|
1
|
+
import type { CollectionSlug } from 'payload';
|
|
2
|
+
import type { RedirectPathOptions } from '../core/redirects/auto/types.js';
|
|
2
3
|
import type { RedirectCollectionOverrides } from '../core/redirects/collection/types.js';
|
|
3
|
-
type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
};
|
|
7
|
-
type PathModes<TSlug extends CollectionSlug> = {
|
|
8
|
-
path: string;
|
|
9
|
-
paths?: never;
|
|
10
|
-
getPath?: never;
|
|
11
|
-
} | {
|
|
12
|
-
path?: never;
|
|
13
|
-
paths: RedirectLocaleMap;
|
|
14
|
-
getPath?: never;
|
|
15
|
-
} | {
|
|
16
|
-
path?: never;
|
|
17
|
-
paths?: never;
|
|
18
|
-
getPath: (args: {
|
|
19
|
-
doc: DataFromCollectionSlug<TSlug>;
|
|
20
|
-
locale: TypedLocale;
|
|
21
|
-
}) => string | null;
|
|
22
|
-
};
|
|
23
|
-
type DisabledPathModes<TSlug extends CollectionSlug> = Partial<PathModes<TSlug>>;
|
|
24
|
-
export type RedirectCollectionOptions<TSlug extends CollectionSlug> = ({
|
|
25
|
-
identifier: string;
|
|
26
|
-
enabled?: true;
|
|
27
|
-
} & PathModes<TSlug>) | ({
|
|
28
|
-
identifier?: string;
|
|
29
|
-
enabled: false;
|
|
30
|
-
} & DisabledPathModes<TSlug>);
|
|
4
|
+
type LocaleCode = Extract<import('payload').TypedLocale, string>;
|
|
5
|
+
type LocaleMap = string extends LocaleCode ? Record<string, string> : Record<LocaleCode, string>;
|
|
6
|
+
export type RedirectCollectionOptions<TSlug extends CollectionSlug = CollectionSlug> = RedirectPathOptions<TSlug>;
|
|
31
7
|
export type RedirectsOptions = {
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
localePrefix?: RedirectLocaleMap;
|
|
36
|
-
/** Centralized per-collection automatic redirect configuration. */
|
|
8
|
+
/** Payload locale codes map to explicit site-relative prefixes; omission means no prefix. */
|
|
9
|
+
localePrefixes?: LocaleMap;
|
|
10
|
+
/** Each entry opts that collection into automatic redirects. Central entries replace local config. */
|
|
37
11
|
collections?: {
|
|
38
12
|
[TSlug in CollectionSlug]?: RedirectCollectionOptions<TSlug>;
|
|
39
13
|
};
|
|
@@ -10,7 +10,11 @@ This document records observable configuration, validation, and publication beha
|
|
|
10
10
|
| The redirects collection slug already exists | Plugin config throws and names the colliding slug. |
|
|
11
11
|
| `redirects()` is registered more than once | Plugin config throws; register it once. |
|
|
12
12
|
| `overrides.fields` changes a required field type | Plugin config throws before Payload builds. Missing required fields are restored from defaults. |
|
|
13
|
-
|
|
|
13
|
+
| A collection has no redirect configuration | The collection is left unchanged; no publication hook is added. |
|
|
14
|
+
| Central collection options name an unregistered collection | Plugin configuration throws and names the collection. |
|
|
15
|
+
| A configured collection has no `versions.drafts` | Plugin configuration throws and names the collection. |
|
|
16
|
+
| Path config has unsupported options or multiple strategies | Plugin configuration throws before Payload builds. |
|
|
17
|
+
| Locale map omits or adds a Payload locale | Plugin configuration throws and names invalid locales. |
|
|
14
18
|
| Automatic generation is disabled | No automatic hook is added; manual rules remain available. |
|
|
15
19
|
|
|
16
20
|
## Redirect collection writes
|
|
@@ -22,7 +26,7 @@ duplicates and loops.
|
|
|
22
26
|
|---|---|
|
|
23
27
|
| Duplicate normalized `from` | Payload validation error on `from`. |
|
|
24
28
|
| Enabled redirect chain loops or exceeds 1,000 hops | Payload validation error on `to`. |
|
|
25
|
-
| `
|
|
29
|
+
| `statusCode` is not `301` or `302` | Payload field validation error. |
|
|
26
30
|
| `to` is missing or invalid | Payload field validation error. |
|
|
27
31
|
| `origin` is invalid | Payload field validation error. |
|
|
28
32
|
| A manual rule already owns an automatic source path | Automatic write is skipped; the manual rule remains unchanged. |
|
|
@@ -33,20 +37,20 @@ same concurrent-write guarantee.
|
|
|
33
37
|
|
|
34
38
|
## Published paths
|
|
35
39
|
|
|
36
|
-
Automatic rules use `
|
|
37
|
-
|
|
40
|
+
Automatic rules use one of `path`, `paths`, or `getPath`, configured centrally or in
|
|
41
|
+
`custom.redirect`. Central configuration replaces local configuration.
|
|
38
42
|
|
|
39
43
|
| Condition | Result |
|
|
40
44
|
|---|---|
|
|
41
|
-
| No matching path configuration |
|
|
42
|
-
| Template value is missing or unsafe | That publication transition is skipped. |
|
|
43
|
-
| `getPath` returns `null` | That
|
|
44
|
-
| `getPath` returns a non-string value
|
|
45
|
-
| Locale is absent |
|
|
46
|
-
| Locale is missing from a configured prefix map |
|
|
45
|
+
| No matching path configuration | Automatic generation is not registered for that collection. |
|
|
46
|
+
| Template value is missing or unsafe | That locale's publication transition is skipped. |
|
|
47
|
+
| `getPath` returns `null` or a non-site-relative path | That locale's transition is skipped. |
|
|
48
|
+
| `getPath` returns a non-string value | That locale's transition is skipped. |
|
|
49
|
+
| Locale is absent | A shared `path` works without a prefix map; localized `paths` cannot resolve. |
|
|
50
|
+
| Locale is missing from a configured prefix map | Plugin configuration fails before Payload builds. |
|
|
47
51
|
| Generated source and destination normalize to the same path | No redirect is written. |
|
|
48
52
|
|
|
49
|
-
Draft saves, first publications, unpublishes, deletions, and unchanged
|
|
53
|
+
Draft saves, first publications, unpublishes, deletions, and unchanged complete paths do not create
|
|
50
54
|
automatic rules.
|
|
51
55
|
|
|
52
56
|
## Adapter boundary
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@klnap/payload-redirect",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Redirect management for Payload CMS.",
|
|
5
5
|
"homepage": "https://github.com/klnap/payload-redirect#readme",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/klnap/payload-redirect/issues"
|
|
@@ -10,33 +10,35 @@
|
|
|
10
10
|
"payload",
|
|
11
11
|
"payloadcms",
|
|
12
12
|
"payload-plugin",
|
|
13
|
+
"cms",
|
|
14
|
+
"redirect",
|
|
13
15
|
"redirects",
|
|
14
|
-
"
|
|
16
|
+
"redirect-management"
|
|
15
17
|
],
|
|
16
18
|
"license": "MIT",
|
|
17
19
|
"author": "klnap",
|
|
18
20
|
"repository": {
|
|
19
21
|
"type": "git",
|
|
20
|
-
"url": "https://github.com/klnap/payload-redirect"
|
|
22
|
+
"url": "git+https://github.com/klnap/payload-redirect.git"
|
|
21
23
|
},
|
|
22
24
|
"type": "module",
|
|
23
25
|
"sideEffects": false,
|
|
24
26
|
"exports": {
|
|
25
27
|
".": {
|
|
26
28
|
"types": "./dist/exports/index.d.ts",
|
|
27
|
-
"import": "./dist/exports/index.js"
|
|
28
|
-
"default": "./dist/exports/index.js"
|
|
29
|
+
"import": "./dist/exports/index.js"
|
|
29
30
|
}
|
|
30
31
|
},
|
|
31
32
|
"files": [
|
|
32
33
|
"dist",
|
|
33
34
|
"README.md",
|
|
34
35
|
"LICENSE",
|
|
35
|
-
"docs"
|
|
36
|
+
"docs/FAILURE_SEMANTICS.md",
|
|
37
|
+
"CHANGELOG.md"
|
|
36
38
|
],
|
|
37
39
|
"scripts": {
|
|
38
40
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
39
|
-
"typecheck:consumer": "bun run build && tsc -p tsconfig.type-fixture.json",
|
|
41
|
+
"typecheck:consumer": "bun run build && tsc -p tsconfig.type-fixture.json && tsc -p tsconfig.type-fixture.no-generated.json",
|
|
40
42
|
"test": "bun test src tests/unit",
|
|
41
43
|
"test:int": "bun scripts/with-ephemeral-postgres.mjs scripts/ephemeral-postgres.config.mjs -- bun test tests/integration tests/security --max-concurrency 1 --timeout=15000",
|
|
42
44
|
"check:boundaries": "depcruise --config dependency-cruiser.config.mjs --output-type err-long src",
|
|
@@ -81,6 +83,5 @@
|
|
|
81
83
|
"publishConfig": {
|
|
82
84
|
"access": "public"
|
|
83
85
|
},
|
|
84
|
-
"main": "./dist/exports/index.js",
|
|
85
86
|
"types": "./dist/exports/index.d.ts"
|
|
86
87
|
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { identifierValueToString } from './identifier-transitions.js';
|
|
2
|
-
import { readIdentifierAtPath } from '../../identifier-field-path.js';
|
|
3
|
-
import { normalizePathOrUrl } from '../../normalize-path.js';
|
|
4
|
-
export const normalizeIdentifierValue = (value) => {
|
|
5
|
-
if (value.startsWith('/') || /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(value)) {
|
|
6
|
-
return normalizePathOrUrl(value);
|
|
7
|
-
}
|
|
8
|
-
return value;
|
|
9
|
-
};
|
|
10
|
-
export const extractIdentifierFromVersionSnapshot = (doc, identifier, locale, localized, contextLocale) => {
|
|
11
|
-
if (localized && !identifier.includes('.')) {
|
|
12
|
-
const field = doc[identifier];
|
|
13
|
-
if (typeof field === 'string') {
|
|
14
|
-
if (contextLocale !== undefined && contextLocale !== locale) {
|
|
15
|
-
return undefined;
|
|
16
|
-
}
|
|
17
|
-
const raw = identifierValueToString(field);
|
|
18
|
-
if (!raw)
|
|
19
|
-
return undefined;
|
|
20
|
-
return normalizeIdentifierValue(raw);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
const raw = readIdentifierAtPath(doc, identifier, locale, localized);
|
|
24
|
-
if (!raw)
|
|
25
|
-
return undefined;
|
|
26
|
-
return normalizeIdentifierValue(raw);
|
|
27
|
-
};
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
export type IdentifierTransition = {
|
|
2
|
-
locale?: string;
|
|
3
|
-
previous: string;
|
|
4
|
-
current: string;
|
|
5
|
-
};
|
|
6
|
-
export declare const identifierValueToString: (value: unknown) => string | undefined;
|
|
7
|
-
/**
|
|
8
|
-
* Compare previous/current per locale without cross-locale fallback.
|
|
9
|
-
*/
|
|
10
|
-
export declare const collectLocalizedIdentifierTransitions: (args: {
|
|
11
|
-
locales: string[];
|
|
12
|
-
previousByLocale: Record<string, string | undefined>;
|
|
13
|
-
currentByLocale: Record<string, string | undefined>;
|
|
14
|
-
}) => IdentifierTransition[];
|
|
15
|
-
export declare const collectScalarIdentifierTransition: (args: {
|
|
16
|
-
previous?: string;
|
|
17
|
-
current?: string;
|
|
18
|
-
}) => IdentifierTransition | undefined;
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
export const identifierValueToString = (value) => {
|
|
2
|
-
if (value == null)
|
|
3
|
-
return undefined;
|
|
4
|
-
if (typeof value === 'string') {
|
|
5
|
-
const t = value.trim();
|
|
6
|
-
return t.length > 0 ? t : undefined;
|
|
7
|
-
}
|
|
8
|
-
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
9
|
-
return String(value);
|
|
10
|
-
}
|
|
11
|
-
return undefined;
|
|
12
|
-
};
|
|
13
|
-
/**
|
|
14
|
-
* Compare previous/current per locale without cross-locale fallback.
|
|
15
|
-
*/
|
|
16
|
-
export const collectLocalizedIdentifierTransitions = (args) => {
|
|
17
|
-
const out = [];
|
|
18
|
-
for (const locale of args.locales) {
|
|
19
|
-
const previous = args.previousByLocale[locale];
|
|
20
|
-
const current = args.currentByLocale[locale];
|
|
21
|
-
if (!previous || !current)
|
|
22
|
-
continue;
|
|
23
|
-
if (previous === current)
|
|
24
|
-
continue;
|
|
25
|
-
out.push({ locale, previous, current });
|
|
26
|
-
}
|
|
27
|
-
return out;
|
|
28
|
-
};
|
|
29
|
-
export const collectScalarIdentifierTransition = (args) => {
|
|
30
|
-
const { previous, current } = args;
|
|
31
|
-
if (!previous || !current)
|
|
32
|
-
return undefined;
|
|
33
|
-
if (previous === current)
|
|
34
|
-
return undefined;
|
|
35
|
-
return { previous, current };
|
|
36
|
-
};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { CollectionConfig, PayloadRequest } from 'payload';
|
|
2
|
-
import type { PublicationTransition } from '../types.js';
|
|
3
|
-
export declare const transitionForLocale: ({ req, collection, docId, locale, identifier, localizedField, hookDoc, publishIntent, }: {
|
|
4
|
-
req: PayloadRequest;
|
|
5
|
-
collection: CollectionConfig;
|
|
6
|
-
docId: string | number;
|
|
7
|
-
locale: string;
|
|
8
|
-
identifier: string;
|
|
9
|
-
localizedField: boolean;
|
|
10
|
-
hookDoc: Record<string, unknown>;
|
|
11
|
-
publishIntent: boolean;
|
|
12
|
-
}) => Promise<PublicationTransition>;
|