@tiavision/sinter-mail 0.0.0-stage → 0.1.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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/docs/mail.md +267 -0
  4. package/docs/proposals/progressive-rendering.md +180 -0
  5. package/docs/proposals/sinter-mail.md +520 -0
  6. package/llms.txt +20 -0
  7. package/package.json +65 -4
  8. package/sinter/autolink.ts +98 -0
  9. package/sinter/components/internal/mail-a.html +5 -0
  10. package/sinter/components/internal/mail-abbr.html +5 -0
  11. package/sinter/components/internal/mail-address.html +5 -0
  12. package/sinter/components/internal/mail-article.html +5 -0
  13. package/sinter/components/internal/mail-aside.html +5 -0
  14. package/sinter/components/internal/mail-b.html +5 -0
  15. package/sinter/components/internal/mail-bdi.html +5 -0
  16. package/sinter/components/internal/mail-bdo.html +5 -0
  17. package/sinter/components/internal/mail-blockquote.html +5 -0
  18. package/sinter/components/internal/mail-br.html +5 -0
  19. package/sinter/components/internal/mail-center.html +5 -0
  20. package/sinter/components/internal/mail-cite.html +5 -0
  21. package/sinter/components/internal/mail-code.html +5 -0
  22. package/sinter/components/internal/mail-dd.html +5 -0
  23. package/sinter/components/internal/mail-del.html +5 -0
  24. package/sinter/components/internal/mail-details.html +5 -0
  25. package/sinter/components/internal/mail-dfn.html +5 -0
  26. package/sinter/components/internal/mail-div.html +5 -0
  27. package/sinter/components/internal/mail-dl.html +5 -0
  28. package/sinter/components/internal/mail-dt.html +5 -0
  29. package/sinter/components/internal/mail-em.html +5 -0
  30. package/sinter/components/internal/mail-figcaption.html +5 -0
  31. package/sinter/components/internal/mail-figure.html +5 -0
  32. package/sinter/components/internal/mail-font.html +5 -0
  33. package/sinter/components/internal/mail-footer.html +5 -0
  34. package/sinter/components/internal/mail-h1.html +5 -0
  35. package/sinter/components/internal/mail-h2.html +5 -0
  36. package/sinter/components/internal/mail-h3.html +5 -0
  37. package/sinter/components/internal/mail-h4.html +5 -0
  38. package/sinter/components/internal/mail-h5.html +5 -0
  39. package/sinter/components/internal/mail-h6.html +5 -0
  40. package/sinter/components/internal/mail-header.html +5 -0
  41. package/sinter/components/internal/mail-hr.html +5 -0
  42. package/sinter/components/internal/mail-i.html +5 -0
  43. package/sinter/components/internal/mail-img.html +5 -0
  44. package/sinter/components/internal/mail-ins.html +5 -0
  45. package/sinter/components/internal/mail-kbd.html +5 -0
  46. package/sinter/components/internal/mail-li.html +5 -0
  47. package/sinter/components/internal/mail-main.html +5 -0
  48. package/sinter/components/internal/mail-mark.html +5 -0
  49. package/sinter/components/internal/mail-nav.html +5 -0
  50. package/sinter/components/internal/mail-node.html +5 -0
  51. package/sinter/components/internal/mail-ol.html +5 -0
  52. package/sinter/components/internal/mail-orphan.html +5 -0
  53. package/sinter/components/internal/mail-p.html +5 -0
  54. package/sinter/components/internal/mail-pre.html +5 -0
  55. package/sinter/components/internal/mail-q.html +5 -0
  56. package/sinter/components/internal/mail-s.html +5 -0
  57. package/sinter/components/internal/mail-samp.html +5 -0
  58. package/sinter/components/internal/mail-section.html +5 -0
  59. package/sinter/components/internal/mail-small.html +5 -0
  60. package/sinter/components/internal/mail-span.html +5 -0
  61. package/sinter/components/internal/mail-steps.html +5 -0
  62. package/sinter/components/internal/mail-steps.ts +46 -0
  63. package/sinter/components/internal/mail-strike.html +5 -0
  64. package/sinter/components/internal/mail-strong.html +5 -0
  65. package/sinter/components/internal/mail-sub.html +5 -0
  66. package/sinter/components/internal/mail-summary.html +5 -0
  67. package/sinter/components/internal/mail-sup.html +5 -0
  68. package/sinter/components/internal/mail-table.html +5 -0
  69. package/sinter/components/internal/mail-time.html +5 -0
  70. package/sinter/components/internal/mail-tt.html +5 -0
  71. package/sinter/components/internal/mail-u.html +5 -0
  72. package/sinter/components/internal/mail-ul.html +5 -0
  73. package/sinter/components/internal/mail-var.html +5 -0
  74. package/sinter/components/internal/mail-wbr.html +5 -0
  75. package/sinter/components/mail-body.html +21 -0
  76. package/sinter/css/hints.ts +259 -0
  77. package/sinter/css/index.ts +270 -0
  78. package/sinter/css/media.ts +251 -0
  79. package/sinter/css/parse.ts +124 -0
  80. package/sinter/css/selectors.ts +530 -0
  81. package/sinter/css/tokenize.ts +279 -0
  82. package/sinter/css/values.ts +647 -0
  83. package/sinter/engine.ts +6 -0
  84. package/sinter/index.ts +5 -0
  85. package/sinter/parse.ts +355 -0
  86. package/sinter/parser/entities.ts +22 -0
  87. package/sinter/parser/index.ts +54 -0
  88. package/sinter/parser/tokenizer.ts +275 -0
  89. package/sinter/parser/tree.ts +1265 -0
  90. package/sinter/plain.ts +125 -0
  91. package/sinter/raw.ts +28 -0
  92. package/sinter/sinter.helpers.ts +11 -0
  93. package/sinter/sinter.types.ts +135 -0
  94. package/sinter/tags.ts +169 -0
  95. package/sinter/tree.ts +168 -0
