1
1
mirror of https://github.com/theoludwig/html-w3c-validator.git synced 2024-07-20 07:30:11 +02:00

Compare commits

...

10 Commits

Author SHA1 Message Date
5f63d749e8
docs: fix wrong link for .html-w3c-validatorrc.json JSON schema 2024-02-02 17:28:44 +01:00
67b70feb15
fix: wrong husky config 2024-02-02 17:10:44 +01:00
6b28c6d224
perf: remove usage of html-validator dependency
Allows to have better control of the implementation.
Also reduce package size by removing needed dependencies to install.
2024-02-02 17:02:19 +01:00
a1340b2729
fix: improve config schema 2024-02-02 15:56:32 +01:00
92320385b5
docs: update description 2024-02-02 15:44:03 +01:00
8934ac1b7a
feat: add config JSON schema 2024-02-02 15:35:18 +01:00
09731d4749
refactor: simplify logic 2024-02-02 14:47:31 +01:00
2e0e136355
docs: add CLI option --current-working-directory 2024-02-02 08:22:57 +01:00
04a2742e46
chore: cleaner configs 2024-01-30 01:16:56 +01:00
75f862d0fd
docs(license): add email address 2024-01-29 21:57:54 +01:00
26 changed files with 828 additions and 1771 deletions

View File

@ -23,6 +23,5 @@ jobs:
- run: 'npm run lint:commit -- --to "${{ github.sha }}"' - run: 'npm run lint:commit -- --to "${{ github.sha }}"'
- run: "npm run lint:editorconfig" - run: "npm run lint:editorconfig"
- run: "npm run lint:markdown"
- run: "npm run lint:eslint" - run: "npm run lint:eslint"
- run: "npm run lint:prettier" - run: "npm run lint:prettier"

3
.husky/commit-msg Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env sh
npm run lint:commit -- --edit

4
.husky/pre-commit Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env sh
npm run lint:staged
npm run build:typescript

View File

@ -1,6 +1,6 @@
{ {
"*": ["editorconfig-checker"], "**/*": ["editorconfig-checker", "prettier --write --ignore-unknown"],
"*.{js,ts,jsx,tsx}": ["prettier --write", "eslint --fix"], "**/*.{js,jsx,ts,tsx}": [
"*.{yml,json}": ["prettier --write"], "eslint --fix --max-warnings 0 --report-unused-disable-directives"
"*.md": ["prettier --write", "markdownlint --dot --fix"] ]
} }

View File

@ -1,11 +0,0 @@
{
"config": {
"extends": "markdownlint/style/prettier",
"relative-links": true,
"default": true,
"MD033": false
},
"globs": ["**/*.{md,mdx}"],
"ignores": ["**/node_modules"],
"customRules": ["markdownlint-rule-relative-links"]
}

View File

