@postalsys/email-ai-tools 3.0.5 → 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,13 +1,10 @@
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
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");
11
8
  const css_select_1 = require("css-select");
12
9
  const css_what_1 = require("css-what");
13
10
  const domutils_1 = require("domutils");
@@ -16,12 +13,10 @@ const token_estimate_js_1 = require("./token-estimate.js");
16
13
  // for an AI in text a mail client does not render, and the summary has to describe the message
17
14
  // as it looks to the person it was sent to. The links are collected before anything is removed,
18
15
  // because the checks run on them must see every link the message carries, hidden or not
19
- // Elements a browser reads as raw text, or as markup depending on whether scripts run, where the
20
- // parser here builds elements: a style element inside one is text to a mail client and a sheet
21
- // here, or the other way round. A sheet in one makes the sheets unreadable (see gatherStyle())
22
- const RAW_TEXT_IN_BROWSER = new Set(['noframes', 'noembed', 'iframe', 'plaintext', 'noscript', 'xmp', 'textarea', 'title']);
23
- // Elements whose content is never rendered as text
24
- const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed']);
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']);
25
20
  // Everything here runs synchronously in the process that called it, so how much of a message is
26
21
  // read has to be this library's decision rather than the sender's. The HTML is cut before it is
27
22
  // parsed; the text of a link is cut to what a reader could take in as its destination
@@ -35,13 +30,16 @@ exports.MAX_LINK_TEXT_LENGTH = MAX_LINK_TEXT_LENGTH;
35
30
  const MAX_STYLE_LENGTH = 128 * 1024;
36
31
  const MAX_HIDING_RULES = 100;
37
32
  const MAX_SELECTOR_LENGTH = 512;
38
- // How deep elements may nest before the rest of the document is left out. The parser's work grows
39
- // with the square of the depth and every walk over the document recurses: a megabyte of nothing but
40
- // opening tags took the parser and the link scan more than ten seconds, and then overflowed the
41
- // stack. Real mail nests a few dozen levels, a layout of tables in tables a hundred or two. The
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
42
36
  // HTML to text converter reads no deeper than this either, so nothing it would have shown is lost
43
37
  const MAX_NESTING = 500;
44
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;
45
43
  // The work the hiding rules may cost, as tests of a selector against an element, a descendant
46
44
  // combinator counting once for every level it may have to climb. Ten million such tests take about
47
45
  // half a second; ordinary mail, a few thousand elements and a few dozen rules, stays far below it.
@@ -53,12 +51,15 @@ const RULE_WORK_BUDGET = 10_000_000;
53
51
  // sets anything the hiding check reads, no sheet is trusted (see sheetRules())
54
52
  const ALWAYS_MIN_WIDTH = 320;
55
53
  const ALWAYS_MAX_WIDTH = 4000;
56
- // The start of an Outlook conditional comment's text, "[if mso]>" and the like. The condition is
57
- // bounded, so a comment that only starts like one is not scanned for its end
58
- const CONDITIONAL_OPEN = /^\[if [^\]]{0,200}\]>/i;
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;
59
57
  // What is left of a downlevel-revealed opener, "<!--[if !mso]><!-->" or "<!--[if !mso]><!-- -->"
60
58
  const REVEALED_OPEN_REST = /^<!(?:--\s*)?$/;
61
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]/;
62
63
  // Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
63
64
  // bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
64
65
  // stops them splitting words the model should recognise or reordering text it should read
@@ -82,11 +83,16 @@ function skipNoise(text, i) {
82
83
  else if (text[j] === quote) {
83
84
  return j + 1;
84
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
+ }
85
90
  }
86
91
  return text.length;
87
92
  }
88
- // The text with each comment, and each quoted string unless `keepStrings`, replaced by a space, in
89
- // one pass. A declaration carries no strings worth reading, a selector does
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
90
96
  function withoutNoise(input, keepStrings) {
91
97
  let output = '';
92
98
  let from = 0;
@@ -99,22 +105,13 @@ function withoutNoise(input, keepStrings) {
99
105
  i = end;
100
106
  }
101
107
  else {
102
- output += `${input.substring(from, i)} `;
108
+ // ".a/**/.b" is ".a.b" in a selector
109
+ output += input.substring(from, i) + (keepStrings ? '' : ' ');
103
110
  i = from = end;
104
111
  }
105
112
  }
