@rankcli/agent-runtime 0.0.15 → 0.0.17

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 (203) hide show
  1. package/README.md +5 -4
  2. package/dist/index.d.mts +44 -393
  3. package/dist/index.d.ts +44 -393
  4. package/dist/index.js +22098 -26131
  5. package/dist/index.mjs +11834 -15857
  6. package/package.json +10 -4
  7. package/scripts/build-deno.ts +0 -134
  8. package/src/analyzers/core-web-vitals-analyzer.test.ts +0 -236
  9. package/src/analyzers/core-web-vitals-analyzer.ts +0 -557
  10. package/src/analyzers/geo-analyzer.test.ts +0 -310
  11. package/src/analyzers/geo-analyzer.ts +0 -814
  12. package/src/analyzers/image-optimization-analyzer.test.ts +0 -145
  13. package/src/analyzers/image-optimization-analyzer.ts +0 -348
  14. package/src/analyzers/index.ts +0 -233
  15. package/src/analyzers/internal-linking-analyzer.test.ts +0 -141
  16. package/src/analyzers/internal-linking-analyzer.ts +0 -419
  17. package/src/analyzers/mobile-seo-analyzer.test.ts +0 -140
  18. package/src/analyzers/mobile-seo-analyzer.ts +0 -455
  19. package/src/analyzers/security-headers-analyzer.test.ts +0 -115
  20. package/src/analyzers/security-headers-analyzer.ts +0 -318
  21. package/src/analyzers/structured-data-analyzer.test.ts +0 -210
  22. package/src/analyzers/structured-data-analyzer.ts +0 -590
  23. package/src/audit/ai/analyzer.ts +0 -347
  24. package/src/audit/ai/index.ts +0 -29
  25. package/src/audit/ai/prompts/content-analysis.ts +0 -271
  26. package/src/audit/ai/types.ts +0 -179
  27. package/src/audit/checks/additional-checks.ts +0 -439
  28. package/src/audit/checks/agent-experience.ts +0 -108
  29. package/src/audit/checks/ai-citation-worthiness.ts +0 -399
  30. package/src/audit/checks/ai-content-structure.ts +0 -325
  31. package/src/audit/checks/ai-readiness.ts +0 -406
  32. package/src/audit/checks/anchor-text.ts +0 -179
  33. package/src/audit/checks/answer-conciseness.ts +0 -322
  34. package/src/audit/checks/asset-minification.ts +0 -270
  35. package/src/audit/checks/bing-optimization.ts +0 -206
  36. package/src/audit/checks/brand-mention-optimization.ts +0 -349
  37. package/src/audit/checks/caching-headers.ts +0 -305
  38. package/src/audit/checks/canonical-advanced.ts +0 -150
  39. package/src/audit/checks/canonical-domain.ts +0 -196
  40. package/src/audit/checks/citation-quality.ts +0 -358
  41. package/src/audit/checks/client-rendering.ts +0 -542
  42. package/src/audit/checks/color-contrast.ts +0 -342
  43. package/src/audit/checks/content-freshness.ts +0 -170
  44. package/src/audit/checks/content-science.ts +0 -589
  45. package/src/audit/checks/conversion-elements.ts +0 -526
  46. package/src/audit/checks/crawlability.ts +0 -220
  47. package/src/audit/checks/directory-listing.ts +0 -172
  48. package/src/audit/checks/dom-analysis.ts +0 -191
  49. package/src/audit/checks/dom-size.ts +0 -246
  50. package/src/audit/checks/duplicate-content.ts +0 -194
  51. package/src/audit/checks/eeat-signals.ts +0 -990
  52. package/src/audit/checks/entity-seo.ts +0 -396
  53. package/src/audit/checks/featured-snippet.ts +0 -473
  54. package/src/audit/checks/freshness-signals.ts +0 -443
  55. package/src/audit/checks/funnel-intent.ts +0 -463
  56. package/src/audit/checks/hreflang.ts +0 -174
  57. package/src/audit/checks/html-compliance.ts +0 -302
  58. package/src/audit/checks/image-dimensions.ts +0 -167
  59. package/src/audit/checks/images.ts +0 -160
  60. package/src/audit/checks/indexnow.ts +0 -275
  61. package/src/audit/checks/interactive-tools.ts +0 -475
  62. package/src/audit/checks/internal-link-graph.ts +0 -436
  63. package/src/audit/checks/keyword-analysis.ts +0 -239
  64. package/src/audit/checks/keyword-cannibalization.ts +0 -385
  65. package/src/audit/checks/keyword-placement.ts +0 -471
  66. package/src/audit/checks/links.ts +0 -273
  67. package/src/audit/checks/llms-txt.ts +0 -224
  68. package/src/audit/checks/local-seo.ts +0 -296
  69. package/src/audit/checks/mobile.ts +0 -167
  70. package/src/audit/checks/modern-images.ts +0 -226
  71. package/src/audit/checks/navboost-signals.ts +0 -395
  72. package/src/audit/checks/on-page.ts +0 -209
  73. package/src/audit/checks/page-resources.ts +0 -285
  74. package/src/audit/checks/pagination.ts +0 -180
  75. package/src/audit/checks/performance.ts +0 -153
  76. package/src/audit/checks/platform-presence.ts +0 -580
  77. package/src/audit/checks/rag-chunk-readiness.test.ts +0 -159
  78. package/src/audit/checks/rag-chunk-readiness.ts +0 -163
  79. package/src/audit/checks/redirect-analysis.ts +0 -153
  80. package/src/audit/checks/redirect-chain.ts +0 -389
  81. package/src/audit/checks/resource-hints.ts +0 -420
  82. package/src/audit/checks/responsive-css.ts +0 -247
  83. package/src/audit/checks/responsive-images.ts +0 -396
  84. package/src/audit/checks/review-ecosystem.ts +0 -415
  85. package/src/audit/checks/robots-validation.ts +0 -373
  86. package/src/audit/checks/security-headers.ts +0 -188
  87. package/src/audit/checks/security.ts +0 -144
  88. package/src/audit/checks/serp-preview.ts +0 -251
  89. package/src/audit/checks/site-maturity.ts +0 -453
  90. package/src/audit/checks/social-meta.test.ts +0 -275
  91. package/src/audit/checks/social-meta.ts +0 -134
  92. package/src/audit/checks/soft-404.ts +0 -151
  93. package/src/audit/checks/structured-data.ts +0 -238
  94. package/src/audit/checks/tech-detection.ts +0 -496
  95. package/src/audit/checks/topical-clusters.ts +0 -435
  96. package/src/audit/checks/tracker-bloat.ts +0 -462
  97. package/src/audit/checks/tracking-verification.test.ts +0 -371
  98. package/src/audit/checks/tracking-verification.ts +0 -636
  99. package/src/audit/checks/url-safety.ts +0 -682
  100. package/src/audit/deno-entry.ts +0 -66
  101. package/src/audit/discovery/index.ts +0 -15
  102. package/src/audit/discovery/link-crawler.ts +0 -233
  103. package/src/audit/discovery/repo-routes.ts +0 -347
  104. package/src/audit/engine.ts +0 -633
  105. package/src/audit/fixes/index.ts +0 -209
  106. package/src/audit/fixes/social-meta-fixes.test.ts +0 -329
  107. package/src/audit/fixes/social-meta-fixes.ts +0 -463
  108. package/src/audit/index.ts +0 -74
  109. package/src/audit/runner.test.ts +0 -299
  110. package/src/audit/runner.ts +0 -130
  111. package/src/audit/types.ts +0 -1987
  112. package/src/content/featured-snippet.ts +0 -367
  113. package/src/content/generator.test.ts +0 -534
  114. package/src/content/generator.ts +0 -501
  115. package/src/content/headline.ts +0 -317
  116. package/src/content/index.ts +0 -62
  117. package/src/content/intent.ts +0 -258
  118. package/src/content/keyword-density.ts +0 -349
  119. package/src/content/readability.ts +0 -262
  120. package/src/executor.ts +0 -336
  121. package/src/fixer/framework-fixes.test.ts +0 -489
  122. package/src/fixer/framework-fixes.ts +0 -5287
  123. package/src/fixer/index.ts +0 -6
  124. package/src/fixer/schemas.ts +0 -971
  125. package/src/fixer.ts +0 -642
  126. package/src/frameworks/detector.test.ts +0 -248
  127. package/src/frameworks/detector.ts +0 -899
  128. package/src/frameworks/index.ts +0 -68
  129. package/src/frameworks/recipes/angular.yaml +0 -171
  130. package/src/frameworks/recipes/astro.yaml +0 -206
  131. package/src/frameworks/recipes/django.yaml +0 -180
  132. package/src/frameworks/recipes/laravel.yaml +0 -137
  133. package/src/frameworks/recipes/nextjs.yaml +0 -268
  134. package/src/frameworks/recipes/nuxt.yaml +0 -175
  135. package/src/frameworks/recipes/rails.yaml +0 -188
  136. package/src/frameworks/recipes/react.yaml +0 -202
  137. package/src/frameworks/recipes/sveltekit.yaml +0 -154
  138. package/src/frameworks/recipes/vue.yaml +0 -137
  139. package/src/frameworks/recipes/wordpress.yaml +0 -209
  140. package/src/frameworks/suggestion-engine.ts +0 -357
  141. package/src/geo/geo-content.test.ts +0 -305
  142. package/src/geo/geo-content.ts +0 -266
  143. package/src/geo/geo-history.test.ts +0 -473
  144. package/src/geo/geo-history.ts +0 -433
  145. package/src/geo/geo-tracker.test.ts +0 -359
  146. package/src/geo/geo-tracker.ts +0 -411
  147. package/src/geo/index.ts +0 -11
  148. package/src/geo/llm-citation-checker.ts +0 -188
  149. package/src/git/commit-helper.test.ts +0 -261
  150. package/src/git/commit-helper.ts +0 -329
  151. package/src/git/index.ts +0 -12
  152. package/src/git/pr-helper.test.ts +0 -284
  153. package/src/git/pr-helper.ts +0 -307
  154. package/src/index.ts +0 -76
  155. package/src/keywords/ai-keyword-engine.ts +0 -1062
  156. package/src/keywords/ai-summarizer.ts +0 -387
  157. package/src/keywords/ci-mode.ts +0 -555
  158. package/src/keywords/engine.ts +0 -359
  159. package/src/keywords/index.ts +0 -151
  160. package/src/keywords/llm-judge.ts +0 -357
  161. package/src/keywords/nlp-analysis.ts +0 -706
  162. package/src/keywords/prioritizer.ts +0 -295
  163. package/src/keywords/site-crawler.ts +0 -342
  164. package/src/keywords/sources/autocomplete.ts +0 -139
  165. package/src/keywords/sources/competitive-search.ts +0 -450
  166. package/src/keywords/sources/competitor-analysis.ts +0 -374
  167. package/src/keywords/sources/dataforseo.ts +0 -206
  168. package/src/keywords/sources/free-sources.ts +0 -294
  169. package/src/keywords/sources/gsc.ts +0 -123
  170. package/src/keywords/topic-grouping.ts +0 -327
  171. package/src/keywords/types.ts +0 -144
  172. package/src/keywords/wizard.ts +0 -457
  173. package/src/loader.ts +0 -40
  174. package/src/ranking/index.ts +0 -5
  175. package/src/ranking/serp-client.ts +0 -348
  176. package/src/ranking/tracker.ts +0 -380
  177. package/src/ranking/types.ts +0 -123
  178. package/src/reports/index.ts +0 -7
  179. package/src/reports/report-generator.test.ts +0 -293
  180. package/src/reports/report-generator.ts +0 -713
  181. package/src/scheduler/alerts.test.ts +0 -458
  182. package/src/scheduler/alerts.ts +0 -328
  183. package/src/scheduler/index.ts +0 -8
  184. package/src/scheduler/scheduled-audit.test.ts +0 -377
  185. package/src/scheduler/scheduled-audit.ts +0 -149
  186. package/src/test/integration-test.ts +0 -325
  187. package/src/tools/analyzer.ts +0 -373
  188. package/src/tools/crawl.ts +0 -293
  189. package/src/tools/files.ts +0 -301
  190. package/src/tools/h1-fixer.ts +0 -249
  191. package/src/tools/index.ts +0 -67
  192. package/src/tracking/github-action.ts +0 -326
  193. package/src/tracking/google-analytics.ts +0 -265
  194. package/src/tracking/index.ts +0 -45
  195. package/src/tracking/report-generator.ts +0 -386
  196. package/src/tracking/search-console.ts +0 -335
  197. package/src/types.ts +0 -148
  198. package/src/utils/http.ts +0 -302
  199. package/src/wasm-adapter.ts +0 -297
  200. package/src/wasm-entry.ts +0 -14
  201. package/tsconfig.json +0 -17
  202. package/tsup.wasm.config.ts +0 -26
  203. package/vitest.config.ts +0 -15