@ -1,6 +1,6 @@
# MIT License # MIT License
Copyright (c) Théo LUDWIG Copyright (c) Théo LUDWIG <contact@theoludwig.fr>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,9 +1,7 @@
<h1 align="center">html-w3c-validator</h1> <h1 align="center">html-w3c-validator</h1>
<p align="center"> <p align="center">
<strong>CLI for validating multiple html pages using <a href="https://validator.w3.org/">validator.w3.org</a>.</strong> <strong>CLI for validating HTML pages using <a href="https://validator.w3.org/">validator.w3.org</a>.</strong>
</p>
</p> </p>
<p align="center"> <p align="center">
@ -22,11 +20,11 @@
## 📜 About ## 📜 About
**html-w3c-validator** is a CLI tool to validate multiple html pages using [validator.w3.org](https://validator.w3.org/). **html-w3c-validator** is a CLI tool to validate HTML pages using [validator.w3.org](https://validator.w3.org/).
You might use a JavaScript framework or simply use HTML but **you should always validate your production HTML** and this validation should be part of your CI/CD pipeline (tests, linting, etc.). You might use a JavaScript framework or simply use HTML but **you should always validate your production HTML** and this validation should be part of your CI/CD pipeline (tests, linting, etc.).
### Why should I validate my HTML pages? ### Why is HTML page validation important?
Quote from [https://validator.w3.org/docs/help.html#why-validate](https://validator.w3.org/docs/help.html#why-validate): Quote from [https://validator.w3.org/docs/help.html#why-validate](https://validator.w3.org/docs/help.html#why-validate):
@ -40,7 +38,7 @@ You can combine **html-w3c-validator** with [start-server-and-test](https://gith
### Prerequisites ### Prerequisites
- [Node.js](https://nodejs.org/) >= 16.0.0 [Node.js](https://nodejs.org/) >= 16.0.0
### Installation (with [start-server-and-test](https://github.com/bahmutov/start-server-and-test)) ### Installation (with [start-server-and-test](https://github.com/bahmutov/start-server-and-test))
@ -59,8 +57,8 @@ npm install --save-dev html-w3c-validator start-server-and-test
"start": "serve \"./build\"", "start": "serve \"./build\"",
// Command to validate your HTML pages // Command to validate your HTML pages
"test:html-w3c-validator": "start-server-and-test \"start\" \"http://127.0.0.1:3000\" \"html-w3c-validator\"" "test:html-w3c-validator": "start-server-and-test \"start\" \"http://127.0.0.1:3000\" \"html-w3c-validator\"",
} },
} }
``` ```
@ -68,13 +66,16 @@ npm install --save-dev html-w3c-validator start-server-and-test
```jsonc ```jsonc
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/master/schema/html-w3c-validatorrc-schema.json",
// URLs to validate.
"urls": ["http://127.0.0.1:3000/", "http://127.0.0.1:3000/about"], "urls": ["http://127.0.0.1:3000/", "http://127.0.0.1:3000/about"],
// You can also specify HTML files instead of URLs // Files to validate.
"files": ["./index.html", "./about.html"], "files": ["./index.html", "./about.html"],
// Specify the severities of the validator (default: ["warning", "error"]) // Specify the severities of the validator messages to report. (default: ["warning", "error"])
"severities": ["info", "warning", "error"] "severities": ["info", "warning", "error"],
} }
``` ```
@ -98,8 +99,9 @@ See the [./example](./example) folder for practical usage.
### Options ### Options
```text ```text
-V, --version Output the version number. --current-working-directory <path> The current working directory (default: `process.cwd()`).
-h, --help Display help for command. -V, --version Output the version number.
-h, --help Display help for command.
``` ```
## 💡 Contributing ## 💡 Contributing

View File

@ -1,4 +1,5 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"urls": ["http://127.0.0.1:3000/", "http://127.0.0.1:3000/about"], "urls": ["http://127.0.0.1:3000/", "http://127.0.0.1:3000/about"],
"files": ["./build/index.html", "./build/about.html"] "files": ["./build/index.html", "./build/about.html"]
} }

View File