106
113
  return output + input.substring(from);
107
114
  }
108
- function declarations(input) {
109
- const list = [];
110
- for (const declaration of withoutNoise(input, false).split(';')) {
111
- const match = /^\s*([a-z-]+)\s*:\s*([^!]*)(!\s*important)?/i.exec(declaration);
112
- if (match) {
113
- list.push([match[1].toLowerCase(), match[2].trim().toLowerCase(), !!match[3]]);
114
- }
115
- }
116
- return list;
117
- }
118
115
  // The properties the hiding check reads. A style sheet rule that sets none of them cannot hide an
119
116
  // element or show one again, so it is not matched at all
120
117
  // Vertical padding, which a box of no height still shows (see isCollapsed())
@@ -124,12 +121,29 @@ const HIDING_PROPERTIES = new Set([
124
121
  'visibility',
125
122
  'opacity',
126
123
  'font-size',
127
- 'text-indent',
128
124
  'height',
129
125
  'max-height',
130
126
  'min-height',
131
127
  'overflow',
132
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',
133
147
  ...PADDING_PROPERTIES
134
148
  ]);
135
149
  // The same properties found in raw style text, for style that is not read rule by rule
@@ -137,67 +151,193 @@ const HIDING_IN_TEXT = new RegExp(`(?:^|[{;\\s"'])(?:${[...HIDING_PROPERTIES].jo
137
151
  // Whether style text nothing here reads rule by rule sets what the hiding check reads. A backslash
138
152
  // counts too: CSS allows escapes in a property name, which no check here decodes
139
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
+ }
140
229
  // The hiding properties an element inside can set again: they are inherited, so text inside an
141
- // element that is hidden by one of them shows when something inside it sets the property itself
142
- const INHERITED_HIDING = new Set(['visibility', 'font-size', 'text-indent']);
143
- // Elements a height of zero does not collapse: inline elements ignore height, and a table and its
144
- // rows and cells grow to fit what they hold
145
- const UNCOLLAPSIBLE_TAGS = new Set([
146
- 'a',
147
- 'abbr',
148
- 'b',
149
- 'bdi',
150
- 'bdo',
151
- 'big',
152
- 'cite',
153
- 'code',
154
- 'dfn',
155
- 'em',
156
- 'font',
157
- 'i',
158
- 'kbd',
159
- 'label',
160
- 'mark',
161
- 'q',
162
- 's',
163
- 'samp',
164
- 'small',
165
- 'span',
166
- 'strike',
167
- 'strong',
168
- 'sub',
169
- 'sup',
170
- 'time',
171
- 'tt',
172
- 'u',
173
- 'var',
174
- 'table',
175
- 'thead',
176
- 'tbody',
177
- 'tfoot',
178
- 'tr',
179
- 'td',
180
- 'th',
181
- 'caption'
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'
182
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']);
183
280
  const BLOCK_DISPLAYS = new Set(['block', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'list-item', 'flow-root']);
184
- const isClipped = (value) => value === 'hidden' || value === 'clip';
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
+ ];
185
297
  // A length of zero that holds whatever the box sits in. A percentage is resolved against the parent
186
298
  // and becomes auto when the parent's height is, which is the usual case
187
- const isAbsoluteZero = (value) => /^0(?:\.0*)?(?:px|pt|pc|em|rem|ex|ch|cm|mm|in|q|vh|vw|vmin|vmax)?$/.test(value || '');
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
+ }
188
320
  /**
189
321
  * Whether a box of no height clips everything in it: the preheader trick. Only where it holds for
190
- * every reader, so a block-level box, an absolute zero, nothing that sets a minimum height again, no
191
- * vertical padding (overflow clips at the padding edge, so text shows in the padding) and a clipped
192
- * overflow
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
193
325
  */
194
- function isCollapsed(style, element) {
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)) {
333
+ return false;
334
+ }
195
335
  const display = style.get('display');
196
- const blockLevel = display ? BLOCK_DISPLAYS.has(display) : !UNCOLLAPSIBLE_TAGS.has(element.name);
336
+ const blockLevel = display ? BLOCK_DISPLAYS.has(display) : BLOCK_TAGS.has(element.name);
197
337
  if (!blockLevel || !(isAbsoluteZero(style.get('height')) || isAbsoluteZero(style.get('max-height')))) {
198
338
  return false;
199
339
  }
200
- if (style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) {
340
+ if ((style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) || COLLAPSE_UNDOING.some(property => style.has(property))) {
201
341
  return false;
202
342
  }
203
343
  for (const property of PADDING_PROPERTIES) {
@@ -205,40 +345,120 @@ function isCollapsed(style, element) {
205
345
  return false;
206
346
  }
207
347
  }
208
- return isClipped(style.get('overflow')) || isClipped(style.get('overflow-y'));
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') {
396
+ continue;
397
+ }
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);
209
428
  }
210
429
  /**
211
430
  * How an element is hidden by what applies to it, the last value for a property winning (see
212
431
  * appliedDeclarations() for the order). "final" when nothing inside it can show text again: no
213
- * display, the hidden attribute, an opacity a child's own can only lower further, a collapsed box.
214
- * "inherited" when it is hidden by visibility, a font size below a pixel or a far negative text
215
- * indent, which an element inside can set again. Only what reliably hides text for every reader
216
- * counts: negative positions and colors depend on other properties, so they are left alone rather
217
- * than dropping text the reader sees
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
218
438
  */
219
- function hiding(applied, element) {
220
- const hiddenAttribute = 'hidden' in element.attribs;
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;
221
445
  if (!applied.length) {
222
446
  // most elements: no rule matched and no style attribute
223
447
  return hiddenAttribute ? 'final' : '';
224
448
  }
225
449
  const style = new Map(applied.map(([property, value]) => [property, value]));
226
450
  const value = (property) => style.get(property) || '';
227
- const number = (property) => parseFloat(value(property));
228
451
  if (value('display') === 'none' ||
229
452
  // the hidden attribute is a user agent rule, which an author display value overrides
230
453
  (hiddenAttribute && !style.has('display')) ||
231
- number('opacity') < 0.1 ||
232
- isCollapsed(style, element)) {
454
+ // a display:contents element draws no box, and its opacity hides nothing
455
+ (/^(?:0+(?:\.0+)?|\.0+)%?$/.test(value('opacity')) && value('display') !== 'contents')) {
233
456
  return 'final';
234
457
  }
235
- // zero in any unit, or below one pixel
236
- const fontSize = number('font-size');
237
- if (value('visibility') === 'hidden' ||
238
- value('visibility') === 'collapse' ||
239
- fontSize === 0 ||
240
- (fontSize < 1 && /^[\d.]+(?:px|pt)?$/.test(value('font-size'))) ||
241
- number('text-indent') <= -1000) {
458
+ if (isCollapsed(applied, style, element, vertical)) {
459
+ return 'collapsed';
460
+ }
461
+ if (value('visibility') === 'hidden' || value('visibility') === 'collapse' || isHidingFontSize(fontSize(applied))) {
242
462
  return 'inherited';
243
463
  }
244
464
  return '';
@@ -300,12 +520,14 @@ function blockEnd(css, start) {
300
520
  * @returns The rules in sheet order, each with only the declarations the check reads
301
521
  */
302
522
  function sheetRules(css) {
303
- if (css.includes('\\')) {
523
+ if (css.includes('\\') || NON_ASCII_SPACE.test(css)) {
304
524
  // an escape in a property name or a selector is one no check here decodes
305
525
  return null;
306
526
  }
307
527
  const rules = [];
308
528
  let start = 0;
529
+ // the unconditional media blocks entered, whose "}" ends them
530
+ let entered = 0;
309
531
  for (let i = 0; i < css.length;) {
310
532
  const end = skipNoise(css, i);
311
533
  if (end !== i) {
@@ -314,11 +536,20 @@ function sheetRules(css) {
314
536
  }
315
537
  const char = css[i];
316
538
  if (char === ';' || char === '}') {
317
- // the end of a statement, or of a media block that was entered. A sheet another one
318
- // imports holds rules nothing here reads
319
- if (/^\s*@import\b/i.test(css.substring(start, i))) {
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))) {
320
548
  return null;
321
549
  }
550
+ if (char === '}') {
551
+ entered--;
552
+ }
322
553
  start = ++i;
323
554
  continue;
324
555
  }
@@ -330,6 +561,7 @@ function sheetRules(css) {
330
561
  const media = /^@media\s+(.+)$/i.exec(prelude);
331
562
  if (media && isUnconditionalQuery(media[1])) {
332
563
  // entered, so that its rules are read next
564
+ entered++;
333
565
  i = start = i + 1;
334
566
  continue;
335
567
  }
@@ -343,6 +575,10 @@ function sheetRules(css) {
343
575
  }
344
576
  continue;
345
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
+ }
346
582
  const found = declarations(block).filter(([property]) => HIDING_PROPERTIES.has(property));
347
583
  if (prelude && found.length) {
348
584
  if (rules.length >= MAX_HIDING_RULES) {
@@ -358,15 +594,17 @@ function sheetRules(css) {
358
594
  // a long list of them, and :has() recurses as deep as the document goes. The sibling combinators
359
595
  // scan the siblings before an element for every element tested, so they are left out too
360
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';
361
599
  const isRoot = (token) => !!token && token.type === 'tag' && (token.name === 'html' || token.name === 'body');
362
600
  /**
363
601
  * The selector as the matcher reads it, or null for one it cannot match as a mail client does: the
364
602
  * same parse decides what is allowed, what it costs and what is compiled, so the three cannot
365
- * disagree. "html > ..." and "body > ..." are refused too: the parser builds neither around a
366
- * fragment, so what is a child of the root there cannot be told
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
367
605
  */
368
606
  function matchableSelector(selector) {
369
- if (selector.length > MAX_SELECTOR_LENGTH) {
607
+ if (selector.length > MAX_SELECTOR_LENGTH || !validSelectorText(selector)) {
370
608
  return null;
371
609
  }
372
610
  let parsed;
@@ -379,6 +617,28 @@ function matchableSelector(selector) {
379
617
  const matchable = (part) => part.every(token => MATCHABLE_TOKENS.has(token.type)) && !part.some((token, i) => isRoot(token) && part[i + 1]?.type === 'child');
380
618
  return parsed.every(matchable) ? parsed : null;
381
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
+ }
382
642
  /**
383
643
  * What testing one part of a selector list against one element may cost, in tests: the depth of
384
644
  * the document for every descendant combinator in it, since each one climbs the ancestors of the
@@ -398,7 +658,7 @@ function specificity(part) {
398
658
  if (token.type === 'attribute') {
399
659
  // "#p" is an id selector, "[id=p]" an attribute selector that weighs like a class: the
400
660
  // parser gives both the same token and marks only the shorthand with quirks-mode case
401
- value += token.name === 'id' && token.action === 'equals' && token.ignoreCase === 'quirks' ? 1_000_000 : 1000;
661
+ value += isQuirksName(token) && token.name === 'id' && token.action === 'equals' ? 1_000_000 : 1000;
402
662
  }
403
663
  else if (token.type === 'tag') {
404
664
  value += 1;
@@ -407,17 +667,24 @@ function specificity(part) {
407
667
  return value;
408
668
  }
409
669
  /**
410
- * A part without a leading "html" or "body" before a descendant combinator. A browser builds both
411
- * around any fragment, the parser builds only what the message wrote, so "body p" would match
412
- * nothing in a message without a body element where a mail client matches every paragraph. Before
413
- * a descendant combinator the two match the same elements anywhere in the document
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
414
675
  */
415
- function withoutImpliedRoot(part) {
416
- let start = 0;
417
- while (start + 2 < part.length && isRoot(part[start]) && part[start + 1].type === 'descendant') {
418
- start += 2;
419
- }
420
- return start ? part.slice(start) : part;
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
+ };
421
688
  }
422
689
  /**
423
690
  * Compiles the rules of the message's own style sheets that the hiding check reads, one entry for
@@ -427,27 +694,34 @@ function withoutImpliedRoot(part) {
427
694
  * unread: leaving out one rule could leave out the one that shows text again, and then text every
428
695
  * reader sees would be taken from the model. Each early return below is one way that happens
429
696
  */
430
- function hidingRules(parsed) {
431
- // the document was cut short, by the length or the nesting limit, so a sheet may follow unread
432
- if (parsed.truncated) {
433
- return [];
434
- }
435
- // a linked sheet, or an escaped property name in a style attribute
436
- if (parsed.unreadableStyle) {
437
- return [];
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 };
438
702
  }
439
- // a sheet one client applies and another does not: in a conditional comment, or for some media
440
- if (parsed.conditionalStyle.some(mentionsHiding)) {
441
- return [];
442
- }
443
- // more style than is read
444
- if (parsed.css.length > MAX_STYLE_LENGTH) {
445
- return [];
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);
446
714
  }
447
- // an at-rule, an @import, an escape or more rules than are read (see sheetRules())
448
- const read = sheetRules(parsed.css);
449
- if (!read) {
450
- return [];
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);
451
725
  }
452
726
  const rules = [];
453
727
  let work = 0;
@@ -455,209 +729,323 @@ function hidingRules(parsed) {
455
729
  // a selector that cannot be matched as a mail client matches it
456
730
  const matchable = matchableSelector(selector);
457
731
  if (!matchable) {
458
- return [];
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);
459
741
  }
460
742
  // or more work than matching is allowed
461
743
  work += parsed.elements * matchable.reduce((sum, part) => sum + selectorCost(part, parsed.maxDepth), 0);
462
744
  if (work > RULE_WORK_BUDGET) {
463
- return [];
745
+ return unread(parsed);
464
746
  }
465
747
  for (const part of matchable) {
466
- // weighed as written, matched without the root the parser did not build
467
- rules.push({ test: (0, css_select_1.compile)([withoutImpliedRoot(part)]), declarations, specificity: specificity(part), order });
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 });
468
757
  }
469
758
  }
470
- return rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
759
+ return { rules: rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order), inline: true, hiddenAttribute: true, undoable: true };
471
760
  }
472
- // Builds the document as the parser reads it and stops reading once an element opens deeper than
473
- // MAX_NESTING: the parser stack, and with it the cost of every element that follows, stays bounded.
474
- // What was read until then is kept, the rest is left out the way text past the length limit is.
475
- // The count follows the parser's own events, which close the elements it closes on its own too. The
476
- // handler also gathers what the hiding rules need to know, so that takes no walk of its own
477
- class NestingLimitHandler extends htmlparser2_1.DomHandler {
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 {
478
773
  constructor() {
479
- super(...arguments);
480
- this.elements = 0;
481
- this.maxDepth = 0;
482
- this.sheets = [];
483
- /** The style elements for some readers only (a media attribute that does not hold for all) */
484
- this.conditionalSheets = [];
485
- /** Something applies styles that cannot be read here */
486
- this.unreadableStyle = false;
487
- /** The parser stopped before the end of the document */
774
+ /** The depth of each node, the document at 0 */
775
+ this.depths = new WeakMap();
488
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;
489
810
  }
490
- onparserinit(parser) {
491
- super.onparserinit(parser);
492
- this.reader = parser;
493
- }
494
- onopentag(name, attribs) {
495
- super.onopentag(name, attribs);
496
- // the stack starts with the document itself
497
- const depth = this.tagStack.length - 1;
498
- this.elements++;
499
- this.maxDepth = Math.max(this.maxDepth, depth);
500
- this.gatherStyle(name, attribs);
501
- if (depth > MAX_NESTING) {
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
+ }
502
833
  this.stopped = true;
503
- this.reader.pause();
504
834
  }
505
835
  }
506
- // A browser ends a comment at "--!>" and a CDATA section, which HTML has not, at the first ">",
507
- // where the parser here reads on to "-->" and "]]>": a style element between the two ends is a
508
- // sheet to a mail client and comment text here
509
- oncomment(data) {
510
- super.oncomment(data);
511
- if (data.includes('--!>') || (data.startsWith('[CDATA[') && data.includes('>'))) {
512
- this.unreadableStyle = true;
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);
513
861
  }
514
- }
515
- gatherStyle(name, attribs) {
516
- // an escaped property name in a style attribute is one no check here decodes
517
- if (attribs.style && attribs.style.includes('\\')) {
518
- this.unreadableStyle = true;
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);
869
+ }
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;
519
883
  }
520
- if (name === 'link' && /\bstylesheet\b/i.test(attribs.rel || '')) {
521
- // a sheet loaded from elsewhere holds rules nothing here reads
522
- this.unreadableStyle = true;
884
+ if (!(0, domutils_1.isTag)(node)) {
885
+ continue;
523
886
  }
524
- if (name === 'plaintext') {
525
- // a browser reads everything after it as text, sheets included
526
- this.unreadableStyle = true;
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;
527
914
  }
528
- if (name === 'svg' || name === 'math') {
529
- // a browser parses foreign content by other rules than the parser here: a style element
530
- // in MathML is no sheet, one in SVG decodes entities and comments, and title or script
531
- // in SVG hold markup rather than text
532
- this.unreadableStyle = true;
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;
533
918
  }
534
- if (name !== 'style' || (attribs.type && attribs.type.trim().toLowerCase() !== 'text/css')) {
535
- // a browser applies no sheet of another type
536
- return;
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;
537
923
  }
538
- const sheet = this.tagStack[this.tagStack.length - 1];
539
- const ancestors = this.tagStack.slice(1, -1);
540
- if (ancestors.some(element => element.name === 'template')) {
541
- // never rendered, so never applied
542
- return;
924
+ if (node.name === 'style') {
925
+ gatherSheet(node, found, revealed || outlookOnly.has(node));
543
926
  }
544
- if (ancestors.some(element => RAW_TEXT_IN_BROWSER.has(element.name))) {
545
- this.unreadableStyle = true;
546
- return;
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;
547
931
  }
548
- if (attribs.media && !isUnconditionalQuery(attribs.media)) {
549
- // applied to some readers only, which counts once its text is known (hidingRules())
550
- this.conditionalSheets.push(sheet);
551
- return;
932
+ if (node.name !== 'template') {
933
+ // a template's content is never rendered, its sheets included
934
+ pending.push(...[...node.children].reverse());
552
935
  }
553
- this.sheets.push(sheet);
554
936
  }
937
+ return found;
555
938
  }
556
- /**
557
- * Where each comment ends, found the way a browser finds it: at the first "-->" or "--!>", with
558
- * "<!-->" and "<!--->" empty comments and one that never ends running to the end. The two endings
559
- * are searched for once each and reused while they lie ahead, so the scan stays linear however many
560
- * comments there are
561
- */
562
- class CommentScanner {
563
- constructor(html) {
564
- this.html = html;
565
- }
566
- next(token, cached, from) {
567
- return cached !== undefined && (cached < 0 || cached >= from) ? cached : this.html.indexOf(token, from);
568
- }
569
- /** The comment opening at `start` ("<!--"): where its text starts and ends, and where it ends */
570
- comment(start) {
571
- const dataStart = start + 4;
572
- for (const empty of ['>', '->']) {
573
- if (this.html.startsWith(empty, dataStart)) {
574
- return { dataStart, dataEnd: dataStart, end: dataStart + empty.length };
575
- }
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;
576
945
  }
577
- const dash = (this.dash = this.next('-->', this.dash, dataStart));
578
- const bang = (this.bang = this.next('--!>', this.bang, dataStart));
579
- if (bang >= 0 && (dash < 0 || bang < dash)) {
580
- return { dataStart, dataEnd: bang, end: bang + 4 };
946
+ if (ancestor.name === 'td' || ancestor.name === 'th' || ancestor.name === 'caption') {
947
+ return false;
581
948
  }
582
- if (dash >= 0) {
583
- return { dataStart, dataEnd: dash, end: dash + 3 };
949
+ }
950
+ return false;
951
+ }
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;
584
964
  }
585
- return { dataStart, dataEnd: this.html.length, end: this.html.length };
586
965
  }
966
+ return null;
587
967
  }
588
968
  /**
589
- * Reads Outlook's conditional comments as the clients that show the message do, and collects the
590
- * parts only some of them apply:
591
- * - "<!--[if mso]>...<![endif]-->" is one comment to every client but Outlook for Windows, which
592
- * shows what it wraps. That content is kept, as it always was, so Outlook-only text is read too
593
- * - "<!--[if !mso]><!-->...<!--<![endif]-->" is two comments around content every client but
594
- * Outlook shows. The two comments stay comments and the content stays where it is
595
- * - every other comment is left for the parser, ended where a browser ends it
596
- * Removing the markers piece by piece used to leave a bare "<!--" behind the revealed closer, which
597
- * the parser read as a comment running over the rest of the message: the pattern email builders
598
- * write in every message, and all of it past the first such section was left out
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
599
972
  *
600
- * @returns The HTML, and the text of each conditional section that holds a style element: Outlook
601
- * applies such a sheet and the other clients do not, or the other way round
973
+ * @returns The nodes put in place
602
974
  */
603
- function stripConditionalComments(html) {
604
- const scanner = new CommentScanner(html);
605
- const styled = [];
606
- const collect = (section) => {
607
- if (/<style[\s>]/i.test(section)) {
608
- styled.push(section);
609
- }
610
- };
611
- let output = '';
612
- let from = 0;
613
- let revealed = -1;
614
- for (let start = html.indexOf('<!--'); start >= 0; start = html.indexOf('<!--', from)) {
615
- const { dataStart, dataEnd, end } = scanner.comment(start);
616
- const data = html.substring(dataStart, dataEnd);
617
- const open = CONDITIONAL_OPEN.exec(data);
618
- const rest = open ? data.substring(open[0].length) : '';
619
- if (open && rest.toLowerCase().endsWith(CONDITIONAL_CLOSE)) {
620
- // Outlook-only content, kept without its markers
621
- const content = rest.substring(0, rest.length - CONDITIONAL_CLOSE.length);
622
- collect(content);
623
- output += html.substring(from, start) + content;
624
- }
625
- else {
626
- if (open && REVEALED_OPEN_REST.test(rest)) {
627
- revealed = end;
628
- }
629
- else if (data.toLowerCase() === CONDITIONAL_CLOSE && revealed >= 0) {
630
- collect(html.substring(revealed, start));
631
- revealed = -1;
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);
632
987
  }
633
- else if (open && end === html.length) {
634
- // one that never closes is a comment to the end everywhere but in Outlook
635
- collect(rest);
988
+ else {
989
+ (0, domutils_1.prepend)(comment, child);
636
990
  }
637
- // a comment to every client, written so the parser ends it where a browser does: the
638
- // parser here reads on past "--!>" to the next "-->"
639
- output += `${html.substring(from, start)}<!--${data}-->`;
640
991
  }
641
- from = end;
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
+ }
642
1006
  }
643
- if (revealed >= 0) {
644
- collect(html.substring(revealed));
1007
+ else {
1008
+ for (const child of placed) {
1009
+ (0, domutils_1.appendChild)(body, child);
1010
+ }
645
1011
  }
646
- return { html: output + html.substring(from), styled };
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);
647
1037
  }
648
1038
  function parseDocument(html) {
649
1039
  const source = (0, token_estimate_js_1.truncate)(html, MAX_HTML_LENGTH);
650
- const { html: markup, styled } = stripConditionalComments(source);
651
- const handler = new NestingLimitHandler();
652
- new htmlparser2_1.Parser(handler).end(markup);
1040
+ const builder = new TreeBuilder();
1041
+ const document = builder.document(source);
1042
+ const found = gather(document, builder);
653
1043
  return {
654
- document: handler.root,
655
- elements: handler.elements,
656
- maxDepth: handler.maxDepth,
657
- css: handler.sheets.map(sheet => (0, domutils_1.textContent)(sheet)).join('\n'),
658
- conditionalStyle: styled.concat(handler.conditionalSheets.map(sheet => (0, domutils_1.textContent)(sheet))),
659
- unreadableStyle: handler.unreadableStyle,
660
- truncated: handler.stopped || source.length !== String(html ?? '').length
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
661
1049
  };
662
1050
  }
663
1051
  function hasText(node) {
@@ -673,9 +1061,9 @@ function hasText(node) {
673
1061
  * order, then those of the style attribute. Weighing them any other way would let a sender show
674
1062
  * text to every reader that the summary leaves out
675
1063
  *
676
- * @param rules - In cascade order, as hidingRules() returns them
1064
+ * @param rules - In cascade order, as readStyle() returns them
677
1065
  */
678
- function appliedDeclarations(element, rules) {
1066
+ function appliedDeclarations(element, rules, inlineTrusted) {
679
1067
  const matched = [];
680
1068
  for (const rule of rules) {
681
1069
  if (rule.test(element)) {
@@ -683,7 +1071,7 @@ function appliedDeclarations(element, rules) {
683
1071
  }
684
1072
  }
685
1073
  // only what the check reads, so an element styled for color and fonts alone has nothing to weigh
686
- const inline = element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
1074
+ const inline = inlineTrusted && element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
687
1075
  if (!matched.length && !inline.some(declaration => declaration[2])) {
688
1076
  return inline;
689
1077
  }
@@ -700,15 +1088,16 @@ function appliedDeclarations(element, rules) {
700
1088
  * learned about each element, so no element is tested twice
701
1089
  */
702
1090
  class Walk {
703
- constructor(rules) {
1091
+ constructor(trust) {
704
1092
  this.hiddenElements = 0;
705
1093
  this.invisibleCharacters = 0;
706
1094
  this.appliedCache = new Map();
707
- this.setsInheritedCache = new Map();
708
- this.rules = rules;
1095
+ this.reachCache = new Map();
1096
+ this.verticalElements = new WeakSet();
1097
+ this.trust = trust;
709
1098
  }
710
- // Kept only for an element whose declarations were read ahead of the walk, by setsInherited(),
711
- // and dropped when the walk reaches it, since no element is reached twice
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
712
1101
  applied(element, keep) {
713
1102
  const cached = this.appliedCache.get(element);
714
1103
  if (cached) {
@@ -717,31 +1106,85 @@ class Walk {
717
1106
  }
718
1107
  return cached;
719
1108
  }
720
- const applied = appliedDeclarations(element, this.rules);
1109
+ const applied = appliedDeclarations(element, this.trust.rules, this.trust.inline);
721
1110
  if (keep) {
722
1111
  this.appliedCache.set(element, applied);
723
1112
  }
724
1113
  return applied;
725
1114
  }
726
- // Whether the element or anything inside it sets an inherited hiding property itself
727
- setsInherited(element) {
728
- let sets = this.setsInheritedCache.get(element);
729
- if (sets === undefined) {
730
- sets = this.applied(element, true).some(([property]) => INHERITED_HIDING.has(property)) || this.insideSetsInherited(element);
731
- this.setsInheritedCache.set(element, sets);
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
+ }
732
1153
  }
733
- return sets;
1154
+ return reach;
734
1155
  }
735
- // Whether anything inside the element sets an inherited hiding property, so text in it may show
736
- insideSetsInherited(element) {
737
- return element.children.some(child => (0, domutils_1.isTag)(child) && this.setsInherited(child));
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;
738
1174
  }
739
1175
  isHidden(element) {
740
- const hidden = hiding(this.applied(element, false), element);
741
- // an element hidden only by an inherited property is kept when something inside it sets the
742
- // property again: what is left of its own text then reaches the model, rather than text a
743
- // reader sees being taken from it
744
- return hidden === 'final' || (hidden === 'inherited' && !this.insideSetsInherited(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';
745
1188
  }
746
1189
  }
747
1190
  // Each element is tested as the walk reaches it, so nothing under an element that was removed is
@@ -793,22 +1236,69 @@ function collectLinks(document) {
793
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);
794
1237
  return targets.map(node => ({ href: node.attribs.href || node.attribs.action, text: linkText(node) }));
795
1238
  }
796
- // A browser shows flow content a message put inside <head>, the converter reads only <body>:
797
- // what is left of the head after the metadata went moves to the front of the body
798
- function surfaceHead(document) {
799
- const head = (0, domutils_1.findOne)(node => node.name === 'head', document.children);
800
- if (!head) {
801
- return;
802
- }
803
- const body = (0, domutils_1.findOne)(node => node.name === 'body', document.children);
804
- if (!body) {
805
- head.name = 'div';
806
- 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
+ }
807
1274
  }
808
- for (const child of head.children.slice().reverse()) {
809
- (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
+ }
810
1301
  }
811
- (0, domutils_1.removeElement)(head);
812
1302
  }
813
1303
  /**
814
1304
  * Parses an HTML message once: every link it carries, for the checks, and the document as the
@@ -819,10 +1309,22 @@ function visibleHtml(html) {
819
1309
  const { document } = parsed;
820
1310
  const links = collectLinks(document);
821
1311
  // the rules are read before the style elements go with everything else that is not rendered
822
- const walk = new Walk(hidingRules(parsed));
1312
+ const walk = new Walk(readStyle(parsed));
823
1313
  stripHidden(document, walk);
824
- surfaceHead(document);
825
- return { links, hiddenElements: walk.hiddenElements, invisibleCharacters: walk.invisibleCharacters, html: () => (0, dom_serializer_1.default)(document) };
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
+ };
826
1328
  }
827
1329
  /**
828
1330
  * Removes the characters that take no space on screen