@klnap/payload-redirect 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +41 -40
  3. package/dist/core/redirects/auto/create-redirect.d.ts +3 -3
  4. package/dist/core/redirects/auto/create-redirect.js +6 -5
  5. package/dist/core/redirects/auto/create-redirect.js.map +1 -0
  6. package/dist/core/redirects/auto/match-existing-rule.d.ts +1 -1
  7. package/dist/core/redirects/auto/match-existing-rule.js +3 -2
  8. package/dist/core/redirects/auto/match-existing-rule.js.map +1 -0
  9. package/dist/core/redirects/auto/persist-auto-rule.d.ts +2 -2
  10. package/dist/core/redirects/auto/persist-auto-rule.js +12 -11
  11. package/dist/core/redirects/auto/persist-auto-rule.js.map +1 -0
  12. package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +2 -2
  13. package/dist/core/redirects/auto/publication/get-publication-transition.js +7 -6
  14. package/dist/core/redirects/auto/publication/get-publication-transition.js.map +1 -0
  15. package/dist/core/redirects/auto/publication/locales.d.ts +1 -1
  16. package/dist/core/redirects/auto/publication/locales.js +14 -13
  17. package/dist/core/redirects/auto/publication/locales.js.map +1 -0
  18. package/dist/core/redirects/auto/publication/publish-intent.d.ts +1 -1
  19. package/dist/core/redirects/auto/publication/publish-intent.js +5 -4
  20. package/dist/core/redirects/auto/publication/publish-intent.js.map +1 -0
  21. package/dist/core/redirects/auto/publication/versions/document-locale.d.ts +1 -1
  22. package/dist/core/redirects/auto/publication/versions/document-locale.js +1 -0
  23. package/dist/core/redirects/auto/publication/versions/document-locale.js.map +1 -0
  24. package/dist/core/redirects/auto/publication/versions/version-pages.d.ts +2 -2
  25. package/dist/core/redirects/auto/publication/versions/version-pages.js +3 -2
  26. package/dist/core/redirects/auto/publication/versions/version-pages.js.map +1 -0
  27. package/dist/core/redirects/auto/publication/versions/version-rows.js +5 -4
  28. package/dist/core/redirects/auto/publication/versions/version-rows.js.map +1 -0
  29. package/dist/core/redirects/auto/types.d.ts +1 -1
  30. package/dist/core/redirects/auto/types.js +1 -0
  31. package/dist/core/redirects/auto/types.js.map +1 -0
  32. package/dist/core/redirects/collection/access.d.ts +1 -1
  33. package/dist/core/redirects/collection/access.js +3 -2
  34. package/dist/core/redirects/collection/access.js.map +1 -0
  35. package/dist/core/redirects/collection/collection.d.ts +2 -2
  36. package/dist/core/redirects/collection/collection.js +10 -9
  37. package/dist/core/redirects/collection/collection.js.map +1 -0
  38. package/dist/core/redirects/collection/duplicate-guard.d.ts +1 -1
  39. package/dist/core/redirects/collection/duplicate-guard.js +34 -33
  40. package/dist/core/redirects/collection/duplicate-guard.js.map +1 -0
  41. package/dist/core/redirects/collection/fields.d.ts +1 -1
  42. package/dist/core/redirects/collection/fields.js +51 -50
  43. package/dist/core/redirects/collection/fields.js.map +1 -0
  44. package/dist/core/redirects/collection/graph-lock.d.ts +1 -1
  45. package/dist/core/redirects/collection/graph-lock.js +8 -7
  46. package/dist/core/redirects/collection/graph-lock.js.map +1 -0
  47. package/dist/core/redirects/collection/origin-hook.d.ts +1 -1
  48. package/dist/core/redirects/collection/origin-hook.js +6 -5
  49. package/dist/core/redirects/collection/origin-hook.js.map +1 -0
  50. package/dist/core/redirects/collection/types.d.ts +2 -2
  51. package/dist/core/redirects/collection/types.js +1 -0
  52. package/dist/core/redirects/collection/types.js.map +1 -0
  53. package/dist/core/redirects/context-keys.d.ts +2 -2
  54. package/dist/core/redirects/context-keys.js +3 -2
  55. package/dist/core/redirects/context-keys.js.map +1 -0
  56. package/dist/core/redirects/model/errors.js +2 -1
  57. package/dist/core/redirects/model/errors.js.map +1 -0
  58. package/dist/core/redirects/model/origin.d.ts +1 -1
  59. package/dist/core/redirects/model/origin.js +4 -3
  60. package/dist/core/redirects/model/origin.js.map +1 -0
  61. package/dist/core/redirects/model/status-code.js +5 -4
  62. package/dist/core/redirects/model/status-code.js.map +1 -0
  63. package/dist/core/redirects/normalize-path.js +23 -22
  64. package/dist/core/redirects/normalize-path.js.map +1 -0
  65. package/dist/core/redirects/queries.d.ts +2 -2
  66. package/dist/core/redirects/queries.js +1 -0
  67. package/dist/core/redirects/queries.js.map +1 -0
  68. package/dist/core/url/published-path.js +20 -19
  69. package/dist/core/url/published-path.js.map +1 -0
  70. package/dist/core/url/route-params.js +9 -8
  71. package/dist/core/url/route-params.js.map +1 -0
  72. package/dist/exports/index.d.ts +4 -4
  73. package/dist/exports/index.js +2 -1
  74. package/dist/exports/index.js.map +1 -0
  75. package/dist/plugin/payload-plugin.d.ts +2 -2
  76. package/dist/plugin/payload-plugin.js +22 -21
  77. package/dist/plugin/payload-plugin.js.map +1 -0
  78. package/dist/plugin/types.d.ts +4 -4
  79. package/dist/plugin/types.js +1 -0
  80. package/dist/plugin/types.js.map +1 -0
  81. package/docs/FAILURE_SEMANTICS.md +28 -28
  82. package/package.json +21 -13
@@ -1,4 +1,4 @@
1
1
  export declare const REDIRECT_CONTEXT_KEYS: {
2
- readonly internal: 'payloadRedirectInternal';
3
- readonly skipAuto: 'payloadRedirectSkipAuto';
2
+ readonly internal: "payloadRedirectInternal";
3
+ readonly skipAuto: "payloadRedirectSkipAuto";
4
4
  };
@@ -1,4 +1,5 @@
1
1
  export const REDIRECT_CONTEXT_KEYS = {
2
- internal: 'payloadRedirectInternal',
3
- skipAuto: 'payloadRedirectSkipAuto',
2
+ internal: "payloadRedirectInternal",
3
+ skipAuto: "payloadRedirectSkipAuto",
4
4
  };
5
+ //# sourceMappingURL=context-keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-keys.js","sourceRoot":"","sources":["../../../src/core/redirects/context-keys.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,QAAQ,EAAE,yBAAyB;IACnC,QAAQ,EAAE,yBAAyB;CAC3B,CAAC","sourcesContent":["export const REDIRECT_CONTEXT_KEYS = {\n internal: \"payloadRedirectInternal\",\n skipAuto: \"payloadRedirectSkipAuto\",\n} as const;\n"]}
@@ -1,3 +1,4 @@
1
1
  export class RedirectValidationError extends Error {
2
- name = 'RedirectValidationError';
2
+ name = "RedirectValidationError";
3
3
  }