@ -14,11 +14,11 @@
"..": { "..": {
"version": "0.0.0-development", "version": "0.0.0-development",
"dev": true, "dev": true,
"hasInstallScript": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"chalk": "5.3.0", "chalk": "5.3.0",
"clipanion": "3.2.1", "clipanion": "3.2.1",
"html-validator": "6.0.1",
"log-symbols": "6.0.0", "log-symbols": "6.0.0",
"ora": "8.0.1", "ora": "8.0.1",
"read-pkg": "9.0.1", "read-pkg": "9.0.1",
@ -28,33 +28,29 @@
"html-w3c-validator": "build/index.js" "html-w3c-validator": "build/index.js"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "18.4.3", "@commitlint/cli": "18.6.0",
"@commitlint/config-conventional": "18.4.3", "@commitlint/config-conventional": "18.6.0",
"@swc/cli": "0.1.63", "@swc/cli": "0.3.6",
"@swc/core": "1.3.101", "@swc/core": "1.3.107",
"@tsconfig/strictest": "2.0.2", "@tsconfig/strictest": "2.0.2",
"@types/html-validator": "5.0.6", "@types/node": "20.11.16",
"@types/mock-fs": "4.13.4", "@types/sinon": "17.0.3",
"@types/node": "20.10.5", "@typescript-eslint/eslint-plugin": "6.20.0",
"@types/sinon": "17.0.2", "@typescript-eslint/parser": "6.20.0",
"@typescript-eslint/eslint-plugin": "6.16.0",
"@typescript-eslint/parser": "6.16.0",
"editorconfig-checker": "5.1.2", "editorconfig-checker": "5.1.2",
"eslint": "8.56.0", "eslint": "8.56.0",
"eslint-config-conventions": "13.1.0", "eslint-config-conventions": "13.1.0",
"eslint-config-prettier": "9.1.0", "eslint-config-prettier": "9.1.0",
"eslint-plugin-import": "2.29.1", "eslint-plugin-import": "2.29.1",
"eslint-plugin-prettier": "5.1.2", "eslint-plugin-prettier": "5.1.3",
"eslint-plugin-promise": "6.1.1", "eslint-plugin-promise": "6.1.1",
"eslint-plugin-unicorn": "50.0.1", "eslint-plugin-unicorn": "50.0.1",
"execa": "8.0.1", "execa": "8.0.1",
"lint-staged": "15.2.0", "husky": "9.0.10",
"markdownlint-cli2": "0.11.0", "lint-staged": "15.2.1",
"markdownlint-rule-relative-links": "2.1.2", "pinst": "3.0.0",
"mock-fs": "5.2.0", "prettier": "3.2.4",
"prettier": "3.1.1", "semantic-release": "23.0.0",
"rimraf": "5.0.5",
"semantic-release": "22.0.12",
"serve": "14.2.1", "serve": "14.2.1",
"sinon": "17.0.1", "sinon": "17.0.1",
"typescript": "5.3.3" "typescript": "5.3.3"
@ -80,9 +76,9 @@
} }
}, },
"node_modules/@sideway/address": { "node_modules/@sideway/address": {
"version": "4.1.4", "version": "4.1.5",
"resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.4.tgz", "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz",
"integrity": "sha512-7vwq+rOHVWjyXxVlR76Agnvhy8I9rpzjosTESvmhNeXOXdZZB15Fl+TI9x1SiHZH5Jv2wTGduSxFDIaq0m3DUw==", "integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@hapi/hoek": "^9.0.0" "@hapi/hoek": "^9.0.0"
@ -242,12 +238,12 @@
"dev": true "dev": true
}, },
"node_modules/axios": { "node_modules/axios": {
"version": "1.6.2", "version": "1.6.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz",
"integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"follow-redirects": "^1.15.0", "follow-redirects": "^1.15.4",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"proxy-from-env": "^1.1.0" "proxy-from-env": "^1.1.0"
} }
@ -601,9 +597,9 @@
} }
}, },
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.15.3", "version": "1.15.5",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
"integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@ -747,14 +743,14 @@
"dev": true "dev": true
}, },
"node_modules/joi": { "node_modules/joi": {
"version": "17.11.0", "version": "17.12.1",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.11.0.tgz", "resolved": "https://registry.npmjs.org/joi/-/joi-17.12.1.tgz",
"integrity": "sha512-NgB+lZLNoqISVy1rZocE9PZI36bL/77ie924Ri43yEvi9GUUMPeyVIr8KdFTMUlby1p0PBYMk9spIxEUQYqrJQ==", "integrity": "sha512-vtxmq+Lsc5SlfqotnfVjlViWfOL9nt/avKNbKYizwf6gsCfq9NYY/ceYRMFD8XDdrjJ9abJyScWmhmIiy+XRtQ==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@hapi/hoek": "^9.0.0", "@hapi/hoek": "^9.3.0",
"@hapi/topo": "^5.0.0", "@hapi/topo": "^5.1.0",
"@sideway/address": "^4.1.3", "@sideway/address": "^4.1.5",
"@sideway/formula": "^3.0.1", "@sideway/formula": "^3.0.1",
"@sideway/pinpoint": "^2.0.0" "@sideway/pinpoint": "^2.0.0"
} }

