castle-web-cli 0.4.212 → 0.4.213

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 (46) hide show
  1. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  2. package/dist/externalSourcemaps.js +2 -1
  3. package/dist/ide.js +7 -2
  4. package/dist/playCover/bridge.d.ts +6 -0
  5. package/dist/playCover/bridge.js +159 -0
  6. package/dist/playCover/builtins.d.ts +29 -0
  7. package/dist/playCover/builtins.js +189 -0
  8. package/dist/playCover/capture.d.ts +53 -0
  9. package/dist/playCover/capture.js +419 -0
  10. package/dist/playCover/clone.d.ts +40 -0
  11. package/dist/playCover/clone.js +317 -0
  12. package/dist/playCover/engine.d.ts +37 -0
  13. package/dist/playCover/engine.js +76 -0
  14. package/dist/playCover/errors.d.ts +6 -0
  15. package/dist/playCover/errors.js +18 -0
  16. package/dist/playCover/images.d.ts +21 -0
  17. package/dist/playCover/images.js +180 -0
  18. package/dist/playCover/instrument.d.ts +49 -0
  19. package/dist/playCover/instrument.js +334 -0
  20. package/dist/playCover/protocol.d.ts +14 -0
  21. package/dist/playCover/protocol.js +139 -0
  22. package/dist/playCover/rasterize.d.ts +21 -0
  23. package/dist/playCover/rasterize.js +408 -0
  24. package/dist/playCover/resources.d.ts +31 -0
  25. package/dist/playCover/resources.js +823 -0
  26. package/dist/playCover/scratchCanvas.d.ts +4 -0
  27. package/dist/playCover/scratchCanvas.js +16 -0
  28. package/dist/playCover/textSamples.d.ts +36 -0
  29. package/dist/playCover/textSamples.js +412 -0
  30. package/dist/playCover/validate.d.ts +79 -0
  31. package/dist/playCover/validate.js +883 -0
  32. package/dist/playCover/verify.d.ts +56 -0
  33. package/dist/playCover/verify.js +578 -0
  34. package/dist/playCover/verifyRecord.d.ts +71 -0
  35. package/dist/playCover/verifyRecord.js +243 -0
  36. package/dist/playCoverGate.d.ts +4 -0
  37. package/dist/playCoverGate.js +57 -0
  38. package/dist/playCoverPlacement.d.ts +11 -0
  39. package/dist/playCoverPlacement.js +110 -0
  40. package/dist/serve.d.ts +1 -0
  41. package/dist/serve.js +35 -17
  42. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  43. package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
  44. package/dist/shell/index.html +2 -2
  45. package/package.json +2 -2
  46. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,40 @@
