@postalsys/email-ai-tools 3.0.4 → 3.0.6

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.
@@ -1,23 +1,22 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MAX_LINK_TEXT_LENGTH = exports.MAX_HTML_LENGTH = exports.INVISIBLE_CHARS = void 0;
3
+ exports.MAX_NESTING = exports.MAX_LINK_TEXT_LENGTH = exports.MAX_HTML_LENGTH = exports.INVISIBLE_CHARS = void 0;
7
4
  exports.visibleHtml = visibleHtml;
8
5
  exports.visibleText = visibleText;
9
- const htmlparser2_1 = require("htmlparser2");
10
- const dom_serializer_1 = __importDefault(require("dom-serializer"));
6
+ const parse5_1 = require("parse5");
7
+ const parse5_htmlparser2_tree_adapter_1 = require("parse5-htmlparser2-tree-adapter");
8
+ const css_select_1 = require("css-select");
9
+ const css_what_1 = require("css-what");
11
10
  const domutils_1 = require("domutils");
12
11
  const token_estimate_js_1 = require("./token-estimate.js");
13
12
  // What the reader never sees must not reach the model either: an email can carry instructions
14
13
  // for an AI in text a mail client does not render, and the summary has to describe the message
15
14
  // as it looks to the person it was sent to. The links are collected before anything is removed,
16
15
  // because the checks run on them must see every link the message carries, hidden or not
17
- // Elements whose content is never rendered as text
18
- const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed']);
19
- // Comments and quoted strings inside a style attribute, which carry no declarations
20
- const STYLE_NOISE = /\/\*[\s\S]*?\*\/|"[^"]*"|'[^']*'/g;
16
+ // Elements whose content is never rendered as text. Noembed and noframes are shown only by browsers
17
+ // that support neither embeds nor frames, which no mail client is, and their content is written out
18
+ // raw, where the converter's own parser would read it as markup
19
+ const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed', 'noembed', 'noframes']);
21
20
  // Everything here runs synchronously in the process that called it, so how much of a message is
22
21
  // read has to be this library's decision rather than the sender's. The HTML is cut before it is
23
22
  // parsed; the text of a link is cut to what a reader could take in as its destination
@@ -25,69 +24,1029 @@ const MAX_HTML_LENGTH = 1024 * 1024;
25
24
  exports.MAX_HTML_LENGTH = MAX_HTML_LENGTH;
26
25
  const MAX_LINK_TEXT_LENGTH = 1024;
27
26
  exports.MAX_LINK_TEXT_LENGTH = MAX_LINK_TEXT_LENGTH;
