@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
@@ -1,107 +1,39 @@
1
- import { localeCode } from './preview-path.js';
2
1
  const DYNAMIC_SEGMENT = /\[([^\]]+)\]/g;
3
- const UNSUPPORTED_TEMPLATE = /\[\[\.\.\.|\[\.\.\.[^\]]*\]|\/\[\](?:\/|$)|\[\[|\]\]|\/\[\.\.\./;
4
- const VALID_PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
- const FORBIDDEN_FIELD_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype']);
6
- export function templateHasUnsupportedDynamicSyntax(template) {
7
- return UNSUPPORTED_TEMPLATE.test(template);
8
- }
9
- function isSupportedParamName(name) {
10
- if (!VALID_PARAM_NAME.test(name))
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
- return names;
29
- }
30
- export function readValueAtPath(data, fieldPath) {
31
- if (fieldPath.length === 0)
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
- let current = data;
38
- for (const part of parts) {
39
- if (current === null || current === undefined || typeof current !== 'object') {
40
- return undefined;
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 (Array.isArray(current))
43
- return undefined;
44
- if (!Object.hasOwn(current, part))
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
- return { field: mapping, localized: false };
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
+ };
@@ -1,10 +1,4 @@
1
- export { type CreateRedirectOptions, createRedirect, } from '../core/redirects/auto/create-redirect.js';
2
- export type { RedirectsCollectionAccess } from '../core/redirects/collection/access.js';
3
- export { REDIRECT_CONTEXT_KEYS } from '../core/redirects/context-keys.js';
4
- export { RedirectAmbiguousRuleError, RedirectConfigError, RedirectValidationError, } from '../core/redirects/model/errors.js';
5
1
  export type { RedirectOrigin } from '../core/redirects/model/origin.js';
6
2
  export type { RedirectStatusCode } from '../core/redirects/model/status-code.js';
7
- export { type ResolveRedirectArgs, resolveRedirect, } from '../core/redirects/resolution/resolve.js';
8
- export type { ResolvedRedirect } from '../core/redirects/resolution/resolved.js';
9
3
  export { redirects } from '../plugin/payload-plugin.js';
10
- export type { RedirectsPluginConfig } from '../plugin/resolve-config.js';
4
+ export type { RedirectCollectionOptions, RedirectsOptions } from '../plugin/types.js';
@@ -1,5 +1 @@
1
- export { createRedirect, } from '../core/redirects/auto/create-redirect.js';
2
- export { REDIRECT_CONTEXT_KEYS } from '../core/redirects/context-keys.js';
3
- export { RedirectAmbiguousRuleError, RedirectConfigError, RedirectValidationError, } from '../core/redirects/model/errors.js';
4
- export { resolveRedirect, } from '../core/redirects/resolution/resolve.js';
5
1
  export { redirects } from '../plugin/payload-plugin.js';
@@ -1,3 +1,3 @@
1
- import type { Plugin } from 'payload';
2
- import { type RedirectsPluginConfig } from './resolve-config.js';
3
- export declare const redirects: (pluginConfig: RedirectsPluginConfig) => Plugin;
1
+ import { type Plugin } from 'payload';
2
+ import type { RedirectsOptions } from './types.js';
3
+ export declare const redirects: (options?: RedirectsOptions) => Plugin;
@@ -1,55 +1,154 @@
1
+ import { definePlugin } from 'payload';
1
2
  import { createRedirect } from '../core/redirects/auto/create-redirect.js';
2
3
  import { createRedirectsCollection } from '../core/redirects/collection/collection.js';
3
- import { PAYLOAD_REDIRECT_CUSTOM_KEY, registerRedirectRuntime, } from '../core/redirects/runtime.js';
4
- import { readRedirectCustom } from './redirect-custom.js';
5
- import { resolveRedirectsPluginConfig } from './resolve-config.js';
6
- const replaceOrAppendCollection = (collections, collection) => {
7
- const list = collections ?? [];
8
- const index = list.findIndex((c) => c.slug === collection.slug);
9
- if (index === -1)
10
- return [...list, collection];
11
- const next = [...list];
12
- next[index] = collection;
13
- return next;
4
+ import { isValidLocalePrefix } from '../core/url/published-path.js';
5
+ import { isValidPathTemplate } from '../core/url/route-params.js';
6
+ const PLUGIN_SLUG = '@klnap/payload-redirect';
7
+ const DEFAULT_COLLECTION_SLUG = 'redirects';
8
+ const PATH_OPTIONS = new Set(['enabled', 'path', 'paths', 'getPath']);
9
+ const asRecord = (value) => value && typeof value === 'object' && !Array.isArray(value)
10
+ ? value
11
+ : undefined;
12
+ const localeCodes = (config) => {
13
+ const locales = config.localization === false ? undefined : config.localization?.locales;
14
+ return Array.isArray(locales)
15
+ ? locales.map((locale) => typeof locale === 'string' ? locale : locale.code)
16
+ : [];
14
17
  };
15
- const appendHook = (existing, hook) => {
16
- if (!existing)
17
- return [hook];
18
- return Array.isArray(existing) ? [...existing, hook] : [existing, hook];
18
+ const assertLocaleMap = (value, locales, name) => {
19
+ const map = asRecord(value);
20
+ if (!map)
21
+ throw new Error(`payload-redirect: ${name} must be a locale map`);
22
+ const missing = locales.filter((locale) => !Object.hasOwn(map, locale));
23
+ const unknown = Object.keys(map).filter((locale) => !locales.includes(locale));
24
+ if (missing.length || unknown.length) {
25
+ throw new Error(`payload-redirect: ${name} has invalid locales (missing: ${missing.join(', ') || 'none'}; unknown: ${unknown.join(', ') || 'none'})`);
26
+ }
27
+ for (const [locale, path] of Object.entries(map)) {
28
+ if (typeof path !== 'string') {
29
+ throw new Error(`payload-redirect: ${name}.${locale} must be a string`);
30
+ }
31
+ }
32
+ return map;
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
+ };
87
+ const validateOptions = (config, options) => {
88
+ const locales = localeCodes(config);
89
+ if (options.localePrefixes !== undefined) {
90
+ const prefixes = assertLocaleMap(options.localePrefixes, locales, 'localePrefixes');
91
+ for (const [locale, prefix] of Object.entries(prefixes)) {
92
+ if (!isValidLocalePrefix(prefix)) {
93
+ throw new Error(`payload-redirect: localePrefixes.${locale} must be a site-relative path prefix`);
94
+ }
95
+ }
96
+ }
97
+ for (const slug of Object.keys(asRecord(options.collections) ?? {})) {
98
+ if (!config.collections?.some((collection) => collection.slug === slug)) {
99
+ throw new Error(`payload-redirect: configured collection "${slug}" is not registered`);
100
+ }
101
+ }
102
+ for (const collection of config.collections ?? []) {
103
+ const selected = selectedCollectionOptions(collection, options);
104
+ if (selected === undefined)
105
+ continue;
106
+ validatePathOptions(selected, collection.slug, locales, collection);
107
+ }
19
108
  };
20
- const wireCollectionRedirectHook = (collection) => {
21
- const meta = readRedirectCustom(collection.custom);
22
- if (!meta)
109
+ const wireCollectionRedirect = (collection, options, collectionSlug) => {
110
+ const selected = selectedCollectionOptions(collection, options);
111
+ const record = asRecord(selected);
112
+ if (!record || record.enabled === false)
23
113
  return collection;
114
+ const afterChange = collection.hooks?.afterChange;
115
+ const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];
116
+ const redirectOptions = selected;
24
117
  return {
25
118
  ...collection,
26
119
  hooks: {
27
120
  ...collection.hooks,
28
- afterChange: appendHook(collection.hooks?.afterChange, createRedirect({ identifier: meta.identifier })),
121
+ afterChange: [
122
+ ...hooks,
123
+ createRedirect({
124
+ collectionSlug,
125
+ pathOptions: redirectOptions,
126
+ localePrefixes: options.localePrefixes,
127
+ }),
128
+ ],
29
129
  },
30
130
  };
31
131
  };
32
- export const redirects = (pluginConfig) => (incoming) => {
33
- if (incoming.custom && PAYLOAD_REDIRECT_CUSTOM_KEY in incoming.custom) {
34
- throw new Error(`payload-redirect: config.custom.${PAYLOAD_REDIRECT_CUSTOM_KEY} is reserved; duplicate plugin installation is not supported`);
35
- }
36
- const resolved = resolveRedirectsPluginConfig(pluginConfig);
37
- const collectionSlug = resolved.collection.slug;
38
- const collections = (incoming.collections ?? []).map(wireCollectionRedirectHook);
39
- const existingCollection = collections.find((collection) => collection.slug === collectionSlug);
40
- const redirectCollection = existingCollection
41
- ? createRedirectsCollection({
42
- base: existingCollection,
43
- trash: resolved.collection.trash,
44
- access: resolved.collection.access,
45
- })
46
- : resolved.collection;
47
- return {
48
- ...incoming,
49
- collections: replaceOrAppendCollection(collections, redirectCollection),
50
- custom: registerRedirectRuntime(incoming, {
51
- collectionSlug,
52
- localePrefix: resolved.localePrefix,
53
- }),
54
- };
55
- };
132
+ const definedRedirectsPlugin = definePlugin({
133
+ slug: PLUGIN_SLUG,
134
+ plugin: ({ config, ...options }) => {
135
+ validateOptions(config, options);
136
+ const registeredCount = config.plugins?.filter((plugin) => plugin.slug === PLUGIN_SLUG).length ?? 0;
137
+ if (registeredCount > 1) {
138
+ throw new Error('payload-redirect: register redirects() only once in config.plugins');
139
+ }
140
+ const redirectsCollection = createRedirectsCollection(options.overrides);
141
+ const collectionSlug = redirectsCollection.slug || DEFAULT_COLLECTION_SLUG;
142
+ if (config.collections?.some(({ slug }) => slug === collectionSlug)) {
143
+ throw new Error(`payload-redirect: collection slug "${collectionSlug}" is already registered; configure it with redirects({ overrides: { slug } }) instead of defining a host collection`);
144
+ }
145
+ return {
146
+ ...config,
147
+ collections: [
148
+ ...(config.collections ?? []).map((collection) => wireCollectionRedirect(collection, options, collectionSlug)),
149
+ redirectsCollection,
150
+ ],
151
+ };
152
+ },
153
+ });
154
+ export const redirects = (options = {}) => definedRedirectsPlugin(options);
@@ -0,0 +1,17 @@
1
+ import type { CollectionSlug } from 'payload';
2
+ import type { RedirectPathOptions } from '../core/redirects/auto/types.js';
3
+ import type { RedirectCollectionOverrides } from '../core/redirects/collection/types.js';
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>;
7
+ export type RedirectsOptions = {
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. */
11
+ collections?: {
12
+ [TSlug in CollectionSlug]?: RedirectCollectionOptions<TSlug>;
13
+ };
14
+ /** Native collection overrides for the plugin-owned redirects collection. */
15
+ overrides?: RedirectCollectionOverrides;
16
+ };
17
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,104 +1,60 @@
1
1
  # Failure semantics — `@klnap/payload-redirect`
2
2
 
3
- This document describes **observable** failures: thrown errors, validation messages, and resolver behavior. It reflects the current implementation and tests, not future guarantees.
3
+ This document records observable configuration, validation, and publication behavior.
4
4
 
5
- ## Thrown errors (public classes)
6
-
7
- ### `RedirectConfigError`
8
-
9
- **When:** Plugin configuration or host redirects collection is invalid at startup (via `resolveRedirectsPluginConfig` / `assertValidCollectionConfig`).
10
-
11
- **Examples:**
12
-
13
- - `redirects plugin requires collection — register a redirects CollectionConfig...`
14
- - `redirects collection field "from" must have unique: true`
15
- - `redirects collection field "StatusCode" must be type select, got "..."`
16
-
17
- **Recovery:** Fix `payload.config` collection definition or plugin options.
18
-
19
- ### `RedirectValidationError`
20
-
21
- **When:** Path or status/destination rules are violated (normalization, field validators).
22
-
23
- **Examples:**
24
-
25
- - `from/to must be a non-empty site-relative path`
26
- - `Invalid absolute URL: ...`
27
- - `StatusCode must be one of 301, 302` (via `assertRedirectStatusCode`)
28
- - `StatusCode 301 requires a non-empty "to" field`
29
-
30
- **Recovery:** Correct admin input or API payload.
31
-
32
- ### `RedirectAmbiguousRuleError`
33
-
34
- **When:** `resolveRedirect` finds **more than one** document for the same normalized `from` with the resolve select (enabled rules should be unique by DB constraint).
35
-
36
- **Message shape:** `Multiple redirect rules exist for "<path>" (unique constraint should prevent this)`
37
-
38
- **Recovery:** Data repair—dedupe `from` in the redirects collection.
39
-
40
- ### Runtime: plugin not registered
41
-
42
- **When:** `getRedirectRuntime` is called without `redirects()` having registered runtime on `config.custom`.
43
-
44
- **Message:** `payload-redirect: plugin runtime missing — add redirects() to payload config`
45
-
46
- ## Collection validation (admin / API)
47
-
48
- | Check | User-visible result |
49
- |-------|---------------------|
50
- | Duplicate normalized `from` | Payload `ValidationError`: *A redirect rule already exists for this source path* |
51
- | Enabled destination chain loops or exceeds 1,000 hops | Payload `ValidationError` on `to` |
52
- | Invalid `from` / `to` path | Field validation message from `RedirectValidationError` text |
53
- | `StatusCode` not 301 or 302 | *StatusCode must be 301 or 302* |
54
- | Invalid `origin` | *origin must be manual or auto* |
55
- | `301`/`302` without `to` | Destination validation error on `to` |
56
-
57
- `from` is normalized in the duplicate guard before comparison.
58
-
59
- ## `resolveRedirect` behavior
5
+ ## Plugin configuration
60
6
 
61
7
  | Condition | Result |
62
- |-----------|--------|
63
- | No document for normalized `from` | `null` |
64
- | Document exists, `enabled: false` | `null` |
65
- | Document exists, enabled, valid 301/302 with `to` | `{ statusCode, to }` |
66
- | Document exists but status not 301/302 (invalid stored record) | `null` (assertion fails inside mapping) |
67
- | Multiple documents same `from` | `RedirectAmbiguousRuleError` |
68
-
69
- `overrideAccess: false` on lookup—respects collection read access.
8
+ |---|---|
9
+ | `redirects()` is not registered | Payload config has no redirects collection or automatic publication hooks. |
10
+ | The redirects collection slug already exists | Plugin config throws and names the colliding slug. |
11
+ | `redirects()` is registered more than once | Plugin config throws; register it once. |
12
+ | `overrides.fields` changes a required field type | Plugin config throws before Payload builds. Missing required fields are restored from defaults. |
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. |
18
+ | Automatic generation is disabled | No automatic hook is added; manual rules remain available. |
19
+
20
+ ## Redirect collection writes
21
+
22
+ `from` and `to` must be non-empty site-relative paths. The plugin normalizes them before checking
23
+ duplicates and loops.
70
24
 
71
- ## Auto redirect persistence (`ensureAutoRedirect`)
72
-
73
- | Situation | Outcome |
74
- |-----------|---------|
75
- | No existing rule for `from` | Creates rule (`origin: auto`, `301`, enabled) |
76
- | Existing **Auto** rule, same `from`/`to`/301/enabled | `skipped` |
77
- | Existing **Auto** rule, different `to` | Updates `to` (and normalizes 301/enabled) |
78
- | Existing **Manual** rule on same `from` | `skipped` (no overwrite) |
79
-
80
- Internal writes set `payloadRedirectInternal` and `payloadRedirectSkipAuto` on context.
81
-
82
- ## Publication transition (no redirect)
83
-
84
- Auto hook returns early (no pairs) when implementation detects:
85
-
86
- - No drafts on collection
87
- - Draft save
88
- - `payloadRedirectSkipAuto`
89
- - Unpublished document (per `publish-intent` / status helpers)
90
- - No locale to evaluate (depends on request and localized draft status)
91
- - No identifier change for locale
92
- - Empty/disallowed paths after build/normalize
25
+ | Condition | Result |
26
+ |---|---|
27
+ | Duplicate normalized `from` | Payload validation error on `from`. |
28
+ | Enabled redirect chain loops or exceeds 1,000 hops | Payload validation error on `to`. |
29
+ | `statusCode` is not `301` or `302` | Payload field validation error. |
30
+ | `to` is missing or invalid | Payload field validation error. |
31
+ | `origin` is invalid | Payload field validation error. |
32
+ | A manual rule already owns an automatic source path | Automatic write is skipped; the manual rule remains unchanged. |
93
33
 
94
- Exact branches are covered by `tests/security/*` and `tests/integration/*`.
34
+ Internal writes carry server-side request context and run inside the Payload transaction. PostgreSQL
35
+ uses a transaction-scoped advisory lock to serialize graph checks. Other adapters do not claim the
36
+ same concurrent-write guarantee.
95
37
 
96
- ## Configuration vs runtime
38
+ ## Published paths
97
39
 
98
- | Layer | Failure mode |
99
- |-------|----------------|
100
- | Plugin init | `RedirectConfigError` — process fails to build config |
101
- | Save redirect | Field validation or duplicate `ValidationError` |
102
- | Resolve | `null`, thrown ambiguous error, or Payload access error from `find` |
40
+ Automatic rules use one of `path`, `paths`, or `getPath`, configured centrally or in
41
+ `custom.redirect`. Central configuration replaces local configuration.
103
42
 
104
- This package does **not** define HTTP status codes for “no redirect”; the host returns `null` resolution as “continue normal routing.”
43
+ | Condition | Result |
44
+ |---|---|
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. |
51
+ | Generated source and destination normalize to the same path | No redirect is written. |
52
+
53
+ Draft saves, first publications, unpublishes, deletions, and unchanged complete paths do not create
54
+ automatic rules.
55
+
56
+ ## Adapter boundary
57
+
58
+ PostgreSQL is the supported adapter for atomic graph validation and writes. SQLite, MongoDB, and
59
+ other adapters may provide Payload transactions, but this package does not assume their locking
60
+ semantics match PostgreSQL advisory locks.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@klnap/payload-redirect",
3
- "version": "0.1.0",
4
- "description": "Payload CMS plugin for managed HTTP redirects with validation and resolution helpers",
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,32 +10,35 @@
10
10
  "payload",
11
11
  "payloadcms",
12
12
  "payload-plugin",
13
+ "cms",
14
+ "redirect",
13
15
  "redirects",
14
- "nextjs"
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",
41
+ "typecheck:consumer": "bun run build && tsc -p tsconfig.type-fixture.json && tsc -p tsconfig.type-fixture.no-generated.json",
39
42
  "test": "bun test src tests/unit",
40
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",
41
44
  "check:boundaries": "depcruise --config dependency-cruiser.config.mjs --output-type err-long src",
@@ -45,7 +48,7 @@
45
48
  "check:release": "bun pm pack --dry-run && bun run check:exports",
46
49
  "prepack": "bun run build",
47
50
  "check:exports": "bun scripts/check-exports.mjs",
48
- "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json"
51
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json"
49
52
  },
50
53
  "peerDependencies": {
51
54
  "@payloadcms/db-postgres": ">=3.94.1 <4",
@@ -80,6 +83,5 @@
80
83
  "publishConfig": {
81
84
  "access": "public"
82
85
  },
83
- "main": "./dist/exports/index.js",
84
86
  "types": "./dist/exports/index.d.ts"
85
87
  }
@@ -1,2 +0,0 @@
1
- export declare const normalizeIdentifierValue: (value: string) => string;
2
- export declare const extractIdentifierFromVersionSnapshot: (doc: Record<string, unknown>, identifier: string, locale: string, localized: boolean, contextLocale?: string) => string | undefined;
@@ -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
- };