@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,49 +1,33 @@
1
1
  import { REDIRECT_CONTEXT_KEYS } from '../../context-keys.js';
2
- import { getRequestLocales, hasLocalizedDraftStatus, isIdentifierLocalized, listLocales, } from './locales.js';
3
- import { isDraftSave, isPublishIntent, isUnpublishedStatus } from './publish-intent.js';
4
- import { transitionForLocale } from './transition-for-locale.js';
5
- export const getPublicationTransition = async (args, options) => {
6
- const { req, doc, collection, data } = args;
7
- const publishIntent = isPublishIntent(data);
2
+ import { getRequestLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from './locales.js';
3
+ import { isDraftSave, isLocalePublished } from './publish-intent.js';
4
+ import { fetchLocalePublishedDoc } from './versions/document-locale.js';
5
+ import { fetchPublishedVersionPages } from './versions/version-pages.js';
6
+ export const getPublicationTransition = async (args) => {
7
+ const { req, doc, collection } = args;
8
8
  if (!collection.versions?.drafts)
9
9
  return [];
10
- if (isDraftSave(req))
10
+ if (isDraftSave(req) || req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
11
11
  return [];
12
- if (req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
13
- return [];
14
- const docRecord = doc;
15
- if (isUnpublishedStatus(docRecord._status) && !hasLocalizedDraftStatus(collection)) {
16
- return [];
17
- }
18
- let locales = getRequestLocales(req);
19
- const localizedField = isIdentifierLocalized(collection, options.identifier);
20
12
  const docId = doc.id;
21
- const publishAllLocales = req.query?.publishAllLocales === 'true' || req.query?.publishAllLocales === true;
22
- if (locales.length === 0 && publishAllLocales) {
23
- locales = listLocales(req);
24
- }
25
- if (locales.length === 0 &&
26
- localizedField &&
27
- hasLocalizedDraftStatus(collection) &&
28
- docRecord._status &&
29
- typeof docRecord._status === 'object') {
30
- locales = Object.entries(docRecord._status)
31
- .filter(([, value]) => value === 'published')
32
- .map(([code]) => code);
33
- }
13
+ const locales = getRequestLocales(req, doc._status);
14
+ const localizeStatus = hasLocalizedDraftStatus(collection);
15
+ const defaultLocale = resolveDefaultLocale(req);
34
16
  const transitions = [];
35
17
  for (const locale of locales) {
36
- const t = await transitionForLocale({
18
+ const currentDoc = await fetchLocalePublishedDoc({ req, collection, docId, locale });
19
+ if (!currentDoc || !isLocalePublished(currentDoc._status, locale ?? ''))
20
+ continue;
21
+ const publishedDocs = (await fetchPublishedVersionPages({
37
22
  req,
38
- collection,
23
+ collectionSlug: collection.slug,
39
24
  docId,
40
25
  locale,
41
- identifier: options.identifier,
42
- localizedField,
43
- hookDoc: docRecord,
44
- publishIntent,
45
- });
46
- transitions.push(t);
26
+ versionFilter: { localizeStatus, defaultLocale },
27
+ }))
28
+ .map((row) => row.version)
29
+ .filter((version) => Boolean(version));
30
+ transitions.push({ locale, currentDoc, publishedDocs });
47
31
  }
48
32
  return transitions;
49
33
  };
@@ -1,6 +1,8 @@
1
- import type { CollectionConfig, PayloadRequest } from 'payload';
2
- export declare const listLocales: (req: PayloadRequest) => string[];
3
- export declare const getRequestLocales: (req: PayloadRequest) => string[];
4
- export declare const hasLocalizedDraftStatus: (collection: CollectionConfig) => boolean;
5
- export declare const isIdentifierLocalized: (collection: CollectionConfig, identifier: string) => boolean;
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare const getRequestLocales: (req: PayloadRequest, status: unknown) => Array<string | undefined>;
3
+ export declare const hasLocalizedDraftStatus: (collection: {
4
+ versions?: {
5
+ drafts?: unknown;
6
+ } | false;
7
+ }) => boolean;
6
8
  export declare const resolveDefaultLocale: (req: PayloadRequest) => string | undefined;
@@ -1,38 +1,42 @@
1
- import { isIdentifierPathLocalized } from '../../identifier-field-path.js';
2
- export const listLocales = (req) => {
1
+ const listLocales = (req) => {
3
2
  const localization = req.payload.config.localization;
4
- if (!localization)
3
+ if (localization === false || !localization)
5
4
  return [];
6
- return localization.locales.map((l) => (typeof l === 'string' ? l : l.code));
5
+ return localization.locales.map((locale) => (typeof locale === 'string' ? locale : locale.code));
7
6
  };
8
- export const getRequestLocales = (req) => {
9
- if (req.query?.publishAllLocales === 'true' || req.query?.publishAllLocales === true) {
10
- return listLocales(req);
7
+ export const getRequestLocales = (req, status) => {
8
+ const localization = listLocales(req);
9
+ if (localization.length === 0)
10
+ return [undefined];
11
+ const specificLocale = typeof req.query?.publishSpecificLocale === 'string'
12
+ ? req.query.publishSpecificLocale
13
+ : undefined;
14
+ if (specificLocale && specificLocale !== 'all')
15
+ return [specificLocale];
16
+ if (specificLocale === 'all' ||
17
+ req.query?.publishAllLocales === 'true' ||
18
+ req.query?.publishAllLocales === true) {
19
+ return localization;
11
20
  }
12
- const locale = (typeof req.query?.publishSpecificLocale === 'string' && req.query.publishSpecificLocale) ||
13
- (typeof req.query?.locale === 'string' && req.query.locale) ||
14
- (typeof req.locale === 'string' ? req.locale : undefined);
15
- if (locale && locale !== 'all')
16
- return [locale];
17
- const all = listLocales(req);
18
- if (all.length === 0)
19
- return ['en'];
20
- return [];
21
+ const requestedLocale = typeof req.query?.locale === 'string' ? req.query.locale : undefined;
22
+ if (requestedLocale && requestedLocale !== 'all')
23
+ return [requestedLocale];
24
+ if (requestedLocale === 'all')
25
+ return localization;
26
+ if (status && typeof status === 'object' && !Array.isArray(status)) {
27
+ return Object.entries(status)
28
+ .filter(([, value]) => value === 'published')
29
+ .map(([locale]) => locale);
30
+ }
31
+ if (typeof req.locale === 'string')
32
+ return [req.locale];
33
+ return status === 'published' ? localization : [];
21
34
  };
22
35
  export const hasLocalizedDraftStatus = (collection) => {
23
- const versions = collection.versions;
24
- if (!versions || typeof versions !== 'object' || !('drafts' in versions))
25
- return false;
26
- const drafts = versions.drafts;
27
- return typeof drafts === 'object' && drafts !== null && drafts.localizeStatus === true;
28
- };
29
- export const isIdentifierLocalized = (collection, identifier) => {
30
- return isIdentifierPathLocalized(collection.fields, identifier);
36
+ const drafts = collection.versions === false ? undefined : collection.versions?.drafts;
37
+ return Boolean(drafts && typeof drafts === 'object' && 'localizeStatus' in drafts && drafts.localizeStatus);
31
38
  };
32
39
  export const resolveDefaultLocale = (req) => {
33
40
  const localization = req.payload.config.localization;
34
- if (typeof localization === 'object' && localization && 'defaultLocale' in localization) {
35
- return String(localization.defaultLocale);
36
- }
37
- return undefined;
41
+ return localization ? localization.defaultLocale : undefined;
38
42
  };
@@ -1,5 +1,3 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  export declare const isDraftSave: (req: PayloadRequest) => boolean;
3
- export declare const isUnpublishedStatus: (status: unknown) => boolean;
4
- export declare const isPublishIntent: (data: unknown) => boolean;
5
- export declare const isLocalePublished: (status: unknown, locale: string, localizeStatus: boolean) => boolean;
3
+ export declare const isLocalePublished: (status: unknown, locale: string) => boolean;
@@ -1,31 +1,7 @@
1
1
  export const isDraftSave = (req) => req.query?.draft === 'true' || req.query?.draft === true;
2
- export const isUnpublishedStatus = (status) => {
3
- if (status === 'published')
4
- return false;
5
- if (status === 'draft' || status == null)
6
- return true;
7
- if (typeof status === 'object') {
8
- return !Object.values(status).includes('published');
9
- }
10
- return true;
11
- };
12
- export const isPublishIntent = (data) => {
13
- if (!data || typeof data !== 'object')
14
- return false;
15
- const status = data._status;
16
- if (status === 'published')
17
- return true;
18
- if (status && typeof status === 'object') {
19
- return Object.values(status).includes('published');
20
- }
21
- return false;
22
- };
23
- export const isLocalePublished = (status, locale, localizeStatus) => {
2
+ export const isLocalePublished = (status, locale) => {
24
3
  if (typeof status === 'object' && status !== null) {
25
4
  return status[locale] === 'published';
26
5
  }
27
- if (status === 'published') {
28
- return !localizeStatus;
29
- }
30
- return false;
6
+ return status === 'published';
31
7
  };
@@ -1,9 +1,7 @@
1
- import type { CollectionConfig, PayloadRequest, TypedLocale } from 'payload';
2
- export declare const toTypedLocale: (locale: string) => TypedLocale;
3
- export declare const fetchLocalePublishedDoc: ({ req, collection, docId, locale, draft, }: {
1
+ import type { CollectionConfig, PayloadRequest } from 'payload';
2
+ export declare const fetchLocalePublishedDoc: ({ req, collection, docId, locale, }: {
4
3
  req: PayloadRequest;
5
4
  collection: CollectionConfig;
6
5
  docId: string | number;
7
- locale: string;
8
- draft?: boolean;
9
- }) => Promise<Record<string, unknown> | undefined>;
6
+ locale?: string;
7
+ }) => Promise<Record<string, unknown>>;
@@ -1,18 +1,9 @@
1
- export const toTypedLocale = (locale) => locale;
2
- export const fetchLocalePublishedDoc = async ({ req, collection, docId, locale, draft = false, }) => {
3
- try {
4
- return (await req.payload.findByID({
5
- collection: collection.slug,
6
- id: docId,
7
- locale: toTypedLocale(locale),
8
- fallbackLocale: false,
9
- depth: 0,
10
- draft,
11
- overrideAccess: true,
12
- req,
13
- }));
14
- }
15
- catch {
16
- return undefined;
17
- }
18
- };
1
+ export const fetchLocalePublishedDoc = async ({ req, collection, docId, locale, }) => (await req.payload.findByID({
2
+ collection: collection.slug,
3
+ id: docId,
4
+ ...(locale ? { locale: locale } : {}),
5
+ fallbackLocale: false,
6
+ depth: 0,
7
+ overrideAccess: true,
8
+ req,
9
+ }));
@@ -1,20 +1,12 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import { type VersionRow } from './version-rows.js';
3
- export declare const fetchPublishedVersionPages: ({ req, collectionSlug, docId, locale, versionLocale, versionFilter, }: {
3
+ export declare const fetchPublishedVersionPages: ({ req, collectionSlug, docId, locale, versionFilter, }: {
4
4
  req: PayloadRequest;
5
5
  collectionSlug: string;
6
6
  docId: string | number;
7
- locale: string;
8
- versionLocale?: string;
7
+ locale?: string;
9
8
  versionFilter?: {
10
9
  localizeStatus?: boolean;
11
10
  defaultLocale?: string;
12
- identifier?: string;
13
11
  };
14
12
  }) => Promise<VersionRow[]>;
15
- export declare const fetchVersionHistoryPages: ({ req, collectionSlug, docId, versionLocale, }: {
16
- req: PayloadRequest;
17
- collectionSlug: string;
18
- docId: string | number;
19
- versionLocale?: string;
20
- }) => Promise<VersionRow[]>;
@@ -1,10 +1,8 @@
1
- import { toTypedLocale } from './document-locale.js';
2
1
  import { isPublishedVersionRow } from './version-rows.js';
3
- export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, locale, versionLocale, versionFilter, }) => {
2
+ export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, locale, versionFilter, }) => {
4
3
  const published = [];
5
4
  let page = 1;
6
5
  const limit = 50;
7
- const queryLocale = versionLocale ?? locale;
8
6
  while (true) {
9
7
  const result = await req.payload.findVersions({
10
8
  collection: collectionSlug,
@@ -13,39 +11,15 @@ export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, l
13
11
  depth: 0,
14
12
  page,
15
13
  limit,
16
- ...(versionLocale === undefined ? undefined : { locale: toTypedLocale(queryLocale) }),
14
+ ...(locale ? { locale: locale } : {}),
15
+ fallbackLocale: false,
17
16
  overrideAccess: true,
18
17
  req,
19
18
  });
20
- const rows = result.docs.filter((row) => isPublishedVersionRow(row, locale, versionFilter));
21
- published.push(...rows);
19
+ published.push(...result.docs.filter((row) => isPublishedVersionRow(row, locale, versionFilter)));
22
20
  if (!result.hasNextPage)
23
21
  break;
24
22
  page += 1;
25
23
  }
26
24
  return published;
27
25
  };
28
- export const fetchVersionHistoryPages = async ({ req, collectionSlug, docId, versionLocale, }) => {
29
- const rows = [];
30
- let page = 1;
31
- const limit = 50;
32
- while (true) {
33
- const result = await req.payload.findVersions({
34
- collection: collectionSlug,
35
- where: { parent: { equals: docId } },
36
- sort: '-updatedAt',
37
- depth: 0,
38
- page,
39
- limit,
40
- ...(versionLocale === undefined ? undefined : { locale: toTypedLocale(versionLocale) }),
41
- overrideAccess: true,
42
- req,
43
- });
44
- const docs = result.docs.filter((row) => !row.snapshot && !row.autosave);
45
- rows.push(...docs);
46
- if (!result.hasNextPage)
47
- break;
48
- page += 1;
49
- }
50
- return rows;
51
- };
@@ -7,13 +7,7 @@ export type VersionRow = {
7
7
  published_locale?: string;
8
8
  version?: Record<string, unknown>;
9
9
  };
10
- export declare const isPublishedVersionRow: (row: VersionRow, locale: string, options?: {
10
+ export declare const isPublishedVersionRow: (row: VersionRow, locale: string | undefined, options?: {
11
11
  localizeStatus?: boolean;
12
12
  defaultLocale?: string;
13
- identifier?: string;
14
13
  }) => boolean;
15
- export declare const pickPublishedVersions: (rows: VersionRow[], locale: string, options?: {
16
- localizeStatus?: boolean;
17
- defaultLocale?: string;
18
- identifier?: string;
19
- }) => VersionRow[];
@@ -2,40 +2,16 @@ export const isPublishedVersionRow = (row, locale, options) => {
2
2
  if (row.snapshot || row.autosave)
3
3
  return false;
4
4
  const publishedLocale = row.publishedLocale ?? row.published_locale;
5
- if (publishedLocale) {
5
+ if (publishedLocale)
6
6
  return publishedLocale === locale;
7
- }
8
7
  const status = row.version?._status;
9
8
  if (status === 'draft')
10
9
  return false;
11
- if (options?.localizeStatus && options.identifier) {
12
- const field = row.version?.[options.identifier];
13
- if (typeof field === 'string') {
14
- if (typeof status === 'object' && status !== null) {
15
- return status[locale] === 'published';
16
- }
17
- return status === 'published';
18
- }
19
- if (field && typeof field === 'object' && !Array.isArray(field)) {
20
- if (!(locale in field))
21
- return false;
22
- if (typeof status === 'object' && status !== null) {
23
- return status[locale] === 'published';
24
- }
25
- if (status === 'published')
26
- return true;
27
- return false;
28
- }
29
- }
30
- if (status && typeof status === 'object') {
31
- return status[locale] === 'published';
10
+ if (status && typeof status === 'object' && !Array.isArray(status)) {
11
+ return locale !== undefined && status[locale] === 'published';
32
12
  }
33
13
  if (status === 'published') {
34
- if (options?.localizeStatus && options.defaultLocale) {
35
- return locale === options.defaultLocale;
36
- }
37
- return true;
14
+ return !options?.localizeStatus || locale !== undefined;
38
15
  }
39
16
  return false;
40
17
  };
41
- export const pickPublishedVersions = (rows, locale, options) => rows.filter((row) => isPublishedVersionRow(row, locale, options));
@@ -1,9 +1,30 @@
1
+ import type { CollectionSlug, DataFromCollectionSlug, TypedLocale } from 'payload';
2
+ export type RedirectPathOptions<TSlug extends CollectionSlug = CollectionSlug> = {
3
+ enabled?: true;
4
+ path: string;
5
+ paths?: never;
6
+ getPath?: never;
7
+ } | {
8
+ enabled?: true;
9
+ path?: never;
10
+ paths: string extends Extract<TypedLocale, string> ? Record<string, string> : Record<Extract<TypedLocale, string>, string>;
11
+ getPath?: never;
12
+ } | {
13
+ enabled?: true;
14
+ path?: never;
15
+ paths?: never;
16
+ getPath: (args: {
17
+ doc: DataFromCollectionSlug<TSlug>;
18
+ locale: TypedLocale | undefined;
19
+ }) => string | null;
20
+ } | {
21
+ enabled: false;
22
+ path?: never;
23
+ paths?: never;
24
+ getPath?: never;
25
+ };
1
26
  export type PublicationTransition = {
2
- published: boolean;
3
27
  locale?: string;
4
- previous?: string;
5
- current?: string;
6
- };
7
- export type GetPublicationTransitionOptions = {
8
- identifier: string;
28
+ currentDoc: Record<string, unknown>;
29
+ publishedDocs: Record<string, unknown>[];
9
30
  };
@@ -1,13 +1,8 @@
1
1
  import type { Access, PayloadRequest } from 'payload';
2
- export type RedirectsCollectionAccess = {
3
- read?: Access;
4
- create?: Access;
5
- update?: Access;
6
- delete?: Access;
2
+ export declare const isInternalRedirectWrite: (req: PayloadRequest) => boolean;
3
+ export declare const defaultRedirectAccess: {
4
+ read: Access;
5
+ create: Access;
6
+ update: Access;
7
+ delete: Access;
7
8
  };
8
- export declare const isRedirectInternalRequest: (req: PayloadRequest) => boolean;
9
- export declare const redirectReadAccess: Access;
10
- export declare const redirectCreateAccess: Access;
11
- export declare const redirectUpdateAccess: Access;
12
- export declare const redirectDeleteAccess: Access;
13
- export declare const mergeRedirectsAccess: (base: RedirectsCollectionAccess | undefined, overrides: RedirectsCollectionAccess | undefined) => RedirectsCollectionAccess;
@@ -1,26 +1,9 @@
1
1
  import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
2
- export const isRedirectInternalRequest = (req) => Boolean(req.context?.[REDIRECT_CONTEXT_KEYS.internal]);
3
- export const redirectReadAccess = () => true;
4
- /**
5
- * Manual redirect rules are human-managed. A service principal (type `service`) is refused, so
6
- * automation cannot write them unless a host grants it explicitly through its own access override.
7
- * Automatic rules are written by the package itself under the internal context and are not affected.
8
- */
9
- const isHumanSignedIn = (req) => Boolean(req.user) && req.user.type !== 'service';
10
- export const redirectCreateAccess = ({ req }) => {
11
- if (isRedirectInternalRequest(req))
12
- return true;
13
- return isHumanSignedIn(req);
2
+ export const isInternalRedirectWrite = (req) => Boolean(req.context?.[REDIRECT_CONTEXT_KEYS.internal]);
3
+ const isHumanUser = (req) => Boolean(req.user) && req.user.type !== 'service';
4
+ export const defaultRedirectAccess = {
5
+ read: (() => true),
6
+ create: (({ req }) => isInternalRedirectWrite(req) || isHumanUser(req)),
7
+ update: (({ req }) => isInternalRedirectWrite(req) || isHumanUser(req)),
8
+ delete: (({ req }) => isHumanUser(req)),
14
9
  };
15
- export const redirectUpdateAccess = ({ req }) => {
16
- if (isRedirectInternalRequest(req))
17
- return true;
18
- return isHumanSignedIn(req);
19
- };
20
- export const redirectDeleteAccess = ({ req }) => isHumanSignedIn(req);
21
- export const mergeRedirectsAccess = (base, overrides) => ({
22
- read: base?.read ?? overrides?.read ?? redirectReadAccess,
23
- create: base?.create ?? overrides?.create ?? redirectCreateAccess,
24
- update: base?.update ?? overrides?.update ?? redirectUpdateAccess,
25
- delete: base?.delete ?? overrides?.delete ?? redirectDeleteAccess,
26
- });
@@ -1,11 +1,3 @@
1
1
  import type { CollectionConfig } from 'payload';
2
- import { type RedirectsCollectionAccess } from './access.js';
3
- export type CreateRedirectsCollectionOptions = {
4
- base?: CollectionConfig;
5
- /** Soft-delete (trash). Default true; set false to disable. Base collection `trash` wins when set. */
6
- trash?: boolean;
7
- /** Plugin-level access overrides (applied when base collection omits a handler). */
8
- access?: RedirectsCollectionAccess;
9
- };
10
- export declare const createRedirectsCollection: (options: CreateRedirectsCollectionOptions) => CollectionConfig;
11
- export type { RedirectsCollectionAccess } from './access.js';
2
+ import type { RedirectCollectionOverrides } from './types.js';
3
+ export declare const createRedirectsCollection: (overrides?: RedirectCollectionOverrides) => CollectionConfig;
@@ -1,41 +1,38 @@
1
- import { mergeRedirectsAccess, redirectCreateAccess, redirectDeleteAccess, redirectReadAccess, redirectUpdateAccess, } from './access.js';
1
+ import { defaultRedirectAccess } from './access.js';
2
2
  import { createDuplicateBeforeChange } from './duplicate-guard.js';
3
- import { buildRedirectFields, mergeRedirectFields } from './fields.js';
3
+ import { assertRedirectFields, buildRedirectFields, mergeRedirectFields } from './fields.js';
4
4
  import { createRedirectOriginBeforeChange } from './origin-hook.js';
5
5
  const DEFAULT_SLUG = 'redirects';
6
- export const createRedirectsCollection = (options) => {
7
- const base = options.base;
8
- const slug = base?.slug ?? DEFAULT_SLUG;
9
- const fields = base?.fields ? mergeRedirectFields(base.fields) : buildRedirectFields();
10
- const existingHooks = base?.hooks ?? {};
11
- const trash = base?.trash ?? options.trash ?? true;
12
- const access = mergeRedirectsAccess(base?.access, options.access);
6
+ export const createRedirectsCollection = (overrides = {}) => {
7
+ const defaultFields = buildRedirectFields();
8
+ const fields = overrides.fields
9
+ ? mergeRedirectFields(overrides.fields({ defaultFields }))
10
+ : defaultFields;
11
+ assertRedirectFields(fields);
12
+ const slug = overrides.slug ?? DEFAULT_SLUG;
13
+ const existingHooks = overrides.hooks ?? {};
14
+ const access = { ...defaultRedirectAccess, ...overrides.access };
13
15
  return {
14
- ...base,
16
+ ...overrides,
15
17
  slug,
16
- trash,
17
- versions: base?.versions ?? false,
18
- timestamps: base?.timestamps ?? true,
18
+ trash: overrides.trash ?? true,
19
+ versions: overrides.versions ?? false,
20
+ timestamps: overrides.timestamps ?? true,
19
21
  admin: {
20
22
  useAsTitle: 'from',
21
- defaultColumns: ['from', 'to', 'StatusCode', 'origin', 'enabled', 'updatedAt'],
23
+ defaultColumns: ['from', 'to', 'statusCode', 'origin', 'enabled', 'updatedAt'],
22
24
  listSearchableFields: ['from', 'to'],
23
- ...base?.admin,
24
- },
25
- defaultSort: 'from',
26
- access: {
27
- read: access.read ?? redirectReadAccess,
28
- create: access.create ?? redirectCreateAccess,
29
- update: access.update ?? redirectUpdateAccess,
30
- delete: access.delete ?? redirectDeleteAccess,
25
+ ...overrides.admin,
31
26
  },
27
+ defaultSort: overrides.defaultSort ?? 'from',
28
+ access,
32
29
  fields,
33
30
  hooks: {
34
31
  ...existingHooks,
35
32
  beforeChange: [
36
33
  ...(existingHooks.beforeChange ?? []),
37
34
  createRedirectOriginBeforeChange(),
38
- createDuplicateBeforeChange(),
35
+ createDuplicateBeforeChange(slug),
39
36
  ],
40
37
  },
41
38
  };
@@ -18,4 +18,4 @@ export declare const resolveDuplicateGuardExcludeId: (operation: string, origina
18
18
  * loop walk for any update that omits `from` or `to`.
19
19
  */
20
20
  export declare const effectiveRuleData: (operation: string, data: Record<string, unknown> | undefined, originalDoc: Record<string, unknown> | null | undefined) => Record<string, unknown> | undefined;
21
- export declare const createDuplicateBeforeChange: () => CollectionBeforeChangeHook;
21
+ export declare const createDuplicateBeforeChange: (collectionSlug?: string) => CollectionBeforeChangeHook;
@@ -3,7 +3,6 @@ import { lockRedirectRuleGraph } from './graph-lock.js';
3
3
  import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, validateDestinationForStatus, } from '../model/status-code.js';
4
4
  import { normalizeRedirectSourcePath, normalizeRelativeRedirectPath, } from '../normalize-path.js';
5
5
  import { findRedirectByFrom } from '../queries.js';
6
- import { getRedirectRuntime } from '../runtime.js';
7
6
  /** Enabled rules followed from `to` before a write is refused as unverifiable. Bounds the lookups per write. */
8
7
  export const MAX_REDIRECT_CHAIN_HOPS = 1000;
9
8
  const DUPLICATE_MESSAGE = 'A redirect rule already exists for this source path';
@@ -57,7 +56,7 @@ const resolveExcludeId = (args) => resolveDuplicateGuardExcludeId(args.operation
57
56
  * repeats a hop without reaching `from` predates this write, so it is accepted. Runs past
58
57
  * MAX_REDIRECT_CHAIN_HOPS are refused as unverifiable. One indexed lookup on `from` per hop.
59
58
  */
60
- const assertNoLoop = async (args, normalizedFrom) => {
59
+ const assertNoLoop = async (args, normalizedFrom, collectionSlug) => {
61
60
  const { data, req } = args;
62
61
  if (!data || data.enabled === false)
63
62
  return;
@@ -67,7 +66,6 @@ const assertNoLoop = async (args, normalizedFrom) => {
67
66
  if (normalizedTo === normalizedFrom) {
68
67
  throw new ValidationError({ errors: [{ message: LOOP_MESSAGE, path: 'to' }] });
69
68
  }
70
- const { collectionSlug } = getRedirectRuntime(req.payload.config);
71
69
  const excludeId = resolveExcludeId(args);
72
70
  const visited = new Set();
73
71
  let current = normalizedTo;
@@ -97,14 +95,13 @@ const assertNoLoop = async (args, normalizedFrom) => {
97
95
  }
98
96
  throw new ValidationError({ errors: [{ message: CHAIN_TOO_LONG_MESSAGE, path: 'to' }] });
99
97
  };
100
- const assertNoDuplicateFrom = async (args) => {
98
+ const assertNoDuplicateFrom = async (args, collectionSlug) => {
101
99
  const { data, req } = args;
102
100
  if (!data)
103
101
  return undefined;
104
102
  const normalizedFrom = resolveNormalizedFrom(data);
105
103
  if (!normalizedFrom)
106
104
  return undefined;
107
- const { collectionSlug } = getRedirectRuntime(req.payload.config);
108
105
  const duplicate = await findDuplicateFrom({
109
106
  req,
110
107
  collectionSlug,
@@ -114,7 +111,7 @@ const assertNoDuplicateFrom = async (args) => {
114
111
  if (duplicate) {
115
112
  throw new ValidationError({ errors: [{ message: DUPLICATE_MESSAGE, path: 'from' }] });
116
113
  }
117
- await assertNoLoop(args, normalizedFrom);
114
+ await assertNoLoop(args, normalizedFrom, collectionSlug);
118
115
  return normalizedFrom;
119
116
  };
120
117
  const normalizeRulePaths = (data) => {
@@ -142,7 +139,7 @@ const normalizeRulePaths = (data) => {
142
139
  }
143
140
  data.to = normalize(data.to, 'to');
144
141
  try {
145
- const statusCode = assertRedirectStatusCode(data.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
142
+ const statusCode = assertRedirectStatusCode(data.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
146
143
  validateDestinationForStatus(statusCode, data.to);
147
144
  }
148
145
  catch (error) {
@@ -162,7 +159,7 @@ export const effectiveRuleData = (operation, data, originalDoc) => {
162
159
  return data;
163
160
  return { ...originalDoc, ...data };
164
161
  };
165
- export const createDuplicateBeforeChange = () => {
162
+ export const createDuplicateBeforeChange = (collectionSlug = 'redirects') => {
166
163
  return async (args) => {
167
164
  const { data, req, operation, originalDoc } = args;
168
165
  if (operation === 'create' || operation === 'update') {
@@ -183,7 +180,7 @@ export const createDuplicateBeforeChange = () => {
183
180
  req,
184
181
  operation,
185
182
  originalDoc: args.originalDoc,
186
- });
183
+ }, collectionSlug);
187
184
  if (data && normalizedFrom && typeof data.from === 'string') {
188
185
  data.from = normalizedFrom;
189
186
  }
@@ -1,3 +1,4 @@
1
1
  import type { Field } from 'payload';
2
2
  export declare const buildRedirectFields: () => Field[];
3
3
  export declare const mergeRedirectFields: (existingFields: Field[]) => Field[];
4
+ export declare const assertRedirectFields: (fields: Field[]) => void;