@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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -2
  3. package/docs/mail.md +298 -0
  4. package/docs/proposals/progressive-rendering.md +180 -0
  5. package/docs/proposals/sinter-mail.md +520 -0
  6. package/llms.txt +21 -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 +348 -0
  78. package/sinter/css/media.ts +254 -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 +669 -0
  83. package/sinter/engine.ts +6 -0
  84. package/sinter/index.ts +5 -0
  85. package/sinter/parse.ts +359 -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 +144 -0
  94. package/sinter/tags.ts +169 -0
  95. package/sinter/tree.ts +168 -0
@@ -0,0 +1,669 @@
1
+ // Values: each declaration checked against its property's grammar and re-serialized from its tokens, or
2
+ // dropped. Shorthands are expanded here into the longhands the cascade keeps (sinter/tags.ts,
3
+ // PROPERTIES), so a later longhand and an earlier shorthand meet in one place, in declaration order.
4
+ //
5
+ // What is kept is a simple form of what browsers accept: lengths in absolute and font-relative units,
6
+ // percentages, colours, keywords, font lists. Not kept: viewport units (the email's box is not the
7
+ // viewport), math functions, `var()`, `env()`, `attr()`, images and any other function, negative margins
8
+ // (an email must not reach outside its box over the app), vendor-prefixed properties. A kept value
9
+ // never contains a backslash or a function the runtime refuses: strings are re-quoted from their decoded
10
+ // characters, and the only functions written are rgb(), rgba(), hsl() and hsla() with numbers in them.
11
+ import type { Property } from '../sinter.types.js';
12
+ import { parseComponents, type CV, type Func } from './tokenize.js';
13
+
14
+ /**
15
+ * What the cascade tracks: the kept properties, the longhands of the two kept properties that are
16
+ * shorthands in CSS (`text-decoration`, `overflow`), joined back when the element's style is written, and
17
+ * `color-scheme`, read on the email's `<html>` and `<body>` (the schemes it is written for) and never kept.
18
+ */
19
+ export type Longhand =
20
+ | Exclude<Property, 'text-decoration' | 'overflow'>
21
+ | 'text-decoration-line' | 'text-decoration-style' | 'text-decoration-color'
22
+ | 'overflow-x' | 'overflow-y'
23
+ | 'color-scheme';
24
+
25
+ export type Assignment = [Longhand, string];
26
+
27
+ const WIDE = new Set(['inherit', 'initial', 'unset']);
28
+
29
+ // ── Numbers, lengths, colours ────────────────────────────────────────────────────────────────────────
30
+
31
+ /** a number as CSS writes it: at most four decimals, no `-0` */
32
+ export function num(n: number): string {
33
+ const r = Math.round(n * 1e4) / 1e4;
34
+ return r === 0 ? '0' : String(r);
35
+ }
36
+
37
+ // the units kept, with their size in px for the bound on small negative values
38
+ const UNITS: Record<string, number> = { px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6, em: 16, rem: 16, ex: 8, ch: 8 };
39
+
40
+ interface LengthOptions {
41
+ /** a percentage is allowed */
42
+ pct?: boolean;
43
+ /**
44
+ * negative values: invalid (the default, as for widths and paddings), down to about one em ('small'),
45
+ * or written as 0 ('clamp': valid CSS that would move the box out, as a negative margin)
46
+ */
47
+ neg?: 'small' | 'clamp';
48
+ }
49
+
50
+ /** a length (or percentage, or unitless 0), re-serialized; null otherwise */
51
+ export function length(v: CV | undefined, o: LengthOptions = {}): string | null {
52
+ if (!v) return null;
53
+ if (v.t === 'number') return v.n === 0 ? '0' : null;
54
+ let n: number;
55
+ let unit: string;
56
+ if (v.t === 'dimension') {
57
+ unit = v.unit.toLowerCase();
58
+ if (!(unit in UNITS)) return null;
59
+ n = v.n;
60
+ } else if (v.t === 'percentage' && o.pct) {
61
+ unit = '%';
62
+ n = v.n;
63
+ } else return null;
64
+ if (!Number.isFinite(n)) return null;
65
+ if (n < 0) {
66
+ if (o.neg === 'clamp') return '0';
67
+ if (o.neg !== 'small') return null;
68
+ // about one em: a heading's tightened letter-spacing, an icon nudged down, not a box moved away
69
+ if (unit === '%' ? n < -100 : n * UNITS[unit] < -16) return null;
70
+ }
71
+ return num(n) + unit;
72
+ }
73
+
74
+ const NAMED = new Set(
75
+ ('aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue ' +
76
+ 'chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey ' +
77
+ 'darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray ' +
78
+ 'darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen ' +
79
+ 'fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki ' +
80
+ 'lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen ' +
81
+ 'lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime ' +
82
+ 'limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue ' +
83
+ 'mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive ' +
84
+ 'olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +
85
+ 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue ' +
86
+ 'slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke ' +
87
+ 'yellow yellowgreen').split(' '),
88
+ );
89
+
90
+ // system colours, the deprecated ones included: Outlook writes `windowtext` in every border
91
+ const SYSTEM = new Set(
92
+ ('activeborder activecaption appworkspace background buttonface buttonhighlight buttonshadow buttontext captiontext graytext ' +
93
+ 'highlight highlighttext inactiveborder inactivecaption inactivecaptiontext infobackground infotext menu menutext scrollbar ' +
94
+ 'threeddarkshadow threedface threedhighlight threedlightshadow threedshadow window windowframe windowtext canvas canvastext ' +
95
+ 'linktext visitedtext activetext buttonborder field fieldtext mark marktext selecteditem selecteditemtext accentcolor accentcolortext').split(' '),
96
+ );
97
+
98
+ /** whether `name` (lowercase) is a named colour */
99
+ export const isNamedColor = (name: string): boolean => NAMED.has(name);
100
+
101
+ const isHex = (s: string) => /^[0-9a-fA-F]+$/.test(s);
102
+ const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
103
+
104
+ /** a colour, re-serialized: a name, `#hex` (lowercase), rgb()/rgba()/hsl()/hsla() with plain numbers */
105
+ export function color(v: CV | undefined): string | null {
106
+ if (!v) return null;
107
+ if (v.t === 'ident') {
108
+ const k = v.v.toLowerCase();
109
+ return NAMED.has(k) || SYSTEM.has(k) || k === 'transparent' || k === 'currentcolor' ? k : null;
110
+ }
111
+ if (v.t === 'hash') {
112
+ const h = v.v;
113
+ return isHex(h) && (h.length === 3 || h.length === 4 || h.length === 6 || h.length === 8) ? '#' + h.toLowerCase() : null;
114
+ }
115
+ if (v.t === 'func') {
116
+ const name = v.name.toLowerCase();
117
+ if (name === 'rgb' || name === 'rgba') return rgb(v);
118
+ if (name === 'hsl' || name === 'hsla') return hsl(v);
119
+ }
120
+ return null;
121
+ }
122
+
123
+ /** a colour function's arguments: legacy (comma-separated, 3 or 4) or modern (space-separated, `/ alpha`) */
124
+ function channels(f: Func): { legacy: boolean; c: CV[]; alpha: CV | null } | null {
125
+ const xs = f.args.filter((x) => x.t !== 'ws');
126
+ if (xs.some((x) => x.t === ',')) {
127
+ // legacy: a, b, c[, alpha]
128
+ const c: CV[] = [];
129
+ for (let i = 0; i < xs.length; i += 2) {
130
+ c.push(xs[i]);
131
+ if (i + 1 < xs.length && xs[i + 1].t !== ',') return null;
132
+ }
133
+ if (xs.length % 2 === 0 || (c.length !== 3 && c.length !== 4)) return null;
134
+ return { legacy: true, c: c.slice(0, 3), alpha: c[3] ?? null };
135
+ }
136
+ if (xs.length === 3) return { legacy: false, c: xs, alpha: null };
137
+ if (xs.length === 5 && xs[3].t === 'delim' && xs[3].v === '/') return { legacy: false, c: xs.slice(0, 3), alpha: xs[4] };
138
+ return null;
139
+ }
140
+
141
+ const isNone = (v: CV) => v.t === 'ident' && v.v.toLowerCase() === 'none';
142
+
143
+ function alphaOf(v: CV | null, legacy: boolean): number | null {
144
+ if (!v) return 1;
145
+ if (v.t === 'number' && Number.isFinite(v.n)) return clamp(v.n, 0, 1);
146
+ if (v.t === 'percentage' && Number.isFinite(v.n)) return clamp(v.n / 100, 0, 1);
147
+ if (!legacy && isNone(v)) return 0;
148
+ return null;
149
+ }
150
+
151
+ function rgb(f: Func): string | null {
152
+ const ch = channels(f);
153
+ if (!ch) return null;
154
+ const { legacy, c } = ch;
155
+ // legacy syntax: all numbers or all percentages
156
+ if (legacy && !(c.every((x) => x.t === 'number') || c.every((x) => x.t === 'percentage'))) return null;
157
+ const out: number[] = [];
158
+ for (const x of c) {
159
+ if (x.t === 'number' && Number.isFinite(x.n)) out.push(clamp(x.n, 0, 255));
160
+ else if (x.t === 'percentage' && Number.isFinite(x.n)) out.push(clamp(x.n * 2.55, 0, 255));
161
+ else if (!legacy && isNone(x)) out.push(0);
162
+ else return null;
163
+ }
164
+ const a = alphaOf(ch.alpha, legacy);
165
+ if (a === null) return null;
166
+ const body = out.map(num).join(', ');
167
+ return a === 1 ? `rgb(${body})` : `rgba(${body}, ${num(a)})`;
168
+ }
169
+
170
+ const ANGLE: Record<string, number> = { deg: 1, grad: 0.9, rad: 180 / Math.PI, turn: 360 };
171
+
172
+ function hsl(f: Func): string | null {
173
+ const ch = channels(f);
174
+ if (!ch) return null;
175
+ const { legacy, c } = ch;
176
+ const [h, s, l] = c;
177
+ let hue: number;
178
+ if (h.t === 'number' && Number.isFinite(h.n)) hue = h.n;
179
+ else if (h.t === 'dimension' && h.unit.toLowerCase() in ANGLE && Number.isFinite(h.n)) hue = h.n * ANGLE[h.unit.toLowerCase()];
180
+ else if (!legacy && isNone(h)) hue = 0;
181
+ else return null;
182
+ const pct = (x: CV): number | null => {
183
+ if (x.t === 'percentage' && Number.isFinite(x.n)) return clamp(x.n, 0, 100);
184
+ if (!legacy && x.t === 'number' && Number.isFinite(x.n)) return clamp(x.n, 0, 100);
185
+ if (!legacy && isNone(x)) return 0;
186
+ return null;
187
+ };
188
+ const sat = pct(s);
189
+ const lig = pct(l);
190
+ const a = alphaOf(ch.alpha, legacy);
191
+ if (sat === null || lig === null || a === null) return null;
192
+ hue = ((hue % 360) + 360) % 360;
193
+ const body = `${num(hue)}, ${num(sat)}%, ${num(lig)}%`;
194
+ return a === 1 ? `hsl(${body})` : `hsla(${body}, ${num(a)})`;
195
+ }
196
+
197
+ // ── Keywords ─────────────────────────────────────────────────────────────────────────────────────────
198
+
199
+ const kw = (v: CV | undefined): string | null => (v?.t === 'ident' ? v.v.toLowerCase() : null);
200
+ const oneOf = (words: string) => {
201
+ const set = new Set(words.split(' '));
202
+ return (v: CV | undefined) => {
203
+ const k = kw(v);
204
+ return k !== null && set.has(k) ? k : null;
205
+ };
206
+ };
207
+
208
+ const BORDER_STYLE = oneOf('none hidden dotted dashed solid double groove ridge inset outset');
209
+ const BORDER_WIDTH = (v: CV | undefined) => oneOf('thin medium thick')(v) ?? length(v);
210
+ const FONT_SIZE = (v: CV | undefined) => oneOf('xx-small x-small small medium large x-large xx-large xxx-large larger smaller')(v) ?? length(v, { pct: true });
211
+ const LINE_HEIGHT = (v: CV | undefined): string | null => {
212
+ if (kw(v) === 'normal') return 'normal';
213
+ if (v?.t === 'number' && Number.isFinite(v.n) && v.n >= 0) return num(v.n);
214
+ return length(v, { pct: true });
215
+ };
216
+ const FONT_WEIGHT = (v: CV | undefined): string | null => {
217
+ const k = oneOf('normal bold bolder lighter')(v);
218
+ if (k) return k;
219
+ return v?.t === 'number' && v.n >= 1 && v.n <= 1000 ? num(v.n) : null;
220
+ };
221
+ const FONT_STYLE = oneOf('normal italic oblique');
222
+ const FONT_VARIANT = oneOf('normal none small-caps all-small-caps petite-caps all-petite-caps unicase titling-caps');
223
+ const OVERFLOW = oneOf('visible hidden clip scroll auto');
224
+ const SIZE_KEYWORDS = 'min-content max-content fit-content';
225
+ const box = (extra: string) => (v: CV | undefined) => oneOf(`${extra} ${SIZE_KEYWORDS}`)(v) ?? length(v, { pct: true });
226
+ const LIST_TYPES = oneOf(
227
+ 'disc circle square disclosure-open disclosure-closed decimal decimal-leading-zero lower-roman upper-roman lower-greek ' +
228
+ 'lower-alpha lower-latin upper-alpha upper-latin armenian georgian hebrew cjk-decimal cjk-ideographic hiragana katakana ' +
229
+ 'hiragana-iroha katakana-iroha arabic-indic bengali devanagari persian thai lower-armenian upper-armenian none',
230
+ );
231
+ const listType = (v: CV | undefined): string | null => (v?.t === 'string' ? quote(v.v) : LIST_TYPES(v));
232
+
233
+ /** a string re-quoted from its decoded characters; null when it cannot be written without an escape */
234
+ export function quote(s: string): string | null {
235
+ // control characters would need an escape; text the runtime refuses is refused here first
236
+ if (/[\u0000-\u001f\u007f\\]/.test(s) || /url\(|image\(|image-set\(/i.test(s)) return null;
237
+ if (!s.includes('"')) return `"${s}"`;
238
+ if (!s.includes("'")) return `'${s}'`;
239
+ return null;
240
+ }
241
+
242
+ // the single-value longhands: each a check of the one component value
243
+ type Check = (v: CV | undefined) => string | null;
244
+
245
+ const SINGLE: Partial<Record<Longhand, Check>> = {
246
+ color,
247
+ 'background-color': color,
248
+ 'font-size': FONT_SIZE,
249
+ 'font-style': FONT_STYLE,
250
+ 'font-weight': FONT_WEIGHT,
251
+ 'font-variant': FONT_VARIANT,
252
+ 'line-height': LINE_HEIGHT,
253
+ 'letter-spacing': (v) => (kw(v) === 'normal' ? 'normal' : length(v, { neg: 'small' })),
254
+ 'word-spacing': (v) => (kw(v) === 'normal' ? 'normal' : length(v, { neg: 'small' })),
255
+ 'text-align': oneOf('left right center justify start end match-parent -webkit-center -webkit-left -webkit-right'),
256
+ 'text-transform': oneOf('none capitalize uppercase lowercase full-width full-size-kana'),
257
+ 'text-indent': (v) => length(v, { pct: true, neg: 'clamp' }),
258
+ 'white-space': oneOf('normal nowrap pre pre-wrap pre-line break-spaces'),
259
+ 'vertical-align': (v) => oneOf('baseline sub super text-top text-bottom middle top bottom')(v) ?? length(v, { pct: true, neg: 'small' }),
260
+ 'word-break': oneOf('normal break-all keep-all break-word'),
261
+ 'overflow-wrap': oneOf('normal break-word anywhere'),
262
+ width: box('auto'),
263
+ height: box('auto'),
264
+ 'min-width': box('auto'),
265
+ 'min-height': box('auto'),
266
+ 'max-width': box('none'),
267
+ 'max-height': box('none'),
268
+ 'margin-top': (v) => (kw(v) === 'auto' ? 'auto' : length(v, { pct: true, neg: 'clamp' })),
269
+ 'margin-right': (v) => (kw(v) === 'auto' ? 'auto' : length(v, { pct: true, neg: 'clamp' })),
270
+ 'margin-bottom': (v) => (kw(v) === 'auto' ? 'auto' : length(v, { pct: true, neg: 'clamp' })),
271
+ 'margin-left': (v) => (kw(v) === 'auto' ? 'auto' : length(v, { pct: true, neg: 'clamp' })),
272
+ 'padding-top': (v) => length(v, { pct: true }),
273
+ 'padding-right': (v) => length(v, { pct: true }),
274
+ 'padding-bottom': (v) => length(v, { pct: true }),
275
+ 'padding-left': (v) => length(v, { pct: true }),
276
+ 'border-top-width': BORDER_WIDTH,
277
+ 'border-right-width': BORDER_WIDTH,
278
+ 'border-bottom-width': BORDER_WIDTH,
279
+ 'border-left-width': BORDER_WIDTH,
280
+ 'border-top-style': BORDER_STYLE,
281
+ 'border-right-style': BORDER_STYLE,
282
+ 'border-bottom-style': BORDER_STYLE,
283
+ 'border-left-style': BORDER_STYLE,
284
+ 'border-top-color': color,
285
+ 'border-right-color': color,
286
+ 'border-bottom-color': color,
287
+ 'border-left-color': color,
288
+ 'border-collapse': oneOf('collapse separate'),
289
+ 'table-layout': oneOf('auto fixed'),
290
+ 'caption-side': oneOf('top bottom'),
291
+ display: oneOf(
292
+ 'block inline inline-block none flex inline-flex grid inline-grid list-item flow-root table inline-table table-row-group ' +
293
+ 'table-header-group table-footer-group table-row table-cell table-column-group table-column table-caption',
294
+ ),
295
+ 'list-style-type': listType,
296
+ 'list-style-position': oneOf('inside outside'),
297
+ opacity: (v) => (v?.t === 'number' && Number.isFinite(v.n) ? num(clamp(v.n, 0, 1)) : v?.t === 'percentage' && Number.isFinite(v.n) ? num(clamp(v.n / 100, 0, 1)) : null),
298
+ 'box-sizing': oneOf('content-box border-box'),
299
+ float: oneOf('left right none'),
300
+ clear: oneOf('left right both none'),
301
+ 'text-decoration-style': oneOf('solid double dotted dashed wavy'),
302
+ 'text-decoration-color': color,
303
+ 'overflow-x': OVERFLOW,
304
+ 'overflow-y': OVERFLOW,
305
+ };
306
+
307
+ const SIDES = ['top', 'right', 'bottom', 'left'] as const;
308
+ const CORNERS = ['top-left', 'top-right', 'bottom-right', 'bottom-left'] as const;
309
+
310
+ /** 1 to 4 values to top, right, bottom, left, as CSS repeats them */
311
+ function fourSides(xs: CV[], check: Check, name: (side: (typeof SIDES)[number]) => Longhand): Assignment[] | null {
312
+ if (xs.length < 1 || xs.length > 4) return null;
313
+ const vs: string[] = [];
314
+ for (const x of xs) {
315
+ const v = check(x);
316
+ if (v === null) return null;
317
+ vs.push(v);
318
+ }
319
+ const [t, r = t, b = t, l = r] = vs;
320
+ return [[name('top'), t], [name('right'), r], [name('bottom'), b], [name('left'), l]];
321
+ }
322
+
323
+ // ── Shorthands ───────────────────────────────────────────────────────────────────────────────────────
324
+
325
+ /** the longhands each shorthand sets, for CSS-wide keywords */
326
+ const SHORTHANDS: Record<string, Longhand[]> = {
327
+ margin: SIDES.map((s) => `margin-${s}` as Longhand),
328
+ padding: SIDES.map((s) => `padding-${s}` as Longhand),
329
+ 'border-width': SIDES.map((s) => `border-${s}-width` as Longhand),
330
+ 'border-style': SIDES.map((s) => `border-${s}-style` as Longhand),
331
+ 'border-color': SIDES.map((s) => `border-${s}-color` as Longhand),
332
+ border: SIDES.flatMap((s) => [`border-${s}-width`, `border-${s}-style`, `border-${s}-color`] as Longhand[]),
333
+ ...Object.fromEntries(SIDES.map((s) => [`border-${s}`, [`border-${s}-width`, `border-${s}-style`, `border-${s}-color`] as Longhand[]])),
334
+ 'border-radius': CORNERS.map((c) => `border-${c}-radius` as Longhand),
335
+ background: ['background-color'],
336
+ font: ['font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', 'font-family'],
337
+ 'list-style': ['list-style-type', 'list-style-position'],
338
+ overflow: ['overflow-x', 'overflow-y'],
339
+ 'text-decoration': ['text-decoration-line', 'text-decoration-style', 'text-decoration-color'],
340
+ 'text-decoration-line': ['text-decoration-line'],
341
+ 'font-family': ['font-family'],
342
+ 'border-spacing': ['border-spacing'],
343
+ 'word-wrap': ['overflow-wrap'],
344
+ 'color-scheme': ['color-scheme'],
345
+ ...Object.fromEntries(CORNERS.map((c) => [`border-${c}-radius`, [`border-${c}-radius` as Longhand]])),
346
+ };
347
+
348
+ /**
349
+ * The longhands a declaration sets, its value re-serialized; null when the property is not kept or the
350
+ * value is invalid or unsafe (the declaration is then ignored, as an invalid one is by a browser).
351
+ */
352
+ export function expand(name: string, value: CV[] | string): Assignment[] | null {
353
+ const items = typeof value === 'string' ? parseComponents(value) : value;
354
+ const xs = items.filter((x) => x.t !== 'ws');
355
+ if (xs.length === 0) return null;
356
+ const single = SINGLE[name as Longhand];
357
+ const longhands = SHORTHANDS[name] ?? (single ? [name as Longhand] : null);
358
+ if (!longhands) return null;
359
+ // inherit, initial, unset: for every longhand (revert and revert-layer are not kept: they would reach
360
+ // the page's own styles in a way the email's author did not see)
361
+ if (xs.length === 1) {
362
+ const k = kw(xs[0]);
363
+ if (k !== null && WIDE.has(k)) return longhands.map((l) => [l, k]);
364
+ }
365
+ if (single) {
366
+ if (xs.length !== 1) return null;
367
+ const v = single(xs[0]);
368
+ return v === null ? null : [[name as Longhand, v]];
369
+ }
370
+ switch (name) {
371
+ case 'margin': return fourSides(xs, SINGLE['margin-top']!, (s) => `margin-${s}` as Longhand);
372
+ case 'padding': return fourSides(xs, SINGLE['padding-top']!, (s) => `padding-${s}` as Longhand);
373
+ case 'border-width': return fourSides(xs, BORDER_WIDTH, (s) => `border-${s}-width` as Longhand);
374
+ case 'border-style': return fourSides(xs, BORDER_STYLE, (s) => `border-${s}-style` as Longhand);
375
+ case 'border-color': return fourSides(xs, color, (s) => `border-${s}-color` as Longhand);
376
+ case 'border': return border(xs, SIDES);
377
+ case 'border-top': return border(xs, ['top']);
378
+ case 'border-right': return border(xs, ['right']);
379
+ case 'border-bottom': return border(xs, ['bottom']);
380
+ case 'border-left': return border(xs, ['left']);
381
+ case 'border-radius': return borderRadius(xs);
382
+ case 'border-top-left-radius': case 'border-top-right-radius': case 'border-bottom-right-radius': case 'border-bottom-left-radius': {
383
+ const v = corner(xs);
384
+ return v === null ? null : [[name, v]];
385
+ }
386
+ case 'border-spacing': {
387
+ if (xs.length > 2) return null;
388
+ const vs = xs.map((x) => length(x));
389
+ return vs.includes(null) ? null : [['border-spacing', vs.join(' ')]];
390
+ }
391
+ case 'background': return background(items);
392
+ case 'font': return font(items);
393
+ case 'font-family': {
394
+ const v = fontFamily(items);
395
+ return v === null ? null : [['font-family', v]];
396
+ }
397
+ case 'list-style': return listStyle(xs);
398
+ case 'overflow': {
399
+ if (xs.length > 2) return null;
400
+ const x = OVERFLOW(xs[0]);
401
+ const y = xs.length === 2 ? OVERFLOW(xs[1]) : x;
402
+ return x === null || y === null ? null : [['overflow-x', x], ['overflow-y', y]];
403
+ }
404
+ case 'text-decoration': return textDecoration(xs, true);
405
+ case 'text-decoration-line': return textDecoration(xs, false);
406
+ case 'word-wrap': {
407
+ const v = xs.length === 1 ? SINGLE['overflow-wrap']!(xs[0]) : null;
408
+ return v === null ? null : [['overflow-wrap', v]];
409
+ }
410
+ case 'color-scheme': {
411
+ const v = colorScheme(xs);
412
+ return v === null ? null : [['color-scheme', v]];
413
+ }
414
+ }
415
+ return null;
416
+ }
417
+
418
+ /**
419
+ * `color-scheme`: `normal`, or the schemes (`light`, `dark`, names of others) with `only` before or after
420
+ * them; written as the known schemes, `light dark` in that order, or `normal` when it names neither
421
+ */
422
+ function colorScheme(xs: CV[]): string | null {
423
+ const names = xs.map(kw);
424
+ if (names.includes(null)) return null;
425
+ if (names.length === 1 && names[0] === 'normal') return 'normal';
426
+ if (names.includes('normal') || names.filter((n) => n === 'only').length > 1) return null;
427
+ if (names.indexOf('only') > 0 && names.indexOf('only') < names.length - 1) return null;
428
+ const known = (['light', 'dark'] as const).filter((s) => names.includes(s));
429
+ if (names.filter((n) => n !== 'only').length === 0) return null;
430
+ return known.length ? known.join(' ') : 'normal';
431
+ }
432
+
433
+ /** `border` and `border-<side>`: width || style || colour, each at most once; the rest initial */
434
+ function border(xs: CV[], sides: readonly (typeof SIDES)[number][]): Assignment[] | null {
435
+ if (xs.length > 3) return null;
436
+ let w: string | null = null, s: string | null = null, c: string | null = null;
437
+ for (const x of xs) {
438
+ let v: string | null;
439
+ if (s === null && (v = BORDER_STYLE(x)) !== null) s = v;
440
+ else if (w === null && (v = BORDER_WIDTH(x)) !== null) w = v;
441
+ else if (c === null && (v = color(x)) !== null) c = v;
442
+ else return null;
443
+ }
444
+ return sides.flatMap((side): Assignment[] => [
445
+ [`border-${side}-width`, w ?? 'medium'],
446
+ [`border-${side}-style`, s ?? 'none'],
447
+ [`border-${side}-color`, c ?? 'currentcolor'],
448
+ ]);
449
+ }
450
+
451
+ const RADIUS = (v: CV | undefined) => length(v, { pct: true });
452
+
453
+ /** one corner: one radius, or a horizontal and a vertical one */
454
+ function corner(xs: CV[]): string | null {
455
+ if (xs.length > 2) return null;
456
+ const vs = xs.map(RADIUS);
457
+ if (vs.includes(null)) return null;
458
+ return vs.length === 2 && vs[0] === vs[1] ? vs[0] : vs.join(' ');
459
+ }
460
+
461
+ /** `border-radius`: 1–4 horizontal radii, then optionally `/` and 1–4 vertical ones, per corner */
462
+ function borderRadius(xs: CV[]): Assignment[] | null {
463
+ const slash = xs.findIndex((x) => x.t === 'delim' && x.v === '/');
464
+ const h = slash < 0 ? xs : xs.slice(0, slash);
465
+ const v = slash < 0 ? null : xs.slice(slash + 1);
466
+ const expandFour = (ys: CV[]): string[] | null => {
467
+ if (ys.length < 1 || ys.length > 4) return null;
468
+ const out = ys.map(RADIUS);
469
+ if (out.includes(null)) return null;
470
+ const [a, b = a, c = a, d = b] = out as string[];
471
+ return [a, b, c, d];
472
+ };
473
+ const hs = expandFour(h);
474
+ const vs = v ? expandFour(v) : hs;
475
+ if (!hs || !vs) return null;
476
+ return CORNERS.map((c, i): Assignment => [`border-${c}-radius` as Longhand, hs[i] === vs[i] ? hs[i] : `${hs[i]} ${vs[i]}`]);
477
+ }
478
+
479
+ const GENERIC = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong']);
480
+ const NOT_FAMILY = new Set(['inherit', 'initial', 'unset', 'default', 'revert', 'revert-layer']);
481
+
482
+ /**
483
+ * A font-family list: each family a string or a run of identifiers, written back as a string (a generic
484
+ * family as its keyword). A family that cannot be written without an escape is left out of the list.
485
+ */
486
+ export function fontFamily(items: CV[]): string | null {
487
+ const out: string[] = [];
488
+ let part: CV[] = [];
489
+ const flush = (): boolean => {
490
+ const xs = part.filter((x) => x.t !== 'ws');
491
+ part = [];
492
+ if (xs.length === 0) return false;
493
+ if (xs.length === 1 && xs[0].t === 'string') {
494
+ const q = quote(xs[0].v);
495
+ if (q !== null) out.push(q);
496
+ return true;
497
+ }
498
+ if (!xs.every((x) => x.t === 'ident')) return false;
499
+ const words = xs.map((x) => (x as { v: string }).v);
500
+ const first = words[0].toLowerCase();
501
+ if (words.length === 1 && GENERIC.has(first)) { out.push(first); return true; }
502
+ if (NOT_FAMILY.has(first)) return false;
503
+ const q = quote(words.join(' '));
504
+ if (q !== null) out.push(q);
505
+ return true;
506
+ };
507
+ for (const v of items) {
508
+ if (v.t === ',') { if (!flush()) return null; } else part.push(v);
509
+ }
510
+ if (!flush()) return null;
511
+ return out.length ? out.join(', ') : null;
512
+ }
513
+
514
+ const STRETCH = new Set(['ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded']);
515
+ const SYSTEM_FONTS = new Set(['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar']);
516
+
517
+ /**
518
+ * `font`: [style || variant || weight || stretch]? size [/ line-height]? family. It sets every font
519
+ * longhand: what it does not name goes back to its initial value. System fonts are not kept.
520
+ */
521
+ function font(items: CV[]): Assignment[] | null {
522
+ const xs = items.filter((x) => x.t !== 'ws');
523
+ if (xs.length === 1 && SYSTEM_FONTS.has(kw(xs[0]) ?? '')) return null;
524
+ let style: string | null = null, variant: string | null = null, weight: string | null = null;
525
+ let stretch = false;
526
+ let i = 0;
527
+ for (let n = 0; n < 4 && i < xs.length; n++) {
528
+ const x = xs[i];
529
+ const k = kw(x);
530
+ if (k === 'normal') { i++; continue; }
531
+ if (style === null && (k === 'italic' || k === 'oblique')) { style = k; i++; continue; }
532
+ if (variant === null && k === 'small-caps') { variant = k; i++; continue; }
533
+ if (weight === null && k !== null && ['bold', 'bolder', 'lighter'].includes(k)) { weight = k; i++; continue; }
534
+ if (weight === null && x.t === 'number' && x.n >= 1 && x.n <= 1000) { weight = num(x.n); i++; continue; }
535
+ if (!stretch && k !== null && STRETCH.has(k)) { stretch = true; i++; continue; }
536
+ break;
537
+ }
538
+ const size = FONT_SIZE(xs[i]);
539
+ if (size === null) return null;
540
+ i++;
541
+ let lineHeight = 'normal';
542
+ if (xs[i]?.t === 'delim' && (xs[i] as { v: string }).v === '/') {
543
+ const lh = LINE_HEIGHT(xs[i + 1]);
544
+ if (lh === null) return null;
545
+ lineHeight = lh;
546
+ i += 2;
547
+ }
548
+ // the family is the rest of the original items, after the component values consumed
549
+ const rest = items.slice(items.indexOf(xs[i - 1]) + 1);
550
+ const family = fontFamily(rest);
551
+ if (family === null) return null;
552
+ return [
553
+ ['font-style', style ?? 'normal'],
554
+ ['font-variant', variant ?? 'normal'],
555
+ ['font-weight', weight ?? 'normal'],
556
+ ['font-size', size],
557
+ ['line-height', lineHeight],
558
+ ['font-family', family],
559
+ ];
560
+ }
561
+
562
+ const BG_KEYWORDS = new Set([
563
+ 'none', 'repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'space', 'round', 'scroll', 'fixed', 'local', 'left', 'right', 'top',
564
+ 'bottom', 'center', 'border-box', 'padding-box', 'content-box', 'text', 'auto', 'cover', 'contain',
565
+ ]);
566
+ const IMAGE_FUNCTIONS = new Set([
567
+ 'url', 'linear-gradient', 'radial-gradient', 'conic-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient',
568
+ 'repeating-conic-gradient', 'image-set', '-webkit-image-set', '-webkit-linear-gradient', '-webkit-radial-gradient',
569
+ '-webkit-repeating-linear-gradient', '-webkit-repeating-radial-gradient', '-webkit-gradient', 'cross-fade', '-webkit-cross-fade',
570
+ ]);
571
+
572
+ /**
573
+ * `background`: only its colour is kept (images are not, in version 1), but the whole value is checked
574
+ * as a browser would, so an invalid `background` does not reset the colour. A valid one without a
575
+ * colour sets it to its initial value, `transparent`.
576
+ */
577
+ function background(items: CV[]): Assignment[] | null {
578
+ const xs = items.filter((x) => x.t !== 'ws');
579
+ const layers: CV[][] = [[]];
580
+ for (const x of xs) {
581
+ if (x.t === ',') layers.push([]);
582
+ else layers[layers.length - 1].push(x);
583
+ }
584
+ let c: string | null = null;
585
+ for (let l = 0; l < layers.length; l++) {
586
+ const layer = layers[l];
587
+ if (layer.length === 0) return null;
588
+ for (const x of layer) {
589
+ const k = kw(x);
590
+ if (k !== null && BG_KEYWORDS.has(k)) continue;
591
+ if (x.t === 'url' || (x.t === 'func' && IMAGE_FUNCTIONS.has(x.name.toLowerCase()))) continue;
592
+ if (x.t === 'delim' && x.v === '/') continue;
593
+ // positions and sizes (a position may be negative)
594
+ if ((x.t === 'number' && x.n === 0) || x.t === 'percentage' || (x.t === 'dimension' && x.unit.toLowerCase() in UNITS)) continue;
595
+ const v = color(x);
596
+ // a colour only once, and only in the last layer
597
+ if (v !== null && c === null && l === layers.length - 1) { c = v; continue; }
598
+ return null;
599
+ }
600
+ }
601
+ return [['background-color', c ?? 'transparent']];
602
+ }
603
+
604
+ /** `list-style`: type || position || image; `none` sets whichever of type and image is not given */
605
+ function listStyle(xs: CV[]): Assignment[] | null {
606
+ if (xs.length > 3) return null;
607
+ let type: string | null = null, position: string | null = null;
608
+ let image = false;
609
+ let nones = 0;
610
+ for (const x of xs) {
611
+ const k = kw(x);
612
+ if (k === 'none') { nones++; continue; }
613
+ let v: string | null;
614
+ if (position === null && (v = SINGLE['list-style-position']!(x)) !== null) position = v;
615
+ else if (type === null && (v = listType(x)) !== null) type = v;
616
+ else if (!image && (x.t === 'url' || (x.t === 'func' && IMAGE_FUNCTIONS.has(x.name.toLowerCase())))) image = true;
617
+ else return null;
618
+ }
619
+ // `none` fills the type when nothing else did; two need both type and image free
620
+ if (nones > 2 || (nones === 2 && (type !== null || image)) || (nones === 1 && type !== null && image)) return null;
621
+ if (nones > 0 && type === null) type = 'none';
622
+ return [['list-style-type', type ?? 'disc'], ['list-style-position', position ?? 'outside']];
623
+ }
624
+
625
+ const LINES = new Set(['underline', 'overline', 'line-through', 'blink']);
626
+
627
+ /**
628
+ * `text-decoration` (line || style || colour || thickness; the thickness is checked and not kept) or,
629
+ * with `shorthand` false, `text-decoration-line`.
630
+ */
631
+ function textDecoration(xs: CV[], shorthand: boolean): Assignment[] | null {
632
+ const lines: string[] = [];
633
+ let none = false;
634
+ let style: string | null = null, c: string | null = null, thickness = false;
635
+ for (const x of xs) {
636
+ const k = kw(x);
637
+ let v: string | null;
638
+ if (k === 'none' && !none && lines.length === 0) { none = true; continue; }
639
+ if (k !== null && LINES.has(k) && !none && !lines.includes(k)) { lines.push(k); continue; }
640
+ if (!shorthand) return null;
641
+ if (style === null && (v = SINGLE['text-decoration-style']!(x)) !== null) { style = v; continue; }
642
+ if (c === null && (v = color(x)) !== null) { c = v; continue; }
643
+ if (!thickness && (k === 'auto' || k === 'from-font' || length(x, { pct: true }) !== null)) { thickness = true; continue; }
644
+ return null;
645
+ }
646
+ const line = lines.length ? lines.join(' ') : none ? 'none' : null;
647
+ if (!shorthand) return line === null ? null : [['text-decoration-line', line]];
648
+ return [['text-decoration-line', line ?? 'none'], ['text-decoration-style', style ?? 'solid'], ['text-decoration-color', c ?? 'currentcolor']];
649
+ }
650
+
651
+ /** the `text-decoration` value from its tracked longhands, or null */
652
+ export function joinTextDecoration(line?: string, style?: string, c?: string): string | null {
653
+ if (line === undefined && style === undefined && c === undefined) return null;
654
+ // a CSS-wide keyword is written as itself when the other two are unset or the same keyword
655
+ if (line !== undefined && WIDE.has(line)) return (style === undefined || style === line) && (c === undefined || c === line) ? line : null;
656
+ const parts = [line ?? 'none'];
657
+ if (style !== undefined && !WIDE.has(style) && style !== 'solid') parts.push(style);
658
+ if (c !== undefined && !WIDE.has(c) && c !== 'currentcolor') parts.push(c);
659
+ return parts.join(' ');
660
+ }
661
+
662
+ /** `overflow` from its tracked longhands: kept when both axes are the same (`clip` written as `hidden`) */
663
+ export function joinOverflow(x?: string, y?: string): string | null {
664
+ const norm = (v: string | undefined) => (v === 'clip' ? 'hidden' : v ?? 'visible');
665
+ if (x === undefined && y === undefined) return null;
666
+ const a = norm(x);
667
+ const b = norm(y);
668
+ return a === b ? a : null;
669
+ }