@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,19 +1,12 @@
1
- import { RedirectValidationError } from '../model/errors.js';
2
1
  import { DEFAULT_REDIRECT_ORIGIN, isRedirectOrigin, REDIRECT_ORIGIN_VALUES, } from '../model/origin.js';
3
2
  import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, validateDestinationForStatus, } from '../model/status-code.js';
4
- import { normalizeRedirectSourcePath, normalizeRelativeRedirectPath, } from '../normalize-path.js';
5
- /**
6
- * Matches collection `read: () => true`. Required under hosts that wrap field
7
- * access fail-closed (e.g. host IAM plugins): Payload validates sort/where
8
- * against field read, and `defaultSort: 'from'` always queries these paths.
9
- */
3
+ import { normalizeRedirectSourcePath, normalizeRelativeRedirectPath } from '../normalize-path.js';
10
4
  const publicFieldRead = { read: () => true };
11
- /** Sibling `from` may be invalid; its own field validator reports that, so skip it here. */
12
- const normalizeSiblingFrom = (from) => {
13
- if (typeof from !== 'string' || from.trim().length === 0)
5
+ const normalizeSiblingFrom = (value) => {
6
+ if (typeof value !== 'string')
14
7
  return undefined;
15
8
  try {
16
- return normalizeRelativeRedirectPath(from);
9
+ return normalizeRedirectSourcePath(value);
17
10
  }
18
11
  catch {
19
12
  return undefined;
@@ -27,44 +20,44 @@ export const buildRedirectFields = () => [
27
20
  unique: true,
28
21
  access: publicFieldRead,
29
22
  validate: (value) => {
30
- if (typeof value !== 'string' || value.trim().length === 0) {
23
+ if (typeof value !== 'string')
24
+ return 'from is required';
25
+ if (!value.trim())
31
26
  return 'from is required';
32
- }
33
27
  try {
34
28
  normalizeRedirectSourcePath(value);
35
29
  return true;
36
30
  }
37
31
  catch (error) {
38
- return error instanceof RedirectValidationError ? error.message : 'Invalid from path';
32
+ return error instanceof Error ? error.message : 'Invalid from path';
39
33
  }
40
34
  },
41
35
  },
42
36
  {
43
37
  name: 'to',
44
38
  type: 'text',
39
+ required: true,
45
40
  access: publicFieldRead,
46
41
  validate: (value, { siblingData }) => {
47
42
  try {
48
- const code = assertRedirectStatusCode(siblingData?.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
49
- validateDestinationForStatus(code, value);
50
- if (typeof value === 'string' && value.trim().length > 0) {
51
- // Why: a rule whose `to` equals its `from` makes the browser loop on itself.
52
- if (normalizeRelativeRedirectPath(value) === normalizeSiblingFrom(siblingData?.from)) {
53
- return 'to must differ from from';
54
- }
43
+ const statusCode = assertRedirectStatusCode(siblingData?.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
44
+ validateDestinationForStatus(statusCode, value);
45
+ if (typeof value === 'string' &&
46
+ normalizeRelativeRedirectPath(value) === normalizeSiblingFrom(siblingData?.from)) {
47
+ return 'to must differ from from';
55
48
  }
56
49
  return true;
57
50
  }
58
51
  catch (error) {
59
- return error instanceof RedirectValidationError ? error.message : 'Invalid to path';
52
+ return error instanceof Error ? error.message : 'Invalid to path';
60
53
  }
61
54
  },
62
55
  },
63
56
  {
64
- name: 'StatusCode',
57
+ name: 'statusCode',
65
58
  type: 'select',
66
59
  label: 'Type',
67
- defaultValue: '301',
60
+ defaultValue: String(DEFAULT_REDIRECT_STATUS_CODE),
68
61
  required: true,
69
62
  access: publicFieldRead,
70
63
  options: [
@@ -77,12 +70,10 @@ export const buildRedirectFields = () => [
77
70
  return true;
78
71
  }
79
72
  catch (error) {
80
- return error instanceof RedirectValidationError ? error.message : 'Invalid status code';
73
+ return error instanceof Error ? error.message : 'Invalid statusCode';
81
74
  }
82
75
  },
83
- admin: {
84
- position: 'sidebar',
85
- },
76
+ admin: { position: 'sidebar' },
86
77
  },
87
78
  {
88
79
  name: 'enabled',
@@ -90,9 +81,7 @@ export const buildRedirectFields = () => [
90
81
  defaultValue: true,
91
82
  index: true,
92
83
  access: publicFieldRead,
93
- admin: {
94
- position: 'sidebar',
95
- },
84
+ admin: { position: 'sidebar' },
96
85
  },
97
86
  {
98
87
  name: 'origin',
@@ -104,59 +93,70 @@ export const buildRedirectFields = () => [
104
93
  { label: 'Manual', value: 'manual' },
105
94
  { label: 'Auto', value: 'auto' },
106
95
  ],
107
- admin: {
108
- position: 'sidebar',
109
- readOnly: true,
110
- },
111
- validate: (value) => {
112
- if (!isRedirectOrigin(value)) {
113
- return `origin must be ${REDIRECT_ORIGIN_VALUES.join(' or ')}`;
114
- }
115
- return true;
116
- },
96
+ validate: (value) => isRedirectOrigin(value) ? true : `origin must be ${REDIRECT_ORIGIN_VALUES.join(' or ')}`,
97
+ admin: { position: 'sidebar', readOnly: true },
117
98
  },
118
99
  ];
119
100
  export const mergeRedirectFields = (existingFields) => {
120
- const built = buildRedirectFields();
121
- const hostByName = new Map(existingFields
122
- .filter((f) => 'name' in f && typeof f.name === 'string')
101
+ const defaults = buildRedirectFields();
102
+ const existingByName = new Map(existingFields
103
+ .filter((field) => 'name' in field && typeof field.name === 'string')
123
104
  .map((field) => [field.name, field]));
124
- const pluginNames = new Set(built
125
- .filter((f) => 'name' in f && typeof f.name === 'string')
105
+ const defaultNames = new Set(defaults
106
+ .filter((field) => 'name' in field && typeof field.name === 'string')
126
107
  .map((field) => field.name));
127
- const merged = [];
128
- for (const field of built) {
129
- const name = 'name' in field && typeof field.name === 'string' ? field.name : '';
130
- if (!name)
131
- continue;
132
- const hostField = hostByName.get(name);
133
- if (!hostField) {
134
- merged.push(field);
135
- continue;
136
- }
137
- const pluginValidate = 'validate' in field && typeof field.validate === 'function' ? field.validate : undefined;
138
- const hostValidate = 'validate' in hostField && typeof hostField.validate === 'function'
139
- ? hostField.validate
140
- : undefined;
141
- const validate = pluginValidate
142
- ? async (value, options) => {
143
- const result = await pluginValidate(value, options);
144
- if (result !== true || !hostValidate)
145
- return result;
146
- return hostValidate(value, options);
147
- }
108
+ const merged = defaults.map((field) => {
109
+ if (!('name' in field) || typeof field.name !== 'string')
110
+ return field;
111
+ const override = existingByName.get(field.name);
112
+ if (!override)
113
+ return field;
114
+ const validate = 'validate' in field && typeof field.validate === 'function' ? field.validate : undefined;
115
+ const overrideValidate = 'validate' in override && typeof override.validate === 'function'
116
+ ? override.validate
148
117
  : undefined;
149
- merged.push({
118
+ return {
150
119
  ...field,
151
- ...hostField,
152
- ...(validate ? { validate } : {}),
153
- });
120
+ ...override,
121
+ ...(validate
122
+ ? {
123
+ validate: async (value, options) => {
124
+ const run = validate;
125
+ const result = await run(value, options);
126
+ return result === true && overrideValidate
127
+ ? overrideValidate(value, options)
128
+ : result;
129
+ },
130
+ }
131
+ : {}),
132
+ };
133
+ });
134
+ return [
135
+ ...merged,
136
+ ...existingFields.filter((field) => !('name' in field) || typeof field.name !== 'string' || !defaultNames.has(field.name)),
137
+ ];
138
+ };
139
+ export const assertRedirectFields = (fields) => {
140
+ const expected = new Map([
141
+ ['from', 'text'],
142
+ ['to', 'text'],
143
+ ['statusCode', 'select'],
144
+ ['enabled', 'checkbox'],
145
+ ['origin', 'select'],
146
+ ]);
147
+ const named = fields.filter((field) => 'name' in field && typeof field.name === 'string');
148
+ for (const [name, type] of expected) {
149
+ const matching = named.filter((field) => field.name === name);
150
+ if (matching.length !== 1 || !('type' in matching[0]) || matching[0].type !== type) {
151
+ throw new Error(`payload-redirect: overrides.fields must retain exactly one ${type} field named "${name}"`);
152
+ }
153
+ }
154
+ const from = named.find((field) => field.name === 'from');
155
+ const enabled = named.find((field) => field.name === 'enabled');
156
+ if (!from || !('unique' in from) || from.unique !== true) {
157
+ throw new Error('payload-redirect: overrides.fields must keep from.unique: true');
154
158
  }
155
- for (const field of existingFields) {
156
- const name = 'name' in field && typeof field.name === 'string' ? field.name : '';
157
- if (name && pluginNames.has(name))
158
- continue;
159
- merged.push(field);
159
+ if (!enabled || !('index' in enabled) || enabled.index !== true) {
160
+ throw new Error('payload-redirect: overrides.fields must keep enabled.index: true');
160
161
  }
161
- return merged;
162
162
  };
@@ -1,22 +1,15 @@
1
- import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
2
- import { DEFAULT_REDIRECT_ORIGIN } from '../model/origin.js';
1
+ import { isInternalRedirectWrite } from './access.js';
3
2
  export const createRedirectOriginBeforeChange = () => async (args) => {
4
3
  const { data, operation, req } = args;
5
- if (req.context?.[REDIRECT_CONTEXT_KEYS.internal]) {
6
- if (data.origin !== 'auto') {
7
- data.origin = 'auto';
8
- }
9
- return data;
4
+ if (isInternalRedirectWrite(req)) {
5
+ data.origin = 'auto';
10
6
  }
11
- // Origin is server-owned: a non-internal write can never set or keep 'auto'.
12
- if (operation === 'create') {
13
- data.origin = DEFAULT_REDIRECT_ORIGIN;
7
+ else if (operation === 'create') {
8
+ data.origin = 'manual';
14
9
  }
15
- if (operation === 'update') {
10
+ else {
16
11
  data.origin =
17
- args.originalDoc?.origin === 'auto'
18
- ? 'manual'
19
- : (args.originalDoc?.origin ?? DEFAULT_REDIRECT_ORIGIN);
12
+ args.originalDoc?.origin === 'auto' ? 'manual' : (args.originalDoc?.origin ?? 'manual');
20
13
  }
21
14
  return data;
22
15
  };
@@ -0,0 +1,7 @@
1
+ import type { CollectionConfig, Field } from 'payload';
2
+ export type RedirectCollectionOverrides = Omit<CollectionConfig, 'fields' | 'slug'> & {
3
+ fields?: (args: {
4
+ defaultFields: Field[];
5
+ }) => Field[];
6
+ slug?: string;
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,9 +1,3 @@
1
- export declare class RedirectConfigError extends Error {
2
- readonly name = "RedirectConfigError";
3
- }
4
1
  export declare class RedirectValidationError extends Error {
5
2
  readonly name = "RedirectValidationError";
6
3
  }
7
- export declare class RedirectAmbiguousRuleError extends Error {
8
- readonly name = "RedirectAmbiguousRuleError";
9
- }
@@ -1,9 +1,3 @@
1
- export class RedirectConfigError extends Error {
2
- name = 'RedirectConfigError';
3
- }
4
1
  export class RedirectValidationError extends Error {
5
2
  name = 'RedirectValidationError';
6
3
  }
7
- export class RedirectAmbiguousRuleError extends Error {
8
- name = 'RedirectAmbiguousRuleError';
9
- }
@@ -2,19 +2,16 @@ import { RedirectValidationError } from './errors.js';
2
2
  const SUPPORTED = [301, 302];
3
3
  export const DEFAULT_REDIRECT_STATUS_CODE = 301;
4
4
  const normalizeStatusCode = (value) => {
5
- const n = typeof value === 'string' ? Number(value) : value;
6
- if (typeof n !== 'number' || !Number.isFinite(n))
7
- return undefined;
8
- if (SUPPORTED.includes(n)) {
9
- return n;
10
- }
5
+ const code = typeof value === 'string' ? Number(value) : value;
6
+ if (code === 301 || code === 302)
7
+ return code;
11
8
  return undefined;
12
9
  };
13
10
  export const isRedirectStatusCode = (value) => normalizeStatusCode(value) !== undefined;
14
11
  export const assertRedirectStatusCode = (value) => {
15
12
  const code = normalizeStatusCode(value);
16
13
  if (code === undefined) {
17
- throw new RedirectValidationError(`StatusCode must be one of ${SUPPORTED.join(', ')}`);
14
+ throw new RedirectValidationError(`statusCode must be one of ${SUPPORTED.join(', ')}`);
18
15
  }
19
16
  return code;
20
17
  };
@@ -22,6 +19,6 @@ export const requiresDestination = (_statusCode) => true;
22
19
  export const validateDestinationForStatus = (statusCode, to) => {
23
20
  const hasTo = typeof to === 'string' && to.trim().length > 0;
24
21
  if (!hasTo) {
25
- throw new RedirectValidationError(`StatusCode ${statusCode} requires a non-empty "to" field`);
22
+ throw new RedirectValidationError(`statusCode ${statusCode} requires a non-empty "to" field`);
26
23
  }
27
24
  };
@@ -1,26 +1,10 @@
1
1
  import type { Payload, PayloadRequest, SelectType } from 'payload';
2
2
  import type { RedirectStatusCode } from './model/status-code.js';
3
- /** Fields loaded by `resolveRedirect` (omit description). */
4
- export declare const redirectResolveSelect: {
5
- readonly from: true;
6
- readonly to: true;
7
- readonly StatusCode: true;
8
- readonly enabled: true;
9
- };
10
- /** Lookup hooks / idempotent writes (includes `id`). */
11
- export declare const redirectLookupSelect: {
12
- readonly from: true;
13
- readonly to: true;
14
- readonly StatusCode: true;
15
- readonly enabled: true;
16
- readonly id: true;
17
- readonly origin: true;
18
- };
19
3
  export type RedirectLookupDoc = {
20
4
  id: string | number;
21
5
  from?: string | null;
22
6
  to?: string | null;
23
- StatusCode?: RedirectStatusCode | null;
7
+ statusCode?: RedirectStatusCode | null;
24
8
  enabled?: boolean | null;
25
9
  origin?: string | null;
26
10
  };
@@ -34,5 +18,7 @@ type FindByFromBase = {
34
18
  };
35
19
  export declare const findRedirectByFrom: (payload: Payload, { collectionSlug, from, req, overrideAccess, context, select, excludeId, }: FindByFromBase & {
36
20
  excludeId?: string | number;
37
- }) => Promise<import("payload").PaginatedDocs<import("payload").JsonObject & import("payload").TypeWithID>>;
21
+ }) => Promise<{
22
+ docs: RedirectLookupDoc[];
23
+ }>;
38
24
  export {};
@@ -1,14 +1,10 @@
1
- /** Fields loaded by `resolveRedirect` (omit description). */
2
- export const redirectResolveSelect = {
1
+ /** Lookup hooks / idempotent writes (includes `id`). */
2
+ const redirectLookupSelect = {
3
+ id: true,
3
4
  from: true,
4
5
  to: true,
5
- StatusCode: true,
6
+ statusCode: true,
6
7
  enabled: true,
7
- };
8
- /** Lookup hooks / idempotent writes (includes `id`). */
9
- export const redirectLookupSelect = {
10
- id: true,
11
- ...redirectResolveSelect,
12
8
  origin: true,
13
9
  };
14
10
  export const findRedirectByFrom = async (payload, { collectionSlug, from, req, overrideAccess = false, context, select = redirectLookupSelect, excludeId, }) => {
@@ -17,7 +13,7 @@ export const findRedirectByFrom = async (payload, { collectionSlug, from, req, o
17
13
  and: [{ from: { equals: from } }, { id: { not_equals: excludeId } }],
18
14
  }
19
15
  : { from: { equals: from } };
20
- return payload.find({
16
+ return (await payload.find({
21
17
  collection: collectionSlug,
22
18
  where,
23
19
  limit: 1,
@@ -26,5 +22,5 @@ export const findRedirectByFrom = async (payload, { collectionSlug, from, req, o
26
22
  overrideAccess,
27
23
  context,
28
24
  req,
29
- });
25
+ }));
30
26
  };
@@ -1,19 +1,8 @@
1
- import { type PreviewRoutes } from './preview-routes.js';
2
- import { type RouteParamsConfig } from './route-params.js';
3
- export type LocalePrefix = Record<string, string>;
4
- export type PublishedLinkPathTemplate = {
1
+ export type LocalePrefixes = Record<string, string>;
2
+ export type PublishedPathConfiguration = {
5
3
  path?: string;
6
4
  paths?: Record<string, string>;
7
- routes?: PreviewRoutes;
8
- params?: RouteParamsConfig;
5
+ getPath?: unknown;
9
6
  };
10
- export type ResolvedPublishedPathConfig = PublishedLinkPathTemplate & {
11
- localePrefix: LocalePrefix;
12
- };
13
- export declare function mergeLocalePrefix(plugin?: LocalePrefix, schema?: LocalePrefix): LocalePrefix;
14
- export declare function resolveLocaleRoutePrefix(localePrefix: LocalePrefix, code: string): string | null;
15
- export declare function resolvePathTemplate(config: Pick<PublishedLinkPathTemplate, 'path' | 'paths' | 'routes'>, locale: unknown): string | null;
16
- export declare function buildPublishedPath(config: ResolvedPublishedPathConfig, data: Record<string, unknown>, locale: unknown): string | null;
17
- export declare function resolvePublishedPathConfig(pluginLocalePrefix?: LocalePrefix, link?: PublishedLinkPathTemplate & {
18
- localePrefix?: LocalePrefix;
19
- }): ResolvedPublishedPathConfig | null;
7
+ export declare const isValidLocalePrefix: (prefix: string) => boolean;
8
+ export declare const buildPublishedPath: (config: PublishedPathConfiguration, doc: Record<string, unknown>, locale: unknown, localePrefixes?: LocalePrefixes) => string | null;
@@ -1,102 +1,49 @@
1
- import { localeCode } from './preview-path.js';
2
- import { buildPreviewPath } from './preview-routes.js';
3
- import { applyDynamicSegments } from './route-params.js';
4
- export function mergeLocalePrefix(plugin, schema) {
5
- return Object.assign({}, plugin, schema);
6
- }
7
- function normalizeLocalePrefix(prefix) {
8
- const trimmed = prefix.trim();
9
- if (!trimmed || trimmed === '/')
10
- return '';
11
- const withLeading = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
12
- return withLeading.replace(/\/+$/, '');
13
- }
14
- export function resolveLocaleRoutePrefix(localePrefix, code) {
15
- if (Object.keys(localePrefix).length === 0) {
16
- return `/${code}`;
1
+ import { applyDynamicSegments, hasControlCharacter, isValidPathTemplate } from './route-params.js';
2
+ const localeCode = (locale) => {
3
+ if (typeof locale === 'string')
4
+ return locale || undefined;
5
+ if (locale && typeof locale === 'object' && 'code' in locale) {
6
+ const code = locale.code;
7
+ return typeof code === 'string' && code ? code : undefined;
17
8
  }
18
- const explicit = localePrefix[code];
19
- if (explicit === undefined) {
20
- return null;
21
- }
22
- return normalizeLocalePrefix(explicit);
23
- }
24
- function patternForLocale(previewRoutes, locale) {
25
- const entries = Object.entries(previewRoutes);
26
- if (entries.length === 0)
27
- return null;
28
- const first = entries[0];
29
- if (!first)
30
- return null;
31
- const [, template] = first;
32
- const code = localeCode(locale);
33
- if (!code)
34
- return null;
35
- if (typeof template === 'string')
36
- return template;
37
- return template[code] ?? null;
38
- }
39
- export function resolvePathTemplate(config, locale) {
40
- const code = localeCode(locale);
41
- if (!code)
42
- return null;
43
- const localized = config.paths?.[code];
44
- if (localized)
45
- return localized;
46
- if (config.path)
47
- return config.path;
48
- if (config.routes)
49
- return patternForLocale(config.routes, locale);
50
- return null;
51
- }
52
- function joinPrefixAndPath(prefix, pathname) {
53
- if (pathname === '/' || pathname === '') {
54
- return prefix || '/';
55
- }
56
- const normalized = pathname.startsWith('/') ? pathname : `/${pathname}`;
57
- return `${prefix}${normalized}`;
58
- }
59
- function usesLegacyPreviewPathBuilder(config) {
60
- const hasNewTemplate = Boolean(config.path) || Boolean(config.paths && Object.keys(config.paths).length > 0);
61
- if (hasNewTemplate)
62
- return false;
63
- if (!config.routes || Object.keys(config.routes).length === 0)
64
- return false;
65
- return Object.keys(config.localePrefix).length === 0;
66
- }
67
- export function buildPublishedPath(config, data, locale) {
68
- if (usesLegacyPreviewPathBuilder(config)) {
69
- if (!config.routes)
70
- throw new Error('Legacy preview path requires locale routes');
71
- return buildPreviewPath(config.routes, data, locale, config.params);
9
+ return undefined;
10
+ };
11
+ export const isValidLocalePrefix = (prefix) => prefix === '' ||
12
+ (prefix.startsWith('/') &&
13
+ !prefix.startsWith('//') &&
14
+ !prefix.includes('?') &&
15
+ !prefix.includes('#') &&
16
+ !prefix.includes('\\') &&
17
+ !hasControlCharacter(prefix));
18
+ const withPrefix = (prefix, path) => path === '/' ? prefix || '/' : `${prefix}${path}`;
19
+ const isSiteRelativePath = (path) => path.startsWith('/') &&
20
+ !path.startsWith('//') &&
21
+ !path.includes('?') &&
22
+ !path.includes('#') &&
23
+ !path.includes('\\') &&
24
+ !hasControlCharacter(path);
25
+ export const buildPublishedPath = (config, doc, locale, localePrefixes) => {
26
+ if (typeof config.getPath === 'function') {
27
+ const path = config.getPath({
28
+ doc,
29
+ locale,
30
+ });
31
+ if (path === null)
32
+ return null;
33
+ if (typeof path !== 'string')
34
+ return null;
35
+ return isSiteRelativePath(path) ? path : null;
72
36
  }
73
37
  const code = localeCode(locale);
74
- if (!code)
38
+ const template = config.paths !== undefined ? (code ? config.paths[code] : undefined) : config.path;
39
+ if (typeof template !== 'string' || !isValidPathTemplate(template))
75
40
  return null;
76
- const pattern = resolvePathTemplate(config, locale);
77
- if (!pattern)
78
- return null;
79
- const resolved = applyDynamicSegments(pattern, data, locale, config.params);
41
+ const resolved = applyDynamicSegments(template, doc, code);
80
42
  if (resolved === null)
81
43
  return null;
82
- const prefix = resolveLocaleRoutePrefix(config.localePrefix, code);
83
- if (prefix === null)
84
- return null;
85
- return joinPrefixAndPath(prefix, resolved);
86
- }
87
- export function resolvePublishedPathConfig(pluginLocalePrefix, link) {
88
- if (!link)
89
- return null;
90
- const hasRoutes = link.routes && typeof link.routes === 'object' && Object.keys(link.routes).length > 0;
91
- const hasPath = typeof link.path === 'string' && link.path.length > 0;
92
- const hasPaths = link.paths && Object.keys(link.paths).length > 0;
93
- if (!hasRoutes && !hasPath && !hasPaths)
44
+ if (localePrefixes === undefined)
45
+ return resolved;
46
+ if (!code || !Object.hasOwn(localePrefixes, code))
94
47
  return null;
95
- return {
96
- localePrefix: mergeLocalePrefix(pluginLocalePrefix, link.localePrefix),
97
- path: link.path,
98
- paths: link.paths,
99
- routes: hasRoutes ? link.routes : undefined,
100
- params: link.params,
101
- };
102
- }
48
+ return withPrefix(localePrefixes[code], resolved);
49
+ };
@@ -1,11 +1,3 @@
1
- export type RouteParamFieldSpec = {
2
- field: string;
3
- localized?: boolean;
4
- };
5
- export type RouteParamMapping = string | RouteParamFieldSpec;
6
- export type RouteParamsConfig = Record<string, RouteParamMapping>;
7
- export declare function templateHasUnsupportedDynamicSyntax(template: string): boolean;
8
- export declare function extractDynamicSegments(template: string): string[];
9
- export declare function readValueAtPath(data: Record<string, unknown>, fieldPath: string): unknown;
10
- export declare function resolveRouteParam(paramName: string, data: Record<string, unknown>, locale: unknown, routeParams: RouteParamsConfig | undefined): string | null;
11
- export declare function applyDynamicSegments(pattern: string, data: Record<string, unknown>, locale: unknown, routeParams: RouteParamsConfig | undefined): string | null;
1
+ export declare const hasControlCharacter: (value: string) => boolean;
2
+ export declare const isValidPathTemplate: (template: string) => boolean;
3
+ export declare const applyDynamicSegments: (template: string, doc: Record<string, unknown>, locale: string | undefined) => string | null;