@@ -0,0 +1,530 @@
1
+ // Selectors (Selectors Level 4): parsed from a rule's prelude, matched against the raw tree.
2
+ //
3
+ // Three outcomes for a selector list, as a browser has them: invalid (the whole rule is dropped, as CSS
4
+ // drops a rule with any invalid selector in its list), a selector this cannot match (valid CSS that
5
+ // depends on state a static email has no say in: `:hover`, `::before`, `:focus`; that selector never
6
+ // matches, the rest of the list still does), or a selector to match.
7
+ //
8
+ // Matching runs right to left over the parent pointers, with the three failure kinds of WebKit's
9
+ // SelectorChecker, so a chain of descendant combinators stays linear in the tree's depth.
10
+ import { attr, type RawElement } from '../raw.js';
11
+ import type { CV, Token } from './tokenize.js';
12
+
13
+ export type Combinator = ' ' | '>' | '+' | '~';
14
+
15
+ type Simple =
16
+ | { k: 'tag'; v: string }
17
+ | { k: 'id'; v: string }
18
+ | { k: 'class'; v: string }
19
+ | { k: 'attr'; name: string; op: '' | '=' | '~=' | '|=' | '^=' | '$=' | '*='; v: string; i: boolean }
20
+ | { k: 'never' }
21
+ | { k: 'root' | 'empty' | 'link' }
22
+ | { k: 'nth'; last: boolean; type: boolean; a: number; b: number; of: Complex[] | null }
23
+ | { k: 'not' | 'is'; list: Complex[] };
24
+
25
+ export interface Compound {
26
+ simple: Simple[];
27
+ }
28
+
29
+ export interface Complex {
30
+ /** compounds left to right */
31
+ compounds: Compound[];
32
+ /** combinators[i] sits between compounds[i] and compounds[i + 1] */
33
+ combinators: Combinator[];
34
+ /** packed (a, b, c) */
35
+ specificity: number;
36
+ }
37
+
38
+ const spec = (a: number, b: number, c: number) => a * 1_000_000 + b * 1_000 + c;
39
+
40
+ class Invalid extends Error {}
41
+
42
+ // valid in Chromium, and never true of a static email (or of what it keeps of one)
43
+ const NEVER_CLASSES = new Set([
44
+ 'hover', 'active', 'focus', 'focus-within', 'focus-visible', 'visited', 'target', 'target-within', 'checked',
45
+ 'disabled', 'enabled', 'default', 'indeterminate', 'valid', 'invalid', 'in-range', 'out-of-range', 'required',
46
+ 'optional', 'read-only', 'read-write', 'placeholder-shown', 'autofill', '-webkit-autofill', 'fullscreen',
47
+ 'modal', 'picture-in-picture', 'playing', 'paused', 'defined', 'user-invalid', 'user-valid', 'open', 'popover-open',
48
+ 'host', 'current', 'past', 'future', 'blank', 'lang', 'dir', 'has', 'state', 'host-context',
49
+ '-webkit-any', '-webkit-full-screen', 'window-inactive', 'horizontal', 'vertical', 'decrement', 'increment',
50
+ 'start', 'end', 'double-button', 'single-button', 'no-button', 'corner-present',
51
+ ]);
52
+ const NEVER_ELEMENTS = new Set([
53
+ 'before', 'after', 'first-line', 'first-letter', 'selection', 'placeholder', 'marker', 'backdrop', 'file-selector-button',
54
+ 'cue', 'part', 'slotted', 'highlight', 'spelling-error', 'grammar-error', 'target-text', 'view-transition', 'search-text',
55
+ 'details-content', 'picker', 'column', 'scroll-marker', 'scroll-button',
56
+ ]);
57
+ // the legacy pseudo-elements written with one colon
58
+ const LEGACY_ELEMENTS = new Set(['before', 'after', 'first-line', 'first-letter']);
59
+
60
+ const ws = (v: CV | undefined) => v?.t === 'ws';
61
+
62
+ /**
63
+ * A rule prelude as a selector list: null when invalid (the rule is dropped); a selector this cannot
64
+ * match is left out of the list, so the list can be empty.
65
+ */
66
+ export function parseSelectorList(prelude: CV[]): Complex[] | null {
67
+ try {
68
+ return list(prelude, false, 0).filter((c) => !c.compounds.some(isNever));
69
+ } catch (e) {
70
+ if (e instanceof Invalid) return null;
71
+ throw e;
72
+ }
73
+ }
74
+
75
+ // a nesting bound: `:not(:not(…` deeper than this is invalid rather than a deep recursion
76
+ const MAX_DEPTH = 32;
77
+
78
+ function list(items: CV[], forgiving: boolean, depth: number): Complex[] {
79
+ if (depth > MAX_DEPTH) throw new Invalid();
80
+ const parts: CV[][] = [[]];
81
+ for (const v of items) {
82
+ if (v.t === ',') parts.push([]);
83
+ else parts[parts.length - 1].push(v);
84
+ }
85
+ const out: Complex[] = [];
86
+ for (const p of parts) {
87
+ try {
88
+ out.push(complex(p, depth));
89
+ } catch (e) {
90
+ if (!(e instanceof Invalid) || !forgiving) throw e;
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+
96
+ function isNever(c: Compound): boolean {
97
+ return c.simple.some((s) => s.k === 'never');
98
+ }
99
+
100
+ function complex(items: CV[], depth: number): Complex {
101
+ let i = 0;
102
+ while (ws(items[i])) i++;
103
+ let end = items.length;
104
+ while (end > i && ws(items[end - 1])) end--;
105
+ if (i >= end) throw new Invalid();
106
+ const compounds: Compound[] = [];
107
+ const combinators: Combinator[] = [];
108
+ let a = 0, b = 0, c = 0;
109
+ for (;;) {
110
+ const r = compound(items, i, end, depth);
111
+ compounds.push(r.compound);
112
+ a += r.a; b += r.b; c += r.c;
113
+ i = r.next;
114
+ if (i >= end) break;
115
+ // a combinator: whitespace, or `>`, `+`, `~` with whitespace around it
116
+ let comb: Combinator = ' ';
117
+ while (ws(items[i])) i++;
118
+ const v = items[i];
119
+ if (v.t === 'delim' && (v.v === '>' || v.v === '+' || v.v === '~')) {
120
+ comb = v.v;
121
+ i++;
122
+ while (ws(items[i])) i++;
123
+ }
124
+ if (i >= end) throw new Invalid();
125
+ combinators.push(comb);
126
+ }
127
+ return { compounds, combinators, specificity: spec(Math.min(a, 999), Math.min(b, 999), Math.min(c, 999)) };
128
+ }
129
+
130
+ interface Parsed {
131
+ compound: Compound;
132
+ next: number;
133
+ a: number;
134
+ b: number;
135
+ c: number;
136
+ }
137
+
138
+ const isIdent = (v: CV | undefined): v is Extract<Token, { t: 'ident' }> => v?.t === 'ident';
139
+
140
+ function compound(items: CV[], i: number, end: number, depth: number): Parsed {
141
+ const simple: Simple[] = [];
142
+ let a = 0, b = 0, c = 0;
143
+ const start = i;
144
+ // a type or universal selector, with an optional namespace prefix (`*|`, `|`)
145
+ const typeAt = (k: number): { name: string | null; next: number } | null => {
146
+ const v = items[k];
147
+ if (isIdent(v)) return { name: v.v.toLowerCase(), next: k + 1 };
148
+ if (v?.t === 'delim' && v.v === '*') return { name: null, next: k + 1 };
149
+ return null;
150
+ };
151
+ let t = typeAt(i);
152
+ const bar = (k: number) => { const v = items[k]; return v?.t === 'delim' && v.v === '|'; };
153
+ if (t && bar(t.next) && typeAt(t.next + 1)) {
154
+ // `ns|type`: only `*|` is known without @namespace (which is not read); any other prefix is invalid
155
+ if (t.name !== null) throw new Invalid();
156
+ t = typeAt(t.next + 1);
157
+ } else if (!t && bar(i) && typeAt(i + 1)) {
158
+ // `|type`: elements in no namespace, which an HTML document has none of
159
+ t = typeAt(i + 1);
160
+ simple.push({ k: 'never' });
161
+ }
162
+ if (t) {
163
+ if (t.name !== null) { simple.push({ k: 'tag', v: t.name }); c++; }
164
+ i = t.next;
165
+ }
166
+ let pseudoElement = false;
167
+ while (i < end) {
168
+ const v = items[i];
169
+ if (v.t === 'ws') break;
170
+ if (v.t === 'delim' && (v.v === '>' || v.v === '+' || v.v === '~')) break;
171
+ // after a pseudo-element, only pseudo-classes may follow (which, here, never match anyway)
172
+ if (pseudoElement && v.t !== ':') throw new Invalid();
173
+ if (v.t === 'hash') {
174
+ if (!v.id) throw new Invalid();
175
+ simple.push({ k: 'id', v: v.v });
176
+ a++;
177
+ i++;
178
+ } else if (v.t === 'delim' && v.v === '.') {
179
+ const n = items[i + 1];
180
+ if (!isIdent(n)) throw new Invalid();
181
+ simple.push({ k: 'class', v: n.v });
182
+ b++;
183
+ i += 2;
184
+ } else if (v.t === 'block' && v.open === '[') {
185
+ simple.push(attribute(v.items));
186
+ b++;
187
+ i++;
188
+ } else if (v.t === ':') {
189
+ const n = items[i + 1];
190
+ if (n?.t === ':') {
191
+ // a pseudo-element: valid ones never match, unknown ones (a vendor's, here) are invalid
192
+ const p = items[i + 2];
193
+ const name = isIdent(p) ? p.v.toLowerCase() : p?.t === 'func' ? p.name.toLowerCase() : null;
194
+ if (name === null || !(NEVER_ELEMENTS.has(name) || name.startsWith('-webkit-'))) throw new Invalid();
195
+ simple.push({ k: 'never' });
196
+ c++;
197
+ pseudoElement = true;
198
+ i += 3;
199
+ continue;
200
+ }
201
+ if (isIdent(n)) {
202
+ const name = n.v.toLowerCase();
203
+ i += 2;
204
+ if (LEGACY_ELEMENTS.has(name)) { simple.push({ k: 'never' }); c++; pseudoElement = true; continue; }
205
+ const s = pseudoClass(name);
206
+ simple.push(s);
207
+ if (s.k !== 'never' || NEVER_CLASSES.has(name)) b++;
208
+ continue;
209
+ }
210
+ if (n?.t === 'func') {
211
+ const r = pseudoFunction(n.name.toLowerCase(), n.args, depth);
212
+ simple.push(r.simple);
213
+ a += r.a; b += r.b; c += r.c;
214
+ i += 2;
215
+ continue;
216
+ }
217
+ throw new Invalid();
218
+ } else if (v.t === 'delim' && v.v === '&') {
219
+ // the nesting selector at the top level is :scope, which is :root here
220
+ simple.push({ k: 'root' });
221
+ b++;
222
+ i++;
223
+ } else throw new Invalid();
224
+ }
225
+ if (i === start) throw new Invalid();
226
+ return { compound: { simple }, next: i, a, b, c };
227
+ }
228
+
229
+ function pseudoClass(name: string): Simple {
230
+ switch (name) {
231
+ // :scope, in a stylesheet, is the root
232
+ case 'root': case 'scope': return { k: 'root' };
233
+ case 'empty': return { k: 'empty' };
234
+ case 'link': case 'any-link': case '-webkit-any-link': return { k: 'link' };
235
+ case 'first-child': return { k: 'nth', last: false, type: false, a: 0, b: 1, of: null };
236
+ case 'last-child': return { k: 'nth', last: true, type: false, a: 0, b: 1, of: null };
237
+ case 'first-of-type': return { k: 'nth', last: false, type: true, a: 0, b: 1, of: null };
238
+ case 'last-of-type': return { k: 'nth', last: true, type: true, a: 0, b: 1, of: null };
239
+ case 'only-child': return { k: 'is', list: [single([{ k: 'nth', last: false, type: false, a: 0, b: 1, of: null }, { k: 'nth', last: true, type: false, a: 0, b: 1, of: null }])] };
240
+ case 'only-of-type': return { k: 'is', list: [single([{ k: 'nth', last: false, type: true, a: 0, b: 1, of: null }, { k: 'nth', last: true, type: true, a: 0, b: 1, of: null }])] };
241
+ }
242
+ if (NEVER_CLASSES.has(name)) return { k: 'never' };
243
+ throw new Invalid();
244
+ }
245
+
246
+ const single = (simple: Simple[]): Complex => ({ compounds: [{ simple }], combinators: [], specificity: 0 });
247
+
248
+ function maxSpec(list: Complex[]): number {
249
+ let m = 0;
250
+ for (const c of list) if (c.specificity > m) m = c.specificity;
251
+ return m;
252
+ }
253
+ const unpack = (s: number) => ({ a: Math.floor(s / 1_000_000), b: Math.floor(s / 1_000) % 1_000, c: s % 1_000 });
254
+
255
+ function pseudoFunction(name: string, args: CV[], depth: number): { simple: Simple; a: number; b: number; c: number } {
256
+ switch (name) {
257
+ case 'not': {
258
+ // a complex selector list, not forgiving; a selector in it that cannot be matched makes it unknowable
259
+ const l = list(args, false, depth + 1);
260
+ if (l.length === 0) throw new Invalid();
261
+ const s = unpack(maxSpec(l));
262
+ if (l.some((x) => x.compounds.some(isNever))) return { simple: { k: 'never' }, ...s };
263
+ return { simple: { k: 'not', list: l }, ...s };
264
+ }
265
+ case 'is': case 'matches': case 'where': case '-webkit-any': {
266
+ if (name === 'matches' || name === '-webkit-any') throw new Invalid();
267
+ // forgiving: invalid selectors in it are left out; unmatchable ones never match, as an `or` of them
268
+ const l = list(args, true, depth + 1).filter((x) => !x.compounds.some(isNever));
269
+ const s = name === 'where' ? { a: 0, b: 0, c: 0 } : unpack(maxSpec(l));
270
+ return { simple: l.length ? { k: 'is', list: l } : { k: 'never' }, ...s };
271
+ }
272
+ case 'nth-child': case 'nth-last-child': case 'nth-of-type': case 'nth-last-of-type': {
273
+ const type = name.endsWith('of-type');
274
+ // `An+B [of S]`, `of S` only for the -child forms
275
+ let ofAt = -1;
276
+ if (!type) ofAt = args.findIndex((v) => isIdent(v) && v.v.toLowerCase() === 'of');
277
+ const ab = anb(ofAt < 0 ? args : args.slice(0, ofAt));
278
+ if (!ab) throw new Invalid();
279
+ let of: Complex[] | null = null;
280
+ let s = { a: 0, b: 1, c: 0 };
281
+ if (ofAt >= 0) {
282
+ of = list(args.slice(ofAt + 1), false, depth + 1);
283
+ if (of.length === 0) throw new Invalid();
284
+ const m = unpack(maxSpec(of));
285
+ s = { a: m.a, b: m.b + 1, c: m.c };
286
+ if (of.some((x) => x.compounds.some(isNever))) return { simple: { k: 'never' }, ...s };
287
+ }
288
+ return { simple: { k: 'nth', last: name.includes('last'), type, a: ab.a, b: ab.b, of }, ...s };
289
+ }
290
+ case 'has': {
291
+ // valid (a relative selector list) and not matched here
292
+ return { simple: { k: 'never' }, a: 0, b: 0, c: 0 };
293
+ }
294
+ case 'lang': case 'dir': case 'host': case 'host-context': case 'state': case 'cue': case 'part': case 'slotted':
295
+ return { simple: { k: 'never' }, a: 0, b: 1, c: 0 };
296
+ }
297
+ throw new Invalid();
298
+ }
299
+
300
+ /** the An+B microsyntax, read from the argument's own text */
301
+ function anb(items: CV[]): { a: number; b: number } | null {
302
+ let text = '';
303
+ for (const v of items) {
304
+ switch (v.t) {
305
+ case 'ws': text += ' '; break;
306
+ case 'ident': text += v.v; break;
307
+ case 'number': text += v.s; break;
308
+ case 'dimension': text += v.s + v.unit; break;
309
+ case 'delim': text += v.v; break;
310
+ default: return null;
311
+ }
312
+ }
313
+ text = text.trim().toLowerCase();
314
+ if (text === 'odd') return { a: 2, b: 1 };
315
+ if (text === 'even') return { a: 2, b: 0 };
316
+ let m = /^([+-]?\d+)$/.exec(text);
317
+ if (m) return { a: 0, b: Number(m[1]) };
318
+ m = /^([+-]?)(\d*)n(?:\s*([+-])\s*(\d+)|([+-]\d+))?$/.exec(text);
319
+ if (!m) return null;
320
+ // a sign and digits are not separated from `n`; `+ n` (with a space) is not matched by the pattern
321
+ const a = (m[1] === '-' ? -1 : 1) * (m[2] === '' ? 1 : Number(m[2]));
322
+ const b = m[3] ? (m[3] === '-' ? -1 : 1) * Number(m[4]) : m[5] ? Number(m[5]) : 0;
323
+ return { a, b };
324
+ }
325
+
326
+ const ATTR_OPS = new Set(['=', '~=', '|=', '^=', '$=', '*=']);
327
+
328
+ // the HTML attributes whose values selectors compare ASCII case-insensitively in an HTML document
329
+ const CASE_INSENSITIVE = new Set([
330
+ 'accept', 'accept-charset', 'align', 'alink', 'axis', 'bgcolor', 'charset', 'checked', 'clear', 'codetype', 'color',
331
+ 'compact', 'declare', 'defer', 'dir', 'direction', 'disabled', 'enctype', 'face', 'frame', 'hreflang', 'http-equiv',
332
+ 'lang', 'language', 'link', 'media', 'method', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap', 'readonly',
333
+ 'rel', 'rev', 'rules', 'scope', 'scrolling', 'selected', 'shape', 'target', 'text', 'type', 'valign', 'valuetype',
334
+ 'vlink',
335
+ ]);
336
+
337
+ function attribute(items: CV[]): Simple {
338
+ const xs = items.filter((v) => v.t !== 'ws');
339
+ let i = 0;
340
+ // an optional namespace prefix: `*|name` matches any; `|name` (no namespace) matches HTML attributes
341
+ if (xs[i]?.t === 'delim' && (xs[i] as { v: string }).v === '*' && xs[i + 1]?.t === 'delim' && (xs[i + 1] as { v: string }).v === '|') i += 2;
342
+ else if (xs[i]?.t === 'delim' && (xs[i] as { v: string }).v === '|') i += 1;
343
+ const n = xs[i];
344
+ if (!isIdent(n)) throw new Invalid();
345
+ const name = n.v.toLowerCase();
346
+ i++;
347
+ if (i === xs.length) return { k: 'attr', name, op: '', v: '', i: false };
348
+ // the operator: `=`, or one of `~|^$*` followed by `=` (with no whitespace between)
349
+ let op = '';
350
+ const d = xs[i];
351
+ if (d.t !== 'delim') throw new Invalid();
352
+ if (d.v === '=') { op = '='; i++; } else {
353
+ const raw = items.indexOf(d);
354
+ const eq = items[raw + 1];
355
+ if (eq?.t !== 'delim' || eq.v !== '=') throw new Invalid();
356
+ op = d.v + '=';
357
+ i += 2;
358
+ }
359
+ if (!ATTR_OPS.has(op)) throw new Invalid();
360
+ const val = xs[i];
361
+ if (!val || (val.t !== 'ident' && val.t !== 'string')) throw new Invalid();
362
+ i++;
363
+ let insensitive = CASE_INSENSITIVE.has(name);
364
+ const flag = xs[i];
365
+ if (flag) {
366
+ if (!isIdent(flag) || i + 1 !== xs.length) throw new Invalid();
367
+ const f = flag.v.toLowerCase();
368
+ if (f === 'i') insensitive = true;
369
+ else if (f === 's') insensitive = false;
370
+ else throw new Invalid();
371
+ }
372
+ return { k: 'attr', name, op: op as '=', v: insensitive ? asciiLower(val.v) : val.v, i: insensitive };
373
+ }
374
+
375
+ const asciiLower = (s: string) => s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
376
+
377
+ // ── Matching ─────────────────────────────────────────────────────────────────────────────────────────
378
+
379
+ /** what matching needs of an element, computed once per tree */
380
+ export interface Info {
381
+ el: RawElement;
382
+ parent: Info | null;
383
+ /** the parent's element children (the root alone for the root) */
384
+ siblings: Info[];
385
+ /** index among siblings */
386
+ index: number;
387
+ /** index among siblings of the same tag, and how many there are */
388
+ typeIndex: number;
389
+ typeCount: number;
390
+ id: string | null;
391
+ classes: string[];
392
+ }
393
+
394
+ /** every element of the tree, in document order, with its Info */
395
+ export function indexTree(root: RawElement): Info[] {
396
+ const all: Info[] = [];
397
+ const rootInfo = info(root, null, [], 0);
398
+ rootInfo.siblings.push(rootInfo);
399
+ rootInfo.typeCount = 1;
400
+ // iterative: a deep tree must not exhaust the call stack
401
+ const stack: Info[] = [rootInfo];
402
+ while (stack.length) {
403
+ const p = stack.pop()!;
404
+ all.push(p);
405
+ const kids: Info[] = [];
406
+ for (const c of p.el.children) if (c.type === 'element') kids.push(info(c, p, kids, kids.length));
407
+ const counts = new Map<string, number>();
408
+ for (const k of kids) {
409
+ const n = counts.get(k.el.tag) ?? 0;
410
+ k.typeIndex = n;
411
+ counts.set(k.el.tag, n + 1);
412
+ }
413
+ for (const k of kids) k.typeCount = counts.get(k.el.tag)!;
414
+ for (let j = kids.length - 1; j >= 0; j--) stack.push(kids[j]);
415
+ }
416
+ return all;
417
+ }
418
+
419
+ function info(el: RawElement, parent: Info | null, siblings: Info[], index: number): Info {
420
+ const cls = attr(el, 'class');
421
+ return { el, parent, siblings, index, typeIndex: 0, typeCount: 0, id: attr(el, 'id'), classes: cls ? cls.split(/[ \t\n\f\r]+/).filter(Boolean) : [], };
422
+ }
423
+
424
+ // a match's outcome, as WebKit's matcher has them (plain numbers: sinter's build-time check reads no enum)
425
+ const MATCH = 0, FAIL_LOCAL = 1, FAIL_SIBLINGS = 2, FAIL_ALL = 3;
426
+ type R = typeof MATCH | typeof FAIL_LOCAL | typeof FAIL_SIBLINGS | typeof FAIL_ALL;
427
+
428
+ /**
429
+ * The matching work left for one resolve, in compound tests. A hostile stylesheet can make every rule match
430
+ * every element, or every test walk to the root; past a budget no real email comes near (index.ts,
431
+ * MAX_STEPS), what is left does not match, so a resolve ends in bounded time. One per resolve, passed
432
+ * along: the module keeps no state between calls (sinter runs mail.parse at build time only if it is pure).
433
+ */
434
+ export interface Budget { left: number }
435
+
436
+ /** whether the budget is spent: no further selector matches */
437
+ export const exhausted = (b: Budget): boolean => b.left <= 0;
438
+
439
+ /** whether `sel` matches `e` */
440
+ export function matches(sel: Complex, e: Info, b: Budget): boolean {
441
+ return step(sel, sel.compounds.length - 1, e, b) === MATCH;
442
+ }
443
+
444
+ function step(sel: Complex, k: number, e: Info, b: Budget): R {
445
+ if (--b.left < 0) return FAIL_ALL;
446
+ if (!compoundMatches(sel.compounds[k], e, b)) return FAIL_LOCAL;
447
+ if (k === 0) return MATCH;
448
+ switch (sel.combinators[k - 1]) {
449
+ case ' ': {
450
+ for (let p = e.parent; p; p = p.parent) {
451
+ const r = step(sel, k - 1, p, b);
452
+ if (r === MATCH || r === FAIL_ALL) return r;
453
+ }
454
+ return FAIL_ALL;
455
+ }
456
+ case '>':
457
+ return e.parent ? step(sel, k - 1, e.parent, b) : FAIL_ALL;
458
+ case '+':
459
+ return e.index > 0 ? step(sel, k - 1, e.siblings[e.index - 1], b) : FAIL_SIBLINGS;
460
+ case '~': {
461
+ for (let j = e.index - 1; j >= 0; j--) {
462
+ const r = step(sel, k - 1, e.siblings[j], b);
463
+ if (r === MATCH || r === FAIL_SIBLINGS || r === FAIL_ALL) return r;
464
+ }
465
+ return FAIL_SIBLINGS;
466
+ }
467
+ }
468
+ }
469
+
470
+ function compoundMatches(c: Compound, e: Info, b: Budget): boolean {
471
+ for (const s of c.simple) if (!simpleMatches(s, e, b)) return false;
472
+ return true;
473
+ }
474
+
475
+ function simpleMatches(s: Simple, e: Info, b: Budget): boolean {
476
+ switch (s.k) {
477
+ case 'tag': return e.el.tag === s.v;
478
+ case 'id': return e.id === s.v;
479
+ case 'class': return e.classes.includes(s.v);
480
+ case 'attr': {
481
+ const raw = attr(e.el, s.name);
482
+ if (raw === null) return false;
483
+ const v = s.i ? asciiLower(raw) : raw;
484
+ switch (s.op) {
485
+ case '': return true;
486
+ case '=': return v === s.v;
487
+ case '~=': return s.v !== '' && !/[ \t\n\f\r]/.test(s.v) && v.split(/[ \t\n\f\r]+/).includes(s.v);
488
+ case '|=': return v === s.v || v.startsWith(s.v + '-');
489
+ case '^=': return s.v !== '' && v.startsWith(s.v);
490
+ case '$=': return s.v !== '' && v.endsWith(s.v);
491
+ case '*=': return s.v !== '' && v.includes(s.v);
492
+ }
493
+ return false;
494
+ }
495
+ case 'never': return false;
496
+ case 'root': return e.parent === null;
497
+ case 'empty': return e.el.children.every((c) => c.type === 'text' && c.value === '');
498
+ case 'link': return (e.el.tag === 'a' || e.el.tag === 'area') && attr(e.el, 'href') !== null;
499
+ case 'not': return !s.list.some((x) => matches(x, e, b));
500
+ case 'is': return s.list.some((x) => matches(x, e, b));
501
+ case 'nth': {
502
+ let pos: number;
503
+ if (s.type) pos = s.last ? e.typeCount - e.typeIndex : e.typeIndex + 1;
504
+ else if (s.of) {
505
+ if (!s.of.some((x) => matches(x, e, b))) return false;
506
+ pos = 1;
507
+ const sib = e.siblings;
508
+ if (s.last) { for (let j = e.index + 1; j < sib.length; j++) if (s.of.some((x) => matches(x, sib[j], b))) pos++; }
509
+ else for (let j = 0; j < e.index; j++) if (s.of.some((x) => matches(x, sib[j], b))) pos++;
510
+ } else pos = s.last ? e.siblings.length - e.index : e.index + 1;
511
+ // pos = a·n + b for some n ≥ 0
512
+ if (s.a === 0) return pos === s.b;
513
+ const n = (pos - s.b) / s.a;
514
+ return Number.isInteger(n) && n >= 0;
515
+ }
516
+ }
517
+ }
518
+
519
+ /** the key a selector is bucketed by: its rightmost compound's id, else a class, else its tag */
520
+ export function bucketKey(sel: Complex): string {
521
+ const last = sel.compounds[sel.compounds.length - 1];
522
+ let cls: string | null = null;
523
+ let tag: string | null = null;
524
+ for (const s of last.simple) {
525
+ if (s.k === 'id') return '#' + s.v;
526
+ if (s.k === 'class' && cls === null) cls = s.v;
527
+ if (s.k === 'tag') tag = s.v;
528
+ }
529
+ return cls !== null ? '.' + cls : tag !== null ? tag : '*';
530
+ }