mcp-web-validator 1.3.6 → 1.3.8

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,18 @@ All notable changes to this project are documented here. The project follows [Se
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.3.8] - 2026-09-21
8
+
9
+ ### Fixed
10
+
11
+ - Honored supported character encodings declared by fetched HTML responses instead of always decoding those representations as UTF-8, preventing legacy-encoded page text from being corrupted before validation and SEO analysis.
12
+
13
+ ## [1.3.7] - 2026-09-21
14
+
15
+ ### Changed
16
+
17
+ - Deferred the local screenshot browser download until the first `screenshot.capture` call, so validator-only npm installs no longer fetch Chrome while screenshot users still receive the pinned verified headless shell automatically on demand.
18
+
7
19
  ## [1.3.6] - 2026-09-21
8
20
 
9
21
  ### Fixed
package/README.md CHANGED
@@ -41,7 +41,7 @@ https://web-validator-mcp.digestseo.com/mcp
41
41
  - Node.js 22.12.0 or newer
42
42
  - An MCP client that supports stdio, or a client that supports Streamable HTTP for the hosted endpoint
43
43
 
44
- Puppeteer may download a compatible browser during npm installation. The browser is used only by the local `screenshot.capture` tool.
44
+ The validation, SEO, schema, link, and report tools do not download a browser during installation. The local `screenshot.capture` tool installs its pinned headless browser into Puppeteer's cache on first use, then reuses that browser for later screenshots. Set `PUPPETEER_CACHE_DIR` if you need a custom cache location.
45
45
 
46
46
  ## Local server tools
47
47
 
package/dist/index.js CHANGED
@@ -387,7 +387,7 @@ export function createServer() {
387
387
  });
