castle-web-cli 0.4.212 → 0.4.214

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 (56) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +28 -6
  3. package/dist/agent.js +33 -2
  4. package/dist/cloudGit.d.ts +254 -0
  5. package/dist/cloudGit.js +1687 -0
  6. package/dist/cloudGitServe.d.ts +41 -0
  7. package/dist/cloudGitServe.js +318 -0
  8. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  9. package/dist/externalSourcemaps.js +2 -1
  10. package/dist/gitRemote.d.ts +4 -1
  11. package/dist/gitRemote.js +4 -2
  12. package/dist/ide.js +52 -7
  13. package/dist/index.js +149 -2
  14. package/dist/playCover/bridge.d.ts +6 -0
  15. package/dist/playCover/bridge.js +159 -0
  16. package/dist/playCover/builtins.d.ts +29 -0
  17. package/dist/playCover/builtins.js +189 -0
  18. package/dist/playCover/capture.d.ts +53 -0
  19. package/dist/playCover/capture.js +419 -0
  20. package/dist/playCover/clone.d.ts +40 -0
  21. package/dist/playCover/clone.js +317 -0
  22. package/dist/playCover/engine.d.ts +37 -0
  23. package/dist/playCover/engine.js +76 -0
  24. package/dist/playCover/errors.d.ts +6 -0
  25. package/dist/playCover/errors.js +18 -0
  26. package/dist/playCover/images.d.ts +21 -0
  27. package/dist/playCover/images.js +180 -0
  28. package/dist/playCover/instrument.d.ts +49 -0
  29. package/dist/playCover/instrument.js +334 -0
  30. package/dist/playCover/protocol.d.ts +14 -0
  31. package/dist/playCover/protocol.js +139 -0
  32. package/dist/playCover/rasterize.d.ts +21 -0
  33. package/dist/playCover/rasterize.js +408 -0
  34. package/dist/playCover/resources.d.ts +31 -0
  35. package/dist/playCover/resources.js +823 -0
  36. package/dist/playCover/scratchCanvas.d.ts +4 -0
  37. package/dist/playCover/scratchCanvas.js +16 -0
  38. package/dist/playCover/textSamples.d.ts +36 -0
  39. package/dist/playCover/textSamples.js +412 -0
  40. package/dist/playCover/validate.d.ts +79 -0
  41. package/dist/playCover/validate.js +883 -0
  42. package/dist/playCover/verify.d.ts +56 -0
  43. package/dist/playCover/verify.js +578 -0
  44. package/dist/playCover/verifyRecord.d.ts +71 -0
  45. package/dist/playCover/verifyRecord.js +243 -0
  46. package/dist/playCoverGate.d.ts +4 -0
  47. package/dist/playCoverGate.js +57 -0
  48. package/dist/playCoverPlacement.d.ts +11 -0
  49. package/dist/playCoverPlacement.js +110 -0
  50. package/dist/serve.d.ts +1 -0
  51. package/dist/serve.js +35 -17
  52. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  53. package/dist/shell/assets/{index-DzLbNBc7.js → index-BcslKMfS.js} +94 -92
  54. package/dist/shell/index.html +2 -2
  55. package/package.json +2 -2
  56. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,883 @@
