@mscode-pl/email-lint 0.0.0-stage → 0.1.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.
- package/LICENSE +24 -0
- package/README.md +198 -3
- package/data/caniemail.json +1 -0
- package/dist/cli/colors.d.ts +13 -0
- package/dist/cli/colors.js +23 -0
- package/dist/cli/config.d.ts +11 -0
- package/dist/cli/config.js +56 -0
- package/dist/cli/files.d.ts +7 -0
- package/dist/cli/files.js +44 -0
- package/dist/cli/format.d.ts +23 -0
- package/dist/cli/format.js +204 -0
- package/dist/cli/interactive.d.ts +1 -0
- package/dist/cli/interactive.js +154 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +136 -0
- package/dist/core/baseline.d.ts +1 -0
- package/dist/core/baseline.js +24 -0
- package/dist/core/clients.d.ts +22 -0
- package/dist/core/clients.js +65 -0
- package/dist/core/data.d.ts +20 -0
- package/dist/core/data.js +6 -0
- package/dist/core/lint.d.ts +27 -0
- package/dist/core/lint.js +217 -0
- package/dist/core/rules.d.ts +23 -0
- package/dist/core/rules.js +164 -0
- package/dist/core/selectors.d.ts +15 -0
- package/dist/core/selectors.js +47 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +6 -0
- package/package.json +66 -6
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
declare const CODES: {
|
|
2
|
+
readonly bold: readonly [1, 22];
|
|
3
|
+
readonly dim: readonly [2, 22];
|
|
4
|
+
readonly underline: readonly [4, 24];
|
|
5
|
+
readonly red: readonly [31, 39];
|
|
6
|
+
readonly green: readonly [32, 39];
|
|
7
|
+
readonly yellow: readonly [33, 39];
|
|
8
|
+
};
|
|
9
|
+
export type Style = keyof typeof CODES;
|
|
10
|
+
export type Paint = (style: Style, text: string) => string;
|
|
11
|
+
export declare function colorSupported(): boolean;
|
|
12
|
+
export declare function painter(enabled?: boolean): Paint;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const CODES = {
|
|
2
|
+
bold: [1, 22],
|
|
3
|
+
dim: [2, 22],
|
|
4
|
+
underline: [4, 24],
|
|
5
|
+
red: [31, 39],
|
|
6
|
+
green: [32, 39],
|
|
7
|
+
yellow: [33, 39],
|
|
8
|
+
};
|
|
9
|
+
export function colorSupported() {
|
|
10
|
+
if (process.env.NO_COLOR)
|
|
11
|
+
return false;
|
|
12
|
+
if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0')
|
|
13
|
+
return true;
|
|
14
|
+
return Boolean(process.stdout.isTTY);
|
|
15
|
+
}
|
|
16
|
+
export function painter(enabled = colorSupported()) {
|
|
17
|
+
if (!enabled)
|
|
18
|
+
return (_, text) => text;
|
|
19
|
+
return (style, text) => {
|
|
20
|
+
const [open, close] = CODES[style];
|
|
21
|
+
return `\u001b[${open}m${text}\u001b[${close}m`;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const CONFIG_FILE = "email-lint.config.json";
|
|
2
|
+
export type FailOn = 'error' | 'warning' | 'never';
|
|
3
|
+
export declare const FAIL_ON: FailOn[];
|
|
4
|
+
export interface Config {
|
|
5
|
+
files?: string[];
|
|
6
|
+
clients?: string[];
|
|
7
|
+
ignore?: string[];
|
|
8
|
+
strict?: boolean;
|
|
9
|
+
failOn?: FailOn;
|
|
10
|
+
}
|
|
11
|
+
export declare function loadConfig(path?: string): Promise<Config>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
export const CONFIG_FILE = 'email-lint.config.json';
|
|
3
|
+
export const FAIL_ON = ['error', 'warning', 'never'];
|
|
4
|
+
const KEYS = ['files', 'clients', 'ignore', 'strict', 'failOn'];
|
|
5
|
+
function stringList(value, key, path) {
|
|
6
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
|
|
7
|
+
throw new Error(`${path}: "${key}" must be an array of strings.`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
export async function loadConfig(path) {
|
|
12
|
+
const file = path ?? CONFIG_FILE;
|
|
13
|
+
let raw;
|
|
14
|
+
try {
|
|
15
|
+
raw = await readFile(file, 'utf8');
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (!path && error.code === 'ENOENT')
|
|
19
|
+
return {};
|
|
20
|
+
throw new Error(`Cannot read config ${file}: ${error.message}`);
|
|
21
|
+
}
|
|
22
|
+
let data;
|
|
23
|
+
try {
|
|
24
|
+
data = JSON.parse(raw);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
throw new Error(`${file} is not valid JSON: ${error.message}`);
|
|
28
|
+
}
|
|
29
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
30
|
+
throw new Error(`${file} must contain a JSON object.`);
|
|
31
|
+
}
|
|
32
|
+
const obj = data;
|
|
33
|
+
const unknown = Object.keys(obj).filter((k) => !KEYS.includes(k));
|
|
34
|
+
if (unknown.length) {
|
|
35
|
+
throw new Error(`${file}: unknown option ${unknown.join(', ')}. Allowed: ${KEYS.join(', ')}.`);
|
|
36
|
+
}
|
|
37
|
+
const config = {};
|
|
38
|
+
if (obj.files !== undefined)
|
|
39
|
+
config.files = stringList(obj.files, 'files', file);
|
|
40
|
+
if (obj.clients !== undefined)
|
|
41
|
+
config.clients = stringList(obj.clients, 'clients', file);
|
|
42
|
+
if (obj.ignore !== undefined)
|
|
43
|
+
config.ignore = stringList(obj.ignore, 'ignore', file);
|
|
44
|
+
if (obj.strict !== undefined) {
|
|
45
|
+
if (typeof obj.strict !== 'boolean')
|
|
46
|
+
throw new Error(`${file}: "strict" must be true or false.`);
|
|
47
|
+
config.strict = obj.strict;
|
|
48
|
+
}
|
|
49
|
+
if (obj.failOn !== undefined) {
|
|
50
|
+
if (!FAIL_ON.includes(obj.failOn)) {
|
|
51
|
+
throw new Error(`${file}: "failOn" must be one of ${FAIL_ON.join(', ')}.`);
|
|
52
|
+
}
|
|
53
|
+
config.failOn = obj.failOn;
|
|
54
|
+
}
|
|
55
|
+
return config;
|
|
56
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { glob, stat } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
const SKIP_DIRS = /(^|[\\/])(node_modules|vendor|\.git|coverage)([\\/]|$)/;
|
|
4
|
+
const toPosix = (p) => p.replaceAll('\\', '/');
|
|
5
|
+
export async function resolveFiles(patterns) {
|
|
6
|
+
const files = new Set();
|
|
7
|
+
for (const pattern of patterns) {
|
|
8
|
+
const info = await stat(pattern).catch(() => undefined);
|
|
9
|
+
if (info?.isFile()) {
|
|
10
|
+
files.add(pattern);
|
|
11
|
+
continue;
|
|
12
|
+
}
|
|
13
|
+
const source = info?.isDirectory()
|
|
14
|
+
? `${toPosix(pattern).replace(/\/+$/, '')}/**/*.{html,htm}`
|
|
15
|
+
: toPosix(pattern);
|
|
16
|
+
for await (const file of glob(source, { exclude: (f) => SKIP_DIRS.test(f) })) {
|
|
17
|
+
files.add(file);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return [...files].sort();
|
|
21
|
+
}
|
|
22
|
+
export async function findCandidates(cwd = '.') {
|
|
23
|
+
const byDir = new Map();
|
|
24
|
+
for await (const file of glob('**/*.{html,htm}', { cwd, exclude: (f) => SKIP_DIRS.test(f) })) {
|
|
25
|
+
const dir = toPosix(dirname(file));
|
|
26
|
+
byDir.set(dir, (byDir.get(dir) ?? 0) + 1);
|
|
27
|
+
}
|
|
28
|
+
const candidates = [...byDir].map(([dir, count]) => ({
|
|
29
|
+
pattern: dir,
|
|
30
|
+
label: dir === '.' ? './' : `${dir}/`,
|
|
31
|
+
count,
|
|
32
|
+
}));
|
|
33
|
+
let blade = 0;
|
|
34
|
+
for await (const _ of glob('resources/views/react-email/**/*.blade.php', { cwd }))
|
|
35
|
+
blade++;
|
|
36
|
+
if (blade) {
|
|
37
|
+
candidates.push({
|
|
38
|
+
pattern: 'resources/views/react-email/**/*.blade.php',
|
|
39
|
+
label: 'resources/views/react-email/ (laravel-react-email build)',
|
|
40
|
+
count: blade,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return candidates.sort((a, b) => b.count - a.count || a.pattern.localeCompare(b.pattern));
|
|
44
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ClientSupport, Status } from '../core/clients.js';
|
|
2
|
+
import type { Issue, LintResult } from '../core/lint.js';
|
|
3
|
+
import { type Paint } from './colors.js';
|
|
4
|
+
export interface FileResult extends LintResult {
|
|
5
|
+
file: string;
|
|
6
|
+
}
|
|
7
|
+
export type Format = 'text' | 'json' | 'markdown' | 'github';
|
|
8
|
+
export declare const FORMATS: Format[];
|
|
9
|
+
export declare function groupClients(clients: ClientSupport[], status: Status): string;
|
|
10
|
+
export declare function hasFindings(result: FileResult): boolean;
|
|
11
|
+
export declare function summary(results: FileResult[]): string;
|
|
12
|
+
export declare function fileSummary(result: FileResult): string;
|
|
13
|
+
export declare function formatIssue(issue: Issue, paint?: Paint, indent?: string): string[];
|
|
14
|
+
export interface TextOptions {
|
|
15
|
+
verbose?: boolean;
|
|
16
|
+
paint?: Paint;
|
|
17
|
+
}
|
|
18
|
+
export declare function formatText(results: FileResult[], options?: TextOptions): string;
|
|
19
|
+
export declare function formatMarkdown(results: FileResult[]): string;
|
|
20
|
+
export declare function formatGithub(results: FileResult[]): string;
|
|
21
|
+
export declare function render(results: FileResult[], format: Format, options?: TextOptions): string;
|
|
22
|
+
export declare function onlyErrors(results: FileResult[]): FileResult[];
|
|
23
|
+
export declare function formatFromPath(path: string): Format;
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { painter } from './colors.js';
|
|
2
|
+
export const FORMATS = ['text', 'json', 'markdown', 'github'];
|
|
3
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
4
|
+
function clientGroups(clients, status) {
|
|
5
|
+
const byFamily = new Map();
|
|
6
|
+
for (const c of clients) {
|
|
7
|
+
if (c.status !== status)
|
|
8
|
+
continue;
|
|
9
|
+
byFamily.set(c.familyName, [...(byFamily.get(c.familyName) ?? []), c.platformName]);
|
|
10
|
+
}
|
|
11
|
+
return [...byFamily].map(([family, platforms]) => `${family} (${platforms.join(', ')})`);
|
|
12
|
+
}
|
|
13
|
+
export function groupClients(clients, status) {
|
|
14
|
+
return clientGroups(clients, status).join(', ');
|
|
15
|
+
}
|
|
16
|
+
export function hasFindings(result) {
|
|
17
|
+
return result.issues.length > 0 || result.parseErrors.length > 0;
|
|
18
|
+
}
|
|
19
|
+
export function summary(results) {
|
|
20
|
+
const errors = results.reduce((n, r) => n + r.errors, 0);
|
|
21
|
+
const warnings = results.reduce((n, r) => n + r.warnings, 0);
|
|
22
|
+
if (!errors && !warnings)
|
|
23
|
+
return `No issues in ${plural(results.length, 'file')}.`;
|
|
24
|
+
const affected = results.filter(hasFindings).length;
|
|
25
|
+
return `${plural(errors, 'error')}, ${plural(warnings, 'warning')} in ${affected} of ${plural(results.length, 'file')}.`;
|
|
26
|
+
}
|
|
27
|
+
export function fileSummary(result) {
|
|
28
|
+
if (!hasFindings(result))
|
|
29
|
+
return 'no issues';
|
|
30
|
+
const parts = [plural(result.errors, 'error'), plural(result.warnings, 'warning')];
|
|
31
|
+
if (result.parseErrors.length)
|
|
32
|
+
parts.push(plural(result.parseErrors.length, 'parse error'));
|
|
33
|
+
return parts.join(', ');
|
|
34
|
+
}
|
|
35
|
+
export function formatIssue(issue, paint = painter(), indent = ' ') {
|
|
36
|
+
const level = issue.level === 'error' ? paint('red', 'error ') : paint('yellow', 'warning');
|
|
37
|
+
const pad = `${indent} `;
|
|
38
|
+
const out = [
|
|
39
|
+
`${indent}line ${issue.lines[0]} ${level} ${paint('bold', issue.title)} ${paint('dim', `(${issue.slug})`)}`,
|
|
40
|
+
];
|
|
41
|
+
const unsupported = groupClients(issue.clients, 'unsupported');
|
|
42
|
+
const partial = groupClients(issue.clients, 'partial');
|
|
43
|
+
if (unsupported)
|
|
44
|
+
out.push(`${pad}unsupported: ${unsupported}`);
|
|
45
|
+
if (partial)
|
|
46
|
+
out.push(`${pad}partial: ${partial}`);
|
|
47
|
+
for (const note of new Set(issue.clients.flatMap((c) => c.notes))) {
|
|
48
|
+
out.push(paint('dim', `${pad}note: ${note}`));
|
|
49
|
+
}
|
|
50
|
+
const rest = issue.lines.slice(1);
|
|
51
|
+
if (rest.length)
|
|
52
|
+
out.push(`${pad}also on ${rest.length === 1 ? 'line' : 'lines'} ${rest.join(', ')}`);
|
|
53
|
+
out.push(paint('dim', `${pad}${issue.url}`));
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
function compactLines(result, paint) {
|
|
57
|
+
const rows = [
|
|
58
|
+
...result.parseErrors.map((e) => ({
|
|
59
|
+
line: String(e.line),
|
|
60
|
+
level: paint('red', 'parse '),
|
|
61
|
+
title: e.message,
|
|
62
|
+
groups: [],
|
|
63
|
+
slug: '',
|
|
64
|
+
})),
|
|
65
|
+
...result.issues.map((issue) => ({
|
|
66
|
+
line: issue.lines.length > 1 ? `${issue.lines[0]} +${issue.lines.length - 1}` : String(issue.lines[0]),
|
|
67
|
+
level: issue.level === 'error' ? paint('red', 'error ') : paint('yellow', 'warning'),
|
|
68
|
+
title: issue.title,
|
|
69
|
+
groups: clientGroups(issue.clients, issue.level === 'error' ? 'unsupported' : 'partial'),
|
|
70
|
+
slug: issue.slug,
|
|
71
|
+
})),
|
|
72
|
+
];
|
|
73
|
+
const lineWidth = Math.max(...rows.map((r) => r.line.length));
|
|
74
|
+
const titleWidth = Math.min(28, Math.max(...rows.map((r) => r.title.length)));
|
|
75
|
+
const indent = ' '.repeat(2 + lineWidth + 2 + 7 + 2 + titleWidth + 2);
|
|
76
|
+
const room = Math.max(30, terminalWidth() - indent.length);
|
|
77
|
+
return rows.map((r) => {
|
|
78
|
+
const head = ` ${r.line.padStart(lineWidth)} ${r.level} ${paint('bold', r.title.padEnd(titleWidth))}`;
|
|
79
|
+
const lines = wrapGroups(r.groups, room);
|
|
80
|
+
if (r.slug) {
|
|
81
|
+
const last = lines.length - 1;
|
|
82
|
+
if (last >= 0 && lines[last].length + 2 + r.slug.length <= room) {
|
|
83
|
+
lines[last] += ` ${paint('dim', r.slug)}`;
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
lines.push(paint('dim', r.slug));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return lines.length ? `${head} ${lines.join(`\n${indent}`)}` : head;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function terminalWidth() {
|
|
93
|
+
return Number(process.env.COLUMNS) || process.stdout.columns || 100;
|
|
94
|
+
}
|
|
95
|
+
function wrapGroups(groups, width) {
|
|
96
|
+
const lines = [];
|
|
97
|
+
let current = '';
|
|
98
|
+
for (const group of groups) {
|
|
99
|
+
const next = current ? `${current}, ${group}` : group;
|
|
100
|
+
if (current && next.length > width) {
|
|
101
|
+
lines.push(`${current},`);
|
|
102
|
+
current = group;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
current = next;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (current)
|
|
109
|
+
lines.push(current);
|
|
110
|
+
return lines;
|
|
111
|
+
}
|
|
112
|
+
export function formatText(results, options = {}) {
|
|
113
|
+
const paint = options.paint ?? painter();
|
|
114
|
+
const out = [];
|
|
115
|
+
for (const result of results.filter(hasFindings)) {
|
|
116
|
+
out.push(paint('underline', result.file));
|
|
117
|
+
if (options.verbose) {
|
|
118
|
+
for (const e of result.parseErrors)
|
|
119
|
+
out.push(` line ${e.line} ${paint('red', 'parse')} ${e.message}`);
|
|
120
|
+
for (const issue of result.issues)
|
|
121
|
+
out.push(...formatIssue(issue, paint));
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
out.push(...compactLines(result, paint));
|
|
125
|
+
}
|
|
126
|
+
out.push('');
|
|
127
|
+
}
|
|
128
|
+
const found = results.some((r) => r.issues.length);
|
|
129
|
+
out.push(found ? summary(results) : paint('green', summary(results)));
|
|
130
|
+
if (found && !options.verbose) {
|
|
131
|
+
out.push(paint('dim', 'Errors list clients without support, warnings list partial support. Add --verbose for notes and links.'));
|
|
132
|
+
}
|
|
133
|
+
return out.join('\n');
|
|
134
|
+
}
|
|
135
|
+
const cell = (text) => text.replaceAll('|', '\\|').replace(/\s*\n\s*/g, ' ');
|
|
136
|
+
export function formatMarkdown(results) {
|
|
137
|
+
const out = ['# email-lint report', '', summary(results), ''];
|
|
138
|
+
for (const result of results.filter(hasFindings)) {
|
|
139
|
+
out.push(`## ${result.file}`, '');
|
|
140
|
+
for (const e of result.parseErrors)
|
|
141
|
+
out.push(`- Line ${e.line}: ${cell(e.message)}`);
|
|
142
|
+
if (result.parseErrors.length)
|
|
143
|
+
out.push('');
|
|
144
|
+
if (result.issues.length) {
|
|
145
|
+
out.push('| Line | Level | Feature | Unsupported | Partial |', '| --- | --- | --- | --- | --- |');
|
|
146
|
+
for (const issue of result.issues) {
|
|
147
|
+
out.push(`| ${issue.lines.join(', ')} | ${issue.level} | [${cell(issue.title)}](${issue.url}) | ${cell(groupClients(issue.clients, 'unsupported'))} | ${cell(groupClients(issue.clients, 'partial'))} |`);
|
|
148
|
+
}
|
|
149
|
+
out.push('');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return out.join('\n').trimEnd() + '\n';
|
|
153
|
+
}
|
|
154
|
+
// Workflow command escaping: https://docs.github.com/actions/reference/workflow-commands-for-github-actions
|
|
155
|
+
const escapeData = (s) => s.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
|
156
|
+
const escapeProperty = (s) => escapeData(s).replace(/:/g, '%3A').replace(/,/g, '%2C');
|
|
157
|
+
export function formatGithub(results) {
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const result of results) {
|
|
160
|
+
const file = escapeProperty(result.file.replaceAll('\\', '/'));
|
|
161
|
+
for (const e of result.parseErrors) {
|
|
162
|
+
out.push(`::error file=${file},line=${e.line},title=email-lint::${escapeData(e.message)}`);
|
|
163
|
+
}
|
|
164
|
+
for (const issue of result.issues) {
|
|
165
|
+
const unsupported = groupClients(issue.clients, 'unsupported');
|
|
166
|
+
const partial = groupClients(issue.clients, 'partial');
|
|
167
|
+
const message = [
|
|
168
|
+
unsupported && `Not supported in ${unsupported}.`,
|
|
169
|
+
partial && `Partial support in ${partial}.`,
|
|
170
|
+
issue.url,
|
|
171
|
+
]
|
|
172
|
+
.filter(Boolean)
|
|
173
|
+
.join(' ');
|
|
174
|
+
const title = escapeProperty(`email-lint: ${issue.title}`);
|
|
175
|
+
for (const line of issue.lines) {
|
|
176
|
+
out.push(`::${issue.level} file=${file},line=${line},title=${title}::${escapeData(message)}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
out.push(summary(results));
|
|
181
|
+
return out.join('\n');
|
|
182
|
+
}
|
|
183
|
+
export function render(results, format, options = {}) {
|
|
184
|
+
if (format === 'json')
|
|
185
|
+
return JSON.stringify(results, null, 2);
|
|
186
|
+
if (format === 'markdown')
|
|
187
|
+
return formatMarkdown(results);
|
|
188
|
+
if (format === 'github')
|
|
189
|
+
return formatGithub(results);
|
|
190
|
+
return formatText(results, options);
|
|
191
|
+
}
|
|
192
|
+
export function onlyErrors(results) {
|
|
193
|
+
return results.map((r) => {
|
|
194
|
+
const issues = r.issues.filter((i) => i.level === 'error');
|
|
195
|
+
return { ...r, issues, warnings: 0 };
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
export function formatFromPath(path) {
|
|
199
|
+
if (/\.json$/i.test(path))
|
|
200
|
+
return 'json';
|
|
201
|
+
if (/\.(md|markdown)$/i.test(path))
|
|
202
|
+
return 'markdown';
|
|
203
|
+
return 'text';
|
|
204
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runInteractive(): Promise<number>;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { access, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import * as p from '@clack/prompts';
|
|
3
|
+
import { DEFAULT_CLIENTS } from '../core/clients.js';
|
|
4
|
+
import { loadDataset } from '../core/data.js';
|
|
5
|
+
import { lint } from '../core/lint.js';
|
|
6
|
+
import { painter } from './colors.js';
|
|
7
|
+
import { CONFIG_FILE } from './config.js';
|
|
8
|
+
import { findCandidates, resolveFiles } from './files.js';
|
|
9
|
+
import { fileSummary, formatIssue, hasFindings, render, summary, } from './format.js';
|
|
10
|
+
const POPULAR = ['gmail', 'outlook', 'apple-mail', 'yahoo', 'samsung-email', 'thunderbird'];
|
|
11
|
+
const MANUAL = '<manual>';
|
|
12
|
+
function answer(value) {
|
|
13
|
+
if (p.isCancel(value)) {
|
|
14
|
+
p.cancel('Cancelled.');
|
|
15
|
+
process.exit(130);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
async function askForFiles() {
|
|
20
|
+
const spin = p.spinner();
|
|
21
|
+
spin.start('Looking for email templates');
|
|
22
|
+
const candidates = await findCandidates();
|
|
23
|
+
spin.stop(candidates.length
|
|
24
|
+
? `Found HTML in ${candidates.length} ${candidates.length === 1 ? 'folder' : 'folders'}`
|
|
25
|
+
: 'No HTML files found in this folder');
|
|
26
|
+
while (true) {
|
|
27
|
+
let pattern = MANUAL;
|
|
28
|
+
if (candidates.length) {
|
|
29
|
+
pattern = answer(await p.select({
|
|
30
|
+
message: 'Which emails should be checked?',
|
|
31
|
+
options: [
|
|
32
|
+
...candidates.slice(0, 8).map((c) => ({
|
|
33
|
+
value: c.pattern,
|
|
34
|
+
label: c.label,
|
|
35
|
+
hint: `${c.count} ${c.count === 1 ? 'file' : 'files'}`,
|
|
36
|
+
})),
|
|
37
|
+
{ value: MANUAL, label: 'Enter a path or glob' },
|
|
38
|
+
],
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
if (pattern === MANUAL) {
|
|
42
|
+
pattern = answer(await p.text({
|
|
43
|
+
message: 'Path, folder or glob',
|
|
44
|
+
placeholder: 'emails/**/*.html',
|
|
45
|
+
validate: (v) => (v?.trim() ? undefined : 'Enter a path'),
|
|
46
|
+
})).trim();
|
|
47
|
+
}
|
|
48
|
+
const files = await resolveFiles([pattern]);
|
|
49
|
+
if (files.length)
|
|
50
|
+
return { pattern, files };
|
|
51
|
+
p.log.warn(`No HTML files match "${pattern}". Try another path.`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function askForClients() {
|
|
55
|
+
const { family } = loadDataset().nicenames;
|
|
56
|
+
const ordered = [...POPULAR, ...Object.keys(family).filter((f) => !POPULAR.includes(f))];
|
|
57
|
+
return answer(await p.multiselect({
|
|
58
|
+
message: 'Which email clients matter to you?',
|
|
59
|
+
options: ordered.map((f) => ({ value: f, label: family[f] ?? f })),
|
|
60
|
+
initialValues: DEFAULT_CLIENTS,
|
|
61
|
+
required: true,
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
function showDetails(result) {
|
|
65
|
+
const paint = painter();
|
|
66
|
+
const lines = [
|
|
67
|
+
paint('underline', result.file),
|
|
68
|
+
'',
|
|
69
|
+
...result.parseErrors.map((e) => `line ${e.line} ${paint('red', 'parse')} ${e.message}`),
|
|
70
|
+
...result.issues.flatMap((issue) => [...formatIssue(issue, paint, ''), '']),
|
|
71
|
+
];
|
|
72
|
+
p.log.message(lines.join('\n').trimEnd());
|
|
73
|
+
}
|
|
74
|
+
async function saveReport(results) {
|
|
75
|
+
const format = answer(await p.select({
|
|
76
|
+
message: 'Report format',
|
|
77
|
+
options: [
|
|
78
|
+
{ value: 'markdown', label: 'Markdown', hint: 'for a pull request or an issue' },
|
|
79
|
+
{ value: 'json', label: 'JSON', hint: 'for scripts' },
|
|
80
|
+
{ value: 'text', label: 'Plain text' },
|
|
81
|
+
],
|
|
82
|
+
}));
|
|
83
|
+
const extension = { markdown: 'md', json: 'json', text: 'txt', github: 'txt' }[format];
|
|
84
|
+
const path = answer(await p.text({
|
|
85
|
+
message: 'Save as',
|
|
86
|
+
initialValue: `email-lint-report.${extension}`,
|
|
87
|
+
validate: (v) => (v?.trim() ? undefined : 'Enter a file name'),
|
|
88
|
+
})).trim();
|
|
89
|
+
await writeFile(path, render(results, format, { paint: painter(false), verbose: true }));
|
|
90
|
+
p.log.success(`Saved ${path}`);
|
|
91
|
+
}
|
|
92
|
+
async function saveConfig(pattern, clients) {
|
|
93
|
+
const exists = await access(CONFIG_FILE).then(() => true, () => false);
|
|
94
|
+
if (exists) {
|
|
95
|
+
const overwrite = answer(await p.confirm({ message: `${CONFIG_FILE} exists. Overwrite it?` }));
|
|
96
|
+
if (!overwrite)
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
await writeFile(CONFIG_FILE, `${JSON.stringify({ files: [pattern], clients }, null, 2)}\n`);
|
|
100
|
+
p.log.success(`Saved ${CONFIG_FILE}. Running email-lint with no arguments in CI now uses it.`);
|
|
101
|
+
}
|
|
102
|
+
function command(pattern, clients) {
|
|
103
|
+
const isDefault = clients.length === DEFAULT_CLIENTS.length && DEFAULT_CLIENTS.every((c) => clients.includes(c));
|
|
104
|
+
const quoted = /[\s*?{}]/.test(pattern) ? `"${pattern}"` : pattern;
|
|
105
|
+
return ['npx @mscode-pl/email-lint', quoted, ...(isDefault ? [] : [`--clients ${clients.join(',')}`])].join(' ');
|
|
106
|
+
}
|
|
107
|
+
export async function runInteractive() {
|
|
108
|
+
p.intro('email-lint');
|
|
109
|
+
const { pattern, files } = await askForFiles();
|
|
110
|
+
const clients = await askForClients();
|
|
111
|
+
const spin = p.spinner();
|
|
112
|
+
spin.start(`Checking ${files.length} ${files.length === 1 ? 'file' : 'files'}`);
|
|
113
|
+
const results = [];
|
|
114
|
+
for (const file of files) {
|
|
115
|
+
results.push({ file, ...lint(await readFile(file, 'utf8'), { clients }) });
|
|
116
|
+
}
|
|
117
|
+
spin.stop(summary(results));
|
|
118
|
+
const withFindings = results.filter(hasFindings);
|
|
119
|
+
if (withFindings.length) {
|
|
120
|
+
p.log.message(results.map((r) => `${r.file} ${fileSummary(r)}`).join('\n'));
|
|
121
|
+
}
|
|
122
|
+
while (true) {
|
|
123
|
+
const action = answer(await p.select({
|
|
124
|
+
message: 'What next?',
|
|
125
|
+
options: [
|
|
126
|
+
...(withFindings.length > 1 ? [{ value: 'file', label: 'Show details for one file' }] : []),
|
|
127
|
+
...(withFindings.length
|
|
128
|
+
? [{ value: 'all', label: withFindings.length > 1 ? 'Show details for all files' : 'Show details' }]
|
|
129
|
+
: []),
|
|
130
|
+
...(withFindings.length ? [{ value: 'report', label: 'Save the report to a file' }] : []),
|
|
131
|
+
{ value: 'config', label: `Save these settings to ${CONFIG_FILE}` },
|
|
132
|
+
{ value: 'done', label: 'Done' },
|
|
133
|
+
],
|
|
134
|
+
}));
|
|
135
|
+
if (action === 'done')
|
|
136
|
+
break;
|
|
137
|
+
if (action === 'all')
|
|
138
|
+
withFindings.forEach(showDetails);
|
|
139
|
+
if (action === 'report')
|
|
140
|
+
await saveReport(results);
|
|
141
|
+
if (action === 'config')
|
|
142
|
+
await saveConfig(pattern, clients);
|
|
143
|
+
if (action === 'file') {
|
|
144
|
+
const file = answer(await p.select({
|
|
145
|
+
message: 'Which file?',
|
|
146
|
+
options: withFindings.map((r) => ({ value: r.file, label: r.file, hint: fileSummary(r) })),
|
|
147
|
+
}));
|
|
148
|
+
showDetails(withFindings.find((r) => r.file === file));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
p.note(command(pattern, clients), 'The same check as one command');
|
|
152
|
+
p.outro('Done');
|
|
153
|
+
return 0;
|
|
154
|
+
}
|