@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.
- package/CHANGELOG.md +18 -0
- package/README.md +4 -3
- package/dist/cjs/lib/visible-text.js +839 -337
- package/dist/cjs/package-info.d.ts +1 -1
- package/dist/cjs/package-info.js +1 -1
- package/dist/esm/lib/visible-text.js +840 -335
- package/dist/esm/package-info.d.ts +1 -1
- package/dist/esm/package-info.js +1 -1
- package/package.json +5 -3
|
@@ -1,19 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import { parse, parseFragment, serialize } from 'parse5';
|
|
2
|
+
import { adapter } from 'parse5-htmlparser2-tree-adapter';
|
|
3
3
|
import { compile } from 'css-select';
|
|
4
4
|
import { parse as parseSelector } from 'css-what';
|
|
5
|
-
import { isTag, isText, isComment, hasChildren, textContent, findAll, findOne,
|
|
5
|
+
import { isTag, isText, isComment, hasChildren, textContent, findAll, findOne, removeElement, prepend, appendChild, prependChild } from 'domutils';
|
|
6
6
|
import { truncate } from './token-estimate.js';
|
|
7
7
|
// What the reader never sees must not reach the model either: an email can carry instructions
|
|
8
8
|
// for an AI in text a mail client does not render, and the summary has to describe the message
|
|
9
9
|
// as it looks to the person it was sent to. The links are collected before anything is removed,
|
|
10
10
|
// because the checks run on them must see every link the message carries, hidden or not
|
|
11
|
-
// Elements
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
const
|
|
15
|
-
// Elements whose content is never rendered as text
|
|
16
|
-
const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'title', 'iframe', 'object', 'embed']);
|
|
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']);
|
|
17
15
|
// Everything here runs synchronously in the process that called it, so how much of a message is
|
|
18
16
|
// read has to be this library's decision rather than the sender's. The HTML is cut before it is
|
|
19
17
|
// parsed; the text of a link is cut to what a reader could take in as its destination
|
|
@@ -25,12 +23,15 @@ const MAX_LINK_TEXT_LENGTH = 1024;
|
|
|
25
23
|
const MAX_STYLE_LENGTH = 128 * 1024;
|
|
26
24
|
const MAX_HIDING_RULES = 100;
|
|
27
25
|
const MAX_SELECTOR_LENGTH = 512;
|
|
28
|
-
// How deep elements may nest before the rest of the document is left out. The parser's
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
// stack. Real mail nests a few dozen levels, a layout of tables in tables a hundred or two. The
|
|
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
|
|
32
29
|
// HTML to text converter reads no deeper than this either, so nothing it would have shown is lost
|
|
33
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;
|
|
34
35
|
// The work the hiding rules may cost, as tests of a selector against an element, a descendant
|
|
35
36
|
// combinator counting once for every level it may have to climb. Ten million such tests take about
|
|
36
37
|
// half a second; ordinary mail, a few thousand elements and a few dozen rules, stays far below it.
|
|
@@ -42,12 +43,15 @@ const RULE_WORK_BUDGET = 10_000_000;
|
|
|
42
43
|
// sets anything the hiding check reads, no sheet is trusted (see sheetRules())
|
|
43
44
|
const ALWAYS_MIN_WIDTH = 320;
|
|
44
45
|
const ALWAYS_MAX_WIDTH = 4000;
|
|
45
|
-
// The start of an Outlook conditional comment's text, "[if mso]>" and the like.
|
|
46
|
-
//
|
|
47
|
-
const CONDITIONAL_OPEN = /^\[if [^\]]{0,200}\]>/i;
|
|
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;
|
|
48
49
|
// What is left of a downlevel-revealed opener, "<!--[if !mso]><!-->" or "<!--[if !mso]><!-- -->"
|
|
49
50
|
const REVEALED_OPEN_REST = /^<!(?:--\s*)?$/;
|
|
50
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]/;
|
|
51
55
|
// Characters that take no space on screen: zero-width joiners and spaces, soft hyphens, the
|
|
52
56
|
// bidirectional controls and the word joiner. Removing them changes nothing the reader sees and
|
|
53
57
|
// stops them splitting words the model should recognise or reordering text it should read
|
|
@@ -70,11 +74,16 @@ function skipNoise(text, i) {
|
|
|
70
74
|
else if (text[j] === quote) {
|
|
71
75
|
return j + 1;
|
|
72
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
|
+
}
|
|
73
81
|
}
|
|
74
82
|
return text.length;
|
|
75
83
|
}
|
|
76
|
-
// The text
|
|
77
|
-
//
|
|
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
|
|
78
87
|
function withoutNoise(input, keepStrings) {
|
|
79
88
|
let output = '';
|
|
80
89
|
let from = 0;
|
|
@@ -87,22 +96,13 @@ function withoutNoise(input, keepStrings) {
|
|
|
87
96
|
i = end;
|
|
88
97
|
}
|
|
89
98
|
else {
|
|
90
|
-
|
|
99
|
+
// ".a/**/.b" is ".a.b" in a selector
|
|
100
|
+
output += input.substring(from, i) + (keepStrings ? '' : ' ');
|
|
91
101
|
i = from = end;
|
|
92
102
|
}
|
|
93
103
|
}
|
|
94
104
|
return output + input.substring(from);
|
|
95
105
|
}
|
|
96
|
-
function declarations(input) {
|
|
97
|
-
const list = [];
|
|
98
|
-
for (const declaration of withoutNoise(input, false).split(';')) {
|
|
99
|
-
const match = /^\s*([a-z-]+)\s*:\s*([^!]*)(!\s*important)?/i.exec(declaration);
|
|
100
|
-
if (match) {
|
|
101
|
-
list.push([match[1].toLowerCase(), match[2].trim().toLowerCase(), !!match[3]]);
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
return list;
|
|
105
|
-
}
|
|
106
106
|
// The properties the hiding check reads. A style sheet rule that sets none of them cannot hide an
|
|
107
107
|
// element or show one again, so it is not matched at all
|
|
108
108
|
// Vertical padding, which a box of no height still shows (see isCollapsed())
|
|
@@ -112,12 +112,29 @@ const HIDING_PROPERTIES = new Set([
|
|
|
112
112
|
'visibility',
|
|
113
113
|
'opacity',
|
|
114
114
|
'font-size',
|
|
115
|
-
'text-indent',
|
|
116
115
|
'height',
|
|
117
116
|
'max-height',
|
|
118
117
|
'min-height',
|
|
119
118
|
'overflow',
|
|
120
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',
|
|
121
138
|
...PADDING_PROPERTIES
|
|
122
139
|
]);
|
|
123
140
|
// The same properties found in raw style text, for style that is not read rule by rule
|
|
@@ -125,67 +142,193 @@ const HIDING_IN_TEXT = new RegExp(`(?:^|[{;\\s"'])(?:${[...HIDING_PROPERTIES].jo
|
|
|
125
142
|
// Whether style text nothing here reads rule by rule sets what the hiding check reads. A backslash
|
|
126
143
|
// counts too: CSS allows escapes in a property name, which no check here decodes
|
|
127
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
|
+
}
|
|
128
220
|
// The hiding properties an element inside can set again: they are inherited, so text inside an
|
|
129
|
-
// element that is hidden by one of them shows when something inside it sets the property itself
|
|
130
|
-
|
|
131
|
-
//
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
'
|
|
142
|
-
'
|
|
143
|
-
'
|
|
144
|
-
'
|
|
145
|
-
'
|
|
146
|
-
'
|
|
147
|
-
'
|
|
148
|
-
'
|
|
149
|
-
'
|
|
150
|
-
'
|
|
151
|
-
'
|
|
152
|
-
'
|
|
153
|
-
'
|
|
154
|
-
'
|
|
155
|
-
'
|
|
156
|
-
'
|
|
157
|
-
'
|
|
158
|
-
'
|
|
159
|
-
'
|
|
160
|
-
'
|
|
161
|
-
'
|
|
162
|
-
'
|
|
163
|
-
'
|
|
164
|
-
'
|
|
165
|
-
'
|
|
166
|
-
'
|
|
167
|
-
'
|
|
168
|
-
'
|
|
169
|
-
'
|
|
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'
|
|
170
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']);
|
|
171
271
|
const BLOCK_DISPLAYS = new Set(['block', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'list-item', 'flow-root']);
|
|
172
|
-
|
|
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
|
+
];
|
|
173
288
|
// A length of zero that holds whatever the box sits in. A percentage is resolved against the parent
|
|
174
289
|
// and becomes auto when the parent's height is, which is the usual case
|
|
175
|
-
const isAbsoluteZero = (value) => /^0(?:\.0
|
|
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
|
+
}
|
|
176
311
|
/**
|
|
177
312
|
* Whether a box of no height clips everything in it: the preheader trick. Only where it holds for
|
|
178
|
-
* every reader, so a block-level box, an absolute zero, nothing that sets a minimum height
|
|
179
|
-
* vertical padding (overflow clips at the padding edge, so text
|
|
180
|
-
* overflow
|
|
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
|
|
181
316
|
*/
|
|
182
|
-
function isCollapsed(style, element) {
|
|
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
|
+
}
|
|
183
326
|
const display = style.get('display');
|
|
184
|
-
const blockLevel = display ? BLOCK_DISPLAYS.has(display) :
|
|
327
|
+
const blockLevel = display ? BLOCK_DISPLAYS.has(display) : BLOCK_TAGS.has(element.name);
|
|
185
328
|
if (!blockLevel || !(isAbsoluteZero(style.get('height')) || isAbsoluteZero(style.get('max-height')))) {
|
|
186
329
|
return false;
|
|
187
330
|
}
|
|
188
|
-
if (style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) {
|
|
331
|
+
if ((style.has('min-height') && !isAbsoluteZero(style.get('min-height'))) || COLLAPSE_UNDOING.some(property => style.has(property))) {
|
|
189
332
|
return false;
|
|
190
333
|
}
|
|
191
334
|
for (const property of PADDING_PROPERTIES) {
|
|
@@ -193,40 +336,120 @@ function isCollapsed(style, element) {
|
|
|
193
336
|
return false;
|
|
194
337
|
}
|
|
195
338
|
}
|
|
196
|
-
|
|
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') {
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
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);
|
|
197
419
|
}
|
|
198
420
|
/**
|
|
199
421
|
* How an element is hidden by what applies to it, the last value for a property winning (see
|
|
200
422
|
* appliedDeclarations() for the order). "final" when nothing inside it can show text again: no
|
|
201
|
-
* display, the hidden attribute, an opacity a child's own
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
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
|
|
206
429
|
*/
|
|
207
|
-
function hiding(
|
|
208
|
-
|
|
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;
|
|
209
436
|
if (!applied.length) {
|
|
210
437
|
// most elements: no rule matched and no style attribute
|
|
211
438
|
return hiddenAttribute ? 'final' : '';
|
|
212
439
|
}
|
|
213
440
|
const style = new Map(applied.map(([property, value]) => [property, value]));
|
|
214
441
|
const value = (property) => style.get(property) || '';
|
|
215
|
-
const number = (property) => parseFloat(value(property));
|
|
216
442
|
if (value('display') === 'none' ||
|
|
217
443
|
// the hidden attribute is a user agent rule, which an author display value overrides
|
|
218
444
|
(hiddenAttribute && !style.has('display')) ||
|
|
219
|
-
|
|
220
|
-
|
|
445
|
+
// a display:contents element draws no box, and its opacity hides nothing
|
|
446
|
+
(/^(?:0+(?:\.0+)?|\.0+)%?$/.test(value('opacity')) && value('display') !== 'contents')) {
|
|
221
447
|
return 'final';
|
|
222
448
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
fontSize === 0 ||
|
|
228
|
-
(fontSize < 1 && /^[\d.]+(?:px|pt)?$/.test(value('font-size'))) ||
|
|
229
|
-
number('text-indent') <= -1000) {
|
|
449
|
+
if (isCollapsed(applied, style, element, vertical)) {
|
|
450
|
+
return 'collapsed';
|
|
451
|
+
}
|
|
452
|
+
if (value('visibility') === 'hidden' || value('visibility') === 'collapse' || isHidingFontSize(fontSize(applied))) {
|
|
230
453
|
return 'inherited';
|
|
231
454
|
}
|
|
232
455
|
return '';
|
|
@@ -288,12 +511,14 @@ function blockEnd(css, start) {
|
|
|
288
511
|
* @returns The rules in sheet order, each with only the declarations the check reads
|
|
289
512
|
*/
|
|
290
513
|
function sheetRules(css) {
|
|
291
|
-
if (css.includes('\\')) {
|
|
514
|
+
if (css.includes('\\') || NON_ASCII_SPACE.test(css)) {
|
|
292
515
|
// an escape in a property name or a selector is one no check here decodes
|
|
293
516
|
return null;
|
|
294
517
|
}
|
|
295
518
|
const rules = [];
|
|
296
519
|
let start = 0;
|
|
520
|
+
// the unconditional media blocks entered, whose "}" ends them
|
|
521
|
+
let entered = 0;
|
|
297
522
|
for (let i = 0; i < css.length;) {
|
|
298
523
|
const end = skipNoise(css, i);
|
|
299
524
|
if (end !== i) {
|
|
@@ -302,11 +527,20 @@ function sheetRules(css) {
|
|
|
302
527
|
}
|
|
303
528
|
const char = css[i];
|
|
304
529
|
if (char === ';' || char === '}') {
|
|
305
|
-
|
|
306
|
-
// imports holds rules nothing here reads
|
|
307
|
-
if (
|
|
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)) {
|
|
308
533
|
return null;
|
|
309
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
|
+
}
|
|
310
544
|
start = ++i;
|
|
311
545
|
continue;
|
|
312
546
|
}
|
|
@@ -318,6 +552,7 @@ function sheetRules(css) {
|
|
|
318
552
|
const media = /^@media\s+(.+)$/i.exec(prelude);
|
|
319
553
|
if (media && isUnconditionalQuery(media[1])) {
|
|
320
554
|
// entered, so that its rules are read next
|
|
555
|
+
entered++;
|
|
321
556
|
i = start = i + 1;
|
|
322
557
|
continue;
|
|
323
558
|
}
|
|
@@ -331,6 +566,10 @@ function sheetRules(css) {
|
|
|
331
566
|
}
|
|
332
567
|
continue;
|
|
333
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
|
+
}
|
|
334
573
|
const found = declarations(block).filter(([property]) => HIDING_PROPERTIES.has(property));
|
|
335
574
|
if (prelude && found.length) {
|
|
336
575
|
if (rules.length >= MAX_HIDING_RULES) {
|
|
@@ -346,15 +585,17 @@ function sheetRules(css) {
|
|
|
346
585
|
// a long list of them, and :has() recurses as deep as the document goes. The sibling combinators
|
|
347
586
|
// scan the siblings before an element for every element tested, so they are left out too
|
|
348
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';
|
|
349
590
|
const isRoot = (token) => !!token && token.type === 'tag' && (token.name === 'html' || token.name === 'body');
|
|
350
591
|
/**
|
|
351
592
|
* The selector as the matcher reads it, or null for one it cannot match as a mail client does: the
|
|
352
593
|
* same parse decides what is allowed, what it costs and what is compiled, so the three cannot
|
|
353
|
-
* disagree. "html > ..." and "body > ..." are refused too:
|
|
354
|
-
*
|
|
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
|
|
355
596
|
*/
|
|
356
597
|
function matchableSelector(selector) {
|
|
357
|
-
if (selector.length > MAX_SELECTOR_LENGTH) {
|
|
598
|
+
if (selector.length > MAX_SELECTOR_LENGTH || !validSelectorText(selector)) {
|
|
358
599
|
return null;
|
|
359
600
|
}
|
|
360
601
|
let parsed;
|
|
@@ -367,6 +608,28 @@ function matchableSelector(selector) {
|
|
|
367
608
|
const matchable = (part) => part.every(token => MATCHABLE_TOKENS.has(token.type)) && !part.some((token, i) => isRoot(token) && part[i + 1]?.type === 'child');
|
|
368
609
|
return parsed.every(matchable) ? parsed : null;
|
|
369
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
|
+
}
|
|
370
633
|
/**
|
|
371
634
|
* What testing one part of a selector list against one element may cost, in tests: the depth of
|
|
372
635
|
* the document for every descendant combinator in it, since each one climbs the ancestors of the
|
|
@@ -386,7 +649,7 @@ function specificity(part) {
|
|
|
386
649
|
if (token.type === 'attribute') {
|
|
387
650
|
// "#p" is an id selector, "[id=p]" an attribute selector that weighs like a class: the
|
|
388
651
|
// parser gives both the same token and marks only the shorthand with quirks-mode case
|
|
389
|
-
value += token.name === 'id' && token.action === 'equals'
|
|
652
|
+
value += isQuirksName(token) && token.name === 'id' && token.action === 'equals' ? 1_000_000 : 1000;
|
|
390
653
|
}
|
|
391
654
|
else if (token.type === 'tag') {
|
|
392
655
|
value += 1;
|
|
@@ -395,17 +658,24 @@ function specificity(part) {
|
|
|
395
658
|
return value;
|
|
396
659
|
}
|
|
397
660
|
/**
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
*
|
|
401
|
-
* a
|
|
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
|
|
402
666
|
*/
|
|
403
|
-
function
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
+
};
|
|
409
679
|
}
|
|
410
680
|
/**
|
|
411
681
|
* Compiles the rules of the message's own style sheets that the hiding check reads, one entry for
|
|
@@ -415,27 +685,34 @@ function withoutImpliedRoot(part) {
|
|
|
415
685
|
* unread: leaving out one rule could leave out the one that shows text again, and then text every
|
|
416
686
|
* reader sees would be taken from the model. Each early return below is one way that happens
|
|
417
687
|
*/
|
|
418
|
-
function
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
// a linked sheet, or an escaped property name in a style attribute
|
|
424
|
-
if (parsed.unreadableStyle) {
|
|
425
|
-
return [];
|
|
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 };
|
|
426
693
|
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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);
|
|
434
705
|
}
|
|
435
|
-
// an at-rule, an @import, an escape or more rules than are read (see sheetRules())
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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);
|
|
439
716
|
}
|
|
440
717
|
const rules = [];
|
|
441
718
|
let work = 0;
|
|
@@ -443,209 +720,323 @@ function hidingRules(parsed) {
|
|
|
443
720
|
// a selector that cannot be matched as a mail client matches it
|
|
444
721
|
const matchable = matchableSelector(selector);
|
|
445
722
|
if (!matchable) {
|
|
446
|
-
return
|
|
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);
|
|
447
732
|
}
|
|
448
733
|
// or more work than matching is allowed
|
|
449
734
|
work += parsed.elements * matchable.reduce((sum, part) => sum + selectorCost(part, parsed.maxDepth), 0);
|
|
450
735
|
if (work > RULE_WORK_BUDGET) {
|
|
451
|
-
return
|
|
736
|
+
return unread(parsed);
|
|
452
737
|
}
|
|
453
738
|
for (const part of matchable) {
|
|
454
|
-
|
|
455
|
-
|
|
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 });
|
|
456
748
|
}
|
|
457
749
|
}
|
|
458
|
-
return rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
|
|
750
|
+
return { rules: rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order), inline: true, hiddenAttribute: true, undoable: true };
|
|
459
751
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
//
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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 {
|
|
466
764
|
constructor() {
|
|
467
|
-
|
|
468
|
-
this.
|
|
469
|
-
this.maxDepth = 0;
|
|
470
|
-
this.sheets = [];
|
|
471
|
-
/** The style elements for some readers only (a media attribute that does not hold for all) */
|
|
472
|
-
this.conditionalSheets = [];
|
|
473
|
-
/** Something applies styles that cannot be read here */
|
|
474
|
-
this.unreadableStyle = false;
|
|
475
|
-
/** The parser stopped before the end of the document */
|
|
765
|
+
/** The depth of each node, the document at 0 */
|
|
766
|
+
this.depths = new WeakMap();
|
|
476
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;
|
|
477
801
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
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
|
+
}
|
|
490
824
|
this.stopped = true;
|
|
491
|
-
this.reader.pause();
|
|
492
825
|
}
|
|
493
826
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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);
|
|
501
852
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
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);
|
|
860
|
+
}
|
|
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;
|
|
507
874
|
}
|
|
508
|
-
if (
|
|
509
|
-
|
|
510
|
-
this.unreadableStyle = true;
|
|
875
|
+
if (!isTag(node)) {
|
|
876
|
+
continue;
|
|
511
877
|
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
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;
|
|
515
905
|
}
|
|
516
|
-
if (name === 'svg' || name === 'math') {
|
|
517
|
-
//
|
|
518
|
-
|
|
519
|
-
// in SVG hold markup rather than text
|
|
520
|
-
this.unreadableStyle = true;
|
|
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;
|
|
521
909
|
}
|
|
522
|
-
if (name
|
|
523
|
-
// a
|
|
524
|
-
|
|
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;
|
|
525
914
|
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
if (ancestors.some(element => element.name === 'template')) {
|
|
529
|
-
// never rendered, so never applied
|
|
530
|
-
return;
|
|
915
|
+
if (node.name === 'style') {
|
|
916
|
+
gatherSheet(node, found, revealed || outlookOnly.has(node));
|
|
531
917
|
}
|
|
532
|
-
if (
|
|
533
|
-
|
|
534
|
-
|
|
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;
|
|
535
922
|
}
|
|
536
|
-
if (
|
|
537
|
-
//
|
|
538
|
-
|
|
539
|
-
return;
|
|
923
|
+
if (node.name !== 'template') {
|
|
924
|
+
// a template's content is never rendered, its sheets included
|
|
925
|
+
pending.push(...[...node.children].reverse());
|
|
540
926
|
}
|
|
541
|
-
this.sheets.push(sheet);
|
|
542
927
|
}
|
|
928
|
+
return found;
|
|
543
929
|
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
class CommentScanner {
|
|
551
|
-
constructor(html) {
|
|
552
|
-
this.html = html;
|
|
553
|
-
}
|
|
554
|
-
next(token, cached, from) {
|
|
555
|
-
return cached !== undefined && (cached < 0 || cached >= from) ? cached : this.html.indexOf(token, from);
|
|
556
|
-
}
|
|
557
|
-
/** The comment opening at `start` ("<!--"): where its text starts and ends, and where it ends */
|
|
558
|
-
comment(start) {
|
|
559
|
-
const dataStart = start + 4;
|
|
560
|
-
for (const empty of ['>', '->']) {
|
|
561
|
-
if (this.html.startsWith(empty, dataStart)) {
|
|
562
|
-
return { dataStart, dataEnd: dataStart, end: dataStart + empty.length };
|
|
563
|
-
}
|
|
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;
|
|
564
936
|
}
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
if (bang >= 0 && (dash < 0 || bang < dash)) {
|
|
568
|
-
return { dataStart, dataEnd: bang, end: bang + 4 };
|
|
937
|
+
if (ancestor.name === 'td' || ancestor.name === 'th' || ancestor.name === 'caption') {
|
|
938
|
+
return false;
|
|
569
939
|
}
|
|
570
|
-
|
|
571
|
-
|
|
940
|
+
}
|
|
941
|
+
return false;
|
|
942
|
+
}
|
|
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;
|
|
572
955
|
}
|
|
573
|
-
return { dataStart, dataEnd: this.html.length, end: this.html.length };
|
|
574
956
|
}
|
|
957
|
+
return null;
|
|
575
958
|
}
|
|
576
959
|
/**
|
|
577
|
-
*
|
|
578
|
-
*
|
|
579
|
-
*
|
|
580
|
-
* shows what it wraps. That content is kept, as it always was, so Outlook-only text is read too
|
|
581
|
-
* - "<!--[if !mso]><!-->...<!--<![endif]-->" is two comments around content every client but
|
|
582
|
-
* Outlook shows. The two comments stay comments and the content stays where it is
|
|
583
|
-
* - every other comment is left for the parser, ended where a browser ends it
|
|
584
|
-
* Removing the markers piece by piece used to leave a bare "<!--" behind the revealed closer, which
|
|
585
|
-
* the parser read as a comment running over the rest of the message: the pattern email builders
|
|
586
|
-
* write in every message, and all of it past the first such section was left out
|
|
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
|
|
587
963
|
*
|
|
588
|
-
* @returns The
|
|
589
|
-
* applies such a sheet and the other clients do not, or the other way round
|
|
964
|
+
* @returns The nodes put in place
|
|
590
965
|
*/
|
|
591
|
-
function
|
|
592
|
-
const
|
|
593
|
-
const
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const { dataStart, dataEnd, end } = scanner.comment(start);
|
|
604
|
-
const data = html.substring(dataStart, dataEnd);
|
|
605
|
-
const open = CONDITIONAL_OPEN.exec(data);
|
|
606
|
-
const rest = open ? data.substring(open[0].length) : '';
|
|
607
|
-
if (open && rest.toLowerCase().endsWith(CONDITIONAL_CLOSE)) {
|
|
608
|
-
// Outlook-only content, kept without its markers
|
|
609
|
-
const content = rest.substring(0, rest.length - CONDITIONAL_CLOSE.length);
|
|
610
|
-
collect(content);
|
|
611
|
-
output += html.substring(from, start) + content;
|
|
612
|
-
}
|
|
613
|
-
else {
|
|
614
|
-
if (open && REVEALED_OPEN_REST.test(rest)) {
|
|
615
|
-
revealed = end;
|
|
616
|
-
}
|
|
617
|
-
else if (data.toLowerCase() === CONDITIONAL_CLOSE && revealed >= 0) {
|
|
618
|
-
collect(html.substring(revealed, start));
|
|
619
|
-
revealed = -1;
|
|
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);
|
|
620
978
|
}
|
|
621
|
-
else
|
|
622
|
-
|
|
623
|
-
collect(rest);
|
|
979
|
+
else {
|
|
980
|
+
prepend(comment, child);
|
|
624
981
|
}
|
|
625
|
-
// a comment to every client, written so the parser ends it where a browser does: the
|
|
626
|
-
// parser here reads on past "--!>" to the next "-->"
|
|
627
|
-
output += `${html.substring(from, start)}<!--${data}-->`;
|
|
628
982
|
}
|
|
629
|
-
|
|
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
|
+
}
|
|
630
997
|
}
|
|
631
|
-
|
|
632
|
-
|
|
998
|
+
else {
|
|
999
|
+
for (const child of placed) {
|
|
1000
|
+
appendChild(body, child);
|
|
1001
|
+
}
|
|
633
1002
|
}
|
|
634
|
-
return
|
|
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;
|
|
1026
|
+
}
|
|
1027
|
+
found.sheets.push(sheet);
|
|
635
1028
|
}
|
|
636
1029
|
function parseDocument(html) {
|
|
637
1030
|
const source = truncate(html, MAX_HTML_LENGTH);
|
|
638
|
-
const
|
|
639
|
-
const
|
|
640
|
-
|
|
1031
|
+
const builder = new TreeBuilder();
|
|
1032
|
+
const document = builder.document(source);
|
|
1033
|
+
const found = gather(document, builder);
|
|
641
1034
|
return {
|
|
642
|
-
document
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
unreadableStyle: handler.unreadableStyle,
|
|
648
|
-
truncated: handler.stopped || source.length !== String(html ?? '').length
|
|
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
|
|
649
1040
|
};
|
|
650
1041
|
}
|
|
651
1042
|
function hasText(node) {
|
|
@@ -661,9 +1052,9 @@ function hasText(node) {
|
|
|
661
1052
|
* order, then those of the style attribute. Weighing them any other way would let a sender show
|
|
662
1053
|
* text to every reader that the summary leaves out
|
|
663
1054
|
*
|
|
664
|
-
* @param rules - In cascade order, as
|
|
1055
|
+
* @param rules - In cascade order, as readStyle() returns them
|
|
665
1056
|
*/
|
|
666
|
-
function appliedDeclarations(element, rules) {
|
|
1057
|
+
function appliedDeclarations(element, rules, inlineTrusted) {
|
|
667
1058
|
const matched = [];
|
|
668
1059
|
for (const rule of rules) {
|
|
669
1060
|
if (rule.test(element)) {
|
|
@@ -671,7 +1062,7 @@ function appliedDeclarations(element, rules) {
|
|
|
671
1062
|
}
|
|
672
1063
|
}
|
|
673
1064
|
// only what the check reads, so an element styled for color and fonts alone has nothing to weigh
|
|
674
|
-
const inline = element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
|
|
1065
|
+
const inline = inlineTrusted && element.attribs.style ? declarations(element.attribs.style).filter(([property]) => HIDING_PROPERTIES.has(property)) : [];
|
|
675
1066
|
if (!matched.length && !inline.some(declaration => declaration[2])) {
|
|
676
1067
|
return inline;
|
|
677
1068
|
}
|
|
@@ -688,15 +1079,16 @@ function appliedDeclarations(element, rules) {
|
|
|
688
1079
|
* learned about each element, so no element is tested twice
|
|
689
1080
|
*/
|
|
690
1081
|
class Walk {
|
|
691
|
-
constructor(
|
|
1082
|
+
constructor(trust) {
|
|
692
1083
|
this.hiddenElements = 0;
|
|
693
1084
|
this.invisibleCharacters = 0;
|
|
694
1085
|
this.appliedCache = new Map();
|
|
695
|
-
this.
|
|
696
|
-
this.
|
|
1086
|
+
this.reachCache = new Map();
|
|
1087
|
+
this.verticalElements = new WeakSet();
|
|
1088
|
+
this.trust = trust;
|
|
697
1089
|
}
|
|
698
|
-
// Kept only for an element whose declarations were read ahead of the walk, by
|
|
699
|
-
//
|
|
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
|
|
700
1092
|
applied(element, keep) {
|
|
701
1093
|
const cached = this.appliedCache.get(element);
|
|
702
1094
|
if (cached) {
|
|
@@ -705,31 +1097,85 @@ class Walk {
|
|
|
705
1097
|
}
|
|
706
1098
|
return cached;
|
|
707
1099
|
}
|
|
708
|
-
const applied = appliedDeclarations(element, this.rules);
|
|
1100
|
+
const applied = appliedDeclarations(element, this.trust.rules, this.trust.inline);
|
|
709
1101
|
if (keep) {
|
|
710
1102
|
this.appliedCache.set(element, applied);
|
|
711
1103
|
}
|
|
712
1104
|
return applied;
|
|
713
1105
|
}
|
|
714
|
-
//
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
this.
|
|
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);
|
|
720
1130
|
}
|
|
721
|
-
return
|
|
1131
|
+
return reach;
|
|
722
1132
|
}
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
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;
|
|
726
1165
|
}
|
|
727
1166
|
isHidden(element) {
|
|
728
|
-
const
|
|
729
|
-
|
|
730
|
-
//
|
|
731
|
-
// reader sees being taken
|
|
732
|
-
|
|
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';
|
|
733
1179
|
}
|
|
734
1180
|
}
|
|
735
1181
|
// Each element is tested as the walk reaches it, so nothing under an element that was removed is
|
|
@@ -781,22 +1227,69 @@ function collectLinks(document) {
|
|
|
781
1227
|
const targets = findAll(node => ((node.name === 'a' || node.name === 'area') && !!node.attribs.href) || (node.name === 'form' && !!node.attribs.action), document.children);
|
|
782
1228
|
return targets.map(node => ({ href: node.attribs.href || node.attribs.action, text: linkText(node) }));
|
|
783
1229
|
}
|
|
784
|
-
//
|
|
785
|
-
//
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
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
|
+
}
|
|
795
1265
|
}
|
|
796
|
-
|
|
797
|
-
|
|
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
|
+
}
|
|
798
1292
|
}
|
|
799
|
-
removeElement(head);
|
|
800
1293
|
}
|
|
801
1294
|
/**
|
|
802
1295
|
* Parses an HTML message once: every link it carries, for the checks, and the document as the
|
|
@@ -807,10 +1300,22 @@ function visibleHtml(html) {
|
|
|
807
1300
|
const { document } = parsed;
|
|
808
1301
|
const links = collectLinks(document);
|
|
809
1302
|
// the rules are read before the style elements go with everything else that is not rendered
|
|
810
|
-
const walk = new Walk(
|
|
1303
|
+
const walk = new Walk(readStyle(parsed));
|
|
811
1304
|
stripHidden(document, walk);
|
|
812
|
-
|
|
813
|
-
|
|
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
|
+
};
|
|
814
1319
|
}
|
|
815
1320
|
/**
|
|
816
1321
|
* Removes the characters that take no space on screen
|