@ingram-tech/nk-seo 0.7.0 → 0.8.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/src/url.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Resolves a site-relative path against a base origin; absolute http(s) URLs
3
+ * pass through untouched. The one URL-resolution rule for the whole package —
4
+ * every entry (builders, metadata, routes, hreflang) resolves through here so
5
+ * they can't drift (e.g. trailing-slash `baseUrl` producing `//` paths).
6
+ *
7
+ * Throws when the input escapes the site origin. A protocol-relative path
8
+ * (`//evil.com/x` — which a request to `https://site//evil.com/x` puts into
9
+ * `req.nextUrl.pathname` and thus into `x-pathname`) or a scheme'd value
10
+ * (`javascript:…`) would otherwise flow straight into a canonical/hreflang
11
+ * link, an SEO-hijack primitive once cached. Loud beats poisoned.
12
+ */
13
+ export const absoluteUrl = (path: string, baseUrl: string): string => {
14
+ if (/^https?:\/\//.test(path)) return path;
15
+ const base = new URL(baseUrl);
16
+ const resolved = new URL(path, base);
17
+ if (resolved.origin !== base.origin) {
18
+ throw new Error(
19
+ `@ingram-tech/nk-seo: "${path}" resolves outside the site origin ${base.origin}`,
20
+ );
21
+ }
22
+ return resolved.toString();
23
+ };
package/src/verify.ts ADDED
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Runtime verification that a site actually serves the hreflang cluster it
3
+ * advertises. Point it at a running deployment from CI or a test.
4
+ *
5
+ * hreflang is an unusual kind of markup: it is a set of promises about OTHER
6
+ * URLs, and nothing local can tell you whether those promises hold. A site can
7
+ * emit a flawless cluster while its middleware redirects every URL in it away,
8
+ * or while each variant quietly canonicalizes to the default language. Both
9
+ * delete the non-default languages from search, neither raises an error, and
10
+ * Search Console reports them as ordinary redirects and duplicates months
11
+ * later. The only way to know is to fetch the URLs and look.
12
+ */
13
+ import { hreflangAlternates, type HreflangConfig } from "./alternates.js";
14
+
15
+ export interface HreflangProblem {
16
+ /** The advertised URL the problem was found at. */
17
+ url: string;
18
+ /** The page whose cluster advertises it. */
19
+ pathname: string;
20
+ problem: string;
21
+ }
22
+
23
+ export interface VerifyHreflangOptions {
24
+ /** Injectable for tests. Defaults to the global `fetch`. */
25
+ fetch?: typeof globalThis.fetch;
26
+ /**
27
+ * Also require `<html lang>` to match the locale the URL names. Default
28
+ * `true`. Turn it off only if the attribute carries a regional tag the
29
+ * cluster doesn't (e.g. `lang="fr-BE"` with `hreflang="fr"`).
30
+ */
31
+ checkHtmlLang?: boolean;
32
+ }
33
+
34
+ /** Attributes of one HTML tag, lowercased keys, entity-decoded values. */
35
+ type Attrs = Record<string, string>;
36
+
37
+ const decode = (value: string): string =>
38
+ value
39
+ .replace(/&amp;/g, "&")
40
+ .replace(/&lt;/g, "<")
41
+ .replace(/&gt;/g, ">")
42
+ .replace(/&quot;/g, '"')
43
+ .replace(/&#0?39;|&apos;/g, "'");
44
+
45
+ const parseAttrs = (tag: string): Attrs => {
46
+ const attrs: Attrs = {};
47
+ const pattern =
48
+ /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g;
49
+ let match = pattern.exec(tag);
50
+ while (match !== null) {
51
+ const key = match[1]?.toLowerCase();
52
+ const value = match[2] ?? match[3] ?? match[4] ?? "";
53
+ if (key) attrs[key] = decode(value);
54
+ match = pattern.exec(tag);
55
+ }
56
+ return attrs;
57
+ };
58
+
59
+ const tagsNamed = (html: string, name: string): Attrs[] => {
60
+ const pattern = new RegExp(`<${name}\\b[^>]*>`, "gi");
61
+ return (html.match(pattern) ?? []).map(parseAttrs);
62
+ };
63
+
64
+ /**
65
+ * Fetch every URL the cluster for each pathname advertises and report what
66
+ * doesn't hold. An empty array means the cluster is sound.
67
+ *
68
+ * Checks, per advertised URL:
69
+ * - it returns 200 and is not a redirect (an annotated URL that 3xx's is the
70
+ * single most common way to lose a language);
71
+ * - its canonical points at itself, not at the default language;
72
+ * - it advertises the whole cluster back (Google discards non-reciprocal
73
+ * annotations, silently);
74
+ * - `<html lang>` matches the locale the URL names.
75
+ */
76
+ export async function verifyHreflangCluster(
77
+ config: HreflangConfig,
78
+ pathnames: readonly string[],
79
+ options: VerifyHreflangOptions = {},
80
+ ): Promise<HreflangProblem[]> {
81
+ const doFetch = options.fetch ?? globalThis.fetch;
82
+ const checkHtmlLang = options.checkHtmlLang ?? true;
83
+ const problems: HreflangProblem[] = [];
84
+
85
+ for (const pathname of pathnames) {
86
+ const { links } = hreflangAlternates(config, pathname);
87
+ const expected = links.map((link) => link.href);
88
+
89
+ // Map each advertised URL back to the locale it names. `links` is the
90
+ // locale list in order, then x-default; a real locale wins when the two
91
+ // share a URL (the prefix strategy's default locale does).
92
+ const localeOf = new Map<string, string | undefined>();
93
+ links.forEach((link, index) => {
94
+ const locale = config.locales[index];
95
+ if (locale === undefined) {
96
+ if (!localeOf.has(link.href)) localeOf.set(link.href, undefined);
97
+ return;
98
+ }
99
+ localeOf.set(link.href, locale);
100
+ });
101
+
102
+ for (const [url, locale] of localeOf) {
103
+ const add = (problem: string): void => {
104
+ problems.push({ url, pathname, problem });
105
+ };
106
+
107
+ let response: Response;
108
+ try {
109
+ response = await doFetch(url, { redirect: "manual" });
110
+ } catch (error) {
111
+ add(
112
+ `request failed: ${error instanceof Error ? error.message : error}`,
113
+ );
114
+ continue;
115
+ }
116
+
117
+ if (response.status >= 300 && response.status < 400) {
118
+ const target = response.headers.get("location") ?? "(no location)";
119
+ add(
120
+ `advertised in hreflang but redirects (${response.status} → ${target}); ` +
121
+ "an annotated URL must serve its language with a 200",
122
+ );
123
+ continue;
124
+ }
125
+ if (response.status !== 200) {
126
+ add(`advertised in hreflang but returned ${response.status}`);
127
+ continue;
128
+ }
129
+
130
+ const html = await response.text();
131
+
132
+ const canonicals = tagsNamed(html, "link")
133
+ .filter((attrs) => attrs.rel?.toLowerCase() === "canonical")
134
+ .map((attrs) => attrs.href)
135
+ .filter((href): href is string => href !== undefined);
136
+ if (canonicals.length === 0) {
137
+ add("no <link rel=canonical>");
138
+ } else if (canonicals.length > 1) {
139
+ add(
140
+ `${canonicals.length} <link rel=canonical> tags; Google ignores all of them`,
141
+ );
142
+ } else if (canonicals[0] !== url) {
143
+ add(
144
+ `canonical points at ${canonicals[0]}, not itself; ` +
145
+ "a variant that canonicalizes elsewhere is discarded",
146
+ );
147
+ }
148
+
149
+ const advertised = new Set(
150
+ tagsNamed(html, "link")
151
+ .filter(
152
+ (attrs) =>
153
+ attrs.rel?.toLowerCase() === "alternate" && attrs.hreflang,
154
+ )
155
+ .map((attrs) => attrs.href)
156
+ .filter((href): href is string => href !== undefined),
157
+ );
158
+ const missing = expected.filter((href) => !advertised.has(href));
159
+ if (missing.length > 0) {
160
+ add(
161
+ `does not link back to ${missing.join(", ")}; ` +
162
+ "hreflang must be reciprocal or Google drops the cluster",
163
+ );
164
+ }
165
+
166
+ if (checkHtmlLang && locale !== undefined) {
167
+ const lang = tagsNamed(html, "html")[0]?.lang;
168
+ if (lang !== locale) {
169
+ add(
170
+ `serves <html lang="${lang ?? ""}"> but is advertised as "${locale}"`,
171
+ );
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ return problems;
178
+ }
179
+
180
+ /**
181
+ * {@link verifyHreflangCluster}, but throws a single readable error listing every
182
+ * problem. The shape to call from a test or a CI step.
183
+ */
184
+ export async function assertHreflangCluster(
185
+ config: HreflangConfig,
186
+ pathnames: readonly string[],
187
+ options?: VerifyHreflangOptions,
188
+ ): Promise<void> {
189
+ const problems = await verifyHreflangCluster(config, pathnames, options);
190
+ if (problems.length === 0) return;
191
+ const lines = problems.map((p) => ` ${p.url}\n ${p.problem}`);
192
+ throw new Error(
193
+ `@ingram-tech/nk-seo: ${problems.length} hreflang problem(s):\n${lines.join("\n")}`,
194
+ );
195
+ }