1
+ import { type ResourceBudget } from './resources.js';
2
+ import { type Effect, type EffectClips, type EmbeddedBitmap, type TextSample } from './verifyRecord.js';
3
+ export interface WebglFrame {
4
+ dataUrl: string;
5
+ width: number;
6
+ height: number;
7
+ valid: boolean;
8
+ }
9
+ /** The inert copy: everything the rasterizer needs, nothing it could fetch. */
10
+ export interface CoverPacket {
11
+ version: number;
12
+ width: number;
13
+ height: number;
14
+ backdropColor: string;
15
+ html: string;
16
+ fontCss: string;
17
+ byteLength: number;
18
+ /** Bitmaps whose painted pixels the rasterizer checks (verifyRecord.ts). */
19
+ bitmaps: EmbeddedBitmap[];
20
+ /** Bitmaps painted in a way the check cannot predict. */
21
+ unverifiedBitmaps: number;
22
+ /** Text drawn in each embedded web font, for the rasterizer's font check. */
23
+ textSamples: TextSample[];
24
+ /** Blur-type effects the card uses, each probed by the rasterizer's check. */
25
+ effects: Effect[];
26
+ /** Everything in the captured card WebKit is refused (engine.ts). */
27
+ webkitEffects: string[];
28
+ /**
29
+ * The attribute prefix this capture marks its own elements with in the copy
30
+ * (a random `data-cover-<nonce>`); a deck's own data-cover-* attributes are
31
+ * stripped from the copy besides.
32
+ */
33
+ marker: string;
34
+ /** How many of the deck's own data-cover-* attributes were left out of the copy. */
35
+ strippedMarks: number;
36
+ /** Where those effects are clipped, for the rasterizer's unclipped redraw. */
37
+ effectClips: EffectClips;
38
+ }
39
+ /** Copies `source` into an inert packet. Synchronous by contract. */
40
+ export declare function serializeCard(source: Element, budget: ResourceBudget, fontCss: string, fontFamilies: string[], webglFrames: Map<HTMLCanvasElement, WebglFrame>): CoverPacket;
@@ -0,0 +1,317 @@
1
+ // The synchronous half of a Play cover capture: an inert copy of the card made
2
+ // in one JavaScript turn at the end of an animation frame -- structure, every
3
+ // computed style inlined, canvases replaced by <img>s of their pixels, images
4
+ // and fonts already embedded as data: URLs. No scripts, handlers, links or
5
+ // external URLs survive into it.
6
+ //
7
+ // Adapted from the visual-snapshot prototype's serializer (see instrument.ts
8
+ // for provenance).
9
+ import { fail } from './errors.js';
10
+ import { contexts, natives } from './instrument.js';
11
+ import { allowedResourceUrl, rewriteCssValueSynchronously, } from './resources.js';
12
+ import { decodePseudoContent, HTML_NAMESPACE, lineClampDisplay, SVG_NAMESPACE, validateElement, } from './validate.js';
13
+ import { collectEffectClips, collectEffects, collectTextSamples, collectWebKitRefusedEffects, recordBitmap, } from './verifyRecord.js';
14
+ const MAX_NODES = 3_000;
15
+ const MAX_PACKAGE_BYTES = 12 * 1024 * 1024;
16
+ const PACKET_VERSION = 2;
17
+ const DROPPED_ATTRIBUTES = ['href', 'action', 'formaction', 'srcset', 'poster'];
18
+ function copyComputedStyle(source, target, pseudo, label, state) {
19
+ const style = getComputedStyle(source, pseudo);
20
+ for (const property of style) {
21
+ // Custom properties are already substituted into every property that
22
+ // uses them; their raw text is arbitrary and draws nothing itself.
23
+ if (property.startsWith('--'))
24
+ continue;
25
+ target.style.setProperty(property, rewriteCssValueSynchronously(style.getPropertyValue(property), state.budget, label, property), style.getPropertyPriority(property));
26
+ }
27
+ // A line-clamped -webkit-box reports display flow-root: without its box
28
+ // model restored, the copy clamps without the ellipsis (lineClampDisplay).
29
+ const clampDisplay = pseudo ? null : lineClampDisplay(source, style);
30
+ if (clampDisplay) {
31
+ target.style.setProperty('display', clampDisplay);
32
+ target.style.setProperty('-webkit-box-orient', 'vertical');
33
+ }
34
+ target.style.setProperty('animation', 'none', 'important');
35
+ target.style.setProperty('transition', 'none', 'important');
36
+ target.style.setProperty('caret-color', 'transparent', 'important');
37
+ target.style.setProperty('overflow-anchor', 'none', 'important');
38
+ }
39
+ function appendPseudo(source, target, pseudo, label, state) {
40
+ const style = getComputedStyle(source, pseudo);
41
+ const text = decodePseudoContent(style.content);
42
+ if (text === null || style.display === 'none')
43
+ return;
44
+ const node = document.createElement('span');
45
+ node.setAttribute('data-cover-pseudo', pseudo.slice(2));
46
+ node.textContent = text;
47
+ copyComputedStyle(source, node, pseudo, `${label}${pseudo}`, state);
48
+ if (pseudo === '::before')
49
+ target.prepend(node);
50
+ else
51
+ target.append(node);
52
+ }
53
+ function embeddedImageSource(source, value, budget) {
54
+ const allowed = allowedResourceUrl(source.currentSrc || value, 'image');
55
+ const embedded = allowed.inline ? allowed.url : budget.cache.get(allowed.url);
56
+ if (typeof embedded !== 'string')
57
+ fail('RESOURCE_NOT_PRELOADED', '<img> source was not preloaded');
58
+ return embedded;
59
+ }
60
+ function copySafeAttributes(source, target, budget, record) {
61
+ for (const attribute of source.attributes) {
62
+ const name = attribute.name.toLowerCase();
63
+ if (name === 'style' || name === 'id' || name === 'class' || name.startsWith('on'))
64
+ continue;
65
+ // The capture marks its own elements in the copy; a deck's attributes of
66
+ // that shape must never reach it, or it could steer what gets checked.
67
+ if (name.startsWith('data-cover-')) {
68
+ record.strippedMarks++;
69
+ continue;
70
+ }
71
+ if (DROPPED_ATTRIBUTES.includes(name))
72
+ continue;
73
+ if (name === 'src') {
74
+ if (!(source instanceof HTMLImageElement)) {
75
+ fail('UNSUPPORTED_RESOURCE', `<${source.tagName.toLowerCase()}> has src`);
76
+ }
77
+ target.setAttribute('src', embeddedImageSource(source, attribute.value, budget));
78
+ continue;
79
+ }
80
+ target.setAttribute(attribute.name, attribute.value);
81
+ }
82
+ if (source instanceof HTMLInputElement && ['checkbox', 'radio'].includes(source.type)) {
83
+ target.checked = source.checked;
84
+ if (source.checked)
85
+ target.setAttribute('checked', '');
86
+ else
87
+ target.removeAttribute('checked');
88
+ }
89
+ }
90
+ function canvasDataUrl(source, label, state) {
91
+ const tracked = contexts.get(source);
92
+ if (!tracked) {
93
+ fail('CANVAS_CONTEXT_UNKNOWN', `${label} context was created before capture installation or never requested`);
94
+ }
95
+ if (tracked.kind === 'unsupported')
96
+ fail('UNSUPPORTED_CANVAS_CONTEXT', `${label} uses ${tracked.requestedType}`);
97
+ if (tracked.kind === 'webgl') {
98
+ const frame = state.webglFrames.get(source);
99
+ if (!frame)
100
+ fail('WEBGL_CAPTURE_REQUIRED', `${label} needs an end-of-render capture`);
101
+ const gl = tracked.context;
102
+ if (!frame.valid)
103
+ fail('WEBGL_CAPTURE_STALE', `${label} was not captured synchronously in this turn`);
104
+ if (frame.width !== gl.drawingBufferWidth || frame.height !== gl.drawingBufferHeight) {
105
+ fail('WEBGL_CAPTURE_STALE', `${label} was resized after capture`);
106
+ }
107
+ return frame.dataUrl;
108
+ }
109
+ try {
110
+ return source.toDataURL('image/png');
111
+ }
112
+ catch (error) {
113
+ fail('CANVAS_READBACK_FAILED', `${label}: ${error instanceof Error ? error.message : ''}`);
114
+ }
115
+ }
116
+ function cloneCanvas(source, label, state) {
117
+ const image = document.createElement('img');
118
+ const dataUrl = canvasDataUrl(source, label, state);
119
+ image.src = dataUrl;
120
+ image.alt = '';
121
+ image.draggable = false;
122
+ copyComputedStyle(source, image, null, label, state);
123
+ recordBitmap(source, image, dataUrl, state.record);
124
+ state.record.clones.set(source, image);
125
+ return image;
126
+ }
127
+ function cloneChildren(source, label, state) {
128
+ const children = [];
129
+ let childIndex = 0;
130
+ for (const child of source.childNodes) {
131
+ if (child.nodeType === Node.TEXT_NODE) {
132
+ children.push(document.createTextNode(child.textContent ?? ''));
133
+ }
134
+ else if (child instanceof Element) {
135
+ childIndex++;
136
+ if (getComputedStyle(child).display === 'none')
137
+ continue;
138
+ children.push(cloneElement(child, `${label} > ${child.tagName.toLowerCase()}:nth-child(${childIndex})`, state));
139
+ }
140
+ else if (child.nodeType !== Node.COMMENT_NODE) {
141
+ fail('UNSUPPORTED_NODE', `${label} contains node type ${child.nodeType}`);
142
+ }
143
+ }
144
+ return children;
145
+ }
146
+ // Whether the page gives this element's scrollbars room: classic scrollbars do,
147
+ // overlay scrollbars (macOS by default) and headless browsers' hidden ones do
148
+ // not. The copy then draws them, or not, to match.
149
+ function isScrollContainer(target) {
150
+ const scrolls = (value) => value === 'auto' || value === 'scroll';
151
+ return scrolls(target.style.overflowX) || scrolls(target.style.overflowY);
152
+ }
153
+ // Scrolling is baked into a clipped, translated wrapper: the copy has no
154
+ // scroll position of its own to restore, and draws no scrollbars (a box whose
155
+ // scrollbars the page gives room is refused, validate.ts). The wrapper is the
156
+ // content box's width, so text wraps as it does on the page, and it starts
157
+ // where the page's content does -- below the top padding, which scrolls with it.
158
+ function appendScrolled(source, target, children) {
159
+ if (isScrollContainer(target))
160
+ target.style.setProperty('scrollbar-width', 'none', 'important');
161
+ if (!source.scrollLeft && !source.scrollTop) {
162
+ target.append(...children);
163
+ return;
164
+ }
165
+ const style = getComputedStyle(source);
166
+ const px = (value) => Number.parseFloat(value) || 0;
167
+ const contentWidth = source.clientWidth - px(style.paddingLeft) - px(style.paddingRight);
168
+ const contentHeight = source.scrollHeight - px(style.paddingTop) - px(style.paddingBottom);
169
+ const scroller = document.createElement('div');
170
+ scroller.style.cssText = [
171
+ 'position:relative',
172
+ `width:${Math.max(0, contentWidth)}px`,
173
+ `min-height:${Math.max(0, contentHeight)}px`,
174
+ `transform:translate(${-source.scrollLeft}px,${-source.scrollTop}px)`,
175
+ 'transform-origin:top left',
176
+ ].join(';');
177
+ scroller.append(...children);
178
+ target.style.setProperty('overflow', 'hidden', 'important');
179
+ target.append(scroller);
180
+ }
181
+ function cloneElement(source, label, state) {
182
+ if (++state.nodes > MAX_NODES)
183
+ fail('PACKAGE_TOO_COMPLEX', `more than ${MAX_NODES} elements`);
184
+ validateElement(source, label);
185
+ if (source instanceof HTMLCanvasElement)
186
+ return cloneCanvas(source, label, state);
187
+ const target = source.namespaceURI === SVG_NAMESPACE
188
+ ? document.createElementNS(SVG_NAMESPACE, source.localName)
189
+ : // <body> as the root is copied as a plain block: every property is
190
+ // inlined from its computed style, and a nested <body> is not a thing
191
+ // the rasterizer's document should have to interpret.
192
+ document.createElement(source === document.body ? 'div' : source.tagName.toLowerCase());
193
+ state.record.clones.set(source, target);
194
+ copySafeAttributes(source, target, state.budget, state.record);
195
+ copyComputedStyle(source, target, null, label, state);
196
+ const src = target.getAttribute('src');
197
+ if (source instanceof HTMLImageElement && src)
198
+ recordBitmap(source, target, src, state.record);
199
+ const html = source.namespaceURI === HTML_NAMESPACE;
200
+ if (html)
201
+ appendPseudo(source, target, '::before', label, state);
202
+ appendScrolled(source, target, cloneChildren(source, label, state));
203
+ if (html)
204
+ appendPseudo(source, target, '::after', label, state);
205
+ return target;
206
+ }
207
+ function rootScale(source) {
208
+ const value = getComputedStyle(source).transform;
209
+ if (value === 'none')
210
+ return null;
211
+ let matrix;
212
+ try {
213
+ matrix = new DOMMatrixReadOnly(value);
214
+ }
215
+ catch {
216
+ fail('UNSUPPORTED_ROOT_TRANSFORM', `cannot parse root transform ${value}`);
217
+ }
218
+ const epsilon = 1e-8;
219
+ if (!matrix.is2D ||
220
+ Math.abs(matrix.b) > epsilon ||
221
+ Math.abs(matrix.c) > epsilon ||
222
+ matrix.a <= 0 ||
223
+ matrix.d <= 0) {
224
+ fail('UNSUPPORTED_ROOT_TRANSFORM', 'only positive axis-aligned root scale/translation is supported');
225
+ }
226
+ return { scaleX: matrix.a, scaleY: matrix.d };
227
+ }
228
+ // A positioned/translated root is normalized into a cropped wrapper at the
229
+ // origin, so the copy's box is exactly the card's on-screen box.
230
+ function wrapTransformedRoot(clone, rect, scale, marker) {
231
+ for (const [property, value] of [
232
+ ['position', 'absolute'],
233
+ ['inset', 'auto'],
234
+ ['left', '0'],
235
+ ['top', '0'],
236
+ ['right', 'auto'],
237
+ ['bottom', 'auto'],
238
+ ['margin', '0'],
239
+ ['transform-origin', 'top left'],
240
+ ['transform', `scale(${scale.scaleX},${scale.scaleY})`],
241
+ ]) {
242
+ clone.style.setProperty(property, value, 'important');
243
+ }
244
+ const wrapper = document.createElement('div');
245
+ wrapper.setAttribute(`${marker}-root-wrapper`, '');
246
+ wrapper.style.cssText = `position:relative;width:${rect.width}px;height:${rect.height}px;overflow:hidden`;
247
+ wrapper.append(clone);
248
+ return wrapper;
249
+ }
250
+ /** Copies `source` into an inert packet. Synchronous by contract. */
251
+ export function serializeCard(source, budget, fontCss, fontFamilies, webglFrames) {
252
+ const scale = rootScale(source);
253
+ const rect = source.getBoundingClientRect();
254
+ if (!(rect.width > 0 && rect.height > 0))
255
+ fail('EMPTY_TARGET', 'target has no visible bounds');
256
+ const record = {
257
+ originX: rect.left,
258
+ originY: rect.top,
259
+ scaleX: scale?.scaleX ?? 1,
260
+ scaleY: scale?.scaleY ?? 1,
261
+ root: source,
262
+ bitmaps: [],
263
+ unverified: 0,
264
+ clones: new Map(),
265
+ marker: newMarker(),
266
+ strippedMarks: 0,
267
+ };
268
+ let clone = cloneElement(source, source.tagName.toLowerCase(), {
269
+ nodes: 0,
270
+ budget,
271
+ webglFrames,
272
+ record,
273
+ });
274
+ // The card is positioned in the live page (centered, or offset by its
275
+ // parent); the copy starts at the origin of its own box.
276
+ if (scale)
277
+ clone = wrapTransformedRoot(clone, rect, scale, record.marker);
278
+ else
279
+ pinRootToOrigin(clone);
280
+ // Before the HTML is taken: it tags the clipping boxes in the copy.
281
+ const effectClips = collectEffectClips(source, record);
282
+ const html = clone.outerHTML;
283
+ const byteLength = new TextEncoder().encode(html + fontCss).byteLength;
284
+ if (byteLength > MAX_PACKAGE_BYTES)
285
+ fail('PACKAGE_TOO_LARGE', `${byteLength} bytes exceeds ${MAX_PACKAGE_BYTES}`);
286
+ return {
287
+ version: PACKET_VERSION,
288
+ width: Math.ceil(rect.width),
289
+ height: Math.ceil(rect.height),
290
+ backdropColor: getComputedStyle(document.body).backgroundColor,
291
+ html,
292
+ fontCss,
293
+ byteLength,
294
+ bitmaps: record.bitmaps,
295
+ unverifiedBitmaps: record.unverified,
296
+ textSamples: collectTextSamples(source, fontFamilies),
297
+ effects: collectEffects(source),
298
+ webkitEffects: collectWebKitRefusedEffects(source),
299
+ effectClips,
300
+ marker: record.marker,
301
+ strippedMarks: record.strippedMarks,
302
+ };
303
+ }
304
+ function newMarker() {
305
+ const bytes = new Uint8Array(6);
306
+ natives.getRandomValues(bytes);
307
+ return `data-cover-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
308
+ }
309
+ function pinRootToOrigin(clone) {
310
+ const position = clone.style.getPropertyValue('position');
311
+ if (position === 'fixed' || position === 'absolute' || position === 'sticky') {
312
+ clone.style.setProperty('position', 'relative', 'important');
313
+ }
314
+ for (const side of ['left', 'top', 'right', 'bottom'])
315
+ clone.style.setProperty(side, 'auto', 'important');
316
+ clone.style.setProperty('margin', '0', 'important');
317
+ }
@@ -0,0 +1,37 @@
1
+ export interface EngineHints {
2
+ userAgent: string;
3
+ platform?: string;
4
+ maxTouchPoints?: number;
5
+ /** navigator.vendor: "Apple Computer, Inc." in WebKit, "Google Inc." in Chromium. */
6
+ vendor?: string;
7
+ }
8
+ export declare function isWebKitEngine(hints: EngineHints): boolean;
9
+ declare global {
10
+ interface Window {
11
+ /** Test seam: treat this page as WebKit (a deck can only refuse itself with it). */
12
+ __castleCoverAssumeWebKit?: boolean;
13
+ }
14
+ }
15
+ /**
16
+ * v1 refuses every capture in WebKit, before anything is frozen or fetched:
17
+ * Safari kept finding ways to draw a wrong cover that no check made from its
18
+ * own drawing could see (the hard HUD shadow; data: images painted late). The
19
+ * WebKit code paths stay -- the effect rule, the unverifiable-bitmap rule, the
20
+ * check strip's data: sentinels -- for a diagnostic build to exercise, so
21
+ * Safari can be re-enabled with evidence.
22
+ *
23
+ * TODO(safari re-enable): before turning this off, the sentinel should use a
24
+ * fresh image per draw (a cached 2x2 can be painted while a card's own
25
+ * background images are not), and the redraw loop must not stop early on
26
+ * identical failures before the halfway re-decode has been tried, since
27
+ * WebKit's late paint can repeat identically.
28
+ */
29
+ export declare function refuseWebKitCapture(): void;
30
+ /** Whether the current page should follow the WebKit rules. */
31
+ export declare function runningInWebKit(): boolean;
32
+ /**
33
+ * WebKit's rule, applied twice: here before anything is frozen, and again on
34
+ * the card as captured (rasterize.ts) -- an effect the deck adds in the very
35
+ * frame being captured (a hover, a pulse, a glow) must be refused too.
36
+ */
37
+ export declare function refuseWebKitEffects(effects: string[]): void;
@@ -0,0 +1,76 @@
1
+ // Which rendering engine is drawing the cover. Used for one rule only: WebKit
2
+ // is refused any card with a shadow or blur (EFFECT_NOT_REPRODUCIBLE), because
3
+ // Safari 18.6 was seen to draw a translucent HUD's box-shadow as a hard,
4
+ // shifted rectangle that passed every check the capture could make -- the
5
+ // same wrong drawing whether clipped or not, and away from any edge. See
6
+ // .claude/skills/screenshots/SKILL.md for the evidence.
7
+ //
8
+ // Every browser on iOS and iPadOS is WebKit whatever it calls itself (Chrome
9
+ // there is CriOS, Firefox FxiOS, Edge EdgiOS), and so is the Castle app's
10
+ // WKWebView. Elsewhere, AppleWebKit without a Chromium token is Safari or
11
+ // another WebKit browser; Chromium browsers (Chrome, Edge, Opera, Samsung
12
+ // Internet, Android WebView) all carry "Chrome/" or "Chromium/", and Firefox
13
+ // carries no AppleWebKit at all.
14
+ import { fail } from './errors.js';
15
+ const IOS_DEVICE = /\((?:iPhone|iPad|iPod)[;)]/;
16
+ const IOS_BROWSER = /\b(?:CriOS|FxiOS|EdgiOS|OPiOS|GSA)\//;
17
+ const CHROMIUM = /\b(?:Chrome|Chromium|HeadlessChrome)\//;
18
+ export function isWebKitEngine(hints) {
19
+ const ua = hints.userAgent;
20
+ if (IOS_DEVICE.test(ua) || IOS_BROWSER.test(ua))
21
+ return true;
22
+ // iPadOS asks for desktop sites as a Mac; only an iPad has a touch screen.
23
+ if (hints.platform === 'MacIntel' && (hints.maxTouchPoints ?? 0) > 1)
24
+ return true;
25
+ if (CHROMIUM.test(ua))
26
+ return false;
27
+ // A WebKit browser whose user agent was changed or trimmed still reports
28
+ // Apple as its vendor.
29
+ return /AppleWebKit\//.test(ua) || hints.vendor === 'Apple Computer, Inc.';
30
+ }
31
+ /**
32
+ * v1 refuses every capture in WebKit, before anything is frozen or fetched:
33
+ * Safari kept finding ways to draw a wrong cover that no check made from its
34
+ * own drawing could see (the hard HUD shadow; data: images painted late). The
35
+ * WebKit code paths stay -- the effect rule, the unverifiable-bitmap rule, the
36
+ * check strip's data: sentinels -- for a diagnostic build to exercise, so
37
+ * Safari can be re-enabled with evidence.
38
+ *
39
+ * TODO(safari re-enable): before turning this off, the sentinel should use a
40
+ * fresh image per draw (a cached 2x2 can be painted while a card's own
41
+ * background images are not), and the redraw loop must not stop early on
42
+ * identical failures before the halfway re-decode has been tried, since
43
+ * WebKit's late paint can repeat identically.
44
+ */
45
+ export function refuseWebKitCapture() {
46
+ const allowed = typeof __COVER_ALLOW_WEBKIT__ === 'boolean' && __COVER_ALLOW_WEBKIT__;
47
+ if (runningInWebKit() && !allowed)
48
+ fail('BROWSER_UNSUPPORTED', 'webkit: covers are not made in WebKit yet');
49
+ }
50
+ // Read once, when this module loads: in the deck frame that is the bridge's
51
+ // first line, before any deck code runs, so a deck that later redefines
52
+ // navigator.userAgent (to pass for Chrome inside Safari) changes nothing. The
53
+ // shell, which the deck cannot reach, makes the same check on its own page.
54
+ const LOADED_HINTS = typeof navigator === 'undefined'
55
+ ? null
56
+ : {
57
+ userAgent: navigator.userAgent,
58
+ platform: navigator.platform,
59
+ maxTouchPoints: navigator.maxTouchPoints,
60
+ vendor: navigator.vendor,
61
+ };
62
+ /** Whether the current page should follow the WebKit rules. */
63
+ export function runningInWebKit() {
64
+ if (typeof window !== 'undefined' && window.__castleCoverAssumeWebKit === true)
65
+ return true;
66
+ return LOADED_HINTS !== null && isWebKitEngine(LOADED_HINTS);
67
+ }
68
+ /**
69
+ * WebKit's rule, applied twice: here before anything is frozen, and again on
70
+ * the card as captured (rasterize.ts) -- an effect the deck adds in the very
71
+ * frame being captured (a hover, a pulse, a glow) must be refused too.
72
+ */
73
+ export function refuseWebKitEffects(effects) {
74
+ if (effects.length)
75
+ fail('EFFECT_NOT_REPRODUCIBLE', `webkit: the card uses ${effects.join(', ')}`);
76
+ }
@@ -0,0 +1,6 @@
1
+ export declare class CoverCaptureError extends Error {
2
+ readonly code: string;
3
+ constructor(code: string, message: string);
4
+ }
5
+ export declare function fail(code: string, message: string): never;
6
+ export declare function errorCode(error: unknown): string;
@@ -0,0 +1,18 @@
1
+ // Every way a Play cover capture refuses is one of these, carrying a stable
2
+ // code (see protocol.ts for what a creator is told about each). The capture is
3
+ // fail-closed by design: an unsupported case rejects with its code rather than
4
+ // producing a less faithful picture.
5
+ export class CoverCaptureError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(`${code}: ${message}`);
9
+ this.name = 'CoverCaptureError';
10
+ this.code = code;
11
+ }
12
+ }
13
+ export function fail(code, message) {
14
+ throw new CoverCaptureError(code, message);
15
+ }
16
+ export function errorCode(error) {
17
+ return error instanceof CoverCaptureError ? error.code : 'CAPTURE_FAILED';
18
+ }
@@ -0,0 +1,21 @@
1
+ /** Whether a record of reported URLs (CSP, resource timing) names this one. */
2
+ export declare function recordNames(record: Record<string, true>, rawUrl: string, base: string): boolean;
3
+ export declare function refuseBlockedImage(url: string, label: string): void;
4
+ /** A CSS image URL the page has not finished loading refuses. */
5
+ export declare function refuseUnloadedCssImage(url: string, label: string): void;
6
+ /** An <img> that has not finished loading (or failed) refuses. */
7
+ export declare function refuseUnloadedImg(image: HTMLImageElement, label: string): void;
8
+ /**
9
+ * The data: URL to embed for a fetched image, tied to what the page shows.
10
+ * `pageImage` is the page's own <img> when there is one; for a CSS image a
11
+ * fresh Image of the same URL stands in for it.
12
+ */
13
+ /** Only PNG and JPEG bytes, and no animated PNG (the page shows its frames, the cover one). */
14
+ export declare function checkImageBytes(bytes: Uint8Array, mime: string, url: string): void;
15
+ export declare function pageTiedImage(url: string, fetched: {
16
+ bytes: Uint8Array;
17
+ mime: string;
18
+ dataUrl: string;
19
+ /** The response may not be reused (no-store, no-cache, max-age=0). */
20
+ uncacheable: boolean;
21
+ }, pageImage: HTMLImageElement | null): Promise<string>;