4
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/core/redirects/model/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAC9B,IAAI,GAAG,yBAAyB,CAAC;CACpD","sourcesContent":["export class RedirectValidationError extends Error {\n override readonly name = \"RedirectValidationError\";\n}\n"]}
@@ -1,4 +1,4 @@
1
- export declare const REDIRECT_ORIGIN_VALUES: readonly ['manual', 'auto'];
1
+ export declare const REDIRECT_ORIGIN_VALUES: readonly ["manual", "auto"];
2
2
  export type RedirectOrigin = (typeof REDIRECT_ORIGIN_VALUES)[number];
3
3
  export declare const DEFAULT_REDIRECT_ORIGIN: RedirectOrigin;
4
4
  export declare const isRedirectOrigin: (value: unknown) => value is RedirectOrigin;
@@ -1,3 +1,4 @@
1
- export const REDIRECT_ORIGIN_VALUES = ['manual', 'auto'];
2
- export const DEFAULT_REDIRECT_ORIGIN = 'manual';
3
- export const isRedirectOrigin = (value) => typeof value === 'string' && REDIRECT_ORIGIN_VALUES.includes(value);
1
+ export const REDIRECT_ORIGIN_VALUES = ["manual", "auto"];
2
+ export const DEFAULT_REDIRECT_ORIGIN = "manual";
3
+ export const isRedirectOrigin = (value) => typeof value === "string" && REDIRECT_ORIGIN_VALUES.includes(value);
4
+ //# sourceMappingURL=origin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"origin.js","sourceRoot":"","sources":["../../../../src/core/redirects/model/origin.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAU,CAAC;AAIlE,MAAM,CAAC,MAAM,uBAAuB,GAAmB,QAAQ,CAAC;AAEhE,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAc,EAA2B,EAAE,CAC1E,OAAO,KAAK,KAAK,QAAQ,IAAK,sBAA4C,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC","sourcesContent":["export const REDIRECT_ORIGIN_VALUES = [\"manual\", \"auto\"] as const;\n\nexport type RedirectOrigin = (typeof REDIRECT_ORIGIN_VALUES)[number];\n\nexport const DEFAULT_REDIRECT_ORIGIN: RedirectOrigin = \"manual\";\n\nexport const isRedirectOrigin = (value: unknown): value is RedirectOrigin =>\n typeof value === \"string\" && (REDIRECT_ORIGIN_VALUES as readonly string[]).includes(value);\n"]}
@@ -1,8 +1,8 @@
1
- import { RedirectValidationError } from './errors.js';
1
+ import { RedirectValidationError } from "./errors.js";
2
2
  const SUPPORTED = [301, 302];
3
3
  export const DEFAULT_REDIRECT_STATUS_CODE = 301;
4
4
  const normalizeStatusCode = (value) => {
5
- const code = typeof value === 'string' ? Number(value) : value;
5
+ const code = typeof value === "string" ? Number(value) : value;
6
6
  if (code === 301 || code === 302)
7
7
  return code;
8
8
  return undefined;
@@ -11,14 +11,15 @@ export const isRedirectStatusCode = (value) => normalizeStatusCode(value) !== un
11
11
  export const assertRedirectStatusCode = (value) => {
12
12
  const code = normalizeStatusCode(value);
13
13
  if (code === undefined) {
14
- throw new RedirectValidationError(`statusCode must be one of ${SUPPORTED.join(', ')}`);
14
+ throw new RedirectValidationError(`statusCode must be one of ${SUPPORTED.join(", ")}`);
15
15
  }
16
16
  return code;
17
17
  };
18
18
  export const requiresDestination = (_statusCode) => true;
19
19
  export const validateDestinationForStatus = (statusCode, to) => {
20
- const hasTo = typeof to === 'string' && to.trim().length > 0;
20
+ const hasTo = typeof to === "string" && to.trim().length > 0;
21
21
  if (!hasTo) {
22
22
  throw new RedirectValidationError(`statusCode ${statusCode} requires a non-empty "to" field`);
23
23
  }
24
24
  };
25
+ //# sourceMappingURL=status-code.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-code.js","sourceRoot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AK,EAAE,CAAC;QACX,MAAM,IAAI,uBAAuB,CAAC,cAAc,UAAU,kCAAkC,CAAC,CAAC;IAChG,CAAC;AACH,CAAC,CAAC","sourcesContent":["import { RedirectValidationError } from \"#redirect/core/redirects/model/errors\";\n\nexport type RedirectStatusCode = 301 | 302;\n\nconst SUPPORTED: readonly RedirectStatusCode[] = [301, 302];\n\nexport const DEFAULT_REDIRECT_STATUS_CODE: RedirectStatusCode = 301;\n\nconst normalizeStatusCode = (value: unknown): RedirectStatusCode | undefined => {\n const code = typeof value === \"string\" ? Number(value) : value;\n if (code === 301 || code === 302) return code;\n return undefined;\n};\n\nexport const isRedirectStatusCode = (value: unknown): value is RedirectStatusCode =>\n normalizeStatusCode(value) !== undefined;\n\nexport const assertRedirectStatusCode = (value: unknown): RedirectStatusCode => {\n const code = normalizeStatusCode(value);\n if (code === undefined) {\n throw new RedirectValidationError(`statusCode must be one of ${SUPPORTED.join(\", \")}`);\n }\n return code;\n};\n\nexport const requiresDestination = (_statusCode: RedirectStatusCode): boolean => true;\n\nexport const validateDestinationForStatus = (statusCode: RedirectStatusCode, to: unknown): void => {\n const hasTo = typeof to === \"string\" && to.trim().length > 0;\n if (!hasTo) {\n throw new RedirectValidationError(`statusCode ${statusCode} requires a non-empty \"to\" field`);\n }\n};\n"]}
@@ -1,27 +1,27 @@
1
- import { RedirectValidationError } from './model/errors.js';
2
- const RELATIVE_PATH_MESSAGE = 'Path must be site-relative (e.g. /blog/post). Do not include a protocol or hostname.';
1
+ import { RedirectValidationError } from "./model/errors.js";
2
+ const RELATIVE_PATH_MESSAGE = "Path must be site-relative (e.g. /blog/post). Do not include a protocol or hostname.";
3
3
  /**
4
4
  * Admin / manual rules: site-relative paths only (no absolute URLs).
5
5
  */
6
6
  export const assertRelativeRedirectPath = (input) => {
7
7
  const trimmed = input.trim();
8
8
  if (!trimmed) {
9
- throw new RedirectValidationError('from/to must be a non-empty site-relative path');
9
+ throw new RedirectValidationError("from/to must be a non-empty site-relative path");
10
10
  }
11
11
  if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(trimmed)) {
12
12
  throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);
13
13
  }
14
- if (trimmed.startsWith('//')) {
14
+ if (trimmed.startsWith("//")) {
15
15
  throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);
16
16
  }
17
17
  // WHATWG URL parsing treats "\" as "/" and strips tabs/newlines, so "/\evil.example"