388
388
  server.registerTool("screenshot.capture", {
389
389
  title: "Capture responsive screenshots",
390
- description: "Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Existing matching files may be replaced.",
390
+ description: "Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Downloads the pinned headless browser on first use if it is not already cached. Existing matching files may be replaced.",
391
391
  inputSchema: {
392
392
  targetPath: z
393
393
  .string()
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,sBAAsB,EAGtB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC;AAE9C,MAAM,cAAc,GAAG,SAAS,CAAC;AACjC,MAAM,aAAa,GAAG,wBAAwB,CAAC;AAC/C,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC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MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,KAAK,CAAC,qBAAqB,cAAc,mBAAmB,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACpG,IAAI,WAAW,KAAK,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;IACpC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC7B,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { captureScreenshots } from \"./screenshot.js\";\nimport {\n auditSeoMetadata,\n auditSeoMetadataDetailed,\n checkBrokenLinks,\n validateSchemaMarkup,\n validateSchemaMarkupDetailed,\n} from \"./seo-auditor.js\";\nimport {\n createValidationReport,\n type ValidationReport,\n type ValidationReportCheck,\n validationReportChecks,\n} from \"./report.js\";\nimport { fetchPublicText, getErrorMessage, readTextFile } from \"./network.js\";\nimport {\n cssValidationContent,\n failureContent,\n htmlValidationContent,\n linkCheckContent,\n reportContent,\n schemaValidationContent,\n screenshotCaptureContent,\n seoAuditContent,\n} from \"./presentation.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\nimport {\n MAX_CSS_VALIDATION_BYTES,\n validateCssContent,\n validateHtmlContent,\n} from \"./w3c-validator.js\";\n\nexport const SERVER_VERSION = PACKAGE_VERSION;\n\nconst HTML_MAX_BYTES = 2_000_000;\nconst CSS_MAX_BYTES = MAX_CSS_VALIDATION_BYTES;\nconst PATH_MAX_LENGTH = 4_096;\nconst MAX_VIEWPORTS = 8;\n\nconst filePathSchema = z.string().trim().min(1).max(PATH_MAX_LENGTH);\nconst htmlContentSchema = z.string().min(1).max(HTML_MAX_BYTES);\nconst publicUrlSchema = z\n .string()\n .url()\n .refine((value) => {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n }, \"URL must use HTTP or HTTPS.\");\n\nconst w3cMessageSchema = z.object({\n type: z.string(),\n message: z.string(),\n lastLine: z.number().int().optional(),\n lastColumn: z.number().int().optional(),\n firstLine: z.number().int().optional(),\n firstColumn: z.number().int().optional(),\n extract: z.string().optional(),\n});\n\nconst cssMessageSchema = z.object({\n line: z.number().int(),\n type: z.string(),\n message: z.string(),\n context: z.string().optional(),\n compatibility: z.literal(\"known-validator-limitation\").optional(),\n});\n\nconst seoIssueSchema = z.object({\n code: z.string().describe(\"Stable machine-readable audit rule identifier.\"),\n severity: z.enum([\"error\", \"warning\", \"info\"]),\n category: z.enum([\"SEO\", \"Schema\", \"BrokenLinks\", \"Accessibility\"]),\n message: z.string(),\n element: z.string().optional(),\n});\n\nconst linkStatusSchema = z.object({\n url: z.string(),\n status: z.union([z.number().int(), z.enum([\"blocked\", \"failed\"])]),\n ok: z.boolean(),\n message: z.string().optional(),\n});\n\nconst screenshotSchema = z.object({\n viewportName: z.string(),\n width: z.number().int(),\n height: z.number().int(),\n outputPath: z.string(),\n});\n\nconst reportSummarySchema = z.object({\n overallScore: z.number().int().min(0).max(100).nullable(),\n htmlScore: z.number().int().min(0).max(100).nullable(),\n cssScore: z.number().int().min(0).max(100).nullable(),\n seoScore: z.number().int().min(0).max(100).nullable(),\n linkScore: z.number().int().min(0).max(100).nullable(),\n htmlErrors: z.number().int().nonnegative(),\n htmlWarnings: z.number().int().nonnegative(),\n cssErrors: z.number().int().nonnegative(),\n cssCompatibilityLimitations: z.number().int().nonnegative(),\n seoErrors: z.number().int().nonnegative(),\n seoWarnings: z.number().int().nonnegative(),\n schemaErrors: z.number().int().nonnegative(),\n linksChecked: z.number().int().nonnegative(),\n brokenLinks: z.number().int().nonnegative(),\n});\n\nconst externalReadOnlyAnnotations = {\n // These calls contact external recipients but do not modify external state.\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n} as const;\n\nconst localReadOnlyAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction result<T extends object>(\n structuredContent: T,\n content: string,\n isError = false,\n): CallToolResult {\n return {\n structuredContent: structuredContent as Record<string, unknown>,\n content: [\n {\n type: \"text\",\n text: content,\n },\n ],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction failedReport(filePath: string, error: string): ValidationReport {\n return {\n report: `Validation report could not be generated: ${error}`,\n summary: {\n overallScore: null,\n htmlScore: null,\n cssScore: null,\n seoScore: null,\n linkScore: null,\n htmlErrors: 0,\n htmlWarnings: 0,\n cssErrors: 0,\n cssCompatibilityLimitations: 0,\n seoErrors: 0,\n seoWarnings: 0,\n schemaErrors: 0,\n linksChecked: 0,\n brokenLinks: 0,\n },\n htmlMessages: [],\n cssMessages: [],\n seoIssues: [],\n schemaIssues: [],\n links: [],\n failedChecks: [\"input\"],\n errors: [`${path.basename(filePath || \"document\")}: ${error}`],\n };\n}\n\ninterface ValidationReportDependencies {\n readTextFile: typeof readTextFile;\n validateHtmlContent: typeof validateHtmlContent;\n validateCssContent: typeof validateCssContent;\n auditSeoMetadata: typeof auditSeoMetadata;\n validateSchemaMarkup: typeof validateSchemaMarkup;\n checkBrokenLinks: typeof checkBrokenLinks;\n}\n\nconst validationReportDependencies: ValidationReportDependencies = {\n readTextFile,\n validateHtmlContent,\n validateCssContent,\n auditSeoMetadata,\n validateSchemaMarkup,\n checkBrokenLinks,\n};\n\nexport interface GenerateValidationReportOptions {\n htmlFilePath: string;\n cssFilePath?: string;\n baseUrl?: string;\n}\n\n/** Runs independent validation checks without discarding successful results when another check fails. */\nexport async function generateValidationReport(\n { htmlFilePath, cssFilePath, baseUrl }: GenerateValidationReportOptions,\n dependencies: ValidationReportDependencies = validationReportDependencies,\n): Promise<ValidationReport> {\n const html = await dependencies.readTextFile(htmlFilePath, HTML_MAX_BYTES);\n const failedChecks: ValidationReportCheck[] = [];\n const errors: string[] = [];\n const recordFailure = (check: ValidationReportCheck, label: string, cause: unknown): void => {\n if (!failedChecks.includes(check)) {\n failedChecks.push(check);\n }\n errors.push(`${label} was unavailable: ${getErrorMessage(cause)}`);\n };\n\n let css: string | undefined;\n if (cssFilePath) {\n try {\n css = await dependencies.readTextFile(cssFilePath, CSS_MAX_BYTES);\n } catch (cause) {\n recordFailure(\"css\", \"CSS validation\", cause);\n }\n }\n\n const [htmlResult, cssResult, seoResult, schemaResult, linksResult] = await Promise.allSettled([\n dependencies.validateHtmlContent(html),\n css === undefined ? Promise.resolve([]) : dependencies.validateCssContent(css),\n Promise.resolve().then(() => dependencies.auditSeoMetadata(html)),\n Promise.resolve().then(() => dependencies.validateSchemaMarkup(html)),\n dependencies.checkBrokenLinks(html, baseUrl, 25),\n ]);\n\n if (htmlResult.status === \"rejected\") recordFailure(\"html\", \"HTML validation\", htmlResult.reason);\n if (cssResult.status === \"rejected\") recordFailure(\"css\", \"CSS validation\", cssResult.reason);\n if (seoResult.status === \"rejected\") recordFailure(\"seo\", \"SEO analysis\", seoResult.reason);\n if (schemaResult.status === \"rejected\") recordFailure(\"schema\", \"JSON-LD analysis\", schemaResult.reason);\n if (linksResult.status === \"rejected\") recordFailure(\"links\", \"Link checking\", linksResult.reason);\n\n return createValidationReport({\n htmlFilePath,\n cssAudited: css !== undefined,\n htmlMessages: htmlResult.status === \"fulfilled\" ? htmlResult.value : [],\n cssMessages: cssResult.status === \"fulfilled\" ? cssResult.value : [],\n seoIssues: seoResult.status === \"fulfilled\" ? seoResult.value.slice(0, 200) : [],\n schemaIssues: schemaResult.status === \"fulfilled\" ? schemaResult.value.slice(0, 200) : [],\n links: linksResult.status === \"fulfilled\" ? linksResult.value : [],\n failedChecks,\n errors,\n });\n}\n\nexport function createServer(): McpServer {\n const server = new McpServer(\n { name: \"mcp-web-validator\", version: SERVER_VERSION },\n {\n instructions:\n \"Validate only files, markup, and public URLs the user owns or is authorized to inspect. HTML and CSS validation send supplied content to W3C-operated validators. Link checks contact public links without following redirects. Screenshot capture executes page content in a sandboxed local browser and writes PNG files.\",\n },\n );\n\n server.registerTool(\n \"html.local\",\n {\n title: \"Validate local HTML\",\n description:\n \"Reads a bounded local HTML file and sends its markup to the W3C Nu HTML Checker. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to an HTML file.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const html = await readTextFile(filePath, HTML_MAX_BYTES);\n const errors = await validateHtmlContent(html);\n return result({ errors }, htmlValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"HTML validation\",\n error,\n \"Confirm the file exists and is readable, then retry. If the W3C service is unavailable, try again later.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"html.url\",\n {\n title: \"Validate a public URL\",\n description:\n \"Fetches a bounded public HTTP(S) page, then sends its markup to the W3C Nu HTML Checker. Private, reserved, credentialed, and nonstandard-port destinations are rejected.\",\n inputSchema: {\n url: publicUrlSchema.describe(\"Public HTTP(S) URL on port 80 or 443.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n fetchedUrl: z.string().optional(),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ url }) => {\n try {\n const fetched = await fetchPublicText(url, {\n maxBytes: HTML_MAX_BYTES,\n timeoutMs: 15_000,\n maxRedirects: 3,\n acceptedContentTypes: [\"text/html\", \"application/xhtml+xml\"],\n headers: {\n accept: \"text/html,application/xhtml+xml;q=0.9\",\n \"user-agent\": `DigestSEO-Web-Validator/${SERVER_VERSION} (+https://digestseo.com/validator-mcp/)`,\n },\n });\n if (fetched.status < 200 || fetched.status >= 300) {\n throw new Error(`Target URL returned HTTP ${fetched.status}.`);\n }\n const errors = await validateHtmlContent(fetched.text);\n return result(\n { errors, fetchedUrl: fetched.url },\n htmlValidationContent(errors, fetched.url),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"URL validation\",\n error,\n \"Confirm the URL is public, uses HTTP or HTTPS on a standard port, and returns HTML, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"css.local\",\n {\n title: \"Validate local CSS\",\n description:\n \"Reads a bounded local CSS file and sends it to the W3C Jigsaw CSS Validator. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to a CSS file.\"),\n },\n outputSchema: {\n errors: z.array(cssMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const css = await readTextFile(filePath, CSS_MAX_BYTES);\n const errors = await validateCssContent(css);\n return result({ errors }, cssValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"CSS validation\",\n error,\n \"Confirm the file exists, is readable, and is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"seo.metadata\",\n {\n title: \"Audit SEO metadata\",\n description:\n \"Analyzes supplied HTML locally for metadata, heading structure, viewport configuration, image alternatives, and Open Graph fields.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup to inspect locally.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = auditSeoMetadataDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n seoAuditContent(issues, totalIssues, truncated),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"SEO audit\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"links.broken\",\n {\n title: \"Check public links\",\n description:\n \"Resolves and checks up to 25 public HTTP(S) links in supplied HTML. Redirects are reported but not followed, and response bodies are discarded.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup containing links to check.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n maxLinks: z\n .number()\n .int()\n .min(1)\n .max(25)\n .default(25)\n .describe(\"Maximum number of public HTTP(S) links to check, from 1 to 25.\"),\n },\n outputSchema: {\n links: z.array(linkStatusSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlContent, baseUrl, maxLinks }) => {\n try {\n const links = await checkBrokenLinks(htmlContent, baseUrl, maxLinks);\n return result({ links }, linkCheckContent(links, baseUrl));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { links: [], error },\n failureContent(\n \"Link check\",\n error,\n \"Confirm the base URL is public and the supplied HTML is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"schema.markup\",\n {\n title: \"Validate JSON-LD syntax\",\n description:\n \"Parses JSON-LD blocks in supplied HTML locally and reports empty blocks or JSON syntax errors. It does not validate vocabulary semantics.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML containing JSON-LD script blocks.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = validateSchemaMarkupDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n schemaValidationContent(issues, totalIssues, truncated, htmlContent),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"JSON-LD syntax\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"report.validation\",\n {\n title: \"Generate a validation report\",\n description:\n \"Combines W3C HTML/CSS validation, local SEO/accessibility checks, JSON-LD syntax checks, and a bounded public-link check into a Markdown and structured report.\",\n inputSchema: {\n htmlFilePath: filePathSchema.describe(\"Absolute or workspace-relative HTML file path.\"),\n cssFilePath: filePathSchema\n .optional()\n .describe(\"Optional absolute or workspace-relative CSS file path.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n },\n outputSchema: {\n report: z.string(),\n summary: reportSummarySchema,\n htmlMessages: z.array(w3cMessageSchema),\n cssMessages: z.array(cssMessageSchema),\n seoIssues: z.array(seoIssueSchema),\n schemaIssues: z.array(seoIssueSchema),\n links: z.array(linkStatusSchema),\n failedChecks: z.array(z.enum(validationReportChecks)),\n errors: z.array(z.string()).optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlFilePath, cssFilePath, baseUrl }) => {\n try {\n const reportData = await generateValidationReport({\n htmlFilePath,\n cssFilePath,\n baseUrl,\n });\n return result(reportData, reportContent(reportData));\n } catch (cause) {\n const error = getErrorMessage(cause);\n const reportData = failedReport(htmlFilePath, error);\n return result(\n reportData,\n failureContent(\n \"Validation report\",\n error,\n \"Confirm the input paths are readable and any base URL is public, then regenerate the report.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"screenshot.capture\",\n {\n title: \"Capture responsive screenshots\",\n description:\n \"Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Existing matching files may be replaced.\",\n inputSchema: {\n targetPath: z\n .string()\n .trim()\n .min(1)\n .max(PATH_MAX_LENGTH)\n .describe(\"Local HTML path or HTTP(S) URL to render.\"),\n outputDir: filePathSchema\n .optional()\n .default(\".mcp-validator/screenshots\")\n .describe(\"Directory where PNG screenshots will be written.\"),\n viewports: z\n .array(\n z.object({\n name: z\n .string()\n .regex(/^[A-Za-z0-9_-]{1,50}$/)\n .describe(\"Safe filename label for this screenshot viewport.\"),\n width: z\n .number()\n .int()\n .min(200)\n .max(3_840)\n .describe(\"Viewport width in CSS pixels, from 200 to 3840.\"),\n height: z\n .number()\n .int()\n .min(200)\n .max(4_320)\n .describe(\"Viewport height in CSS pixels, from 200 to 4320.\"),\n }),\n )\n .min(1)\n .max(MAX_VIEWPORTS)\n .optional()\n .describe(\"Optional viewport definitions; defaults to desktop, tablet, and mobile sizes.\"),\n },\n outputSchema: {\n screenshots: z.array(screenshotSchema),\n outputDirectory: z.string(),\n error: z.string().optional(),\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ targetPath, outputDir, viewports }) => {\n const outputDirectory = path.resolve(outputDir);\n try {\n const screenshots = await captureScreenshots(targetPath, outputDirectory, viewports);\n return result(\n { screenshots, outputDirectory },\n screenshotCaptureContent(screenshots.length, outputDirectory),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { screenshots: [], outputDirectory, error },\n failureContent(\n \"Screenshot capture\",\n error,\n \"Confirm the target is reachable or readable and the output directory is writable, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n return server;\n}\n\nexport async function run(): Promise<void> {\n const server = createServer();\n await server.connect(new StdioServerTransport());\n console.error(`mcp-web-validator ${SERVER_VERSION} started on stdio`);\n}\n\nconst invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : undefined;\nif (invokedPath === import.meta.url) {\n run().catch((cause: unknown) => {\n console.error(\"Fatal error starting mcp-web-validator:\", getErrorMessage(cause));\n process.exitCode = 1;\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,sBAAsB,EAGtB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CA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,CACX,EAAE,WAAW,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK,EAAE,EAC3C,cAAc,CACZ,oBAAoB,EACpB,KAAK,EACL,+FAA+F,CAChG,EACD,IAAI,CACL,CAAC;QACJ,CAAC;IACH,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,GAAG;IACvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAC9B,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,KAAK,CAAC,qBAAqB,cAAc,mBAAmB,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACpG,IAAI,WAAW,KAAK,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;IACpC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC7B,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { captureScreenshots } from \"./screenshot.js\";\nimport {\n auditSeoMetadata,\n auditSeoMetadataDetailed,\n checkBrokenLinks,\n validateSchemaMarkup,\n validateSchemaMarkupDetailed,\n} from \"./seo-auditor.js\";\nimport {\n createValidationReport,\n type ValidationReport,\n type ValidationReportCheck,\n validationReportChecks,\n} from \"./report.js\";\nimport { fetchPublicText, getErrorMessage, readTextFile } from \"./network.js\";\nimport {\n cssValidationContent,\n failureContent,\n htmlValidationContent,\n linkCheckContent,\n reportContent,\n schemaValidationContent,\n screenshotCaptureContent,\n seoAuditContent,\n} from \"./presentation.js\";\nimport { PACKAGE_VERSION } from \"./version.js\";\nimport {\n MAX_CSS_VALIDATION_BYTES,\n validateCssContent,\n validateHtmlContent,\n} from \"./w3c-validator.js\";\n\nexport const SERVER_VERSION = PACKAGE_VERSION;\n\nconst HTML_MAX_BYTES = 2_000_000;\nconst CSS_MAX_BYTES = MAX_CSS_VALIDATION_BYTES;\nconst PATH_MAX_LENGTH = 4_096;\nconst MAX_VIEWPORTS = 8;\n\nconst filePathSchema = z.string().trim().min(1).max(PATH_MAX_LENGTH);\nconst htmlContentSchema = z.string().min(1).max(HTML_MAX_BYTES);\nconst publicUrlSchema = z\n .string()\n .url()\n .refine((value) => {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n }, \"URL must use HTTP or HTTPS.\");\n\nconst w3cMessageSchema = z.object({\n type: z.string(),\n message: z.string(),\n lastLine: z.number().int().optional(),\n lastColumn: z.number().int().optional(),\n firstLine: z.number().int().optional(),\n firstColumn: z.number().int().optional(),\n extract: z.string().optional(),\n});\n\nconst cssMessageSchema = z.object({\n line: z.number().int(),\n type: z.string(),\n message: z.string(),\n context: z.string().optional(),\n compatibility: z.literal(\"known-validator-limitation\").optional(),\n});\n\nconst seoIssueSchema = z.object({\n code: z.string().describe(\"Stable machine-readable audit rule identifier.\"),\n severity: z.enum([\"error\", \"warning\", \"info\"]),\n category: z.enum([\"SEO\", \"Schema\", \"BrokenLinks\", \"Accessibility\"]),\n message: z.string(),\n element: z.string().optional(),\n});\n\nconst linkStatusSchema = z.object({\n url: z.string(),\n status: z.union([z.number().int(), z.enum([\"blocked\", \"failed\"])]),\n ok: z.boolean(),\n message: z.string().optional(),\n});\n\nconst screenshotSchema = z.object({\n viewportName: z.string(),\n width: z.number().int(),\n height: z.number().int(),\n outputPath: z.string(),\n});\n\nconst reportSummarySchema = z.object({\n overallScore: z.number().int().min(0).max(100).nullable(),\n htmlScore: z.number().int().min(0).max(100).nullable(),\n cssScore: z.number().int().min(0).max(100).nullable(),\n seoScore: z.number().int().min(0).max(100).nullable(),\n linkScore: z.number().int().min(0).max(100).nullable(),\n htmlErrors: z.number().int().nonnegative(),\n htmlWarnings: z.number().int().nonnegative(),\n cssErrors: z.number().int().nonnegative(),\n cssCompatibilityLimitations: z.number().int().nonnegative(),\n seoErrors: z.number().int().nonnegative(),\n seoWarnings: z.number().int().nonnegative(),\n schemaErrors: z.number().int().nonnegative(),\n linksChecked: z.number().int().nonnegative(),\n brokenLinks: z.number().int().nonnegative(),\n});\n\nconst externalReadOnlyAnnotations = {\n // These calls contact external recipients but do not modify external state.\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n} as const;\n\nconst localReadOnlyAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction result<T extends object>(\n structuredContent: T,\n content: string,\n isError = false,\n): CallToolResult {\n return {\n structuredContent: structuredContent as Record<string, unknown>,\n content: [\n {\n type: \"text\",\n text: content,\n },\n ],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction failedReport(filePath: string, error: string): ValidationReport {\n return {\n report: `Validation report could not be generated: ${error}`,\n summary: {\n overallScore: null,\n htmlScore: null,\n cssScore: null,\n seoScore: null,\n linkScore: null,\n htmlErrors: 0,\n htmlWarnings: 0,\n cssErrors: 0,\n cssCompatibilityLimitations: 0,\n seoErrors: 0,\n seoWarnings: 0,\n schemaErrors: 0,\n linksChecked: 0,\n brokenLinks: 0,\n },\n htmlMessages: [],\n cssMessages: [],\n seoIssues: [],\n schemaIssues: [],\n links: [],\n failedChecks: [\"input\"],\n errors: [`${path.basename(filePath || \"document\")}: ${error}`],\n };\n}\n\ninterface ValidationReportDependencies {\n readTextFile: typeof readTextFile;\n validateHtmlContent: typeof validateHtmlContent;\n validateCssContent: typeof validateCssContent;\n auditSeoMetadata: typeof auditSeoMetadata;\n validateSchemaMarkup: typeof validateSchemaMarkup;\n checkBrokenLinks: typeof checkBrokenLinks;\n}\n\nconst validationReportDependencies: ValidationReportDependencies = {\n readTextFile,\n validateHtmlContent,\n validateCssContent,\n auditSeoMetadata,\n validateSchemaMarkup,\n checkBrokenLinks,\n};\n\nexport interface GenerateValidationReportOptions {\n htmlFilePath: string;\n cssFilePath?: string;\n baseUrl?: string;\n}\n\n/** Runs independent validation checks without discarding successful results when another check fails. */\nexport async function generateValidationReport(\n { htmlFilePath, cssFilePath, baseUrl }: GenerateValidationReportOptions,\n dependencies: ValidationReportDependencies = validationReportDependencies,\n): Promise<ValidationReport> {\n const html = await dependencies.readTextFile(htmlFilePath, HTML_MAX_BYTES);\n const failedChecks: ValidationReportCheck[] = [];\n const errors: string[] = [];\n const recordFailure = (check: ValidationReportCheck, label: string, cause: unknown): void => {\n if (!failedChecks.includes(check)) {\n failedChecks.push(check);\n }\n errors.push(`${label} was unavailable: ${getErrorMessage(cause)}`);\n };\n\n let css: string | undefined;\n if (cssFilePath) {\n try {\n css = await dependencies.readTextFile(cssFilePath, CSS_MAX_BYTES);\n } catch (cause) {\n recordFailure(\"css\", \"CSS validation\", cause);\n }\n }\n\n const [htmlResult, cssResult, seoResult, schemaResult, linksResult] = await Promise.allSettled([\n dependencies.validateHtmlContent(html),\n css === undefined ? Promise.resolve([]) : dependencies.validateCssContent(css),\n Promise.resolve().then(() => dependencies.auditSeoMetadata(html)),\n Promise.resolve().then(() => dependencies.validateSchemaMarkup(html)),\n dependencies.checkBrokenLinks(html, baseUrl, 25),\n ]);\n\n if (htmlResult.status === \"rejected\") recordFailure(\"html\", \"HTML validation\", htmlResult.reason);\n if (cssResult.status === \"rejected\") recordFailure(\"css\", \"CSS validation\", cssResult.reason);\n if (seoResult.status === \"rejected\") recordFailure(\"seo\", \"SEO analysis\", seoResult.reason);\n if (schemaResult.status === \"rejected\") recordFailure(\"schema\", \"JSON-LD analysis\", schemaResult.reason);\n if (linksResult.status === \"rejected\") recordFailure(\"links\", \"Link checking\", linksResult.reason);\n\n return createValidationReport({\n htmlFilePath,\n cssAudited: css !== undefined,\n htmlMessages: htmlResult.status === \"fulfilled\" ? htmlResult.value : [],\n cssMessages: cssResult.status === \"fulfilled\" ? cssResult.value : [],\n seoIssues: seoResult.status === \"fulfilled\" ? seoResult.value.slice(0, 200) : [],\n schemaIssues: schemaResult.status === \"fulfilled\" ? schemaResult.value.slice(0, 200) : [],\n links: linksResult.status === \"fulfilled\" ? linksResult.value : [],\n failedChecks,\n errors,\n });\n}\n\nexport function createServer(): McpServer {\n const server = new McpServer(\n { name: \"mcp-web-validator\", version: SERVER_VERSION },\n {\n instructions:\n \"Validate only files, markup, and public URLs the user owns or is authorized to inspect. HTML and CSS validation send supplied content to W3C-operated validators. Link checks contact public links without following redirects. Screenshot capture executes page content in a sandboxed local browser and writes PNG files.\",\n },\n );\n\n server.registerTool(\n \"html.local\",\n {\n title: \"Validate local HTML\",\n description:\n \"Reads a bounded local HTML file and sends its markup to the W3C Nu HTML Checker. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to an HTML file.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const html = await readTextFile(filePath, HTML_MAX_BYTES);\n const errors = await validateHtmlContent(html);\n return result({ errors }, htmlValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"HTML validation\",\n error,\n \"Confirm the file exists and is readable, then retry. If the W3C service is unavailable, try again later.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"html.url\",\n {\n title: \"Validate a public URL\",\n description:\n \"Fetches a bounded public HTTP(S) page, then sends its markup to the W3C Nu HTML Checker. Private, reserved, credentialed, and nonstandard-port destinations are rejected.\",\n inputSchema: {\n url: publicUrlSchema.describe(\"Public HTTP(S) URL on port 80 or 443.\"),\n },\n outputSchema: {\n errors: z.array(w3cMessageSchema),\n fetchedUrl: z.string().optional(),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ url }) => {\n try {\n const fetched = await fetchPublicText(url, {\n maxBytes: HTML_MAX_BYTES,\n timeoutMs: 15_000,\n maxRedirects: 3,\n acceptedContentTypes: [\"text/html\", \"application/xhtml+xml\"],\n headers: {\n accept: \"text/html,application/xhtml+xml;q=0.9\",\n \"user-agent\": `DigestSEO-Web-Validator/${SERVER_VERSION} (+https://digestseo.com/validator-mcp/)`,\n },\n });\n if (fetched.status < 200 || fetched.status >= 300) {\n throw new Error(`Target URL returned HTTP ${fetched.status}.`);\n }\n const errors = await validateHtmlContent(fetched.text);\n return result(\n { errors, fetchedUrl: fetched.url },\n htmlValidationContent(errors, fetched.url),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"URL validation\",\n error,\n \"Confirm the URL is public, uses HTTP or HTTPS on a standard port, and returns HTML, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"css.local\",\n {\n title: \"Validate local CSS\",\n description:\n \"Reads a bounded local CSS file and sends it to the W3C Jigsaw CSS Validator. Use only files the user is authorized to share.\",\n inputSchema: {\n filePath: filePathSchema.describe(\"Absolute or workspace-relative path to a CSS file.\"),\n },\n outputSchema: {\n errors: z.array(cssMessageSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ filePath }) => {\n try {\n const css = await readTextFile(filePath, CSS_MAX_BYTES);\n const errors = await validateCssContent(css);\n return result({ errors }, cssValidationContent(errors));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { errors: [], error },\n failureContent(\n \"CSS validation\",\n error,\n \"Confirm the file exists, is readable, and is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"seo.metadata\",\n {\n title: \"Audit SEO metadata\",\n description:\n \"Analyzes supplied HTML locally for metadata, heading structure, viewport configuration, image alternatives, and Open Graph fields.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup to inspect locally.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = auditSeoMetadataDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n seoAuditContent(issues, totalIssues, truncated),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"SEO audit\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"links.broken\",\n {\n title: \"Check public links\",\n description:\n \"Resolves and checks up to 25 public HTTP(S) links in supplied HTML. Redirects are reported but not followed, and response bodies are discarded.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML markup containing links to check.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n maxLinks: z\n .number()\n .int()\n .min(1)\n .max(25)\n .default(25)\n .describe(\"Maximum number of public HTTP(S) links to check, from 1 to 25.\"),\n },\n outputSchema: {\n links: z.array(linkStatusSchema),\n error: z.string().optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlContent, baseUrl, maxLinks }) => {\n try {\n const links = await checkBrokenLinks(htmlContent, baseUrl, maxLinks);\n return result({ links }, linkCheckContent(links, baseUrl));\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { links: [], error },\n failureContent(\n \"Link check\",\n error,\n \"Confirm the base URL is public and the supplied HTML is within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"schema.markup\",\n {\n title: \"Validate JSON-LD syntax\",\n description:\n \"Parses JSON-LD blocks in supplied HTML locally and reports empty blocks or JSON syntax errors. It does not validate vocabulary semantics.\",\n inputSchema: {\n htmlContent: htmlContentSchema.describe(\"Raw HTML containing JSON-LD script blocks.\"),\n },\n outputSchema: {\n issues: z.array(seoIssueSchema),\n totalIssues: z.number().int().nonnegative(),\n truncated: z.boolean(),\n error: z.string().optional(),\n },\n annotations: localReadOnlyAnnotations,\n },\n async ({ htmlContent }) => {\n try {\n const { issues, totalIssues, truncated } = validateSchemaMarkupDetailed(htmlContent);\n return result(\n { issues, totalIssues, truncated },\n schemaValidationContent(issues, totalIssues, truncated, htmlContent),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { issues: [], totalIssues: 0, truncated: false, error },\n failureContent(\n \"JSON-LD syntax\",\n error,\n \"Confirm the supplied HTML is complete and within the size limit, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"report.validation\",\n {\n title: \"Generate a validation report\",\n description:\n \"Combines W3C HTML/CSS validation, local SEO/accessibility checks, JSON-LD syntax checks, and a bounded public-link check into a Markdown and structured report.\",\n inputSchema: {\n htmlFilePath: filePathSchema.describe(\"Absolute or workspace-relative HTML file path.\"),\n cssFilePath: filePathSchema\n .optional()\n .describe(\"Optional absolute or workspace-relative CSS file path.\"),\n baseUrl: publicUrlSchema\n .optional()\n .describe(\"Optional public HTTP(S) base URL used to resolve relative links.\"),\n },\n outputSchema: {\n report: z.string(),\n summary: reportSummarySchema,\n htmlMessages: z.array(w3cMessageSchema),\n cssMessages: z.array(cssMessageSchema),\n seoIssues: z.array(seoIssueSchema),\n schemaIssues: z.array(seoIssueSchema),\n links: z.array(linkStatusSchema),\n failedChecks: z.array(z.enum(validationReportChecks)),\n errors: z.array(z.string()).optional(),\n },\n annotations: externalReadOnlyAnnotations,\n },\n async ({ htmlFilePath, cssFilePath, baseUrl }) => {\n try {\n const reportData = await generateValidationReport({\n htmlFilePath,\n cssFilePath,\n baseUrl,\n });\n return result(reportData, reportContent(reportData));\n } catch (cause) {\n const error = getErrorMessage(cause);\n const reportData = failedReport(htmlFilePath, error);\n return result(\n reportData,\n failureContent(\n \"Validation report\",\n error,\n \"Confirm the input paths are readable and any base URL is public, then regenerate the report.\",\n ),\n true,\n );\n }\n },\n );\n\n server.registerTool(\n \"screenshot.capture\",\n {\n title: \"Capture responsive screenshots\",\n description:\n \"Renders a local HTML file or HTTP(S) URL in a sandboxed local Chromium browser and writes PNG screenshots to the requested directory. Downloads the pinned headless browser on first use if it is not already cached. Existing matching files may be replaced.\",\n inputSchema: {\n targetPath: z\n .string()\n .trim()\n .min(1)\n .max(PATH_MAX_LENGTH)\n .describe(\"Local HTML path or HTTP(S) URL to render.\"),\n outputDir: filePathSchema\n .optional()\n .default(\".mcp-validator/screenshots\")\n .describe(\"Directory where PNG screenshots will be written.\"),\n viewports: z\n .array(\n z.object({\n name: z\n .string()\n .regex(/^[A-Za-z0-9_-]{1,50}$/)\n .describe(\"Safe filename label for this screenshot viewport.\"),\n width: z\n .number()\n .int()\n .min(200)\n .max(3_840)\n .describe(\"Viewport width in CSS pixels, from 200 to 3840.\"),\n height: z\n .number()\n .int()\n .min(200)\n .max(4_320)\n .describe(\"Viewport height in CSS pixels, from 200 to 4320.\"),\n }),\n )\n .min(1)\n .max(MAX_VIEWPORTS)\n .optional()\n .describe(\"Optional viewport definitions; defaults to desktop, tablet, and mobile sizes.\"),\n },\n outputSchema: {\n screenshots: z.array(screenshotSchema),\n outputDirectory: z.string(),\n error: z.string().optional(),\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ targetPath, outputDir, viewports }) => {\n const outputDirectory = path.resolve(outputDir);\n try {\n const screenshots = await captureScreenshots(targetPath, outputDirectory, viewports);\n return result(\n { screenshots, outputDirectory },\n screenshotCaptureContent(screenshots.length, outputDirectory),\n );\n } catch (cause) {\n const error = getErrorMessage(cause);\n return result(\n { screenshots: [], outputDirectory, error },\n failureContent(\n \"Screenshot capture\",\n error,\n \"Confirm the target is reachable or readable and the output directory is writable, then retry.\",\n ),\n true,\n );\n }\n },\n );\n\n return server;\n}\n\nexport async function run(): Promise<void> {\n const server = createServer();\n await server.connect(new StdioServerTransport());\n console.error(`mcp-web-validator ${SERVER_VERSION} started on stdio`);\n}\n\nconst invokedPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : undefined;\nif (invokedPath === import.meta.url) {\n run().catch((cause: unknown) => {\n console.error(\"Fatal error starting mcp-web-validator:\", getErrorMessage(cause));\n process.exitCode = 1;\n });\n}\n"]}
package/dist/network.d.ts CHANGED
@@ -24,7 +24,7 @@ export declare class PublicUrlError extends Error {
24
24
  export declare function getErrorMessage(error: unknown): string;
25
25
  export declare function assertPublicHttpUrl(input: string | URL): Promise<URL>;
26
26
  export declare function cancelResponseBody(response: Response): Promise<void>;
27
- export declare function readResponseText(response: Response, maxBytes: number): Promise<string>;
27
+ export declare function readResponseText(response: Response, maxBytes: number, encoding?: string): Promise<string>;
28
28
  /** Fetches a public HTTP(S) URL while validating every redirect target. */
29
29
  export declare function fetchPublicHttp(input: string | URL, options?: PublicFetchOptions): Promise<PublicHttpResult>;
30
30
  /** Fetches bounded text from a public URL and rejects non-success responses. */
package/dist/network.js CHANGED
@@ -174,18 +174,36 @@ export async function cancelResponseBody(response) {
174
174
  // The stream may already be closed or consumed; there is nothing left to release.
175
175
  }
176
176
  }
177
- export async function readResponseText(response, maxBytes) {
177
+ function getDeclaredCharacterEncoding(contentType) {
178
+ if (!contentType) {
179
+ return undefined;
180
+ }
181
+ const match = /(?:^|;)\s*charset\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType);
182
+ if (!match) {
183
+ return undefined;
184
+ }
185
+ return (match[1] ?? match[2] ?? "").trim();
186
+ }
187
+ export async function readResponseText(response, maxBytes, encoding) {
178
188
  assertPositiveInteger(maxBytes, "maxBytes");
179
189
  const declaredLength = Number(response.headers.get("content-length"));
180
190
  if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
181
191
  await cancelResponseBody(response);
182
192
  throw new Error(`Response exceeds the ${maxBytes}-byte limit`);
183
193
  }
194
+ const encodingLabel = encoding === undefined ? "utf-8" : encoding;
195
+ let decoder;
196
+ try {
197
+ decoder = new TextDecoder(encodingLabel);
198
+ }
199
+ catch {
200
+ await cancelResponseBody(response);
201
+ throw new Error(`Unsupported response character encoding "${encodingLabel}"`);
202
+ }
184
203
  if (!response.body) {
185
204
  return "";
186
205
  }
187
206
  const reader = response.body.getReader();
188
- const decoder = new TextDecoder();
189
207
  let totalBytes = 0;
190
208
  let text = "";
191
209
  try {
@@ -306,7 +324,7 @@ export async function fetchPublicText(input, options = {}) {
306
324
  throw new Error(`URL returned unsupported content type ${contentType ?? "missing"}`);
307
325
  }
308
326
  return {
309
- text: await readResponseText(response, maxBytes),
327
+ text: await readResponseText(response, maxBytes, getDeclaredCharacterEncoding(contentTypeHeader)),
310
328
  url: url.href,
311
329
  status: response.status,
312
330
  contentType: contentTypeHeader,
@@ -1 +1 @@
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,MAA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C,IAAI;QACb,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,WAAW,EAAE,iBAAiB;KAC/B,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,QAAgB,EAAE,QAAgB;IACnE,qBAAqB,CAAC,QAAQ,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\";\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"]}
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,EAAE,CAAC;IAClB,CAAC,WAAW,EAAE,CAAC,CAAC;IAChB,CAAC,aAAa,EAAE,EAAE,CAAC;IACnB,CAAC,YAAY,EAAE,EAAE,CAAC;IAClB,CAAC,WAAW,EAAE,EAAE,CAAC;IACjB,CAAC,WAAW,EAAE,EAAE,CAAC;IACjB,CAAC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AI,KAAK,CAAC,yCAAyC,WAAW,IAAI,SAAS,EAAE,CAAC,CAAC;IACvF,CAAC;IAED,OAAO;QACL,IAAI,EAAE,MAAM,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,4BAA4B,CAAC,iBAAiB,CAAC,CAAC;QACjG,GAAG,EAAE,GAAG,CAAC,IAAI;QACb,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,WAAW,EAAE,iBAAiB;KAC/B,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,QAAgB,EAAE,QAAgB;IACnE,qBAAqB,CAAC,QAAQ,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\";\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\nfunction getDeclaredCharacterEncoding(contentType: string | null): string | undefined {\n if (!contentType) {\n return undefined;\n }\n\n const match = /(?:^|;)\\s*charset\\s*=\\s*(?:\"([^\"]*)\"|([^;\\s]*))/i.exec(contentType);\n if (!match) {\n return undefined;\n }\n return (match[1] ?? match[2] ?? \"\").trim();\n}\n\nexport async function readResponseText(\n response: Response,\n maxBytes: number,\n encoding?: string,\n): 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 const encodingLabel = encoding === undefined ? \"utf-8\" : encoding;\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(encodingLabel);\n } catch {\n await cancelResponseBody(response);\n throw new Error(`Unsupported response character encoding \"${encodingLabel}\"`);\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\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, getDeclaredCharacterEncoding(contentTypeHeader)),\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,3 +1,5 @@
1
+ import { type BrowserPlatform, type InstallOptions } from "@puppeteer/browsers";
2
+ import { type Browser as PuppeteerBrowser } from "puppeteer-core";
1
3
  export interface ViewportConfig {
2
4
  name: string;
3
5
  width: number;
@@ -10,10 +12,25 @@ export interface ScreenshotResult {
10
12
  outputPath: string;
11
13
  }
12
14
  export declare const SCREENSHOT_HEADLESS_MODE: "shell";
15
+ export declare const SCREENSHOT_BROWSER_BUILD_ID = "152.0.7977.42";
16
+ type BrowserInstaller = (options: InstallOptions & {
17
+ unpack?: true;
18
+ }) => Promise<{
19
+ executablePath: string;
20
+ }>;
21
+ export interface ScreenshotBrowserRuntime {
22
+ launch(): Promise<PuppeteerBrowser>;
23
+ }
24
+ export declare function resolveScreenshotBrowserExecutable(options?: {
25
+ cacheDir?: string;
26
+ platform?: BrowserPlatform;
27
+ installer?: BrowserInstaller;
28
+ }): Promise<string>;
13
29
  /**
14
30
  * Captures screenshots of a local HTML file or remote URL at different viewport sizes.
15
31
  * @param targetPath Local file path or HTTP(S) URL
16
32
  * @param outputDirectory Absolute path to save screenshots
17
33
  * @param customViewports Optional custom viewport settings
18
34
  */
19
- export declare function captureScreenshots(targetPath: string, outputDirectory: string, customViewports?: ViewportConfig[]): Promise<ScreenshotResult[]>;
35
+ export declare function captureScreenshots(targetPath: string, outputDirectory: string, customViewports?: ViewportConfig[], browserRuntime?: ScreenshotBrowserRuntime): Promise<ScreenshotResult[]>;
36
+ export {};
@@ -1,6 +1,8 @@
1
- import puppeteer from "puppeteer";
1
+ import { Browser as ManagedBrowser, computeExecutablePath, detectBrowserPlatform, install as installBrowser, } from "@puppeteer/browsers";
2
+ import puppeteer from "puppeteer-core";
2
3
  import * as path from "path";
3
4
  import * as fs from "fs/promises";
5
+ import * as os from "node:os";
4
6
  import { fileURLToPath, pathToFileURL } from "node:url";
5
7
  import { assertPublicHttpUrl, getErrorMessage } from "./network.js";
6
8
  const DEFAULT_VIEWPORTS = [
@@ -14,6 +16,60 @@ const MAX_VIEWPORT_DIMENSION = 7_680;
14
16
  const SAFE_VIEWPORT_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
15
17
  const NAVIGATION_TIMEOUT_MS = 30_000;
16
18
  export const SCREENSHOT_HEADLESS_MODE = "shell";
19
+ export const SCREENSHOT_BROWSER_BUILD_ID = "152.0.7977.42";
20
+ export async function resolveScreenshotBrowserExecutable(options = {}) {
21
+ const platform = options.platform ?? detectBrowserPlatform();
22
+ if (!platform) {
23
+ throw new Error("Screenshot capture is not supported on this operating system");
24
+ }
25
+ const cacheDir = options.cacheDir
26
+ ?? process.env.PUPPETEER_CACHE_DIR
27
+ ?? path.join(os.homedir(), ".cache", "puppeteer");
28
+ const browser = ManagedBrowser.CHROMEHEADLESSSHELL;
29
+ const executablePath = computeExecutablePath({
30
+ browser,
31
+ buildId: SCREENSHOT_BROWSER_BUILD_ID,
32
+ cacheDir,
33
+ platform,
34
+ });
35
+ try {
36
+ await fs.access(executablePath);
37
+ return executablePath;
38
+ }
39
+ catch {
40
+ // First screenshot use installs only the verified headless shell, not full Chrome.
41
+ }
42
+ try {
43
+ const installed = await (options.installer ?? installBrowser)({
44
+ browser,
45
+ buildId: SCREENSHOT_BROWSER_BUILD_ID,
46
+ cacheDir,
47
+ platform,
48
+ });
49
+ return installed.executablePath;
50
+ }
51
+ catch (cause) {
52
+ throw new Error(`Screenshot browser setup failed: ${getErrorMessage(cause)}`, { cause });
53
+ }
54
+ }
55
+ let screenshotBrowserExecutablePromise;
56
+ const defaultScreenshotBrowserRuntime = {
57
+ async launch() {
58
+ screenshotBrowserExecutablePromise ??= resolveScreenshotBrowserExecutable();
59
+ let executablePath;
60
+ try {
61
+ executablePath = await screenshotBrowserExecutablePromise;
62
+ }
63
+ catch (cause) {
64
+ screenshotBrowserExecutablePromise = undefined;
65
+ throw cause;
66
+ }
67
+ return puppeteer.launch({
68
+ executablePath,
69
+ headless: SCREENSHOT_HEADLESS_MODE,
70
+ });
71
+ },
72
+ };
17
73
  function validateViewports(viewports) {
18
74
  if (viewports.length === 0 || viewports.length > MAX_VIEWPORTS) {
19
75
  throw new Error(`Between 1 and ${MAX_VIEWPORTS} viewports are required`);
@@ -114,7 +170,7 @@ async function resolveScreenshotRequest(request, localDirectory, onBlocked) {
114
170
  * @param outputDirectory Absolute path to save screenshots
115
171
  * @param customViewports Optional custom viewport settings
116
172
  */
117
- export async function captureScreenshots(targetPath, outputDirectory, customViewports) {
173
+ export async function captureScreenshots(targetPath, outputDirectory, customViewports, browserRuntime = defaultScreenshotBrowserRuntime) {
118
174
  if (typeof targetPath !== "string" || targetPath.trim() === "") {
119
175
  throw new Error("targetPath must be a non-empty string");
120
176
  }
@@ -141,10 +197,7 @@ export async function captureScreenshots(targetPath, outputDirectory, customView
141
197
  }
142
198
  // Ensure output directory exists
143
199
  await fs.mkdir(resolvedOutputDirectory, { recursive: true });
144
- // Launch Puppeteer's bundled headless shell.
145
- const browser = await puppeteer.launch({
146
- headless: SCREENSHOT_HEADLESS_MODE,
147
- });
200
+ const browser = await browserRuntime.launch();
148
201
  const results = [];
149
202
  try {
150
203
  const page = await browser.newPage();
@@ -1 +1 @@
1
- {"version":3,"file":"screenshot.js","sourceRoot":"","sources":["../src/screenshot.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAepE,MAAM,iBAAiB,GAAqB;IAC1C,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE;IAC7C,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE;IAC5C,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;CAC5C,CAAC;AAEF,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAC9D,MAAM,qBA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,CAAC,mCAAmC;aACpD,CAAC,CAAC;YAEH,OAAO,CAAC,IAAI,CAAC;gBACX,YAAY,EAAE,EAAE,CAAC,IAAI;gBACrB,KAAK,EAAE,EAAE,CAAC,KAAK;gBACf,MAAM,EAAE,EAAE,CAAC,MAAM;gBACjB,UAAU;aACX,CAAC,CAAC;QACL,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import puppeteer from \"puppeteer\";\nimport * as path from \"path\";\nimport * as fs from \"fs/promises\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { assertPublicHttpUrl, getErrorMessage } from \"./network.js\";\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewportName: string;\n width: number;\n height: number;\n outputPath: string;\n}\n\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: \"desktop\", width: 1440, height: 900 },\n { name: \"tablet\", width: 768, height: 1024 },\n { name: \"mobile\", width: 375, height: 812 }\n];\n\nconst MAX_VIEWPORTS = 10;\nconst MIN_VIEWPORT_DIMENSION = 100;\nconst MAX_VIEWPORT_DIMENSION = 7_680;\nconst SAFE_VIEWPORT_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\nconst NAVIGATION_TIMEOUT_MS = 30_000;\n\nexport const SCREENSHOT_HEADLESS_MODE = \"shell\" as const;\n\ninterface InterceptedRequest {\n url(): string;\n isInterceptResolutionHandled(): boolean;\n continue(): Promise<unknown>;\n abort(errorCode?: string): Promise<unknown>;\n}\n\nfunction validateViewports(viewports: ViewportConfig[]): ViewportConfig[] {\n if (viewports.length === 0 || viewports.length > MAX_VIEWPORTS) {\n throw new Error(`Between 1 and ${MAX_VIEWPORTS} viewports are required`);\n }\n\n const outputNames = new Set<string>();\n return viewports.map((viewport, index) => {\n if (!viewport || typeof viewport !== \"object\") {\n throw new Error(`Viewport #${index + 1} must be an object`);\n }\n if (typeof viewport.name !== \"string\" || !SAFE_VIEWPORT_NAME.test(viewport.name)) {\n throw new Error(\n `Viewport #${index + 1} name must match ${SAFE_VIEWPORT_NAME.source}`,\n );\n }\n for (const [label, value] of [[\"width\", viewport.width], [\"height\", viewport.height]] as const) {\n if (\n !Number.isSafeInteger(value)\n || value < MIN_VIEWPORT_DIMENSION\n || value > MAX_VIEWPORT_DIMENSION\n ) {\n throw new Error(\n `Viewport #${index + 1} ${label} must be an integer between ${MIN_VIEWPORT_DIMENSION} and ${MAX_VIEWPORT_DIMENSION}`,\n );\n }\n }\n\n const outputName = `${viewport.name}_${viewport.width}x${viewport.height}.png`.toLowerCase();\n if (outputNames.has(outputName)) {\n throw new Error(`Duplicate viewport output filename: ${outputName}`);\n }\n outputNames.add(outputName);\n return { name: viewport.name, width: viewport.width, height: viewport.height };\n });\n}\n\nfunction resolveContainedOutputPath(outputDirectory: string, fileName: string): string {\n const outputPath = path.resolve(outputDirectory, fileName);\n const relativePath = path.relative(outputDirectory, outputPath);\n if (relativePath.startsWith(\"..\") || path.isAbsolute(relativePath)) {\n throw new Error(\"Screenshot output path escapes the requested output directory\");\n }\n return outputPath;\n}\n\nfunction isPathWithinDirectory(directory: string, filePath: string): boolean {\n const relativePath = path.relative(directory, filePath);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath));\n}\n\nasync function assertLocalScreenshotRequestAllowed(requestUrl: URL, localDirectory: string): Promise<void> {\n if (requestUrl.hostname) {\n throw new Error(\"Blocked local file request with a host name\");\n }\n\n let resolvedPath: string;\n try {\n resolvedPath = await fs.realpath(fileURLToPath(requestUrl));\n } catch (error: unknown) {\n throw new Error(`Blocked local file request: ${getErrorMessage(error)}`);\n }\n\n if (!isPathWithinDirectory(localDirectory, resolvedPath)) {\n throw new Error(\"Blocked local file request outside the selected file directory\");\n }\n}\n\nasync function assertScreenshotRequestAllowed(requestUrl: string, localDirectory?: string): Promise<void> {\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(requestUrl);\n } catch {\n throw new Error(\"Blocked invalid page request URL\");\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n await assertPublicHttpUrl(parsedUrl);\n return;\n }\n\n if (parsedUrl.protocol === \"data:\" || parsedUrl.protocol === \"blob:\") {\n return;\n }\n\n if (parsedUrl.protocol === \"file:\" && localDirectory) {\n await assertLocalScreenshotRequestAllowed(parsedUrl, localDirectory);\n return;\n }\n\n throw new Error(`Blocked unsupported page request protocol ${parsedUrl.protocol}`);\n}\n\nasync function resolveScreenshotRequest(\n request: InterceptedRequest,\n localDirectory: string | undefined,\n onBlocked: (message: string) => void,\n): Promise<void> {\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n try {\n await assertScreenshotRequestAllowed(request.url(), localDirectory);\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n await request.continue();\n } catch (error: unknown) {\n onBlocked(getErrorMessage(error));\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n await request.abort(\"blockedbyclient\");\n }\n}\n\n/**\n * Captures screenshots of a local HTML file or remote URL at different viewport sizes.\n * @param targetPath Local file path or HTTP(S) URL\n * @param outputDirectory Absolute path to save screenshots\n * @param customViewports Optional custom viewport settings\n */\nexport async function captureScreenshots(\n targetPath: string,\n outputDirectory: string,\n customViewports?: ViewportConfig[]\n): Promise<ScreenshotResult[]> {\n if (typeof targetPath !== \"string\" || targetPath.trim() === \"\") {\n throw new Error(\"targetPath must be a non-empty string\");\n }\n if (typeof outputDirectory !== \"string\" || outputDirectory.trim() === \"\") {\n throw new Error(\"outputDirectory must be a non-empty string\");\n }\n\n const viewports = validateViewports(\n customViewports && customViewports.length > 0 ? customViewports : DEFAULT_VIEWPORTS,\n );\n const resolvedOutputDirectory = path.resolve(outputDirectory);\n\n // Resolve target to file:// URL if it is a local file path\n let targetUrl: string;\n let localDirectory: string | undefined;\n if (/^https?:\\/\\//i.test(targetPath)) {\n targetUrl = (await assertPublicHttpUrl(targetPath)).href;\n } else {\n const absolutePath = path.resolve(targetPath);\n const resolvedPath = await fs.realpath(absolutePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Screenshot target is not a regular file: ${resolvedPath}`);\n }\n localDirectory = path.dirname(resolvedPath);\n targetUrl = pathToFileURL(resolvedPath).href;\n }\n\n // Ensure output directory exists\n await fs.mkdir(resolvedOutputDirectory, { recursive: true });\n\n // Launch Puppeteer's bundled headless shell.\n const browser = await puppeteer.launch({\n headless: SCREENSHOT_HEADLESS_MODE,\n });\n\n const results: ScreenshotResult[] = [];\n\n try {\n const page = await browser.newPage();\n page.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);\n\n let blockedRequestMessage: string | undefined;\n await page.setRequestInterception(true);\n page.on(\"request\", (request) => {\n void resolveScreenshotRequest(request, localDirectory, (message) => {\n blockedRequestMessage ??= message;\n }).catch(() => {\n // Puppeteer will surface navigation failures; avoid an unhandled listener rejection.\n });\n });\n\n for (const vp of viewports) {\n await page.setViewport({\n width: vp.width,\n height: vp.height,\n deviceScaleFactor: 1\n });\n\n // Load URL (wait until network is idle or DOM loaded)\n try {\n await page.goto(targetUrl, {\n waitUntil: \"domcontentloaded\",\n timeout: NAVIGATION_TIMEOUT_MS,\n });\n } catch (error: unknown) {\n if (blockedRequestMessage) {\n throw new Error(`Screenshot navigation blocked: ${blockedRequestMessage}`);\n }\n throw new Error(`Screenshot navigation failed: ${getErrorMessage(error)}`);\n }\n\n // Short wait for any animations or layout adjustments to settle\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n const fileName = `${vp.name}_${vp.width}x${vp.height}.png`;\n const outputPath = resolveContainedOutputPath(resolvedOutputDirectory, fileName);\n\n await page.screenshot({\n path: outputPath,\n fullPage: false // Captures above the fold viewport\n });\n\n results.push({\n viewportName: vp.name,\n width: vp.width,\n height: vp.height,\n outputPath\n });\n }\n } finally {\n await browser.close();\n }\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AAU,CAAC;gBACpB,IAAI,EAAE,UAAU;gBAChB,QAAQ,EAAE,KAAK,CAAC,mCAAmC;aACpD,CAAC,CAAC;YAEH,OAAO,CAAC,IAAI,CAAC;gBACX,YAAY,EAAE,EAAE,CAAC,IAAI;gBACrB,KAAK,EAAE,EAAE,CAAC,KAAK;gBACf,MAAM,EAAE,EAAE,CAAC,MAAM;gBACjB,UAAU;aACX,CAAC,CAAC;QACL,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import {\n Browser as ManagedBrowser,\n computeExecutablePath,\n detectBrowserPlatform,\n install as installBrowser,\n type BrowserPlatform,\n type InstallOptions,\n} from \"@puppeteer/browsers\";\nimport puppeteer, { type Browser as PuppeteerBrowser } from \"puppeteer-core\";\nimport * as path from \"path\";\nimport * as fs from \"fs/promises\";\nimport * as os from \"node:os\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { assertPublicHttpUrl, getErrorMessage } from \"./network.js\";\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewportName: string;\n width: number;\n height: number;\n outputPath: string;\n}\n\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: \"desktop\", width: 1440, height: 900 },\n { name: \"tablet\", width: 768, height: 1024 },\n { name: \"mobile\", width: 375, height: 812 }\n];\n\nconst MAX_VIEWPORTS = 10;\nconst MIN_VIEWPORT_DIMENSION = 100;\nconst MAX_VIEWPORT_DIMENSION = 7_680;\nconst SAFE_VIEWPORT_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\nconst NAVIGATION_TIMEOUT_MS = 30_000;\n\nexport const SCREENSHOT_HEADLESS_MODE = \"shell\" as const;\nexport const SCREENSHOT_BROWSER_BUILD_ID = \"152.0.7977.42\";\n\ntype BrowserInstaller = (options: InstallOptions & { unpack?: true }) => Promise<{ executablePath: string }>;\n\nexport interface ScreenshotBrowserRuntime {\n launch(): Promise<PuppeteerBrowser>;\n}\n\nexport async function resolveScreenshotBrowserExecutable(options: {\n cacheDir?: string;\n platform?: BrowserPlatform;\n installer?: BrowserInstaller;\n} = {}): Promise<string> {\n const platform = options.platform ?? detectBrowserPlatform();\n if (!platform) {\n throw new Error(\"Screenshot capture is not supported on this operating system\");\n }\n\n const cacheDir = options.cacheDir\n ?? process.env.PUPPETEER_CACHE_DIR\n ?? path.join(os.homedir(), \".cache\", \"puppeteer\");\n const browser = ManagedBrowser.CHROMEHEADLESSSHELL;\n const executablePath = computeExecutablePath({\n browser,\n buildId: SCREENSHOT_BROWSER_BUILD_ID,\n cacheDir,\n platform,\n });\n\n try {\n await fs.access(executablePath);\n return executablePath;\n } catch {\n // First screenshot use installs only the verified headless shell, not full Chrome.\n }\n\n try {\n const installed = await (options.installer ?? installBrowser)({\n browser,\n buildId: SCREENSHOT_BROWSER_BUILD_ID,\n cacheDir,\n platform,\n });\n return installed.executablePath;\n } catch (cause: unknown) {\n throw new Error(\n `Screenshot browser setup failed: ${getErrorMessage(cause)}`,\n { cause },\n );\n }\n}\n\nlet screenshotBrowserExecutablePromise: Promise<string> | undefined;\n\nconst defaultScreenshotBrowserRuntime: ScreenshotBrowserRuntime = {\n async launch(): Promise<PuppeteerBrowser> {\n screenshotBrowserExecutablePromise ??= resolveScreenshotBrowserExecutable();\n let executablePath: string;\n try {\n executablePath = await screenshotBrowserExecutablePromise;\n } catch (cause) {\n screenshotBrowserExecutablePromise = undefined;\n throw cause;\n }\n return puppeteer.launch({\n executablePath,\n headless: SCREENSHOT_HEADLESS_MODE,\n });\n },\n};\n\ninterface InterceptedRequest {\n url(): string;\n isInterceptResolutionHandled(): boolean;\n continue(): Promise<unknown>;\n abort(errorCode?: string): Promise<unknown>;\n}\n\nfunction validateViewports(viewports: ViewportConfig[]): ViewportConfig[] {\n if (viewports.length === 0 || viewports.length > MAX_VIEWPORTS) {\n throw new Error(`Between 1 and ${MAX_VIEWPORTS} viewports are required`);\n }\n\n const outputNames = new Set<string>();\n return viewports.map((viewport, index) => {\n if (!viewport || typeof viewport !== \"object\") {\n throw new Error(`Viewport #${index + 1} must be an object`);\n }\n if (typeof viewport.name !== \"string\" || !SAFE_VIEWPORT_NAME.test(viewport.name)) {\n throw new Error(\n `Viewport #${index + 1} name must match ${SAFE_VIEWPORT_NAME.source}`,\n );\n }\n for (const [label, value] of [[\"width\", viewport.width], [\"height\", viewport.height]] as const) {\n if (\n !Number.isSafeInteger(value)\n || value < MIN_VIEWPORT_DIMENSION\n || value > MAX_VIEWPORT_DIMENSION\n ) {\n throw new Error(\n `Viewport #${index + 1} ${label} must be an integer between ${MIN_VIEWPORT_DIMENSION} and ${MAX_VIEWPORT_DIMENSION}`,\n );\n }\n }\n\n const outputName = `${viewport.name}_${viewport.width}x${viewport.height}.png`.toLowerCase();\n if (outputNames.has(outputName)) {\n throw new Error(`Duplicate viewport output filename: ${outputName}`);\n }\n outputNames.add(outputName);\n return { name: viewport.name, width: viewport.width, height: viewport.height };\n });\n}\n\nfunction resolveContainedOutputPath(outputDirectory: string, fileName: string): string {\n const outputPath = path.resolve(outputDirectory, fileName);\n const relativePath = path.relative(outputDirectory, outputPath);\n if (relativePath.startsWith(\"..\") || path.isAbsolute(relativePath)) {\n throw new Error(\"Screenshot output path escapes the requested output directory\");\n }\n return outputPath;\n}\n\nfunction isPathWithinDirectory(directory: string, filePath: string): boolean {\n const relativePath = path.relative(directory, filePath);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath));\n}\n\nasync function assertLocalScreenshotRequestAllowed(requestUrl: URL, localDirectory: string): Promise<void> {\n if (requestUrl.hostname) {\n throw new Error(\"Blocked local file request with a host name\");\n }\n\n let resolvedPath: string;\n try {\n resolvedPath = await fs.realpath(fileURLToPath(requestUrl));\n } catch (error: unknown) {\n throw new Error(`Blocked local file request: ${getErrorMessage(error)}`);\n }\n\n if (!isPathWithinDirectory(localDirectory, resolvedPath)) {\n throw new Error(\"Blocked local file request outside the selected file directory\");\n }\n}\n\nasync function assertScreenshotRequestAllowed(requestUrl: string, localDirectory?: string): Promise<void> {\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(requestUrl);\n } catch {\n throw new Error(\"Blocked invalid page request URL\");\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n await assertPublicHttpUrl(parsedUrl);\n return;\n }\n\n if (parsedUrl.protocol === \"data:\" || parsedUrl.protocol === \"blob:\") {\n return;\n }\n\n if (parsedUrl.protocol === \"file:\" && localDirectory) {\n await assertLocalScreenshotRequestAllowed(parsedUrl, localDirectory);\n return;\n }\n\n throw new Error(`Blocked unsupported page request protocol ${parsedUrl.protocol}`);\n}\n\nasync function resolveScreenshotRequest(\n request: InterceptedRequest,\n localDirectory: string | undefined,\n onBlocked: (message: string) => void,\n): Promise<void> {\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n try {\n await assertScreenshotRequestAllowed(request.url(), localDirectory);\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n await request.continue();\n } catch (error: unknown) {\n onBlocked(getErrorMessage(error));\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n await request.abort(\"blockedbyclient\");\n }\n}\n\n/**\n * Captures screenshots of a local HTML file or remote URL at different viewport sizes.\n * @param targetPath Local file path or HTTP(S) URL\n * @param outputDirectory Absolute path to save screenshots\n * @param customViewports Optional custom viewport settings\n */\nexport async function captureScreenshots(\n targetPath: string,\n outputDirectory: string,\n customViewports?: ViewportConfig[],\n browserRuntime: ScreenshotBrowserRuntime = defaultScreenshotBrowserRuntime,\n): Promise<ScreenshotResult[]> {\n if (typeof targetPath !== \"string\" || targetPath.trim() === \"\") {\n throw new Error(\"targetPath must be a non-empty string\");\n }\n if (typeof outputDirectory !== \"string\" || outputDirectory.trim() === \"\") {\n throw new Error(\"outputDirectory must be a non-empty string\");\n }\n\n const viewports = validateViewports(\n customViewports && customViewports.length > 0 ? customViewports : DEFAULT_VIEWPORTS,\n );\n const resolvedOutputDirectory = path.resolve(outputDirectory);\n\n // Resolve target to file:// URL if it is a local file path\n let targetUrl: string;\n let localDirectory: string | undefined;\n if (/^https?:\\/\\//i.test(targetPath)) {\n targetUrl = (await assertPublicHttpUrl(targetPath)).href;\n } else {\n const absolutePath = path.resolve(targetPath);\n const resolvedPath = await fs.realpath(absolutePath);\n const stats = await fs.stat(resolvedPath);\n if (!stats.isFile()) {\n throw new Error(`Screenshot target is not a regular file: ${resolvedPath}`);\n }\n localDirectory = path.dirname(resolvedPath);\n targetUrl = pathToFileURL(resolvedPath).href;\n }\n\n // Ensure output directory exists\n await fs.mkdir(resolvedOutputDirectory, { recursive: true });\n\n const browser = await browserRuntime.launch();\n\n const results: ScreenshotResult[] = [];\n\n try {\n const page = await browser.newPage();\n page.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);\n\n let blockedRequestMessage: string | undefined;\n await page.setRequestInterception(true);\n page.on(\"request\", (request) => {\n void resolveScreenshotRequest(request, localDirectory, (message) => {\n blockedRequestMessage ??= message;\n }).catch(() => {\n // Puppeteer will surface navigation failures; avoid an unhandled listener rejection.\n });\n });\n\n for (const vp of viewports) {\n await page.setViewport({\n width: vp.width,\n height: vp.height,\n deviceScaleFactor: 1\n });\n\n // Load URL (wait until network is idle or DOM loaded)\n try {\n await page.goto(targetUrl, {\n waitUntil: \"domcontentloaded\",\n timeout: NAVIGATION_TIMEOUT_MS,\n });\n } catch (error: unknown) {\n if (blockedRequestMessage) {\n throw new Error(`Screenshot navigation blocked: ${blockedRequestMessage}`);\n }\n throw new Error(`Screenshot navigation failed: ${getErrorMessage(error)}`);\n }\n\n // Short wait for any animations or layout adjustments to settle\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n const fileName = `${vp.name}_${vp.width}x${vp.height}.png`;\n const outputPath = resolveContainedOutputPath(resolvedOutputDirectory, fileName);\n\n await page.screenshot({\n path: outputPath,\n fullPage: false // Captures above the fold viewport\n });\n\n results.push({\n viewportName: vp.name,\n width: vp.width,\n height: vp.height,\n outputPath\n });\n }\n } finally {\n await browser.close();\n }\n\n return results;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-web-validator",
3
- "version": "1.3.6",
3
+ "version": "1.3.8",
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": {
@@ -49,14 +49,16 @@
49
49
  },
50
50
  "mcpName": "io.github.AKzar1el/mcp-web-validator",
51
51
  "dependencies": {
52
+ "@puppeteer/browsers": "3.2.0",
52
53
  "@modelcontextprotocol/sdk": "^1.29.0",
53
54
  "cheerio": "^1.0.0",
54
- "puppeteer": "25.7.0",
55
+ "puppeteer-core": "25.7.0",
55
56
  "undici": "^7.29.0",
56
57
  "zod": "^4.4.3"
57
58
  },
58
59
  "devDependencies": {
59
60
  "@types/node": "^26.2.0",
61
+ "puppeteer": "25.7.0",
60
62
  "tsx": "^4.23.0",
61
63
  "typescript": "^7.0.2"
62
64
  }