@klnap/payload-redirect 0.1.0 → 0.2.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 (48) hide show
  1. package/README.md +81 -192
  2. package/dist/core/redirects/auto/create-redirect.js +26 -10
  3. package/dist/core/redirects/auto/persist-auto-rule.js +3 -2
  4. package/dist/core/redirects/auto/publication/transition-for-locale.js +5 -1
  5. package/dist/core/redirects/auto/publication/transitions-to-pairs.d.ts +2 -0
  6. package/dist/core/redirects/auto/publication/transitions-to-pairs.js +7 -1
  7. package/dist/core/redirects/auto/published-link-config.js +5 -1
  8. package/dist/core/redirects/auto/published-path.js +18 -1
  9. package/dist/core/redirects/auto/redirect-custom.d.ts +7 -0
  10. package/dist/core/redirects/auto/redirect-custom.js +19 -0
  11. package/dist/core/redirects/auto/types.d.ts +2 -0
  12. package/dist/core/redirects/collection/access.d.ts +6 -11
  13. package/dist/core/redirects/collection/access.js +7 -24
  14. package/dist/core/redirects/collection/collection.d.ts +2 -10
  15. package/dist/core/redirects/collection/collection.js +19 -22
  16. package/dist/core/redirects/collection/duplicate-guard.d.ts +1 -1
  17. package/dist/core/redirects/collection/duplicate-guard.js +5 -8
  18. package/dist/core/redirects/collection/fields.d.ts +1 -0
  19. package/dist/core/redirects/collection/fields.js +76 -76
  20. package/dist/core/redirects/collection/origin-hook.js +7 -14
  21. package/dist/core/redirects/collection/types.d.ts +7 -0
  22. package/dist/core/redirects/collection/types.js +1 -0
  23. package/dist/core/redirects/model/errors.d.ts +0 -6
  24. package/dist/core/redirects/model/errors.js +0 -6
  25. package/dist/core/redirects/model/status-code.js +4 -7
  26. package/dist/core/redirects/queries.d.ts +4 -9
  27. package/dist/core/redirects/queries.js +5 -9
  28. package/dist/core/url/published-path.d.ts +1 -0
  29. package/dist/core/url/published-path.js +31 -2
  30. package/dist/exports/index.d.ts +1 -7
  31. package/dist/exports/index.js +0 -4
  32. package/dist/plugin/payload-plugin.d.ts +4 -3
  33. package/dist/plugin/payload-plugin.js +140 -43
  34. package/dist/plugin/types.d.ts +43 -0
  35. package/dist/plugin/types.js +1 -0
  36. package/docs/FAILURE_SEMANTICS.md +44 -92
  37. package/docs/adr/0002-database-indexes.md +3 -4
  38. package/package.json +4 -3
  39. package/dist/core/redirects/resolution/resolve.d.ts +0 -7
  40. package/dist/core/redirects/resolution/resolve.js +0 -27
  41. package/dist/core/redirects/resolution/resolved.d.ts +0 -17
  42. package/dist/core/redirects/resolution/resolved.js +0 -18
  43. package/dist/plugin/redirect-custom.d.ts +0 -9
  44. package/dist/plugin/redirect-custom.js +0 -18
  45. package/dist/plugin/resolve-config.d.ts +0 -17
  46. package/dist/plugin/resolve-config.js +0 -20
  47. package/dist/plugin/validate-config.d.ts +0 -3
  48. package/dist/plugin/validate-config.js +0 -40
@@ -1,55 +1,152 @@
1
+ import { definePlugin } from 'payload';
1
2
  import { createRedirect } from '../core/redirects/auto/create-redirect.js';
3
+ import { readRedirectCustom } from '../core/redirects/auto/redirect-custom.js';
2
4
  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;
5
+ import { registerRedirectRuntime } from '../core/redirects/runtime.js';
6
+ const PLUGIN_SLUG = '@klnap/payload-redirect';
7
+ const DEFAULT_COLLECTION_SLUG = 'redirects';
8
+ const asRecord = (value) => value && typeof value === 'object' && !Array.isArray(value)
9
+ ? value
10
+ : undefined;
11
+ const localeCodes = (config) => {
12
+ const locales = config.localization === false ? undefined : config.localization?.locales;
13
+ return Array.isArray(locales)
14
+ ? locales.map((locale) => typeof locale === 'string' ? locale : locale.code)
15
+ : [];
14
16
  };
