@tiavision/sinter-mail 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +113 -2
- package/docs/mail.md +298 -0
- package/docs/proposals/progressive-rendering.md +180 -0
- package/docs/proposals/sinter-mail.md +520 -0
- package/llms.txt +21 -0
- package/package.json +65 -4
- package/sinter/autolink.ts +98 -0
- package/sinter/components/internal/mail-a.html +5 -0
- package/sinter/components/internal/mail-abbr.html +5 -0
- package/sinter/components/internal/mail-address.html +5 -0
- package/sinter/components/internal/mail-article.html +5 -0
- package/sinter/components/internal/mail-aside.html +5 -0
- package/sinter/components/internal/mail-b.html +5 -0
- package/sinter/components/internal/mail-bdi.html +5 -0
- package/sinter/components/internal/mail-bdo.html +5 -0
- package/sinter/components/internal/mail-blockquote.html +5 -0
- package/sinter/components/internal/mail-br.html +5 -0
- package/sinter/components/internal/mail-center.html +5 -0
- package/sinter/components/internal/mail-cite.html +5 -0
- package/sinter/components/internal/mail-code.html +5 -0
- package/sinter/components/internal/mail-dd.html +5 -0
- package/sinter/components/internal/mail-del.html +5 -0
- package/sinter/components/internal/mail-details.html +5 -0
- package/sinter/components/internal/mail-dfn.html +5 -0
- package/sinter/components/internal/mail-div.html +5 -0
- package/sinter/components/internal/mail-dl.html +5 -0
- package/sinter/components/internal/mail-dt.html +5 -0
- package/sinter/components/internal/mail-em.html +5 -0
- package/sinter/components/internal/mail-figcaption.html +5 -0
- package/sinter/components/internal/mail-figure.html +5 -0
- package/sinter/components/internal/mail-font.html +5 -0
- package/sinter/components/internal/mail-footer.html +5 -0
- package/sinter/components/internal/mail-h1.html +5 -0
- package/sinter/components/internal/mail-h2.html +5 -0
- package/sinter/components/internal/mail-h3.html +5 -0
- package/sinter/components/internal/mail-h4.html +5 -0
- package/sinter/components/internal/mail-h5.html +5 -0
- package/sinter/components/internal/mail-h6.html +5 -0
- package/sinter/components/internal/mail-header.html +5 -0
- package/sinter/components/internal/mail-hr.html +5 -0
- package/sinter/components/internal/mail-i.html +5 -0
- package/sinter/components/internal/mail-img.html +5 -0
- package/sinter/components/internal/mail-ins.html +5 -0
- package/sinter/components/internal/mail-kbd.html +5 -0
- package/sinter/components/internal/mail-li.html +5 -0
- package/sinter/components/internal/mail-main.html +5 -0
- package/sinter/components/internal/mail-mark.html +5 -0
- package/sinter/components/internal/mail-nav.html +5 -0
- package/sinter/components/internal/mail-node.html +5 -0
- package/sinter/components/internal/mail-ol.html +5 -0
- package/sinter/components/internal/mail-orphan.html +5 -0
- package/sinter/components/internal/mail-p.html +5 -0
- package/sinter/components/internal/mail-pre.html +5 -0
- package/sinter/components/internal/mail-q.html +5 -0
- package/sinter/components/internal/mail-s.html +5 -0
- package/sinter/components/internal/mail-samp.html +5 -0
- package/sinter/components/internal/mail-section.html +5 -0
- package/sinter/components/internal/mail-small.html +5 -0
- package/sinter/components/internal/mail-span.html +5 -0
- package/sinter/components/internal/mail-steps.html +5 -0
- package/sinter/components/internal/mail-steps.ts +46 -0
- package/sinter/components/internal/mail-strike.html +5 -0
- package/sinter/components/internal/mail-strong.html +5 -0
- package/sinter/components/internal/mail-sub.html +5 -0
- package/sinter/components/internal/mail-summary.html +5 -0
- package/sinter/components/internal/mail-sup.html +5 -0
- package/sinter/components/internal/mail-table.html +5 -0
- package/sinter/components/internal/mail-time.html +5 -0
- package/sinter/components/internal/mail-tt.html +5 -0
- package/sinter/components/internal/mail-u.html +5 -0
- package/sinter/components/internal/mail-ul.html +5 -0
- package/sinter/components/internal/mail-var.html +5 -0
- package/sinter/components/internal/mail-wbr.html +5 -0
- package/sinter/components/mail-body.html +21 -0
- package/sinter/css/hints.ts +259 -0
- package/sinter/css/index.ts +348 -0
- package/sinter/css/media.ts +254 -0
- package/sinter/css/parse.ts +124 -0
- package/sinter/css/selectors.ts +530 -0
- package/sinter/css/tokenize.ts +279 -0
- package/sinter/css/values.ts +669 -0
- package/sinter/engine.ts +6 -0
- package/sinter/index.ts +5 -0
- package/sinter/parse.ts +359 -0
- package/sinter/parser/entities.ts +22 -0
- package/sinter/parser/index.ts +54 -0
- package/sinter/parser/tokenizer.ts +275 -0
- package/sinter/parser/tree.ts +1265 -0
- package/sinter/plain.ts +125 -0
- package/sinter/raw.ts +28 -0
- package/sinter/sinter.helpers.ts +11 -0
- package/sinter/sinter.types.ts +144 -0
- package/sinter/tags.ts +169 -0
- package/sinter/tree.ts +168 -0
package/sinter/engine.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// What mail.parse runs: the HTML parser and the cascade, behind one specifier of the package's own
|
|
2
|
+
// (`@tiavision/sinter-mail/parser`). An app that lists this package in `sinter({ lazy })` makes both load
|
|
3
|
+
// when a let first needs mail.parse; lazy packages are matched by import specifier, so parse.ts imports
|
|
4
|
+
// them by that name and never by a relative path.
|
|
5
|
+
export { parseHTML } from './parser/index.js';
|
|
6
|
+
export { resolve, resolveStyles } from './css/index.js';
|
package/sinter/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// The package's entry: the helpers, which an app re-exports as a namespace
|
|
2
|
+
// (`export * as mail from '@tiavision/sinter-mail'`), and the tree's types
|
|
3
|
+
// (`export type { Body } from '@tiavision/sinter-mail'` in its src/sinter.types.ts).
|
|
4
|
+
export * from './sinter.helpers.js';
|
|
5
|
+
export type * from './sinter.types.js';
|
package/sinter/parse.ts
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// `mail.parse(html, options)`: an email's HTML body to the tree of sinter.types.ts.
|
|
2
|
+
//
|
|
3
|
+
// Three steps: the HTML parser builds the document the browser would build (sinter/parser), the cascade
|
|
4
|
+
// resolves every element's styles from its legacy attributes, the email's <style> rules and its style
|
|
5
|
+
// attribute (sinter/css), and this module keeps only what an email may contain (sinter/tags.ts): the
|
|
6
|
+
// allowed tags, their attributes with checked values, the images the options allow, ids only where an
|
|
7
|
+
// in-email link needs them, and a table structure the components can render.
|
|
8
|
+
//
|
|
9
|
+
// Pure: the same source and options give the same tree, with no globals beyond the language's and
|
|
10
|
+
// `URL`, so sinter runs it at build time over a `file:` resource. The tree is kept with sinter's memo():
|
|
11
|
+
// one parse per source and options, the tree frozen and shared.
|
|
12
|
+
import { parseHTML, resolve } from '@tiavision/sinter-mail/parser';
|
|
13
|
+
import { memo } from '@tiaforge-ui/sinter/memo';
|
|
14
|
+
import type { RawElement, RawNode } from './raw.js';
|
|
15
|
+
import { attr } from './raw.js';
|
|
16
|
+
import { attrsOf, DROP, RENAME, TAGS, TEXT } from './tags.js';
|
|
17
|
+
import type { Attrs, Body, Element, Node, ParseOptions, Property, Style, Tag } from './sinter.types.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The tree of an email's HTML body under `options`. The same source and options give the same tree,
|
|
21
|
+
* frozen: change a copy.
|
|
22
|
+
*/
|
|
23
|
+
export function parse(html: string | null | undefined, options?: ParseOptions): Body {
|
|
24
|
+
const o = optionsOf(options);
|
|
25
|
+
return parseTree(typeof html === 'string' ? html : '', o.images, o.proxy, o.cidTemplate, o.cidMap, o.media, o.dataImages);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** the parse, kept by its arguments (all primitives, or an array of them: memo's keys) */
|
|
29
|
+
const parseTree = memo(
|
|
30
|
+
(html: string, images: Images, proxy: string, cidTemplate: string, cidMap: string[], media: 'wide' | 'narrow', dataImages: number): Body =>
|
|
31
|
+
build(html, { images, proxy, cidTemplate, cidMap: pairs(cidMap), media, dataImages }),
|
|
32
|
+
{ maxSize: 8 * 1024 * 1024 },
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
type Images = 'block' | 'allow' | 'proxy';
|
|
36
|
+
interface Options {
|
|
37
|
+
images: Images;
|
|
38
|
+
proxy: string;
|
|
39
|
+
/** a template with `{cid}`, or '' */
|
|
40
|
+
cidTemplate: string;
|
|
41
|
+
cidMap: Map<string, string>;
|
|
42
|
+
media: 'wide' | 'narrow';
|
|
43
|
+
dataImages: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ── Options ───────────────────────────────────────────────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
const fail = (msg: string): never => {
|
|
49
|
+
throw new TypeError(`mail.parse: ${msg}`);
|
|
50
|
+
};
|
|
51
|
+
const once = (s: string, part: string) => s.split(part).length === 2;
|
|
52
|
+
|
|
53
|
+
/** the options as primitives, validated: equal policies share one tree; an invalid one throws at each call */
|
|
54
|
+
function optionsOf(options: ParseOptions | undefined) {
|
|
55
|
+
const o = options ?? {};
|
|
56
|
+
const images = o.images ?? 'block';
|
|
57
|
+
if (!['block', 'allow', 'proxy'].includes(images)) fail(`\`images\` is 'block', 'allow' or 'proxy', not ${JSON.stringify(images)}`);
|
|
58
|
+
let proxy = '';
|
|
59
|
+
if (images === 'proxy') {
|
|
60
|
+
if (typeof o.proxy !== 'string' || !once(o.proxy, '{url}')) fail(`\`proxy\` is a URL template with \`{url}\` once, such as '/images?url={url}', not ${JSON.stringify(o.proxy)}`);
|
|
61
|
+
if (!appUrl(o.proxy!.replace('{url}', 'x'))) fail(`\`proxy\` is a path on this site or an https: URL, not ${JSON.stringify(o.proxy)}`);
|
|
62
|
+
proxy = o.proxy!;
|
|
63
|
+
} else if (o.proxy !== undefined && typeof o.proxy !== 'string') fail('`proxy` is a string');
|
|
64
|
+
let cidTemplate = '';
|
|
65
|
+
const cidMap: string[] = [];
|
|
66
|
+
if (typeof o.cid === 'string') {
|
|
67
|
+
if (!once(o.cid, '{cid}') || !appUrl(o.cid.replace('{cid}', 'x'))) fail(`\`cid\` is a map or a URL template with \`{cid}\` once, not ${JSON.stringify(o.cid)}`);
|
|
68
|
+
cidTemplate = o.cid;
|
|
69
|
+
} else if (o.cid != null) {
|
|
70
|
+
if (typeof o.cid !== 'object' || Array.isArray(o.cid)) fail('`cid` is a map from content id to URL, or a template with `{cid}`');
|
|
71
|
+
for (const k of Object.keys(o.cid).sort()) {
|
|
72
|
+
const v = (o.cid as Record<string, unknown>)[k];
|
|
73
|
+
if (typeof v !== 'string') fail(`\`cid\`: the URL of ${JSON.stringify(k)} is not a string`);
|
|
74
|
+
cidMap.push(contentId(k), v as string);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const media = o.media ?? 'wide';
|
|
78
|
+
if (media !== 'wide' && media !== 'narrow') fail(`\`media\` is 'wide' or 'narrow', not ${JSON.stringify(media)}`);
|
|
79
|
+
const dataImages = o.dataImages ?? 65536;
|
|
80
|
+
if (typeof dataImages !== 'number' || !Number.isInteger(dataImages) || dataImages < 0) fail(`\`dataImages\` is a length in characters, not ${JSON.stringify(dataImages)}`);
|
|
81
|
+
return { images: images as Images, proxy, cidTemplate, cidMap, media: media as 'wide' | 'narrow', dataImages };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const pairs = (flat: string[]) => {
|
|
85
|
+
const m = new Map<string, string>();
|
|
86
|
+
for (let i = 0; i < flat.length; i += 2) m.set(flat[i], flat[i + 1]);
|
|
87
|
+
return m;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** a content id as `cid:` URLs and Content-ID headers write it, without `<>` and percent-encoding */
|
|
91
|
+
function contentId(s: string): string {
|
|
92
|
+
let v = s.trim();
|
|
93
|
+
if (v.startsWith('<') && v.endsWith('>')) v = v.slice(1, -1);
|
|
94
|
+
try {
|
|
95
|
+
v = decodeURIComponent(v);
|
|
96
|
+
} catch {
|
|
97
|
+
// a lone `%`: as written
|
|
98
|
+
}
|
|
99
|
+
return v;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── URLs ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
/** an absolute URL with one of `schemes`, normalized by the URL standard (which strips what disguises a scheme), or null */
|
|
105
|
+
function absolute(value: string, schemes: readonly string[]): URL | null {
|
|
106
|
+
if (!/^\s*[a-z][a-z\d+.-]*:/i.test(value)) return null;
|
|
107
|
+
let u: URL;
|
|
108
|
+
try {
|
|
109
|
+
u = new URL(value);
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
return schemes.includes(u.protocol) ? u : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A URL the app gave (a proxy, a `cid:` target): a path on the app's own site, an https: URL, or for
|
|
118
|
+
* `cid:` maps a raster `data:` URL or a `blob:` URL. Never one an email wrote.
|
|
119
|
+
*/
|
|
120
|
+
function appUrl(value: string): boolean {
|
|
121
|
+
if (value.startsWith('/') && !value.startsWith('//') && !value.includes('\\')) return true;
|
|
122
|
+
return absolute(value, ['https:', 'http:', 'blob:']) !== null || RASTER.test(value);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** a raster image as a base64 `data:` URL: never SVG, which may hold script */
|
|
126
|
+
const RASTER = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z\d+/=\s]*$/i;
|
|
127
|
+
|
|
128
|
+
// ── The tree ──────────────────────────────────────────────────────────────────────────────────────────
|
|
129
|
+
|
|
130
|
+
interface Context {
|
|
131
|
+
o: Options;
|
|
132
|
+
/** the fragment names in-email links point to */
|
|
133
|
+
targets: Set<string>;
|
|
134
|
+
/** the ids given so far: the first element with an id keeps it, as the browser's getElementById finds it */
|
|
135
|
+
ids: Set<string>;
|
|
136
|
+
origins: Set<string>;
|
|
137
|
+
styles: Map<RawElement, Style>;
|
|
138
|
+
/** projected(): the style kept per resolved style and tag */
|
|
139
|
+
projected: Map<Style, Map<Tag, Style>>;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function build(html: string, o: Options): Body {
|
|
143
|
+
const root = parseHTML(html);
|
|
144
|
+
const { styles, colorScheme, dark } = resolve(root, { media: o.media });
|
|
145
|
+
const body = root.children.find((n): n is RawElement => n.type === 'element' && n.tag === 'body');
|
|
146
|
+
const cx: Context = { o, targets: new Set(), ids: new Set(), origins: new Set(), styles, projected: new Map() };
|
|
147
|
+
if (body) collectTargets(body, cx.targets);
|
|
148
|
+
const children = body ? nodes(body, 'body', cx) : [];
|
|
149
|
+
// the body's style is the root's: its text properties and its background, the <html> element's under it
|
|
150
|
+
const style: Style = {};
|
|
151
|
+
for (const el of [root, body]) {
|
|
152
|
+
const s = el && styles.get(el);
|
|
153
|
+
if (!s) continue;
|
|
154
|
+
for (const p of ROOT_PROPS) if (s[p] !== undefined) style[p] = s[p];
|
|
155
|
+
}
|
|
156
|
+
const out: Body = { type: 'body', style, children, images: { origins: [...cx.origins].sort() } };
|
|
157
|
+
// the schemes it is written for: what it declares, and dark too when its colours change with the scheme
|
|
158
|
+
const schemes = (['light', 'dark'] as const).filter((s) => colorScheme.includes(s) || (s === 'dark' && dark));
|
|
159
|
+
if (schemes.length) out.schemes = schemes;
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const ROOT_PROPS: readonly Property[] = [...TEXT, 'background-color'];
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The fragments in-email links point at that the email has (an id, or an old-style `<a name>`): such a
|
|
167
|
+
* link keeps its href, and its target its id. Every other id is left out, and every other fragment link
|
|
168
|
+
* loses its href.
|
|
169
|
+
*/
|
|
170
|
+
function collectTargets(body: RawElement, out: Set<string>): void {
|
|
171
|
+
const linked = new Set<string>(), named = new Set<string>();
|
|
172
|
+
const stack: RawElement[] = [body];
|
|
173
|
+
while (stack.length) {
|
|
174
|
+
const el = stack.pop()!;
|
|
175
|
+
const id = attr(el, 'id');
|
|
176
|
+
if (id) named.add(id);
|
|
177
|
+
if (el.tag === 'a') {
|
|
178
|
+
const name = attr(el, 'name');
|
|
179
|
+
if (name) named.add(name);
|
|
180
|
+
const href = attr(el, 'href')?.trim();
|
|
181
|
+
if (href?.startsWith('#') && href.length > 1) linked.add(fragment(href));
|
|
182
|
+
}
|
|
183
|
+
for (const c of el.children) if (c.type === 'element') stack.push(c);
|
|
184
|
+
}
|
|
185
|
+
for (const f of linked) if (named.has(f)) out.add(f);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function fragment(href: string): string {
|
|
189
|
+
try {
|
|
190
|
+
return decodeURIComponent(href.slice(1));
|
|
191
|
+
} catch {
|
|
192
|
+
return href.slice(1);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Where an element may stand inside a table (the components render a table's structure in one
|
|
198
|
+
* component, so the tree must hold only these there; the HTML parser already builds this shape, and
|
|
199
|
+
* this keeps it whatever a renamed or unknown element does)
|
|
200
|
+
*/
|
|
201
|
+
const TABLE_CHILDREN: Readonly<Record<string, ReadonlySet<Tag>>> = {
|
|
202
|
+
table: new Set(['caption', 'colgroup', 'thead', 'tbody', 'tfoot']),
|
|
203
|
+
colgroup: new Set(['col']),
|
|
204
|
+
thead: new Set(['tr']),
|
|
205
|
+
tbody: new Set(['tr']),
|
|
206
|
+
tfoot: new Set(['tr']),
|
|
207
|
+
tr: new Set(['td', 'th']),
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/** the children of `el`, which became `tag` */
|
|
211
|
+
function nodes(el: RawElement, tag: string, cx: Context): Node[] {
|
|
212
|
+
const allowed = TABLE_CHILDREN[tag];
|
|
213
|
+
const out: Node[] = [];
|
|
214
|
+
for (const c of el.children) {
|
|
215
|
+
if (c.type === 'text') {
|
|
216
|
+
if (allowed) continue; // whitespace between rows and cells: not rendered, and not placeable
|
|
217
|
+
const last = out[out.length - 1];
|
|
218
|
+
if (last?.type === 'text') out[out.length - 1] = { type: 'text', value: last.value + c.value };
|
|
219
|
+
else if (c.value) out.push({ type: 'text', value: c.value });
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const n = element(c, cx);
|
|
223
|
+
if (!n) continue;
|
|
224
|
+
if (allowed && !allowed.has(n.tag)) continue;
|
|
225
|
+
// a table part outside its place (the parser never builds one; kept out all the same)
|
|
226
|
+
if (!allowed && TAGS[n.tag].inTable) continue;
|
|
227
|
+
out.push(n);
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function element(el: RawElement, cx: Context): Element | null {
|
|
233
|
+
if (DROP.has(el.tag)) return null;
|
|
234
|
+
const tag: Tag = el.tag in TAGS ? (el.tag as Tag) : RENAME[el.tag] ?? 'span';
|
|
235
|
+
const info = TAGS[tag];
|
|
236
|
+
const attrs: Attrs = {};
|
|
237
|
+
for (const name of ATTRS[tag]) {
|
|
238
|
+
const raw = attr(el, name);
|
|
239
|
+
if (raw === null) continue;
|
|
240
|
+
const v = attribute(tag, name, raw, cx);
|
|
241
|
+
if (v !== null) attrs[name] = v;
|
|
242
|
+
}
|
|
243
|
+
// an old-style anchor, <a name="top">, is a target as an id is
|
|
244
|
+
if (tag === 'a' && attrs.id === undefined) {
|
|
245
|
+
const name = attr(el, 'name');
|
|
246
|
+
if (name !== null && cx.targets.has(name) && !cx.ids.has(name)) {
|
|
247
|
+
cx.ids.add(name);
|
|
248
|
+
attrs.id = name;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (tag === 'img') image(el, attrs, cx);
|
|
252
|
+
const style = projected(cx.styles.get(el), tag, cx);
|
|
253
|
+
return { type: 'element', tag, attrs, style, children: info.void ? [] : nodes(el, tag, cx) };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** each tag's attributes, GLOBAL included (attrsOf), listed once */
|
|
257
|
+
const ATTRS = Object.fromEntries(Object.keys(TAGS).map((t) => [t, attrsOf(t as Tag)])) as Record<Tag, readonly (keyof Attrs)[]>;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The resolved style with only the properties `tag` binds. The cascade shares one resolved style among the
|
|
261
|
+
* elements that have the same, so this shares one result per resolved style and tag, as one object of the tree.
|
|
262
|
+
*/
|
|
263
|
+
function projected(resolved: Style | undefined, tag: Tag, cx: Context): Style {
|
|
264
|
+
if (!resolved) return {};
|
|
265
|
+
let byTag = cx.projected.get(resolved);
|
|
266
|
+
if (!byTag) cx.projected.set(resolved, (byTag = new Map()));
|
|
267
|
+
let style = byTag.get(tag);
|
|
268
|
+
if (!style) {
|
|
269
|
+
style = {};
|
|
270
|
+
for (const p of TAGS[tag].props) if (resolved[p] !== undefined) style[p] = resolved[p];
|
|
271
|
+
byTag.set(tag, style);
|
|
272
|
+
}
|
|
273
|
+
return style;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const INTEGER = /^\s*\d{1,9}\s*$/;
|
|
277
|
+
const KEYWORDS: Readonly<Record<string, readonly string[]>> = {
|
|
278
|
+
dir: ['ltr', 'rtl', 'auto'],
|
|
279
|
+
scope: ['row', 'col', 'rowgroup', 'colgroup'],
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/** an attribute's value as the tree keeps it, or null to leave it out */
|
|
283
|
+
function attribute(tag: Tag, name: keyof Attrs, value: string, cx: Context): string | null {
|
|
284
|
+
switch (name) {
|
|
285
|
+
case 'href': {
|
|
286
|
+
const v = value.trim();
|
|
287
|
+
if (v.startsWith('#')) {
|
|
288
|
+
const f = fragment(v);
|
|
289
|
+
return f && cx.targets.has(f) ? '#mail-' + encodeURIComponent(f) : null;
|
|
290
|
+
}
|
|
291
|
+
const u = absolute(v, ['http:', 'https:', 'mailto:', 'tel:']);
|
|
292
|
+
return u ? u.href : null;
|
|
293
|
+
}
|
|
294
|
+
case 'cite': {
|
|
295
|
+
const u = absolute(value.trim(), ['http:', 'https:']);
|
|
296
|
+
return u ? u.href : null;
|
|
297
|
+
}
|
|
298
|
+
case 'src':
|
|
299
|
+
return null; // images: image()
|
|
300
|
+
case 'id': {
|
|
301
|
+
const v = value;
|
|
302
|
+
if (!v || !cx.targets.has(v) || cx.ids.has(v)) return null;
|
|
303
|
+
cx.ids.add(v);
|
|
304
|
+
return v;
|
|
305
|
+
}
|
|
306
|
+
case 'width':
|
|
307
|
+
case 'height':
|
|
308
|
+
return /^\s*\d{1,5}\s*%?\s*$/.test(value) ? value.replace(/\s/g, '') : null;
|
|
309
|
+
case 'colspan':
|
|
310
|
+
return INTEGER.test(value) ? String(Math.min(Math.max(+value, 1), 1000)) : null;
|
|
311
|
+
case 'rowspan':
|
|
312
|
+
return INTEGER.test(value) ? String(Math.min(+value, 65534)) : null;
|
|
313
|
+
case 'span':
|
|
314
|
+
return INTEGER.test(value) ? String(Math.min(Math.max(+value, 1), 1000)) : null;
|
|
315
|
+
case 'start':
|
|
316
|
+
case 'value':
|
|
317
|
+
return /^\s*-?\d{1,9}\s*$/.test(value) ? String(+value) : null;
|
|
318
|
+
case 'reversed':
|
|
319
|
+
case 'open':
|
|
320
|
+
return '';
|
|
321
|
+
case 'type':
|
|
322
|
+
return tag === 'ol' ? (['1', 'a', 'A', 'i', 'I'].includes(value.trim()) ? value.trim() : null)
|
|
323
|
+
: ['disc', 'circle', 'square'].includes(value.trim().toLowerCase()) ? value.trim().toLowerCase() : null;
|
|
324
|
+
case 'dir':
|
|
325
|
+
case 'scope': {
|
|
326
|
+
const v = value.trim().toLowerCase();
|
|
327
|
+
return KEYWORDS[name].includes(v) ? v : null;
|
|
328
|
+
}
|
|
329
|
+
case 'lang':
|
|
330
|
+
return /^[a-z\d-]{1,35}$/i.test(value.trim()) ? value.trim() : null;
|
|
331
|
+
default:
|
|
332
|
+
// text: title, alt, abbr, headers, datetime; bounded, as no email needs a longer one
|
|
333
|
+
return value.length > 2000 ? value.slice(0, 2000) : value;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** an image's `src` under the options, and its origin counted */
|
|
338
|
+
function image(el: RawElement, attrs: Attrs, cx: Context): void {
|
|
339
|
+
const src = (attr(el, 'src') ?? '').trim();
|
|
340
|
+
const { o } = cx;
|
|
341
|
+
if (/^cid:/i.test(src)) {
|
|
342
|
+
const id = contentId(src.slice(4));
|
|
343
|
+
const url = o.cidMap.get(id) ?? (o.cidTemplate ? o.cidTemplate.replace('{cid}', encodeURIComponent(id)) : undefined);
|
|
344
|
+
if (url !== undefined && appUrl(url)) attrs.src = url;
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (/^data:/i.test(src)) {
|
|
348
|
+
const v = src.replace(/\s/g, '');
|
|
349
|
+
if (RASTER.test(v) && v.length <= o.dataImages) attrs.src = v;
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const u = absolute(src, ['http:', 'https:']);
|
|
353
|
+
if (!u) return;
|
|
354
|
+
cx.origins.add(u.origin);
|
|
355
|
+
if (o.images === 'allow') attrs.src = u.href;
|
|
356
|
+
else if (o.images === 'proxy') attrs.src = o.proxy.replace('{url}', encodeURIComponent(u.href));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export type { RawNode };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Generated by scripts/build-entities.mjs from character-entities 2.0.2 and character-entities-legacy 3.0.0; do not edit.
|
|
2
|
+
// The named character references, packed (see the script): unpacked once, when the parser loads.
|
|
3
|
+
|
|
4
|
+
const PACKED =
|
|
5
|
+
'9 Tab 1 NewLine n excl 1 QUOT!,quot! 1 num 1 dollar 1 percnt 1 AMP!,amp! 1 apos 1 lpar 1 rpar 1 ast,midast 1 plus 1 comma 2 period 1 sol b colon 1 semi 1 LT!,lt! 0+6he nvlt 1 equals 0+6hx bne 1 GT!,gt! 0+6he nvgt 1 quest 1 commat r lbrack,lsqb 1 bsol 1 rbrack,rsqb 1 Hat 1 UnderBar,lowbar 1 DiacriticalGrave,grave 6+2y fjlig l lbrace,lcub 1 VerticalLine,verbar,vert 1 rbrace,rcub z NonBreakingSpace,nbsp! 1 iexcl! 1 cent! 1 pound! 1 curren! 1 yen! 1 brvbar! 1 sect! 1 Dot,DoubleDot,die,uml! 1 COPY!,copy! 1 ordf! 1 laquo! 1 not! 1 shy! 1 REG!,circledR,reg! 1 macr!,strns 1 deg! 1 PlusMinus,plusmn!,pm 1 sup2! 1 sup3! 1 DiacriticalAcute,acute! 1 micro! 1 para! 1 CenterDot,centerdot,middot! 1 Cedilla,cedil! 1 sup1! 1 ordm! 1 raquo! 1 frac14! 1 frac12!,half 1 frac34! 1 iquest! 1 Agrave! 1 Aacute! 1 Acirc! 1 Atilde! 1 Auml! 1 Aring!,angst 1 AElig! 1 Ccedil! 1 Egrave! 1 Eacute! 1 Ecirc! 1 Euml! 1 Igrave! 1 Iacute! 1 Icirc! 1 Iuml! 1 ETH! 1 Ntilde! 1 Ograve! 1 Oacute! 1 Ocirc! 1 Otilde! 1 Ouml! 1 times! 1 Oslash! 1 Ugrave! 1 Uacute! 1 Ucirc! 1 Uuml! 1 Yacute! 1 THORN! 1 szlig! 1 agrave! 1 aacute! 1 acirc! 1 atilde! 1 auml! 1 aring! 1 aelig! 1 ccedil! 1 egrave! 1 eacute! 1 ecirc! 1 euml! 1 igrave! 1 iacute! 1 icirc! 1 iuml! 1 eth! 1 ntilde! 1 ograve! 1 oacute! 1 ocirc! 1 otilde! 1 ouml! 1 div,divide! 1 oslash! 1 ugrave! 1 uacute! 1 ucirc! 1 uuml! 1 yacute! 1 thorn! 1 yuml! 1 Amacr 1 amacr 1 Abreve 1 abreve 1 Aogon 1 aogon 1 Cacute 1 cacute 1 Ccirc 1 ccirc 1 Cdot 1 cdot 1 Ccaron 1 ccaron 1 Dcaron 1 dcaron 1 Dstrok 1 dstrok 1 Emacr 1 emacr 3 Edot 1 edot 1 Eogon 1 eogon 1 Ecaron 1 ecaron 1 Gcirc 1 gcirc 1 Gbreve 1 gbreve 1 Gdot 1 gdot 1 Gcedil 2 Hcirc 1 hcirc 1 Hstrok 1 hstrok 1 Itilde 1 itilde 1 Imacr 1 imacr 3 Iogon 1 iogon 1 Idot 1 imath,inodot 1 IJlig 1 ijlig 1 Jcirc 1 jcirc 1 Kcedil 1 kcedil 1 kgreen 1 Lacute 1 lacute 1 Lcedil 1 lcedil 1 Lcaron 1 lcaron 1 Lmidot 1 lmidot 1 Lstrok 1 lstrok 1 Nacute 1 nacute 1 Ncedil 1 ncedil 1 Ncaron 1 ncaron 1 napos 1 ENG 1 eng 1 Omacr 1 omacr 3 Odblac 1 odblac 1 OElig 1 oelig 1 Racute 1 racute 1 Rcedil 1 rcedil 1 Rcaron 1 rcaron 1 Sacute 1 sacute 1 Scirc 1 scirc 1 Scedil 1 scedil 1 Scaron 1 scaron 1 Tcedil 1 tcedil 1 Tcaron 1 tcaron 1 Tstrok 1 tstrok 1 Utilde 1 utilde 1 Umacr 1 umacr 1 Ubreve 1 ubreve 1 Uring 1 uring 1 Udblac 1 udblac 1 Uogon 1 uogon 1 Wcirc 1 wcirc 1 Ycirc 1 ycirc 1 Yuml 1 Zacute 1 zacute 1 Zdot 1 zdot 1 Zcaron 1 zcaron k fnof z imped 1s gacute 1u jmath 3z circ 1 Hacek,caron h Breve,breve 1 DiacriticalDot,dot 1 ring 1 ogon 1 DiacriticalTilde,tilde 1 DiacriticalDoubleAcute,dblac 1g DownBreve 3k Alpha 1 Beta 1 Gamma 1 Delta 1 Epsilon 1 Zeta 1 Eta 1 Theta 1 Iota 1 Kappa 1 Lambda 1 Mu 1 Nu 1 Xi 1 Omicron 1 Pi 1 Rho 2 Sigma 1 Tau 1 Upsilon 1 Phi 1 Chi 1 Psi 1 Omega,ohm 8 alpha 1 beta 1 gamma 1 delta 1 epsi,epsilon 1 zeta 1 eta 1 theta 1 iota 1 kappa 1 lambda 1 mu 1 nu 1 xi 1 omicron 1 pi 1 rho 1 sigmaf,sigmav,varsigma 1 sigma 1 tau 1 upsi,upsilon 1 phi 1 chi 1 psi 1 omega 8 thetasym,thetav,vartheta 1 Upsi,upsih 3 phiv,straightphi,varphi 1 piv,varpi 6 Gammad 1 digamma,gammad j kappav,varkappa 1 rhov,varrho 4 epsiv,straightepsilon,varepsilon 1 backepsilon,bepsi b IOcy 1 DJcy 1 GJcy 1 Jukcy 1 DScy 1 Iukcy 1 YIcy 1 Jsercy 1 LJcy 1 NJcy 1 TSHcy 1 KJcy 2 Ubrcy 1 DZcy 1 Acy 1 Bcy 1 Vcy 1 Gcy 1 Dcy 1 IEcy 1 ZHcy 1 Zcy 1 Icy 1 Jcy 1 Kcy 1 Lcy 1 Mcy 1 Ncy 1 Ocy 1 Pcy 1 Rcy 1 Scy 1 Tcy 1 Ucy 1 Fcy 1 KHcy 1 TScy 1 CHcy 1 SHcy 1 SHCHcy 1 HARDcy 1 Ycy 1 SOFTcy 1 Ecy 1 YUcy 1 YAcy 1 acy 1 bcy 1 vcy 1 gcy 1 dcy 1 iecy 1 zhcy 1 zcy 1 icy 1 jcy 1 kcy 1 lcy 1 mcy 1 ncy 1 ocy 1 pcy 1 rcy 1 scy 1 tcy 1 ucy 1 fcy 1 khcy 1 tscy 1 chcy 1 shcy 1 shchcy 1 hardcy 1 ycy 1 softcy 1 ecy 1 yucy 1 yacy 2 iocy 1 djcy 1 gjcy 1 jukcy 1 dscy 1 iukcy 1 yicy 1 jsercy 1 ljcy 1 njcy 1 tshcy 1 kjcy 2 ubrcy 1 dzcy 5gj ensp 1 emsp 1 emsp13 1 emsp14 2 numsp 1 puncsp 1 ThinSpace,thinsp 1 VeryThinSpace,hairsp 1 NegativeMediumSpace,NegativeThickSpace,NegativeThinSpace,NegativeVeryThinSpace,ZeroWidthSpace 1 zwnj 1 zwj 1 lrm 1 rlm 1 dash,hyphen 3 ndash 1 mdash 1 horbar 1 Verbar,Vert 2 OpenCurlyQuote,lsquo 1 CloseCurlyQuote,rsquo,rsquor 1 lsquor,sbquo 2 OpenCurlyDoubleQuote,ldquo 1 CloseCurlyDoubleQuote,rdquo,rdquor 1 bdquo,ldquor 2 dagger 1 Dagger,ddagger 1 bull,bullet 3 nldr 1 hellip,mldr a permil 1 pertenk 1 prime 1 Prime 1 tprime 1 backprime,bprime 4 lsaquo 1 rsaquo 4 OverBar,oline 3 caret 2 hybull 1 frasl b bsemi 8 qprime 8 MediumSpace 0+6bu ThickSpace 1 NoBreak 1 ApplyFunction,af 1 InvisibleTimes,it 1 InvisibleComma,ic 21 euro 1b TripleDot,tdot 1 DotDot 12 Copf,complexes 3 incare 5 gscr 1 HilbertSpace,Hscr,hamilt 1 Hfr,Poincareplane 1 Hopf,quaternions 1 planckh 1 hbar,hslash,planck,plankv 1 Iscr,imagline 1 Ifr,Im,image,imagpart 1 Laplacetrf,Lscr,lagran 1 ell 2 Nopf,naturals 1 numero 1 copysr 1 weierp,wp 1 Popf,primes 1 Qopf,rationals 1 Rscr,realine 1 Re,Rfr,real,realpart 1 Ropf,reals 1 rx 4 TRADE,trade 2 Zopf,integers 3 mho 1 Zfr,zeetrf 1 iiota 3 Bernoullis,Bscr,bernou 1 Cayleys,Cfr 2 escr 1 Escr,expectation 1 Fouriertrf,Fscr 2 Mellintrf,Mscr,phmmat 1 order,orderof,oscr 1 alefsym,aleph 1 beth 1 gimel 1 daleth d CapitalDifferentialD,DD 1 DifferentialD,dd 1 ExponentialE,ee,exponentiale 1 ImaginaryI,ii b frac13 1 frac23 1 frac15 1 frac25 1 frac35 1 frac45 1 frac16 1 frac56 1 frac18 1 frac38 1 frac58 1 frac78 1e LeftArrow,ShortLeftArrow,larr,leftarrow,slarr 1 ShortUpArrow,UpArrow,uarr,uparrow 1 RightArrow,ShortRightArrow,rarr,rightarrow,srarr 1 DownArrow,ShortDownArrow,darr,downarrow 1 LeftRightArrow,harr,leftrightarrow 1 UpDownArrow,updownarrow,varr 1 UpperLeftArrow,nwarr,nwarrow 1 UpperRightArrow,nearr,nearrow 1 LowerRightArrow,searr,searrow 1 LowerLeftArrow,swarr,swarrow 1 nlarr,nleftarrow 1 nrarr,nrightarrow 2 rarrw,rightsquigarrow 0+mw nrarrw 1 Larr,twoheadleftarrow 1 Uarr 1 Rarr,twoheadrightarrow 1 Darr 1 larrtl,leftarrowtail 1 rarrtl,rightarrowtail 1 LeftTeeArrow,mapstoleft 1 UpTeeArrow,mapstoup 1 RightTeeArrow,map,mapsto 1 DownTeeArrow,mapstodown 2 hookleftarrow,larrhk 1 hookrightarrow,rarrhk 1 larrlp,looparrowleft 1 looparrowright,rarrlp 1 harrw,leftrightsquigarrow 1 nharr,nleftrightarrow 2 Lsh,lsh 1 Rsh,rsh 1 ldsh 1 rdsh 2 crarr 1 cularr,curvearrowleft 1 curarr,curvearrowright 3 circlearrowleft,olarr 1 circlearrowright,orarr 1 LeftVector,leftharpoonup,lharu 1 DownLeftVector,leftharpoondown,lhard 1 RightUpVector,uharr,upharpoonright 1 LeftUpVector,uharl,upharpoonleft 1 RightVector,rharu,rightharpoonup 1 DownRightVector,rhard,rightharpoondown 1 RightDownVector,dharr,downharpoonright 1 LeftDownVector,dharl,downharpoonleft 1 RightArrowLeftArrow,rightleftarrows,rlarr 1 UpArrowDownArrow,udarr 1 LeftArrowRightArrow,leftrightarrows,lrarr 1 leftleftarrows,llarr 1 upuparrows,uuarr 1 rightrightarrows,rrarr 1 ddarr,downdownarrows 1 ReverseEquilibrium,leftrightharpoons,lrhar 1 Equilibrium,rightleftharpoons,rlhar 1 nLeftarrow,nlArr 1 nLeftrightarrow,nhArr 1 nRightarrow,nrArr 1 DoubleLeftArrow,Leftarrow,lArr 1 DoubleUpArrow,Uparrow,uArr 1 DoubleRightArrow,Implies,Rightarrow,rArr 1 DoubleDownArrow,Downarrow,dArr 1 DoubleLeftRightArrow,Leftrightarrow,hArr,iff 1 DoubleUpDownArrow,Updownarrow,vArr 1 nwArr 1 neArr 1 seArr 1 swArr 1 Lleftarrow,lAarr 1 Rrightarrow,rAarr 2 zigrarr 7 LeftArrowBar,larrb 1 RightArrowBar,rarrb g DownArrowUpArrow,duarr 8 loarr 1 roarr 1 hoarr 1 ForAll,forall 1 comp,complement 1 PartialD,part 0+mw npart 1 Exists,exist 1 NotExists,nexist,nexists 1 empty,emptyset,emptyv,varnothing 2 Del,nabla 1 Element,in,isin,isinv 1 NotElement,notin,notinva 2 ReverseElement,SuchThat,ni,niv 1 NotReverseElement,notni,notniva 3 Product,prod 1 Coproduct,coprod 1 Sum,sum 1 minus 1 MinusPlus,mnplus,mp 1 dotplus,plusdo 2 Backslash,setminus,setmn,smallsetminus,ssetmn 1 lowast 1 SmallCircle,compfn 2 Sqrt,radic 3 Proportional,prop,propto,varpropto,vprop 1 infin 1 angrt 1 ang,angle 0+6he nang 1 angmsd,measuredangle 1 angsph 1 VerticalBar,mid,shortmid,smid 1 NotVerticalBar,nmid,nshortmid,nsmid 1 DoubleVerticalBar,par,parallel,shortparallel,spar 1 NotDoubleVerticalBar,npar,nparallel,nshortparallel,nspar 1 and,wedge 1 or,vee 1 cap 0+1e68 caps 1 cup 0+1e68 cups 1 Integral,int 1 Int 1 iiint,tint 1 ContourIntegral,conint,oint 1 Conint,DoubleContourIntegral 1 Cconint 1 cwint 1 ClockwiseContourIntegral,cwconint 1 CounterClockwiseContourIntegral,awconint 1 Therefore,there4,therefore 1 Because,becaus,because 1 ratio 1 Colon,Proportion 1 dotminus,minusd 2 mDDot 1 homtht 1 Tilde,sim,thicksim,thksim 0+6he nvsim 1 backsim,bsim 0+mp race 1 ac,mstpos 0+mr acE 1 acd 1 VerticalTilde,wr,wreath 1 NotTilde,nsim 1 EqualTilde,eqsim,esim 0+mw NotEqualTilde,nesim 1 TildeEqual,sime,simeq 1 NotTildeEqual,nsime,nsimeq 1 TildeFullEqual,cong 1 simne 1 NotTildeFullEqual,ncong 1 TildeTilde,ap,approx,asymp,thickapprox,thkap 1 NotTildeTilde,nap,napprox 1 ape,approxeq 1 apid 0+mw napid 1 backcong,bcong 1 CupCap,asympeq 0+6he nvap 1 Bumpeq,HumpDownHump,bump 0+mw NotHumpDownHump,nbump 1 HumpEqual,bumpe,bumpeq 0+mw NotHumpEqual,nbumpe 1 DotEqual,doteq,esdot 0+mw nedot 1 doteqdot,eDot 1 efDot,fallingdotseq 1 erDot,risingdotseq 1 Assign,colone,coloneq 1 ecolon,eqcolon 1 ecir,eqcirc 1 circeq,cire 2 wedgeq 1 veeeq 2 triangleq,trie 3 equest,questeq 1 NotEqual,ne 1 Congruent,equiv 0+6hx bnequiv 1 NotCongruent,nequiv 2 le,leq 0+6he nvle 1 GreaterEqual,ge,geq 0+6he nvge 1 LessFullEqual,lE,leqq 0+mw nlE,nleqq 1 GreaterFullEqual,gE,geqq 0+mw NotGreaterFullEqual,ngE,ngeqq 1 lnE,lneqq 0+1e68 lvertneqq,lvnE 1 gnE,gneqq 0+1e68 gvertneqq,gvnE 1 Lt,NestedLessLess,ll 0+mw NotLessLess,nLtv 0+6he nLt 1 Gt,NestedGreaterGreater,gg 0+mw NotGreaterGreater,nGtv 0+6he nGt 1 between,twixt 1 NotCupCap 1 NotLess,nless,nlt 1 NotGreater,ngt,ngtr 1 NotLessEqual,nle,nleq 1 NotGreaterEqual,nge,ngeq 1 LessTilde,lesssim,lsim 1 GreaterTilde,gsim,gtrsim 1 NotLessTilde,nlsim 1 NotGreaterTilde,ngsim 1 LessGreater,lessgtr,lg 1 GreaterLess,gl,gtrless 1 NotLessGreater,ntlg 1 NotGreaterLess,ntgl 1 Precedes,pr,prec 1 Succeeds,sc,succ 1 PrecedesSlantEqual,prcue,preccurlyeq 1 SucceedsSlantEqual,sccue,succcurlyeq 1 PrecedesTilde,precsim,prsim 1 SucceedsTilde,scsim,succsim 0+mw NotSucceedsTilde 1 NotPrecedes,npr,nprec 1 NotSucceeds,nsc,nsucc 1 sub,subset 0+6he NotSubset,nsubset,vnsub 1 Superset,sup,supset 0+6he NotSuperset,nsupset,vnsup 1 nsub 1 nsup 1 SubsetEqual,sube,subseteq 1 SupersetEqual,supe,supseteq 1 NotSubsetEqual,nsube,nsubseteq 1 NotSupersetEqual,nsupe,nsupseteq 1 subne,subsetneq 0+1e68 varsubsetneq,vsubne 1 supne,supsetneq 0+1e68 varsupsetneq,vsupne 2 cupdot 1 UnionPlus,uplus 1 SquareSubset,sqsub,sqsubset 0+mw NotSquareSubset 1 SquareSuperset,sqsup,sqsupset 0+mw NotSquareSuperset 1 SquareSubsetEqual,sqsube,sqsubseteq 1 SquareSupersetEqual,sqsupe,sqsupseteq 1 SquareIntersection,sqcap 0+1e68 sqcaps 1 SquareUnion,sqcup 0+1e68 sqcups 1 CirclePlus,oplus 1 CircleMinus,ominus 1 CircleTimes,otimes 1 osol 1 CircleDot,odot 1 circledcirc,ocir 1 circledast,oast 2 circleddash,odash 1 boxplus,plusb 1 boxminus,minusb 1 boxtimes,timesb 1 dotsquare,sdotb 1 RightTee,vdash 1 LeftTee,dashv 1 DownTee,top 1 UpTee,bot,bottom,perp 2 models 1 DoubleRightTee,vDash 1 Vdash 1 Vvdash 1 VDash 1 nvdash 1 nvDash 1 nVdash 1 nVDash 1 prurel 2 LeftTriangle,vartriangleleft,vltri 1 RightTriangle,vartriangleright,vrtri 1 LeftTriangleEqual,ltrie,trianglelefteq 0+6he nvltrie 1 RightTriangleEqual,rtrie,trianglerighteq 0+6he nvrtrie 1 origof 1 imof 1 multimap,mumap 1 hercon 1 intcal,intercal 1 veebar 2 barvee 1 angrtvb 1 lrtri 1 Wedge,bigwedge,xwedge 1 Vee,bigvee,xvee 1 Intersection,bigcap,xcap 1 Union,bigcup,xcup 1 Diamond,diam,diamond 1 sdot 1 Star,sstarf 1 divideontimes,divonx 1 bowtie 1 ltimes 1 rtimes 1 leftthreetimes,lthree 1 rightthreetimes,rthree 1 backsimeq,bsime 1 curlyvee,cuvee 1 curlywedge,cuwed 1 Sub,Subset 1 Sup,Supset 1 Cap 1 Cup 1 fork,pitchfork 1 epar 1 lessdot,ltdot 1 gtdot,gtrdot 1 Ll 0+mw nLl 1 Gg,ggg 0+mw nGg 1 LessEqualGreater,leg,lesseqgtr 0+1e68 lesg 1 GreaterEqualLess,gel,gtreqless 0+1e68 gesl 3 cuepr,curlyeqprec 1 cuesc,curlyeqsucc 1 NotPrecedesSlantEqual,nprcue 1 NotSucceedsSlantEqual,nsccue 1 NotSquareSubsetEqual,nsqsube 1 NotSquareSupersetEqual,nsqsupe 3 lnsim 1 gnsim 1 precnsim,prnsim 1 scnsim,succnsim 1 NotLeftTriangle,nltri,ntriangleleft 1 NotRightTriangle,nrtri,ntriangleright 1 NotLeftTriangleEqual,nltrie,ntrianglelefteq 1 NotRightTriangleEqual,nrtrie,ntrianglerighteq 1 vellip 1 ctdot 1 utdot 1 dtdot 1 disin 1 isinsv 1 isins 1 isindot 0+mw notindot 1 notinvc 1 notinvb 2 isinE 0+mw notinE 1 nisd 1 xnis 1 nis 1 notnivc 1 notnivb 7 barwed,barwedge 1 Barwed,doublebarwedge 2 LeftCeiling,lceil 1 RightCeiling,rceil 1 LeftFloor,lfloor 1 RightFloor,rfloor 1 drcrop 1 dlcrop 1 urcrop 1 ulcrop 1 bnot 2 profline 1 profsurf 2 telrec 1 target 6 ulcorn,ulcorner 1 urcorn,urcorner 1 dlcorn,llcorner 1 drcorn,lrcorner 3 frown,sfrown 1 smile,ssmile a cylcty 1 profalar 8 topbot 7 ovbar 2 solbar 1p angzarr 1g lmoust,lmoustache 1 rmoust,rmoustache 3 OverBracket,tbrk 1 UnderBracket,bbrk 1 bbrktbrk 12 OverParenthesis 1 UnderParenthesis 1 OverBrace 1 UnderBrace 3 trpezium 5 elinters 1o blank 4l circledS,oS 1k HorizontalLine,boxh 2 boxv a boxdr 4 boxdl 4 boxur 4 boxul 4 boxvr 8 boxvl 8 boxhd 8 boxhu 8 boxvh k boxH 1 boxV 1 boxdR 1 boxDr 1 boxDR 1 boxdL 1 boxDl 1 boxDL 1 boxuR 1 boxUr 1 boxUR 1 boxuL 1 boxUl 1 boxUL 1 boxvR 1 boxVr 1 boxVR 1 boxvL 1 boxVl 1 boxVL 1 boxHd 1 boxhD 1 boxHD 1 boxHu 1 boxhU 1 boxHU 1 boxvH 1 boxVh 1 boxVH k uhblk 4 lhblk 4 block 9 blk14 1 blk12 1 blk34 e Square,squ,square 9 FilledVerySmallSquare,blacksquare,squarf,squf 1 EmptyVerySmallSquare 2 rect 1 marker 3 fltns 2 bigtriangleup,xutri 1 blacktriangle,utrif 1 triangle,utri 3 blacktriangleright,rtrif 1 rtri,triangleright 4 bigtriangledown,xdtri 1 blacktriangledown,dtrif 1 dtri,triangledown 3 blacktriangleleft,ltrif 1 ltri,triangleleft 7 loz,lozenge 1 cir x tridot 3 bigcirc,xcirc 9 ultri 1 urtri 1 lltri 1 EmptySmallSquare 1 FilledSmallSquare 9 bigstar,starf 1 star 8 phone 1e female 2 male u spades,spadesuit 3 clubs,clubsuit 2 hearts,heartsuit 1 diamondsuit,diams 4 sung 3 flat 1 natur,natural 1 sharp 4k check,checkmark 4 cross 9 malt,maltese m sext y VerticalSeparator q lbbrk 1 rbbrk 2d bsolhsub 1 suphsol t LeftDoubleBracket,lobrk 1 RightDoubleBracket,robrk 1 LeftAngleBracket,lang,langle 1 RightAngleBracket,rang,rangle 1 Lang 1 Rang 1 loang 1 roang 8 LongLeftArrow,longleftarrow,xlarr 1 LongRightArrow,longrightarrow,xrarr 1 LongLeftRightArrow,longleftrightarrow,xharr 1 DoubleLongLeftArrow,Longleftarrow,xlArr 1 DoubleLongRightArrow,Longrightarrow,xrArr 1 DoubleLongLeftRightArrow,Longleftrightarrow,xhArr 2 longmapsto,xmap 3 dzigrarr 77 nvlArr 1 nvrArr 1 nvHarr 1 Map 7 lbarr 1 bkarow,rbarr 1 lBarr 1 dbkarow,rBarr 1 RBarr,drbkarow 1 DDotrahd 1 UpArrowBar 1 DownArrowBar 3 Rarrtl 3 latail 1 ratail 1 lAtail 1 rAtail 1 larrfs 1 rarrfs 1 larrbfs 1 rarrbfs 3 nwarhk 1 nearhk 1 hksearow,searhk 1 hkswarow,swarhk 1 nwnear 1 nesear,toea 1 seswar,tosa 1 swnwar 9 rarrc 0+mw nrarrc 2 cudarrr 1 ldca 1 rdca 1 cudarrl 1 larrpl 3 curarrm 1 cularrp 8 rarrpl 3 harrcir 1 Uarrocir 1 lurdshar 1 ldrushar 3 LeftRightVector 1 RightUpDownVector 1 DownLeftRightVector 1 LeftUpDownVector 1 LeftVectorBar 1 RightVectorBar 1 RightUpVectorBar 1 RightDownVectorBar 1 DownLeftVectorBar 1 DownRightVectorBar 1 LeftUpVectorBar 1 LeftDownVectorBar 1 LeftTeeVector 1 RightTeeVector 1 RightUpTeeVector 1 RightDownTeeVector 1 DownLeftTeeVector 1 DownRightTeeVector 1 LeftUpTeeVector 1 LeftDownTeeVector 1 lHar 1 uHar 1 rHar 1 dHar 1 luruhar 1 ldrdhar 1 ruluhar 1 rdldhar 1 lharul 1 llhard 1 rharul 1 lrhard 1 UpEquilibrium,udhar 1 ReverseUpEquilibrium,duhar 1 RoundImplies 1 erarr 1 simrarr 1 larrsim 1 rarrsim 1 rarrap 1 ltlarr 2 gtrarr 1 subrarr 2 suplarr 1 lfisht 1 rfisht 1 ufisht 1 dfisht 6 lopar 1 ropar 5 lbrke 1 rbrke 1 lbrkslu 1 rbrksld 1 lbrksld 1 rbrkslu 1 langd 1 rangd 1 lparlt 1 rpargt 1 gtlPar 1 ltrPar 4 vzigzag 2 vangrt 1 angrtvbd 7 ange 1 range 1 dwangle 1 uwangle 1 angmsdaa 1 angmsdab 1 angmsdac 1 angmsdad 1 angmsdae 1 angmsdaf 1 angmsdag 1 angmsdah 1 bemptyv 1 demptyv 1 cemptyv 1 raemptyv 1 laemptyv 1 ohbar 1 omid 1 opar 2 operp 2 olcross 1 odsold 2 olcir 1 ofcir 1 olt 1 ogt 1 cirscir 1 cirE 1 solb 1 bsolb 4 boxbox 4 trisb 1 rtriltri 1 LeftTriangleBar 0+mw NotLeftTriangleBar 1 RightTriangleBar 0+mw NotRightTriangleBar c iinfin 1 infintie 1 nvinfin 5 eparsl 1 smeparsl 1 eqvparsl 6 blacklozenge,lozf 9 RuleDelayed 2 dsol a bigodot,xodot 1 bigoplus,xoplus 1 bigotimes,xotime 2 biguplus,xuplus 2 bigsqcup,xsqcup 6 iiiint,qint 1 fpartint 3 cirfnint 1 awint 1 rppolint 1 scpolint 1 npolint 1 pointint 1 quatint 1 intlarhk b pluscir 1 plusacir 1 simplus 1 plusdu 1 plussim 1 plustwo 2 mcomma 1 minusdu 3 loplus 1 roplus 1 Cross 1 timesd 1 timesbar 2 smashp 1 lotimes 1 rotimes 1 otimesas 1 Otimes 1 odiv 1 triplus 1 triminus 1 tritime 1 intprod,iprod 3 amalg 1 capdot 2 ncup 1 ncap 1 capand 1 cupor 1 cupcap 1 capcup 1 cupbrcap 1 capbrcup 1 cupcup 1 capcap 1 ccups 1 ccaps 3 ccupssm 3 And 1 Or 1 andand 1 oror 1 orslope 1 andslope 2 andv 1 orv 1 andd 1 ord 2 wedbar 7 sdote 4 simdot 3 congdot 0+mw ncongdot 1 easter 1 apacir 1 apE 0+mw napE 1 eplus 1 pluse 1 Esim 1 Colone 1 Equal 2 ddotseq,eDDot 1 equivDD 1 ltcir 1 gtcir 1 ltquest 1 gtquest 1 LessSlantEqual,leqslant,les 0+mw NotLessSlantEqual,nleqslant,nles 1 GreaterSlantEqual,geqslant,ges 0+mw NotGreaterSlantEqual,ngeqslant,nges 1 lesdot 1 gesdot 1 lesdoto 1 gesdoto 1 lesdotor 1 gesdotol 1 lap,lessapprox 1 gap,gtrapprox 1 lne,lneq 1 gne,gneq 1 lnap,lnapprox 1 gnap,gnapprox 1 lEg,lesseqqgtr 1 gEl,gtreqqless 1 lsime 1 gsime 1 lsimg 1 gsiml 1 lgE 1 glE 1 lesges 1 gesles 1 els,eqslantless 1 egs,eqslantgtr 1 elsdot 1 egsdot 1 el 1 eg 3 siml 1 simg 1 simlE 1 simgE 1 LessLess 0+mw NotNestedLessLess 1 GreaterGreater 0+mw NotNestedGreaterGreater 2 glj 1 gla 1 ltcc 1 gtcc 1 lescc 1 gescc 1 smt 1 lat 1 smte 0+1e68 smtes 1 late 0+1e68 lates 1 bumpE 1 PrecedesEqual,pre,preceq 0+mw NotPrecedesEqual,npre,npreceq 1 SucceedsEqual,sce,succeq 0+mw NotSucceedsEqual,nsce,nsucceq 3 prE 1 scE 1 precneqq,prnE 1 scnE,succneqq 1 prap,precapprox 1 scap,succapprox 1 precnapprox,prnap 1 scnap,succnapprox 1 Pr 1 Sc 1 subdot 1 supdot 1 subplus 1 supplus 1 submult 1 supmult 1 subedot 1 supedot 1 subE,subseteqq 0+mw nsubE,nsubseteqq 1 supE,supseteqq 0+mw nsupE,nsupseteqq 1 subsim 1 supsim 3 subnE,subsetneqq 0+1e68 varsubsetneqq,vsubnE 1 supnE,supsetneqq 0+1e68 varsupsetneqq,vsupnE 3 csub 1 csup 1 csube 1 csupe 1 subsup 1 supsub 1 subsub 1 supsup 1 suphsub 1 supdsub 1 forkv 1 topfork 1 mlcp 9 Dashv,DoubleLeftTee 2 Vdashl 1 Barv 1 vBar 1 vBarv 2 Vbar 1 Not 1 bNot 1 rnmid 1 cirmid 1 midcir 1 topcir 1 nhpar 1 parsim a parsl 0+6hx nparsl 1537 fflig 1 filig 1 fllig 1 ffilig 1 ffllig 16zc Ascr 2 Cscr 1 Dscr 3 Gscr 3 Jscr 1 Kscr 3 Nscr 1 Oscr 1 Pscr 1 Qscr 2 Sscr 1 Tscr 1 Uscr 1 Vscr 1 Wscr 1 Xscr 1 Yscr 1 Zscr 1 ascr 1 bscr 1 cscr 1 dscr 2 fscr 2 hscr 1 iscr 1 jscr 1 kscr 1 lscr 1 mscr 1 nscr 2 pscr 1 qscr 1 rscr 1 sscr 1 tscr 1 uscr 1 vscr 1 wscr 1 xscr 1 yscr 1 zscr 1h Afr 1 Bfr 2 Dfr 1 Efr 1 Ffr 1 Gfr 3 Jfr 1 Kfr 1 Lfr 1 Mfr 1 Nfr 1 Ofr 1 Pfr 1 Qfr 2 Sfr 1 Tfr 1 Ufr 1 Vfr 1 Wfr 1 Xfr 1 Yfr 2 afr 1 bfr 1 cfr 1 dfr 1 efr 1 ffr 1 gfr 1 hfr 1 ifr 1 jfr 1 kfr 1 lfr 1 mfr 1 nfr 1 ofr 1 pfr 1 qfr 1 rfr 1 sfr 1 tfr 1 ufr 1 vfr 1 wfr 1 xfr 1 yfr 1 zfr 1 Aopf 1 Bopf 2 Dopf 1 Eopf 1 Fopf 1 Gopf 2 Iopf 1 Jopf 1 Kopf 1 Lopf 1 Mopf 2 Oopf 4 Sopf 1 Topf 1 Uopf 1 Vopf 1 Wopf 1 Xopf 1 Yopf 2 aopf 1 bopf 1 copf 1 dopf 1 eopf 1 fopf 1 gopf 1 hopf 1 iopf 1 jopf 1 kopf 1 lopf 1 mopf 1 nopf 1 oopf 1 popf 1 qopf 1 ropf 1 sopf 1 topf 1 uopf 1 vopf 1 wopf 1 xopf 1 yopf 1 zopf';
|
|
6
|
+
|
|
7
|
+
/** every named character reference, by its name without `;` */
|
|
8
|
+
export const ENTITIES: ReadonlyMap<string, string> = new Map();
|
|
9
|
+
/** the names that are also references without `;` (`&`, `©`) */
|
|
10
|
+
export const LEGACY: ReadonlySet<string> = new Set();
|
|
11
|
+
|
|
12
|
+
const fields = PACKED.split(' ');
|
|
13
|
+
for (let i = 0, code = 0; i < fields.length; i += 2) {
|
|
14
|
+
const [delta, second] = fields[i].split('+');
|
|
15
|
+
code += parseInt(delta, 36);
|
|
16
|
+
const value = String.fromCodePoint(code) + (second ? String.fromCodePoint(parseInt(second, 36)) : '');
|
|
17
|
+
for (const name of fields[i + 1].split(',')) {
|
|
18
|
+
const bare = name.replace('!', '');
|
|
19
|
+
(ENTITIES as Map<string, string>).set(bare, value);
|
|
20
|
+
if (bare !== name) (LEGACY as Set<string>).add(bare);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The HTML parser: an email's HTML as the raw tree of sinter/raw.ts, the document the browser builds from it
|
|
2
|
+
// (the standard's tokenizer and tree construction, tokenizer.ts and tree.ts), without its comments, doctype,
|
|
3
|
+
// foreign content (`<svg>`, `<math>`, dropped with their subtrees) and template contents.
|
|
4
|
+
//
|
|
5
|
+
// Pure and self-contained: it imports nothing outside this folder and uses no global beyond the language's,
|
|
6
|
+
// so sinter can run it at build time and in the browser alike.
|
|
7
|
+
import type { RawElement, RawNode } from '../raw.js';
|
|
8
|
+
import { build, HTML, type Node } from './tree.js';
|
|
9
|
+
|
|
10
|
+
export interface ParseHTMLOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The deepest an element may be nested, the `<html>` element being 1 (default 256). An element that would
|
|
13
|
+
* open deeper goes beside the element at the bound instead of inside it, as browsers bound their trees,
|
|
14
|
+
* so a hostile email can neither build a tree deeper than this nor make the parse slower than linear.
|
|
15
|
+
*/
|
|
16
|
+
maxDepth?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** `html` parsed as the browser parses it: its `<html>` element */
|
|
20
|
+
export function parseHTML(html: string, options?: ParseHTMLOptions): RawElement {
|
|
21
|
+
const max = Math.max(3, Math.floor(options?.maxDepth ?? 256));
|
|
22
|
+
return toRaw(build(String(html), max), max);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** the parse's tree as raw nodes: foreign elements and template contents left out, adjacent texts joined */
|
|
26
|
+
function toRaw(root: Node, max: number): RawElement {
|
|
27
|
+
const out: RawElement = { type: 'element', tag: root.tag, attrs: copy(root), children: [], parent: null };
|
|
28
|
+
// depth first without recursion (a tree can be as deep as `max`); each entry a node, its parent and the parent's depth
|
|
29
|
+
const todo: [Node | string, RawElement, number][] = [];
|
|
30
|
+
const add = (n: Node, into: RawElement, depth: number): void => {
|
|
31
|
+
for (let i = n.kids.length - 1; i >= 0; i--) todo.push([n.kids[i], into, depth]);
|
|
32
|
+
};
|
|
33
|
+
add(root, out, 1);
|
|
34
|
+
while (todo.length) {
|
|
35
|
+
const [n, into, depth] = todo.pop()!;
|
|
36
|
+
if (typeof n === 'string') {
|
|
37
|
+
const last = into.children[into.children.length - 1];
|
|
38
|
+
if (last?.type === 'text') last.value += n;
|
|
39
|
+
else into.children.push({ type: 'text', value: n });
|
|
40
|
+
} else if (n.ns === HTML) {
|
|
41
|
+
if (depth >= max) {
|
|
42
|
+
// deeper than the bound, which only the adoption agency's moves can make: its content goes in its place
|
|
43
|
+
add(n, into, depth);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const el: RawElement = { type: 'element', tag: n.tag, attrs: copy(n), children: [], parent: into };
|
|
47
|
+
into.children.push(el as RawNode);
|
|
48
|
+
add(n, el, depth + 1);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const copy = (n: Node): [string, string][] => n.attrs.map(([a, v]) => [a, v]);
|