18
18
  // or "/\t/evil.example" resolve to another origin. Reject those characters outright.
19
19
  if (hasBackslashOrControlChar(trimmed)) {
20
- throw new RedirectValidationError('Path must not contain backslashes or control characters.');
20
+ throw new RedirectValidationError("Path must not contain backslashes or control characters.");
21
21
  }
22
- const pathOnly = trimmed.split(/[?#]/)[0] ?? '';
23
- const firstSegment = pathOnly.replace(/^\/+/, '').split('/')[0] ?? '';
24
- if (!trimmed.startsWith('/') && firstSegment && looksLikeHostname(firstSegment)) {
22
+ const pathOnly = trimmed.split(/[?#]/)[0] ?? "";
23
+ const firstSegment = pathOnly.replace(/^\/+/, "").split("/")[0] ?? "";
24
+ if (!trimmed.startsWith("/") && firstSegment && looksLikeHostname(firstSegment)) {
25
25
  throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);
26
26
  }
27
27
  };
@@ -34,10 +34,10 @@ const hasBackslashOrControlChar = (value) => {
34
34
  return false;
35
35
  };
36
36
  const looksLikeHostname = (segment) => {
37
- if (!segment.includes('.')) {
37
+ if (!segment.includes(".")) {
38
38
  return false;
39
39
  }
40
- if (segment === '.' || segment === '..') {
40
+ if (segment === "." || segment === "..") {
41
41
  return false;
42
42
  }
43
43
  return /^[a-zA-Z0-9.-]+$/.test(segment);
@@ -49,7 +49,7 @@ const looksLikeHostname = (segment) => {
49
49
  export const normalizePathOrUrl = (input) => {
50
50
  const trimmed = input.trim();
51
51
  if (!trimmed) {
52
- throw new RedirectValidationError('from/to must be a non-empty path or URL');
52
+ throw new RedirectValidationError("from/to must be a non-empty path or URL");
53
53
  }
54
54
  if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(trimmed)) {
55
55
  return normalizeAbsoluteUrl(trimmed);
@@ -63,23 +63,23 @@ export const normalizeRelativeRedirectPath = (input) => {
63
63
  };
64
64
  export const normalizeRedirectSourcePath = (input) => {
65
65
  const normalized = normalizeRelativeRedirectPath(input);
66
- if (normalized.includes('#')) {
67
- throw new RedirectValidationError('from must not contain a fragment');
66
+ if (normalized.includes("#")) {
67
+ throw new RedirectValidationError("from must not contain a fragment");
68
68
  }
69
69
  return normalized;
70
70
  };
71
71
  const normalizePath = (path) => {
72
72
  const boundary = path.search(/[?#]/);
73
- const suffix = boundary < 0 ? '' : path.slice(boundary);
73
+ const suffix = boundary < 0 ? "" : path.slice(boundary);
74
74
  let p = boundary < 0 ? path : path.slice(0, boundary);
75
- if (!p.startsWith('/')) {
75
+ if (!p.startsWith("/")) {
76
76
  p = `/${p}`;
77
77
  }
78
- p = p.replace(/\/{2,}/g, '/');
78
+ p = p.replace(/\/{2,}/g, "/");
79
79
  // Browsers resolve these segments before requesting the path.
80
80
  const segments = [];
81
- for (const segment of p.slice(1).split('/')) {
82
- if (segment === '.' || /^%2e$/i.test(segment))
81
+ for (const segment of p.slice(1).split("/")) {
82
+ if (segment === "." || /^%2e$/i.test(segment))
83
83
  continue;
84
84
  if (/^(?:\.\.|\.%2e|%2e\.|%2e%2e)$/i.test(segment)) {
85
85
  segments.pop();
@@ -87,16 +87,16 @@ const normalizePath = (path) => {
87
87
  }
88
88
  segments.push(segment);
89
89
  }
90
- p = `/${segments.join('/')}`;
91
- if (p.length > 1 && p.endsWith('/')) {
90
+ p = `/${segments.join("/")}`;
91
+ if (p.length > 1 && p.endsWith("/")) {
92
92
  p = p.slice(0, -1);
93
93
  }
94
- return `${p === '' ? '/' : p}${suffix}`;
94
+ return `${p === "" ? "/" : p}${suffix}`;
95
95
  };
96
96
  const normalizeAbsoluteUrl = (url) => {
97
97
  try {
98
98
  const parsed = new URL(url);
99
- parsed.pathname = normalizePath(parsed.pathname || '/');
99
+ parsed.pathname = normalizePath(parsed.pathname || "/");
100
100
  return parsed.toString();
101
101
  }
102
102
  catch {
@@ -104,3 +104,4 @@ const normalizeAbsoluteUrl = (url) => {
104
104
  }
105
105
  };
106
106
  export const pathsEqual = (a, b) => normalizePathOrUrl(a) === normalizePathOrUrl(b);
107
+ //# sourceMappingURL=normalize-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize-path.js","sourceRoot":"","sources":["../../../src/core/redirects/normalize-path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAEhF,MAAM,qBAAqB,GACzB,sFAAsF,CAAC;AAEzF;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,KAAa,EAAQ,EAAE;IAChE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,uBAAuB,CAAC,gDAAgD,CAAC,CAAC;IACtF,CAAC;IAED,IAAI,2BAA2B,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9C,MAAM,IAAI,uBAAuB,CAAC,qBAAqB,CAAC,CAAC;IAC3D,CAAC;IAED,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,uBAAuB,CAAC,qBAAqB,CAAC,CAAC;IAC3D,CAAC;IAED,qFAAqF;IACrF,qFAAqF;IACrF,IAAI,yBAAyB,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,uBAAuB,CAAC,0DAA0D,CAAC,CAAC;IAChG,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAChD,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,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AW,EAAE,CAC1D,kBAAkB,CAAC,CAAC,CAAC,KAAK,kBAAkB,CAAC,CAAC,CAAC,CAAC","sourcesContent":["import { RedirectValidationError } from \"#redirect/core/redirects/model/errors\";\n\nconst RELATIVE_PATH_MESSAGE =\n \"Path must be site-relative (e.g. /blog/post). Do not include a protocol or hostname.\";\n\n/**\n * Admin / manual rules: site-relative paths only (no absolute URLs).\n */\nexport const assertRelativeRedirectPath = (input: string): void => {\n const trimmed = input.trim();\n if (!trimmed) {\n throw new RedirectValidationError(\"from/to must be a non-empty site-relative path\");\n }\n\n if (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.test(trimmed)) {\n throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);\n }\n\n if (trimmed.startsWith(\"//\")) {\n throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);\n }\n\n // WHATWG URL parsing treats \"\\\" as \"/\" and strips tabs/newlines, so \"/\\evil.example\"\n // or \"/\\t/evil.example\" resolve to another origin. Reject those characters outright.\n if (hasBackslashOrControlChar(trimmed)) {\n throw new RedirectValidationError(\"Path must not contain backslashes or control characters.\");\n }\n\n const pathOnly = trimmed.split(/[?#]/)[0] ?? \"\";\n const firstSegment = pathOnly.replace(/^\\/+/, \"\").split(\"/\")[0] ?? \"\";\n if (!trimmed.startsWith(\"/\") && firstSegment && looksLikeHostname(firstSegment)) {\n throw new RedirectValidationError(RELATIVE_PATH_MESSAGE);\n }\n};\n\nconst hasBackslashOrControlChar = (value: string): boolean => {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code === 0x5c || code < 0x20 || code === 0x7f) return true;\n }\n return false;\n};\n\nconst looksLikeHostname = (segment: string): boolean => {\n if (!segment.includes(\".\")) {\n return false;\n }\n if (segment === \".\" || segment === \"..\") {\n return false;\n }\n return /^[a-zA-Z0-9.-]+$/.test(segment);\n};\n\n/**\n * Canonical path/URL for storage and lookup.\n * Minimal normalization — no destructive reshaping of materially different URLs.\n */\nexport const normalizePathOrUrl = (input: string): string => {\n const trimmed = input.trim();\n if (!trimmed) {\n throw new RedirectValidationError(\"from/to must be a non-empty path or URL\");\n }\n\n if (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.test(trimmed)) {\n return normalizeAbsoluteUrl(trimmed);\n }\n\n return normalizePath(trimmed);\n};\n\n/** Normalize a site-relative path (no protocol/host). */\nexport const normalizeRelativeRedirectPath = (input: string): string => {\n assertRelativeRedirectPath(input);\n return normalizePath(input.trim());\n};\n\nexport const normalizeRedirectSourcePath = (input: string): string => {\n const normalized = normalizeRelativeRedirectPath(input);\n if (normalized.includes(\"#\")) {\n throw new RedirectValidationError(\"from must not contain a fragment\");\n }\n return normalized;\n};\n\nconst normalizePath = (path: string): string => {\n const boundary = path.search(/[?#]/);\n const suffix = boundary < 0 ? \"\" : path.slice(boundary);\n let p = boundary < 0 ? path : path.slice(0, boundary);\n if (!p.startsWith(\"/\")) {\n p = `/${p}`;\n }\n p = p.replace(/\\/{2,}/g, \"/\");\n // Browsers resolve these segments before requesting the path.\n const segments: string[] = [];\n for (const segment of p.slice(1).split(\"/\")) {\n if (segment === \".\" || /^%2e$/i.test(segment)) continue;\n if (/^(?:\\.\\.|\\.%2e|%2e\\.|%2e%2e)$/i.test(segment)) {\n segments.pop();\n continue;\n }\n segments.push(segment);\n }\n p = `/${segments.join(\"/\")}`;\n if (p.length > 1 && p.endsWith(\"/\")) {\n p = p.slice(0, -1);\n }\n return `${p === \"\" ? \"/\" : p}${suffix}`;\n};\n\nconst normalizeAbsoluteUrl = (url: string): string => {\n try {\n const parsed = new URL(url);\n parsed.pathname = normalizePath(parsed.pathname || \"/\");\n return parsed.toString();\n } catch {\n throw new RedirectValidationError(`Invalid absolute URL: ${url}`);\n }\n};\n\nexport const pathsEqual = (a: string, b: string): boolean =>\n normalizePathOrUrl(a) === normalizePathOrUrl(b);\n"]}
@@ -1,5 +1,5 @@
1
- import type { Payload, PayloadRequest, SelectType } from 'payload';
2
- import type { RedirectStatusCode } from './model/status-code.js';
1
+ import type { Payload, PayloadRequest, SelectType } from "payload";
2
+ import type { RedirectStatusCode } from "./model/status-code.js";
3
3
  export type RedirectLookupDoc = {
4
4
  id: string | number;
5
5
  from?: string | null;
@@ -24,3 +24,4 @@ export const findRedirectByFrom = async (payload, { collectionSlug, from, req, o
24
24
  req,
25
25
  }));
26
26
  };
27
+ //# sourceMappingURL=queries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.js","sourceRoot":"","sources":["../../../src/core/redirects/queries.ts"],"names":[],"mappings":"AAGA,wDAAwD;AACxD,MAAM,oBAAoB,GAAG;IAC3B,EAAE,EAAE,IAAI;IACR,IAAI,EAAE,IAAI;IACV,EAAE,EAAE,IAAI;IACR,UAAU,EAAE,IAAI;IAChB,OAAO,EAAE,IAAI;IACb,MAAM,EAAE,IAAI;CACJ,CAAC;AAoBX,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EACrC,OAAgB,EAChB,EACE,cAAc,EACd,IAAI,EACJ,GAAG,EACH,cAAc,GAAG,KAAK,EACtB,OAAO,EACP,MAAM,GAAG,oBAAoB,EAC7B,SAAS,GACwC,EACX,EAAE;IAC1C,MAAM,KAAK,GACT,SAAS,KAAK,SAAS;QACrB,CAAC,CAAC;YACE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,CAAC;SACrE;QACH,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC;IAEjC,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC;QACzB,UAAU,EAAE,cAAgC;QAC5C,KAAK;QACL,KAAK,EAAE,CAAC;QACR,KAAK,EAAE,CAAC;QACR,MAAM;QACN,cAAc;QACd,OAAO;QACP,GAAG;KACJ,CAAC,CAA6C,CAAC;AAClD,CAAC,CAAC","sourcesContent":["import type { CollectionSlug, Payload, PayloadRequest, SelectType, Where } from \"payload\";\nimport type { RedirectStatusCode } from \"#redirect/core/redirects/model/status-code\";\n\n/** Lookup hooks / idempotent writes (includes `id`). */\nconst redirectLookupSelect = {\n id: true,\n from: true,\n to: true,\n statusCode: true,\n enabled: true,\n origin: true,\n} as const;\n\nexport type RedirectLookupDoc = {\n id: string | number;\n from?: string | null;\n to?: string | null;\n statusCode?: RedirectStatusCode | null;\n enabled?: boolean | null;\n origin?: string | null;\n};\n\ntype FindByFromBase = {\n collectionSlug: string;\n from: string;\n req?: PayloadRequest;\n overrideAccess?: boolean;\n context?: Record<string, unknown>;\n select?: SelectType;\n};\n\nexport const findRedirectByFrom = async (\n payload: Payload,\n {\n collectionSlug,\n from,\n req,\n overrideAccess = false,\n context,\n select = redirectLookupSelect,\n excludeId,\n }: FindByFromBase & { excludeId?: string | number },\n): Promise<{ docs: RedirectLookupDoc[] }> => {\n const where: Where =\n excludeId !== undefined\n ? {\n and: [{ from: { equals: from } }, { id: { not_equals: excludeId } }],\n }\n : { from: { equals: from } };\n\n return (await payload.find({\n collection: collectionSlug as CollectionSlug,\n where,\n limit: 1,\n depth: 0,\n select,\n overrideAccess,\n context,\n req,\n })) as unknown as { docs: RedirectLookupDoc[] };\n};\n"]}
@@ -1,42 +1,42 @@
1
- import { applyDynamicSegments, hasControlCharacter, isValidPathTemplate } from './route-params.js';
1
+ import { applyDynamicSegments, hasControlCharacter, isValidPathTemplate } from "./route-params.js";
2
2
  const localeCode = (locale) => {
3
- if (typeof locale === 'string')
3
+ if (typeof locale === "string")
4
4
  return locale || undefined;
5
- if (locale && typeof locale === 'object' && 'code' in locale) {
5
+ if (locale && typeof locale === "object" && "code" in locale) {
6
6
  const code = locale.code;
7
- return typeof code === 'string' && code ? code : undefined;
7
+ return typeof code === "string" && code ? code : undefined;
8
8
  }
9
9
  return undefined;
10
10
  };
11
- export const isValidLocalePrefix = (prefix) => prefix === '' ||
12
- (prefix.startsWith('/') &&
13
- !prefix.startsWith('//') &&
14
- !prefix.includes('?') &&
15
- !prefix.includes('#') &&
16
- !prefix.includes('\\') &&
11
+ export const isValidLocalePrefix = (prefix) => prefix === "" ||
12
+ (prefix.startsWith("/") &&
13
+ !prefix.startsWith("//") &&
14
+ !prefix.includes("?") &&
15
+ !prefix.includes("#") &&
16
+ !prefix.includes("\\") &&
17
17
  !hasControlCharacter(prefix));
18
- const withPrefix = (prefix, path) => path === '/' ? prefix || '/' : `${prefix}${path}`;
19
- const isSiteRelativePath = (path) => path.startsWith('/') &&
20
- !path.startsWith('//') &&
21
- !path.includes('?') &&
22
- !path.includes('#') &&
23
- !path.includes('\\') &&
18
+ const withPrefix = (prefix, path) => path === "/" ? prefix || "/" : `${prefix}${path}`;
19
+ const isSiteRelativePath = (path) => path.startsWith("/") &&
20
+ !path.startsWith("//") &&
21
+ !path.includes("?") &&
22
+ !path.includes("#") &&
23
+ !path.includes("\\") &&
24
24
  !hasControlCharacter(path);
25
25
  export const buildPublishedPath = (config, doc, locale, localePrefixes) => {
26
- if (typeof config.getPath === 'function') {
26
+ if (typeof config.getPath === "function") {
27
27
  const path = config.getPath({
28
28
  doc,
29
29
  locale,
30
30
  });
31
31
  if (path === null)
32
32
  return null;
33
- if (typeof path !== 'string')
33
+ if (typeof path !== "string")
34
34
  return null;
35
35
  return isSiteRelativePath(path) ? path : null;
36
36
  }
37
37
  const code = localeCode(locale);
38
38
  const template = config.paths !== undefined ? (code ? config.paths[code] : undefined) : config.path;
39
- if (typeof template !== 'string' || !isValidPathTemplate(template))
39
+ if (typeof template !== "string" || !isValidPathTemplate(template))
40
40
  return null;
41
41
  const resolved = applyDynamicSegments(template, doc, code);
42
42
  if (resolved === null)
@@ -47,3 +47,4 @@ export const buildPublishedPath = (config, doc, locale, localePrefixes) => {
47
47
  return null;
48
48
  return withPrefix(localePrefixes[code], resolved);
49
49
  };
50
+ //# sourceMappingURL=published-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"published-path.js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AAQ,CAAC;IAClD,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,EAAE,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC/D,OAAO,UAAU,CAAC,cAAc,CAAC,IAAI,CAAE,EAAE,QAAQ,CAAC,CAAC;AACrD,CAAC,CAAC","sourcesContent":["import { applyDynamicSegments, hasControlCharacter, isValidPathTemplate } from \"./route-params.js\";\n\nexport type LocalePrefixes = Record<string, string>;\n\nexport type PublishedPathConfiguration = {\n path?: string;\n paths?: Record<string, string>;\n getPath?: unknown;\n};\n\nconst localeCode = (locale: unknown): string | undefined => {\n if (typeof locale === \"string\") return locale || undefined;\n if (locale && typeof locale === \"object\" && \"code\" in locale) {\n const code = (locale as { code?: unknown }).code;\n return typeof code === \"string\" && code ? code : undefined;\n }\n return undefined;\n};\n\nexport const isValidLocalePrefix = (prefix: string): boolean =>\n prefix === \"\" ||\n (prefix.startsWith(\"/\") &&\n !prefix.startsWith(\"//\") &&\n !prefix.includes(\"?\") &&\n !prefix.includes(\"#\") &&\n !prefix.includes(\"\\\\\") &&\n !hasControlCharacter(prefix));\n\nconst withPrefix = (prefix: string, path: string): string =>\n path === \"/\" ? prefix || \"/\" : `${prefix}${path}`;\n\nconst isSiteRelativePath = (path: string): boolean =>\n path.startsWith(\"/\") &&\n !path.startsWith(\"//\") &&\n !path.includes(\"?\") &&\n !path.includes(\"#\") &&\n !path.includes(\"\\\\\") &&\n !hasControlCharacter(path);\n\nexport const buildPublishedPath = (\n config: PublishedPathConfiguration,\n doc: Record<string, unknown>,\n locale: unknown,\n localePrefixes?: LocalePrefixes,\n): string | null => {\n if (typeof config.getPath === \"function\") {\n const path = (\n config.getPath as (args: { doc: Record<string, unknown>; locale: unknown }) => unknown\n )({\n doc,\n locale,\n });\n if (path === null) return null;\n if (typeof path !== \"string\") return null;\n return isSiteRelativePath(path) ? path : null;\n }\n\n const code = localeCode(locale);\n const template =\n config.paths !== undefined ? (code ? config.paths[code] : undefined) : config.path;\n if (typeof template !== \"string\" || !isValidPathTemplate(template)) return null;\n\n const resolved = applyDynamicSegments(template, doc, code);\n if (resolved === null) return null;\n\n if (localePrefixes === undefined) return resolved;\n if (!code || !Object.hasOwn(localePrefixes, code)) return null;\n return withPrefix(localePrefixes[code]!, resolved);\n};\n"]}
@@ -1,20 +1,20 @@
1
1
  const DYNAMIC_SEGMENT = /\[([^\]]+)\]/g;
2
2
  const VALID_FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
- const FORBIDDEN_FIELD_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
3
+ const FORBIDDEN_FIELD_NAMES = new Set(["__proto__", "constructor", "prototype"]);
4
4
  export const hasControlCharacter = (value) => [...value].some((character) => {
5
5
  const code = character.charCodeAt(0);
6
6
  return code <= 0x1f || code === 0x7f;
7
7
  });
8
8
  export const isValidPathTemplate = (template) => {
9
- if (!template.startsWith('/') ||
10
- template.startsWith('//') ||
9
+ if (!template.startsWith("/") ||
10
+ template.startsWith("//") ||
11
11
  /[?#\\]/.test(template) ||
12
12
  hasControlCharacter(template)) {
13
13
  return false;
14
14
  }
15
15
  const fields = [...template.matchAll(DYNAMIC_SEGMENT)];
16
- if (template.replace(DYNAMIC_SEGMENT, '').includes('[') ||
17
- template.replace(DYNAMIC_SEGMENT, '').includes(']')) {
16
+ if (template.replace(DYNAMIC_SEGMENT, "").includes("[") ||
17
+ template.replace(DYNAMIC_SEGMENT, "").includes("]")) {
18
18
  return false;
19
19
  }
20
20
  return fields.every(([, name]) => Boolean(name && VALID_FIELD_NAME.test(name) && !FORBIDDEN_FIELD_NAMES.has(name)));
@@ -26,14 +26,15 @@ export const applyDynamicSegments = (template, doc, locale) => {
26
26
  let result = template;
27
27
  for (const field of extractDynamicSegments(template)) {
28
28
  let value = doc[field];
29
- if (value && typeof value === 'object' && !Array.isArray(value)) {
29
+ if (value && typeof value === "object" && !Array.isArray(value)) {
30
30
  value = locale ? value[locale] : undefined;
31
31
  }
32
- if (typeof value === 'number' && Number.isFinite(value))
32
+ if (typeof value === "number" && Number.isFinite(value))
33
33
  value = String(value);
34
- if (typeof value !== 'string' || !value || value === '.' || value === '..')
34
+ if (typeof value !== "string" || !value || value === "." || value === "..")
35
35
  return null;
36
36
  result = result.replaceAll(`[${field}]`, encodeURIComponent(value));
37
37
  }
38
38
  return result;
39
39
  };
40
+ //# sourceMappingURL=route-params.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-params.js","sourceRoot":"","sources":["../../../src/core/url/route-params.ts"],"names":[],"mappings":"AAAA,MAAM,eAAe,GAAG,eAAe,CAAC;AACxC,MAAM,gBAAgB,GAAG,0BAA0B,CAAC;AACpD,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;AAEjF,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,KAAa,EAAW,EAAE,CAC5D,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE;IAC5B,MAAM,IAAI,GAAG,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACrC,OAAO,IAAI,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC;AACvC,CAAC,CAAC,CAAC;AAEL,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,QAAgB,EAAW,EAAE;IAC/D,IACE,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC;QACzB,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;QACvB,mBAAmB,CAAC,QAAQ,CAAC,EAC7B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,MAAM,GAAG,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC;IACvD,IACE,QAAQ,CAAC,OAAO,CAAC,eA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C;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC/E,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QACxF,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,KAAK,GAAG,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC","sourcesContent":["const DYNAMIC_SEGMENT = /\\[([^\\]]+)\\]/g;\nconst VALID_FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FORBIDDEN_FIELD_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport const hasControlCharacter = (value: string): boolean =>\n [...value].some((character) => {\n const code = character.charCodeAt(0);\n return code <= 0x1f || code === 0x7f;\n });\n\nexport const isValidPathTemplate = (template: string): boolean => {\n if (\n !template.startsWith(\"/\") ||\n template.startsWith(\"//\") ||\n /[?#\\\\]/.test(template) ||\n hasControlCharacter(template)\n ) {\n return false;\n }\n\n const fields = [...template.matchAll(DYNAMIC_SEGMENT)];\n if (\n template.replace(DYNAMIC_SEGMENT, \"\").includes(\"[\") ||\n template.replace(DYNAMIC_SEGMENT, \"\").includes(\"]\")\n ) {\n return false;\n }\n\n return fields.every(([, name]) =>\n Boolean(name && VALID_FIELD_NAME.test(name) && !FORBIDDEN_FIELD_NAMES.has(name)),\n );\n};\n\nconst extractDynamicSegments = (template: string): string[] =>\n [...template.matchAll(DYNAMIC_SEGMENT)].flatMap(([, name]) => (name ? [name] : []));\n\nexport const applyDynamicSegments = (\n template: string,\n doc: Record<string, unknown>,\n locale: string | undefined,\n): string | null => {\n if (!isValidPathTemplate(template)) return null;\n\n let result = template;\n for (const field of extractDynamicSegments(template)) {\n let value = doc[field];\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n value = locale ? (value as Record<string, unknown>)[locale] : undefined;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value)) value = String(value);\n if (typeof value !== \"string\" || !value || value === \".\" || value === \"..\") return null;\n result = result.replaceAll(`[${field}]`, encodeURIComponent(value));\n }\n\n return result;\n};\n"]}
@@ -1,4 +1,4 @@
1
- export type { RedirectOrigin } from '../core/redirects/model/origin.js';
2
- export type { RedirectStatusCode } from '../core/redirects/model/status-code.js';
3
- export { redirects } from '../plugin/payload-plugin.js';
4
- export type { RedirectCollectionOptions, RedirectsOptions } from '../plugin/types.js';
1
+ export type { RedirectOrigin } from "../core/redirects/model/origin.js";
2
+ export type { RedirectStatusCode } from "../core/redirects/model/status-code.js";
3
+ export { redirects } from "../plugin/payload-plugin.js";
4
+ export type { RedirectCollectionOptions, RedirectsOptions } from "../plugin/types.js";
@@ -1 +1,2 @@
1
- export { redirects } from '../plugin/payload-plugin.js';
1
+ export { redirects } from "../plugin/payload-plugin.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/exports/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export type { RedirectOrigin } from \"#redirect/core/redirects/model/origin\";\nexport type { RedirectStatusCode } from \"#redirect/core/redirects/model/status-code\";\nexport { redirects } from \"#redirect/plugin/payload-plugin\";\nexport type { RedirectCollectionOptions, RedirectsOptions } from \"#redirect/plugin/types\";\n"]}
@@ -1,3 +1,3 @@
1
- import { type Plugin } from 'payload';
2
- import type { RedirectsOptions } from './types.js';
1
+ import { type Plugin } from "payload";
2
+ import type { RedirectsOptions } from "./types.js";
3
3
  export declare const redirects: (options?: RedirectsOptions) => Plugin;
@@ -1,18 +1,18 @@
1
- import { definePlugin } from 'payload';
2
- import { createRedirect } from '../core/redirects/auto/create-redirect.js';
3
- import { createRedirectsCollection } from '../core/redirects/collection/collection.js';
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)
1
+ import { definePlugin } from "payload";
2
+ import { createRedirect } from "../core/redirects/auto/create-redirect.js";
3
+ import { createRedirectsCollection } from "../core/redirects/collection/collection.js";
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
10
  ? value
11
11
  : undefined;
12
12
  const localeCodes = (config) => {
13
13
  const locales = config.localization === false ? undefined : config.localization?.locales;
14
14
  return Array.isArray(locales)
15
- ? locales.map((locale) => typeof locale === 'string' ? locale : locale.code)
15
+ ? locales.map((locale) => typeof locale === "string" ? locale : locale.code)
16
16
  : [];
17
17
  };
18
18
  const assertLocaleMap = (value, locales, name) => {
@@ -22,10 +22,10 @@ const assertLocaleMap = (value, locales, name) => {
22
22
  const missing = locales.filter((locale) => !Object.hasOwn(map, locale));
23
23
  const unknown = Object.keys(map).filter((locale) => !locales.includes(locale));
24
24
  if (missing.length || unknown.length) {
25
- throw new Error(`payload-redirect: ${name} has invalid locales (missing: ${missing.join(', ') || 'none'}; unknown: ${unknown.join(', ') || 'none'})`);
25
+ throw new Error(`payload-redirect: ${name} has invalid locales (missing: ${missing.join(", ") || "none"}; unknown: ${unknown.join(", ") || "none"})`);
26
26
  }
27
27
  for (const [locale, path] of Object.entries(map)) {
28
- if (typeof path !== 'string') {
28
+ if (typeof path !== "string") {
29
29
  throw new Error(`payload-redirect: ${name}.${locale} must be a string`);
30
30
  }
31
31
  }
@@ -37,9 +37,9 @@ const validatePathOptions = (value, slug, locales, collection) => {
37
37
  throw new Error(`payload-redirect: redirect config for "${slug}" must be an object`);
38
38
  const unsupported = Object.keys(options).filter((key) => !PATH_OPTIONS.has(key));
39
39
  if (unsupported.length) {
40
- throw new Error(`payload-redirect: unsupported redirect option for "${slug}": ${unsupported.join(', ')}`);
40
+ throw new Error(`payload-redirect: unsupported redirect option for "${slug}": ${unsupported.join(", ")}`);
41
41
  }
42
- const modes = ['path', 'paths', 'getPath'].filter((key) => Object.hasOwn(options, key));
42
+ const modes = ["path", "paths", "getPath"].filter((key) => Object.hasOwn(options, key));
43
43
  if (options.enabled === false) {
44
44
  if (modes.length) {
45
45
  throw new Error(`payload-redirect: disabled redirect config for "${slug}" cannot define a path`);
@@ -53,16 +53,16 @@ const validatePathOptions = (value, slug, locales, collection) => {
53
53
  throw new Error(`payload-redirect: collection "${slug}" must configure exactly one of path, paths, or getPath`);
54
54
  }
55
55
  if (!collection.versions ||
56
- typeof collection.versions !== 'object' ||
56
+ typeof collection.versions !== "object" ||
57
57
  !collection.versions.drafts) {
58
58
  throw new Error(`payload-redirect: automatic redirects for "${slug}" require versions.drafts`);
59
59
  }
60
- if (Object.hasOwn(options, 'path')) {
61
- if (typeof options.path !== 'string' || !isValidPathTemplate(options.path)) {
60
+ if (Object.hasOwn(options, "path")) {
61
+ if (typeof options.path !== "string" || !isValidPathTemplate(options.path)) {
62
62
  throw new Error(`payload-redirect: collections.${slug}.path must be a valid site-relative template`);
63
63
  }
64
64
  }
65
- else if (Object.hasOwn(options, 'paths')) {
65
+ else if (Object.hasOwn(options, "paths")) {
66
66
  if (locales.length === 0) {
67
67
  throw new Error(`payload-redirect: collections.${slug}.paths requires Payload localization`);
68
68
  }
@@ -73,7 +73,7 @@ const validatePathOptions = (value, slug, locales, collection) => {
73
73
  }
74
74
  }
75
75
  }
76
- else if (typeof options.getPath !== 'function') {
76
+ else if (typeof options.getPath !== "function") {
77
77
  throw new Error(`payload-redirect: collections.${slug}.getPath must be a function`);
78
78
  }
79
79
  };
@@ -87,7 +87,7 @@ const selectedCollectionOptions = (collection, options) => {
87
87
  const validateOptions = (config, options) => {
88
88
  const locales = localeCodes(config);
89
89
  if (options.localePrefixes !== undefined) {
90
- const prefixes = assertLocaleMap(options.localePrefixes, locales, 'localePrefixes');
90
+ const prefixes = assertLocaleMap(options.localePrefixes, locales, "localePrefixes");
91
91
  for (const [locale, prefix] of Object.entries(prefixes)) {
92
92
  if (!isValidLocalePrefix(prefix)) {
93
93
  throw new Error(`payload-redirect: localePrefixes.${locale} must be a site-relative path prefix`);
@@ -135,7 +135,7 @@ const definedRedirectsPlugin = definePlugin({
135
135
  validateOptions(config, options);
136
136
  const registeredCount = config.plugins?.filter((plugin) => plugin.slug === PLUGIN_SLUG).length ?? 0;
137
137
  if (registeredCount > 1) {
138
- throw new Error('payload-redirect: register redirects() only once in config.plugins');
138
+ throw new Error("payload-redirect: register redirects() only once in config.plugins");
139
139
  }
140
140
  const redirectsCollection = createRedirectsCollection(options.overrides);
141
141
  const collectionSlug = redirectsCollection.slug || DEFAULT_COLLECTION_SLUG;
@@ -152,3 +152,4 @@ const definedRedirectsPlugin = definePlugin({
152
152
  },
153
153
  });
154
154
  export const redirects = (options = {}) => definedRedirectsPlugin(options);
155
+ //# sourceMappingURL=payload-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payload-plugin.js","sourceRoot":"","sources":["../../src/plugin/payload-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,YAAY,EAAe,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EAAE,mBAAmB,EAAE,MAAM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AAE,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,KAAK,cAAc,CAAC,EAAE,CAAC;YACpE,MAAM,IAAI,KAAK,CACb,sCAAsC,cAAc,qHAAqH,CAC1K,CAAC;QACJ,CAAC;QAED,OAAO;YACL,GAAG,MAAM;YACT,WAAW,EAAE;gBACX,GAAG,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAC/C,sBAAsB,CAAC,UAAU,EAAE,OAAO,EAAE,cAAc,CAAC,CAC5D;gBACD,mBAAmB;aACpB;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,OAAO,GAAqB,EAAE,EAAU,EAAE,CAClE,sBAAsB,CAAC,OAAO,CAAC,CAAC","sourcesContent":["import { type CollectionConfig, type Config, definePlugin, type Plugin } from \"payload\";\nimport { createRedirect } from \"#redirect/core/redirects/auto/create-redirect\";\nimport { createRedirectsCollection } from \"#redirect/core/redirects/collection/collection\";\nimport { isValidLocalePrefix } from \"#redirect/core/url/published-path\";\nimport { isValidPathTemplate } from \"#redirect/core/url/route-params\";\nimport type { RedirectCollectionOptions, RedirectsOptions } from \"./types.js\";\n\nconst PLUGIN_SLUG = \"@klnap/payload-redirect\";\nconst DEFAULT_COLLECTION_SLUG = \"redirects\";\nconst PATH_OPTIONS = new Set([\"enabled\", \"path\", \"paths\", \"getPath\"]);\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst localeCodes = (config: Config): string[] => {\n const locales = config.localization === false ? undefined : config.localization?.locales;\n return Array.isArray(locales)\n ? locales.map((locale) =>\n typeof locale === \"string\" ? locale : (locale as { code: string }).code,\n )\n : [];\n};\n\nconst assertLocaleMap = (\n value: unknown,\n locales: string[],\n name: string,\n): Record<string, string> => {\n const map = asRecord(value);\n if (!map) throw new Error(`payload-redirect: ${name} must be a locale map`);\n const missing = locales.filter((locale) => !Object.hasOwn(map, locale));\n const unknown = Object.keys(map).filter((locale) => !locales.includes(locale));\n if (missing.length || unknown.length) {\n throw new Error(\n `payload-redirect: ${name} has invalid locales (missing: ${missing.join(\", \") || \"none\"}; unknown: ${unknown.join(\", \") || \"none\"})`,\n );\n }\n for (const [locale, path] of Object.entries(map)) {\n if (typeof path !== \"string\") {\n throw new Error(`payload-redirect: ${name}.${locale} must be a string`);\n }\n }\n return map as Record<string, string>;\n};\n\nconst validatePathOptions = (\n value: unknown,\n slug: string,\n locales: string[],\n collection: CollectionConfig,\n): void => {\n const options = asRecord(value);\n if (!options)\n throw new Error(`payload-redirect: redirect config for \"${slug}\" must be an object`);\n\n const unsupported = Object.keys(options).filter((key) => !PATH_OPTIONS.has(key));\n if (unsupported.length) {\n throw new Error(\n `payload-redirect: unsupported redirect option for \"${slug}\": ${unsupported.join(\", \")}`,\n );\n }\n\n const modes = [\"path\", \"paths\", \"getPath\"].filter((key) => Object.hasOwn(options, key));\n if (options.enabled === false) {\n if (modes.length) {\n throw new Error(\n `payload-redirect: disabled redirect config for \"${slug}\" cannot define a path`,\n );\n }\n return;\n }\n if (options.enabled !== undefined && options.enabled !== true) {\n throw new Error(`payload-redirect: redirect config for \"${slug}\" enabled must be a boolean`);\n }\n if (modes.length !== 1) {\n throw new Error(\n `payload-redirect: collection \"${slug}\" must configure exactly one of path, paths, or getPath`,\n );\n }\n if (\n !collection.versions ||\n typeof collection.versions !== \"object\" ||\n !collection.versions.drafts\n ) {\n throw new Error(`payload-redirect: automatic redirects for \"${slug}\" require versions.drafts`);\n }\n\n if (Object.hasOwn(options, \"path\")) {\n if (typeof options.path !== \"string\" || !isValidPathTemplate(options.path)) {\n throw new Error(\n `payload-redirect: collections.${slug}.path must be a valid site-relative template`,\n );\n }\n } else if (Object.hasOwn(options, \"paths\")) {\n if (locales.length === 0) {\n throw new Error(`payload-redirect: collections.${slug}.paths requires Payload localization`);\n }\n const paths = assertLocaleMap(options.paths, locales, `collections.${slug}.paths`);\n for (const [locale, path] of Object.entries(paths)) {\n if (!isValidPathTemplate(path)) {\n throw new Error(\n `payload-redirect: collections.${slug}.paths.${locale} must be a valid site-relative template`,\n );\n }\n }\n } else if (typeof options.getPath !== \"function\") {\n throw new Error(`payload-redirect: collections.${slug}.getPath must be a function`);\n }\n};\n\nconst selectedCollectionOptions = (\n collection: CollectionConfig,\n options: RedirectsOptions,\n): unknown => {\n const central = asRecord(options.collections);\n if (central && Object.hasOwn(central, collection.slug)) {\n return central[collection.slug];\n }\n return asRecord(collection.custom)?.redirect;\n};\n\nconst validateOptions = (config: Config, options: RedirectsOptions): void => {\n const locales = localeCodes(config);\n if (options.localePrefixes !== undefined) {\n const prefixes = assertLocaleMap(options.localePrefixes, locales, \"localePrefixes\");\n for (const [locale, prefix] of Object.entries(prefixes)) {\n if (!isValidLocalePrefix(prefix)) {\n throw new Error(\n `payload-redirect: localePrefixes.${locale} must be a site-relative path prefix`,\n );\n }\n }\n }\n\n for (const slug of Object.keys(asRecord(options.collections) ?? {})) {\n if (!config.collections?.some((collection) => collection.slug === slug)) {\n throw new Error(`payload-redirect: configured collection \"${slug}\" is not registered`);\n }\n }\n\n for (const collection of config.collections ?? []) {\n const selected = selectedCollectionOptions(collection, options);\n if (selected === undefined) continue;\n validatePathOptions(selected, collection.slug, locales, collection);\n }\n};\n\nconst wireCollectionRedirect = (\n collection: CollectionConfig,\n options: RedirectsOptions,\n collectionSlug: string,\n): CollectionConfig => {\n const selected = selectedCollectionOptions(collection, options);\n const record = asRecord(selected);\n if (!record || record.enabled === false) return collection;\n\n const afterChange = collection.hooks?.afterChange;\n const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];\n const redirectOptions = selected as RedirectCollectionOptions;\n\n return {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [\n ...hooks,\n createRedirect({\n collectionSlug,\n pathOptions: redirectOptions,\n localePrefixes: options.localePrefixes,\n }),\n ],\n },\n };\n};\n\nconst definedRedirectsPlugin = definePlugin<RedirectsOptions>({\n slug: PLUGIN_SLUG,\n plugin: ({ config, ...options }) => {\n validateOptions(config, options);\n const registeredCount =\n config.plugins?.filter((plugin) => plugin.slug === PLUGIN_SLUG).length ?? 0;\n if (registeredCount > 1) {\n throw new Error(\"payload-redirect: register redirects() only once in config.plugins\");\n }\n\n const redirectsCollection = createRedirectsCollection(options.overrides);\n const collectionSlug = redirectsCollection.slug || DEFAULT_COLLECTION_SLUG;\n if (config.collections?.some(({ slug }) => slug === collectionSlug)) {\n throw new Error(\n `payload-redirect: collection slug \"${collectionSlug}\" is already registered; configure it with redirects({ overrides: { slug } }) instead of defining a host collection`,\n );\n }\n\n return {\n ...config,\n collections: [\n ...(config.collections ?? []).map((collection) =>\n wireCollectionRedirect(collection, options, collectionSlug),\n ),\n redirectsCollection,\n ],\n };\n },\n});\n\nexport const redirects = (options: RedirectsOptions = {}): Plugin =>\n definedRedirectsPlugin(options);\n"]}
@@ -1,7 +1,7 @@
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>;
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
5
  type LocaleMap = string extends LocaleCode ? Record<string, string> : Record<LocaleCode, string>;
6
6
  export type RedirectCollectionOptions<TSlug extends CollectionSlug = CollectionSlug> = RedirectPathOptions<TSlug>;
7
7
  export type RedirectsOptions = {
@@ -1 +1,2 @@
1
1
  export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/plugin/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { CollectionSlug } from \"payload\";\nimport type { RedirectPathOptions } from \"#redirect/core/redirects/auto/types\";\nimport type { RedirectCollectionOverrides } from \"#redirect/core/redirects/collection/types\";\n\ntype LocaleCode = Extract<import(\"payload\").TypedLocale, string>;\ntype LocaleMap = string extends LocaleCode ? Record<string, string> : Record<LocaleCode, string>;\n\nexport type RedirectCollectionOptions<TSlug extends CollectionSlug = CollectionSlug> =\n RedirectPathOptions<TSlug>;\n\nexport type RedirectsOptions = {\n /** Payload locale codes map to explicit site-relative prefixes; omission means no prefix. */\n localePrefixes?: LocaleMap;\n /** Each entry opts that collection into automatic redirects. Central entries replace local config. */\n collections?: { [TSlug in CollectionSlug]?: RedirectCollectionOptions<TSlug> };\n /** Native collection overrides for the plugin-owned redirects collection. */\n overrides?: RedirectCollectionOverrides;\n};\n"]}