28
- // Outlook for Windows shows what a conditional comment wraps; the markers go, the content stays.
29
- // The condition is bounded: an opening marker that never closes used to be scanned to the end
30
- // of the document, once for every marker, which is quadratic
31
- const CONDITIONAL_COMMENT = /<!--\[if [^\]]{0,200}\]>|<!\[endif\]-->/gi;
27
+ // The style sheets of a message are read for the rules that hide text or show it again. How much of
28
+ // them is read, how many such rules are applied and how long a selector may be are bounded, since
29
+ // every rule is tested against every element
30
+ const MAX_STYLE_LENGTH = 128 * 1024;
31
+ const MAX_HIDING_RULES = 100;
32
+ const MAX_SELECTOR_LENGTH = 512;
33
+ // How deep elements may nest before the rest of the document is left out. The parser's scope checks
34
+ // scan the open elements, so its work grows with the square of the depth (two hundred thousand
35
+ // nested divs took five minutes), and every walk over the document recurses. Real mail nests a few dozen levels, a layout of tables in tables a hundred or two. The
36
+ // HTML to text converter reads no deeper than this either, so nothing it would have shown is lost
37
+ const MAX_NESTING = 500;
38
+ exports.MAX_NESTING = MAX_NESTING;
39
+ // How many Outlook-only sections are parsed into place. Each is a parse of its own, a fraction of a
40
+ // millisecond for the few a message has; past this many the rest stay comments, as every client but
41
+ // Outlook reads them
42
+ const MAX_SECTIONS = 1000;
43
+ // The work the hiding rules may cost, as tests of a selector against an element, a descendant
44
+ // combinator counting once for every level it may have to climb. Ten million such tests take about
45
+ // half a second; ordinary mail, a few thousand elements and a few dozen rules, stays far below it.
46
+ // Past the budget no rule is applied, and the text stays in front of the model as it did before
47
+ // style sheets were read at all
48
+ const RULE_WORK_BUDGET = 10_000_000;
49
+ // A media query is honored only when it holds for every reader: no narrower than the smallest
50
+ // phone, no wider than any screen. A sheet or a block for some readers only is not read, and when it
51
+ // sets anything the hiding check reads, no sheet is trusted (see sheetRules())
52
+ const ALWAYS_MIN_WIDTH = 320;
53
+ const ALWAYS_MAX_WIDTH = 4000;
54
+ // The start of an Outlook conditional comment's text, "[if mso]>", "[if gte mso 9]>" and the like.
55
+ // The condition is bounded and holds no markup or quotes, which no real condition does
56
+ const CONDITIONAL_OPEN = /^\[if [^\]<>"']{0,200}\]>/i;
57
+ // What is left of a downlevel-revealed opener, "<!--[if !mso]><!-->" or "<!--[if !mso]><!-- -->"
58
+ const REVEALED_OPEN_REST = /^<!(?:--\s*)?$/;
59
+ const CONDITIONAL_CLOSE = '<![endif]';
60
+ // What JavaScript takes as whitespace and HTML and CSS do not: a no-break space or an ideographic
61
+ // space is part of a name to them, a vertical tab a character of its own
62
+ const NON_ASCII_SPACE = /[^\S \t\n\f\r]/;
32
63
  // Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
33
64
  // bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
34
65
  // stops them splitting words the model should recognise or reordering text it should read
35
66
  const INVISIBLE_CHARS = /[\u00ad\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/g;
36
67
  exports.INVISIBLE_CHARS = INVISIBLE_CHARS;
37
- // Only what reliably hides text. Zero sizes of boxes and negative positions depend on other
38
- // properties to hide anything, so they are left alone rather than dropping text the reader sees
39
- function isHiddenStyle(input) {
40
- const style = String(input ?? '').replace(STYLE_NOISE, ' ');
41
- if (!style.trim()) {
68
+ // Where a comment or a quoted string that starts at `i` ends, or `i` when neither starts there. One
69
+ // that never closes runs to the end of the text, so a scan never restarts from every opening marker
70
+ function skipNoise(text, i) {
71
+ if (text[i] === '/' && text[i + 1] === '*') {
72
+ const end = text.indexOf('*/', i + 2);
73
+ return end < 0 ? text.length : end + 2;
74
+ }
75
+ const quote = text[i];
76
+ if (quote !== '"' && quote !== "'") {
77
+ return i;
78
+ }
79
+ for (let j = i + 1; j < text.length; j++) {
80
+ if (text[j] === '\\') {
81
+ j++;
82
+ }
83
+ else if (text[j] === quote) {
84
+ return j + 1;
85
+ }
86
+ else if (text[j] === '\n' || text[j] === '\r' || text[j] === '\f') {
87
+ // a string ends at a line break it did not escape, as CSS reads it (a bad string)
88
+ return j;
89
+ }
90
+ }
91
+ return text.length;
92
+ }
93
+ // The text without its comments, and without its quoted strings unless `keepStrings`, in one pass.
94
+ // A declaration carries no strings worth reading and its comments separate (they become a space); a
95
+ // selector keeps its strings, and a comment in it joins what is around it, as tokenizing CSS does
96
+ function withoutNoise(input, keepStrings) {
97
+ let output = '';
98
+ let from = 0;
99
+ for (let i = 0; i < input.length;) {
100
+ const end = skipNoise(input, i);
101
+ if (end === i) {
102
+ i++;
103
+ }
104
+ else if (keepStrings && input[i] !== '/') {
105
+ i = end;
106
+ }
107
+ else {
108
+ // ".a/**/.b" is ".a.b" in a selector
109
+ output += input.substring(from, i) + (keepStrings ? '' : ' ');
110
+ i = from = end;
111
+ }
112
+ }
113
+ return output + input.substring(from);
114
+ }
115
+ // The properties the hiding check reads. A style sheet rule that sets none of them cannot hide an
116
+ // element or show one again, so it is not matched at all
117
+ // Vertical padding, which a box of no height still shows (see isCollapsed())
118
+ const PADDING_PROPERTIES = ['padding', 'padding-top', 'padding-bottom', 'padding-block', 'padding-block-start', 'padding-block-end'];
119
+ const HIDING_PROPERTIES = new Set([
120
+ 'display',
121
+ 'visibility',
122
+ 'opacity',
123
+ 'font-size',
124
+ 'height',
125
+ 'max-height',
126
+ 'min-height',
127
+ 'overflow',
128
+ 'overflow-y',
129
+ // read for what a collapsed box cannot clip (see Walk), or sizes it after all (isCollapsed())
130
+ 'position',
131
+ 'block-size',
132
+ 'min-block-size',
133
+ 'max-block-size',
134
+ 'inline-size',
135
+ 'min-inline-size',
136
+ 'max-inline-size',
137
+ 'overflow-clip-margin',
138
+ 'writing-mode',
139
+ 'flex',
140
+ 'flex-basis',
141
+ 'flex-grow',
142
+ '-webkit-box-flex',
143
+ '-webkit-box-flex-group',
144
+ // shorthands that set what the check reads: the font size, and every property at once
145
+ 'font',
146
+ 'all',
147
+ ...PADDING_PROPERTIES
148
+ ]);
149
+ // The same properties found in raw style text, for style that is not read rule by rule
150
+ const HIDING_IN_TEXT = new RegExp(`(?:^|[{;\\s"'])(?:${[...HIDING_PROPERTIES].join('|')})\\s*:`, 'i');
151
+ // Whether style text nothing here reads rule by rule sets what the hiding check reads. A backslash
152
+ // counts too: CSS allows escapes in a property name, which no check here decodes
153
+ const mentionsHiding = (text) => text.includes('\\') || HIDING_IN_TEXT.test(text);
154
+ // What a string becomes in a split declaration: no hiding value holds one, so a value with one in
155
+ // it never reads as hiding
156
+ const STRING_MARK = ' \u0001 ';
157
+ // and a url(), which unlike a string is no font family either
158
+ const URL_MARK = ' \u0002 ';
159
+ /**
160
+ * Splits a declaration list where CSS does: at a ";" outside every bracket, string and url().
161
+ * Inside "(", "[" or "{" a ";" belongs to the value, a string ends at a line break it does not
162
+ * escape (and the declaration it is in is invalid), and an unquoted url() runs to its ")". Strings,
163
+ * urls and comments are left out of the text, since no value the hiding check reads needs them
164
+ */
165
+ function splitDeclarations(input) {
166
+ const parts = [];
167
+ let current = '';
168
+ let invalid = false;
169
+ let depth = 0;
170
+ for (let i = 0; i < input.length;) {
171
+ const char = input[i];
172
+ const noise = skipNoise(input, i);
173
+ if (noise !== i) {
174
+ // a string cut by a line break stops short of its closing quote
175
+ invalid = invalid || ((char === '"' || char === "'") && input[noise - 1] !== char);
176
+ // a string is no part of any hiding value: "display:none 'x'" is a declaration a browser
177
+ // rejects, so it must not read as "none". A comment only separates
178
+ current += char === '/' ? ' ' : STRING_MARK;
179
+ i = noise;
180
+ continue;
181
+ }
182
+ if ((char === 'u' || char === 'U') && /^url\(\s*[^\s"')]/i.test(input.substring(i, i + 8))) {
183
+ let j = input.indexOf('(', i) + 1;
184
+ while (j < input.length && input[j] !== ')') {
185
+ j += input[j] === '\\' ? 2 : 1;
186
+ }
187
+ current += URL_MARK;
188
+ i = j + 1;
189
+ continue;
190
+ }
191
+ if (char === '(' || char === '[' || char === '{') {
192
+ depth++;
193
+ }
194
+ else if ((char === ')' || char === ']' || char === '}') && depth > 0) {
195
+ depth--;
196
+ }
197
+ else if (char === ';' && depth === 0) {
198
+ parts.push({ text: current, invalid });
199
+ current = '';
200
+ invalid = false;
201
+ i++;
202
+ continue;
203
+ }
204
+ current += char;
205
+ i++;
206
+ }
207
+ parts.push({ text: current, invalid });
208
+ return parts;
209
+ }
210
+ /**
211
+ * The declarations of a declaration list, every value kept as written. A value counts as hiding only
212
+ * when it is clearly one ("none", an exact zero; see hiding()), so any other value, one a browser
213
+ * computes (calc(), var()), a keyword or one it rejects, keeps the text: as the last value for a
214
+ * property it undoes what an earlier one hid, which is what a browser does with every value it
215
+ * accepts. A declaration a browser drops whole (a "!" followed by anything but "important", a
216
+ * string cut by a line break) is dropped here too
217
+ */
218
+ function declarations(input) {
219
+ const list = [];
220
+ for (const { text, invalid } of splitDeclarations(input)) {
221
+ const match = /^\s*([a-z-]+)\s*:\s*([\s\S]*?)\s*(!\s*important\s*)?$/i.exec(text);
222
+ if (!match || invalid || match[2].includes('!')) {
223
+ continue;
224
+ }
225
+ list.push([match[1].toLowerCase(), match[2].toLowerCase(), !!match[3]]);
226
+ }
227
+ return list;
228
+ }
229
+ // The hiding properties an element inside can set again: they are inherited, so text inside an
230
+ // element that is hidden by one of them shows when something inside it sets the property itself.
231
+ // A negative text indent is not among the hiding properties at all: it moves the first line only,
232
+ // and how much of the text that line holds depends on the font and the width, which are unknown
233
+ const INHERITED_HIDING = new Set(['visibility', 'font-size', 'font', 'all']);
234
+ // Elements that set the font size again by the browser's own style: a table in a document without a
235
+ // doctype, and form controls in any
236
+ const FONT_RESET_TAGS = new Set(['table', 'button', 'textarea', 'select', 'input']);
237
+ // Elements that are block-level by the browser's own style. A box of no height collapses only when
238
+ // it is block-level: height does not apply to an inline element, and every element a browser does
239
+ // not know, "o:p" among them, is inline. A table and its parts grow to fit what they hold, and the
240
+ // root and the body pass their overflow to the viewport, so neither list holds them
241
+ const BLOCK_TAGS = new Set([
242
+ 'address',
243
+ 'article',
244
+ 'aside',
245
+ 'blockquote',
246
+ 'center',
247
+ 'dd',
248
+ 'details',
249
+ 'dir',
250
+ 'div',
251
+ 'dl',
252
+ 'dt',
253
+ 'figcaption',
254
+ 'figure',
255
+ 'footer',
256
+ 'form',
257
+ 'h1',
258
+ 'h2',
259
+ 'h3',
260
+ 'h4',
261
+ 'h5',
262
+ 'h6',
263
+ 'header',
264
+ 'hgroup',
265
+ 'li',
266
+ 'main',
267
+ 'menu',
268
+ 'nav',
269
+ 'ol',
270
+ 'p',
271
+ 'pre',
272
+ 'section',
273
+ 'summary',
274
+ 'ul'
275
+ ]);
276
+ // Elements a box of no height does not hide whatever their display: a fieldset draws its legend in
277
+ // its border and pads itself, a dialog pads itself, form controls carry padding and text of their
278
+ // own, and the root and the body pass their overflow to the viewport
279
+ const UNCOLLAPSIBLE_TAGS = new Set(['html', 'body', 'fieldset', 'legend', 'dialog', 'button', 'textarea', 'select', 'option', 'optgroup', 'input']);
280
+ const BLOCK_DISPLAYS = new Set(['block', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'list-item', 'flow-root']);
281
+ // Sizes that set the height again in other words, and a margin the clipping is drawn out by
282
+ const COLLAPSE_UNDOING = [
283
+ 'block-size',
284
+ 'min-block-size',
285
+ 'max-block-size',
286
+ 'inline-size',
287
+ 'min-inline-size',
288
+ 'max-inline-size',
289
+ 'overflow-clip-margin',
290
+ // a flex item's size along a column is set by these, whatever its height
291
+ 'flex',
292
+ 'flex-basis',
293
+ 'flex-grow',
294
+ '-webkit-box-flex',
295
+ '-webkit-box-flex-group'
296
+ ];
297
+ // A length of zero that holds whatever the box sits in. A percentage is resolved against the parent
298
+ // and becomes auto when the parent's height is, which is the usual case
299
+ const isAbsoluteZero = (value) => /^(?:0+(?:\.0+)?|\.0+)(?:px|pt|pc|em|rem|ex|ch|cm|mm|in|q|vh|vw|vmin|vmax)?$/.test(value || '');
300
+ const OVERFLOW_KEYWORDS = new Set(['visible', 'hidden', 'clip', 'scroll', 'auto', 'overlay']);
301
+ // The vertical overflow as it resolves: the shorthand and the longhand in the order they apply, the
302
+ // second value of a two-value shorthand, and a value a browser rejects (three words, an unknown one)
303
+ // skipped as it skips it
304
+ function overflowY(applied) {
305
+ let value = '';
306
+ for (const [property, declared] of applied) {
307
+ const values = declared.split(/\s+/);
308
+ if (!values.every(keyword => OVERFLOW_KEYWORDS.has(keyword))) {
309
+ continue;
310
+ }
311
+ if (property === 'overflow' && values.length <= 2) {
312
+ value = values[1] || values[0];
313
+ }
314
+ else if (property === 'overflow-y' && values.length === 1) {
315
+ value = declared;
316
+ }
317
+ }
318
+ return value;
319
+ }
320
+ /**
321
+ * Whether a box of no height clips everything in it: the preheader trick. Only where it holds for
322
+ * every reader, so a block-level box, an absolute zero, nothing that sets a minimum height or a size
323
+ * again or draws the clipping out, no vertical padding (overflow clips at the padding edge, so text
324
+ * shows in the padding) and a vertical overflow that resolves to hidden or clip
325
+ */
326
+ function isCollapsed(applied, style, element, vertical) {
327
+ // in a vertical writing mode, its own or inherited, the height is the inline size and inline
328
+ // padding is vertical, both of which content shows through
329
+ if (vertical) {
330
+ return false;
331
+ }
332
+ if (UNCOLLAPSIBLE_TAGS.has(element.name)) {
42
333
  return false;
43
334
  }
44
- for (const declaration of style.split(';')) {
45
- const match = /^\s*([a-z-]+)\s*:\s*([^!]*)/i.exec(declaration);
46
- if (!match) {
335
+ const display = style.get('display');
336
+ const blockLevel = display ? BLOCK_DISPLAYS.has(display) : BLOCK_TAGS.has(element.name);
337
+ if (!blockLevel || !(isAbsoluteZero(style.get('height')) || isAbsoluteZero(style.get('max-height')))) {
338
+ return false;
339
+ }
340
+ if ((style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) || COLLAPSE_UNDOING.some(property => style.has(property))) {
341
+ return false;
342
+ }
343
+ for (const property of PADDING_PROPERTIES) {
344
+ if (style.has(property) && !style.get(property).split(/\s+/).every(isAbsoluteZero)) {
345
+ return false;
346
+ }
347
+ }
348
+ const overflow = overflowY(applied);
349
+ return overflow === 'hidden' || overflow === 'clip';
350
+ }
351
+ // A font size that hides text: zero in any unit, or below a pixel with a unit. A number without a
352
+ // unit is read only in quirks mode, and a webmail shows the message in its own standards-mode page
353
+ // A zero as CSS writes one (a digit after any dot), in a length unit it knows or as a percentage
354
+ const isHidingFontSize = (value) => /^(?:0+(?:\.0+)?|\.0+)(?:px|pt|pc|em|rem|ex|ch|cap|ic|lh|rlh|cm|mm|in|q|vh|vw|vmin|vmax|vb|vi|svh|svw|lvh|lvw|dvh|dvw|cqw|cqh|cqi|cqb|cqmin|cqmax|%)?$/.test(value) || /^0?\.\d+(?:px|pt)$/.test(value);
355
+ /**
356
+ * The font size as it resolves: the longhand and the font shorthand in the order they apply. The
357
+ * shorthand sets the size whatever else it says, so it hides only when its own size is a hiding
358
+ * one ("font:0 Arial"); a system font such as "menu" sets one too
359
+ */
360
+ function fontSize(applied) {
361
+ let size = '';
362
+ for (const [property, value] of applied) {
363
+ if (property === 'font-size') {
364
+ size = value;
365
+ }
366
+ else if (property === 'font') {
367
+ size = hidingFontShorthand(value) ? '0' : 'set';
368
+ }
369
+ }
370
+ return size;
371
+ }
372
+ // A CSS identifier: what a class, an id, an unquoted attribute value and a font family name are
373
+ const IDENT = /^(?:--|-?[_a-z\u0080-\uffff])[-_a-z0-9\u0080-\uffff]*$/i;
374
+ // What may come before the size in the font shorthand, each kind at most once ("normal" may stand
375
+ // for any of them), four in all
376
+ const FONT_PREFIX_KINDS = [
377
+ ['style', /^(?:italic|oblique)$/],
378
+ ['variant', /^small-caps$/],
379
+ ['weight', /^(?:bold|bolder|lighter|[1-9]\d{0,2}|1000)$/],
380
+ ['stretch', /^(?:ultra-|extra-|semi-)?(?:condensed|expanded)$/]
381
+ ];
382
+ const CSS_WIDE = /^(?:inherit|initial|unset|revert|revert-layer|default)$/;
383
+ const LINE_HEIGHT = /^(?:normal|(?:\d+\.?\d*|\.\d+)(?:px|pt|pc|em|rem|ex|ch|lh|rlh|cm|mm|in|q|vh|vw|vmin|vmax|%)?)$/;
384
+ /**
385
+ * Whether a font shorthand is a valid one with a hiding size: style, variant, weight and stretch
386
+ * keywords, then the size (with a line height after a "/"), then a list of families, each a quoted
387
+ * string or names. Anything else is either a size that shows text or a declaration a browser
388
+ * rejects, and both keep the text here
389
+ */
390
+ function hidingFontShorthand(value) {
391
+ const tokens = value.split(/[ \t\n\f\r]+/).filter(Boolean);
392
+ const seen = new Set();
393
+ let at = 0;
394
+ for (; at < tokens.length && at < 4; at++) {
395
+ if (tokens[at] === 'normal') {
47
396
  continue;
48
397
  }
49
- const property = match[1].toLowerCase();
50
- const value = match[2].trim().toLowerCase();
51
- const number = parseFloat(value);
52
- switch (property) {
53
- case 'display':
54
- if (value === 'none') {
55
- return true;
56
- }
57
- break;
58
- case 'visibility':
59
- if (value === 'hidden' || value === 'collapse') {
60
- return true;
61
- }
62
- break;
63
- case 'opacity':
64
- if (Number.isFinite(number) && number < 0.1) {
65
- return true;
66
- }
67
- break;
68
- case 'font-size':
69
- // zero in any unit, or below one pixel
70
- if (Number.isFinite(number) && (number === 0 || (number < 1 && /^[\d.]+(?:px|pt)?$/.test(value)))) {
71
- return true;
72
- }
73
- break;
74
- case 'text-indent':
75
- if (Number.isFinite(number) && number <= -1000) {
76
- return true;
398
+ const kind = FONT_PREFIX_KINDS.find(([, pattern]) => pattern.test(tokens[at]));
399
+ if (!kind) {
400
+ break;
401
+ }
402
+ if (seen.has(kind[0])) {
403
+ return false;
404
+ }
405
+ seen.add(kind[0]);
406
+ }
407
+ if (at >= tokens.length) {
408
+ return false;
409
+ }
410
+ let [size, lineHeight] = tokens[at].split('/');
411
+ let rest = tokens.slice(at + 1);
412
+ if (lineHeight === '' || (lineHeight === undefined && rest[0] && rest[0].startsWith('/'))) {
413
+ // the line height in a token of its own, after a "/" or within it
414
+ lineHeight = lineHeight === '' ? rest.shift() : rest.shift().substring(1) || rest.shift();
415
+ }
416
+ if (lineHeight !== undefined && !LINE_HEIGHT.test(lineHeight || '')) {
417
+ return false;
418
+ }
419
+ rest = rest.filter(Boolean);
420
+ // every family is one quoted string (left as a mark by the declaration splitter) or names, and
421
+ // a single name is no CSS-wide keyword
422
+ const families = rest
423
+ .join(' ')
424
+ .split(',')
425
+ .map(family => family.trim().split(' ').filter(Boolean));
426
+ const validFamily = (words) => words.length > 0 && (words.join(' ') === '\u0001' || (words.every(word => IDENT.test(word)) && !(words.length === 1 && CSS_WIDE.test(words[0]))));
427
+ return isHidingFontSize(size) && rest.length > 0 && families.every(validFamily);
428
+ }
429
+ /**
430
+ * How an element is hidden by what applies to it, the last value for a property winning (see
431
+ * appliedDeclarations() for the order). "final" when nothing inside it can show text again: no
432
+ * display, the hidden attribute, an opacity of zero, which a child's own cannot raise. "inherited" when
433
+ * it is hidden by visibility or a font size below a pixel, which an element inside can set again.
434
+ * "collapsed" for a box of no height that clips its content, which an element inside escapes when
435
+ * it is positioned against something outside the box. Only what reliably hides text for every
436
+ * reader counts: negative positions, indents and colors depend on other properties, so they are
437
+ * left alone rather than dropping text the reader sees
438
+ */
439
+ function hiding(declared, element, hiddenAttributeTrusted, vertical) {
440
+ // "all" sets every property again, so only what comes after the last one applies, and it is an
441
+ // author display value that overrides the hidden attribute
442
+ const reset = declared.map(([property]) => property).lastIndexOf('all');
443
+ const applied = reset < 0 ? declared : declared.slice(reset + 1);
444
+ const hiddenAttribute = hiddenAttributeTrusted && reset < 0 && 'hidden' in element.attribs;
445
+ if (!applied.length) {
446
+ // most elements: no rule matched and no style attribute
447
+ return hiddenAttribute ? 'final' : '';
448
+ }
449
+ const style = new Map(applied.map(([property, value]) => [property, value]));
450
+ const value = (property) => style.get(property) || '';
451
+ if (value('display') === 'none' ||
452
+ // the hidden attribute is a user agent rule, which an author display value overrides
453
+ (hiddenAttribute && !style.has('display')) ||
454
+ // a display:contents element draws no box, and its opacity hides nothing
455
+ (/^(?:0+(?:\.0+)?|\.0+)%?$/.test(value('opacity')) && value('display') !== 'contents')) {
456
+ return 'final';
457
+ }
458
+ if (isCollapsed(applied, style, element, vertical)) {
459
+ return 'collapsed';
460
+ }
461
+ if (value('visibility') === 'hidden' || value('visibility') === 'collapse' || isHidingFontSize(fontSize(applied))) {
462
+ return 'inherited';
463
+ }
464
+ return '';
465
+ }
466
+ // Whether one condition of a media query holds for every reader
467
+ function alwaysTrueCondition(condition) {
468
+ if (condition === 'all' || condition === 'screen') {
469
+ return true;
470
+ }
471
+ const match = /^\(\s*(min|max)-(?:device-)?width\s*:\s*([\d.]+)(px)?\s*\)$/.exec(condition);
472
+ if (!match) {
473
+ return false;
474
+ }
475
+ const width = Number(match[2]);
476
+ if (!match[3] && width !== 0) {
477
+ return false;
478
+ }
479
+ return match[1] === 'min' ? width <= ALWAYS_MIN_WIDTH : width >= ALWAYS_MAX_WIDTH;
480
+ }
481
+ // A media query list that holds whoever reads the message: "screen", "all and (min-width: 0)" and
482
+ // the like
483
+ function isUnconditionalQuery(queries) {
484
+ return queries
485
+ .toLowerCase()
486
+ .split(',')
487
+ .some(query => query
488
+ .trim()
489
+ .replace(/^only\s+/, '')
490
+ .split(/\s+and\s+/)
491
+ .every(condition => alwaysTrueCondition(condition.trim())));
492
+ }
493
+ // Where the block opening at `start` closes, nested blocks, comments and strings skipped
494
+ function blockEnd(css, start) {
495
+ let depth = 0;
496
+ for (let i = start; i < css.length;) {
497
+ const end = skipNoise(css, i);
498
+ if (end !== i) {
499
+ i = end;
500
+ continue;
501
+ }
502
+ if (css[i] === '{') {
503
+ depth++;
504
+ }
505
+ else if (css[i] === '}' && --depth === 0) {
506
+ return i;
507
+ }
508
+ i++;
509
+ }
510
+ return css.length;
511
+ }
512
+ /**
513
+ * What the style sheets say about hiding, or null when they cannot be read faithfully. Every rule a
514
+ * mail client would apply has to be read for a rule that hides to be trusted: a rule left unread
515
+ * may be the one that shows the element again, and then text every reader sees would be taken from
516
+ * the model. So when any rule that sets something the check reads is left unread (inside a
517
+ * conditional or unknown at-rule, behind an @import, past the rule cap, with an escaped property
518
+ * name) the sheets count for nothing and only the style attributes do, as before sheets were read
519
+ *
520
+ * @returns The rules in sheet order, each with only the declarations the check reads
521
+ */
522
+ function sheetRules(css) {
523
+ if (css.includes('\\') || NON_ASCII_SPACE.test(css)) {
524
+ // an escape in a property name or a selector is one no check here decodes
525
+ return null;
526
+ }
527
+ const rules = [];
528
+ let start = 0;
529
+ // the unconditional media blocks entered, whose "}" ends them
530
+ let entered = 0;
531
+ for (let i = 0; i < css.length;) {
532
+ const end = skipNoise(css, i);
533
+ if (end !== i) {
534
+ i = end;
535
+ continue;
536
+ }
537
+ const char = css[i];
538
+ if (char === ';' || char === '}') {
539
+ const statement = withoutNoise(css.substring(start, i), true).trim();
540
+ // a sheet another one imports holds rules nothing here reads
541
+ if (/^@import\b/i.test(statement)) {
542
+ return null;
543
+ }
544
+ // a ";" ends an at-rule statement only, and a "}" a block that was entered. Anywhere else
545
+ // a browser keeps it as part of the next rule's selector, which is then invalid and the
546
+ // rule dropped, where here it would be read
547
+ if ((char === ';' && !statement.startsWith('@')) || (char === '}' && (statement || entered === 0))) {
548
+ return null;
549
+ }
550
+ if (char === '}') {
551
+ entered--;
552
+ }
553
+ start = ++i;
554
+ continue;
555
+ }
556
+ if (char !== '{') {
557
+ i++;
558
+ continue;
559
+ }
560
+ const prelude = withoutNoise(css.substring(start, i), true).trim();
561
+ const media = /^@media\s+(.+)$/i.exec(prelude);
562
+ if (media && isUnconditionalQuery(media[1])) {
563
+ // entered, so that its rules are read next
564
+ entered++;
565
+ i = start = i + 1;
566
+ continue;
567
+ }
568
+ const close = blockEnd(css, i);
569
+ const block = css.substring(i + 1, close);
570
+ i = start = close + 1;
571
+ if (prelude.startsWith('@')) {
572
+ // any other at-rule is not read, so it must not set what the check reads
573
+ if (mentionsHiding(block)) {
574
+ return null;
575
+ }
576
+ continue;
577
+ }
578
+ if (block.includes('{') && mentionsHiding(block)) {
579
+ // a nested rule (CSS nesting, which browsers apply) is not read rule by rule here
580
+ return null;
581
+ }
582
+ const found = declarations(block).filter(([property]) => HIDING_PROPERTIES.has(property));
583
+ if (prelude && found.length) {
584
+ if (rules.length >= MAX_HIDING_RULES) {
585
+ return null;
586
+ }
587
+ rules.push({ selector: prelude, declarations: found });
588
+ }
589
+ }
590
+ return rules;
591
+ }
592
+ // The selector tokens a rule may use. A pseudo-class or a pseudo-element is left out: the structural
593
+ // pseudo-classes (:nth-child() and the like) are matched by counting siblings, which is quadratic in
594
+ // a long list of them, and :has() recurses as deep as the document goes. The sibling combinators
595
+ // scan the siblings before an element for every element tested, so they are left out too
596
+ const MATCHABLE_TOKENS = new Set(['tag', 'universal', 'attribute', 'descendant', 'child']);
597
+ // A class or id selector, which css-what marks for case-insensitive matching in quirks mode
598
+ const isQuirksName = (token) => token.type === 'attribute' && token.ignoreCase === 'quirks';
599
+ const isRoot = (token) => !!token && token.type === 'tag' && (token.name === 'html' || token.name === 'body');
600
+ /**
601
+ * The selector as the matcher reads it, or null for one it cannot match as a mail client does: the
602
+ * same parse decides what is allowed, what it costs and what is compiled, so the three cannot
603
+ * disagree. "html > ..." and "body > ..." are refused too: a webmail shows the message inside a
604
+ * page of its own, where the message's root and body are not the page's
605
+ */
606
+ function matchableSelector(selector) {
607
+ if (selector.length > MAX_SELECTOR_LENGTH || !validSelectorText(selector)) {
608
+ return null;
609
+ }
610
+ let parsed;
611
+ try {
612
+ parsed = (0, css_what_1.parse)(selector);
613
+ }
614
+ catch {
615
+ return null;
616
+ }
617
+ const matchable = (part) => part.every(token => MATCHABLE_TOKENS.has(token.type)) && !part.some((token, i) => isRoot(token) && part[i + 1]?.type === 'child');
618
+ return parsed.every(matchable) ? parsed : null;
619
+ }
620
+ /**
621
+ * What css-what accepts and a browser does not, checked on the text: an id or class that starts with a digit, a
622
+ * namespace (which the matcher cannot match), and an attribute value or flag that is not valid
623
+ * unquoted. Any of these leaves the sheets unread rather than matched otherwise than a browser does
624
+ */
625
+ function validSelectorText(selector) {
626
+ if (selector.includes('|')) {
627
+ return false;
628
+ }
629
+ // every class and id name has to be an identifier ("-" alone or "-1" is not one)
630
+ const names = selector.replace(/\[[^\]]*\]|"[^"]*"|'[^']*'/g, ' ').match(/[#.][^\s#.[>,:*~+()]*/g) || [];
631
+ if (names.some(name => !IDENT.test(name.substring(1)))) {
632
+ return false;
633
+ }
634
+ for (const attribute of selector.match(/\[[^\]]*\]/g) || []) {
635
+ const match = /^\[\s*[-_a-z0-9]+\s*(?:[~|^$*]?=\s*("[^"]*"|'[^']*'|[^\s\]]+)\s*([a-z]*)\s*)?\]$/i.exec(attribute);
636
+ if (!match || (match[1] && !/^["']/.test(match[1]) && !IDENT.test(match[1])) || (match[2] && match[2].toLowerCase() !== 'i')) {
637
+ return false;
638
+ }
639
+ }
640
+ return true;
641
+ }
642
+ /**
643
+ * What testing one part of a selector list against one element may cost, in tests: the depth of
644
+ * the document for every descendant combinator in it, since each one climbs the ancestors of the
645
+ * element. The child combinator climbs one level and costs nothing more
646
+ */
647
+ function selectorCost(part, maxDepth) {
648
+ return maxDepth ** part.filter(token => token.type === 'descendant').length;
649
+ }
650
+ /**
651
+ * The specificity of one part of a selector list, as one number that sorts the way the three
652
+ * counts do: ids, then classes and attributes, then types. No part a hiding rule may use comes
653
+ * near a thousand of any of them, the selector length limit sees to that
654
+ */
655
+ function specificity(part) {
656
+ let value = 0;
657
+ for (const token of part) {
658
+ if (token.type === 'attribute') {
659
+ // "#p" is an id selector, "[id=p]" an attribute selector that weighs like a class: the
660
+ // parser gives both the same token and marks only the shorthand with quirks-mode case
661
+ value += isQuirksName(token) && token.name === 'id' && token.action === 'equals' ? 1_000_000 : 1000;
662
+ }
663
+ else if (token.type === 'tag') {
664
+ value += 1;
665
+ }
666
+ }
667
+ return value;
668
+ }
669
+ /**
670
+ * When the sheets are not read, they apply no rule, and the style attributes and the hidden
671
+ * attribute count only where nothing unread could override them: an "!important" declaration
672
+ * overrides a style attribute, an imported or linked sheet could hold one, an escaped property
673
+ * name in a style attribute is one no check here decodes, and any author display value overrides
674
+ * the hidden attribute
675
+ */
676
+ function unread(parsed) {
677
+ const texts = [parsed.css, ...parsed.conditionalStyle];
678
+ const inline = !parsed.externalStyle && !parsed.escapedInline && !texts.some(text => text.includes('!') || /@import/i.test(text));
679
+ // an unread rule could set what undoes inherited hiding or a collapsed box (a child's visibility
680
+ // or font size, a minimum height, a position), so those count only when nothing unread mentions
681
+ // a hiding property
682
+ return {
683
+ rules: [],
684
+ inline,
685
+ hiddenAttribute: inline && !texts.some(text => /(?:^|[{;\s"'])display\s*:/i.test(text)),
686
+ undoable: inline && !texts.some(mentionsHiding)
687
+ };
688
+ }
689
+ /**
690
+ * Compiles the rules of the message's own style sheets that the hiding check reads, one entry for
691
+ * each part of a selector list since each part has a specificity of its own, in the order the
692
+ * cascade weighs them. This is the one place that decides whether the sheets can be trusted, and
693
+ * they are not, so no rule is returned at all, whenever a rule a mail client would apply is left
694
+ * unread: leaving out one rule could leave out the one that shows text again, and then text every
695
+ * reader sees would be taken from the model. Each early return below is one way that happens
696
+ */
697
+ function readStyle(parsed) {
698
+ if (parsed.stylePolicy) {
699
+ // with author style possibly blocked, no sheet and no style attribute is known to apply; the
700
+ // hidden attribute is the browser's own style, which a policy does not block
701
+ return { rules: [], inline: false, hiddenAttribute: true, undoable: false };
702
+ }
703
+ if (
704
+ // the document was cut short, by the length or the nesting limit, so a sheet may follow unread
705
+ parsed.truncated ||
706
+ // something the walk flagged: a linked sheet, an escape in a style attribute, foreign content,
707
+ // a sheet that depends on scripting, a table quirks mode keeps in a paragraph
708
+ parsed.unreadableStyle ||
709
+ // a sheet one client applies and another does not: in a conditional comment, or for some media
710
+ parsed.conditionalStyle.some(mentionsHiding) ||
711
+ // more style than is read
712
+ parsed.css.length > MAX_STYLE_LENGTH) {
713
+ return unread(parsed);
714
+ }
715
+ // an at-rule, an @import, an escape or more rules than are read (see sheetRules()). Each style
716
+ // element is a sheet of its own: a comment or a selector left open at the end of one ends there,
717
+ // and joined to the next it would take that one's first rule with it
718
+ const read = [];
719
+ for (const sheet of parsed.sheets) {
720
+ const rules = sheetRules((0, domutils_1.textContent)(sheet));
721
+ if (!rules || read.length + rules.length > MAX_HIDING_RULES) {
722
+ return unread(parsed);
723
+ }
724
+ read.push(...rules);
725
+ }
726
+ const rules = [];
727
+ let work = 0;
728
+ for (const [order, { selector, declarations }] of read.entries()) {
729
+ // a selector that cannot be matched as a mail client matches it
730
+ const matchable = matchableSelector(selector);
731
+ if (!matchable) {
732
+ return unread(parsed);
733
+ }
734
+ // a class or id that a quirks-mode client matches whatever the case and a standards-mode one
735
+ // does not, where the two could disagree: a document in quirks mode is in that mode when a
736
+ // client shows it as its own page, and in the standards mode of the page around it when a
737
+ // webmail shows it inline
738
+ const caseMatters = (token) => parsed.quirks && isQuirksName(token) && (parsed.mixedCaseNames || /[A-Z]/.test(token.value));
739
+ if (matchable.some(part => part.some(caseMatters))) {
740
+ return unread(parsed);
741
+ }
742
+ // or more work than matching is allowed
743
+ work += parsed.elements * matchable.reduce((sum, part) => sum + selectorCost(part, parsed.maxDepth), 0);
744
+ if (work > RULE_WORK_BUDGET) {
745
+ return unread(parsed);
746
+ }
747
+ for (const part of matchable) {
748
+ let test;
749
+ try {
750
+ test = (0, css_select_1.compile)([part]);
751
+ }
752
+ catch {
753
+ // a selector the matcher refuses (it throws on some valid ones) is one not read
754
+ return unread(parsed);
755
+ }
756
+ rules.push({ test, declarations, specificity: specificity(part), order });
757
+ }
758
+ }
759
+ return { rules: rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order), inline: true, hiddenAttribute: true, undoable: true };
760
+ }
761
+ class NestingLimit extends Error {
762
+ }
763
+ // The levels a document puts above the message's own elements: the root and the body
764
+ const ROOT_DEPTH = 2;
765
+ /**
766
+ * Builds the tree through parse5, the HTML parser browsers follow, so a selector sees the parents a
767
+ * mail client gives an element: the paragraphs it closes, the tbody it adds, the content it moves out
768
+ * of a table, the text it reads raw. The build stops once an element would sit deeper than
769
+ * MAX_NESTING; what was built until then is kept, the rest is left out the way text past the
770
+ * length limit is
771
+ */
772
+ class TreeBuilder {
773
+ constructor() {
774
+ /** The depth of each node, the document at 0 */
775
+ this.depths = new WeakMap();
776
+ this.stopped = false;
777
+ this.fragmentDepth = 0;
778
+ const place = (parent, child) => {
779
+ const depth = (this.depths.get(parent) ?? 0) + 1;
780
+ if (depth > MAX_NESTING + ROOT_DEPTH) {
781
+ throw new NestingLimit();
782
+ }
783
+ this.depths.set(child, depth);
784
+ };
785
+ this.treeAdapter = {
786
+ ...parse5_htmlparser2_tree_adapter_1.adapter,
787
+ createDocumentFragment: () => {
788
+ const fragment = parse5_htmlparser2_tree_adapter_1.adapter.createDocumentFragment();
789
+ this.depths.set(fragment, this.fragmentDepth);
790
+ return fragment;
791
+ },
792
+ appendChild: (parent, child) => {
793
+ place(parent, child);
794
+ parse5_htmlparser2_tree_adapter_1.adapter.appendChild(parent, child);
795
+ },
796
+ insertBefore: (parent, child, reference) => {
797
+ place(parent, child);
798
+ parse5_htmlparser2_tree_adapter_1.adapter.insertBefore(parent, child, reference);
799
+ }
800
+ };
801
+ }
802
+ document(html) {
803
+ let document = null;
804
+ const treeAdapter = {
805
+ ...this.treeAdapter,
806
+ createDocument: () => (document = parse5_htmlparser2_tree_adapter_1.adapter.createDocument())
807
+ };
808
+ this.build(() => (0, parse5_1.parse)(html, { treeAdapter, scriptingEnabled: false }));
809
+ return document;
810
+ }
811
+ /** Parses HTML as the content of `context`, as a browser would read it there */
812
+ fragment(context, html) {
813
+ let fragment = null;
814
+ this.fragmentDepth = this.depths.get(context) ?? ROOT_DEPTH;
815
+ const treeAdapter = {
816
+ ...this.treeAdapter,
817
+ createDocumentFragment: () => {
818
+ fragment = this.treeAdapter.createDocumentFragment();
819
+ return fragment;
820
+ }
821
+ };
822
+ this.build(() => (0, parse5_1.parseFragment)(context, html, { treeAdapter, scriptingEnabled: false }));
823
+ return fragment ? [...fragment.children] : [];
824
+ }
825
+ build(run) {
826
+ try {
827
+ run();
828
+ }
829
+ catch (err) {
830
+ if (!(err instanceof NestingLimit)) {
831
+ throw err;
832
+ }
833
+ this.stopped = true;
834
+ }
835
+ }
836
+ }
837
+ // Mail clients run no scripts, so a noscript element's content is markup to them. A page around a
838
+ // message may run them, and to it the content is text: a sheet in one is read by some and not others
839
+ const SCRIPTING_DEPENDENT = 'noscript';
840
+ function gather(document, builder) {
841
+ const found = {
842
+ elements: 0,
843
+ maxDepth: 0,
844
+ sheets: [],
845
+ conditionalStyle: [],
846
+ unreadableStyle: false,
847
+ mixedCaseNames: false,
848
+ externalStyle: false,
849
+ escapedInline: false,
850
+ stylePolicy: false,
851
+ quirks: !!document['x-mode'] && document['x-mode'] !== 'no-quirks'
852
+ };
853
+ const outlookOnly = new WeakSet();
854
+ let revealed = false;
855
+ let sections = 0;
856
+ const pending = [...document.children].reverse();
857
+ while (pending.length) {
858
+ const node = pending.pop();
859
+ if (node.parent && outlookOnly.has(node.parent)) {
860
+ outlookOnly.add(node);
861
+ }
862
+ if ((0, domutils_1.isComment)(node)) {
863
+ const open = CONDITIONAL_OPEN.exec(node.data);
864
+ const rest = open ? node.data.substring(open[0].length) : '';
865
+ if (open && rest.toLowerCase().endsWith(CONDITIONAL_CLOSE) && sections++ < MAX_SECTIONS) {
866
+ const placed = placeSection(node, rest.substring(0, rest.length - CONDITIONAL_CLOSE.length), document, builder);
867
+ for (const child of placed) {
868
+ outlookOnly.add(child);
77
869
  }
78
- break;
870
+ pending.push(...placed.reverse());
871
+ }
872
+ else if (open && REVEALED_OPEN_REST.test(rest)) {
873
+ revealed = true;
874
+ }
875
+ else if (node.data.toLowerCase() === CONDITIONAL_CLOSE) {
876
+ revealed = false;
877
+ }
878
+ else if (open && /<style[\s>]/i.test(rest)) {
879
+ // a section that never closed, or one outside the body: Outlook may apply its sheets
880
+ found.conditionalStyle.push(rest);
881
+ }
882
+ continue;
883
+ }
884
+ if (!(0, domutils_1.isTag)(node)) {
885
+ continue;
886
+ }
887
+ found.elements++;
888
+ found.maxDepth = Math.max(found.maxDepth, builder.depths.get(node) ?? 0);
889
+ const attribs = node.attribs;
890
+ if (Object.values(attribs).some(value => NON_ASCII_SPACE.test(value))) {
891
+ // a browser splits a class list (and a ~= match) at ASCII whitespace only, the matcher
892
+ // here at any: a no-break space between two names is one name to a browser
893
+ found.unreadableStyle = true;
894
+ }
895
+ if (node.name === 'meta' && /^\s*content-security-policy\s*$/i.test(attribs['http-equiv'] || '')) {
896
+ // a policy can block the message's own style altogether, sheets and style attributes
897
+ found.stylePolicy = true;
898
+ }
899
+ if (node.name === 'template' && ('shadowrootmode' in attribs || 'shadowroot' in attribs)) {
900
+ // a declarative shadow root, whose own sheets outrank the document's "!important" ones
901
+ found.unreadableStyle = true;
902
+ }
903
+ if (!found.mixedCaseNames && (/[A-Z]/.test(attribs.class || '') || /[A-Z]/.test(attribs.id || ''))) {
904
+ // a class or id a quirks-mode document matches whatever the case, a standards-mode one not
905
+ found.mixedCaseNames = true;
906
+ }
907
+ if (attribs.style && (attribs.style.includes('\\') || NON_ASCII_SPACE.test(attribs.style))) {
908
+ // an escaped property name in a style attribute is one no check here decodes
909
+ found.unreadableStyle = found.escapedInline = true;
910
+ }
911
+ if (node.name === 'link' && /\bstylesheet\b/i.test(attribs.rel || '')) {
912
+ // a sheet loaded from elsewhere holds rules nothing here reads
913
+ found.unreadableStyle = found.externalStyle = true;
914
+ }
915
+ if (node.name === 'svg' || node.name === 'math') {
916
+ // foreign content: a style element in MathML is no sheet, one in SVG reads entities
917
+ found.unreadableStyle = true;
918
+ }
919
+ if (node.name === 'table' && found.quirks && insideParagraph(node)) {
920
+ // quirks mode keeps a paragraph open around a table, the page around a webmail message
921
+ // closes it, so the table and what it holds have other ancestors there
922
+ found.unreadableStyle = true;
923
+ }
924
+ if (node.name === 'style') {
925
+ gatherSheet(node, found, revealed || outlookOnly.has(node));
926
+ }
927
+ if (node.name === 'select' && node.children.some(child => (0, domutils_1.isText)(child) && mentionsHiding(child.data))) {
928
+ // a browser that parses select content anew (Chromium's customizable select) builds a
929
+ // style element there, where the parser here keeps its text
930
+ found.unreadableStyle = true;
931
+ }
932
+ if (node.name !== 'template') {
933
+ // a template's content is never rendered, its sheets included
934
+ pending.push(...[...node.children].reverse());
935
+ }
936
+ }
937
+ return found;
938
+ }
939
+ // Whether a paragraph holds the element, looking no further out than the nearest table cell, where a
940
+ // paragraph outside does not reach in
941
+ function insideParagraph(element) {
942
+ for (let ancestor = element.parent; ancestor && (0, domutils_1.isTag)(ancestor); ancestor = ancestor.parent) {
943
+ if (ancestor.name === 'p') {
944
+ return true;
945
+ }
946
+ if (ancestor.name === 'td' || ancestor.name === 'th' || ancestor.name === 'caption') {
947
+ return false;
79
948
  }
80
949
  }
81
950
  return false;
82
951
  }
83
- function isHiddenElement(node) {
84
- const attribs = node.attribs || {};
85
- const style = attribs.style || '';
86
- // the hidden attribute is a user agent rule, which an author display value overrides
87
- if ('hidden' in attribs && !/display\s*:\s*(?!none)/i.test(style.replace(STYLE_NOISE, ' '))) {
88
- return true;
952
+ // What each part of a table holds as a browser builds it
953
+ const TABLE_PART_CONTENT = {
954
+ table: new Set(['caption', 'colgroup', 'thead', 'tbody', 'tfoot', 'tr', 'script', 'style', 'template']),
955
+ thead: new Set(['tr', 'script', 'style', 'template']),
956
+ tbody: new Set(['tr', 'script', 'style', 'template']),
957
+ tfoot: new Set(['tr', 'script', 'style', 'template']),
958
+ tr: new Set(['td', 'th', 'script', 'style', 'template'])
959
+ };
960
+ function findTable(part) {
961
+ for (let node = part; node; node = node.parent && (0, domutils_1.isTag)(node.parent) ? node.parent : null) {
962
+ if (node.name === 'table') {
963
+ return node;
964
+ }
89
965
  }
90
- return isHiddenStyle(style);
966
+ return null;
967
+ }
968
+ /**
969
+ * Puts an Outlook-only section in place of its comment, parsed as a browser reads content there. A
970
+ * comment the parser kept outside the body, before the root or between the head and the body, holds
971
+ * content Outlook shows at the start of the body, or at its end when the comment came after it
972
+ *
973
+ * @returns The nodes put in place
974
+ */
975
+ function placeSection(comment, content, document, builder) {
976
+ const parent = comment.parent;
977
+ const body = (0, domutils_1.findOne)(node => node.name === 'body', document.children);
978
+ if (parent && (0, domutils_1.isTag)(parent) && parent.name !== 'html') {
979
+ const placed = builder.fragment(parent, content);
980
+ // a table part holds only the parts that belong in it; the parser moves anything else out in
981
+ // front of the table, which a fragment has none of, so that move is made here
982
+ const allowed = TABLE_PART_CONTENT[parent.name];
983
+ const table = allowed ? findTable(parent) : null;
984
+ for (const child of placed) {
985
+ if (table && (((0, domutils_1.isTag)(child) && !allowed.has(child.name)) || ((0, domutils_1.isText)(child) && /\S/.test(child.data)))) {
986
+ (0, domutils_1.prepend)(table, child);
987
+ }
988
+ else {
989
+ (0, domutils_1.prepend)(comment, child);
990
+ }
991
+ }
992
+ (0, domutils_1.removeElement)(comment);
993
+ return placed;
994
+ }
995
+ const siblings = parent ? parent.children : [];
996
+ const beforeBody = siblings.indexOf(comment) < siblings.findIndex(node => (0, domutils_1.isTag)(node) && (node.name === 'body' || node.name === 'html'));
997
+ (0, domutils_1.removeElement)(comment);
998
+ if (!body) {
999
+ return [];
1000
+ }
1001
+ const placed = builder.fragment(body, content);
1002
+ if (beforeBody) {
1003
+ for (const child of [...placed].reverse()) {
1004
+ (0, domutils_1.prependChild)(body, child);
1005
+ }
1006
+ }
1007
+ else {
1008
+ for (const child of placed) {
1009
+ (0, domutils_1.appendChild)(body, child);
1010
+ }
1011
+ }
1012
+ return placed;
1013
+ }
1014
+ function gatherSheet(sheet, found, someClients) {
1015
+ if ('type' in sheet.attribs && sheet.attribs.type !== '' && sheet.attribs.type.toLowerCase() !== 'text/css') {
1016
+ // a browser applies no sheet of another type, and compares the type exactly: "text/css "
1017
+ // is another type. Where that could matter, the sheets are not trusted
1018
+ if (mentionsHiding((0, domutils_1.textContent)(sheet))) {
1019
+ found.unreadableStyle = true;
1020
+ }
1021
+ return;
1022
+ }
1023
+ let ancestor = sheet.parent;
1024
+ while (ancestor && (0, domutils_1.isTag)(ancestor)) {
1025
+ if (ancestor.name === SCRIPTING_DEPENDENT) {
1026
+ found.unreadableStyle = true;
1027
+ }
1028
+ ancestor = ancestor.parent;
1029
+ }
1030
+ // a titled sheet is applied only when its title is the preferred one, which other titles and a
1031
+ // Default-Style setting decide, so it counts as style some clients apply
1032
+ if (someClients || (sheet.attribs.title || '').trim() || (sheet.attribs.media && !isUnconditionalQuery(sheet.attribs.media))) {
1033
+ found.conditionalStyle.push((0, domutils_1.textContent)(sheet));
1034
+ return;
1035
+ }
1036
+ found.sheets.push(sheet);
1037
+ }
1038
+ function parseDocument(html) {
1039
+ const source = (0, token_estimate_js_1.truncate)(html, MAX_HTML_LENGTH);
1040
+ const builder = new TreeBuilder();
1041
+ const document = builder.document(source);
1042
+ const found = gather(document, builder);
1043
+ return {
1044
+ document,
1045
+ ...found,
1046
+ css: found.sheets.map(sheet => (0, domutils_1.textContent)(sheet)).join('\n'),
1047
+ // the document was cut short, by the nesting limit (in a section too) or the length limit
1048
+ truncated: builder.stopped || source.length !== String(html ?? '').length
1049
+ };
91
1050
  }
92
1051
  function hasText(node) {
93
1052
  if ((0, domutils_1.isText)(node)) {
@@ -95,7 +1054,142 @@ function hasText(node) {
95
1054
  }
96
1055
  return (0, domutils_1.hasChildren)(node) && node.children.some(hasText);
97
1056
  }
98
- function stripHidden(node, stats) {
1057
+ /**
1058
+ * The declarations that apply to an element, in the order of the cascade, so the last one for a
1059
+ * property is the one that holds: the matching rules by specificity and then by their place in the
1060
+ * sheet, then the style attribute, then the "!important" declarations of the rules in the same
1061
+ * order, then those of the style attribute. Weighing them any other way would let a sender show
1062
+ * text to every reader that the summary leaves out
1063
+ *
1064
+ * @param rules - In cascade order, as readStyle() returns them
1065
+ */
1066
+ function appliedDeclarations(element, rules, inlineTrusted) {
1067
+ const matched = [];
1068
+ for (const rule of rules) {
1069
+ if (rule.test(element)) {
1070
+ matched.push(...rule.declarations);
1071
+ }
1072
+ }
1073
+ // only what the check reads, so an element styled for color and fonts alone has nothing to weigh
1074
+ const inline = inlineTrusted && element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
1075
+ if (!matched.length && !inline.some(declaration => declaration[2])) {
1076
+ return inline;
1077
+ }
1078
+ const normal = [];
1079
+ const important = [];
1080
+ for (const declaration of [...matched, ...inline]) {
1081
+ (declaration[2] ? important : normal).push(declaration);
1082
+ }
1083
+ // the rules come before the attribute in both, so this is the cascade order
1084
+ return normal.concat(important);
1085
+ }
1086
+ /**
1087
+ * The walk over the document: what it counts, the rules it tests each element against, and what it
1088
+ * learned about each element, so no element is tested twice
1089
+ */
1090
+ class Walk {
1091
+ constructor(trust) {
1092
+ this.hiddenElements = 0;
1093
+ this.invisibleCharacters = 0;
1094
+ this.appliedCache = new Map();
1095
+ this.reachCache = new Map();
1096
+ this.verticalElements = new WeakSet();
1097
+ this.trust = trust;
1098
+ }
1099
+ // Kept only for an element whose declarations were read ahead of the walk, by reach(), and
1100
+ // dropped when the walk reaches it, since no element is reached twice
1101
+ applied(element, keep) {
1102
+ const cached = this.appliedCache.get(element);
1103
+ if (cached) {
1104
+ if (!keep) {
1105
+ this.appliedCache.delete(element);
1106
+ }
1107
+ return cached;
1108
+ }
1109
+ const applied = appliedDeclarations(element, this.trust.rules, this.trust.inline);
1110
+ if (keep) {
1111
+ this.appliedCache.set(element, applied);
1112
+ }
1113
+ return applied;
1114
+ }
1115
+ // What the element or anything inside it sets that shows text an ancestor hides (see Reach).
1116
+ // One walk of each subtree, however deep the hidden ancestors are nested
1117
+ reach(element) {
1118
+ let reach = this.reachCache.get(element);
1119
+ if (!reach) {
1120
+ reach = this.insideReach(element);
1121
+ let position = '';
1122
+ for (const [property, value] of this.applied(element, true)) {
1123
+ reach.setsInherited = reach.setsInherited || INHERITED_HIDING.has(property);
1124
+ position = property === 'position' ? value : position;
1125
+ }
1126
+ // a dialog is positioned by the browser's own style, outside the box it sits in
1127
+ reach.escapes = reach.escapes || position === 'absolute' || position === 'fixed' || element.name === 'dialog';
1128
+ // a size set by the browser's own style or by an attribute: tables and form controls,
1129
+ // a font or basefont size, an SVG or MathML font-size or mathsize, and any SVG or
1130
+ // MathML element, which take sizes of their own
1131
+ reach.setsInherited =
1132
+ reach.setsInherited ||
1133
+ FONT_RESET_TAGS.has(element.name) ||
1134
+ ((element.name === 'font' || element.name === 'basefont') && 'size' in element.attribs) ||
1135
+ 'font-size' in element.attribs ||
1136
+ 'mathsize' in element.attribs ||
1137
+ (element.namespace ?? 'http://www.w3.org/1999/xhtml') !== 'http://www.w3.org/1999/xhtml';
1138
+ this.reachCache.set(element, reach);
1139
+ }
1140
+ return reach;
1141
+ }
1142
+ insideReach(element) {
1143
+ const reach = { setsInherited: false, escapes: false };
1144
+ for (const child of element.children) {
1145
+ if ((0, domutils_1.isTag)(child)) {
1146
+ const { setsInherited, escapes } = this.reach(child);
1147
+ reach.setsInherited = reach.setsInherited || setsInherited;
1148
+ reach.escapes = reach.escapes || escapes;
1149
+ if (reach.setsInherited && reach.escapes) {
1150
+ break;
1151
+ }
1152
+ }
1153
+ }
1154
+ return reach;
1155
+ }
1156
+ // Whether the element is in a vertical writing mode: its own, or the one it inherits. The walk
1157
+ // reaches a parent before its children, so the parent's is known. An "all" after the last
1158
+ // writing-mode leaves it unknown, which counts as vertical: no box is then taken as collapsed
1159
+ isVertical(element, declared) {
1160
+ let mode = null;
1161
+ for (const [property, value] of declared) {
1162
+ if (property === 'writing-mode') {
1163
+ mode = value;
1164
+ }
1165
+ else if (property === 'all') {
1166
+ mode = 'unknown';
1167
+ }
1168
+ }
1169
+ const vertical = mode === null ? !!element.parent && this.verticalElements.has(element.parent) : mode !== 'horizontal-tb';
1170
+ if (vertical) {
1171
+ this.verticalElements.add(element);
1172
+ }
1173
+ return vertical;
1174
+ }
1175
+ isHidden(element) {
1176
+ const declared = this.applied(element, false);
1177
+ const hidden = hiding(declared, element, this.trust.hiddenAttribute, this.isVertical(element, declared));
1178
+ // an element whose hiding something inside it can undo is kept when something does: what is
1179
+ // left of its own text then reaches the model, rather than text a reader sees being taken
1180
+ // from it
1181
+ if (hidden === 'inherited') {
1182
+ return this.trust.undoable && !this.insideReach(element).setsInherited;
1183
+ }
1184
+ if (hidden === 'collapsed') {
1185
+ return this.trust.undoable && !this.insideReach(element).escapes;
1186
+ }
1187
+ return hidden === 'final';
1188
+ }
1189
+ }
1190
+ // Each element is tested as the walk reaches it, so nothing under an element that was removed is
1191
+ // ever tested
1192
+ function stripHidden(node, walk) {
99
1193
  if (!(0, domutils_1.hasChildren)(node)) {
100
1194
  return;
101
1195
  }
@@ -106,7 +1200,7 @@ function stripHidden(node, stats) {
106
1200
  if ((0, domutils_1.isText)(child)) {
107
1201
  // before the conversion, which would turn a zero-width space into a plain one
108
1202
  const cleaned = child.data.replace(INVISIBLE_CHARS, '');
109
- stats.invisibleCharacters += child.data.length - cleaned.length;
1203
+ walk.invisibleCharacters += child.data.length - cleaned.length;
110
1204
  child.data = cleaned;
111
1205
  return true;
112
1206
  }
@@ -116,17 +1210,17 @@ function stripHidden(node, stats) {
116
1210
  if (HIDDEN_TAGS.has(child.name)) {
117
1211
  return false;
118
1212
  }
119
- if (isHiddenElement(child)) {
1213
+ if (walk.isHidden(child)) {
120
1214
  // a layout element with no text in it is not hidden content, only a spacer
121
1215
  if (hasText(child)) {
122
- stats.hiddenElements++;
1216
+ walk.hiddenElements++;
123
1217
  }
124
1218
  return false;
125
1219
  }
126
1220
  return true;
127
1221
  });
128
1222
  for (const child of node.children) {
129
- stripHidden(child, stats);
1223
+ stripHidden(child, walk);
130
1224
  }
131
1225
  }
132
1226
  // What the reader takes as the link: its text, and the alt and title of an image standing in
@@ -142,38 +1236,98 @@ function collectLinks(document) {
142
1236
  const targets = (0, domutils_1.findAll)(node => ((node.name === 'a' || node.name === 'area') && !!node.attribs.href) || (node.name === 'form' && !!node.attribs.action), document.children);
143
1237
  return targets.map(node => ({ href: node.attribs.href || node.attribs.action, text: linkText(node) }));
144
1238
  }
145
- // A browser shows flow content a message put inside <head>, the converter reads only <body>:
146
- // what is left of the head after the metadata went moves to the front of the body
147
- function surfaceHead(document) {
148
- const head = (0, domutils_1.findOne)(node => node.name === 'head', document.children);
149
- if (!head) {
150
- return;
151
- }
152
- const body = (0, domutils_1.findOne)(node => node.name === 'body', document.children);
153
- if (!body) {
154
- head.name = 'div';
155
- return;
1239
+ // The elements the text converter's own parser reads as raw text whatever their namespace, beside
1240
+ // script, style and title, which never reach it (HIDDEN_TAGS). Plaintext is read as raw text by a
1241
+ // browser and written out raw by the serializer
1242
+ const RAW_TEXT_NAMES = new Set(['textarea', 'xmp', 'plaintext']);
1243
+ // The elements the serializer and the converter's parser disagree about being void. The serializer
1244
+ // writes a bgsound with no end tag, which the converter keeps open over what follows it; a parse5
1245
+ // command or isindex is an ordinary element the converter would close at once
1246
+ const VOID_TO_PARSER_ONLY = 'bgsound';
1247
+ const VOID_TO_CONVERTER_ONLY = new Set(['command', 'isindex', 'image']);
1248
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
1249
+ /**
1250
+ * Renames what the text converter's own parser would build otherwise than the tree here, so the
1251
+ * document it reads is this one. That parser goes by element name, not namespace:
1252
+ * - it reads textarea and xmp as raw text, so "</textarea><!--" in the text of an xmp inside a
1253
+ * MathML or SVG textarea ended the textarea there and opened a comment over the rest of the
1254
+ * message. In HTML they become a pre, which shows text as written as they do, so every "<" in
1255
+ * text reaches the converter escaped
1256
+ * - it applies the HTML rules of which tag closes which to SVG and MathML elements too, so a
1257
+ * foreign td inside a foreign td closed the real table cell around them, and the converter left
1258
+ * out the rest of the cell. Every element outside HTML becomes a span, which no rule closes;
1259
+ * the serializer writes no self-closing tag and no CDATA, the only things the converter reads
1260
+ * otherwise inside foreign content
1261
+ * - it writes a table out from its cells only, so a caption moves out in front of its table
1262
+ * - it and the serializer disagree about which elements are void (see VOID_TO_PARSER_ONLY): an
1263
+ * Outlook-only bgsound in a table, written with no end tag, held the rest of the table open
1264
+ */
1265
+ function neutralizeForConverter(root) {
1266
+ // a cell span the converter cannot lay out: a negative colspan left the cell out of the table,
1267
+ // and a negative rowspan walks its layout backwards
1268
+ for (const cell of (0, domutils_1.findAll)(node => node.name === 'td' || node.name === 'th', root.children)) {
1269
+ for (const span of ['colspan', 'rowspan']) {
1270
+ if (span in cell.attribs && !/^\s*[1-9]\d{0,3}\s*$/.test(cell.attribs[span])) {
1271
+ delete cell.attribs[span];
1272
+ }
1273
+ }
156
1274
  }
157
- for (const child of head.children.slice().reverse()) {
158
- (0, domutils_1.prependChild)(body, child);
1275
+ const affected = (0, domutils_1.findAll)(node => RAW_TEXT_NAMES.has(node.name) ||
1276
+ node.name === 'caption' ||
1277
+ node.name === VOID_TO_PARSER_ONLY ||
1278
+ VOID_TO_CONVERTER_ONLY.has(node.name) ||
1279
+ (node.namespace ?? HTML_NAMESPACE) !== HTML_NAMESPACE, root.children);
1280
+ for (const element of affected) {
1281
+ if (element.name === VOID_TO_PARSER_ONLY) {
1282
+ // a void element, which never shows text
1283
+ (0, domutils_1.removeElement)(element);
1284
+ }
1285
+ else if ((element.namespace ?? HTML_NAMESPACE) !== HTML_NAMESPACE || VOID_TO_CONVERTER_ONLY.has(element.name)) {
1286
+ element.name = 'span';
1287
+ }
1288
+ else if (element.name === 'caption') {
1289
+ // the converter writes a table out from its cells and leaves a caption out; a reader
1290
+ // sees it above the table, where it goes as a block
1291
+ element.name = 'div';
1292
+ const table = element.parent;
1293
+ if (table && (0, domutils_1.isTag)(table)) {
1294
+ (0, domutils_1.removeElement)(element);
1295
+ (0, domutils_1.prepend)(table, element);
1296
+ }
1297
+ }
1298
+ else {
1299
+ element.name = 'pre';
1300
+ }
159
1301
  }
160
- (0, domutils_1.removeElement)(head);
161
1302
  }
162
1303
  /**
163
1304
  * Parses an HTML message once: every link it carries, for the checks, and the document as the
164
1305
  * reader sees it, for the model
165
1306
  */
166
1307
  function visibleHtml(html) {
167
- const document = (0, htmlparser2_1.parseDocument)((0, token_estimate_js_1.truncate)(html, MAX_HTML_LENGTH).replace(CONDITIONAL_COMMENT, ''));
1308
+ const parsed = parseDocument(html);
1309
+ const { document } = parsed;
168
1310
  const links = collectLinks(document);
169
- const stats = { hiddenElements: 0, invisibleCharacters: 0 };
170
- stripHidden(document, stats);
171
- surfaceHead(document);
172
- return { links, hiddenElements: stats.hiddenElements, invisibleCharacters: stats.invisibleCharacters, html: () => (0, dom_serializer_1.default)(document) };
1311
+ // the rules are read before the style elements go with everything else that is not rendered
1312
+ const walk = new Walk(readStyle(parsed));
1313
+ stripHidden(document, walk);
1314
+ neutralizeForConverter(document);
1315
+ // the parser builds a head and a body around any message, and moves what a browser shows out of
1316
+ // the head; the converter reads the body. Written out by the parser's own serializer, which
1317
+ // escapes text by namespace: a serializer that goes by name writes the text of a MathML or SVG
1318
+ // element called "xmp" raw, and the converter's parser then reads its decoded entities as
1319
+ // markup that can open a comment over the rest of the message. Scripting is off there as in
1320
+ // the parse, so a noscript element's content is written out as the markup it was read as
1321
+ const body = (0, domutils_1.findOne)(node => node.name === 'body', document.children) ?? document;
1322
+ return {
1323
+ links,
1324
+ hiddenElements: walk.hiddenElements,
1325
+ invisibleCharacters: walk.invisibleCharacters,
1326
+ html: () => (0, parse5_1.serialize)(body, { treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter, scriptingEnabled: false })
1327
+ };
173
1328
  }
174
1329
  /**
175
1330
  * Removes the characters that take no space on screen
176
- *
177
1331
  */
178
1332
  function visibleText(input) {
179
1333
  const text = String(input ?? '');