mcp-web-validator 1.3.4 → 1.3.6

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 CHANGED
@@ -4,6 +4,19 @@ All notable changes to this project are documented here. The project follows [Se
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.3.6] - 2026-09-21
8
+
9
+ ### Fixed
10
+
11
+ - Pinned each public HTTP(S) fetch hop to the DNS addresses already validated as public, closing a DNS-rebinding/TOCTOU gap between URL validation and connection establishment while preserving hostname-based TLS/SNI and redirect revalidation.
12
+
13
+ ## [1.3.5] - 2026-09-20
14
+
15
+ ### Fixed
16
+
17
+ - Rejected malformed Nu HTML Checker message objects instead of silently dropping them from local validation results.
18
+ - Withheld the validation report SEO score when JSON-LD/schema analysis is unavailable, preventing partial reports from treating missing schema evidence as clean.
19
+
7
20
  ## [1.3.4] - 2026-09-20
8
21
 
9
22
  ### Fixed
package/dist/network.d.ts CHANGED
@@ -22,10 +22,6 @@ export declare class PublicUrlError extends Error {
22
22
  readonly name = "PublicUrlError";
23
23
  }
24
24
  export declare function getErrorMessage(error: unknown): string;
25
- /**
26
- * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,
27
- * documentation, multicast, or otherwise non-public address space.
28
- */
29
25
  export declare function assertPublicHttpUrl(input: string | URL): Promise<URL>;
30
26
  export declare function cancelResponseBody(response: Response): Promise<void>;
31
27
  export declare function readResponseText(response: Response, maxBytes: number): Promise<string>;
package/dist/network.js CHANGED
@@ -2,6 +2,7 @@ import { lookup } from "node:dns/promises";
2
2
  import * as fs from "node:fs/promises";
3
3
  import { BlockList, isIP } from "node:net";
4
4
  import * as path from "node:path";
5
+ import { Agent } from "undici";
5
6
  const DEFAULT_TIMEOUT_MS = 10_000;
6
7
  const DEFAULT_MAX_REDIRECTS = 5;
7
8
  const DNS_TIMEOUT_MS = 5_000;
