@emailens/engine 0.8.1 → 0.8.3

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/README.md CHANGED
@@ -1,9 +1,16 @@
1
1
  # @emailens/engine
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/@emailens/engine)](https://www.npmjs.com/package/@emailens/engine)
4
+ [![license](https://img.shields.io/npm/l/@emailens/engine)](./LICENSE)
5
+ [![tests](https://img.shields.io/badge/tests-574%20passing-brightgreen)]()
6
+ [![node](https://img.shields.io/node/v/@emailens/engine)](https://nodejs.org/)
7
+
3
8
  **Your email looks perfect in Apple Mail. Gmail strips half the CSS. Outlook renders it in Word.**
4
9
 
5
10
  `@emailens/engine` analyzes your HTML against 250+ CSS properties across 12 email clients, scores compatibility, and shows you exactly what to fix — before you hit send.
6
11
 
12
+ > **[emailens.dev](https://emailens.dev)** — Try the hosted version. Paste HTML, get a full audit in seconds.
13
+
7
14
  ## Quick Start
8
15
 
9
16
  ```bash
@@ -42,6 +49,8 @@ console.log(report.accessibility.score); // 88
42
49
  console.log(report.size.clipped); // false (under Gmail's 102KB limit)
43
50
  ```
44
51
 
52
+ ## Score too low? Fix it
53
+
45
54
  Score too low? Fix it automatically:
46
55
 
47
56
  ```typescript
@@ -69,6 +78,8 @@ const { code } = await generateAiFix({
69
78
 
70
79
  ## What It Catches
71
80
 
81
+ 8 analysis engines, one `auditEmail()` call.
82
+
72
83
  - **CSS compatibility** — 250+ properties tested across 12 email clients, with fix snippets and AI-powered auto-fix
73
84
  - **Spam scoring** — 45+ signals modeled after SpamAssassin, CAN-SPAM, and GDPR
74
85
  - **Accessibility** — WCAG contrast ratios, alt text, semantic structure, heading hierarchy
@@ -78,475 +89,35 @@ const { code } = await generateAiFix({
78
89
  - **Domain authentication** — SPF, DKIM, DMARC, MX, and BIMI DNS record validation
79
90
  - **Template variables** — unresolved merge tags across 6 template systems (Handlebars, ERB, Mailchimp, etc.)
80
91
 
81
- ## API Reference
82
-
83
- ### `auditEmail(html: string, options?: AuditOptions): AuditReport`
84
-
85
- **Unified API** — runs all 8 email analysis checks in a single call. Returns compatibility warnings + scores, spam analysis, link validation, accessibility audit, image analysis, inbox preview extraction, size checking, and template variable detection.
86
-
87
- Internally parses the HTML once and shares the DOM across all analyzers.
88
-
89
- ```typescript
90
- import { auditEmail } from "@emailens/engine";
91
-
92
- const report = auditEmail(html, {
93
- framework: "jsx", // attach framework-specific fix snippets
94
- spam: { emailType: "transactional" }, // skip unsubscribe check
95
- skip: ["images"], // skip specific checks
96
- });
97
-
98
- // report.compatibility.warnings — CSSWarning[]
99
- // report.compatibility.scores — Record<string, ClientScore>
100
- // report.spam — SpamReport
101
- // report.links — LinkReport
102
- // report.accessibility — AccessibilityReport
103
- // report.images — ImageReport
104
- // report.inboxPreview — InboxPreview
105
- // report.size — SizeReport
106
- // report.templateVariables — TemplateReport
107
- ```
108
-
109
- **`AuditOptions`:**
110
- - `framework?: "jsx" | "mjml" | "maizzle"` — attach framework-specific fix snippets
111
- - `spam?: SpamAnalysisOptions` — options for spam analysis
112
- - `skip?: Array<"spam" | "links" | "accessibility" | "images" | "compatibility" | "inboxPreview" | "size" | "templateVariables">` — skip specific checks
113
-
114
- ---
115
-
116
- ### `createSession(html: string, options?: CreateSessionOptions): EmailSession`
117
-
118
- **Session API** — pre-parses the HTML once and exposes all analysis methods on the shared DOM. Use this when you need to call multiple analysis functions on the same HTML to avoid redundant parsing.
119
-
120
- ```typescript
121
- import { createSession } from "@emailens/engine";
122
-
123
- const session = createSession(html, { framework: "jsx" });
124
-
125
- // All analysis methods share a single DOM parse:
126
- const warnings = session.analyze();
127
- const scores = session.score(warnings);
128
- const spam = session.analyzeSpam();
129
- const links = session.validateLinks();
130
- const a11y = session.checkAccessibility();
131
- const images = session.analyzeImages();
132
- const preview = session.extractInboxPreview();
133
- const size = session.checkSize();
134
- const templates = session.checkTemplateVariables();
135
-
136
- // Or run everything at once:
137
- const report = session.audit();
138
-
139
- // Transforms and dark mode still work (parse internally per client):
140
- const transforms = session.transformForAllClients();
141
- const darkMode = session.simulateDarkMode("gmail-web");
142
- ```
143
-
144
- **`CreateSessionOptions`:**
145
- - `framework?: "jsx" | "mjml" | "maizzle"` — framework for fix snippets (applies to all session methods)
146
-
147
- **`EmailSession` methods:**
148
-
149
- | Method | Shares DOM | Description |
150
- |---|---|---|
151
- | `audit(options?)` | Yes | Run all checks (equivalent to `auditEmail`) |
152
- | `analyze()` | Yes | CSS compatibility warnings |
153
- | `score(warnings)` | — | Generate per-client scores |
154
- | `analyzeSpam(options?)` | Yes | Spam indicator analysis |
155
- | `validateLinks()` | Yes | Link validation |
156
- | `checkAccessibility()` | Yes | Accessibility audit |
157
- | `analyzeImages()` | Yes | Image analysis |
158
- | `extractInboxPreview()` | Yes | Subject line and preheader extraction |
159
- | `checkSize()` | Yes | Gmail clipping size check |
160
- | `checkTemplateVariables()` | Yes | Unresolved template variable detection |
161
- | `checkDeliverability(domain)` | — | DNS deliverability check (async, SPF/DKIM/DMARC/MX/BIMI) |
162
- | `transformForClient(clientId)` | No | Transform for one client |
163
- | `transformForAllClients()` | No | Transform for all 12 clients |
164
- | `simulateDarkMode(clientId)` | No | Dark mode simulation |
165
-
166
- **When to use sessions vs standalone functions:**
167
-
168
- - **Multiple analysis calls on the same HTML** → use `createSession()` to avoid redundant parsing
169
- - **Single analysis call** → use standalone functions (`auditEmail`, `analyzeEmail`, etc.)
170
- - **Server-side batch processing** → use `createSession()` per email for best throughput
171
-
172
- ---
173
-
174
- ### `analyzeEmail(html: string, framework?: Framework): CSSWarning[]`
175
-
176
- Analyzes an HTML email and returns CSS compatibility warnings for all 12 email clients. Detects `<style>`, `<link>`, `<svg>`, `<video>`, `<form>`, inline CSS properties, `@font-face`, `@media` queries, gradients, flexbox/grid, and more.
177
-
178
- The optional `framework` parameter controls which fix snippets are attached to warnings. Analysis always runs on compiled HTML.
179
-
180
- ```typescript
181
- const warnings = analyzeEmail(html); // Plain HTML
182
- const warnings = analyzeEmail(html, "jsx"); // React Email fixes
183
- const warnings = analyzeEmail(html, "mjml"); // MJML fixes
184
- ```
185
-
186
- ### `generateCompatibilityScore(warnings): Record<string, ClientScore>`
187
-
188
- Generates a 0–100 compatibility score per email client. Formula: `100 - (errors × 15) - (warnings × 5) - (info × 1)`.
189
-
190
- ### `warningsForClient(warnings, clientId): CSSWarning[]`
191
-
192
- Filter warnings for a specific client.
193
-
194
- ### `errorWarnings(warnings): CSSWarning[]`
195
-
196
- Get only error-severity warnings.
197
-
198
- ### `structuralWarnings(warnings): CSSWarning[]`
199
-
200
- Get only warnings that require HTML restructuring (`fixType: "structural"`).
201
-
202
- ---
203
-
204
- ### `analyzeSpam(html: string, options?: SpamAnalysisOptions): SpamReport`
205
-
206
- Analyzes an HTML email for spam scoring issues. Returns a 0–100 score (100 = clean) and an array of issues. Uses heuristic rules modeled after SpamAssassin, CAN-SPAM, and GDPR.
207
-
208
- > **Note:** Spam scoring heuristics — not a real spam filter. This checks for common anti-patterns that trigger spam filters but cannot predict actual inbox placement. For real spam testing, use the `checkSpamAssassin()` integration or a dedicated service.
209
-
210
- ```typescript
211
- import { analyzeSpam } from "@emailens/engine";
212
-
213
- const report = analyzeSpam(html, {
214
- emailType: "transactional", // skip unsubscribe check
215
- listUnsubscribeHeader: "...", // satisfies unsubscribe requirement
216
- });
217
- // { score: 95, level: "low", issues: [...] }
218
- ```
219
-
220
- **Checks:** caps ratio, excessive punctuation, spam trigger phrases, missing unsubscribe link (with transactional email exemption), hidden text, URL shorteners, image-to-text ratio, deceptive links (with ESP tracking domain allowlist), all-caps subject.
221
-
222
- ### `validateLinks(html: string): LinkReport`
223
-
224
- Static analysis of all links in an HTML email. No network requests.
225
-
226
- ```typescript
227
- import { validateLinks } from "@emailens/engine";
228
-
229
- const report = validateLinks(html);
230
- // { totalLinks: 12, issues: [...], breakdown: { https: 10, http: 1, mailto: 1, ... } }
231
- ```
232
-
233
- **Checks:** empty/placeholder hrefs, `javascript:` protocol, insecure HTTP, generic link text, missing accessible names, empty mailto/tel, very long URLs, duplicate links.
234
-
235
- ### `checkAccessibility(html: string): AccessibilityReport`
236
-
237
- Audits an HTML email for accessibility issues. Returns a 0–100 score and detailed issues.
238
-
239
- ```typescript
240
- import { checkAccessibility } from "@emailens/engine";
241
-
242
- const report = checkAccessibility(html);
243
- // { score: 88, issues: [...] }
244
- ```
245
-
246
- **Checks:** missing `lang` attribute, missing `<title>`, image alt text, link accessibility, layout table roles, small text, color contrast (WCAG 2.1), heading hierarchy.
247
-
248
- ### `analyzeImages(html: string): ImageReport`
249
-
250
- Analyzes images for email best practices.
251
-
252
- ```typescript
253
- import { analyzeImages } from "@emailens/engine";
254
-
255
- const report = analyzeImages(html);
256
- // { total: 5, totalDataUriBytes: 0, issues: [...], images: [...] }
257
- ```
258
-
259
- **Checks:** missing dimensions, oversized data URIs, missing alt, WebP/SVG format, missing `display:block`, tracking pixels, high image count.
260
-
261
- ### `extractInboxPreview(html: string): InboxPreview`
262
-
263
- Extracts subject line (from `<title>`) and preheader text from the email HTML. Returns per-client truncation data showing how subject and preheader will appear across 8 email clients.
264
-
265
- ```typescript
266
- import { extractInboxPreview } from "@emailens/engine";
267
-
268
- const preview = extractInboxPreview(html);
269
- // { subject: "Newsletter", preheader: "This week's highlights...",
270
- // subjectLength: 10, preheaderLength: 28,
271
- // truncation: [...], issues: [...] }
272
- ```
273
-
274
- **Checks:** missing `<title>`, subject too long, missing preheader, preheader too short/long, `&zwnj;&nbsp;` padding hack, emoji in subject.
275
-
276
- ### `checkSize(html: string): SizeReport`
277
-
278
- Checks email HTML byte size for Gmail clipping issues. Gmail clips messages larger than ~102KB, hiding content behind a "View entire message" link.
279
-
280
- ```typescript
281
- import { checkSize } from "@emailens/engine";
282
-
283
- const report = checkSize(html);
284
- // { htmlBytes: 45230, humanSize: "44.2 KB", clipped: false, issues: [] }
285
- ```
286
-
287
- **Checks:** Gmail clipping threshold (102KB), approaching clip threshold warning (90KB).
288
-
289
- ### `checkTemplateVariables(html: string): TemplateReport`
290
-
291
- Scans email HTML for unresolved template/merge variables in text content and key attributes (`href`, `src`, `alt`).
292
-
293
- ```typescript
294
- import { checkTemplateVariables } from "@emailens/engine";
295
-
296
- const report = checkTemplateVariables(html);
297
- // { unresolvedCount: 0, issues: [] }
298
- ```
299
-
300
- **Detects:** `{{var}}` (Handlebars/Mustache), `${var}` (ES template literals), `<%= %>` (ERB/EJS), `*|TAG|*` (Mailchimp), `%%tag%%` (Salesforce), `{merge_field}` (single-brace).
301
-
302
- ---
303
-
304
- ### `checkDeliverability(domain, options?): Promise<DeliverabilityReport>`
305
-
306
- Validates email deliverability for a domain by checking MX, SPF, DKIM, DMARC, and BIMI DNS records. All DNS queries have a 5-second timeout. No external dependencies — uses `node:dns/promises`.
307
-
308
- ```typescript
309
- import { checkDeliverability } from "@emailens/engine";
310
-
311
- const report = await checkDeliverability("example.com");
312
- console.log(report.score); // 0-100
313
- console.log(report.checks); // individual check results
314
- console.log(report.issues); // actionable issues
315
- ```
316
-
317
- **Checks:**
318
- - **MX** — domain can receive email
319
- - **SPF** — authorized senders (`v=spf1`), flags dangerous `+all`
320
- - **DKIM** — probes 15 common selectors (`google`, `selector1`, `default`, `dkim`, etc.)
321
- - **DMARC** — policy enforcement (`v=DMARC1`), warns on `p=none`
322
- - **BIMI** — brand indicator (optional, nice-to-have)
323
-
324
- Also available as a session method: `session.checkDeliverability("example.com")`.
325
-
326
- > **Note:** This is standalone async — not wired into the synchronous `auditEmail()` pipeline.
327
-
328
- ### `checkSpamAssassin(input, options?): Promise<SpamAssassinResult | null>`
92
+ ## Installation
329
93
 
330
- Opt-in integration with a local SpamAssassin installation. Shells out to `spamc` (daemon) or `spamassassin` (standalone) via `execFile`. Returns `null` if SpamAssassin is not installed.
331
-
332
- ```typescript
333
- import { checkSpamAssassin } from "@emailens/engine";
334
-
335
- const result = await checkSpamAssassin(rawRfc2822Message);
336
- if (result) {
337
- console.log(result.score); // e.g. 3.2
338
- console.log(result.isSpam); // true if score >= threshold
339
- console.log(result.rules); // matched SpamAssassin rules
340
- }
341
- ```
342
-
343
- > **Note:** Requires a full RFC 2822 message (headers + body), not just HTML.
344
-
345
- ---
346
-
347
- ### `transformForClient(html, clientId, framework?): TransformResult`
348
-
349
- Transforms HTML for a specific email client — strips unsupported CSS, inlines `<style>` blocks (for Gmail), removes unsupported elements.
350
-
351
- ### `transformForAllClients(html, framework?): TransformResult[]`
352
-
353
- Transforms HTML for all 12 email clients at once.
354
-
355
- ### `simulateDarkMode(html, clientId): { html, warnings }`
356
-
357
- Simulates how an email client applies dark mode using luminance-based color detection.
358
-
359
- - **Full inversion** (Gmail Android, Samsung Mail): inverts all light backgrounds and dark text
360
- - **Partial inversion** (Gmail Web, Apple Mail, Yahoo, Outlook.com, HEY, Superhuman): only inverts very light/dark colors
361
- - **No dark mode** (Outlook Windows, Thunderbird)
362
-
363
- ### `getCodeFix(property, clientId, framework?): CodeFix | undefined`
364
-
365
- Returns a paste-ready code fix for a CSS property + client combination. Fixes are tiered:
366
-
367
- 1. **Framework + client specific** (e.g., `border-radius` + Outlook + JSX → VML component)
368
- 2. **Framework specific** (e.g., `@font-face` + MJML → `<mj-font>`)
369
- 3. **Client specific** (e.g., `border-radius` + Outlook → VML roundrect)
370
- 4. **Generic HTML fallback**
371
-
372
- ### `diffResults(before, after): DiffResult[]`
373
-
374
- Compares two sets of analysis results to show what improved, regressed, or stayed the same.
375
-
376
- ---
377
-
378
- ## Compile Module
379
-
380
- Compile email templates from JSX, MJML, or Maizzle to HTML.
381
-
382
- ```typescript
383
- import { compile, detectFormat, CompileError } from "@emailens/engine/compile";
384
-
385
- // Auto-detect format and compile
386
- const format = detectFormat("email.tsx"); // "jsx"
387
- const html = await compile(source, format);
388
-
389
- // Or use specific compilers
390
- import { compileReactEmail, compileMjml, compileMaizzle } from "@emailens/engine/compile";
391
- ```
392
-
393
- ### `compile(source, format, filePath?): Promise<string>`
394
-
395
- Compile source to HTML based on format. Lazily imports per-format compilers.
396
-
397
- ### `compileReactEmail(source, options?): Promise<string>`
398
-
399
- Compile React Email JSX/TSX to HTML. Pipeline: validate → transpile (sucrase) → sandbox execute → render.
400
-
401
- ```typescript
402
- import { compileReactEmail } from "@emailens/engine/compile";
403
-
404
- const html = await compileReactEmail(jsxSource, {
405
- sandbox: "isolated-vm", // "vm" | "isolated-vm" | "quickjs"
406
- });
407
- ```
408
-
409
- **Sandbox strategies:**
410
- - `"isolated-vm"` (default) — Separate V8 isolate. True heap isolation. Requires `isolated-vm` native addon.
411
- - `"vm"` — `node:vm` with hardened globals. Fast, zero-dependency, but NOT a true security boundary. Suitable for CLI/local use.
412
- - `"quickjs"` — Validates code in WASM sandbox, then executes in `node:vm`. Security is equivalent to `"vm"`. No native addons needed.
413
-
414
- **Peer dependencies:** `sucrase`, `react`, `@react-email/components`, `@react-email/render`. Plus `isolated-vm` or `quickjs-emscripten` depending on sandbox strategy.
415
-
416
- ### `compileMjml(source): Promise<string>`
417
-
418
- Compile MJML to HTML. **Peer dependency:** `mjml`.
419
-
420
- ### `compileMaizzle(source): Promise<string>`
421
-
422
- Compile Maizzle template to HTML. **Peer dependency:** `@maizzle/framework`.
423
-
424
- **Security:** PostHTML file-system directives (`<extends>`, `<component>`, `<fetch>`, `<include>`, `<module>`, `<slot>`, `<fill>`, `<raw>`, `<block>`, `<yield>`) are rejected at validation time to prevent server-side file reads.
425
-
426
- ### `detectFormat(filePath): InputFormat`
427
-
428
- Auto-detect input format from file extension (`.tsx`/`.jsx` → `"jsx"`, `.mjml` → `"mjml"`, `.html` → `"html"`).
429
-
430
- ### `CompileError`
431
-
432
- Unified error class for all compilation failures. Available from both `@emailens/engine` and `@emailens/engine/compile`.
433
-
434
- ```typescript
435
- import { CompileError } from "@emailens/engine";
436
-
437
- try {
438
- await compile(source, "jsx");
439
- } catch (err) {
440
- if (err instanceof CompileError) {
441
- console.log(err.format); // "jsx" | "mjml" | "maizzle"
442
- console.log(err.phase); // "validation" | "transpile" | "execution" | "render" | "compile"
443
- }
444
- }
445
- ```
446
-
447
- ---
448
-
449
- ## Performance
450
-
451
- ### Shared DOM parsing
452
-
453
- The engine internally parses HTML using [Cheerio](https://cheerio.js.org/). For a typical 50–100KB email, each `cheerio.load()` call takes 5–15ms. Without optimization, calling multiple analysis functions on the same HTML would parse it repeatedly.
454
-
455
- **`auditEmail()`** parses the HTML once and shares the DOM across all 8 analyzers (compatibility, spam, links, accessibility, images, inbox preview, size, template variables). Previously each analyzer parsed independently — this eliminates ~80% of parsing overhead in the audit path.
456
-
457
- **`createSession()`** extends this optimization to any combination of calls. When you need to call `analyzeEmail()` + `analyzeSpam()` + `validateLinks()` + other checks on the same HTML, a session shares a single parse across all of them.
458
-
459
- ### Typical performance characteristics
460
-
461
- | Operation | Complexity | Notes |
462
- |---|---|---|
463
- | `auditEmail()` | 1 parse + 8 analyses | Shared DOM, most efficient for full reports |
464
- | `createSession()` | 1 parse upfront | Amortized across all subsequent analysis calls |
465
- | `analyzeEmail()` | 1 parse + CSS property scan | Scans `<style>` blocks + inline styles × 12 clients |
466
- | `transformForAllClients()` | 12 parses (1 per client) | Each client mutates its own DOM copy |
467
- | `simulateDarkMode()` | 1 parse per call | Mutates DOM for color inversion |
468
-
469
- ### Optimization tips for consumers
470
-
471
- ```typescript
472
- // Instead of this (6 separate HTML parses):
473
- const warnings = analyzeEmail(html, "jsx");
474
- const scores = generateCompatibilityScore(warnings);
475
- const spam = analyzeSpam(html);
476
- const links = validateLinks(html);
477
- const a11y = checkAccessibility(html);
478
- const images = analyzeImages(html);
479
-
480
- // Do this (1 HTML parse):
481
- const report = auditEmail(html, { framework: "jsx" });
482
-
483
- // Or for selective analysis (1 HTML parse):
484
- const session = createSession(html, { framework: "jsx" });
485
- const warnings = session.analyze();
486
- const scores = session.score(warnings);
487
- const spam = session.analyzeSpam();
488
- // ... pick only what you need
489
- ```
490
-
491
- ---
492
-
493
- ## Security Considerations
494
-
495
- ### Input Size Limits
496
-
497
- All public functions enforce a 2MB (`MAX_HTML_SIZE`) input limit. Inputs exceeding this limit throw immediately. The limit is exported so consumers can check before calling:
498
-
499
- ```typescript
500
- import { MAX_HTML_SIZE } from "@emailens/engine";
501
- if (html.length > MAX_HTML_SIZE) {
502
- // handle oversized input
503
- }
504
- ```
505
-
506
- ### Compile Module Security
507
-
508
- - **React Email JSX**: User code runs in a sandboxed environment. The `"isolated-vm"` strategy provides true heap isolation. The `"vm"` and `"quickjs"` strategies use `node:vm` which is NOT a security boundary — suitable for CLI use where users run their own code. For server deployments accepting untrusted input, use `"isolated-vm"`.
509
- - **Maizzle**: PostHTML directives that access the filesystem (`<extends>`, `<fetch>`, `<include>`, `<raw>`, `<block>`, `<yield>`, etc.) are rejected at validation time.
510
- - **MJML**: Compiled through the `mjml` package with default settings.
511
-
512
- ---
513
-
514
- ## AI-Powered Fixes
515
-
516
- The engine classifies every warning as either `css` (CSS-only swap) or `structural` (requires HTML restructuring). For structural issues, the engine can generate a prompt and delegate to an LLM.
517
-
518
- ### `generateAiFix(options): Promise<AiFixResult>`
519
-
520
- ```typescript
521
- import { generateAiFix, AI_FIX_SYSTEM_PROMPT } from "@emailens/engine";
522
-
523
- const result = await generateAiFix({
524
- originalHtml: html,
525
- warnings,
526
- scores,
527
- scope: "all",
528
- format: "jsx",
529
- provider: async (prompt) => {
530
- const msg = await anthropic.messages.create({
531
- model: "claude-sonnet-4-6",
532
- max_tokens: 8192,
533
- system: AI_FIX_SYSTEM_PROMPT,
534
- messages: [{ role: "user", content: prompt }],
535
- });
536
- return msg.content[0].type === "text" ? msg.content[0].text : "";
537
- },
538
- });
94
+ ```bash
95
+ npm install @emailens/engine
539
96
  ```
540
97
 
541
- ### `estimateAiFixTokens(options): Promise<TokenEstimate>`
98
+ Three entry points:
542
99
 
543
- Estimate tokens before making an API call.
100
+ | Import | Description |
101
+ |---|---|
102
+ | `@emailens/engine` | Core analysis — CSS, spam, a11y, links, images, inbox preview, size, templates, AI fix |
103
+ | `@emailens/engine/compile` | JSX / MJML / Maizzle → HTML compilers |
104
+ | `@emailens/engine/server` | Node-only: DNS deliverability checks, SpamAssassin integration |
544
105
 
545
- ### `heuristicTokenCount(text): number`
106
+ ## Why Emailens?
546
107
 
547
- Instant synchronous token estimate (~3.5 chars/token).
108
+ - **Offline-first** runs entirely locally, no network calls required (except DNS deliverability checks)
109
+ - **Unified audit** — one function call returns CSS compatibility, spam, accessibility, links, images, inbox preview, size, and template checks
110
+ - **Framework-aware** — fix snippets tailored to React Email (JSX), MJML, and Maizzle
111
+ - **AI-ready** — structural issues get LLM-powered auto-fix with any provider (Claude, GPT, etc.)
112
+ - **Programmable** — TypeScript API, not a GUI — integrate into CI, editors, or build pipelines
548
113
 
549
- ---
114
+ | | @emailens/engine | Litmus | Email on Acid | caniemail.com |
115
+ |---|---|---|---|---|
116
+ | Local/offline | Yes | No | No | Data only |
117
+ | Programmatic API | Yes | Limited | No | No |
118
+ | CSS + Spam + A11y | Yes | Separate tools | Separate tools | CSS only |
119
+ | AI auto-fix | Yes | No | No | No |
120
+ | Open source | MIT | No | No | Yes (data) |
550
121
 
551
122
  ## Supported Email Clients
552
123
 
@@ -565,139 +136,49 @@ Instant synchronous token estimate (~3.5 chars/token).
565
136
  | HEY Mail | `hey-mail` | Webmail | WebKit | Yes |
566
137
  | Superhuman | `superhuman` | Desktop | Blink | Yes |
567
138
 
568
- ## Types
139
+ ## API Documentation
569
140
 
570
- ```typescript
571
- type SupportLevel = "supported" | "partial" | "unsupported" | "unknown";
572
- type Framework = "jsx" | "mjml" | "maizzle";
573
- type InputFormat = "html" | Framework;
574
- type FixType = "css" | "structural";
575
-
576
- interface CSSWarning {
577
- severity: "error" | "warning" | "info";
578
- client: string;
579
- property: string;
580
- message: string;
581
- suggestion?: string;
582
- fix?: CodeFix;
583
- fixType?: FixType;
584
- line?: number; // line number in <style> block
585
- selector?: string; // element selector for inline styles
586
- }
587
-
588
- interface AuditReport {
589
- compatibility: {
590
- warnings: CSSWarning[];
591
- scores: Record<string, { score: number; errors: number; warnings: number; info: number }>;
592
- };
593
- spam: SpamReport;
594
- links: LinkReport;
595
- accessibility: AccessibilityReport;
596
- images: ImageReport;
597
- inboxPreview: InboxPreview;
598
- size: SizeReport;
599
- templateVariables: TemplateReport;
600
- }
601
-
602
- interface EmailSession {
603
- readonly html: string;
604
- readonly framework: Framework | undefined;
605
- audit(options?): AuditReport;
606
- analyze(): CSSWarning[];
607
- score(warnings): Record<string, ClientScore>;
608
- analyzeSpam(options?): SpamReport;
609
- validateLinks(): LinkReport;
610
- checkAccessibility(): AccessibilityReport;
611
- analyzeImages(): ImageReport;
612
- extractInboxPreview(): InboxPreview;
613
- checkSize(): SizeReport;
614
- checkTemplateVariables(): TemplateReport;
615
- transformForClient(clientId): TransformResult;
616
- transformForAllClients(): TransformResult[];
617
- simulateDarkMode(clientId): { html; warnings };
618
- }
619
-
620
- interface InboxPreview {
621
- subject: string | null;
622
- preheader: string | null;
623
- subjectLength: number;
624
- preheaderLength: number;
625
- truncation: ClientTruncation[];
626
- issues: InboxPreviewIssue[];
627
- }
628
-
629
- interface SizeReport {
630
- htmlBytes: number;
631
- humanSize: string;
632
- clipped: boolean;
633
- issues: SizeIssue[];
634
- }
635
-
636
- interface TemplateReport {
637
- unresolvedCount: number;
638
- issues: TemplateIssue[];
639
- }
640
-
641
- interface SpamReport {
642
- score: number; // 0–100 (100 = clean)
643
- level: "low" | "medium" | "high";
644
- issues: SpamIssue[];
645
- }
646
-
647
- interface LinkReport {
648
- totalLinks: number;
649
- issues: LinkIssue[];
650
- breakdown: { https: number; http: number; mailto: number; tel: number; ... };
651
- }
652
-
653
- interface AccessibilityReport {
654
- score: number; // 0–100
655
- issues: AccessibilityIssue[];
656
- }
657
-
658
- interface ImageReport {
659
- total: number;
660
- totalDataUriBytes: number;
661
- issues: ImageIssue[];
662
- images: ImageInfo[];
663
- }
664
-
665
- interface DeliverabilityReport {
666
- domain: string;
667
- checks: DeliverabilityCheck[];
668
- score: number; // 0-100
669
- issues: DeliverabilityIssue[];
670
- }
671
-
672
- interface DeliverabilityCheck {
673
- name: "spf" | "dkim" | "dmarc" | "mx" | "bimi";
674
- status: "pass" | "fail" | "warn" | "skip";
675
- message: string;
676
- detail?: string;
677
- record?: string;
678
- }
679
-
680
- interface SpamAssassinResult {
681
- score: number;
682
- threshold: number;
683
- isSpam: boolean;
684
- rules: Array<{ name: string; score: number; description: string }>;
685
- rawOutput: string;
686
- }
687
- ```
141
+ Full API reference: **[docs/API.md](./docs/API.md)**
142
+
143
+ Covers:
144
+ - `auditEmail` and `createSession` core analysis
145
+ - Standalone analyzers (CSS, spam, links, accessibility, images, inbox preview, size, templates)
146
+ - DNS deliverability and SpamAssassin integration
147
+ - Client transforms and dark mode simulation
148
+ - Compile module (JSX, MJML, Maizzle)
149
+ - AI-powered fixes and token estimation
150
+ - Performance optimization guide
151
+ - Security considerations
152
+ - Full TypeScript type definitions
153
+
154
+ ## Roadmap
155
+
156
+ - [ ] Outlook VML auto-generation
157
+ - [ ] GitHub Actions integration (score thresholds in CI)
158
+ - [x] Automated caniemail.com data sync
159
+ - [ ] Real-time rendering previews
160
+ - [ ] MJML/Maizzle source-level linting
161
+ - [ ] Plugin system for custom analyzers
688
162
 
689
163
  ## Contributing
690
164
 
691
- Contributions are welcome! Please [open an issue](https://github.com/nicholasgriffintn/emailens/issues) to discuss your idea before submitting a PR.
165
+ Contributions are welcome! See **[CONTRIBUTING.md](./CONTRIBUTING.md)** for architecture overview, setup instructions, and PR guidelines.
692
166
 
693
167
  ```bash
694
- bun test
168
+ bun install && bun test # 580 tests
695
169
  ```
696
170
 
697
- 574 tests covering CSS analysis (250+ properties), transformation, dark mode simulation, framework-aware fixes, AI fix generation, token estimation, spam scoring, link validation, accessibility checking, image analysis, inbox preview extraction, size checking, template variable detection, DNS deliverability checking, session API, security hardening, integration pipelines, accuracy benchmarks, and battle tests.
171
+ ### Data Maintenance
172
+
173
+ CSS support data is auto-synced from [caniemail.com](https://www.caniemail.com/). Other data (dark mode behavior, display limits, Superhuman overrides) is manually curated and tracked with verification dates.
174
+
175
+ ```bash
176
+ bun run sync:caniemail # Refresh CSS support matrix from caniemail.com
177
+ bun run check:freshness # Flag stale data sources (exits 1 if any overdue)
178
+ ```
698
179
 
699
- **Project structure:** analysis modules live in `src/`, each with a corresponding test file in `tests/`. The engine parses HTML once and shares the DOM across all analyzers.
180
+ See [CONTRIBUTING.md](./CONTRIBUTING.md#data-sources-and-freshness) for full details on data sources and verification procedures.
700
181
 
701
182
  ## License
702
183
 
703
- MIT
184
+ MIT — Copyright 2025 [Emailens](https://emailens.dev)