@@ -1,305 +0,0 @@
1
- /**
2
- * Browser Caching Headers Check
3
- *
4
- * Validates HTTP caching headers for optimal performance:
5
- * - Cache-Control header
6
- * - Expires header
7
- * - ETag header
8
- * - Last-Modified header
9
- *
10
- * Proper caching improves page load times for repeat visitors
11
- * and reduces server load.
12
- */
13
-
14
- import { httpGet } from '../../utils/http.js';
15
- import type { AuditIssue } from '../types.js';
16
-
17
- export interface CachingHeadersData {
18
- htmlCaching: {
19
- cacheControl?: string;
20
- expires?: string;
21
- etag?: string;
22
- lastModified?: string;
23
- maxAge?: number;
24
- isPublic: boolean;
25
- isPrivate: boolean;
26
- noStore: boolean;
27
- noCache: boolean;
28
- };
29
- staticAssets: AssetCachingInfo[];
30
- issues: {
31
- noCaching: number;
32
- shortTtl: number;
33
- properlyConfigured: number;
34
- };
35
- }
36
-
37
- interface AssetCachingInfo {
38
- url: string;
39
- type: string;
40
- cacheControl?: string;
41
- maxAge?: number;
42
- hasCaching: boolean;
43
- }
44
-
45
- // Recommended cache durations (in seconds)
46
- const CACHE_RECOMMENDATIONS = {
47
- html: 0, // HTML should generally not be cached or have short TTL
48
- css: 31536000, // 1 year for versioned assets
49
- js: 31536000,
50
- images: 31536000,
51
- fonts: 31536000,
52
- minimum: 86400, // 1 day minimum for static assets
53
- };
54
-
55
- export async function analyzeCachingHeaders(
56
- url: string,
57
- headers?: Record<string, string>
58
- ): Promise<{ issues: AuditIssue[]; data: CachingHeadersData }> {
59
- const issues: AuditIssue[] = [];
60
-
61
- // Analyze HTML page headers
62
- let htmlHeaders = headers;
63
- if (!htmlHeaders) {
64
- try {
65
- const response = await httpGet<string>(url, {
66
- timeout: 10000,
67
- validateStatus: () => true,
68
- });
69
- htmlHeaders = response.headers as Record<string, string>;
70
- } catch {
71
- htmlHeaders = {};
72
- }
73
- }
74
-
75
- const htmlCaching = parseCacheHeaders(htmlHeaders);
76
-
77
- // Check HTML caching (should be minimal or no caching)
78
- if (htmlCaching.maxAge && htmlCaching.maxAge > 3600) {
79
- issues.push({
80
- code: 'CACHING_HTML_TOO_LONG',
81
- severity: 'notice',
82
- category: 'performance',
83
- title: 'HTML page has long cache duration',
84
- description: `HTML page has Cache-Control max-age of ${htmlCaching.maxAge} seconds (${Math.round(htmlCaching.maxAge / 3600)} hours). HTML content changes frequently.`,
85
- impact: 'Users may see stale content. Content updates may not appear immediately.',
86
- howToFix: 'Set shorter cache duration for HTML: Cache-Control: no-cache or max-age=0, must-revalidate',
87
- affectedUrls: [url],
88
- });
89
- }
90
-
91
- // Sample static assets to check their caching
92
- const staticAssets: AssetCachingInfo[] = [];
93
- const assetUrls = await getStaticAssetUrls(url);
94
-
95
- let noCaching = 0;
96
- let shortTtl = 0;
97
- let properlyConfigured = 0;
98
-
99
- // Check up to 5 static assets
100
- const assetsToCheck = assetUrls.slice(0, 5);
101
-
102
- for (const assetUrl of assetsToCheck) {
103
- try {
104
- const assetResponse = await httpGet<string>(assetUrl, {
105
- timeout: 5000,
106
- validateStatus: () => true,
107
- });
108
-
109
- const assetCaching = parseCacheHeaders(assetResponse.headers as Record<string, string>);
110
- const type = getAssetType(assetUrl);
111
-
112
- const assetInfo: AssetCachingInfo = {
113
- url: assetUrl,
114
- type,
115
- cacheControl: assetCaching.cacheControl,
116
- maxAge: assetCaching.maxAge,
117
- hasCaching: Boolean(assetCaching.cacheControl || assetCaching.expires),
118
- };
119
-
120
- staticAssets.push(assetInfo);
121
-
122
- if (!assetInfo.hasCaching) {
123
- noCaching++;
124
- } else if (assetCaching.maxAge && assetCaching.maxAge < CACHE_RECOMMENDATIONS.minimum) {
125
- shortTtl++;
126
- } else {
127
- properlyConfigured++;
128
- }
129
- } catch {
130
- // Asset check failed, skip
131
- }
132
- }
133
-
134
- // Generate issues for static assets
135
- if (noCaching > 0) {
136
- issues.push({
137
- code: 'CACHING_STATIC_NO_CACHE',
138
- severity: 'warning',
139
- category: 'performance',
140
- title: 'Static assets missing cache headers',
141
- description: `${noCaching} static asset(s) have no Cache-Control header. This forces browsers to re-download on every visit.`,
142
- impact: 'Slower page loads for repeat visitors. Increased bandwidth usage.',
143
- howToFix: 'Add Cache-Control headers to static assets. For versioned files (with hash in filename), use: Cache-Control: public, max-age=31536000, immutable',
144
- affectedUrls: staticAssets.filter(a => !a.hasCaching).map(a => a.url),
145
- details: {
146
- recommendation: {
147
- 'versioned assets (with hash)': 'Cache-Control: public, max-age=31536000, immutable',
148
- 'non-versioned assets': 'Cache-Control: public, max-age=86400',
149
- },
150
- },
151
- });
152
- }
153
-
154
- if (shortTtl > 0) {
155
- issues.push({
156
- code: 'CACHING_STATIC_SHORT_TTL',
157
- severity: 'notice',
158
- category: 'performance',
159
- title: 'Static assets have short cache duration',
160
- description: `${shortTtl} static asset(s) have cache duration under 1 day. Consider longer caching for better performance.`,
161
- impact: 'Assets are re-downloaded more often than necessary.',
162
- howToFix: 'Increase max-age for static assets. Use versioned filenames (hash in filename) to enable long-term caching.',
163
- affectedUrls: staticAssets.filter(a => a.maxAge && a.maxAge < CACHE_RECOMMENDATIONS.minimum).map(a => a.url),
164
- });
165
- }
166
-
167
- // Check for missing ETag or Last-Modified
168
- if (!htmlCaching.etag && !htmlCaching.lastModified) {
169
- issues.push({
170
- code: 'CACHING_NO_VALIDATORS',
171
- severity: 'notice',
172
- category: 'performance',
173
- title: 'Missing cache validators (ETag/Last-Modified)',
174
- description: 'Page is missing both ETag and Last-Modified headers. These allow efficient cache validation.',
175
- impact: 'Browsers cannot efficiently validate if cached content is still fresh.',
176
- howToFix: 'Configure your server to send ETag or Last-Modified headers. Most web servers do this automatically for static files.',
177
- affectedUrls: [url],
178
- });
179
- }
180
-
181
- return {
182
- issues,
183
- data: {
184
- htmlCaching,
185
- staticAssets,
186
- issues: {
187
- noCaching,
188
- shortTtl,
189
- properlyConfigured,
190
- },
191
- },
192
- };
193
- }
194
-
195
- function parseCacheHeaders(headers: Record<string, string>): CachingHeadersData['htmlCaching'] {
196
- const cacheControl = headers['cache-control'] || headers['Cache-Control'];
197
- const expires = headers['expires'] || headers['Expires'];
198
- const etag = headers['etag'] || headers['ETag'];
199
- const lastModified = headers['last-modified'] || headers['Last-Modified'];
200
-
201
- let maxAge: number | undefined;
202
- let isPublic = false;
203
- let isPrivate = false;
204
- let noStore = false;
205
- let noCache = false;
206
-
207
- if (cacheControl) {
208
- // Parse max-age
209
- const maxAgeMatch = cacheControl.match(/max-age=(\d+)/i);
210
- if (maxAgeMatch) {
211
- maxAge = parseInt(maxAgeMatch[1], 10);
212
- }
213
-
214
- // Parse directives
215
- const lowerCC = cacheControl.toLowerCase();
216
- isPublic = lowerCC.includes('public');
217
- isPrivate = lowerCC.includes('private');
218
- noStore = lowerCC.includes('no-store');
219
- noCache = lowerCC.includes('no-cache');
220
- }
221
-
222
- return {
223
- cacheControl,
224
- expires,
225
- etag,
226
- lastModified,
227
- maxAge,
228
- isPublic,
229
- isPrivate,
230
- noStore,
231
- noCache,
232
- };
233
- }
234
-
235
- async function getStaticAssetUrls(pageUrl: string): Promise<string[]> {
236
- const assets: string[] = [];
237
-
238
- try {
239
- const response = await httpGet<string>(pageUrl, {
240
- timeout: 10000,
241
- validateStatus: () => true,
242
- });
243
-
244
- const html = response.data as string;
245
- const baseUrl = new URL(pageUrl);
246
-
247
- // Extract CSS files
248
- const cssMatches = html.match(/href="([^"]+\.css[^"]*)"/gi);
249
- if (cssMatches) {
250
- for (const match of cssMatches.slice(0, 2)) {
251
- const href = match.match(/href="([^"]+)"/)?.[1];
252
- if (href) {
253
- try {
254
- assets.push(new URL(href, baseUrl).href);
255
- } catch {
256
- // Invalid URL
257
- }
258
- }
259
- }
260
- }
261
-
262
- // Extract JS files
263
- const jsMatches = html.match(/src="([^"]+\.js[^"]*)"/gi);
264
- if (jsMatches) {
265
- for (const match of jsMatches.slice(0, 2)) {
266
- const src = match.match(/src="([^"]+)"/)?.[1];
267
- if (src) {
268
- try {
269
- assets.push(new URL(src, baseUrl).href);
270
- } catch {
271
- // Invalid URL
272
- }
273
- }
274
- }
275
- }
276
-
277
- // Extract image files
278
- const imgMatches = html.match(/src="([^"]+\.(png|jpg|jpeg|gif|webp|svg)[^"]*)"/gi);
279
- if (imgMatches) {
280
- for (const match of imgMatches.slice(0, 1)) {
281
- const src = match.match(/src="([^"]+)"/)?.[1];
282
- if (src) {
283
- try {
284
- assets.push(new URL(src, baseUrl).href);
285
- } catch {
286
- // Invalid URL
287
- }
288
- }
289
- }
290
- }
291
- } catch {
292
- // Failed to fetch page
293
- }
294
-
295
- return assets;
296
- }
297
-
298
- function getAssetType(url: string): string {
299
- const lowerUrl = url.toLowerCase();
300
- if (lowerUrl.includes('.css')) return 'css';
301
- if (lowerUrl.includes('.js')) return 'javascript';
302
- if (lowerUrl.match(/\.(png|jpg|jpeg|gif|webp|svg|ico)/)) return 'image';
303
- if (lowerUrl.match(/\.(woff|woff2|ttf|otf|eot)/)) return 'font';
304
- return 'other';
305
- }
@@ -1,150 +0,0 @@
1
- import * as cheerio from 'cheerio';
2
- import { httpGet } from '../../utils/http.js';
3
- import type { AuditIssue } from '../types.js';
4
- import { ISSUE_DEFINITIONS } from '../types.js';
5
-
6
- export interface CanonicalData {
7
- canonical?: string;
8
- isSelfReferencing: boolean;
9
- isCrossDomain: boolean;
10
- canonicalChain?: string[];
11
- finalCanonical?: string;
12
- }
13
-
14
- export async function analyzeCanonicalAdvanced(
15
- html: string,
16
- url: string,
17
- options: { checkChain?: boolean; sitemapUrls?: string[] } = {}
18
- ): Promise<{ issues: AuditIssue[]; data: CanonicalData }> {
19
- const issues: AuditIssue[] = [];
20
- const $ = cheerio.load(html);
21
-
22
- const canonicalLink = $('link[rel="canonical"]').attr('href');
23
- const baseUrl = new URL(url);
24
-
25
- const data: CanonicalData = {
26
- canonical: canonicalLink,
27
- isSelfReferencing: false,
28
- isCrossDomain: false,
29
- };
30
-
31
- if (!canonicalLink) {
32
- return { issues, data };
33
- }
34
-
35
- // Resolve canonical URL
36
- let canonicalUrl: URL;
37
- try {
38
- canonicalUrl = new URL(canonicalLink, url);
39
- } catch {
40
- return { issues, data };
41
- }
42
-
43
- // Check if self-referencing
44
- const normalizedUrl = normalizeUrl(url);
45
- const normalizedCanonical = normalizeUrl(canonicalUrl.href);
46
- data.isSelfReferencing = normalizedUrl === normalizedCanonical;
47
-
48
- // Check for cross-domain canonical
49
- if (canonicalUrl.hostname !== baseUrl.hostname) {
50
- data.isCrossDomain = true;
51
- issues.push({
52
- ...ISSUE_DEFINITIONS.CANONICAL_CROSS_DOMAIN,
53
- affectedUrls: [url],
54
- details: {
55
- canonical: canonicalUrl.href,
56
- sourceDomain: baseUrl.hostname,
57
- targetDomain: canonicalUrl.hostname,
58
- },
59
- });
60
- }
61
-
62
- // Check for canonical chain if enabled
63
- if (options.checkChain && !data.isSelfReferencing) {
64
- const chain = await followCanonicalChain(canonicalUrl.href, [url]);
65
- if (chain.length > 2) {
66
- data.canonicalChain = chain;
67
- data.finalCanonical = chain[chain.length - 1];
68
- issues.push({
69
- ...ISSUE_DEFINITIONS.CANONICAL_CHAIN,
70
- affectedUrls: [url],
71
- details: {
72
- chain,
73
- depth: chain.length,
74
- },
75
- });
76
- }
77
- }
78
-
79
- // Check if canonical matches sitemap
80
- if (options.sitemapUrls && options.sitemapUrls.length > 0) {
81
- const sitemapNormalized = options.sitemapUrls.map(normalizeUrl);
82
- const urlInSitemap = sitemapNormalized.includes(normalizedUrl);
83
- const canonicalInSitemap = sitemapNormalized.includes(normalizedCanonical);
84
-
85
- if (urlInSitemap && !canonicalInSitemap && !data.isSelfReferencing) {
86
- issues.push({
87
- ...ISSUE_DEFINITIONS.CANONICAL_MISMATCH_SITEMAP,
88
- affectedUrls: [url],
89
- details: {
90
- pageUrl: url,
91
- canonical: canonicalUrl.href,
92
- message: 'Page is in sitemap but its canonical URL is not',
93
- },
94
- });
95
- }
96
- }
97
-
98
- return { issues, data };
99
- }
100
-
101
- async function followCanonicalChain(
102
- url: string,
103
- chain: string[] = [],
104
- maxDepth: number = 5
105
- ): Promise<string[]> {
106
- if (chain.length >= maxDepth) return chain;
107
-
108
- try {
109
- const response = await httpGet<string>(url, {
110
- timeout: 5000,
111
- maxRedirects: 5,
112
- validateStatus: (status) => status < 400,
113
- });
114
-
115
- const $ = cheerio.load(response.data);
116
- const nextCanonical = $('link[rel="canonical"]').attr('href');
117
-
118
- if (!nextCanonical) {
119
- return [...chain, url];
120
- }
121
-
122
- const resolvedCanonical = new URL(nextCanonical, url).href;
123
- const normalizedCurrent = normalizeUrl(url);
124
- const normalizedNext = normalizeUrl(resolvedCanonical);
125
-
126
- // Self-referencing, end of chain
127
- if (normalizedCurrent === normalizedNext) {
128
- return [...chain, url];
129
- }
130
-
131
- // Circular reference detection
132
- if (chain.some(u => normalizeUrl(u) === normalizedNext)) {
133
- return [...chain, url, resolvedCanonical + ' (circular)'];
134
- }
135
-
136
- return followCanonicalChain(resolvedCanonical, [...chain, url], maxDepth);
137
- } catch {
138
- return [...chain, url];
139
- }
140
- }
141
-
142
- function normalizeUrl(urlStr: string): string {
143
- try {
144
- const parsed = new URL(urlStr);
145
- // Remove trailing slash, lowercase hostname
146
- return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.pathname.replace(/\/$/, '')}`;
147
- } catch {
148
- return urlStr.toLowerCase().replace(/\/$/, '');
149
- }
150
- }
@@ -1,196 +0,0 @@
1
- /**
2
- * Canonical Domain Check
3
- *
4
- * Verifies that the site properly handles www vs non-www versions
5
- * to avoid duplicate content issues.
6
- *
7
- * Best practice: One version should redirect to the other (301 redirect).
8
- * Both versions serving content = duplicate content problem.
9
- */
10
-
11
- import { httpGet } from '../../utils/http.js';
12
- import type { AuditIssue } from '../types.js';
13
-
14
- export interface CanonicalDomainData {
15
- primaryDomain: string;
16
- wwwVersion: {
17
- url: string;
18
- status: number | null;
19
- redirectsTo?: string;
20
- accessible: boolean;
21
- };
22
- nonWwwVersion: {
23
- url: string;
24
- status: number | null;
25
- redirectsTo?: string;
26
- accessible: boolean;
27
- };
28
- hasProperRedirect: boolean;
29
- preferredVersion: 'www' | 'non-www' | 'unknown';
30
- httpsRedirect: {
31
- httpToHttps: boolean;
32
- httpsStatus: number | null;
33
- };
34
- }
35
-
36
- export async function analyzeCanonicalDomain(
37
- url: string
38
- ): Promise<{ issues: AuditIssue[]; data: CanonicalDomainData }> {
39
- const issues: AuditIssue[] = [];
40
- const parsedUrl = new URL(url);
41
- const hostname = parsedUrl.hostname;
42
-
43
- // Determine www and non-www versions
44
- const isWww = hostname.startsWith('www.');
45
- const wwwHostname = isWww ? hostname : `www.${hostname}`;
46
- const nonWwwHostname = isWww ? hostname.substring(4) : hostname;
47
-
48
- // Skip if hostname has multiple subdomains (e.g., api.staging.example.com)
49
- const parts = nonWwwHostname.split('.');
50
- if (parts.length > 2 && !nonWwwHostname.match(/\.(co|com|org|net|gov)\.[a-z]{2}$/i)) {
51
- // This is a subdomain, not a main domain
52
- return {
53
- issues: [],
54
- data: {
55
- primaryDomain: hostname,
56
- wwwVersion: { url: '', status: null, accessible: false },
57
- nonWwwVersion: { url: '', status: null, accessible: false },
58
- hasProperRedirect: true, // N/A for subdomains
59
- preferredVersion: 'unknown',
60
- httpsRedirect: { httpToHttps: false, httpsStatus: null },
61
- },
62
- };
63
- }
64
-
65
- const wwwUrl = `https://${wwwHostname}${parsedUrl.pathname}`;
66
- const nonWwwUrl = `https://${nonWwwHostname}${parsedUrl.pathname}`;
67
-
68
- // Test both versions
69
- const [wwwResult, nonWwwResult] = await Promise.all([
70
- testUrl(wwwUrl),
71
- testUrl(nonWwwUrl),
72
- ]);
73
-
74
- // Determine if proper redirect exists
75
- let hasProperRedirect = false;
76
- let preferredVersion: 'www' | 'non-www' | 'unknown' = 'unknown';
77
-
78
- // Check if www redirects to non-www
79
- if (wwwResult.status && wwwResult.status >= 300 && wwwResult.status < 400) {
80
- if (wwwResult.redirectsTo?.includes(nonWwwHostname)) {
81
- hasProperRedirect = true;
82
- preferredVersion = 'non-www';
83
- }
84
- }
85
-
86
- // Check if non-www redirects to www
87
- if (nonWwwResult.status && nonWwwResult.status >= 300 && nonWwwResult.status < 400) {
88
- if (nonWwwResult.redirectsTo?.includes(wwwHostname)) {
89
- hasProperRedirect = true;
90
- preferredVersion = 'www';
91
- }
92
- }
93
-
94
- // Both accessible without redirect = problem
95
- const bothAccessible =
96
- wwwResult.accessible &&
97
- nonWwwResult.accessible &&
98
- wwwResult.status === 200 &&
99
- nonWwwResult.status === 200;
100
-
101
- if (bothAccessible && !hasProperRedirect) {
102
- issues.push({
103
- code: 'CANONICAL_WWW_DUPLICATE',
104
- severity: 'warning',
105
- category: 'crawlability',
106
- title: 'Both www and non-www versions accessible',
107
- description: `Both ${wwwUrl} and ${nonWwwUrl} return 200 OK. This creates duplicate content.`,
108
- impact: 'Search engines may index both versions, diluting page authority and causing ranking issues.',
109
- howToFix: 'Set up a 301 redirect from one version to the other. Most sites prefer non-www, but either works. Configure at server/CDN level.',
110
- affectedUrls: [wwwUrl, nonWwwUrl],
111
- details: {
112
- wwwStatus: wwwResult.status,
113
- nonWwwStatus: nonWwwResult.status,
114
- recommendation: 'Choose one version as canonical and 301 redirect the other.',
115
- },
116
- });
117
- }
118
-
119
- // Check HTTP to HTTPS redirect
120
- const httpUrl = `http://${hostname}${parsedUrl.pathname}`;
121
- const httpResult = await testUrl(httpUrl);
122
-
123
- let httpToHttps = false;
124
- if (httpResult.status && httpResult.status >= 300 && httpResult.status < 400) {
125
- if (httpResult.redirectsTo?.startsWith('https://')) {
126
- httpToHttps = true;
127
- }
128
- }
129
-
130
- if (!httpToHttps && httpResult.accessible && httpResult.status === 200) {
131
- issues.push({
132
- code: 'CANONICAL_NO_HTTPS_REDIRECT',
133
- severity: 'warning',
134
- category: 'security',
135
- title: 'HTTP does not redirect to HTTPS',
136
- description: 'The HTTP version of the site is accessible without redirecting to HTTPS.',
137
- impact: 'Duplicate content issues and security concerns. Users may access insecure version.',
138
- howToFix: 'Configure a 301 redirect from HTTP to HTTPS at the server or CDN level.',
139
- affectedUrls: [httpUrl],
140
- });
141
- }
142
-
143
- return {
144
- issues,
145
- data: {
146
- primaryDomain: hostname,
147
- wwwVersion: {
148
- url: wwwUrl,
149
- status: wwwResult.status,
150
- redirectsTo: wwwResult.redirectsTo,
151
- accessible: wwwResult.accessible,
152
- },
153
- nonWwwVersion: {
154
- url: nonWwwUrl,
155
- status: nonWwwResult.status,
156
- redirectsTo: nonWwwResult.redirectsTo,
157
- accessible: nonWwwResult.accessible,
158
- },
159
- hasProperRedirect,
160
- preferredVersion,
161
- httpsRedirect: {
162
- httpToHttps,
163
- httpsStatus: httpResult.status,
164
- },
165
- },
166
- };
167
- }
168
-
169
- async function testUrl(url: string): Promise<{
170
- status: number | null;
171
- redirectsTo?: string;
172
- accessible: boolean;
173
- }> {
174
- try {
175
- const response = await httpGet<string>(url, {
176
- timeout: 10000,
177
- maxRedirects: 0, // Don't follow redirects
178
- validateStatus: () => true,
179
- });
180
-
181
- const status = response.status;
182
- const location = response.headers.location || response.headers.Location;
183
-
184
- return {
185
- status,
186
- redirectsTo: location,
187
- accessible: status !== null && status < 500,
188
- };
189
- } catch (error) {
190
- // DNS resolution failure, connection refused, etc.
191
- return {
192
- status: null,
193
- accessible: false,
194
- };
195
- }
196
- }