@klnap/payload-redirect 0.3.1 → 0.4.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.
- package/CHANGELOG.md +19 -0
- package/README.md +368 -168
- package/dist/core/redirects/auto/create-global-redirect.d.ts +11 -0
- package/dist/core/redirects/auto/create-global-redirect.js +18 -0
- package/dist/core/redirects/auto/create-global-redirect.js.map +1 -0
- package/dist/core/redirects/auto/create-redirect.d.ts +10 -6
- package/dist/core/redirects/auto/create-redirect.js +18 -9
- package/dist/core/redirects/auto/create-redirect.js.map +1 -1
- package/dist/core/redirects/auto/persist-auto-rule.d.ts +1 -1
- package/dist/core/redirects/auto/persist-auto-rule.js +8 -5
- package/dist/core/redirects/auto/persist-auto-rule.js.map +1 -1
- package/dist/core/redirects/auto/publication/global-transition.d.ts +6 -0
- package/dist/core/redirects/auto/publication/global-transition.js +63 -0
- package/dist/core/redirects/auto/publication/global-transition.js.map +1 -0
- package/dist/core/redirects/auto/publication/locales.d.ts +1 -0
- package/dist/core/redirects/auto/publication/locales.js +4 -0
- package/dist/core/redirects/auto/publication/locales.js.map +1 -1
- package/dist/core/redirects/auto/types.d.ts +3 -3
- package/dist/core/redirects/auto/types.js.map +1 -1
- package/dist/core/redirects/collection/collection.js +5 -3
- package/dist/core/redirects/collection/collection.js.map +1 -1
- package/dist/core/redirects/collection/duplicate-guard.js +0 -4
- package/dist/core/redirects/collection/duplicate-guard.js.map +1 -1
- package/dist/core/redirects/collection/fields.js +0 -6
- package/dist/core/redirects/collection/fields.js.map +1 -1
- package/dist/core/redirects/collection/graph-lock.d.ts +6 -1
- package/dist/core/redirects/collection/graph-lock.js +11 -0
- package/dist/core/redirects/collection/graph-lock.js.map +1 -1
- package/dist/core/redirects/collection/origin-hook.js +3 -2
- package/dist/core/redirects/collection/origin-hook.js.map +1 -1
- package/dist/core/redirects/context-keys.d.ts +1 -1
- package/dist/core/redirects/context-keys.js +1 -1
- package/dist/core/redirects/context-keys.js.map +1 -1
- package/dist/exports/index.d.ts +1 -1
- package/dist/exports/index.js.map +1 -1
- package/dist/plugin/payload-plugin.js +54 -19
- package/dist/plugin/payload-plugin.js.map +1 -1
- package/dist/plugin/types.d.ts +7 -2
- package/dist/plugin/types.js.map +1 -1
- package/docs/FAILURE_SEMANTICS.md +25 -6
- package/package.json +1 -1
- package/dist/core/redirects/collection/access.d.ts +0 -8
- package/dist/core/redirects/collection/access.js +0 -10
- package/dist/core/redirects/collection/access.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/fields.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,2BAA2B,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAElG,MAAM,eAAe,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,EAAW,CAAC;AAEtD,MAAM,oBAAoB,GAAG,CAAC,KAAc,EAAsB,EAAE;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChD,IAAI,CAAC;QACH,OAAO,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAY,EAAE,CAAC;IAChD;QACE,IAAI,EAAE,MAAM;QACZ,IAAI,EAAE,MAAM;QACZ,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,eAAe;QACvB,QAAQ,EAAE,CAAC,KAAc,EAAE,EAAE;YAC3B,IAAI,OAAO,KA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,IAAI,QAAQ,EAAE,CAAC;QACpC,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;QAC9D,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAE,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAE,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACrF,MAAM,IAAI,KAAK,CACb,8DAA8D,IAAI,iBAAiB,IAAI,GAAG,CAC3F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IAChE,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QACzD,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACpF,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACtF,CAAC;AACH,CAAC,CAAC","sourcesContent":["import type { Field, Validate } from \"payload\";\nimport {\n DEFAULT_REDIRECT_ORIGIN,\n isRedirectOrigin,\n REDIRECT_ORIGIN_VALUES,\n} from \"#redirect/core/redirects/model/origin\";\nimport {\n assertRedirectStatusCode,\n DEFAULT_REDIRECT_STATUS_CODE,\n validateDestinationForStatus,\n} from \"#redirect/core/redirects/model/status-code\";\nimport { normalizeRedirectSourcePath, normalizeRelativeRedirectPath } from \"../normalize-path.js\";\n\nconst publicFieldRead = { read: () => true } as const;\n\nconst normalizeSiblingFrom = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n try {\n return normalizeRedirectSourcePath(value);\n } catch {\n return undefined;\n }\n};\n\nexport const buildRedirectFields = (): Field[] => [\n {\n name: \"from\",\n type: \"text\",\n required: true,\n unique: true,\n access: publicFieldRead,\n validate: (value: unknown) => {\n if (typeof value !== \"string\") return \"from is required\";\n if (!value.trim()) return \"from is required\";\n try {\n normalizeRedirectSourcePath(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid from path\";\n }\n },\n },\n {\n name: \"to\",\n type: \"text\",\n required: true,\n access: publicFieldRead,\n validate: (value: unknown, { siblingData }: { siblingData: Record<string, unknown> }) => {\n try {\n const statusCode = assertRedirectStatusCode(\n siblingData?.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE,\n );\n validateDestinationForStatus(statusCode, value);\n if (\n typeof value === \"string\" &&\n normalizeRelativeRedirectPath(value) === normalizeSiblingFrom(siblingData?.from)\n ) {\n return \"to must differ from from\";\n }\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid to path\";\n }\n },\n },\n {\n name: \"statusCode\",\n type: \"select\",\n label: \"Type\",\n defaultValue: String(DEFAULT_REDIRECT_STATUS_CODE),\n required: true,\n access: publicFieldRead,\n options: [\n { label: \"Permanent\", value: \"301\" },\n { label: \"Temporary\", value: \"302\" },\n ],\n validate: (value: unknown) => {\n try {\n assertRedirectStatusCode(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid statusCode\";\n }\n },\n admin: { position: \"sidebar\" },\n },\n {\n name: \"enabled\",\n type: \"checkbox\",\n defaultValue: true,\n index: true,\n access: publicFieldRead,\n admin: { position: \"sidebar\" },\n },\n {\n name: \"origin\",\n type: \"select\",\n required: true,\n defaultValue: DEFAULT_REDIRECT_ORIGIN,\n access: publicFieldRead,\n options: [\n { label: \"Manual\", value: \"manual\" },\n { label: \"Auto\", value: \"auto\" },\n ],\n validate: (value: unknown) =>\n isRedirectOrigin(value) ? true : `origin must be ${REDIRECT_ORIGIN_VALUES.join(\" or \")}`,\n admin: { position: \"sidebar\", readOnly: true },\n },\n];\n\nexport const mergeRedirectFields = (existingFields: Field[]): Field[] => {\n const defaults = buildRedirectFields();\n const existingByName = new Map(\n existingFields\n .filter(\n (field): field is Field & { name: string } =>\n \"name\" in field && typeof field.name === \"string\",\n )\n .map((field) => [field.name, field]),\n );\n const defaultNames = new Set(\n defaults\n .filter(\n (field): field is Field & { name: string } =>\n \"name\" in field && typeof field.name === \"string\",\n )\n .map((field) => field.name),\n );\n const merged = defaults.map((field) => {\n if (!(\"name\" in field) || typeof field.name !== \"string\") return field;\n const override = existingByName.get(field.name);\n if (!override) return field;\n const validate =\n \"validate\" in field && typeof field.validate === \"function\" ? field.validate : undefined;\n const overrideValidate =\n \"validate\" in override && typeof override.validate === \"function\"\n ? override.validate\n : undefined;\n return {\n ...field,\n ...override,\n ...(validate\n ? {\n validate: async (value: unknown, options: Parameters<Validate>[1]) => {\n const run = validate as Validate;\n const result = await run(value, options);\n return result === true && overrideValidate\n ? (overrideValidate as Validate)(value, options)\n : result;\n },\n }\n : {}),\n } as Field;\n });\n\n return [\n ...merged,\n ...existingFields.filter(\n (field) =>\n !(\"name\" in field) || typeof field.name !== \"string\" || !defaultNames.has(field.name),\n ),\n ];\n};\n\nexport const assertRedirectFields = (fields: Field[]): void => {\n const expected = new Map([\n [\"from\", \"text\"],\n [\"to\", \"text\"],\n [\"statusCode\", \"select\"],\n [\"enabled\", \"checkbox\"],\n [\"origin\", \"select\"],\n ]);\n const named = fields.filter(\n (field): field is Field & { name: string } => \"name\" in field && typeof field.name === \"string\",\n );\n\n for (const [name, type] of expected) {\n const matching = named.filter((field) => field.name === name);\n if (matching.length !== 1 || !(\"type\" in matching[0]!) || matching[0]!.type !== type) {\n throw new Error(\n `payload-redirect: overrides.fields must retain exactly one ${type} field named \"${name}\"`,\n );\n }\n }\n\n const from = named.find((field) => field.name === \"from\");\n const enabled = named.find((field) => field.name === \"enabled\");\n if (!from || !(\"unique\" in from) || from.unique !== true) {\n throw new Error(\"payload-redirect: overrides.fields must keep from.unique: true\");\n }\n if (!enabled || !(\"index\" in enabled) || enabled.index !== true) {\n throw new Error(\"payload-redirect: overrides.fields must keep enabled.index: true\");\n }\n};\n"]}
|
|
1
|
+
{"version":3,"file":"fields.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/fields.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,2BAA2B,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAElG,MAAM,oBAAoB,GAAG,CAAC,KAAc,EAAsB,EAAE;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChD,IAAI,CAAC;QACH,OAAO,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAY,EAAE,CAAC;IAChD;QACE,IAAI,EAAE,MAAM;QACZ,IAAI,EAAE,MAAM;QACZ,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,IAAI;QACZ,QAAQ,EAAE,CAAC,KAAc,EAAE,EAAE;YAC3B,IAAI,OAAO,KAAK,KAAK,QAAQ;gBAAE,OAAO,kBAAkB,CAAC;YACzD,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;gBAAE,OAAO,kBAAkB,CAAC;YAC7C,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AAI,QAAQ,CAAC,CAAC,CAAE,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAE,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACrF,MAAM,IAAI,KAAK,CACb,8DAA8D,IAAI,iBAAiB,IAAI,GAAG,CAC3F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IAChE,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QACzD,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACpF,CAAC;IACD,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACtF,CAAC;AACH,CAAC,CAAC","sourcesContent":["import type { Field, Validate } from \"payload\";\nimport {\n DEFAULT_REDIRECT_ORIGIN,\n isRedirectOrigin,\n REDIRECT_ORIGIN_VALUES,\n} from \"#redirect/core/redirects/model/origin\";\nimport {\n assertRedirectStatusCode,\n DEFAULT_REDIRECT_STATUS_CODE,\n validateDestinationForStatus,\n} from \"#redirect/core/redirects/model/status-code\";\nimport { normalizeRedirectSourcePath, normalizeRelativeRedirectPath } from \"../normalize-path.js\";\n\nconst normalizeSiblingFrom = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n try {\n return normalizeRedirectSourcePath(value);\n } catch {\n return undefined;\n }\n};\n\nexport const buildRedirectFields = (): Field[] => [\n {\n name: \"from\",\n type: \"text\",\n required: true,\n unique: true,\n validate: (value: unknown) => {\n if (typeof value !== \"string\") return \"from is required\";\n if (!value.trim()) return \"from is required\";\n try {\n normalizeRedirectSourcePath(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid from path\";\n }\n },\n },\n {\n name: \"to\",\n type: \"text\",\n required: true,\n validate: (value: unknown, { siblingData }: { siblingData: Record<string, unknown> }) => {\n try {\n const statusCode = assertRedirectStatusCode(\n siblingData?.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE,\n );\n validateDestinationForStatus(statusCode, value);\n if (\n typeof value === \"string\" &&\n normalizeRelativeRedirectPath(value) === normalizeSiblingFrom(siblingData?.from)\n ) {\n return \"to must differ from from\";\n }\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid to path\";\n }\n },\n },\n {\n name: \"statusCode\",\n type: \"select\",\n label: \"Type\",\n defaultValue: String(DEFAULT_REDIRECT_STATUS_CODE),\n required: true,\n options: [\n { label: \"Permanent\", value: \"301\" },\n { label: \"Temporary\", value: \"302\" },\n ],\n validate: (value: unknown) => {\n try {\n assertRedirectStatusCode(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid statusCode\";\n }\n },\n admin: { position: \"sidebar\" },\n },\n {\n name: \"enabled\",\n type: \"checkbox\",\n defaultValue: true,\n index: true,\n admin: { position: \"sidebar\" },\n },\n {\n name: \"origin\",\n type: \"select\",\n required: true,\n defaultValue: DEFAULT_REDIRECT_ORIGIN,\n options: [\n { label: \"Manual\", value: \"manual\" },\n { label: \"Auto\", value: \"auto\" },\n ],\n validate: (value: unknown) =>\n isRedirectOrigin(value) ? true : `origin must be ${REDIRECT_ORIGIN_VALUES.join(\" or \")}`,\n admin: { position: \"sidebar\", readOnly: true },\n },\n];\n\nexport const mergeRedirectFields = (existingFields: Field[]): Field[] => {\n const defaults = buildRedirectFields();\n const existingByName = new Map(\n existingFields\n .filter(\n (field): field is Field & { name: string } =>\n \"name\" in field && typeof field.name === \"string\",\n )\n .map((field) => [field.name, field]),\n );\n const defaultNames = new Set(\n defaults\n .filter(\n (field): field is Field & { name: string } =>\n \"name\" in field && typeof field.name === \"string\",\n )\n .map((field) => field.name),\n );\n const merged = defaults.map((field) => {\n if (!(\"name\" in field) || typeof field.name !== \"string\") return field;\n const override = existingByName.get(field.name);\n if (!override) return field;\n const validate =\n \"validate\" in field && typeof field.validate === \"function\" ? field.validate : undefined;\n const overrideValidate =\n \"validate\" in override && typeof override.validate === \"function\"\n ? override.validate\n : undefined;\n return {\n ...field,\n ...override,\n ...(validate\n ? {\n validate: async (value: unknown, options: Parameters<Validate>[1]) => {\n const run = validate as Validate;\n const result = await run(value, options);\n return result === true && overrideValidate\n ? (overrideValidate as Validate)(value, options)\n : result;\n },\n }\n : {}),\n } as Field;\n });\n\n return [\n ...merged,\n ...existingFields.filter(\n (field) =>\n !(\"name\" in field) || typeof field.name !== \"string\" || !defaultNames.has(field.name),\n ),\n ];\n};\n\nexport const assertRedirectFields = (fields: Field[]): void => {\n const expected = new Map([\n [\"from\", \"text\"],\n [\"to\", \"text\"],\n [\"statusCode\", \"select\"],\n [\"enabled\", \"checkbox\"],\n [\"origin\", \"select\"],\n ]);\n const named = fields.filter(\n (field): field is Field & { name: string } => \"name\" in field && typeof field.name === \"string\",\n );\n\n for (const [name, type] of expected) {\n const matching = named.filter((field) => field.name === name);\n if (matching.length !== 1 || !(\"type\" in matching[0]!) || matching[0]!.type !== type) {\n throw new Error(\n `payload-redirect: overrides.fields must retain exactly one ${type} field named \"${name}\"`,\n );\n }\n }\n\n const from = named.find((field) => field.name === \"from\");\n const enabled = named.find((field) => field.name === \"enabled\");\n if (!from || !(\"unique\" in from) || from.unique !== true) {\n throw new Error(\"payload-redirect: overrides.fields must keep from.unique: true\");\n }\n if (!enabled || !(\"index\" in enabled) || enabled.index !== true) {\n throw new Error(\"payload-redirect: overrides.fields must keep enabled.index: true\");\n }\n};\n"]}
|
|
@@ -1,2 +1,7 @@
|
|
|
1
|
-
import type { PayloadRequest } from "payload";
|
|
1
|
+
import type { CollectionBeforeOperationHook, PayloadRequest } from "payload";
|
|
2
2
|
export declare function lockRedirectRuleGraph(req: PayloadRequest): Promise<void>;
|
|
3
|
+
/**
|
|
4
|
+
* Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership
|
|
5
|
+
* or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createRedirectGraphLockBeforeOperation: () => CollectionBeforeOperationHook;
|
|
@@ -29,4 +29,15 @@ export async function lockRedirectRuleGraph(req) {
|
|
|
29
29
|
throw new Error("Redirect rule lock requires READ COMMITTED transactions.");
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership
|
|
34
|
+
* or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.
|
|
35
|
+
*/
|
|
36
|
+
export const createRedirectGraphLockBeforeOperation = () => {
|
|
37
|
+
return async ({ operation, req }) => {
|
|
38
|
+
if (operation === "create" || operation === "update") {
|
|
39
|
+
await lockRedirectRuleGraph(req);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
};
|
|
32
43
|
//# sourceMappingURL=graph-lock.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-lock.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/graph-lock.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,wBAAwB,GAAG,UAAU,CAAC;AAW5C,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,GAAmB;IAC7D,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAA2C,CAAC;IACpE,gFAAgF;IAChF,IAAI,EAAE,IAAI,IAAI;QAAE,OAAO;IACvB,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;QAAE,OAAO;IAEjE,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC;IAC9C,MAAM,OAAO,GAAG,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IACzF,MAAM,EAAE,GAAG,OAAO,EAAE,EAAsC,CAAC;IAC3D,IAAI,EAAE,IAAI,IAAI,IAAI,OAAO,EAAE,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;IAC5F,CAAC;IAED,oEAAoE;IACpE,MAAM,EAAE,CAAC,OAAO,CAAC,0CAA0C,QAAQ,KAAK,CAAC,CAAC;IAE1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACjE,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB,KAAK,gBAAgB,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\n\n/**\n * Serializes writes to the redirect rule graph. The loop and duplicate checks read committed rows,\n * so two concurrent writes that each close a cycle could both pass unless the second waits for the\n * first to commit. The lock is transaction-scoped and released at commit or rollback.\n *\n * Postgres is the supported adapter: the lock needs the request transaction and READ COMMITTED\n * isolation, and the function throws when either is missing rather than checking without it.\n * Adapters without advisory locks return without locking.\n */\nconst LOCK_KEY = \"payload-redirect:rule-graph\";\nconst POSTGRES_ADAPTER_PATTERN = /postgres/;\n\ntype TransactionQueryable = {\n execute: (query: string) => Promise<{ rows: Array<Record<string, unknown>> }>;\n};\n\ntype DbWithSessions = {\n packageName?: string;\n sessions?: Record<string, { db?: unknown } | undefined>;\n};\n\nexport async function lockRedirectRuleGraph(req: PayloadRequest): Promise<void> {\n const db = req.payload?.db as unknown as DbWithSessions | undefined;\n // No database adapter means there is no transaction graph to serialize against.\n if (db == null) return;\n if (!POSTGRES_ADAPTER_PATTERN.test(db.packageName ?? \"\")) return;\n\n const transactionID = await req.transactionID;\n const session = transactionID == null ? undefined : db.sessions?.[String(transactionID)];\n const tx = session?.db as TransactionQueryable | undefined;\n if (tx == null || typeof tx.execute !== \"function\") {\n throw new Error(\"Redirect rule lock needs the request transaction; refusing without it.\");\n }\n\n // LOCK_KEY is a constant, so inlining it into the SQL text is safe.\n await tx.execute(`select pg_advisory_xact_lock(hashtext('${LOCK_KEY}'))`);\n\n const isolation = await tx.execute(\"show transaction_isolation\");\n if (isolation.rows[0]?.transaction_isolation !== \"read committed\") {\n throw new Error(\"Redirect rule lock requires READ COMMITTED transactions.\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph-lock.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/graph-lock.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,wBAAwB,GAAG,UAAU,CAAC;AAW5C,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,GAAmB;IAC7D,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAA2C,CAAC;IACpE,gFAAgF;IAChF,IAAI,EAAE,IAAI,IAAI;QAAE,OAAO;IACvB,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;QAAE,OAAO;IAEjE,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC;IAC9C,MAAM,OAAO,GAAG,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IACzF,MAAM,EAAE,GAAG,OAAO,EAAE,EAAsC,CAAC;IAC3D,IAAI,EAAE,IAAI,IAAI,IAAI,OAAO,EAAE,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;IAC5F,CAAC;IAED,oEAAoE;IACpE,MAAM,EAAE,CAAC,OAAO,CAAC,0CAA0C,QAAQ,KAAK,CAAC,CAAC;IAE1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACjE,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB,KAAK,gBAAgB,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,sCAAsC,GAAG,GAAkC,EAAE;IACxF,OAAO,KAAK,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,EAAE;QAClC,IAAI,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,qBAAqB,CAAC,GAAG,CAAC,CAAC;QACnC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type { CollectionBeforeOperationHook, PayloadRequest } from \"payload\";\n\n/**\n * Serializes writes to the redirect rule graph. The loop and duplicate checks read committed rows,\n * so two concurrent writes that each close a cycle could both pass unless the second waits for the\n * first to commit. The lock is transaction-scoped and released at commit or rollback.\n *\n * Postgres is the supported adapter: the lock needs the request transaction and READ COMMITTED\n * isolation, and the function throws when either is missing rather than checking without it.\n * Adapters without advisory locks return without locking.\n */\nconst LOCK_KEY = \"payload-redirect:rule-graph\";\nconst POSTGRES_ADAPTER_PATTERN = /postgres/;\n\ntype TransactionQueryable = {\n execute: (query: string) => Promise<{ rows: Array<Record<string, unknown>> }>;\n};\n\ntype DbWithSessions = {\n packageName?: string;\n sessions?: Record<string, { db?: unknown } | undefined>;\n};\n\nexport async function lockRedirectRuleGraph(req: PayloadRequest): Promise<void> {\n const db = req.payload?.db as unknown as DbWithSessions | undefined;\n // No database adapter means there is no transaction graph to serialize against.\n if (db == null) return;\n if (!POSTGRES_ADAPTER_PATTERN.test(db.packageName ?? \"\")) return;\n\n const transactionID = await req.transactionID;\n const session = transactionID == null ? undefined : db.sessions?.[String(transactionID)];\n const tx = session?.db as TransactionQueryable | undefined;\n if (tx == null || typeof tx.execute !== \"function\") {\n throw new Error(\"Redirect rule lock needs the request transaction; refusing without it.\");\n }\n\n // LOCK_KEY is a constant, so inlining it into the SQL text is safe.\n await tx.execute(`select pg_advisory_xact_lock(hashtext('${LOCK_KEY}'))`);\n\n const isolation = await tx.execute(\"show transaction_isolation\");\n if (isolation.rows[0]?.transaction_isolation !== \"read committed\") {\n throw new Error(\"Redirect rule lock requires READ COMMITTED transactions.\");\n }\n}\n\n/**\n * Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership\n * or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.\n */\nexport const createRedirectGraphLockBeforeOperation = (): CollectionBeforeOperationHook => {\n return async ({ operation, req }) => {\n if (operation === \"create\" || operation === \"update\") {\n await lockRedirectRuleGraph(req);\n }\n };\n};\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { REDIRECT_CONTEXT_KEYS } from "../context-keys.js";
|
|
2
2
|
export const createRedirectOriginBeforeChange = () => async (args) => {
|
|
3
3
|
const { data, operation, req } = args;
|
|
4
|
-
|
|
4
|
+
// This marker tracks automatic-rule provenance; Local API overrideAccess grants the privilege.
|
|
5
|
+
if (req.context?.[REDIRECT_CONTEXT_KEYS.autoWrite]) {
|
|
5
6
|
data.origin = "auto";
|
|
6
7
|
}
|
|
7
8
|
else if (operation === "create") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"origin-hook.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/origin-hook.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"origin-hook.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/origin-hook.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAA+B,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;IAC/F,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAEtC,+FAA+F;IAC/F,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;SAAM,IAAI,SAAS,KAAK,QAAQ,EAAE,CAAC;QAClC,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC;IACzB,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,MAAM;YACT,IAAI,CAAC,WAAW,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,QAAQ,CAAC,CAAC;IAC5F,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC","sourcesContent":["import type { CollectionBeforeChangeHook } from \"payload\";\nimport { REDIRECT_CONTEXT_KEYS } from \"../context-keys.js\";\n\nexport const createRedirectOriginBeforeChange = (): CollectionBeforeChangeHook => async (args) => {\n const { data, operation, req } = args;\n\n // This marker tracks automatic-rule provenance; Local API overrideAccess grants the privilege.\n if (req.context?.[REDIRECT_CONTEXT_KEYS.autoWrite]) {\n data.origin = \"auto\";\n } else if (operation === \"create\") {\n data.origin = \"manual\";\n } else {\n data.origin =\n args.originalDoc?.origin === \"auto\" ? \"manual\" : (args.originalDoc?.origin ?? \"manual\");\n }\n\n return data;\n};\n"]}
|
|
@@ -1 +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,
|
|
1
|
+
{"version":3,"file":"context-keys.js","sourceRoot":"","sources":["../../../src/core/redirects/context-keys.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,SAAS,EAAE,0BAA0B;IACrC,QAAQ,EAAE,yBAAyB;CAC3B,CAAC","sourcesContent":["export const REDIRECT_CONTEXT_KEYS = {\n autoWrite: \"payloadRedirectAutoWrite\",\n skipAuto: \"payloadRedirectSkipAuto\",\n} as const;\n"]}
|
package/dist/exports/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export type { RedirectOrigin } from "../core/redirects/model/origin.js";
|
|
2
2
|
export type { RedirectStatusCode } from "../core/redirects/model/status-code.js";
|
|
3
3
|
export { redirects } from "../plugin/payload-plugin.js";
|
|
4
|
-
export type { RedirectCollectionOptions, RedirectsOptions } from "../plugin/types.js";
|
|
4
|
+
export type { RedirectCollectionOptions, RedirectGlobalOptions, RedirectsOptions, } from "../plugin/types.js";
|
|
@@ -1 +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 {
|
|
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 {\n RedirectCollectionOptions,\n RedirectGlobalOptions,\n RedirectsOptions,\n} from \"#redirect/plugin/types\";\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { definePlugin } from "payload";
|
|
1
|
+
import { definePlugin, } from "payload";
|
|
2
|
+
import { createGlobalRedirect } from "../core/redirects/auto/create-global-redirect.js";
|
|
2
3
|
import { createRedirect } from "../core/redirects/auto/create-redirect.js";
|
|
3
4
|
import { createRedirectsCollection } from "../core/redirects/collection/collection.js";
|
|
4
5
|
import { isValidLocalePrefix } from "../core/url/published-path.js";
|
|
@@ -31,7 +32,7 @@ const assertLocaleMap = (value, locales, name) => {
|
|
|
31
32
|
}
|
|
32
33
|
return map;
|
|
33
34
|
};
|
|
34
|
-
const validatePathOptions = (value, slug, locales,
|
|
35
|
+
const validatePathOptions = (value, entityType, slug, locales, versions) => {
|
|
35
36
|
const options = asRecord(value);
|
|
36
37
|
if (!options)
|
|
37
38
|
throw new Error(`payload-redirect: redirect config for "${slug}" must be an object`);
|
|
@@ -50,26 +51,24 @@ const validatePathOptions = (value, slug, locales, collection) => {
|
|
|
50
51
|
throw new Error(`payload-redirect: redirect config for "${slug}" enabled must be a boolean`);
|
|
51
52
|
}
|
|
52
53
|
if (modes.length !== 1) {
|
|
53
|
-
throw new Error(`payload-redirect:
|
|
54
|
+
throw new Error(`payload-redirect: ${entityType} "${slug}" must configure exactly one of path, paths, or getPath`);
|
|
54
55
|
}
|
|
55
|
-
if (!
|
|
56
|
-
typeof collection.versions !== "object" ||
|
|
57
|
-
!collection.versions.drafts) {
|
|
56
|
+
if (!asRecord(versions)?.drafts) {
|
|
58
57
|
throw new Error(`payload-redirect: automatic redirects for "${slug}" require versions.drafts`);
|
|
59
58
|
}
|
|
60
59
|
if (Object.hasOwn(options, "path")) {
|
|
61
60
|
if (typeof options.path !== "string" || !isValidPathTemplate(options.path)) {
|
|
62
|
-
throw new Error(`payload-redirect:
|
|
61
|
+
throw new Error(`payload-redirect: ${entityType}s.${slug}.path must be a valid site-relative template`);
|
|
63
62
|
}
|
|
64
63
|
}
|
|
65
64
|
else if (Object.hasOwn(options, "paths")) {
|
|
66
65
|
if (locales.length === 0) {
|
|
67
|
-
throw new Error(`payload-redirect:
|
|
66
|
+
throw new Error(`payload-redirect: ${entityType}s.${slug}.paths requires Payload localization`);
|
|
68
67
|
}
|
|
69
|
-
const paths = assertLocaleMap(options.paths, locales,
|
|
68
|
+
const paths = assertLocaleMap(options.paths, locales, `${entityType}s.${slug}.paths`);
|
|
70
69
|
for (const [locale, path] of Object.entries(paths)) {
|
|
71
70
|
if (!isValidPathTemplate(path)) {
|
|
72
|
-
throw new Error(`payload-redirect:
|
|
71
|
+
throw new Error(`payload-redirect: ${entityType}s.${slug}.paths.${locale} must be a valid site-relative template`);
|
|
73
72
|
}
|
|
74
73
|
}
|
|
75
74
|
}
|
|
@@ -77,12 +76,12 @@ const validatePathOptions = (value, slug, locales, collection) => {
|
|
|
77
76
|
throw new Error(`payload-redirect: collections.${slug}.getPath must be a function`);
|
|
78
77
|
}
|
|
79
78
|
};
|
|
80
|
-
const
|
|
81
|
-
const central = asRecord(
|
|
82
|
-
if (central && Object.hasOwn(central,
|
|
83
|
-
return central[
|
|
79
|
+
const selectedOptions = (entity, centralOptions) => {
|
|
80
|
+
const central = asRecord(centralOptions);
|
|
81
|
+
if (central && Object.hasOwn(central, entity.slug)) {
|
|
82
|
+
return central[entity.slug];
|
|
84
83
|
}
|
|
85
|
-
return asRecord(
|
|
84
|
+
return asRecord(entity.custom)?.redirect;
|
|
86
85
|
};
|
|
87
86
|
const validateOptions = (config, options) => {
|
|
88
87
|
const locales = localeCodes(config);
|
|
@@ -99,15 +98,26 @@ const validateOptions = (config, options) => {
|
|
|
99
98
|
throw new Error(`payload-redirect: configured collection "${slug}" is not registered`);
|
|
100
99
|
}
|
|
101
100
|
}
|
|
101
|
+
for (const slug of Object.keys(asRecord(options.globals) ?? {})) {
|
|
102
|
+
if (!config.globals?.some((global) => global.slug === slug)) {
|
|
103
|
+
throw new Error(`payload-redirect: configured global "${slug}" is not registered`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
102
106
|
for (const collection of config.collections ?? []) {
|
|
103
|
-
const selected =
|
|
107
|
+
const selected = selectedOptions(collection, options.collections);
|
|
108
|
+
if (selected === undefined)
|
|
109
|
+
continue;
|
|
110
|
+
validatePathOptions(selected, "collection", collection.slug, locales, collection.versions);
|
|
111
|
+
}
|
|
112
|
+
for (const global of config.globals ?? []) {
|
|
113
|
+
const selected = selectedOptions(global, options.globals);
|
|
104
114
|
if (selected === undefined)
|
|
105
115
|
continue;
|
|
106
|
-
validatePathOptions(selected,
|
|
116
|
+
validatePathOptions(selected, "global", global.slug, locales, global.versions);
|
|
107
117
|
}
|
|
108
118
|
};
|
|
109
119
|
const wireCollectionRedirect = (collection, options, collectionSlug) => {
|
|
110
|
-
const selected =
|
|
120
|
+
const selected = selectedOptions(collection, options.collections);
|
|
111
121
|
const record = asRecord(selected);
|
|
112
122
|
if (!record || record.enabled === false)
|
|
113
123
|
return collection;
|
|
@@ -121,7 +131,7 @@ const wireCollectionRedirect = (collection, options, collectionSlug) => {
|
|
|
121
131
|
afterChange: [
|
|
122
132
|
...hooks,
|
|
123
133
|
createRedirect({
|
|
124
|
-
collectionSlug,
|
|
134
|
+
redirectCollectionSlug: collectionSlug,
|
|
125
135
|
pathOptions: redirectOptions,
|
|
126
136
|
localePrefixes: options.localePrefixes,
|
|
127
137
|
}),
|
|
@@ -129,6 +139,30 @@ const wireCollectionRedirect = (collection, options, collectionSlug) => {
|
|
|
129
139
|
},
|
|
130
140
|
};
|
|
131
141
|
};
|
|
142
|
+
const wireGlobalRedirect = (global, options, redirectCollectionSlug) => {
|
|
143
|
+
const selected = selectedOptions(global, options.globals);
|
|
144
|
+
const record = asRecord(selected);
|
|
145
|
+
if (!record || record.enabled === false)
|
|
146
|
+
return global;
|
|
147
|
+
const afterChange = global.hooks?.afterChange;
|
|
148
|
+
const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];
|
|
149
|
+
const pathOptions = selected;
|
|
150
|
+
return {
|
|
151
|
+
...global,
|
|
152
|
+
hooks: {
|
|
153
|
+
...global.hooks,
|
|
154
|
+
afterChange: [
|
|
155
|
+
...hooks,
|
|
156
|
+
createGlobalRedirect({
|
|
157
|
+
globalSlug: global.slug,
|
|
158
|
+
redirectCollectionSlug,
|
|
159
|
+
pathOptions,
|
|
160
|
+
localePrefixes: options.localePrefixes,
|
|
161
|
+
}),
|
|
162
|
+
],
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
};
|
|
132
166
|
const definedRedirectsPlugin = definePlugin({
|
|
133
167
|
slug: PLUGIN_SLUG,
|
|
134
168
|
plugin: ({ config, ...options }) => {
|
|
@@ -148,6 +182,7 @@ const definedRedirectsPlugin = definePlugin({
|
|
|
148
182
|
...(config.collections ?? []).map((collection) => wireCollectionRedirect(collection, options, collectionSlug)),
|
|
149
183
|
redirectsCollection,
|
|
150
184
|
],
|
|
185
|
+
globals: (config.globals ?? []).map((global) => wireGlobalRedirect(global, options, collectionSlug)),
|
|
151
186
|
};
|
|
152
187
|
},
|
|
153
188
|
});
|
|
@@ -1 +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,mCAAmC,CAAC;AACxE,OAAO,EAAE,mBAAmB,E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AE,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
|
+
{"version":3,"file":"payload-plugin.js","sourceRoot":"","sources":["../../src/plugin/payload-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,YAAY,GAEb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,oBAAoB,EAAE,MAAM,sDAAsD,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAOtE,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAC9C,MAAM,uBAAuB,GAAG,WAAW,CAAC;AAC5C,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC;AAEtE,MAAM,QAAQ,GA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,IAAI,IAAI,uBAAuB,CAAC;QAC3E,IAAI,MAAM,CAAC,WAAW,EAAE,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;YACD,OAAO,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAC7C,kBAAkB,CAAC,MAAM,EAAE,OAAO,EAAE,cAAc,CAAC,CACpD;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 {\n type CollectionConfig,\n type Config,\n type GlobalConfig,\n definePlugin,\n type Plugin,\n} from \"payload\";\nimport { createGlobalRedirect } from \"#redirect/core/redirects/auto/create-global-redirect\";\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 {\n RedirectCollectionOptions,\n RedirectGlobalOptions,\n RedirectsOptions,\n} 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 entityType: \"collection\" | \"global\",\n slug: string,\n locales: string[],\n versions: unknown,\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: ${entityType} \"${slug}\" must configure exactly one of path, paths, or getPath`,\n );\n }\n if (!asRecord(versions)?.drafts) {\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: ${entityType}s.${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(\n `payload-redirect: ${entityType}s.${slug}.paths requires Payload localization`,\n );\n }\n const paths = assertLocaleMap(options.paths, locales, `${entityType}s.${slug}.paths`);\n for (const [locale, path] of Object.entries(paths)) {\n if (!isValidPathTemplate(path)) {\n throw new Error(\n `payload-redirect: ${entityType}s.${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 selectedOptions = (\n entity: { slug: string; custom?: unknown },\n centralOptions: unknown,\n): unknown => {\n const central = asRecord(centralOptions);\n if (central && Object.hasOwn(central, entity.slug)) {\n return central[entity.slug];\n }\n return asRecord(entity.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 slug of Object.keys(asRecord(options.globals) ?? {})) {\n if (!config.globals?.some((global) => global.slug === slug)) {\n throw new Error(`payload-redirect: configured global \"${slug}\" is not registered`);\n }\n }\n\n for (const collection of config.collections ?? []) {\n const selected = selectedOptions(collection, options.collections);\n if (selected === undefined) continue;\n validatePathOptions(selected, \"collection\", collection.slug, locales, collection.versions);\n }\n\n for (const global of config.globals ?? []) {\n const selected = selectedOptions(global, options.globals);\n if (selected === undefined) continue;\n validatePathOptions(selected, \"global\", global.slug, locales, global.versions);\n }\n};\n\nconst wireCollectionRedirect = (\n collection: CollectionConfig,\n options: RedirectsOptions,\n collectionSlug: string,\n): CollectionConfig => {\n const selected = selectedOptions(collection, options.collections);\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 redirectCollectionSlug: collectionSlug,\n pathOptions: redirectOptions,\n localePrefixes: options.localePrefixes,\n }),\n ],\n },\n };\n};\n\nconst wireGlobalRedirect = (\n global: GlobalConfig,\n options: RedirectsOptions,\n redirectCollectionSlug: string,\n): GlobalConfig => {\n const selected = selectedOptions(global, options.globals);\n const record = asRecord(selected);\n if (!record || record.enabled === false) return global;\n\n const afterChange = global.hooks?.afterChange;\n const hooks = Array.isArray(afterChange) ? afterChange : afterChange ? [afterChange] : [];\n const pathOptions = selected as RedirectGlobalOptions;\n\n return {\n ...global,\n hooks: {\n ...global.hooks,\n afterChange: [\n ...hooks,\n createGlobalRedirect({\n globalSlug: global.slug,\n redirectCollectionSlug,\n pathOptions,\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 globals: (config.globals ?? []).map((global) =>\n wireGlobalRedirect(global, options, collectionSlug),\n ),\n };\n },\n});\n\nexport const redirects = (options: RedirectsOptions = {}): Plugin =>\n definedRedirectsPlugin(options);\n"]}
|
package/dist/plugin/types.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import type { CollectionSlug } from "payload";
|
|
1
|
+
import type { CollectionSlug, DataFromCollectionSlug, DataFromGlobalSlug, GlobalSlug } from "payload";
|
|
2
2
|
import type { RedirectPathOptions } from "../core/redirects/auto/types.js";
|
|
3
3
|
import type { RedirectCollectionOverrides } from "../core/redirects/collection/types.js";
|
|
4
4
|
type LocaleCode = Extract<import("payload").TypedLocale, string>;
|
|
5
5
|
type LocaleMap = string extends LocaleCode ? Record<string, string> : Record<LocaleCode, string>;
|
|
6
|
-
export type RedirectCollectionOptions<TSlug extends CollectionSlug = CollectionSlug> = RedirectPathOptions<TSlug
|
|
6
|
+
export type RedirectCollectionOptions<TSlug extends CollectionSlug = CollectionSlug> = RedirectPathOptions<DataFromCollectionSlug<TSlug>>;
|
|
7
|
+
export type RedirectGlobalOptions<TSlug extends GlobalSlug = GlobalSlug> = RedirectPathOptions<DataFromGlobalSlug<TSlug>>;
|
|
7
8
|
export type RedirectsOptions = {
|
|
8
9
|
/** Payload locale codes map to explicit site-relative prefixes; omission means no prefix. */
|
|
9
10
|
localePrefixes?: LocaleMap;
|
|
@@ -11,6 +12,10 @@ export type RedirectsOptions = {
|
|
|
11
12
|
collections?: {
|
|
12
13
|
[TSlug in CollectionSlug]?: RedirectCollectionOptions<TSlug>;
|
|
13
14
|
};
|
|
15
|
+
/** Each entry opts that global into automatic redirects. Central entries replace local config. */
|
|
16
|
+
globals?: {
|
|
17
|
+
[TSlug in GlobalSlug]?: RedirectGlobalOptions<TSlug>;
|
|
18
|
+
};
|
|
14
19
|
/** Native collection overrides for the plugin-owned redirects collection. */
|
|
15
20
|
overrides?: RedirectCollectionOverrides;
|
|
16
21
|
};
|
package/dist/plugin/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/plugin/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/plugin/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n CollectionSlug,\n DataFromCollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n} 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<DataFromCollectionSlug<TSlug>>;\n\nexport type RedirectGlobalOptions<TSlug extends GlobalSlug = GlobalSlug> = RedirectPathOptions<\n DataFromGlobalSlug<TSlug>\n>;\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 /** Each entry opts that global into automatic redirects. Central entries replace local config. */\n globals?: { [TSlug in GlobalSlug]?: RedirectGlobalOptions<TSlug> };\n /** Native collection overrides for the plugin-owned redirects collection. */\n overrides?: RedirectCollectionOverrides;\n};\n"]}
|
|
@@ -10,18 +10,24 @@ This document records observable configuration, validation, and publication beha
|
|
|
10
10
|
| The redirects collection slug already exists | Plugin config throws and names the colliding slug. |
|
|
11
11
|
| `redirects()` is registered more than once | Plugin config throws; register it once. |
|
|
12
12
|
| `overrides.fields` changes a required field type | Plugin config throws before Payload builds. Missing required fields are restored from defaults. |
|
|
13
|
-
| A
|
|
14
|
-
| Central
|
|
15
|
-
| A configured
|
|
13
|
+
| A Collection or Global has no redirect configuration | The entity is left unchanged; no publication hook is added. |
|
|
14
|
+
| Central options name an unregistered Collection or Global | Plugin configuration throws and names the entity. |
|
|
15
|
+
| A configured Collection or Global has no `versions.drafts` | Plugin configuration throws and names the entity. |
|
|
16
16
|
| Path config has unsupported options or multiple strategies | Plugin configuration throws before Payload builds. |
|
|
17
17
|
| Locale map omits or adds a Payload locale | Plugin configuration throws and names invalid locales. |
|
|
18
18
|
| Automatic generation is disabled | No automatic hook is added; manual rules remain available. |
|
|
19
|
+
| A Global defines `custom.redirect` | The plugin appends its Global publication hook and preserves existing hooks. |
|
|
19
20
|
|
|
20
21
|
## Redirect collection writes
|
|
21
22
|
|
|
22
23
|
`from` and `to` must be non-empty site-relative paths. The plugin normalizes them before checking
|
|
23
24
|
duplicates and loops.
|
|
24
25
|
|
|
26
|
+
Collection and field authorization use Payload's native defaults and consumer overrides. Trusted
|
|
27
|
+
automatic redirect operations use Local API `overrideAccess: true`; their request-context marker
|
|
28
|
+
tracks rule origin and recursion only. Ordinary REST, GraphQL, and user-scoped Local API operations
|
|
29
|
+
remain subject to their configured access rules.
|
|
30
|
+
|
|
25
31
|
| Condition | Result |
|
|
26
32
|
| --------------------------------------------------- | -------------------------------------------------------------- |
|
|
27
33
|
| Duplicate normalized `from` | Payload validation error on `from`. |
|
|
@@ -42,7 +48,7 @@ Automatic rules use one of `path`, `paths`, or `getPath`, configured centrally o
|
|
|
42
48
|
|
|
43
49
|
| Condition | Result |
|
|
44
50
|
| ----------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
45
|
-
| No matching path configuration | Automatic generation is not registered for that
|
|
51
|
+
| No matching path configuration | Automatic generation is not registered for that Collection or Global. |
|
|
46
52
|
| Template value is missing or unsafe | That locale's publication transition is skipped. |
|
|
47
53
|
| `getPath` returns `null` or a non-site-relative path | That locale's transition is skipped. |
|
|
48
54
|
| `getPath` returns a non-string value | That locale's transition is skipped. |
|
|
@@ -50,8 +56,21 @@ Automatic rules use one of `path`, `paths`, or `getPath`, configured centrally o
|
|
|
50
56
|
| Locale is missing from a configured prefix map | Plugin configuration fails before Payload builds. |
|
|
51
57
|
| Generated source and destination normalize to the same path | No redirect is written. |
|
|
52
58
|
|
|
53
|
-
Draft saves, first publications, unpublishes,
|
|
54
|
-
|
|
59
|
+
Draft saves, first publications, unpublishes, and deletions create no automatic rules. Existing
|
|
60
|
+
redirects remain when a document is unpublished or deleted.
|
|
61
|
+
|
|
62
|
+
On an unchanged republish, an enabled identical automatic rule is left alone. A missing rule is
|
|
63
|
+
recreated, and a disabled automatic rule is re-enabled, when an earlier published version resolves
|
|
64
|
+
to a different path. The source is the latest earlier published path that differs from the current
|
|
65
|
+
path.
|
|
66
|
+
|
|
67
|
+
An automatic write skips a source path owned by a manual rule. Editing an automatic rule changes
|
|
68
|
+
its origin to `manual`, so later publications do not update it. A path-template change does not
|
|
69
|
+
migrate historical rules.
|
|
70
|
+
|
|
71
|
+
If a generated rule would close a loop, validation rejects the redirect write and the publication
|
|
72
|
+
fails. The collection has one globally unique `from` field and no locale or hostname scope; two
|
|
73
|
+
localized routes cannot own the same source path with different destinations.
|
|
55
74
|
|
|
56
75
|
## Adapter boundary
|
|
57
76
|
|
package/package.json
CHANGED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { REDIRECT_CONTEXT_KEYS } from "../context-keys.js";
|
|
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)),
|
|
9
|
-
};
|
|
10
|
-
//# sourceMappingURL=access.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"access.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/access.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,GAAmB,EAAW,EAAE,CACtE,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC,CAAC;AAEzD,MAAM,WAAW,GAAG,CAAC,GAAmB,EAAW,EAAE,CACnD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAK,GAAG,CAAC,IAA0B,CAAC,IAAI,KAAK,SAAS,CAAC;AAE1E,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAW;IAC5B,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,uBAAuB,CAAC,GAAG,CAAC,IAAI,WAAW,CAAC,GAAG,CAAC,CAAW;IACjF,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,uBAAuB,CAAC,GAAG,CAAC,IAAI,WAAW,CAAC,GAAG,CAAC,CAAW;IACjF,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAW;CAClD,CAAC","sourcesContent":["import type { Access, PayloadRequest } from \"payload\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\n\nexport const isInternalRedirectWrite = (req: PayloadRequest): boolean =>\n Boolean(req.context?.[REDIRECT_CONTEXT_KEYS.internal]);\n\nconst isHumanUser = (req: PayloadRequest): boolean =>\n Boolean(req.user) && (req.user as { type?: string }).type !== \"service\";\n\nexport const defaultRedirectAccess = {\n read: (() => true) as Access,\n create: (({ req }) => isInternalRedirectWrite(req) || isHumanUser(req)) as Access,\n update: (({ req }) => isInternalRedirectWrite(req) || isHumanUser(req)) as Access,\n delete: (({ req }) => isHumanUser(req)) as Access,\n};\n"]}
|