15
- const appendHook = (existing, hook) => {
16
- if (!existing)
17
- return [hook];
18
- return Array.isArray(existing) ? [...existing, hook] : [existing, hook];
17
+ const assertLocaleMap = (value, locales, name) => {
18
+ const map = asRecord(value);
19
+ if (!map)
20
+ throw new Error(`payload-redirect: ${name} must be a locale map`);
21
+ const missing = locales.filter((locale) => !(locale in map));
22
+ const unknown = locales.length
23
+ ? Object.keys(map).filter((locale) => !locales.includes(locale))
24
+ : [];
25
+ if (missing.length || unknown.length) {
26
+ throw new Error(`payload-redirect: ${name} has invalid locales (missing: ${missing.join(', ') || 'none'}; unknown: ${unknown.join(', ') || 'none'})`);
27
+ }
28
+ for (const [locale, path] of Object.entries(map)) {
29
+ if (typeof path !== 'string') {
30
+ throw new Error(`payload-redirect: ${name}.${locale} must be a string`);
31
+ }
32
+ }
33
+ return map;
19
34
  };
20
- const wireCollectionRedirectHook = (collection) => {
21
- const meta = readRedirectCustom(collection.custom);
22
- if (!meta)
35
+ const validateOptions = (config, options) => {
36
+ const locales = localeCodes(config);
37
+ if (options.localePrefix !== undefined) {
38
+ const prefixes = assertLocaleMap(options.localePrefix, locales, 'localePrefix');
39
+ for (const [locale, prefix] of Object.entries(prefixes)) {
40
+ if (prefix !== '' &&
41
+ (!prefix.startsWith('/') ||
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`);
51
+ }
52
+ }
53
+ }
54
+ for (const [slug, collectionOptions] of Object.entries(options.collections ?? {})) {
55
+ if (!collectionOptions)
56
+ continue;
57
+ if (!config.collections?.some((collection) => collection.slug === slug)) {
58
+ throw new Error(`payload-redirect: configured collection "${slug}" is not registered`);
59
+ }
60
+ const modes = ['path', 'paths', 'getPath'].filter((key) => key in collectionOptions);
61
+ if (collectionOptions.enabled !== false && modes.length !== 1) {
62
+ throw new Error(`payload-redirect: collection "${slug}" must configure exactly one of path, paths, or getPath`);
63
+ }
64
+ if (collectionOptions.enabled === false)
65
+ continue;
66
+ if ('path' in collectionOptions) {
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
+ }
85
+ }
86
+ };
87
+ const wireCollectionRedirect = (collection, options) => {
88
+ if (options.enabled === false)
89
+ return collection;
90
+ const custom = asRecord(collection.custom);
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)
23
98
  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
+ const afterChange = collection.hooks?.afterChange;
111
+ const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];
112
+ const hook = createRedirect({ identifier: identifier.trim() });
24
113
  return {
25
114
  ...collection,
115
+ custom: { ...custom, redirect: redirectConfig },
26
116
  hooks: {
27
117
  ...collection.hooks,
28
- afterChange: appendHook(collection.hooks?.afterChange, createRedirect({ identifier: meta.identifier })),
118
+ afterChange: [...hooks, hook],
29
119
  },
30
120
  };
31
121
  };
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
- };
122
+ const definedRedirectsPlugin = definePlugin({
123
+ slug: PLUGIN_SLUG,
124
+ plugin: ({ config, ...options }) => {
125
+ validateOptions(config, options);
126
+ const registeredCount = config.plugins?.filter((plugin) => plugin.slug === PLUGIN_SLUG).length ?? 0;
127
+ if (registeredCount > 1) {
128
+ throw new Error('payload-redirect: register redirects() only once in config.plugins');
129
+ }
130
+ if (Object.hasOwn(asRecord(config.custom) ?? {}, 'payloadRedirect')) {
131
+ throw new Error('payload-redirect: config.custom.payloadRedirect is reserved');
132
+ }
133
+ const redirectsCollection = createRedirectsCollection(options.overrides);
134
+ const collectionSlug = redirectsCollection.slug || DEFAULT_COLLECTION_SLUG;
135
+ const existing = config.collections?.find(({ slug }) => slug === collectionSlug);
136
+ if (existing) {
137
+ throw new Error(`payload-redirect: collection slug "${collectionSlug}" is already registered; configure it with redirects({ overrides: { slug } }) instead of defining a host collection`);
138
+ }
139
+ return {
140
+ ...config,
141
+ custom: registerRedirectRuntime(config, {
142
+ collectionSlug,
143
+ localePrefix: options.localePrefix,
144
+ }),
145
+ collections: [
146
+ ...(config.collections ?? []).map((collection) => wireCollectionRedirect(collection, options)),
147
+ redirectsCollection,
148
+ ],
149
+ };
150
+ },
151
+ });
152
+ export const redirects = (options = {}) => definedRedirectsPlugin(options);
@@ -0,0 +1,43 @@
1
+ import type { CollectionSlug, DataFromCollectionSlug, TypedLocale } from 'payload';
2
+ import type { RedirectCollectionOverrides } from '../core/redirects/collection/types.js';
3
+ type Locales = Extract<TypedLocale, string>;
4
+ export type RedirectLocaleMap = [Locales] extends [never] ? Record<never, never> : {
5
+ [Locale in Locales]: string;
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>);
31
+ export type RedirectsOptions = {
32
+ /** Master switch for automatic redirect generation. Manual redirect management stays enabled. */
33
+ enabled?: boolean;
34
+ /** Host URL prefixes. Payload's localization config remains the locale source of truth. */
35
+ localePrefix?: RedirectLocaleMap;
36
+ /** Centralized per-collection automatic redirect configuration. */
37
+ collections?: {
38
+ [TSlug in CollectionSlug]?: RedirectCollectionOptions<TSlug>;
39
+ };
40
+ /** Native collection overrides for the plugin-owned redirects collection. */
41
+ overrides?: RedirectCollectionOverrides;
42
+ };
43
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,104 +1,56 @@
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` |
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
+ | `custom.redirect` has no identifier | The collection is left unchanged; no publication hook is added. |
14
+ | Automatic generation is disabled | No automatic hook is added; manual rules remain available. |
68
15
 
69
- `overrideAccess: false` on lookup—respects collection read access.
16
+ ## Redirect collection writes
70
17
 
71
- ## Auto redirect persistence (`ensureAutoRedirect`)
18
+ `from` and `to` must be non-empty site-relative paths. The plugin normalizes them before checking
19
+ duplicates and loops.
72
20
 
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
21
+ | Condition | Result |
22
+ |---|---|
23
+ | Duplicate normalized `from` | Payload validation error on `from`. |
24
+ | Enabled redirect chain loops or exceeds 1,000 hops | Payload validation error on `to`. |
25
+ | `StatusCode` is not `301` or `302` | Payload field validation error. |
26
+ | `to` is missing or invalid | Payload field validation error. |
27
+ | `origin` is invalid | Payload field validation error. |
28
+ | A manual rule already owns an automatic source path | Automatic write is skipped; the manual rule remains unchanged. |
93
29
 
94
- Exact branches are covered by `tests/security/*` and `tests/integration/*`.
30
+ Internal writes carry server-side request context and run inside the Payload transaction. PostgreSQL
31
+ uses a transaction-scoped advisory lock to serialize graph checks. Other adapters do not claim the
32
+ same concurrent-write guarantee.
95
33
 
96
- ## Configuration vs runtime
34
+ ## Published paths
97
35
 
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` |
36
+ Automatic rules use `custom.redirect.publishedLink`, falling back to `custom.draft.publishedLink`.
37
+ Plugin-level path defaults apply when the collection does not override them.
103
38
 
104
- This package does **not** define HTTP status codes for “no redirect”; the host returns `null` resolution as “continue normal routing.”
39
+ | Condition | Result |
40
+ |---|---|
41
+ | No matching path configuration | The normalized identifier value is used as the path. |
42
+ | Template value is missing or unsafe | That publication transition is skipped. |
43
+ | `getPath` returns `null` | That publication transition is skipped. |
44
+ | `getPath` returns a non-string value other than `null` | Path building throws. |
45
+ | Locale is absent | The normalized identifier value is used as the path. |
46
+ | Locale is missing from a configured prefix map | That publication transition is skipped. |
47
+ | Generated source and destination normalize to the same path | No redirect is written. |
48
+
49
+ Draft saves, first publications, unpublishes, deletions, and unchanged identifiers do not create
50
+ automatic rules.
51
+
52
+ ## Adapter boundary
53
+
54
+ PostgreSQL is the supported adapter for atomic graph validation and writes. SQLite, MongoDB, and
55
+ other adapters may provide Payload transactions, but this package does not assume their locking
56
+ semantics match PostgreSQL advisory locks.
@@ -6,7 +6,7 @@ Accepted
6
6
 
7
7
  ## Context
8
8
 
9
- Hooks and `resolveRedirect` look up by normalized `from`. At most one row per `from` is a domain invariant.
9
+ Hooks look up by normalized `from`. At most one row per `from` is a domain invariant.
10
10
 
11
11
  ## Schema (Payload field flags)
12
12
 
@@ -17,7 +17,7 @@ Hooks and `resolveRedirect` look up by normalized `from`. At most one row per `f
17
17
 
18
18
  Collection defaults: `versions: false`, `defaultSort: 'from'`, `timestamps: true`.
19
19
 
20
- Custom host collections must keep compatible `from` / `enabled` flags (`validateRedirectsCollectionConfig`).
20
+ The plugin owns this collection and enforces compatible `from` / `enabled` flags.
21
21
 
22
22
  ## Postgres (host migration, optional but recommended)
23
23
 
@@ -35,11 +35,10 @@ See host database performance docs when adding indexes for large redirect tables
35
35
 
36
36
  | Path | DB round-trips | Notes |
37
37
  | :--- | :--- | :--- |
38
- | `resolveRedirect` | 1 | `find` by `from`, internal select (from/to/StatusCode/enabled), `depth: 0` |
39
38
  | `ensureAutoRedirect` | 1 or 2 | Single `find` by `from`; create if absent |
40
39
  | Duplicate guard | 1 per save | `beforeChange`; `id not_equals` on update |
40
+ | Redirect-chain guard | 1 per hop | `beforeChange`; bounded at 1,000 hops |
41
41
 
42
42
  ## Non-goals
43
43
 
44
- - Redirect chains
45
44
  - Composite `(enabled, from)` btree without partial predicate — redundant with unique `from` for point lookups
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.2.0",
4
+ "description": "Payload plugin for manual and publication-generated redirects",
5
5
  "homepage": "https://github.com/klnap/payload-redirect#readme",
6
6
  "bugs": {
7
7
  "url": "https://github.com/klnap/payload-redirect/issues"
@@ -36,6 +36,7 @@
36
36
  ],
37
37
  "scripts": {
38
38
  "typecheck": "tsc -p tsconfig.json --noEmit",
39
+ "typecheck:consumer": "bun run build && tsc -p tsconfig.type-fixture.json",
39
40
  "test": "bun test src tests/unit",
40
41
  "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
42
  "check:boundaries": "depcruise --config dependency-cruiser.config.mjs --output-type err-long src",
@@ -45,7 +46,7 @@
45
46
  "check:release": "bun pm pack --dry-run && bun run check:exports",
46
47
  "prepack": "bun run build",
47
48
  "check:exports": "bun scripts/check-exports.mjs",
48
- "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json"
49
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json"
49
50
  },
50
51
  "peerDependencies": {
51
52
  "@payloadcms/db-postgres": ">=3.94.1 <4",
@@ -1,7 +0,0 @@
1
- import type { Payload } from 'payload';
2
- import type { ResolvedRedirect } from './resolved.js';
3
- export type ResolveRedirectArgs = {
4
- payload: Payload;
5
- from: string;
6
- };
7
- export declare const resolveRedirect: ({ payload, from, }: ResolveRedirectArgs) => Promise<ResolvedRedirect>;
@@ -1,27 +0,0 @@
1
- import { RedirectAmbiguousRuleError } from '../model/errors.js';
2
- import { normalizeRedirectSourcePath } from '../normalize-path.js';
3
- import { findRedirectByFrom, redirectResolveSelect } from '../queries.js';
4
- import { toResolvedRedirect } from './resolved.js';
5
- import { getRedirectRuntime } from '../runtime.js';
6
- export const resolveRedirect = async ({ payload, from, }) => {
7
- const { collectionSlug } = getRedirectRuntime(payload.config);
8
- const normalizedFrom = normalizeRedirectSourcePath(from);
9
- const result = await findRedirectByFrom(payload, {
10
- collectionSlug,
11
- from: normalizedFrom,
12
- overrideAccess: false,
13
- select: redirectResolveSelect,
14
- });
15
- if (result.totalDocs > 1) {
16
- throw new RedirectAmbiguousRuleError(`Multiple redirect rules exist for "${normalizedFrom}" (unique constraint should prevent this)`);
17
- }
18
- const doc = result.docs[0];
19
- if (!doc)
20
- return null;
21
- return toResolvedRedirect({
22
- from: String(doc.from),
23
- to: doc.to,
24
- StatusCode: doc.StatusCode,
25
- enabled: doc.enabled !== false,
26
- });
27
- };
@@ -1,17 +0,0 @@
1
- import type { RedirectStatusCode } from '../model/status-code.js';
2
- export type ResolvedRedirect = {
3
- statusCode: 301 | 302;
4
- to: string;
5
- } | null;
6
- export type RedirectRecord = {
7
- from: string;
8
- to?: string | null;
9
- StatusCode: RedirectStatusCode;
10
- enabled: boolean;
11
- };
12
- export declare const toResolvedRedirect: (record: RedirectRecord) => ResolvedRedirect | null;
13
- export declare const redirectLogicalIdentity: (record: {
14
- from: string;
15
- to?: string | null;
16
- StatusCode: RedirectStatusCode;
17
- }) => string;
@@ -1,18 +0,0 @@
1
- import { assertRedirectStatusCode } from '../model/status-code.js';
2
- export const toResolvedRedirect = (record) => {
3
- if (!record.enabled)
4
- return null;
5
- let code;
6
- try {
7
- code = assertRedirectStatusCode(record.StatusCode);
8
- }
9
- catch {
10
- return null;
11
- }
12
- const to = record.to;
13
- if (typeof to !== 'string' || to.trim().length === 0) {
14
- return null;
15
- }
16
- return { statusCode: code, to: to.trim() };
17
- };
18
- export const redirectLogicalIdentity = (record) => `${record.from}\0${record.to ?? ''}\0${record.StatusCode}`;
@@ -1,9 +0,0 @@
1
- import type { PublishedLinkWire } from '../core/redirects/auto/published-link-config.js';
2
- /** Shape for `CollectionConfig.custom.redirect` — auto redirect on identifier change. */
3
- export type RedirectIdentifierField = string;
4
- export type PayloadRedirectCustom = {
5
- enabled?: boolean;
6
- identifier: RedirectIdentifierField;
7
- publishedLink?: PublishedLinkWire;
8
- };
9
- export declare function readRedirectCustom(custom: unknown): PayloadRedirectCustom | null;
@@ -1,18 +0,0 @@
1
- const REDIRECT_CUSTOM_KEY = 'redirect';
2
- export function readRedirectCustom(custom) {
3
- if (!custom || typeof custom !== 'object')
4
- return null;
5
- const entry = custom[REDIRECT_CUSTOM_KEY];
6
- if (!entry || typeof entry !== 'object')
7
- return null;
8
- const record = entry;
9
- if (record.enabled === false)
10
- return null;
11
- const identifier = record.identifier;
12
- if (typeof identifier !== 'string' || !identifier.trim())
13
- return null;
14
- return {
15
- enabled: record.enabled !== false,
16
- identifier: identifier.trim(),
17
- };
18
- }
@@ -1,17 +0,0 @@
1
- import type { CollectionConfig } from 'payload';
2
- import type { RedirectsCollectionAccess } from '../core/redirects/collection/access.js';
3
- import type { LocalePrefix } from '../core/url/published-path.js';
4
- export type RedirectsPluginConfig = {
5
- localePrefix?: LocalePrefix;
6
- /** Enable Payload trash (soft delete). Default true. */
7
- trash?: boolean;
8
- /** Host-owned collection (register in `config.collections` and pass the same config here). */
9
- collection: CollectionConfig;
10
- /** Access overrides when the host collection omits handlers (base collection wins). */
11
- access?: RedirectsCollectionAccess;
12
- };
13
- export type ResolvedRedirectsPluginConfig = {
14
- localePrefix?: LocalePrefix;
15
- collection: CollectionConfig;
16
- };
17
- export declare const resolveRedirectsPluginConfig: (config?: RedirectsPluginConfig) => ResolvedRedirectsPluginConfig;
@@ -1,20 +0,0 @@
1
- import { createRedirectsCollection } from '../core/redirects/collection/collection.js';
2
- import { RedirectConfigError } from '../core/redirects/model/errors.js';
3
- import { assertValidCollectionConfig } from './validate-config.js';
4
- export const resolveRedirectsPluginConfig = (config) => {
5
- if (!config?.collection) {
6
- throw new RedirectConfigError('redirects plugin requires `collection` — register a redirects CollectionConfig in config.collections and pass it to redirects({ collection })');
7
- }
8
- const collectionOptions = {
9
- trash: config.trash,
10
- access: config.access,
11
- };
12
- const collection = assertValidCollectionConfig(config.collection);
13
- return {
14
- localePrefix: config.localePrefix,
15
- collection: createRedirectsCollection({
16
- base: collection,
17
- ...collectionOptions,
18
- }),
19
- };
20
- };
@@ -1,3 +0,0 @@
1
- import type { CollectionConfig } from 'payload';
2
- export declare const validateRedirectsCollectionConfig: (collection: CollectionConfig) => void;
3
- export declare const assertValidCollectionConfig: (collection: unknown) => CollectionConfig;
@@ -1,40 +0,0 @@
1
- import { RedirectConfigError } from '../core/redirects/model/errors.js';
2
- const isFieldWithName = (field) => 'name' in field && typeof field.name === 'string';
3
- const findField = (fields, name) => fields.find((f) => isFieldWithName(f) && f.name === name);
4
- export const validateRedirectsCollectionConfig = (collection) => {
5
- if (!collection.slug || typeof collection.slug !== 'string') {
6
- throw new RedirectConfigError('redirects collection must have a valid slug');
7
- }
8
- const fields = collection.fields ?? [];
9
- const expectedTypes = {
10
- from: 'text',
11
- to: 'text',
12
- StatusCode: 'select',
13
- enabled: 'checkbox',
14
- origin: 'select',
15
- };
16
- for (const [name, type] of Object.entries(expectedTypes)) {
17
- const field = findField(fields, name);
18
- if (field && (!('type' in field) || field.type !== type)) {
19
- throw new RedirectConfigError(`redirects collection field "${name}" must be type ${type}, got "${field.type}"`);
20
- }
21
- }
22
- const fromField = findField(fields, 'from');
23
- if (fromField) {
24
- if (!('unique' in fromField) || fromField.unique !== true) {
25
- throw new RedirectConfigError('redirects collection field "from" must have unique: true');
26
- }
27
- }
28
- const enabledField = findField(fields, 'enabled');
29
- if (enabledField && (!('index' in enabledField) || enabledField.index !== true)) {
30
- throw new RedirectConfigError('redirects collection field "enabled" must have index: true');
31
- }
32
- };
33
- export const assertValidCollectionConfig = (collection) => {
34
- if (!collection || typeof collection !== 'object') {
35
- throw new RedirectConfigError('collection must be a CollectionConfig object');
36
- }
37
- const cfg = collection;
38
- validateRedirectsCollectionConfig(cfg);
39
- return cfg;
40
- };