2220
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{ {
"name": "html-w3c-validator", "name": "html-w3c-validator",
"version": "0.0.0-development", "version": "0.0.0-development",
"description": "CLI for validating multiple html pages using validator.w3.org.", "description": "CLI for validating HTML pages using validator.w3.org.",
"public": true, "public": true,
"types": "module", "types": "module",
"type": "module", "type": "module",
@ -37,55 +37,52 @@
"npm": ">=9.0.0" "npm": ">=9.0.0"
}, },
"scripts": { "scripts": {
"build": "rimraf ./build && swc ./src --out-dir ./build", "build": "swc ./src --out-dir ./build --strip-leading-paths --delete-dir-on-start",
"build:typescript": "tsc", "build:typescript": "tsc",
"start": "node --enable-source-maps build/index.js", "start": "node --enable-source-maps build/index.js",
"lint:commit": "commitlint", "lint:commit": "commitlint",
"lint:editorconfig": "editorconfig-checker", "lint:editorconfig": "editorconfig-checker",
"lint:markdown": "markdownlint-cli2",
"lint:eslint": "eslint . --max-warnings 0 --report-unused-disable-directives --ignore-path .gitignore", "lint:eslint": "eslint . --max-warnings 0 --report-unused-disable-directives --ignore-path .gitignore",
"lint:prettier": "prettier . --check", "lint:prettier": "prettier . --check",
"lint:staged": "lint-staged", "lint:staged": "lint-staged",
"test": "node --enable-source-maps --test build/", "test": "node --enable-source-maps --test",
"release": "semantic-release" "release": "semantic-release",
"postinstall": "husky",
"prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
}, },
"dependencies": { "dependencies": {
"chalk": "5.3.0", "chalk": "5.3.0",
"clipanion": "3.2.1", "clipanion": "3.2.1",
"html-validator": "6.0.1",
"log-symbols": "6.0.0", "log-symbols": "6.0.0",
"ora": "8.0.1", "ora": "8.0.1",
"read-pkg": "9.0.1", "read-pkg": "9.0.1",
"table": "6.8.1" "table": "6.8.1"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "18.4.3", "@commitlint/cli": "18.6.0",
"@commitlint/config-conventional": "18.4.3", "@commitlint/config-conventional": "18.6.0",
"@swc/cli": "0.1.63", "@swc/cli": "0.3.6",
"@swc/core": "1.3.101", "@swc/core": "1.3.107",
"@tsconfig/strictest": "2.0.2", "@tsconfig/strictest": "2.0.2",
"@types/html-validator": "5.0.6", "@types/node": "20.11.16",
"@types/mock-fs": "4.13.4", "@types/sinon": "17.0.3",
"@types/node": "20.10.5", "@typescript-eslint/eslint-plugin": "6.20.0",
"@types/sinon": "17.0.2", "@typescript-eslint/parser": "6.20.0",
"@typescript-eslint/eslint-plugin": "6.16.0",
"@typescript-eslint/parser": "6.16.0",
"editorconfig-checker": "5.1.2", "editorconfig-checker": "5.1.2",
"eslint": "8.56.0", "eslint": "8.56.0",
"eslint-config-conventions": "13.1.0", "eslint-config-conventions": "13.1.0",
"eslint-config-prettier": "9.1.0", "eslint-config-prettier": "9.1.0",
"eslint-plugin-import": "2.29.1", "eslint-plugin-import": "2.29.1",
"eslint-plugin-prettier": "5.1.2", "eslint-plugin-prettier": "5.1.3",
"eslint-plugin-promise": "6.1.1", "eslint-plugin-promise": "6.1.1",
"eslint-plugin-unicorn": "50.0.1", "eslint-plugin-unicorn": "50.0.1",
"execa": "8.0.1", "execa": "8.0.1",
"lint-staged": "15.2.0", "husky": "9.0.10",
"markdownlint-cli2": "0.11.0", "lint-staged": "15.2.1",
"markdownlint-rule-relative-links": "2.1.2", "pinst": "3.0.0",
"mock-fs": "5.2.0", "prettier": "3.2.4",
"prettier": "3.1.1", "semantic-release": "23.0.0",
"rimraf": "5.0.5",
"semantic-release": "22.0.12",
"serve": "14.2.1", "serve": "14.2.1",
"sinon": "17.0.1", "sinon": "17.0.1",
"typescript": "5.3.3" "typescript": "5.3.3"

View File

@ -0,0 +1,50 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/master/schema/html-w3c-validatorrc-schema.json",
"title": "html-w3c-validator configuration schema",
"type": "object",
"properties": {
"$schema": {
"description": "JSON Schema URI",
"type": "string",
"format": "uri",
"default": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/master/schema/html-w3c-validatorrc-schema.json"
},
"urls": {
"description": "URLs to validate.",
"type": "array",
"default": [],
"minItems": 1,
"items": {
"description": "URL to validate.",
"type": "string",
"format": "uri",
"minLength": 1
}
},
"files": {
"description": "Files to validate.",
"type": "array",
"minItems": 1,
"default": [],
"items": {
"description": "File to validate.",
"type": "string",
"format": "uri-reference",
"minLength": 1
}
},
"severities": {
"description": "Specify the severities to report.",
"type": "array",
"minItems": 1,
"default": ["warning", "error"],
"items": {
"description": "Severity to report.",
"type": "string",
"enum": ["error", "warning", "info"]
}
}
},
"additionalProperties": false
}

View File

@ -1,19 +1,15 @@
import path from "node:path"
import fs from "node:fs" import fs from "node:fs"
import path from "node:path"
import { Command, Option } from "clipanion"
import * as typanion from "typanion"
import chalk from "chalk" import chalk from "chalk"
import ora from "ora" import { Command, Option } from "clipanion"
import logSymbols from "log-symbols" import logSymbols from "log-symbols"
import type { import ora from "ora"
ValidationMessageLocationObject,
ParsedJsonAsValidationResults,
} from "html-validator"
import validateHTML from "html-validator"
import { table } from "table" import { table } from "table"
import * as typanion from "typanion"
import { isExistingPath } from "./utils/isExistingPath.js" import type { ValidateHTMLResult } from "./validateHTML.js"
import { getHTMLFromURL, validateHTML } from "./validateHTML.js"
export const CONFIG_FILE_NAME = ".html-w3c-validatorrc.json" export const CONFIG_FILE_NAME = ".html-w3c-validatorrc.json"
@ -50,7 +46,7 @@ const printResults = (results: Result[]): void => {
export class HTMLValidatorCommand extends Command { export class HTMLValidatorCommand extends Command {
static override usage = { static override usage = {
description: description:
"CLI for validating multiple html pages using <https://validator.w3.org/>.", "CLI for validating HTML pages using <https://validator.w3.org/>.",
} }
public currentWorkingDirectory = Option.String( public currentWorkingDirectory = Option.String(
@ -65,22 +61,20 @@ export class HTMLValidatorCommand extends Command {
public async execute(): Promise<number> { public async execute(): Promise<number> {
const configPath = path.join(this.currentWorkingDirectory, CONFIG_FILE_NAME) const configPath = path.join(this.currentWorkingDirectory, CONFIG_FILE_NAME)
try { try {
if (!(await isExistingPath(configPath))) { let configData: string
try {
configData = await fs.promises.readFile(configPath, {
encoding: "utf-8",
})
} catch (error) {
throw new Error( throw new Error(
`No config file found at ${configPath}. Please create "${CONFIG_FILE_NAME}".`, `No config file found at ${configPath}. Please create "${CONFIG_FILE_NAME}".`,
) )
} }
const configData = await fs.promises.readFile(configPath, {
encoding: "utf-8",
})
let config: Config = { urls: [], files: [] } let config: Config = { urls: [], files: [] }
let isValidConfig = true
try { try {
config = JSON.parse(configData) config = JSON.parse(configData)
} catch { } catch {
isValidConfig = false
}
if (!isValidConfig) {
throw new Error( throw new Error(
`Invalid config file at "${configPath}". Please check the JSON syntax.`, `Invalid config file at "${configPath}". Please check the JSON syntax.`,
) )
@ -137,29 +131,25 @@ export class HTMLValidatorCommand extends Command {
await Promise.all( await Promise.all(
dataToValidate.map(async ({ data, type }) => { dataToValidate.map(async ({ data, type }) => {
try { try {
const options = { let result: ValidateHTMLResult | undefined
format: "json" as "json" | undefined,
}
let result: ParsedJsonAsValidationResults | undefined
if (type === "url") { if (type === "url") {
result = await validateHTML({ result = await validateHTML({
url: data, htmlData: await getHTMLFromURL(data),
isLocal: true,
...options,
}) })
} else if (type === "file") { } else if (type === "file") {
const htmlPath = path.resolve(this.currentWorkingDirectory, data) const htmlPath = path.resolve(this.currentWorkingDirectory, data)
if (!(await isExistingPath(htmlPath))) { let html: string
try {
html = await fs.promises.readFile(htmlPath, {
encoding: "utf-8",
})
} catch (error) {
throw new Error( throw new Error(
`No file found at "${htmlPath}". Please check the path.`, `No file found at "${htmlPath}". Please check the path.`,
) )
} }
const html = await fs.promises.readFile(htmlPath, {
encoding: "utf-8",
})
result = await validateHTML({ result = await validateHTML({
data: html, htmlData: html,
...options,
}) })
} else { } else {
throw new Error("Invalid type") throw new Error("Invalid type")
@ -194,10 +184,9 @@ export class HTMLValidatorCommand extends Command {
row.push(chalk.red(message.type)) row.push(chalk.red(message.type))
} }
row.push(message.message) row.push(message.message)
const violation = message as ValidationMessageLocationObject if (message.extract != null) {
if (violation.extract != null) {
row.push( row.push(
`line: ${violation.lastLine}, column: ${violation.firstColumn}-${violation.lastColumn}`, `line: ${message.lastLine}, column: ${message.firstColumn}-${message.lastColumn}`,
) )
} }
messagesTable.push(row) messagesTable.push(row)

View File

@ -1,7 +1,9 @@
import test from "node:test" import test from "node:test"
import assert from "node:assert/strict" import assert from "node:assert/strict"
import path from "node:path" import path from "node:path"
import fs from "node:fs"
import { PassThrough } from "node:stream" import { PassThrough } from "node:stream"
import { fileURLToPath } from "node:url"
import sinon from "sinon" import sinon from "sinon"
import { execa } from "execa" import { execa } from "execa"
@ -33,7 +35,10 @@ await test("html-w3c-validator", async (t) => {
async () => { async () => {
const exampleURL = new URL("../../example", import.meta.url) const exampleURL = new URL("../../example", import.meta.url)
process.chdir(exampleURL.pathname) process.chdir(exampleURL.pathname)
await execa("rimraf", ["node_modules"]) await fs.promises.rm(
path.join(fileURLToPath(exampleURL), "node_modules"),
{ recursive: true, force: true },
)
await execa("npm", ["install"]) await execa("npm", ["install"])
const { exitCode } = await execa("npm", [ const { exitCode } = await execa("npm", [
"run", "run",

View File

@ -1,4 +1,5 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"urls": [], "urls": [],
"files": [] "files": []
} }

View File

@ -1,3 +1,4 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": "Invalid" "files": "Invalid"
} }

View File

@ -1,4 +1,5 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": ["./index.html"], "files": ["./index.html"],
"severities": [] "severities": []
} }

View File

@ -1,4 +1,5 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": ["./index.html"], "files": ["./index.html"],
"severities": ["errors-invalid"] "severities": ["errors-invalid"]
} }

View File

@ -1,3 +1,4 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"urls": "Invalid" "urls": "Invalid"
} }

View File

@ -1,3 +1,4 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": ["./index.html"] "files": ["./index.html"]
} }

View File

@ -1,3 +1,4 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": ["./build/index.html", "./build/about.html"] "files": ["./build/index.html", "./build/about.html"]
} }

View File

@ -1,3 +1,4 @@
{ {
"$schema": "https://raw.githubusercontent.com/theoludwig/html-w3c-validator/develop/schema/html-w3c-validatorrc-schema.json",
"files": ["./build/index.html", "./build/about.html"] "files": ["./build/index.html", "./build/about.html"]
} }

View File

@ -1,26 +0,0 @@
import test from "node:test"
import assert from "node:assert/strict"
import fsMock from "mock-fs"
import { isExistingPath } from "../isExistingPath.js"
await test("utils/isExistingPath", async (t) => {
t.afterEach(() => {
fsMock.restore()
})
await t.test("should return true if the file exists", async () => {
fsMock({
"/file.txt": "",
})
assert.strictEqual(await isExistingPath("/file.txt"), true)
})
await t.test("should return false if the file doesn't exists", async () => {
fsMock({
"/file.txt": "",
})
assert.strictEqual(await isExistingPath("/randomfile.txt"), false)
})
})

View File

@ -1,10 +0,0 @@
import fs from "node:fs"
export const isExistingPath = async (path: string): Promise<boolean> => {
try {
await fs.promises.access(path, fs.constants.F_OK)
return true
} catch {
return false
}
}

46
src/validateHTML.ts Normal file
View File

@ -0,0 +1,46 @@
export interface ValidateHTMLOptions {
htmlData: string
}
export interface ValidationMessage {
type: "error" | "info" | "non-document-error"
subType?: "warning" | "fatal" | "internal" | "io" | "schema"
message: string
extract?: string
lastLine: number
firstColumn: number
lastColumn: number
}
export interface ValidateHTMLResult {
messages: ValidationMessage[]
}
export const validateHTML = async (
options: ValidateHTMLOptions,
): Promise<ValidateHTMLResult> => {
const { htmlData } = options
const url = new URL("https://validator.w3.org/nu/")
url.searchParams.set("out", "json")
const response = await fetch(url, {
method: "POST",
body: htmlData,
headers: {
"Content-Type": "text/html",
},
})
if (!response.ok) {
throw new Error(`Failed to validate HTML`)
}
const result = (await response.json()) as ValidateHTMLResult
return result
}
export const getHTMLFromURL = async (url: string): Promise<string> => {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Failed to fetch HTML from "${url}"`)
}
const html = await response.text()
return html
}

View File

@ -9,6 +9,6 @@
"rootDir": "./src", "rootDir": "./src",
"noEmit": true, "noEmit": true,
"exactOptionalPropertyTypes": false, "exactOptionalPropertyTypes": false,
"checkJs": false "checkJs": false,
} },
} }