-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanonical.ts
More file actions
114 lines (101 loc) · 4.02 KB
/
Copy pathcanonical.ts
File metadata and controls
114 lines (101 loc) · 4.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Centralized, deterministic canonical-URL computation.
*
* ONE function computes every canonical in the app. The rules:
*
* 1. A CMS-provided `override` wins — but ONLY if it is a valid http/https
* absolute URL. A bare `new URL()` check is not enough: `javascript:` and
* `ftp:` parse successfully, so we restrict the protocol explicitly.
* 2. Otherwise the canonical is derived from the environment origin, an
* optional `/{locale}` segment, and the path.
* 3. Only an allowlisted set of "indexable" query params is retained (default:
* `page`). They are sorted for determinism and URL-encoded. Everything else
* (tracking, session, sort/filter noise) is dropped so the same logical
* page always produces the same canonical.
*
* The origin is environment-scoped (see `./env`), so preview/staging deploys
* never emit production canonicals.
*/
import { getSiteOrigin } from './env';
/** Query params that are allowed to appear in a canonical URL by default. */
export const DEFAULT_INDEXABLE_PARAMS = ['page'] as const;
export type ParamsInput =
| URLSearchParams
| Record<string, string | number | undefined | null>;
export interface CanonicalInput {
/** Route path, e.g. `/blog/my-post`. A leading slash is added if missing. */
path: string;
/** CMS canonical override. Honored only if a valid http/https URL. */
override?: string | null;
/** Optional locale segment, e.g. `en-GB` -> `/en-GB/...`. */
locale?: string | null;
/** Raw query params; only allowlisted keys survive. */
params?: ParamsInput;
/** Override the environment origin (mostly for tests). */
origin?: string;
/** Override the allowlist of indexable params. */
indexableParams?: readonly string[];
}
/**
* Strict URL validation for canonical overrides. Returns true only for absolute
* http/https URLs. Rejects relative paths, `javascript:`, `ftp:`, `mailto:`,
* empty strings, and non-strings.
*/
export function isValidUrl(value: unknown): value is string {
if (typeof value !== 'string' || value.trim() === '') {
return false;
}
let parsed: URL;
try {
parsed = new URL(value);
} catch {
return false;
}
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
}
function toEntries(params: ParamsInput | undefined): Array<[string, string]> {
if (!params) return [];
if (params instanceof URLSearchParams) {
return [...params.entries()];
}
const entries: Array<[string, string]> = [];
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue;
entries.push([key, String(value)]);
}
return entries;
}
function ensureLeadingSlash(path: string): string {
if (path === '') return '/';
return path.startsWith('/') ? path : `/${path}`;
}
/**
* Compute a canonical URL.
*
* @returns an absolute URL string with no trailing-slash surprises, and with
* only allowlisted query params (sorted, encoded).
*/
export function computeCanonical(input: CanonicalInput): string {
// Rule 1: a valid override short-circuits everything.
if (isValidUrl(input.override)) {
return input.override as string;
}
const origin = input.origin ?? getSiteOrigin();
const allowlist = new Set(input.indexableParams ?? DEFAULT_INDEXABLE_PARAMS);
const localeSegment = input.locale ? `/${input.locale.replace(/^\/+|\/+$/g, '')}` : '';
const pathname = `${localeSegment}${ensureLeadingSlash(input.path)}`;
const url = new URL(pathname, ensureTrailingSlash(origin));
// Rule 3: retain only allowlisted params, then sort for determinism.
const kept = toEntries(input.params).filter(([key]) => allowlist.has(key));
// Clear anything the URL constructor might have parsed out of `pathname`.
url.search = '';
for (const [key, value] of kept) {
url.searchParams.append(key, value);
}
url.searchParams.sort();
return url.toString();
}
/** `new URL(path, base)` needs the base to end in `/` to resolve cleanly. */
function ensureTrailingSlash(origin: string): string {
return origin.endsWith('/') ? origin : `${origin}/`;
}