@mscode-pl/email-lint 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { parseArgs } from 'node:util';
5
+ import { DEFAULT_CLIENTS } from '../core/clients.js';
6
+ import { loadDataset } from '../core/data.js';
7
+ import { lint } from '../core/lint.js';
8
+ import { painter } from './colors.js';
9
+ import { CONFIG_FILE, FAIL_ON, loadConfig } from './config.js';
10
+ import { resolveFiles } from './files.js';
11
+ import { FORMATS, formatFromPath, onlyErrors, render } from './format.js';
12
+ import { runInteractive } from './interactive.js';
13
+ const HELP = `Usage: email-lint [files, folders or globs...] [options]
14
+ email-lint mcp Start an MCP server on stdio for AI agents
15
+
16
+ Checks email HTML against caniemail.com support data.
17
+ Run without arguments in a terminal for an interactive mode.
18
+
19
+ Options:
20
+ -c, --clients <list> Clients to check, e.g. gmail,outlook.windows or all
21
+ (default: ${DEFAULT_CLIENTS.join(',')})
22
+ -i, --ignore <list> Feature slugs to skip, e.g. css-display-flex
23
+ --strict Also report baseline features (doctype, <body>, <style>,
24
+ class selectors) and Gmail in a mobile browser
25
+ -f, --format <type> ${FORMATS.join(', ')} (default: text)
26
+ -o, --output <file> Also save the report; format follows the extension
27
+ (.json, .md, anything else is plain text)
28
+ --verbose Show caniemail notes and links for every issue
29
+ -q, --quiet Report errors only
30
+ --fail-on <level> ${FAIL_ON.join(', ')} (default: error)
31
+ --config <file> Config file (default: ${CONFIG_FILE} if present)
32
+ --stdin Read HTML from stdin
33
+ -v, --version Print version and data date
34
+ -h, --help Show this help
35
+
36
+ Examples:
37
+ email-lint dist/emails
38
+ email-lint "resources/views/emails/**/*.html" --clients gmail,outlook
39
+ email-lint emails -o email-report.md
40
+ cat email.html | email-lint --stdin --format json`;
41
+ const list = (value) => value?.split(',').map((s) => s.trim()).filter(Boolean);
42
+ async function readStdin() {
43
+ const chunks = [];
44
+ for await (const chunk of process.stdin)
45
+ chunks.push(chunk);
46
+ return Buffer.concat(chunks).toString('utf8');
47
+ }
48
+ function version() {
49
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
50
+ return `${pkg.version} (caniemail data: ${loadDataset().last_update_date})`;
51
+ }
52
+ async function main() {
53
+ if (process.argv[2] === 'mcp' && process.argv.length === 3) {
54
+ const { serve } = await import('../mcp/server.js');
55
+ await serve();
56
+ return 0;
57
+ }
58
+ const { values, positionals } = parseArgs({
59
+ allowPositionals: true,
60
+ options: {
61
+ clients: { type: 'string', short: 'c' },
62
+ ignore: { type: 'string', short: 'i' },
63
+ strict: { type: 'boolean' },
64
+ verbose: { type: 'boolean', default: false },
65
+ quiet: { type: 'boolean', short: 'q', default: false },
66
+ format: { type: 'string', short: 'f', default: 'text' },
67
+ output: { type: 'string', short: 'o' },
68
+ 'fail-on': { type: 'string' },
69
+ config: { type: 'string' },
70
+ stdin: { type: 'boolean', default: false },
71
+ version: { type: 'boolean', short: 'v' },
72
+ help: { type: 'boolean', short: 'h' },
73
+ },
74
+ });
75
+ if (values.help) {
76
+ console.log(HELP);
77
+ return 0;
78
+ }
79
+ if (values.version) {
80
+ console.log(version());
81
+ return 0;
82
+ }
83
+ const config = await loadConfig(values.config);
84
+ const patterns = positionals.length ? positionals : (config.files ?? []);
85
+ if (!patterns.length && !values.stdin) {
86
+ if (process.stdin.isTTY && process.stdout.isTTY)
87
+ return runInteractive();
88
+ console.log(HELP);
89
+ return 2;
90
+ }
91
+ const format = values.format;
92
+ if (!FORMATS.includes(format)) {
93
+ console.error(`Unknown format "${values.format}". Use ${FORMATS.join(', ')}.`);
94
+ return 2;
95
+ }
96
+ const failOn = (values['fail-on'] ?? config.failOn ?? 'error');
97
+ if (!FAIL_ON.includes(failOn)) {
98
+ console.error(`Unknown --fail-on "${failOn}". Use ${FAIL_ON.join(', ')}.`);
99
+ return 2;
100
+ }
101
+ const options = {
102
+ clients: list(values.clients) ?? config.clients,
103
+ ignore: list(values.ignore) ?? config.ignore,
104
+ strict: values.strict ?? config.strict,
105
+ };
106
+ let results = [];
107
+ if (values.stdin) {
108
+ results.push({ file: '<stdin>', ...lint(await readStdin(), options) });
109
+ }
110
+ else {
111
+ const files = await resolveFiles(patterns);
112
+ if (!files.length) {
113
+ console.error(`No HTML files found for: ${patterns.join(' ')}`);
114
+ return 2;
115
+ }
116
+ for (const file of files) {
117
+ results.push({ file, ...lint(await readFile(file, 'utf8'), options) });
118
+ }
119
+ }
120
+ if (values.quiet)
121
+ results = onlyErrors(results);
122
+ console.log(render(results, format, { verbose: values.verbose }));
123
+ if (values.output) {
124
+ const report = render(results, formatFromPath(values.output), { paint: painter(false), verbose: true });
125
+ await writeFile(values.output, report);
126
+ if (format === 'text')
127
+ console.log(`Report saved to ${values.output}`);
128
+ }
129
+ const errors = results.reduce((n, r) => n + r.errors, 0);
130
+ const warnings = results.reduce((n, r) => n + r.warnings, 0);
131
+ if (failOn === 'error' && errors)
132
+ return 1;
133
+ if (failOn === 'warning' && (errors || warnings))
134
+ return 1;
135
+ return 0;
136
+ }
137
+ main().then((code) => {
138
+ process.exitCode = code;
139
+ }, (error) => {
140
+ console.error(error instanceof Error ? error.message : String(error));
141
+ process.exitCode = 2;
142
+ });
@@ -0,0 +1 @@
1
+ export declare const BASELINE_FEATURES: string[];
@@ -0,0 +1,24 @@
1
+ // Skipped unless strict: the only fix would be removing them from the email.
2
+ export const BASELINE_FEATURES = [
3
+ 'html-doctype',
4
+ 'html-body',
5
+ 'html-style',
6
+ 'html-comments',
7
+ 'html-table',
8
+ 'html-div',
9
+ 'html-p',
10
+ 'html-span',
11
+ 'html-img',
12
+ 'html-lang',
13
+ 'html-dir',
14
+ 'html-role',
15
+ 'html-aria-describedby',
16
+ 'html-aria-hidden',
17
+ 'html-aria-label',
18
+ 'html-aria-labelledby',
19
+ 'html-aria-live',
20
+ 'css-selector-class',
21
+ 'css-selector-type',
22
+ 'css-selector-grouping',
23
+ 'css-at-media',
24
+ ];
@@ -0,0 +1,22 @@
1
+ import type { Dataset, Feature } from './data.js';
2
+ export declare const DEFAULT_CLIENTS: string[];
3
+ export type Status = 'unsupported' | 'partial';
4
+ export interface ClientSupport {
5
+ family: string;
6
+ platform: string;
7
+ familyName: string;
8
+ platformName: string;
9
+ status: Status;
10
+ notes: string[];
11
+ }
12
+ export declare const SKIPPED_PLATFORMS: string[];
13
+ export interface ClientFilter {
14
+ family: string;
15
+ platform?: string;
16
+ }
17
+ export interface ClientSelection {
18
+ include: ClientFilter[] | 'all';
19
+ exclude: Set<string>;
20
+ }
21
+ export declare function parseClients(input: string[] | undefined, dataset: Dataset, strict?: boolean): ClientSelection;
22
+ export declare function unsupportedClients(feature: Feature, dataset: Dataset, selection: ClientSelection): ClientSupport[];
@@ -0,0 +1,65 @@
1
+ export const DEFAULT_CLIENTS = [
2
+ 'gmail',
3
+ 'outlook',
4
+ 'apple-mail',
5
+ 'yahoo',
6
+ 'samsung-email',
7
+ 'thunderbird',
8
+ ];
9
+ // Gmail in a mobile browser drops `<style>`, so it would flag nearly every email.
10
+ export const SKIPPED_PLATFORMS = ['gmail.mobile-webmail'];
11
+ export function parseClients(input, dataset, strict = false) {
12
+ const list = (input?.length ? input : DEFAULT_CLIENTS).map((e) => e.trim().toLowerCase());
13
+ const exclude = new Set(strict ? [] : SKIPPED_PLATFORMS.filter((p) => !list.includes(p)));
14
+ if (list.includes('all'))
15
+ return { include: 'all', exclude };
16
+ const { family: families, platform: platforms } = dataset.nicenames;
17
+ const include = list.map((entry) => {
18
+ const [family, platform] = entry.split('.');
19
+ if (!(family in families)) {
20
+ throw new Error(`Unknown client "${entry}". Known: ${Object.keys(families).join(', ')}.`);
21
+ }
22
+ if (platform && !(platform in platforms)) {
23
+ throw new Error(`Unknown platform "${platform}" in "${entry}". Known: ${Object.keys(platforms).join(', ')}.`);
24
+ }
25
+ return { family, platform };
26
+ });
27
+ return { include, exclude };
28
+ }
29
+ function matchesFilter(selection, family, platform) {
30
+ if (selection.exclude.has(`${family}.${platform}`))
31
+ return false;
32
+ if (selection.include === 'all')
33
+ return true;
34
+ return selection.include.some((f) => f.family === family && (!f.platform || f.platform === platform));
35
+ }
36
+ // Only the newest tested version of each platform counts.
37
+ export function unsupportedClients(feature, dataset, selection) {
38
+ const result = [];
39
+ for (const [family, platforms] of Object.entries(feature.stats)) {
40
+ for (const [platform, versions] of Object.entries(platforms)) {
41
+ if (!matchesFilter(selection, family, platform))
42
+ continue;
43
+ const values = Object.values(versions);
44
+ const latest = values[values.length - 1];
45
+ if (!latest)
46
+ continue;
47
+ const [flag, ...rest] = latest.trim().split(/\s+/);
48
+ const status = flag === 'n' ? 'unsupported' : flag === 'a' ? 'partial' : undefined;
49
+ if (!status)
50
+ continue;
51
+ const notes = rest
52
+ .map((ref) => feature.notes_by_num?.[ref.replace('#', '')])
53
+ .filter((n) => Boolean(n));
54
+ result.push({
55
+ family,
56
+ platform,
57
+ familyName: dataset.nicenames.family[family] ?? family,
58
+ platformName: dataset.nicenames.platform[platform] ?? platform,
59
+ status,
60
+ notes,
61
+ });
62
+ }
63
+ }
64
+ return result;
65
+ }
@@ -0,0 +1,20 @@
1
+ export type SupportValue = string;
2
+ export interface Feature {
3
+ slug: string;
4
+ title: string;
5
+ category: 'css' | 'html' | 'image' | 'others';
6
+ url: string;
7
+ /** family -> platform -> version -> support value ("y", "n", "a #1", "u") */
8
+ stats: Record<string, Record<string, Record<string, SupportValue>>>;
9
+ notes_by_num: Record<string, string> | null;
10
+ }
11
+ export interface Dataset {
12
+ source: string;
13
+ last_update_date: string;
14
+ nicenames: {
15
+ family: Record<string, string>;
16
+ platform: Record<string, string>;
17
+ };
18
+ data: Feature[];
19
+ }
20
+ export declare function loadDataset(): Dataset;
@@ -0,0 +1,6 @@
1
+ import { readFileSync } from 'node:fs';
2
+ let cached;
3
+ export function loadDataset() {
4
+ cached ??= JSON.parse(readFileSync(new URL('../../data/caniemail.json', import.meta.url), 'utf8'));
5
+ return cached;
6
+ }
@@ -0,0 +1,27 @@
1
+ import { type Feature } from './data.js';
2
+ import { type ClientSupport } from './clients.js';
3
+ export interface LintOptions {
4
+ clients?: string[];
5
+ ignore?: string[];
6
+ strict?: boolean;
7
+ }
8
+ export interface Issue {
9
+ slug: string;
10
+ title: string;
11
+ url: string;
12
+ category: Feature['category'];
13
+ level: 'error' | 'warning';
14
+ lines: number[];
15
+ clients: ClientSupport[];
16
+ }
17
+ export interface ParseError {
18
+ line: number;
19
+ message: string;
20
+ }
21
+ export interface LintResult {
22
+ issues: Issue[];
23
+ errors: number;
24
+ warnings: number;
25
+ parseErrors: ParseError[];
26
+ }
27
+ export declare function lint(html: string, options?: LintOptions): LintResult;
@@ -0,0 +1,217 @@
1
+ import { parseDocument } from 'htmlparser2';
2
+ import postcss from 'postcss';
3
+ import { BASELINE_FEATURES } from './baseline.js';
4
+ import { loadDataset } from './data.js';
5
+ import { buildRules } from './rules.js';
6
+ import { analyzeSelector } from './selectors.js';
7
+ import { parseClients, unsupportedClients } from './clients.js';
8
+ const IMAGE_EXTENSIONS = {
9
+ apng: 'image-apng',
10
+ avif: 'image-avif',
11
+ bmp: 'image-bmp',
12
+ gif: 'image-gif',
13
+ heic: 'image-heif',
14
+ heif: 'image-heif',
15
+ ico: 'image-ico',
16
+ jpg: 'image-jpg',
17
+ jpeg: 'image-jpg',
18
+ mp4: 'image-mp4',
19
+ png: 'image-png',
20
+ svg: 'image-svg',
21
+ tif: 'image-tiff',
22
+ tiff: 'image-tiff',
23
+ webp: 'image-webp',
24
+ };
25
+ // Outlook for Windows renders with Word and skips everything between these two comments.
26
+ const WORD_PLATFORMS = new Set(['outlook.windows', 'outlook.windows-mail']);
27
+ const NOT_MSO_START = /^\[if\s+!mso\]>\s*<!/i;
28
+ const NOT_MSO_END = /^\s*<!\[endif\]\s*$/i;
29
+ let rulesCache;
30
+ export function lint(html, options = {}) {
31
+ const dataset = loadDataset();
32
+ rulesCache ??= buildRules(dataset.data);
33
+ const rules = [...rulesCache];
34
+ const selection = parseClients(options.clients, dataset, options.strict);
35
+ const unknown = (options.ignore ?? []).filter((slug) => !dataset.data.some((f) => f.slug === slug));
36
+ if (unknown.length) {
37
+ throw new Error(`Unknown feature slug in ignore list: ${unknown.join(', ')}.`);
38
+ }
39
+ const ignored = new Set([...(options.ignore ?? []), ...(options.strict ? [] : BASELINE_FEATURES)]);
40
+ const hits = new Map();
41
+ const parseErrors = [];
42
+ const lineOf = lineLocator(html);
43
+ let hiddenFromWord = false;
44
+ const hit = (slug, line) => {
45
+ if (ignored.has(slug))
46
+ return;
47
+ let entry = hits.get(slug);
48
+ if (!entry)
49
+ hits.set(slug, (entry = { lines: new Set(), seenByWord: false }));
50
+ entry.lines.add(line);
51
+ if (!hiddenFromWord)
52
+ entry.seenByWord = true;
53
+ };
54
+ const checkUrl = (url, line) => {
55
+ const value = url.trim().replace(/^['"]|['"]$/g, '');
56
+ const dataUri = value.match(/^data:image\/([a-z0-9.+-]+)[;,]/i);
57
+ if (dataUri) {
58
+ hit('image-base64', line);
59
+ const format = IMAGE_EXTENSIONS[dataUri[1].toLowerCase().replace('+xml', '')];
60
+ if (format)
61
+ hit(format, line);
62
+ return;
63
+ }
64
+ const ext = value.split(/[?#]/)[0].match(/\.([a-z0-9]+)$/i)?.[1]?.toLowerCase();
65
+ if (ext && IMAGE_EXTENSIONS[ext])
66
+ hit(IMAGE_EXTENSIONS[ext], line);
67
+ };
68
+ const checkCss = (root, baseLine, inline) => {
69
+ const lineFor = (node) => baseLine + (node.source?.start?.line ?? 1) - 1;
70
+ root.walk((node) => {
71
+ const line = lineFor(node);
72
+ if (node.type === 'comment') {
73
+ hit('css-comments', line);
74
+ }
75
+ else if (node.type === 'atrule') {
76
+ const at = { name: node.name.toLowerCase(), params: node.params };
77
+ for (const [slug, rule] of rules)
78
+ if (rule.atRule?.(at))
79
+ hit(slug, line);
80
+ }
81
+ else if (node.type === 'rule') {
82
+ if (node.parent?.type === 'rule')
83
+ hit('css-nesting', line);
84
+ if (inline || insideKeyframes(node))
85
+ return;
86
+ const info = analyzeSelector(node.selector);
87
+ for (const [slug, rule] of rules)
88
+ if (rule.selector?.(info))
89
+ hit(slug, line);
90
+ }
91
+ else if (node.type === 'decl') {
92
+ const decl = {
93
+ prop: node.prop.toLowerCase().replace(/^-(webkit|moz|ms|o)-/, ''),
94
+ value: stripStrings(node.value),
95
+ important: node.important === true,
96
+ };
97
+ for (const [slug, rule] of rules)
98
+ if (rule.decl?.(decl))
99
+ hit(slug, line);
100
+ for (const match of node.value.matchAll(/url\(([^)]*)\)/gi))
101
+ checkUrl(match[1], line);
102
+ }
103
+ });
104
+ };
105
+ const parseCss = (css, baseLine, inline) => {
106
+ try {
107
+ // Inline styles are wrapped so postcss sees a rule; the wrapper selector is never checked.
108
+ const root = postcss.parse(inline ? `x{${css}}` : css);
109
+ checkCss(root, baseLine, inline);
110
+ }
111
+ catch (error) {
112
+ const err = error;
113
+ parseErrors.push({
114
+ line: baseLine + (err.line ?? 1) - 1,
115
+ message: `CSS: ${err.reason ?? err.message}`,
116
+ });
117
+ }
118
+ };
119
+ const walk = (nodes) => {
120
+ for (const node of nodes) {
121
+ const line = lineOf(node.startIndex ?? 0);
122
+ if (node.type === 'comment') {
123
+ if (NOT_MSO_START.test(node.data))
124
+ hiddenFromWord = true;
125
+ else if (NOT_MSO_END.test(node.data))
126
+ hiddenFromWord = false;
127
+ hit('html-comments', line);
128
+ continue;
129
+ }
130
+ if (node.type === 'directive') {
131
+ if (/^!doctype\s+html\s*$/i.test(node.data))
132
+ hit('html-doctype', line);
133
+ continue;
134
+ }
135
+ if (node.type !== 'tag' && node.type !== 'style' && node.type !== 'script')
136
+ continue;
137
+ const el = node;
138
+ const element = { tag: el.name.toLowerCase(), attrs: el.attribs };
139
+ for (const [slug, rule] of rules)
140
+ if (rule.element?.(element))
141
+ hit(slug, line);
142
+ if (element.attrs.style)
143
+ parseCss(element.attrs.style, line, true);
144
+ if (element.tag === 'img' && element.attrs.src)
145
+ checkUrl(element.attrs.src, line);
146
+ if (element.attrs.background)
147
+ checkUrl(element.attrs.background, line);
148
+ if (element.attrs.srcset) {
149
+ for (const candidate of element.attrs.srcset.split(',')) {
150
+ checkUrl(candidate.trim().split(/\s+/)[0], line);
151
+ }
152
+ }
153
+ if (element.tag === 'style') {
154
+ const text = el.children.map((c) => ('data' in c ? c.data : '')).join('');
155
+ const start = el.children[0]?.startIndex ?? el.startIndex ?? 0;
156
+ parseCss(text, lineOf(start), false);
157
+ continue;
158
+ }
159
+ walk(el.children);
160
+ }
161
+ };
162
+ walk(parseDocument(html, { withStartIndices: true }).children);
163
+ const issues = [];
164
+ for (const [slug, { lines, seenByWord }] of hits) {
165
+ const feature = dataset.data.find((f) => f.slug === slug);
166
+ if (!feature)
167
+ continue;
168
+ const clients = unsupportedClients(feature, dataset, selection).filter((c) => seenByWord || !WORD_PLATFORMS.has(`${c.family}.${c.platform}`));
169
+ if (!clients.length)
170
+ continue;
171
+ issues.push({
172
+ slug,
173
+ title: feature.title.trim(),
174
+ url: feature.url,
175
+ category: feature.category,
176
+ level: clients.some((c) => c.status === 'unsupported') ? 'error' : 'warning',
177
+ lines: [...lines].sort((a, b) => a - b),
178
+ clients,
179
+ });
180
+ }
181
+ issues.sort((a, b) => a.lines[0] - b.lines[0] || a.slug.localeCompare(b.slug));
182
+ return {
183
+ issues,
184
+ errors: issues.filter((i) => i.level === 'error').length,
185
+ warnings: issues.filter((i) => i.level === 'warning').length,
186
+ parseErrors,
187
+ };
188
+ }
189
+ function lineLocator(text) {
190
+ const starts = [0];
191
+ for (let i = 0; i < text.length; i++)
192
+ if (text[i] === '\n')
193
+ starts.push(i + 1);
194
+ return (index) => {
195
+ let lo = 0;
196
+ let hi = starts.length - 1;
197
+ while (lo < hi) {
198
+ const mid = (lo + hi + 1) >> 1;
199
+ if (starts[mid] <= index)
200
+ lo = mid;
201
+ else
202
+ hi = mid - 1;
203
+ }
204
+ return lo + 1;
205
+ };
206
+ }
207
+ function insideKeyframes(node) {
208
+ const parent = node.parent;
209
+ if (!parent || parent.type === 'root' || parent.type === 'document')
210
+ return false;
211
+ if (parent.type === 'atrule' && /keyframes$/i.test(parent.name))
212
+ return true;
213
+ return insideKeyframes(parent);
214
+ }
215
+ function stripStrings(value) {
216
+ return value.replace(/"[^"]*"|'[^']*'/g, '""').replace(/url\([^)]*\)/gi, 'url()');
217
+ }
@@ -0,0 +1,23 @@
1
+ import type { Feature } from './data.js';
2
+ import type { SelectorInfo } from './selectors.js';
3
+ export interface Declaration {
4
+ prop: string;
5
+ value: string;
6
+ important: boolean;
7
+ }
8
+ export interface AtRule {
9
+ name: string;
10
+ params: string;
11
+ }
12
+ export interface Element {
13
+ tag: string;
14
+ attrs: Record<string, string>;
15
+ }
16
+ export interface Rule {
17
+ decl?: (d: Declaration) => boolean;
18
+ atRule?: (a: AtRule) => boolean;
19
+ selector?: (s: SelectorInfo) => boolean;
20
+ element?: (e: Element) => boolean;
21
+ }
22
+ export declare function buildRules(features: Feature[]): Map<string, Rule>;
23
+ export declare const DOCUMENT_FEATURES: Set<string>;