1
+ // What a Play cover capture will and will not copy, element by element.
2
+ // Adapted from the visual-snapshot prototype's serializer (see instrument.ts
3
+ // for provenance). Everything here rejects rather than approximates: an
4
+ // element the inert copy cannot reproduce is a named refusal, never a gap in
5
+ // the picture.
6
+ import { trim } from './builtins.js';
7
+ import { fail } from './errors.js';
8
+ const REJECTED_ELEMENTS = new Set([
9
+ 'SCRIPT',
10
+ 'NOSCRIPT',
11
+ 'IFRAME',
12
+ 'FRAME',
13
+ 'OBJECT',
14
+ 'EMBED',
15
+ 'APPLET',
16
+ 'VIDEO',
17
+ 'AUDIO',
18
+ 'SOURCE',
19
+ 'TRACK',
20
+ 'LINK',
21
+ 'META',
22
+ 'BASE',
23
+ 'MATH',
24
+ 'PORTAL',
25
+ ]);
26
+ export const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
27
+ export const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
28
+ const SAFE_SVG_ELEMENTS = new Set([
29
+ 'svg',
30
+ 'g',
31
+ 'path',
32
+ 'rect',
33
+ 'circle',
34
+ 'ellipse',
35
+ 'line',
36
+ 'polyline',
37
+ 'polygon',
38
+ ]);
39
+ const SVG_PAINT_ATTRIBUTES = [
40
+ 'color',
41
+ 'fill',
42
+ 'flood-color',
43
+ 'lighting-color',
44
+ 'stop-color',
45
+ 'stroke',
46
+ ];
47
+ const HEX_COLOR = /^\s*#[0-9a-f]{3}(?:[0-9a-f](?:[0-9a-f]{2}){0,2})?\s*$/i;
48
+ const INERT_INPUT_TYPES = ['checkbox', 'radio', 'button', 'submit', 'reset'];
49
+ function skipString(value, index) {
50
+ const quote = value[index];
51
+ let at = index + 1;
52
+ while (at < value.length && value[at] !== quote)
53
+ at += value[at] === '\\' ? 2 : 1;
54
+ return at + 1;
55
+ }
56
+ function skipSpace(value, index) {
57
+ let at = index;
58
+ while (/\s/.test(value[at] ?? ''))
59
+ at++;
60
+ return at;
61
+ }
62
+ function readUrlToken(value, start) {
63
+ let at = skipSpace(value, start + 4);
64
+ let url;
65
+ if (value[at] === '"' || value[at] === "'") {
66
+ const close = skipString(value, at);
67
+ url = value.slice(at + 1, close - 1);
68
+ at = skipSpace(value, close);
69
+ if (value[at] !== ')')
70
+ return null;
71
+ }
72
+ else {
73
+ const close = value.indexOf(')', at);
74
+ if (close < 0)
75
+ return null;
76
+ url = value.slice(at, close);
77
+ at = close;
78
+ }
79
+ return { start, end: at + 1, url: trim(url) };
80
+ }
81
+ function startsUrlToken(value, index) {
82
+ return /^url\(/i.test(value.slice(index, index + 4)) && !/[\w-]/.test(value[index - 1] ?? '');
83
+ }
84
+ /**
85
+ * The url() tokens in a CSS value, read the way CSS reads them: text inside a
86
+ * string (a local("...") name, a content string) is never taken for a URL, and
87
+ * neither is a function whose name merely ends in "url".
88
+ */
89
+ export function urlTokens(value) {
90
+ const tokens = [];
91
+ let index = 0;
92
+ while (index < value.length) {
93
+ const char = value[index];
94
+ if (char === '\\') {
95
+ index += 2;
96
+ }
97
+ else if (char === '"' || char === "'") {
98
+ index = skipString(value, index);
99
+ }
100
+ else if (startsUrlToken(value, index)) {
101
+ const token = readUrlToken(value, index);
102
+ if (!token)
103
+ return tokens;
104
+ tokens.push(token);
105
+ index = token.end;
106
+ }
107
+ else {
108
+ index++;
109
+ }
110
+ }
111
+ return tokens;
112
+ }
113
+ export function parseUrlFunctions(value) {
114
+ return urlTokens(value).map((token) => token.url);
115
+ }
116
+ /** The value with url() tokens (from urlTokens, in order) replaced. */
117
+ export function replaceUrlTokens(value, replacements) {
118
+ let result = '';
119
+ let at = 0;
120
+ for (const [token, replacement] of replacements) {
121
+ result += value.slice(at, token.start) + replacement;
122
+ at = token.end;
123
+ }
124
+ return result + value.slice(at);
125
+ }
126
+ /** A comma-separated CSS list, split at its top-level commas only. */
127
+ export function splitCssList(value) {
128
+ const items = [];
129
+ let depth = 0;
130
+ let from = 0;
131
+ let index = 0;
132
+ while (index < value.length) {
133
+ const char = value[index];
134
+ if (char === '\\') {
135
+ index += 2;
136
+ continue;
137
+ }
138
+ if (char === '"' || char === "'") {
139
+ index = skipString(value, index);
140
+ continue;
141
+ }
142
+ if (char === '(')
143
+ depth++;
144
+ else if (char === ')')
145
+ depth = Math.max(0, depth - 1);
146
+ else if (char === ',' && depth === 0) {
147
+ items.push(trim(value.slice(from, index)));
148
+ from = index + 1;
149
+ }
150
+ index++;
151
+ }
152
+ items.push(trim(value.slice(from)));
153
+ return items.filter(Boolean);
154
+ }
155
+ // A CSS font-family list, split the way CSS reads it: commas inside a quoted
156
+ // name ("Comma, Font") belong to the name, backslash escapes are honoured, and
157
+ // an unquoted name of several identifiers is one name with single spaces. A
158
+ // list whose quotes do not balance is refused rather than guessed at -- a
159
+ // mis-split name is a web font silently drawn in its fallback.
160
+ export function familyNames(value) {
161
+ const names = [];
162
+ let current = '';
163
+ let quote = null;
164
+ let quoted = false;
165
+ const finish = () => {
166
+ const name = quoted ? current : trim(current).replace(/\s+/g, ' ');
167
+ if (name)
168
+ names.push(name.toLowerCase());
169
+ current = '';
170
+ quoted = false;
171
+ };
172
+ for (let index = 0; index < value.length; index++) {
173
+ const char = value[index];
174
+ if (char === '\\' && index + 1 < value.length) {
175
+ current += value[++index];
176
+ }
177
+ else if (quote) {
178
+ if (char === quote)
179
+ quote = null;
180
+ else
181
+ current += char;
182
+ }
183
+ else if (char === '"' || char === "'") {
184
+ quote = char;
185
+ quoted = true;
186
+ current = '';
187
+ }
188
+ else if (char === ',') {
189
+ finish();
190
+ }
191
+ else if (!quoted) {
192
+ current += char;
193
+ }
194
+ else if (trim(char)) {
195
+ fail('UNSUPPORTED_FONT', `font-family ${value} has text after a quoted name`);
196
+ }
197
+ }
198
+ if (quote)
199
+ fail('UNSUPPORTED_FONT', `font-family ${value} has an unterminated quote`);
200
+ finish();
201
+ return names;
202
+ }
203
+ /**
204
+ * One family name, unquoted and lower-cased (a FontFace family, an @font-face
205
+ * descriptor). A single name, not a list: Safari reports FontFace.family raw
206
+ * (`It's Font`, no quotes), so only a name wrapped in matching quotes is
207
+ * unquoted, and anything else is taken literally -- an apostrophe inside a name
208
+ * must never fail every capture on the page.
209
+ */
210
+ export function unquoteFamily(name) {
211
+ const trimmed = trim(name);
212
+ const quote = trimmed[0];
213
+ if (trimmed.length >= 2 && (quote === '"' || quote === "'") && trimmed.endsWith(quote)) {
214
+ return trimmed.slice(1, -1).replace(/\\(.)/g, '$1').toLowerCase();
215
+ }
216
+ return trimmed.replace(/\s+/g, ' ').toLowerCase();
217
+ }
218
+ /** The text a ::before/::after renders, or null when it renders none. */
219
+ export function decodePseudoContent(content) {
220
+ if (!content || content === 'none' || content === 'normal')
221
+ return null;
222
+ if (/^url\(/i.test(content)) {
223
+ fail('UNSUPPORTED_PSEUDO_RESOURCE', 'pseudo-element image content is not supported');
224
+ }
225
+ const quoted = (content.startsWith('"') && content.endsWith('"')) ||
226
+ (content.startsWith("'") && content.endsWith("'"));
227
+ if (!quoted)
228
+ fail('UNSUPPORTED_PSEUDO_CONTENT', `cannot freeze pseudo-element content ${content}`);
229
+ if (content.startsWith('"')) {
230
+ try {
231
+ return JSON.parse(content);
232
+ }
233
+ catch {
234
+ /* fall through to the literal unescape */
235
+ }
236
+ }
237
+ return content.slice(1, -1).replace(/\\(['"\\])/g, '$1');
238
+ }
239
+ export function elementHasRenderedText(element, style) {
240
+ if (style.display === 'none' || style.visibility === 'hidden')
241
+ return false;
242
+ for (const child of element.childNodes) {
243
+ if (child.nodeType === Node.TEXT_NODE && trim(child.textContent ?? ''))
244
+ return true;
245
+ }
246
+ return (element instanceof HTMLInputElement &&
247
+ ['button', 'submit', 'reset'].includes(element.type) &&
248
+ Boolean(element.value));
249
+ }
250
+ /** Every element of `root` that paints: subtrees with display:none are skipped. */
251
+ export function visibleSnapshotElements(root) {
252
+ const elements = [];
253
+ const visit = (element) => {
254
+ if (element !== root && getComputedStyle(element).display === 'none')
255
+ return;
256
+ elements.push(element);
257
+ for (const child of element.children)
258
+ visit(child);
259
+ };
260
+ visit(root);
261
+ return elements;
262
+ }
263
+ function validateSvgElement(source, label) {
264
+ if (!SAFE_SVG_ELEMENTS.has(source.localName)) {
265
+ fail('UNSUPPORTED_SVG_ELEMENT', `${label} contains <${source.localName}>`);
266
+ }
267
+ for (const attribute of source.attributes) {
268
+ if (/^on/i.test(attribute.name)) {
269
+ fail('UNSUPPORTED_EVENT_HANDLER', `${label} contains ${attribute.name}`);
270
+ }
271
+ const paintColor = SVG_PAINT_ATTRIBUTES.includes(attribute.localName) && HEX_COLOR.test(attribute.value);
272
+ if (/(?:^|:)href$/i.test(attribute.name) ||
273
+ /url\s*\(/i.test(attribute.value) ||
274
+ (/^\s*#/.test(attribute.value) && !paintColor)) {
275
+ fail('UNSUPPORTED_SVG_REFERENCE', `${label} contains resource/reference attribute ${attribute.name}`);
276
+ }
277
+ }
278
+ }
279
+ // Whether the page gives this element's scrollbars room: classic scrollbars do;
280
+ // overlay scrollbars (macOS by default) and headless browsers' hidden ones do
281
+ // not. The copy cannot draw a live scrollbar faithfully -- its thumb position,
282
+ // its ::-webkit-scrollbar styling -- so a card showing one is refused.
283
+ function hasLayoutScrollbars(source) {
284
+ if (!(source instanceof HTMLElement))
285
+ return false;
286
+ const style = getComputedStyle(source);
287
+ // overflow does not apply to an inline or display:contents box, and its
288
+ // offsetWidth/clientWidth measure something else entirely (clientWidth is 0).
289
+ if (['inline', 'contents', 'none'].includes(style.display))
290
+ return false;
291
+ const scrolls = (value) => value === 'auto' || value === 'scroll';
292
+ if (!scrolls(style.overflowX) && !scrolls(style.overflowY))
293
+ return false;
294
+ const px = (value) => Number.parseFloat(value) || 0;
295
+ const vertical = source.offsetWidth -
296
+ source.clientWidth -
297
+ px(style.borderLeftWidth) -
298
+ px(style.borderRightWidth);
299
+ const horizontal = source.offsetHeight -
300
+ source.clientHeight -
301
+ px(style.borderTopWidth) -
302
+ px(style.borderBottomWidth);
303
+ return vertical > 0.5 || horizontal > 0.5;
304
+ }
305
+ // A scrolled box is copied by moving its content inside a plain translated
306
+ // block (clone.ts appendScrolled). That is only the page's layout when the box
307
+ // itself lays its content out as blocks, left to right and top to bottom, and
308
+ // nothing inside it is placed against the box or the viewport rather than the
309
+ // content: a flex or grid scroller, sticky headers, and absolute or fixed
310
+ // children anchored outside the content all come out wrong, so they refuse.
311
+ function scrollLayoutProblem(source) {
312
+ const style = getComputedStyle(source);
313
+ if (!['block', 'flow-root', 'list-item'].includes(style.display))
314
+ return `its display is ${style.display}`;
315
+ if (style.writingMode !== 'horizontal-tb')
316
+ return `its writing mode is ${style.writingMode}`;
317
+ // Columns are laid out across the box, not down its content: the translated
318
+ // block would re-flow them over each other.
319
+ // That includes columns: 1 -- a scroller of bounded height does not scroll
320
+ // one column down, it adds overflow columns sideways, which is the only way
321
+ // such a box is ever scrolled at all.
322
+ if (style.columnCount !== 'auto' || style.columnWidth !== 'auto') {
323
+ return 'it lays its content out in columns';
324
+ }
325
+ if (style.direction !== 'ltr')
326
+ return 'it lays out right to left';
327
+ for (const element of visibleSnapshotElements(source)) {
328
+ if (element === source)
329
+ continue;
330
+ const position = getComputedStyle(element).position;
331
+ if (position === 'sticky')
332
+ return 'it holds a sticky element';
333
+ if (position === 'fixed')
334
+ return 'it holds a fixed element';
335
+ if (position === 'absolute' && element instanceof HTMLElement) {
336
+ const anchor = element.offsetParent;
337
+ if (!anchor || anchor === source || !source.contains(anchor))
338
+ return 'it holds an element positioned against it';
339
+ }
340
+ }
341
+ return null;
342
+ }
343
+ // ::first-letter and ::first-line are not copied (a copied element's text is
344
+ // laid out afresh, with no pseudo-element rules behind it): one styled apart
345
+ // from its element -- a drop cap, a first line in another font -- would be
346
+ // drawn plain in the cover, so it refuses.
347
+ // Inherited properties are compared with the element's own; properties that
348
+ // do not inherit, with their initial value (what an unstyled pseudo has).
349
+ const FIRST_PSEUDO_INHERITED = [
350
+ 'font-family',
351
+ 'font-size',
352
+ 'font-weight',
353
+ 'font-style',
354
+ 'font-variant',
355
+ 'font-stretch',
356
+ 'letter-spacing',
357
+ 'word-spacing',
358
+ 'line-height',
359
+ 'text-transform',
360
+ 'text-shadow',
361
+ 'color',
362
+ ];
363
+ const FIRST_PSEUDO_INITIAL = [
364
+ ['background-color', 'rgba(0, 0, 0, 0)'],
365
+ ['background-image', 'none'],
366
+ ['text-decoration-line', 'none'],
367
+ ['float', 'none'],
368
+ ['vertical-align', 'baseline'],
369
+ ];
370
+ function firstLineOrLetterStyled(source) {
371
+ const own = getComputedStyle(source);
372
+ for (const pseudo of ['::first-letter', '::first-line']) {
373
+ const style = getComputedStyle(source, pseudo);
374
+ for (const property of FIRST_PSEUDO_INHERITED) {
375
+ if (style.getPropertyValue(property) !== own.getPropertyValue(property))
376
+ return pseudo;
377
+ }
378
+ for (const [property, initial] of FIRST_PSEUDO_INITIAL) {
379
+ if (style.getPropertyValue(property) !== initial)
380
+ return pseudo;
381
+ }
382
+ }
383
+ return null;
384
+ }
385
+ /** Whether the card, or any ancestor up to <html>, styles a first letter or line apart. */
386
+ export function refuseStyledFirstLines(root) {
387
+ for (let element = flatParent(root); element; element = flatParent(element)) {
388
+ const styled = firstLineOrLetterStyled(element);
389
+ if (styled) {
390
+ fail('UNSUPPORTED_PSEUDO_STYLE', `<${element.tagName.toLowerCase()}> around the card styles its ${styled}`);
391
+ }
392
+ }
393
+ }
394
+ // A list item's marker is regenerated in the copy from the copied list
395
+ // style; a ::marker rule of its own (colour, font, content) is not carried.
396
+ const MARKER_INHERITED = [
397
+ 'font-family',
398
+ 'font-size',
399
+ 'font-weight',
400
+ 'font-style',
401
+ 'font-stretch',
402
+ 'letter-spacing',
403
+ 'text-shadow',
404
+ 'color',
405
+ ];
406
+ function markerStyled(source) {
407
+ const own = getComputedStyle(source);
408
+ const marker = getComputedStyle(source, '::marker');
409
+ if (marker.content !== 'normal')
410
+ return true;
411
+ return MARKER_INHERITED.some((property) => marker.getPropertyValue(property) !== own.getPropertyValue(property));
412
+ }
413
+ const MARKER_SAMPLES = {
414
+ disc: '\u2022',
415
+ circle: '\u25e6',
416
+ square: '\u25aa',
417
+ decimal: '0123456789.',
418
+ 'decimal-leading-zero': '0123456789.',
419
+ 'lower-alpha': 'abcdefghijklmnopqrstuvwxyz.',
420
+ 'lower-latin': 'abcdefghijklmnopqrstuvwxyz.',
421
+ 'upper-alpha': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.',
422
+ 'upper-latin': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.',
423
+ 'lower-roman': 'ivxlcdm.',
424
+ 'upper-roman': 'IVXLCDM.',
425
+ 'disclosure-open': '\u25be',
426
+ 'disclosure-closed': '\u25b8',
427
+ };
428
+ /**
429
+ * The characters a list item's marker is drawn with (in the item's own
430
+ * font), for the font check: null when it shows no text marker, undefined
431
+ * when its type is one this does not know.
432
+ */
433
+ export function listMarkerText(element, style) {
434
+ if (!style.display.includes('list-item') || style.listStyleImage !== 'none')
435
+ return null;
436
+ const type = style.listStyleType;
437
+ if (type === 'none')
438
+ return null;
439
+ if (type.startsWith('"') || type.startsWith("'"))
440
+ return decodePseudoContent(type);
441
+ return MARKER_SAMPLES[type];
442
+ }
443
+ /**
444
+ * A live selection or a CSS Custom Highlight over the card paints on the
445
+ * page, and a copy of the card's markup carries neither: refuse.
446
+ *
447
+ * Known limit: a visited link's :visited style is also not copied, and
448
+ * cannot be detected -- getComputedStyle reports the unvisited style by
449
+ * design, so the cover shows links as unvisited.
450
+ */
451
+ export function refuseHighlights(root) {
452
+ const touches = (range) => {
453
+ try {
454
+ const live = document.createRange();
455
+ live.setStart(range.startContainer, range.startOffset);
456
+ live.setEnd(range.endContainer, range.endOffset);
457
+ return live.intersectsNode(root);
458
+ }
459
+ catch {
460
+ return true;
461
+ }
462
+ };
463
+ const selection = document.getSelection();
464
+ if (selection && !selection.isCollapsed) {
465
+ for (let index = 0; index < selection.rangeCount; index++) {
466
+ if (touches(selection.getRangeAt(index))) {
467
+ fail('CARD_TEXT_SELECTED', 'text on the card is selected');
468
+ }
469
+ }
470
+ }
471
+ const highlights = CSS
472
+ .highlights;
473
+ if (highlights) {
474
+ for (const highlight of highlights.values()) {
475
+ for (const range of highlight) {
476
+ if (touches(range))
477
+ fail('UNSUPPORTED_HIGHLIGHT', 'a CSS highlight covers text on the card');
478
+ }
479
+ }
480
+ }
481
+ }
482
+ // Native controls drawn by the platform theme (appearance: auto) paint
483
+ // un-themed inside an SVG image. Checkboxes and radios survive; progress and
484
+ // meter bars do not, nor do buttons -- unless their background or border is
485
+ // author-styled, when the browser draws them from CSS on the page too.
486
+ //
487
+ // A button's untouched look is Chromium's own stylesheet, which no page CSS
488
+ // reaches here and nothing is added to the DOM to learn: a ButtonFace
489
+ // background (rgb(239,239,239) light, rgb(107,107,107) dark), no background
490
+ // image, and a 2px outset border. (Its border colour follows the text colour
491
+ // and says nothing.) Any other background or border is author styling.
492
+ // (Disabled: the same at 30% -- rgba(239,239,239,0.3) light,
493
+ // rgba(19,1,1,0.3) dark -- still natively themed.)
494
+ const DEFAULT_BUTTON_BACKGROUNDS = [
495
+ 'rgb(239, 239, 239)',
496
+ 'rgb(107, 107, 107)',
497
+ 'rgba(239, 239, 239, 0.3)',
498
+ 'rgba(19, 1, 1, 0.3)',
499
+ ];
500
+ function nativeControl(source, style) {
501
+ if (style.appearance === 'none')
502
+ return false;
503
+ if (source instanceof HTMLProgressElement || source instanceof HTMLMeterElement)
504
+ return true;
505
+ const button = source instanceof HTMLButtonElement ||
506
+ (source instanceof HTMLInputElement && ['button', 'submit', 'reset'].includes(source.type));
507
+ if (!button)
508
+ return false;
509
+ return (DEFAULT_BUTTON_BACKGROUNDS.includes(style.backgroundColor) &&
510
+ style.backgroundImage === 'none' &&
511
+ ['Top', 'Right', 'Bottom', 'Left'].every((side) => style.getPropertyValue(`border-${side.toLowerCase()}-style`) === 'outset' &&
512
+ style.getPropertyValue(`border-${side.toLowerCase()}-width`) === '2px'));
513
+ }
514
+ // Elements in the top layer (a modal dialog, an open popover) paint above
515
+ // everything, with a ::backdrop; a copy puts them back in normal stacking.
516
+ function inTopLayer(source) {
517
+ for (const selector of [':modal', ':popover-open']) {
518
+ try {
519
+ if (source.matches(selector))
520
+ return true;
521
+ }
522
+ catch {
523
+ // A selector this browser does not know matches nothing here.
524
+ }
525
+ }
526
+ return false;
527
+ }
528
+ // What an ancestor of the card paints over all of it -- opacity, filters,
529
+ // blending, masks, clipping -- is not part of the card's copy.
530
+ const ANCESTOR_EFFECTS = [
531
+ ['filter', 'none'],
532
+ ['backdrop-filter', 'none'],
533
+ ['mix-blend-mode', 'normal'],
534
+ ['mask-image', 'none'],
535
+ ['-webkit-mask-image', 'none'],
536
+ ['clip-path', 'none'],
537
+ ];
538
+ // Readable copies of stylesheets the page cannot read (cross-origin, e.g. a
539
+ // Google Fonts <link>), fetched under CORS before validation
540
+ // (resources.ts) so a line clamp's declared display can still be read.
541
+ const sheetCopies = new Map();
542
+ /** Forgets every copy (each capture fetches its own). */
543
+ export function clearSheetCopies() {
544
+ sheetCopies.clear();
545
+ }
546
+ export function setSheetCopy(href, text) {
547
+ const copy = new CSSStyleSheet();
548
+ try {
549
+ copy.replaceSync(text);
550
+ sheetCopies.set(href, copy);
551
+ }
552
+ catch {
553
+ // Not parseable: the sheet stays unreadable, and a clamp that needs it refuses.
554
+ }
555
+ }
556
+ // Display keywords read as they are; anything else (var(), a global keyword
557
+ // like inherit or revert-layer, an unknown value) cannot be read plainly.
558
+ const PLAIN_DISPLAYS = new Set([
559
+ 'block',
560
+ 'inline',
561
+ 'inline-block',
562
+ 'flow-root',
563
+ 'inline-flow-root',
564
+ 'flex',
565
+ 'inline-flex',
566
+ 'grid',
567
+ 'inline-grid',
568
+ 'table',
569
+ 'inline-table',
570
+ 'list-item',
571
+ 'contents',
572
+ 'none',
573
+ '-webkit-box',
574
+ '-webkit-inline-box',
575
+ ]);
576
+ function noteDisplay(declared, value) {
577
+ const display = trim(value).replace(/\s*!important$/i, '');
578
+ if (PLAIN_DISPLAYS.has(display))
579
+ declared.values.add(display);
580
+ else
581
+ declared.unknown = true;
582
+ }
583
+ function ruleMatches(element, selector) {
584
+ try {
585
+ return element.matches(selector);
586
+ }
587
+ catch {
588
+ return null;
589
+ }
590
+ }
591
+ // Walks a sheet's rules for display declarations that can apply to the
592
+ // element. Only plain top-level style rules (and @media / @supports / @layer
593
+ // / @import around them) are read; a display declared in nested CSS, inside
594
+ // @container or @scope, or in a sheet that cannot be read makes the answer
595
+ // unknown -- the check refuses rather than interpret it.
596
+ function readRules(rules, element, declared, depth) {
597
+ for (const rule of rules) {
598
+ if (declared.unknown)
599
+ return;
600
+ const kind = rule.constructor.name;
601
+ if (kind === 'CSSStartingStyleRule')
602
+ continue;
603
+ if (rule instanceof CSSMediaRule) {
604
+ if (matchMedia(rule.media.mediaText).matches)
605
+ readRules(rule.cssRules, element, declared, depth);
606
+ continue;
607
+ }
608
+ if (rule instanceof CSSSupportsRule) {
609
+ if (CSS.supports(rule.conditionText))
610
+ readRules(rule.cssRules, element, declared, depth);
611
+ continue;
612
+ }
613
+ if (rule instanceof CSSImportRule) {
614
+ if (!rule.media.mediaText || matchMedia(rule.media.mediaText).matches) {
615
+ readSheet(rule.styleSheet, element, declared, depth + 1);
616
+ }
617
+ continue;
618
+ }
619
+ if (kind === 'CSSNestedDeclarations') {
620
+ if (rule.style.getPropertyValue('display')) {
621
+ declared.unknown = true;
622
+ }
623
+ continue;
624
+ }
625
+ if (rule instanceof CSSStyleRule) {
626
+ const display = rule.style.getPropertyValue('display');
627
+ const nested = rule.cssRules.length > 0;
628
+ if (display) {
629
+ const matches = ruleMatches(element, rule.selectorText);
630
+ if (matches === null)
631
+ declared.unknown = true;
632
+ else if (matches)
633
+ noteDisplay(declared, display);
634
+ }
635
+ // Nested CSS: selectors relative to the parent, conditions inside the
636
+ // rule -- not read. Any display declared in there is unknown.
637
+ if (nested && nestedDeclaresDisplay(rule.cssRules))
638
+ declared.unknown = true;
639
+ continue;
640
+ }
641
+ if (kind === 'CSSContainerRule' || kind === 'CSSScopeRule') {
642
+ if (nestedDeclaresDisplay(rule.cssRules))
643
+ declared.unknown = true;
644
+ continue;
645
+ }
646
+ if ('cssRules' in rule)
647
+ readRules(rule.cssRules, element, declared, depth);
648
+ }
649
+ }
650
+ function nestedDeclaresDisplay(rules) {
651
+ for (const rule of rules) {
652
+ const style = rule.style;
653
+ if (style?.getPropertyValue('display'))
654
+ return true;
655
+ if ('cssRules' in rule && nestedDeclaresDisplay(rule.cssRules))
656
+ return true;
657
+ }
658
+ return false;
659
+ }
660
+ function readSheet(sheet, element, declared, depth) {
661
+ if (!sheet || depth > 16) {
662
+ declared.unknown = true;
663
+ return;
664
+ }
665
+ if (sheet.disabled)
666
+ return;
667
+ if (sheet.media.mediaText && !matchMedia(sheet.media.mediaText).matches)
668
+ return;
669
+ let rules;
670
+ try {
671
+ rules = sheet.cssRules;
672
+ }
673
+ catch {
674
+ const copy = sheet.href ? sheetCopies.get(sheet.href) : undefined;
675
+ if (!copy) {
676
+ declared.unknown = true;
677
+ return;
678
+ }
679
+ rules = copy.cssRules;
680
+ }
681
+ readRules(rules, element, declared, depth);
682
+ }
683
+ // A running animation that animates display decides it frame by frame.
684
+ function animatesDisplay(element) {
685
+ for (const animation of element.getAnimations()) {
686
+ const effect = animation.effect;
687
+ if (effect instanceof KeyframeEffect &&
688
+ effect.getKeyframes().some((frame) => 'display' in frame)) {
689
+ return true;
690
+ }
691
+ }
692
+ return false;
693
+ }
694
+ // The display values an element's own CSS declares for it, read plainly (see
695
+ // readRules), or unknown.
696
+ function declaredDisplays(element) {
697
+ const declared = { values: new Set(), unknown: false };
698
+ const inline = element instanceof HTMLElement ? element.style.getPropertyValue('display') : '';
699
+ if (inline)
700
+ noteDisplay(declared, inline);
701
+ if (animatesDisplay(element))
702
+ declared.unknown = true;
703
+ const root = element.getRootNode();
704
+ const sheets = [
705
+ ...document.styleSheets,
706
+ ...(document.adoptedStyleSheets ?? []),
707
+ ...(root instanceof ShadowRoot ? [...root.styleSheets, ...root.adoptedStyleSheets] : []),
708
+ ];
709
+ for (const sheet of sheets)
710
+ readSheet(sheet, element, declared, 0);
711
+ return declared;
712
+ }
713
+ const WEBKIT_BOXES = ['-webkit-box', '-webkit-inline-box'];
714
+ /**
715
+ * What display a line-clamped element needs in the copy. Chromium clamps
716
+ * (with an ellipsis) only a vertical -webkit-box, and reports that box's
717
+ * display as flow-root (inline-block when inline): written back as
718
+ * reported, the copy loses the clamp's ellipsis. The reported display
719
+ * cannot tell such a box from an author's own flow-root or inline-block, so
720
+ * the element's declared display decides, read only where it is plain:
721
+ * every declaration a -webkit-box -> restore it; every one a plain other
722
+ * keyword (or none at all) -> keep the reported display; anything else --
723
+ * a mix, var() or a global keyword, nested CSS, @container or @scope, an
724
+ * animation of display, a sheet that cannot be read -> refused, rather than
725
+ * interpreted.
726
+ */
727
+ export function lineClampDisplay(element, style) {
728
+ const clamp = Number.parseInt(style.getPropertyValue('-webkit-line-clamp'), 10);
729
+ if (!Number.isFinite(clamp))
730
+ return null;
731
+ if (style.getPropertyValue('-webkit-box-orient') !== 'vertical')
732
+ return null;
733
+ const inline = ['inline-block', 'inline-flow-root', '-webkit-inline-box'].includes(style.display);
734
+ if (!inline && !['flow-root', '-webkit-box'].includes(style.display))
735
+ return null;
736
+ const declared = declaredDisplays(element);
737
+ const values = [...declared.values];
738
+ const boxes = values.filter((value) => WEBKIT_BOXES.includes(value));
739
+ if (!declared.unknown && boxes.length === 0)
740
+ return null;
741
+ if (!declared.unknown && boxes.length === values.length) {
742
+ return inline ? '-webkit-inline-box' : '-webkit-box';
743
+ }
744
+ return fail('UNSUPPORTED_LINE_CLAMP', "a line clamp on a box whose display is not plainly readable from the page's CSS");
745
+ }
746
+ // A ::before / ::after box cannot be matched against style rules the way an
747
+ // element can: a clamp Chromium would apply there (vertical, reported as
748
+ // flow-root / inline-block) is refused rather than copied without its
749
+ // ellipsis.
750
+ function refusePseudoClamps(source) {
751
+ for (const pseudo of ['::before', '::after']) {
752
+ const style = getComputedStyle(source, pseudo);
753
+ if (style.content === 'none' || style.content === 'normal')
754
+ continue;
755
+ if (style.getPropertyValue('-webkit-line-clamp') === 'none')
756
+ continue;
757
+ if (style.getPropertyValue('-webkit-box-orient') !== 'vertical')
758
+ continue;
759
+ if ([
760
+ 'flow-root',
761
+ 'inline-block',
762
+ 'inline-flow-root',
763
+ '-webkit-box',
764
+ '-webkit-inline-box',
765
+ ].includes(style.display)) {
766
+ fail('UNSUPPORTED_LINE_CLAMP', `a line clamp on ${pseudo} content`);
767
+ }
768
+ }
769
+ }
770
+ /** The element's parent in the flattened tree: its slot, its parent, or its shadow host. */
771
+ export function flatParent(element) {
772
+ if (element.assignedSlot)
773
+ return element.assignedSlot;
774
+ if (element.parentElement)
775
+ return element.parentElement;
776
+ const root = element.parentNode;
777
+ return root instanceof ShadowRoot ? root.host : null;
778
+ }
779
+ /** Refuses a card whose ancestors change how it looks as a whole. */
780
+ export function refuseAncestorEffects(root) {
781
+ for (let element = flatParent(root); element; element = flatParent(element)) {
782
+ const style = getComputedStyle(element);
783
+ const label = `<${element.tagName.toLowerCase()}> around the card`;
784
+ if (Number.parseFloat(style.opacity) < 0.999) {
785
+ fail('UNSUPPORTED_ANCESTOR_EFFECT', `${label} has opacity ${style.opacity}`);
786
+ }
787
+ for (const [property, none] of ANCESTOR_EFFECTS) {
788
+ const value = style.getPropertyValue(property);
789
+ if (value && value !== none)
790
+ fail('UNSUPPORTED_ANCESTOR_EFFECT', `${label} has ${property}: ${value}`);
791
+ }
792
+ }
793
+ }
794
+ // Whether an element (the card or one inside it) is the containing block
795
+ // of position:fixed descendants.
796
+ function containsFixed(style) {
797
+ return (style.transform !== 'none' ||
798
+ style.translate !== 'none' ||
799
+ style.rotate !== 'none' ||
800
+ style.scale !== 'none' ||
801
+ style.transformStyle === 'preserve-3d' ||
802
+ style.perspective !== 'none' ||
803
+ (style.contentVisibility !== '' && style.contentVisibility !== 'visible') ||
804
+ (style.containerType !== '' && style.containerType !== 'normal') ||
805
+ style.filter !== 'none' ||
806
+ style.getPropertyValue('backdrop-filter') !== 'none' ||
807
+ /\b(?:paint|layout|strict|content)\b/.test(style.contain) ||
808
+ /\b(?:transform|perspective|filter)\b/.test(style.willChange));
809
+ }
810
+ /**
811
+ * A position:fixed element whose containing block is the viewport is placed
812
+ * relative to it; the copy places it relative to the card. The two agree
813
+ * only when the card fills the viewport from its origin.
814
+ */
815
+ export function refuseViewportFixed(root, elements) {
816
+ const rect = root.getBoundingClientRect();
817
+ const fillsViewport = Math.abs(rect.left) < 0.5 &&
818
+ Math.abs(rect.top) < 0.5 &&
819
+ Math.abs(rect.width - window.innerWidth) < 0.5 &&
820
+ Math.abs(rect.height - window.innerHeight) < 0.5;
821
+ if (fillsViewport)
822
+ return;
823
+ for (const element of elements) {
824
+ if (element === root || getComputedStyle(element).position !== 'fixed')
825
+ continue;
826
+ let contained = false;
827
+ for (let parent = flatParent(element); parent && !contained; parent = flatParent(parent)) {
828
+ contained = containsFixed(getComputedStyle(parent));
829
+ if (parent === root)
830
+ break;
831
+ }
832
+ if (!contained) {
833
+ fail('UNSUPPORTED_FIXED_POSITION', 'a position:fixed element on the card is placed against the page, not the card');
834
+ }
835
+ }
836
+ }
837
+ export function validateElement(source, label) {
838
+ if (source.namespaceURI === SVG_NAMESPACE) {
839
+ validateSvgElement(source, label);
840
+ return;
841
+ }
842
+ if (source.namespaceURI !== HTML_NAMESPACE) {
843
+ fail('UNSUPPORTED_NAMESPACE', `${label} uses unsupported namespace ${source.namespaceURI ?? '(none)'}`);
844
+ }
845
+ if (REJECTED_ELEMENTS.has(source.tagName)) {
846
+ fail('UNSUPPORTED_ELEMENT', `${label} contains <${source.tagName.toLowerCase()}>`);
847
+ }
848
+ if (source.shadowRoot)
849
+ fail('UNSUPPORTED_SHADOW_ROOT', `${label} has a shadow root`);
850
+ if (hasLayoutScrollbars(source))
851
+ fail('UNSUPPORTED_SCROLLBARS', `${label} shows scrollbars that take up room`);
852
+ if (source.scrollTop || source.scrollLeft) {
853
+ const problem = scrollLayoutProblem(source);
854
+ if (problem)
855
+ fail('UNSUPPORTED_SCROLL_LAYOUT', `${label} is scrolled and ${problem}`);
856
+ }
857
+ if (source.hasAttribute('srcset'))
858
+ fail('UNSUPPORTED_RESOURCE', `${label} has srcset`);
859
+ if (nativeControl(source, getComputedStyle(source))) {
860
+ fail('UNSUPPORTED_NATIVE_CONTROL', `${label} is a native control drawn by the platform theme`);
861
+ }
862
+ lineClampDisplay(source, getComputedStyle(source));
863
+ refusePseudoClamps(source);
864
+ if (inTopLayer(source))
865
+ fail('UNSUPPORTED_TOP_LAYER', `${label} is in the top layer (a modal or popover)`);
866
+ const styled = firstLineOrLetterStyled(source);
867
+ if (styled)
868
+ fail('UNSUPPORTED_PSEUDO_STYLE', `${label} styles its ${styled} differently`);
869
+ if (getComputedStyle(source).display.includes('list-item') && markerStyled(source)) {
870
+ fail('UNSUPPORTED_PSEUDO_STYLE', `${label} styles its ::marker differently`);
871
+ }
872
+ if (source instanceof HTMLInputElement) {
873
+ const type = source.type.toLowerCase();
874
+ if (type === 'password')
875
+ fail('SENSITIVE_FORM_CONTROL', `${label} is a password input`);
876
+ if (!INERT_INPUT_TYPES.includes(type)) {
877
+ fail('UNSUPPORTED_FORM_VALUE', `${label} has a stateful ${type} value`);
878
+ }
879
+ }
880
+ if (source instanceof HTMLTextAreaElement || source instanceof HTMLSelectElement) {
881
+ fail('UNSUPPORTED_FORM_VALUE', `${label} contains a stateful form value`);
882
+ }
883
+ }