@@ -111,7 +112,7 @@ async function withTimeout(promise, timeoutMs, label) {
111
112
  * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,
112
113
  * documentation, multicast, or otherwise non-public address space.
113
114
  */
114
- export async function assertPublicHttpUrl(input) {
115
+ async function resolvePublicHttpUrl(input) {
115
116
  const rawUrl = input instanceof URL ? input.href : input;
116
117
  if (typeof rawUrl !== "string" || rawUrl.length === 0 || rawUrl.length > MAX_URL_LENGTH) {
117
118
  throw new PublicUrlError(`URL must contain between 1 and ${MAX_URL_LENGTH} characters`);
@@ -157,7 +158,10 @@ export async function assertPublicHttpUrl(input) {
157
158
  throw new PublicUrlError(`URL hostname resolves to non-public address ${record.address}`);
158
159
  }
159
160
  }
160
- return parsed;
161
+ return { url: parsed, addresses: resolvedAddresses };
162
+ }
163
+ export async function assertPublicHttpUrl(input) {
164
+ return (await resolvePublicHttpUrl(input)).url;
161
165
  }
162
166
  export async function cancelResponseBody(response) {
163
167
  if (!response.body) {
@@ -204,6 +208,34 @@ export async function readResponseText(response, maxBytes) {
204
208
  reader.releaseLock();
205
209
  }
206
210
  }
211
+ function createPinnedDispatcher(resolvedAddresses) {
212
+ const addresses = resolvedAddresses.map((record) => ({ ...record }));
213
+ return new Agent({
214
+ // Every validated request gets its own non-reused connection so a later DNS
215
+ // answer cannot replace the address set approved for this hop.
216
+ pipelining: 0,
217
+ connect: {
218
+ lookup: (_hostname, options, callback) => {
219
+ const requestedFamily = options.family === 4 || options.family === 6 ? options.family : 0;
220
+ const candidates = requestedFamily
221
+ ? addresses.filter((record) => record.family === requestedFamily)
222
+ : addresses;
223
+ if (candidates.length === 0) {
224
+ const error = new Error("No validated address is available for the requested IP family");
225
+ error.code = "ENOTFOUND";
226
+ callback(error, []);
227
+ return;
228
+ }
229
+ if (options.all) {
230
+ callback(null, candidates);
231
+ return;
232
+ }
233
+ const selected = candidates[0];
234
+ callback(null, selected.address, selected.family);
235
+ },
236
+ },
237
+ });
238
+ }
207
239
  /** Fetches a public HTTP(S) URL while validating every redirect target. */
208
240
  export async function fetchPublicHttp(input, options = {}) {
209
241
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -212,33 +244,43 @@ export async function fetchPublicHttp(input, options = {}) {
212
244
  if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {
213
245
  throw new Error("maxRedirects must be an integer between 0 and 10");
214
246
  }
215
- let currentUrl = await assertPublicHttpUrl(input);
247
+ let currentTarget = await resolvePublicHttpUrl(input);
216
248
  for (let redirectCount = 0;; redirectCount += 1) {
217
- const response = await fetch(currentUrl, {
218
- method: options.method ?? "GET",
219
- headers: options.headers,
220
- redirect: "manual",
221
- signal: AbortSignal.timeout(timeoutMs),
222
- });
249
+ const dispatcher = createPinnedDispatcher(currentTarget.addresses);
250
+ let response;
251
+ try {
252
+ response = await fetch(currentTarget.url, {
253
+ method: options.method ?? "GET",
254
+ headers: options.headers,
255
+ redirect: "manual",
256
+ signal: AbortSignal.timeout(timeoutMs),
257
+ dispatcher,
258
+ });
259
+ }
260
+ catch (error) {
261
+ await dispatcher.close();
262
+ throw error;
263
+ }
223
264
  if (!redirectStatuses.has(response.status)) {
224
- return { response, url: currentUrl };
265
+ return { response, url: currentTarget.url };
225
266
  }
226
267
  const location = response.headers.get("location");
227
268
  if (!location) {
228
- return { response, url: currentUrl };
269
+ return { response, url: currentTarget.url };
229
270
  }
230
271
  if (redirectCount >= maxRedirects) {
231
- return { response, url: currentUrl };
272
+ return { response, url: currentTarget.url };
232
273
  }
233
274
  await cancelResponseBody(response);
275
+ await dispatcher.close();
234
276
  let redirectUrl;
235
277
  try {
236
- redirectUrl = new URL(location, currentUrl);
278
+ redirectUrl = new URL(location, currentTarget.url);
237
279
  }
238
280
  catch {
239
281
  throw new PublicUrlError("Redirect target is not a valid URL");
240
282
  }
241
- currentUrl = await assertPublicHttpUrl(redirectUrl);
283
+ currentTarget = await resolvePublicHttpUrl(redirectUrl);
242
284
  }
243
285
  }
244
286
  /** Fetches bounded text from a public URL and rejects non-success responses. */
@@ -1 +1 @@
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AQ,EAAE,UAAU,CAAC,CAAC;IAC5C,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1C,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,+BAA+B,YAAY,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,GAAG,QAAQ,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IACjD,IAAI,QAAQ,CAAC,UAAU,GAAG,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport * as fs from \"node:fs/promises\";\nimport { BlockList, isIP } from \"node:net\";\nimport * as path from \"node:path\";\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_REDIRECTS = 5;\nconst DNS_TIMEOUT_MS = 5_000;\nconst MAX_URL_LENGTH = 8_192;\n\nconst blockedAddresses = new BlockList();\nfor (const [network, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv4\");\n}\n\nfor (const [network, prefix] of [\n [\"::\", 96],\n [\"fc00::\", 7],\n [\"fe80::\", 10],\n [\"ff00::\", 8],\n [\"2001::\", 32],\n [\"2001:2::\", 48],\n [\"2001:10::\", 28],\n [\"2001:db8::\", 32],\n [\"2002::\", 16],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv6\");\n}\n\nconst publicIpv6Addresses = new BlockList();\npublicIpv6Addresses.addSubnet(\"2000::\", 3, \"ipv6\");\n\nconst blockedHostnames = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n\nconst blockedHostnameSuffixes = [\n \".localhost\",\n \".local\",\n \".internal\",\n \".home.arpa\",\n \".test\",\n \".invalid\",\n \".example\",\n \".onion\",\n];\n\nconst redirectStatuses = new Set([301, 302, 303, 307, 308]);\n\nexport interface PublicFetchOptions {\n method?: \"GET\" | \"HEAD\";\n headers?: Record<string, string>;\n timeoutMs?: number;\n maxRedirects?: number;\n}\n\nexport interface PublicTextOptions extends PublicFetchOptions {\n maxBytes?: number;\n acceptedContentTypes?: readonly string[];\n}\n\nexport interface PublicTextResult {\n text: string;\n url: string;\n status: number;\n contentType: string | null;\n}\n\nexport interface PublicHttpResult {\n response: Response;\n url: URL;\n}\n\nexport class PublicUrlError extends Error {\n override readonly name = \"PublicUrlError\";\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") {\n return \"Request timed out\";\n }\n return error.message || error.name;\n }\n\n return typeof error === \"string\" && error.trim() ? error : \"Unknown error\";\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive integer`);\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets = hostname.startsWith(\"[\") && hostname.endsWith(\"]\")\n ? hostname.slice(1, -1)\n : hostname;\n return withoutBrackets.replace(/\\.$/, \"\").toLowerCase();\n}\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n return !blockedAddresses.check(address, \"ipv4\");\n }\n\n if (family === 6) {\n return publicIpv6Addresses.check(address, \"ipv6\")\n && !blockedAddresses.check(address, \"ipv6\");\n }\n\n return false;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timeout: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n\n/**\n * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,\n * documentation, multicast, or otherwise non-public address space.\n */\nexport async function assertPublicHttpUrl(input: string | URL): Promise<URL> {\n const rawUrl = input instanceof URL ? input.href : input;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0 || rawUrl.length > MAX_URL_LENGTH) {\n throw new PublicUrlError(`URL must contain between 1 and ${MAX_URL_LENGTH} characters`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n throw new PublicUrlError(\"URL must be an absolute HTTP or HTTPS URL\");\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new PublicUrlError(\"Only HTTP and HTTPS URLs are allowed\");\n }\n if (parsed.username || parsed.password) {\n throw new PublicUrlError(\"URLs containing credentials are not allowed\");\n }\n // URL normalizes matching defaults (HTTP :80 / HTTPS :443) to an empty port.\n // Any remaining port is custom or mismatched to the scheme and must be rejected.\n if (parsed.port) {\n throw new PublicUrlError(\"Only default HTTP and HTTPS ports are allowed\");\n }\n\n parsed.hash = \"\";\n const hostname = normalizeHostname(parsed.hostname);\n if (!hostname) {\n throw new PublicUrlError(\"URL hostname is required\");\n }\n if (\n blockedHostnames.has(hostname)\n || blockedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix))\n ) {\n throw new PublicUrlError(`URL hostname \"${hostname}\" is not public`);\n }\n\n const literalFamily = isIP(hostname);\n const resolvedAddresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withTimeout(\n lookup(hostname, { all: true, verbatim: true }),\n DNS_TIMEOUT_MS,\n \"DNS lookup\",\n ).catch((error: unknown) => {\n throw new PublicUrlError(`Unable to resolve URL hostname: ${getErrorMessage(error)}`);\n });\n\n if (resolvedAddresses.length === 0) {\n throw new PublicUrlError(\"URL hostname did not resolve to an address\");\n }\n\n for (const record of resolvedAddresses) {\n if (!isPublicAddress(record.address, record.family)) {\n throw new PublicUrlError(`URL hostname resolves to non-public address ${record.address}`);\n }\n }\n\n return parsed;\n}\n\nexport async function cancelResponseBody(response: Response): Promise<void> {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // The stream may already be closed or consumed; there is nothing left to release.\n }\n}\n\nexport async function readResponseText(response: Response, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const declaredLength = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n await cancelResponseBody(response);\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let text = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n text += decoder.decode(value, { stream: true });\n }\n text += decoder.decode();\n return text;\n } finally {\n reader.releaseLock();\n }\n}\n\n/** Fetches a public HTTP(S) URL while validating every redirect target. */\nexport async function fetchPublicHttp(\n input: string | URL,\n options: PublicFetchOptions = {},\n): Promise<PublicHttpResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n assertPositiveInteger(timeoutMs, \"timeoutMs\");\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n throw new Error(\"maxRedirects must be an integer between 0 and 10\");\n }\n\n let currentUrl = await assertPublicHttpUrl(input);\n for (let redirectCount = 0; ; redirectCount += 1) {\n const response = await fetch(currentUrl, {\n method: options.method ?? \"GET\",\n headers: options.headers,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n\n if (!redirectStatuses.has(response.status)) {\n return { response, url: currentUrl };\n }\n\n const location = response.headers.get(\"location\");\n if (!location) {\n return { response, url: currentUrl };\n }\n\n if (redirectCount >= maxRedirects) {\n return { response, url: currentUrl };\n }\n\n await cancelResponseBody(response);\n let redirectUrl: URL;\n try {\n redirectUrl = new URL(location, currentUrl);\n } catch {\n throw new PublicUrlError(\"Redirect target is not a valid URL\");\n }\n currentUrl = await assertPublicHttpUrl(redirectUrl);\n }\n}\n\n/** Fetches bounded text from a public URL and rejects non-success responses. */\nexport async function fetchPublicText(\n input: string | URL,\n options: PublicTextOptions = {},\n): Promise<PublicTextResult> {\n const maxBytes = options.maxBytes ?? 2_000_000;\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const { response, url } = await fetchPublicHttp(input, {\n method: \"GET\",\n headers: options.headers,\n timeoutMs: options.timeoutMs,\n maxRedirects: options.maxRedirects,\n });\n\n if (!response.ok) {\n const status = response.status;\n await cancelResponseBody(response);\n throw new Error(`URL returned HTTP status ${status}`);\n }\n\n const contentTypeHeader = response.headers.get(\"content-type\");\n const contentType = contentTypeHeader?.split(\";\", 1)[0]?.trim().toLowerCase() || null;\n if (\n options.acceptedContentTypes\n && !options.acceptedContentTypes.some((accepted) => accepted.trim().toLowerCase() === contentType)\n ) {\n await cancelResponseBody(response);\n throw new Error(`URL returned unsupported content type ${contentType ?? \"missing\"}`);\n }\n\n return {\n text: await readResponseText(response, maxBytes),\n url: url.href,\n status: response.status,\n contentType: contentTypeHeader,\n };\n}\n\n/** Reads a UTF-8 file only when it is a regular file within the requested cap. */\nexport async function readTextFile(filePath: string, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n const resolvedPath = path.resolve(filePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Path is not a regular file: ${resolvedPath}`);\n }\n if (stats.size > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n\n const contents = await fs.readFile(resolvedPath);\n if (contents.byteLength > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n return contents.toString(\"utf8\");\n}\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAE/B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,cAAc,GAAG,KAAK,CAAC;AAE7B,MAAM,gBAAgB,GAAG,IAAI,SAAS,EAAE,CAAC;AACzC,KAAK,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI;IAC9B,CAAC,SAAS,EAAE,CAAC,CAAC;IACd,CAAC,UAAU,EAAE,CAAC,CAAC;IACf,CAAC,YAAY,EAAE,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M,KAAK,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1C,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,+BAA+B,YAAY,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,GAAG,QAAQ,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IACjD,IAAI,QAAQ,CAAC,UAAU,GAAG,QAAQ,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,gBAAgB,YAAY,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import { lookup } from \"node:dns/promises\";\nimport * as fs from \"node:fs/promises\";\nimport { BlockList, isIP } from \"node:net\";\nimport * as path from \"node:path\";\nimport { Agent } from \"undici\";\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_REDIRECTS = 5;\nconst DNS_TIMEOUT_MS = 5_000;\nconst MAX_URL_LENGTH = 8_192;\n\nconst blockedAddresses = new BlockList();\nfor (const [network, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv4\");\n}\n\nfor (const [network, prefix] of [\n [\"::\", 96],\n [\"fc00::\", 7],\n [\"fe80::\", 10],\n [\"ff00::\", 8],\n [\"2001::\", 32],\n [\"2001:2::\", 48],\n [\"2001:10::\", 28],\n [\"2001:db8::\", 32],\n [\"2002::\", 16],\n] as const) {\n blockedAddresses.addSubnet(network, prefix, \"ipv6\");\n}\n\nconst publicIpv6Addresses = new BlockList();\npublicIpv6Addresses.addSubnet(\"2000::\", 3, \"ipv6\");\n\nconst blockedHostnames = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n\nconst blockedHostnameSuffixes = [\n \".localhost\",\n \".local\",\n \".internal\",\n \".home.arpa\",\n \".test\",\n \".invalid\",\n \".example\",\n \".onion\",\n];\n\nconst redirectStatuses = new Set([301, 302, 303, 307, 308]);\n\nexport interface PublicFetchOptions {\n method?: \"GET\" | \"HEAD\";\n headers?: Record<string, string>;\n timeoutMs?: number;\n maxRedirects?: number;\n}\n\nexport interface PublicTextOptions extends PublicFetchOptions {\n maxBytes?: number;\n acceptedContentTypes?: readonly string[];\n}\n\nexport interface PublicTextResult {\n text: string;\n url: string;\n status: number;\n contentType: string | null;\n}\n\nexport interface PublicHttpResult {\n response: Response;\n url: URL;\n}\n\ninterface ResolvedPublicHttpUrl {\n url: URL;\n addresses: Array<{ address: string; family: number }>;\n}\n\nexport class PublicUrlError extends Error {\n override readonly name = \"PublicUrlError\";\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") {\n return \"Request timed out\";\n }\n return error.message || error.name;\n }\n\n return typeof error === \"string\" && error.trim() ? error : \"Unknown error\";\n}\n\nfunction assertPositiveInteger(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${label} must be a positive integer`);\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets = hostname.startsWith(\"[\") && hostname.endsWith(\"]\")\n ? hostname.slice(1, -1)\n : hostname;\n return withoutBrackets.replace(/\\.$/, \"\").toLowerCase();\n}\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n return !blockedAddresses.check(address, \"ipv4\");\n }\n\n if (family === 6) {\n return publicIpv6Addresses.check(address, \"ipv6\")\n && !blockedAddresses.check(address, \"ipv6\");\n }\n\n return false;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timeout: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timeout = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n\n/**\n * Parses an HTTP(S) URL and rejects hostnames that resolve to local, private,\n * documentation, multicast, or otherwise non-public address space.\n */\nasync function resolvePublicHttpUrl(input: string | URL): Promise<ResolvedPublicHttpUrl> {\n const rawUrl = input instanceof URL ? input.href : input;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0 || rawUrl.length > MAX_URL_LENGTH) {\n throw new PublicUrlError(`URL must contain between 1 and ${MAX_URL_LENGTH} characters`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n throw new PublicUrlError(\"URL must be an absolute HTTP or HTTPS URL\");\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new PublicUrlError(\"Only HTTP and HTTPS URLs are allowed\");\n }\n if (parsed.username || parsed.password) {\n throw new PublicUrlError(\"URLs containing credentials are not allowed\");\n }\n // URL normalizes matching defaults (HTTP :80 / HTTPS :443) to an empty port.\n // Any remaining port is custom or mismatched to the scheme and must be rejected.\n if (parsed.port) {\n throw new PublicUrlError(\"Only default HTTP and HTTPS ports are allowed\");\n }\n\n parsed.hash = \"\";\n const hostname = normalizeHostname(parsed.hostname);\n if (!hostname) {\n throw new PublicUrlError(\"URL hostname is required\");\n }\n if (\n blockedHostnames.has(hostname)\n || blockedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix))\n ) {\n throw new PublicUrlError(`URL hostname \"${hostname}\" is not public`);\n }\n\n const literalFamily = isIP(hostname);\n const resolvedAddresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withTimeout(\n lookup(hostname, { all: true, verbatim: true }),\n DNS_TIMEOUT_MS,\n \"DNS lookup\",\n ).catch((error: unknown) => {\n throw new PublicUrlError(`Unable to resolve URL hostname: ${getErrorMessage(error)}`);\n });\n\n if (resolvedAddresses.length === 0) {\n throw new PublicUrlError(\"URL hostname did not resolve to an address\");\n }\n\n for (const record of resolvedAddresses) {\n if (!isPublicAddress(record.address, record.family)) {\n throw new PublicUrlError(`URL hostname resolves to non-public address ${record.address}`);\n }\n }\n\n return { url: parsed, addresses: resolvedAddresses };\n}\n\nexport async function assertPublicHttpUrl(input: string | URL): Promise<URL> {\n return (await resolvePublicHttpUrl(input)).url;\n}\n\nexport async function cancelResponseBody(response: Response): Promise<void> {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // The stream may already be closed or consumed; there is nothing left to release.\n }\n}\n\nexport async function readResponseText(response: Response, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const declaredLength = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n await cancelResponseBody(response);\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let text = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw new Error(`Response exceeds the ${maxBytes}-byte limit`);\n }\n text += decoder.decode(value, { stream: true });\n }\n text += decoder.decode();\n return text;\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction createPinnedDispatcher(\n resolvedAddresses: ReadonlyArray<{ address: string; family: number }>,\n): Agent {\n const addresses = resolvedAddresses.map((record) => ({ ...record }));\n\n return new Agent({\n // Every validated request gets its own non-reused connection so a later DNS\n // answer cannot replace the address set approved for this hop.\n pipelining: 0,\n connect: {\n lookup: (_hostname, options, callback) => {\n const requestedFamily = options.family === 4 || options.family === 6 ? options.family : 0;\n const candidates = requestedFamily\n ? addresses.filter((record) => record.family === requestedFamily)\n : addresses;\n\n if (candidates.length === 0) {\n const error = new Error(\"No validated address is available for the requested IP family\") as NodeJS.ErrnoException;\n error.code = \"ENOTFOUND\";\n callback(error, []);\n return;\n }\n\n if (options.all) {\n callback(null, candidates);\n return;\n }\n\n const selected = candidates[0];\n callback(null, selected.address, selected.family);\n },\n },\n });\n}\n\n/** Fetches a public HTTP(S) URL while validating every redirect target. */\nexport async function fetchPublicHttp(\n input: string | URL,\n options: PublicFetchOptions = {},\n): Promise<PublicHttpResult> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n assertPositiveInteger(timeoutMs, \"timeoutMs\");\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n throw new Error(\"maxRedirects must be an integer between 0 and 10\");\n }\n\n let currentTarget = await resolvePublicHttpUrl(input);\n for (let redirectCount = 0; ; redirectCount += 1) {\n const dispatcher = createPinnedDispatcher(currentTarget.addresses);\n let response: Response;\n try {\n response = await fetch(currentTarget.url, {\n method: options.method ?? \"GET\",\n headers: options.headers,\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n dispatcher,\n } as RequestInit & { dispatcher: Agent });\n } catch (error) {\n await dispatcher.close();\n throw error;\n }\n\n if (!redirectStatuses.has(response.status)) {\n return { response, url: currentTarget.url };\n }\n\n const location = response.headers.get(\"location\");\n if (!location) {\n return { response, url: currentTarget.url };\n }\n\n if (redirectCount >= maxRedirects) {\n return { response, url: currentTarget.url };\n }\n\n await cancelResponseBody(response);\n await dispatcher.close();\n let redirectUrl: URL;\n try {\n redirectUrl = new URL(location, currentTarget.url);\n } catch {\n throw new PublicUrlError(\"Redirect target is not a valid URL\");\n }\n currentTarget = await resolvePublicHttpUrl(redirectUrl);\n }\n}\n\n/** Fetches bounded text from a public URL and rejects non-success responses. */\nexport async function fetchPublicText(\n input: string | URL,\n options: PublicTextOptions = {},\n): Promise<PublicTextResult> {\n const maxBytes = options.maxBytes ?? 2_000_000;\n assertPositiveInteger(maxBytes, \"maxBytes\");\n\n const { response, url } = await fetchPublicHttp(input, {\n method: \"GET\",\n headers: options.headers,\n timeoutMs: options.timeoutMs,\n maxRedirects: options.maxRedirects,\n });\n\n if (!response.ok) {\n const status = response.status;\n await cancelResponseBody(response);\n throw new Error(`URL returned HTTP status ${status}`);\n }\n\n const contentTypeHeader = response.headers.get(\"content-type\");\n const contentType = contentTypeHeader?.split(\";\", 1)[0]?.trim().toLowerCase() || null;\n if (\n options.acceptedContentTypes\n && !options.acceptedContentTypes.some((accepted) => accepted.trim().toLowerCase() === contentType)\n ) {\n await cancelResponseBody(response);\n throw new Error(`URL returned unsupported content type ${contentType ?? \"missing\"}`);\n }\n\n return {\n text: await readResponseText(response, maxBytes),\n url: url.href,\n status: response.status,\n contentType: contentTypeHeader,\n };\n}\n\n/** Reads a UTF-8 file only when it is a regular file within the requested cap. */\nexport async function readTextFile(filePath: string, maxBytes: number): Promise<string> {\n assertPositiveInteger(maxBytes, \"maxBytes\");\n const resolvedPath = path.resolve(filePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Path is not a regular file: ${resolvedPath}`);\n }\n if (stats.size > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n\n const contents = await fs.readFile(resolvedPath);\n if (contents.byteLength > maxBytes) {\n throw new Error(`File exceeds the ${maxBytes}-byte limit: ${resolvedPath}`);\n }\n return contents.toString(\"utf8\");\n}\n"]}
package/dist/report.js CHANGED
@@ -40,7 +40,9 @@ export function createValidationReport(input) {
40
40
  const cssScore = checkFailed("css") || !input.cssAudited || cssCompatibilityLimitations > 0
41
41
  ? null
42
42
  : clampScore(100 - cssErrors * 20);
43
- const seoScore = checkFailed("seo") ? null : clampScore(100 - seoErrors * 15 - seoWarnings * 4 - schemaErrors * 15);
43
+ const seoScore = checkFailed("seo") || checkFailed("schema")
44
+ ? null
45
+ : clampScore(100 - seoErrors * 15 - seoWarnings * 4 - schemaErrors * 15);
44
46
  const linkScore = checkFailed("links") || input.links.length === 0
45
47
  ? null
46
48
  : clampScore(100 - brokenLinks * 25);
@@ -1 +1 @@
1
- {"version":3,"file":"report.js","sourceRoot":"","sources":["../src/report.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAIlC,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAU,CAAC;AA4ClG,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,cAAc,CAAC,KAAoB;IAC1C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,aAAa,CAAC;IACzC,IAAI,KAAK,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;IAC7B,IAAI,KAAK,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;IAC7B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;SACvB,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC;SACtB,OAAO,CAAC,KAAK,EA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D,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,wCAAwC,EAAE,iCAAiC,CAAC,CAAC;QAC7F,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAC/B,MAAM,CAAC,IAAI,CACT,KAAK,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,MAAM,YAAY,CAAC,IAAI,CAAC,OAAO,IAAI,YAAY,CAAC,IAAI,CAC3I,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;QACzB,OAAO;QACP,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,YAAY;QACZ,GAAG,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7E,CAAC;AACJ,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport type { CSSMessage, W3CMessage } from \"./w3c-validator.js\";\nimport type { LinkStatus, SEOIssue } from \"./seo-auditor.js\";\n\nexport const validationReportChecks = [\"input\", \"html\", \"css\", \"seo\", \"schema\", \"links\"] as const;\nexport type ValidationReportCheck = (typeof validationReportChecks)[number];\n\nexport interface ValidationReportSummary {\n overallScore: number | null;\n htmlScore: number | null;\n cssScore: number | null;\n seoScore: number | null;\n linkScore: number | null;\n htmlErrors: number;\n htmlWarnings: number;\n cssErrors: number;\n cssCompatibilityLimitations: number;\n seoErrors: number;\n seoWarnings: number;\n schemaErrors: number;\n linksChecked: number;\n brokenLinks: number;\n}\n\nexport interface ValidationReport {\n report: string;\n summary: ValidationReportSummary;\n htmlMessages: W3CMessage[];\n cssMessages: CSSMessage[];\n seoIssues: SEOIssue[];\n schemaIssues: SEOIssue[];\n links: LinkStatus[];\n failedChecks: ValidationReportCheck[];\n errors?: string[];\n}\n\nexport interface ValidationReportInput {\n htmlFilePath: string;\n cssAudited: boolean;\n htmlMessages: W3CMessage[];\n cssMessages: CSSMessage[];\n seoIssues: SEOIssue[];\n schemaIssues: SEOIssue[];\n links: LinkStatus[];\n failedChecks?: ValidationReportCheck[];\n errors?: string[];\n}\n\nfunction clampScore(score: number): number {\n return Math.max(0, Math.min(100, score));\n}\n\nfunction scoreIndicator(score: number | null): string {\n if (score === null) return \"Unavailable\";\n if (score >= 90) return \"🟢\";\n if (score >= 50) return \"🟠\";\n return \"🔴\";\n}\n\nfunction markdownCell(value: unknown): string {\n return String(value ?? \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\|/g, \"\\\\|\")\n .replace(/`/g, \"\\\\`\")\n .replace(/[\\r\\n]+/g, \" \")\n .trim();\n}\n\nfunction isRedirect(link: LinkStatus): boolean {\n return typeof link.status === \"number\" && link.status >= 300 && link.status < 400;\n}\n\n/** Builds the human-readable report and its machine-readable equivalent. */\nexport function createValidationReport(input: ValidationReportInput): ValidationReport {\n const failedChecks = input.failedChecks ?? [];\n const checkFailed = (check: ValidationReportCheck): boolean => failedChecks.includes(check);\n const htmlErrors = input.htmlMessages.filter((message) => message.type === \"error\").length;\n const htmlWarnings = input.htmlMessages.length - htmlErrors;\n const cssErrors = input.cssMessages.length;\n const cssCompatibilityLimitations = input.cssMessages.filter(\n (message) => message.compatibility === \"known-validator-limitation\",\n ).length;\n const seoErrors = input.seoIssues.filter((issue) => issue.severity === \"error\").length;\n const seoWarnings = input.seoIssues.filter((issue) => issue.severity === \"warning\").length;\n const schemaErrors = input.schemaIssues.filter((issue) => issue.severity === \"error\").length;\n const brokenLinks = input.links.filter((link) => !link.ok).length;\n const redirectLinks = input.links.filter(isRedirect).length;\n\n const htmlScore = checkFailed(\"html\") ? null : clampScore(100 - htmlErrors * 15 - htmlWarnings * 2);\n const cssScore = checkFailed(\"css\") || !input.cssAudited || cssCompatibilityLimitations > 0\n ? null\n : clampScore(100 - cssErrors * 20);\n const seoScore = checkFailed(\"seo\") ? null : clampScore(100 - seoErrors * 15 - seoWarnings * 4 - schemaErrors * 15);\n const linkScore = checkFailed(\"links\") || input.links.length === 0\n ? null\n : clampScore(100 - brokenLinks * 25);\n const auditedScores = [htmlScore, seoScore, cssScore, linkScore].filter(\n (score): score is number => score !== null,\n );\n const overallScore = failedChecks.length > 0 || cssCompatibilityLimitations > 0 || auditedScores.length === 0\n ? null\n : Math.round(auditedScores.reduce((total, score) => total + score, 0) / auditedScores.length);\n\n const summary: ValidationReportSummary = {\n overallScore,\n htmlScore,\n cssScore,\n seoScore,\n linkScore,\n htmlErrors,\n htmlWarnings,\n cssErrors,\n cssCompatibilityLimitations,\n seoErrors,\n seoWarnings,\n schemaErrors,\n linksChecked: input.links.length,\n brokenLinks,\n };\n\n const report: string[] = [\n `# Web Validation & SEO Audit Report — ${overallScore === null ? \"Partial\" : `${scoreIndicator(overallScore)} **${overallScore}**/100`}`,\n `*Generated for: \\`${markdownCell(path.basename(input.htmlFilePath))}\\`*`,\n \"\",\n \"## Page health scores\",\n \"\",\n \"| Audit | Status | Score |\",\n \"| :--- | :---: | :---: |\",\n `| W3C HTML validation | ${htmlScore === null ? \"Unavailable\" : scoreIndicator(htmlScore)} | ${htmlScore === null ? \"N/A\" : `**${htmlScore}** / 100`} |`,\n `| CSS validation | ${cssScore === null ? (checkFailed(\"css\") ? \"Unavailable\" : cssCompatibilityLimitations > 0 ? \"Compatibility-limited\" : \"Not audited\") : scoreIndicator(cssScore)} | ${cssScore === null ? \"N/A\" : `**${cssScore}** / 100`} |`,\n `| SEO and accessibility | ${seoScore === null ? \"Unavailable\" : scoreIndicator(seoScore)} | ${seoScore === null ? \"N/A\" : `**${seoScore}** / 100`} |`,\n `| Link integrity | ${linkScore === null ? (checkFailed(\"links\") ? \"Unavailable\" : \"No links checked\") : scoreIndicator(linkScore)} | ${linkScore === null ? \"N/A\" : `**${linkScore}** / 100`} |`,\n \"\",\n \"## Summary\",\n \"\",\n `- HTML: ${htmlErrors} error(s), ${htmlWarnings} other diagnostic(s)` ,\n `- CSS: ${input.cssAudited ? `${cssErrors} error(s)${cssCompatibilityLimitations > 0 ? `, ${cssCompatibilityLimitations} known validator limitation(s)` : \"\"}` : \"not audited\"}`,\n `- SEO and accessibility: ${seoErrors} error(s), ${seoWarnings} warning(s)`,\n `- JSON-LD syntax: ${schemaErrors} error(s)`,\n `- Links: ${brokenLinks} broken or unreachable, ${redirectLinks} redirect${redirectLinks === 1 ? \"\" : \"s\"} to review of ${input.links.length} checked`,\n \"\",\n `## HTML diagnostics (${input.htmlMessages.length})`,\n ];\n\n if (failedChecks.length > 0) {\n report.splice(2, 0, \"\", \"## Partial validation report\", \"The following checks were unavailable: \" + failedChecks.join(\", \") + \". Remaining checks completed.\");\n }\n\n if (input.htmlMessages.length === 0) {\n report.push(\"No HTML validation diagnostics were returned.\");\n } else {\n report.push(\"\", \"| Line | Column | Severity | Message | Extract |\", \"| :---: | :---: | :--- | :--- | :--- |\");\n for (const message of input.htmlMessages) {\n report.push(\n `| ${message.lastLine ?? \"N/A\"} | ${message.lastColumn ?? \"N/A\"} | ${markdownCell(message.type)} | ${markdownCell(message.message)} | ${markdownCell(message.extract ?? \"N/A\")} |`,\n );\n }\n }\n\n if (input.cssAudited) {\n report.push(\"\", `## CSS diagnostics (${input.cssMessages.length})`);\n if (input.cssMessages.length === 0) {\n report.push(\"No CSS validation errors were returned.\");\n } else {\n report.push(\"\", \"| Line | Context | Message |\", \"| :---: | :--- | :--- |\");\n for (const message of input.cssMessages) {\n report.push(\n `| ${message.line} | ${markdownCell(message.context ?? \"N/A\")} | ${markdownCell(message.message)} |`,\n );\n }\n if (cssCompatibilityLimitations > 0) {\n report.push(\n \"\",\n `${cssCompatibilityLimitations} known validator limitation(s) match Jigsaw's current parser gap for the standards-defined \\`@container\\` rule. The original Jigsaw diagnostic is preserved, but CSS and overall scores are withheld because this upstream limitation can report valid modern CSS as invalid.`,\n );\n }\n }\n }\n\n const combinedIssues = [...input.seoIssues, ...input.schemaIssues];\n report.push(\"\", `## SEO, accessibility, and JSON-LD findings (${combinedIssues.length})`);\n if (combinedIssues.length === 0) {\n report.push(\"No SEO, accessibility, or JSON-LD syntax findings were returned.\");\n } else {\n report.push(\"\", \"| Category | Severity | Message | Element |\", \"| :--- | :--- | :--- | :--- |\");\n for (const issue of combinedIssues) {\n report.push(\n `| ${markdownCell(issue.category)} | ${markdownCell(issue.severity)} | ${markdownCell(issue.message)} | ${markdownCell(issue.element ?? \"N/A\")} |`,\n );\n }\n }\n\n report.push(\"\", `## Link health (${input.links.length} checked)`);\n if (input.links.length === 0) {\n report.push(\"No public HTTP(S) links were checked.\");\n } else {\n report.push(\"\", \"| URL | Status | Reachable | Details |\", \"| :--- | :---: | :---: | :--- |\");\n for (const link of input.links) {\n report.push(\n `| ${markdownCell(link.url)} | ${markdownCell(link.status)} | ${link.ok ? \"Yes\" : \"No\"} | ${markdownCell(link.message ?? \"Accessible\")} |`,\n );\n }\n }\n\n return {\n report: report.join(\"\\n\"),\n summary,\n htmlMessages: input.htmlMessages,\n cssMessages: input.cssMessages,\n seoIssues: input.seoIssues,\n schemaIssues: input.schemaIssues,\n links: input.links,\n failedChecks,\n ...(input.errors && input.errors.length > 0 ? { errors: input.errors } : {}),\n };\n}\n"]}
1
+ {"version":3,"file":"report.js","sourceRoot":"","sources":["../src/report.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAIlC,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,OAAO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,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,YAAY;QACZ,GAAG,CAAC,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7E,CAAC;AACJ,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport type { CSSMessage, W3CMessage } from \"./w3c-validator.js\";\nimport type { LinkStatus, SEOIssue } from \"./seo-auditor.js\";\n\nexport const validationReportChecks = [\"input\", \"html\", \"css\", \"seo\", \"schema\", \"links\"] as const;\nexport type ValidationReportCheck = (typeof validationReportChecks)[number];\n\nexport interface ValidationReportSummary {\n overallScore: number | null;\n htmlScore: number | null;\n cssScore: number | null;\n seoScore: number | null;\n linkScore: number | null;\n htmlErrors: number;\n htmlWarnings: number;\n cssErrors: number;\n cssCompatibilityLimitations: number;\n seoErrors: number;\n seoWarnings: number;\n schemaErrors: number;\n linksChecked: number;\n brokenLinks: number;\n}\n\nexport interface ValidationReport {\n report: string;\n summary: ValidationReportSummary;\n htmlMessages: W3CMessage[];\n cssMessages: CSSMessage[];\n seoIssues: SEOIssue[];\n schemaIssues: SEOIssue[];\n links: LinkStatus[];\n failedChecks: ValidationReportCheck[];\n errors?: string[];\n}\n\nexport interface ValidationReportInput {\n htmlFilePath: string;\n cssAudited: boolean;\n htmlMessages: W3CMessage[];\n cssMessages: CSSMessage[];\n seoIssues: SEOIssue[];\n schemaIssues: SEOIssue[];\n links: LinkStatus[];\n failedChecks?: ValidationReportCheck[];\n errors?: string[];\n}\n\nfunction clampScore(score: number): number {\n return Math.max(0, Math.min(100, score));\n}\n\nfunction scoreIndicator(score: number | null): string {\n if (score === null) return \"Unavailable\";\n if (score >= 90) return \"🟢\";\n if (score >= 50) return \"🟠\";\n return \"🔴\";\n}\n\nfunction markdownCell(value: unknown): string {\n return String(value ?? \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\\|/g, \"\\\\|\")\n .replace(/`/g, \"\\\\`\")\n .replace(/[\\r\\n]+/g, \" \")\n .trim();\n}\n\nfunction isRedirect(link: LinkStatus): boolean {\n return typeof link.status === \"number\" && link.status >= 300 && link.status < 400;\n}\n\n/** Builds the human-readable report and its machine-readable equivalent. */\nexport function createValidationReport(input: ValidationReportInput): ValidationReport {\n const failedChecks = input.failedChecks ?? [];\n const checkFailed = (check: ValidationReportCheck): boolean => failedChecks.includes(check);\n const htmlErrors = input.htmlMessages.filter((message) => message.type === \"error\").length;\n const htmlWarnings = input.htmlMessages.length - htmlErrors;\n const cssErrors = input.cssMessages.length;\n const cssCompatibilityLimitations = input.cssMessages.filter(\n (message) => message.compatibility === \"known-validator-limitation\",\n ).length;\n const seoErrors = input.seoIssues.filter((issue) => issue.severity === \"error\").length;\n const seoWarnings = input.seoIssues.filter((issue) => issue.severity === \"warning\").length;\n const schemaErrors = input.schemaIssues.filter((issue) => issue.severity === \"error\").length;\n const brokenLinks = input.links.filter((link) => !link.ok).length;\n const redirectLinks = input.links.filter(isRedirect).length;\n\n const htmlScore = checkFailed(\"html\") ? null : clampScore(100 - htmlErrors * 15 - htmlWarnings * 2);\n const cssScore = checkFailed(\"css\") || !input.cssAudited || cssCompatibilityLimitations > 0\n ? null\n : clampScore(100 - cssErrors * 20);\n const seoScore = checkFailed(\"seo\") || checkFailed(\"schema\")\n ? null\n : clampScore(100 - seoErrors * 15 - seoWarnings * 4 - schemaErrors * 15);\n const linkScore = checkFailed(\"links\") || input.links.length === 0\n ? null\n : clampScore(100 - brokenLinks * 25);\n const auditedScores = [htmlScore, seoScore, cssScore, linkScore].filter(\n (score): score is number => score !== null,\n );\n const overallScore = failedChecks.length > 0 || cssCompatibilityLimitations > 0 || auditedScores.length === 0\n ? null\n : Math.round(auditedScores.reduce((total, score) => total + score, 0) / auditedScores.length);\n\n const summary: ValidationReportSummary = {\n overallScore,\n htmlScore,\n cssScore,\n seoScore,\n linkScore,\n htmlErrors,\n htmlWarnings,\n cssErrors,\n cssCompatibilityLimitations,\n seoErrors,\n seoWarnings,\n schemaErrors,\n linksChecked: input.links.length,\n brokenLinks,\n };\n\n const report: string[] = [\n `# Web Validation & SEO Audit Report — ${overallScore === null ? \"Partial\" : `${scoreIndicator(overallScore)} **${overallScore}**/100`}`,\n `*Generated for: \\`${markdownCell(path.basename(input.htmlFilePath))}\\`*`,\n \"\",\n \"## Page health scores\",\n \"\",\n \"| Audit | Status | Score |\",\n \"| :--- | :---: | :---: |\",\n `| W3C HTML validation | ${htmlScore === null ? \"Unavailable\" : scoreIndicator(htmlScore)} | ${htmlScore === null ? \"N/A\" : `**${htmlScore}** / 100`} |`,\n `| CSS validation | ${cssScore === null ? (checkFailed(\"css\") ? \"Unavailable\" : cssCompatibilityLimitations > 0 ? \"Compatibility-limited\" : \"Not audited\") : scoreIndicator(cssScore)} | ${cssScore === null ? \"N/A\" : `**${cssScore}** / 100`} |`,\n `| SEO and accessibility | ${seoScore === null ? \"Unavailable\" : scoreIndicator(seoScore)} | ${seoScore === null ? \"N/A\" : `**${seoScore}** / 100`} |`,\n `| Link integrity | ${linkScore === null ? (checkFailed(\"links\") ? \"Unavailable\" : \"No links checked\") : scoreIndicator(linkScore)} | ${linkScore === null ? \"N/A\" : `**${linkScore}** / 100`} |`,\n \"\",\n \"## Summary\",\n \"\",\n `- HTML: ${htmlErrors} error(s), ${htmlWarnings} other diagnostic(s)` ,\n `- CSS: ${input.cssAudited ? `${cssErrors} error(s)${cssCompatibilityLimitations > 0 ? `, ${cssCompatibilityLimitations} known validator limitation(s)` : \"\"}` : \"not audited\"}`,\n `- SEO and accessibility: ${seoErrors} error(s), ${seoWarnings} warning(s)`,\n `- JSON-LD syntax: ${schemaErrors} error(s)`,\n `- Links: ${brokenLinks} broken or unreachable, ${redirectLinks} redirect${redirectLinks === 1 ? \"\" : \"s\"} to review of ${input.links.length} checked`,\n \"\",\n `## HTML diagnostics (${input.htmlMessages.length})`,\n ];\n\n if (failedChecks.length > 0) {\n report.splice(2, 0, \"\", \"## Partial validation report\", \"The following checks were unavailable: \" + failedChecks.join(\", \") + \". Remaining checks completed.\");\n }\n\n if (input.htmlMessages.length === 0) {\n report.push(\"No HTML validation diagnostics were returned.\");\n } else {\n report.push(\"\", \"| Line | Column | Severity | Message | Extract |\", \"| :---: | :---: | :--- | :--- | :--- |\");\n for (const message of input.htmlMessages) {\n report.push(\n `| ${message.lastLine ?? \"N/A\"} | ${message.lastColumn ?? \"N/A\"} | ${markdownCell(message.type)} | ${markdownCell(message.message)} | ${markdownCell(message.extract ?? \"N/A\")} |`,\n );\n }\n }\n\n if (input.cssAudited) {\n report.push(\"\", `## CSS diagnostics (${input.cssMessages.length})`);\n if (input.cssMessages.length === 0) {\n report.push(\"No CSS validation errors were returned.\");\n } else {\n report.push(\"\", \"| Line | Context | Message |\", \"| :---: | :--- | :--- |\");\n for (const message of input.cssMessages) {\n report.push(\n `| ${message.line} | ${markdownCell(message.context ?? \"N/A\")} | ${markdownCell(message.message)} |`,\n );\n }\n if (cssCompatibilityLimitations > 0) {\n report.push(\n \"\",\n `${cssCompatibilityLimitations} known validator limitation(s) match Jigsaw's current parser gap for the standards-defined \\`@container\\` rule. The original Jigsaw diagnostic is preserved, but CSS and overall scores are withheld because this upstream limitation can report valid modern CSS as invalid.`,\n );\n }\n }\n }\n\n const combinedIssues = [...input.seoIssues, ...input.schemaIssues];\n report.push(\"\", `## SEO, accessibility, and JSON-LD findings (${combinedIssues.length})`);\n if (combinedIssues.length === 0) {\n report.push(\"No SEO, accessibility, or JSON-LD syntax findings were returned.\");\n } else {\n report.push(\"\", \"| Category | Severity | Message | Element |\", \"| :--- | :--- | :--- | :--- |\");\n for (const issue of combinedIssues) {\n report.push(\n `| ${markdownCell(issue.category)} | ${markdownCell(issue.severity)} | ${markdownCell(issue.message)} | ${markdownCell(issue.element ?? \"N/A\")} |`,\n );\n }\n }\n\n report.push(\"\", `## Link health (${input.links.length} checked)`);\n if (input.links.length === 0) {\n report.push(\"No public HTTP(S) links were checked.\");\n } else {\n report.push(\"\", \"| URL | Status | Reachable | Details |\", \"| :--- | :---: | :---: | :--- |\");\n for (const link of input.links) {\n report.push(\n `| ${markdownCell(link.url)} | ${markdownCell(link.status)} | ${link.ok ? \"Yes\" : \"No\"} | ${markdownCell(link.message ?? \"Accessible\")} |`,\n );\n }\n }\n\n return {\n report: report.join(\"\\n\"),\n summary,\n htmlMessages: input.htmlMessages,\n cssMessages: input.cssMessages,\n seoIssues: input.seoIssues,\n schemaIssues: input.schemaIssues,\n links: input.links,\n failedChecks,\n ...(input.errors && input.errors.length > 0 ? { errors: input.errors } : {}),\n };\n}\n"]}
@@ -20,11 +20,11 @@ function assertContentSize(content, maxBytes, label) {
20
20
  }
21
21
  function normalizeW3CMessage(message) {
22
22
  if (typeof message !== "object" || message === null) {
23
- return null;
23
+ throw new Error("W3C HTML validator returned a malformed message");
24
24
  }
25
25
  const candidate = message;
26
26
  if (typeof candidate.type !== "string" || typeof candidate.message !== "string") {
27
- return null;
27
+ throw new Error("W3C HTML validator returned a malformed message");
28
28
  }
29
29
  const normalized = {
30
30
  type: candidate.type,
@@ -71,7 +71,6 @@ export async function validateHtmlContent(htmlContent) {
71
71
  }
72
72
  return data.messages
73
73
  .map(normalizeW3CMessage)
74
- .filter((message) => message !== null)
75
74
  .slice(0, MAX_VALIDATION_MESSAGES);
76
75
  }
77
76
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"w3c-validator.js","sourceRoot":"","sources":["../src/w3c-validator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAoB/C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,cAA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6BAA6B,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC;oBAClD,CAAC,CAAC,EAAE,aAAa,EAAE,4BAAqC,EAAE;oBAC1D,CAAC,CAAC,EAAE,CAAC;aACR,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,0BAA0B,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import {\n cancelResponseBody,\n getErrorMessage,\n readResponseText,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport interface W3CMessage {\n type: string;\n lastLine?: number;\n lastColumn?: number;\n firstLine?: number;\n firstColumn?: number;\n message: string;\n extract?: string;\n}\n\nexport interface CSSMessage {\n line: number;\n type: string;\n message: string;\n context?: string;\n compatibility?: \"known-validator-limitation\";\n}\n\nconst VALIDATOR_TIMEOUT_MS = 20_000;\nconst MAX_HTML_BYTES = 2_000_000;\nexport const MAX_CSS_VALIDATION_BYTES = 128_000;\nconst MAX_VALIDATOR_RESPONSE_BYTES = 5_000_000;\nconst USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\nexport const MAX_VALIDATION_MESSAGES = 200;\n\nfunction isKnownCssValidatorLimitation(type: string | undefined, message: string): boolean {\n if (type?.trim().toLowerCase() !== \"at-rule\") return false;\n const normalized = message.trim().toLowerCase().replace(/[“”\"'‘’]/g, \"\");\n return normalized === \"unrecognized at-rule @container\";\n}\n\nfunction assertContentSize(content: string, maxBytes: number, label: string): void {\n const size = Buffer.byteLength(content, \"utf8\");\n if (size > maxBytes) {\n throw new Error(`${label} exceeds the ${maxBytes}-byte validation limit`);\n }\n}\n\nfunction normalizeW3CMessage(message: unknown): W3CMessage | null {\n if (typeof message !== \"object\" || message === null) {\n return null;\n }\n\n const candidate = message as Record<string, unknown>;\n if (typeof candidate.type !== \"string\" || typeof candidate.message !== \"string\") {\n return null;\n }\n\n const normalized: W3CMessage = {\n type: candidate.type,\n message: candidate.message,\n };\n\n for (const field of [\"lastLine\", \"lastColumn\", \"firstLine\", \"firstColumn\"] as const) {\n if (typeof candidate[field] === \"number\" && Number.isInteger(candidate[field])) {\n normalized[field] = candidate[field];\n }\n }\n\n if (typeof candidate.extract === \"string\") {\n normalized.extract = candidate.extract;\n }\n\n return normalized;\n}\n\n/**\n * Validates HTML using the W3C Nu HTML Checker API\n */\nexport async function validateHtmlContent(htmlContent: string): Promise<W3CMessage[]> {\n const url = \"https://validator.w3.org/nu/?out=json\";\n\n try {\n assertContentSize(htmlContent, MAX_HTML_BYTES, \"HTML content\");\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"User-Agent\": USER_AGENT,\n },\n body: htmlContent,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C HTML validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n const data = JSON.parse(text) as { messages?: unknown };\n if (data.messages === undefined) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n if (!Array.isArray(data.messages)) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n return data.messages\n .map(normalizeW3CMessage)\n .filter((message): message is W3CMessage => message !== null)\n .slice(0, MAX_VALIDATION_MESSAGES);\n } catch (error: unknown) {\n throw new Error(`HTML validation failed: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Validates CSS using the W3C Jigsaw CSS Validator API\n */\nexport async function validateCssContent(cssContent: string): Promise<CSSMessage[]> {\n const url = \"https://jigsaw.w3.org/css-validator/validator\";\n\n try {\n assertContentSize(cssContent, MAX_CSS_VALIDATION_BYTES, \"CSS content\");\n const form = new FormData();\n form.set(\"text\", cssContent);\n form.set(\"output\", \"json\");\n form.set(\"warning\", \"0\");\n form.set(\"profile\", \"css3svg\");\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": USER_AGENT,\n },\n body: form,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C CSS validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n\n // An empty upstream response is indeterminate and must never be presented as a clean result.\n if (!text || text.trim() === \"\") {\n throw new Error(\"W3C CSS validator returned an empty response\");\n }\n\n const data = JSON.parse(text) as {\n cssvalidation?: {\n errors?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n warnings?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n };\n };\n\n if (!data.cssvalidation || typeof data.cssvalidation !== \"object\") {\n throw new Error(\"W3C CSS validator returned an invalid response shape\");\n }\n\n const errors = data.cssvalidation.errors || [];\n return errors.slice(0, MAX_VALIDATION_MESSAGES).map((err) => {\n const message = err.message ? err.message.trim() : \"Unknown CSS validation error\";\n return {\n line: err.line || 0,\n type: \"error\",\n message,\n context: err.context || undefined,\n ...(isKnownCssValidatorLimitation(err.type, message)\n ? { compatibility: \"known-validator-limitation\" as const }\n : {}),\n };\n });\n } catch (error: unknown) {\n throw new Error(`CSS validation failed: ${getErrorMessage(error)}`);\n }\n}\n"]}
1
+ {"version":3,"file":"w3c-validator.js","sourceRoot":"","sources":["../src/w3c-validator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAoB/C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,cAAc,GAAG,SAAS,CAAC;AACjC,MAAM,CAAC,MAAM,wBAAwB,GA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,aAAa,EAAE,4BAAqC,EAAE;oBAC1D,CAAC,CAAC,EAAE,CAAC;aACR,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,0BAA0B,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACtE,CAAC;AACH,CAAC","sourcesContent":["import {\n cancelResponseBody,\n getErrorMessage,\n readResponseText,\n} from \"./network.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\n\nexport interface W3CMessage {\n type: string;\n lastLine?: number;\n lastColumn?: number;\n firstLine?: number;\n firstColumn?: number;\n message: string;\n extract?: string;\n}\n\nexport interface CSSMessage {\n line: number;\n type: string;\n message: string;\n context?: string;\n compatibility?: \"known-validator-limitation\";\n}\n\nconst VALIDATOR_TIMEOUT_MS = 20_000;\nconst MAX_HTML_BYTES = 2_000_000;\nexport const MAX_CSS_VALIDATION_BYTES = 128_000;\nconst MAX_VALIDATOR_RESPONSE_BYTES = 5_000_000;\nconst USER_AGENT = `mcp-web-validator/${PACKAGE_VERSION} (+https://digestseo.com/validator-mcp/)`;\nexport const MAX_VALIDATION_MESSAGES = 200;\n\nfunction isKnownCssValidatorLimitation(type: string | undefined, message: string): boolean {\n if (type?.trim().toLowerCase() !== \"at-rule\") return false;\n const normalized = message.trim().toLowerCase().replace(/[“”\"'‘’]/g, \"\");\n return normalized === \"unrecognized at-rule @container\";\n}\n\nfunction assertContentSize(content: string, maxBytes: number, label: string): void {\n const size = Buffer.byteLength(content, \"utf8\");\n if (size > maxBytes) {\n throw new Error(`${label} exceeds the ${maxBytes}-byte validation limit`);\n }\n}\n\nfunction normalizeW3CMessage(message: unknown): W3CMessage {\n if (typeof message !== \"object\" || message === null) {\n throw new Error(\"W3C HTML validator returned a malformed message\");\n }\n\n const candidate = message as Record<string, unknown>;\n if (typeof candidate.type !== \"string\" || typeof candidate.message !== \"string\") {\n throw new Error(\"W3C HTML validator returned a malformed message\");\n }\n\n const normalized: W3CMessage = {\n type: candidate.type,\n message: candidate.message,\n };\n\n for (const field of [\"lastLine\", \"lastColumn\", \"firstLine\", \"firstColumn\"] as const) {\n if (typeof candidate[field] === \"number\" && Number.isInteger(candidate[field])) {\n normalized[field] = candidate[field];\n }\n }\n\n if (typeof candidate.extract === \"string\") {\n normalized.extract = candidate.extract;\n }\n\n return normalized;\n}\n\n/**\n * Validates HTML using the W3C Nu HTML Checker API\n */\nexport async function validateHtmlContent(htmlContent: string): Promise<W3CMessage[]> {\n const url = \"https://validator.w3.org/nu/?out=json\";\n\n try {\n assertContentSize(htmlContent, MAX_HTML_BYTES, \"HTML content\");\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"User-Agent\": USER_AGENT,\n },\n body: htmlContent,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C HTML validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n const data = JSON.parse(text) as { messages?: unknown };\n if (data.messages === undefined) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n if (!Array.isArray(data.messages)) {\n throw new Error(\"W3C HTML validator returned an invalid response shape\");\n }\n return data.messages\n .map(normalizeW3CMessage)\n .slice(0, MAX_VALIDATION_MESSAGES);\n } catch (error: unknown) {\n throw new Error(`HTML validation failed: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Validates CSS using the W3C Jigsaw CSS Validator API\n */\nexport async function validateCssContent(cssContent: string): Promise<CSSMessage[]> {\n const url = \"https://jigsaw.w3.org/css-validator/validator\";\n\n try {\n assertContentSize(cssContent, MAX_CSS_VALIDATION_BYTES, \"CSS content\");\n const form = new FormData();\n form.set(\"text\", cssContent);\n form.set(\"output\", \"json\");\n form.set(\"warning\", \"0\");\n form.set(\"profile\", \"css3svg\");\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"User-Agent\": USER_AGENT,\n },\n body: form,\n redirect: \"error\",\n signal: AbortSignal.timeout(VALIDATOR_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(`W3C CSS validator returned HTTP status ${response.status}`);\n }\n\n const text = await readResponseText(response, MAX_VALIDATOR_RESPONSE_BYTES);\n\n // An empty upstream response is indeterminate and must never be presented as a clean result.\n if (!text || text.trim() === \"\") {\n throw new Error(\"W3C CSS validator returned an empty response\");\n }\n\n const data = JSON.parse(text) as {\n cssvalidation?: {\n errors?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n warnings?: Array<{\n line: number;\n message: string;\n context?: string;\n type?: string;\n }>;\n };\n };\n\n if (!data.cssvalidation || typeof data.cssvalidation !== \"object\") {\n throw new Error(\"W3C CSS validator returned an invalid response shape\");\n }\n\n const errors = data.cssvalidation.errors || [];\n return errors.slice(0, MAX_VALIDATION_MESSAGES).map((err) => {\n const message = err.message ? err.message.trim() : \"Unknown CSS validation error\";\n return {\n line: err.line || 0,\n type: \"error\",\n message,\n context: err.context || undefined,\n ...(isKnownCssValidatorLimitation(err.type, message)\n ? { compatibility: \"known-validator-limitation\" as const }\n : {}),\n };\n });\n } catch (error: unknown) {\n throw new Error(`CSS validation failed: ${getErrorMessage(error)}`);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-web-validator",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "W3C HTML/CSS Validator and Technical SEO Audit MCP Server for AI coding assistants.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -52,6 +52,7 @@
52
52
  "@modelcontextprotocol/sdk": "^1.29.0",
53
53
  "cheerio": "^1.0.0",
54
54
  "puppeteer": "25.7.0",
55
+ "undici": "^7.29.0",
55
56
  "zod": "^4.4.3"
56
57
  },
57
58
  "devDependencies": {