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