castle-web-cli 0.4.211 → 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 (49) hide show
  1. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  2. package/dist/externalSourcemaps.d.ts +29 -0
  3. package/dist/externalSourcemaps.js +163 -0
  4. package/dist/fontFaceImports.d.ts +7 -0
  5. package/dist/fontFaceImports.js +129 -0
  6. package/dist/ide.js +7 -2
  7. package/dist/playCover/bridge.d.ts +6 -0
  8. package/dist/playCover/bridge.js +159 -0
  9. package/dist/playCover/builtins.d.ts +29 -0
  10. package/dist/playCover/builtins.js +189 -0
  11. package/dist/playCover/capture.d.ts +53 -0
  12. package/dist/playCover/capture.js +419 -0
  13. package/dist/playCover/clone.d.ts +40 -0
  14. package/dist/playCover/clone.js +317 -0
  15. package/dist/playCover/engine.d.ts +37 -0
  16. package/dist/playCover/engine.js +76 -0
  17. package/dist/playCover/errors.d.ts +6 -0
  18. package/dist/playCover/errors.js +18 -0
  19. package/dist/playCover/images.d.ts +21 -0
  20. package/dist/playCover/images.js +180 -0
  21. package/dist/playCover/instrument.d.ts +49 -0
  22. package/dist/playCover/instrument.js +334 -0
  23. package/dist/playCover/protocol.d.ts +14 -0
  24. package/dist/playCover/protocol.js +139 -0
  25. package/dist/playCover/rasterize.d.ts +21 -0
  26. package/dist/playCover/rasterize.js +408 -0
  27. package/dist/playCover/resources.d.ts +31 -0
  28. package/dist/playCover/resources.js +823 -0
  29. package/dist/playCover/scratchCanvas.d.ts +4 -0
  30. package/dist/playCover/scratchCanvas.js +16 -0
  31. package/dist/playCover/textSamples.d.ts +36 -0
  32. package/dist/playCover/textSamples.js +412 -0
  33. package/dist/playCover/validate.d.ts +79 -0
  34. package/dist/playCover/validate.js +883 -0
  35. package/dist/playCover/verify.d.ts +56 -0
  36. package/dist/playCover/verify.js +578 -0
  37. package/dist/playCover/verifyRecord.d.ts +71 -0
  38. package/dist/playCover/verifyRecord.js +243 -0
  39. package/dist/playCoverGate.d.ts +4 -0
  40. package/dist/playCoverGate.js +57 -0
  41. package/dist/playCoverPlacement.d.ts +11 -0
  42. package/dist/playCoverPlacement.js +110 -0
  43. package/dist/serve.d.ts +1 -0
  44. package/dist/serve.js +42 -17
  45. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  46. package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
  47. package/dist/shell/index.html +2 -2
  48. package/package.json +2 -2
  49. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,49 @@
1
+ export type ContextKind = '2d' | 'webgl' | 'unsupported';
2
+ export interface TrackedContext {
3
+ kind: ContextKind;
4
+ context: RenderingContext;
5
+ requestedType: string;
6
+ }
7
+ export interface TrackedFont {
8
+ family: string;
9
+ source: unknown;
10
+ descriptors: Record<string, unknown>;
11
+ /** The document's base URL when the face was made: what its URLs resolve against. */
12
+ baseUrl: string;
13
+ }
14
+ export declare const contexts: WeakMap<HTMLCanvasElement, TrackedContext>;
15
+ export declare const canvasRevisions: WeakMap<HTMLCanvasElement, number>;
16
+ export interface CanvasWrite {
17
+ batch: number;
18
+ width: number;
19
+ height: number;
20
+ }
21
+ export declare const canvasWriteBatch: WeakMap<HTMLCanvasElement, CanvasWrite>;
22
+ export declare const trackedFontFaces: WeakMap<FontFace, TrackedFont>;
23
+ export declare const blockedFontUrls: Record<string, true>;
24
+ export declare const blockedImageUrls: Record<string, true>;
25
+ export declare const loadedResources: Record<string, true>;
26
+ export declare const natives: {
27
+ getContext: {
28
+ (contextId: "2d", options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D | null;
29
+ (contextId: "bitmaprenderer", options?: ImageBitmapRenderingContextSettings): ImageBitmapRenderingContext | null;
30
+ (contextId: "webgl", options?: WebGLContextAttributes): WebGLRenderingContext | null;
31
+ (contextId: "webgl2", options?: WebGLContextAttributes): WebGL2RenderingContext | null;
32
+ (contextId: string, options?: any): RenderingContext | null;
33
+ };
34
+ requestAnimationFrame: ((callback: FrameRequestCallback) => number) & typeof requestAnimationFrame;
35
+ cancelAnimationFrame: ((handle: number) => void) & typeof cancelAnimationFrame;
36
+ getRandomValues: <T extends ArrayBufferView>(array: T) => T;
37
+ toBlob: (callback: BlobCallback, type?: string, quality?: number) => void;
38
+ };
39
+ export declare function setWriteTracking(on: boolean): void;
40
+ /** The id of the RAF batch running now, or of the last one that ran. */
41
+ export declare function currentBatchId(): number;
42
+ /** Whether the deck has any animation callback waiting for a frame. */
43
+ export declare function hasScheduledAnimationFrame(): boolean;
44
+ /** Called once every callback scheduled for a frame has run. */
45
+ export declare function setBatchEndListener(listener: (() => void) | null): void;
46
+ export declare function freezeAnimationFrames(): void;
47
+ export declare function resumeAnimationFrames(): void;
48
+ /** Installs every hook, once. Must run before any deck code. */
49
+ export declare function installInstrumentation(): void;
@@ -0,0 +1,334 @@
1
+ // The part of the Play cover capture that has to run BEFORE the deck's own
2
+ // code: it classifies every canvas context the deck creates, counts writes to
3
+ // visible canvases, remembers dynamic FontFace sources, and puts a cooperative
4
+ // hold on requestAnimationFrame. None of that can be reconstructed after the
5
+ // fact -- a context created before these hooks is one the capture cannot
6
+ // vouch for, and says so (CANVAS_CONTEXT_UNKNOWN) rather than guessing.
7
+ //
8
+ // Adapted from the reviewed visual-snapshot prototype
9
+ // (castle-sandboxes `scripts/visual-snapshot-prototype/serializer.js`, see its
10
+ // README and `docs/browser-capture-context.md`). One deliberate change: the
11
+ // prototype captured right after the FIRST animation callback following arming;
12
+ // this captures at the end of the whole callback batch for that frame
13
+ // (`onBatchEnd`), because a deck with more than one RAF loop (a physics step
14
+ // and a renderer, say) would otherwise be read between them -- and a WebGL
15
+ // canvas with preserveDrawingBuffer:false read before its renderer ran is an
16
+ // empty buffer.
17
+ import { newRecord, parseReportedUrl, violationFields } from './builtins.js';
18
+ export const contexts = new WeakMap();
19
+ export const canvasRevisions = new WeakMap();
20
+ export const canvasWriteBatch = new WeakMap();
21
+ // WebGL extension objects draw into their context's canvas but carry no
22
+ // `canvas` of their own; getExtension records which one each belongs to.
23
+ const extensionCanvas = new WeakMap();
24
+ export const trackedFontFaces = new WeakMap();
25
+ // Font URLs the page's CSP font-src refused to load. The cover's own fetch is
26
+ // governed by connect-src, and its SVG image by no page CSP at all, so without
27
+ // this a source the page could not use would be embedded and drawn.
28
+ // A null-prototype record (builtins.ts): no Set method a deck could replace.
29
+ export const blockedFontUrls = newRecord();
30
+ // The same for img-src: an image the page could not show is never embedded.
31
+ export const blockedImageUrls = newRecord();
32
+ // Every resource the page has finished loading (resource timing, observed
33
+ // from load with no buffer limit), fragment and credentials removed: a CSS
34
+ // image not named here is one the page may not be showing yet.
35
+ export const loadedResources = newRecord();
36
+ export const natives = {
37
+ // Always invoked through Reflect.apply with the canvas as `this`.
38
+ // eslint-disable-next-line @typescript-eslint/unbound-method
39
+ getContext: HTMLCanvasElement.prototype.getContext,
40
+ requestAnimationFrame: window.requestAnimationFrame.bind(window),
41
+ cancelAnimationFrame: window.cancelAnimationFrame.bind(window),
42
+ // For the copy's per-capture mark prefix: taken before deck code can replace it.
43
+ getRandomValues: crypto.getRandomValues.bind(crypto),
44
+ // The final PNG: taken here rather than watched, since zone.js's canvas
45
+ // patch replaces the slot. Always invoked through Reflect.apply.
46
+ // eslint-disable-next-line @typescript-eslint/unbound-method
47
+ toBlob: HTMLCanvasElement.prototype.toBlob,
48
+ };
49
+ let installed = false;
50
+ let rafFrozen = false;
51
+ let nextRafId = 1;
52
+ const rafEntries = new Map();
53
+ let batchTimestamp = null;
54
+ let batchId = 0;
55
+ let batchMembers = new Set();
56
+ let batchEndListener = null;
57
+ // Canvas writes are only counted while a capture holds a session: the
58
+ // wrappers stay installed (a deck may keep references to the methods), but
59
+ // outside a capture each one costs a flag check and nothing else.
60
+ let writeTracking = false;
61
+ export function setWriteTracking(on) {
62
+ writeTracking = on;
63
+ }
64
+ /** The id of the RAF batch running now, or of the last one that ran. */
65
+ export function currentBatchId() {
66
+ return batchId;
67
+ }
68
+ /** Whether the deck has any animation callback waiting for a frame. */
69
+ export function hasScheduledAnimationFrame() {
70
+ return rafEntries.size > 0;
71
+ }
72
+ /** Called once every callback scheduled for a frame has run. */
73
+ export function setBatchEndListener(listener) {
74
+ batchEndListener = listener;
75
+ }
76
+ export function freezeAnimationFrames() {
77
+ rafFrozen = true;
78
+ }
79
+ export function resumeAnimationFrames() {
80
+ rafFrozen = false;
81
+ for (const entry of rafEntries.values()) {
82
+ if (entry.pending) {
83
+ entry.pending = false;
84
+ scheduleRafEntry(entry);
85
+ }
86
+ }
87
+ }
88
+ function markCanvasWrite(canvas) {
89
+ if (!(canvas instanceof HTMLCanvasElement))
90
+ return;
91
+ canvasRevisions.set(canvas, (canvasRevisions.get(canvas) ?? 0) + 1);
92
+ canvasWriteBatch.set(canvas, { batch: batchId, width: canvas.width, height: canvas.height });
93
+ }
94
+ const contextCanvas = (self) => self.canvas;
95
+ const extensionOwner = (self) => extensionCanvas.get(self);
96
+ function trackDrawingMethods(prototype, methods, canvasOf = contextCanvas) {
97
+ if (!prototype)
98
+ return;
99
+ const target = prototype;
100
+ for (const name of methods) {
101
+ const original = target[name];
102
+ if (typeof original !== 'function')
103
+ continue;
104
+ target[name] = function trackedDrawingMethod() {
105
+ // `arguments`, not a rest parameter: this runs on every draw call a deck
106
+ // makes, and it should not allocate an array to do it.
107
+ // eslint-disable-next-line prefer-rest-params
108
+ const result = Reflect.apply(original, this, arguments);
109
+ if (writeTracking)
110
+ markCanvasWrite(canvasOf(this));
111
+ return result;
112
+ };
113
+ }
114
+ }
115
+ // Draw calls that live on extensions rather than the context: instancing for
116
+ // WebGL 1, and the multi-draw / base-instance families.
117
+ const EXTENSION_DRAW_METHODS = [
118
+ 'drawArraysInstancedANGLE',
119
+ 'drawElementsInstancedANGLE',
120
+ 'multiDrawArraysWEBGL',
121
+ 'multiDrawElementsWEBGL',
122
+ 'multiDrawArraysInstancedWEBGL',
123
+ 'multiDrawElementsInstancedWEBGL',
124
+ 'drawArraysInstancedBaseInstanceWEBGL',
125
+ 'drawElementsInstancedBaseVertexBaseInstanceWEBGL',
126
+ 'multiDrawArraysInstancedBaseInstanceWEBGL',
127
+ 'multiDrawElementsInstancedBaseVertexBaseInstanceWEBGL',
128
+ ];
129
+ const trackedExtensionPrototypes = new WeakSet();
130
+ function trackExtension(extension, canvas) {
131
+ if (!extension || typeof extension !== 'object' || !(canvas instanceof HTMLCanvasElement))
132
+ return;
133
+ extensionCanvas.set(extension, canvas);
134
+ const prototype = Object.getPrototypeOf(extension);
135
+ if (!prototype || trackedExtensionPrototypes.has(prototype))
136
+ return;
137
+ trackedExtensionPrototypes.add(prototype);
138
+ trackDrawingMethods(prototype, EXTENSION_DRAW_METHODS, extensionOwner);
139
+ }
140
+ function trackGetExtension(prototype) {
141
+ if (!prototype || !Object.prototype.hasOwnProperty.call(prototype, 'getExtension'))
142
+ return;
143
+ const target = prototype;
144
+ const original = target.getExtension;
145
+ if (typeof original !== 'function')
146
+ return;
147
+ target.getExtension = function trackedGetExtension(name) {
148
+ const extension = Reflect.apply(original, this, [name]);
149
+ trackExtension(extension, this.canvas);
150
+ return extension;
151
+ };
152
+ }
153
+ function contextKind(requestedType) {
154
+ if (requestedType === '2d')
155
+ return '2d';
156
+ return ['webgl', 'experimental-webgl', 'webgl2'].includes(requestedType)
157
+ ? 'webgl'
158
+ : 'unsupported';
159
+ }
160
+ function installCanvasTracking() {
161
+ const getContext = natives.getContext;
162
+ const patched = function patchedGetContext(type, ...args) {
163
+ const context = Reflect.apply(getContext, this, [type, ...args]);
164
+ if (context) {
165
+ const requestedType = String(type).toLowerCase();
166
+ contexts.set(this, { kind: contextKind(requestedType), context, requestedType });
167
+ }
168
+ return context;
169
+ };
170
+ HTMLCanvasElement.prototype.getContext = patched;
171
+ trackDrawingMethods(window.CanvasRenderingContext2D?.prototype, [
172
+ 'clearRect',
173
+ 'drawImage',
174
+ 'fill',
175
+ 'fillRect',
176
+ 'fillText',
177
+ 'putImageData',
178
+ 'stroke',
179
+ 'strokeRect',
180
+ 'strokeText',
181
+ ]);
182
+ const webglDrawingMethods = [
183
+ 'blitFramebuffer',
184
+ 'clear',
185
+ 'clearBufferfi',
186
+ 'clearBufferfv',
187
+ 'clearBufferiv',
188
+ 'clearBufferuiv',
189
+ 'drawArrays',
190
+ 'drawArraysInstanced',
191
+ 'drawElements',
192
+ 'drawElementsInstanced',
193
+ 'drawRangeElements',
194
+ ];
195
+ trackDrawingMethods(window.WebGLRenderingContext?.prototype, webglDrawingMethods);
196
+ trackDrawingMethods(window.WebGL2RenderingContext?.prototype, webglDrawingMethods);
197
+ trackGetExtension(window.WebGLRenderingContext?.prototype);
198
+ trackGetExtension(window.WebGL2RenderingContext?.prototype);
199
+ }
200
+ // A dynamic data/BufferSource FontFace is embeddable only because the capture
201
+ // saw its constructor. An unobserved custom DOM font stays an honest rejection.
202
+ // A Proxy with a construct trap, so the constructor keeps its name, still
203
+ // throws when called without `new`, and can still be subclassed.
204
+ function installFontFaceTracking() {
205
+ if (typeof window.FontFace !== 'function')
206
+ return;
207
+ window.FontFace = new Proxy(window.FontFace, {
208
+ construct(target, args, newTarget) {
209
+ const face = Reflect.construct(target, args, newTarget);
210
+ const [family, source, descriptors] = args;
211
+ trackedFontFaces.set(face, {
212
+ family: String(family),
213
+ source,
214
+ descriptors: { ...(descriptors ?? {}) },
215
+ baseUrl: document.baseURI,
216
+ });
217
+ return face;
218
+ },
219
+ });
220
+ }
221
+ function startBatch(timestamp) {
222
+ batchTimestamp = timestamp;
223
+ batchId++;
224
+ // Everything already handed to the browser runs in this frame; anything
225
+ // requested from here on runs in the next one.
226
+ batchMembers = new Set();
227
+ for (const entry of rafEntries.values())
228
+ if (entry.nativeId !== null)
229
+ batchMembers.add(entry.id);
230
+ }
231
+ function batchRemaining() {
232
+ let remaining = 0;
233
+ for (const id of batchMembers)
234
+ if (typeof rafEntries.get(id)?.nativeId === 'number')
235
+ remaining++;
236
+ return remaining;
237
+ }
238
+ function runRafEntry(entry, timestamp) {
239
+ if (!rafEntries.has(entry.id))
240
+ return;
241
+ if (timestamp !== batchTimestamp)
242
+ startBatch(timestamp);
243
+ entry.nativeId = null;
244
+ batchMembers.delete(entry.id);
245
+ if (rafFrozen) {
246
+ entry.pending = true;
247
+ return;
248
+ }
249
+ rafEntries.delete(entry.id);
250
+ try {
251
+ entry.callback(timestamp);
252
+ }
253
+ finally {
254
+ if (batchRemaining() === 0)
255
+ batchEndListener?.();
256
+ }
257
+ }
258
+ function scheduleRafEntry(entry) {
259
+ entry.nativeId = natives.requestAnimationFrame((timestamp) => runRafEntry(entry, timestamp));
260
+ }
261
+ // Cooperative RAF hold: callbacks requested while frozen are kept and handed
262
+ // to the browser on resume, so a live deck never stays paused.
263
+ function installRafHold() {
264
+ window.requestAnimationFrame = (callback) => {
265
+ if (typeof callback !== 'function') {
266
+ throw new TypeError('requestAnimationFrame callback must be a function');
267
+ }
268
+ const entry = { id: nextRafId++, callback, nativeId: null, pending: false };
269
+ rafEntries.set(entry.id, entry);
270
+ if (rafFrozen)
271
+ entry.pending = true;
272
+ else
273
+ scheduleRafEntry(entry);
274
+ return entry.id;
275
+ };
276
+ window.cancelAnimationFrame = (id) => {
277
+ const entry = rafEntries.get(id);
278
+ if (!entry)
279
+ return;
280
+ rafEntries.delete(id);
281
+ if (entry.nativeId !== null)
282
+ natives.cancelAnimationFrame(entry.nativeId);
283
+ };
284
+ }
285
+ /** Installs every hook, once. Must run before any deck code. */
286
+ export function installInstrumentation() {
287
+ if (installed)
288
+ return;
289
+ installed = true;
290
+ installCanvasTracking();
291
+ installFontFaceTracking();
292
+ installRafHold();
293
+ installCspTracking();
294
+ installResourceTracking();
295
+ }
296
+ function installResourceTracking() {
297
+ if (typeof PerformanceObserver !== 'function')
298
+ return;
299
+ const observer = new PerformanceObserver((list) => {
300
+ for (const entry of list.getEntries()) {
301
+ if (!(entry instanceof PerformanceResourceTiming) || entry.responseEnd <= 0)
302
+ continue;
303
+ const url = parseReportedUrl(entry.name, document.baseURI);
304
+ if (!url)
305
+ continue;
306
+ loadedResources[url.reported] = true;
307
+ }
308
+ });
309
+ try {
310
+ observer.observe({ type: 'resource', buffered: true });
311
+ }
312
+ catch {
313
+ // No resource timing here: every CSS image then refuses as not loaded.
314
+ }
315
+ }
316
+ // Registered on window in the capture phase before any deck script runs, so
317
+ // it hears every violation first; a deck cannot hide one by stopping it.
318
+ function installCspTracking() {
319
+ window.addEventListener('securitypolicyviolation', (event) => {
320
+ if (!event.isTrusted)
321
+ return;
322
+ // Through the getters taken at load, so a deck cannot relabel one.
323
+ const fields = violationFields(event);
324
+ // A report-only policy blocks nothing: the page did load that source.
325
+ if (!fields || fields.disposition !== 'enforce')
326
+ return;
327
+ if (typeof fields.blockedURI !== 'string' || !fields.blockedURI)
328
+ return;
329
+ if (fields.effectiveDirective === 'font-src')
330
+ blockedFontUrls[fields.blockedURI] = true;
331
+ if (fields.effectiveDirective === 'img-src')
332
+ blockedImageUrls[fields.blockedURI] = true;
333
+ }, true);
334
+ }
@@ -0,0 +1,14 @@
1
+ export declare const PLAY_COVER_CAPTURE = "castle-play-cover-capture";
2
+ export declare const PLAY_COVER_CANCEL = "castle-play-cover-cancel";
3
+ export declare const PLAY_COVER_RESULT = "castle-play-cover-result";
4
+ export declare const MAX_REQUEST_ID_LENGTH = 64;
5
+ export declare const COVER_TARGET_SELECTOR = "#castle-card, [data-castle-card]";
6
+ export declare const COVER_SCALE = 2;
7
+ export declare const COVER_MAX_EDGE = 1400;
8
+ export declare const MAX_COVER_PNG_BYTES: number;
9
+ export declare const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
10
+ export declare const FRAME_TIMEOUT_MS = 5000;
11
+ export declare const BRIDGE_DEADLINE_MS = 25000;
12
+ export declare const SHELL_CAPTURE_TIMEOUT_MS = 30000;
13
+ /** The sentence a creator sees for a rejection code (`webkit`: the browser showing it is WebKit). */
14
+ export declare function coverFailureSentence(code: string, webkit?: boolean): string;
@@ -0,0 +1,139 @@
1
+ // The wire contract for the Play panel's "Use as cover", shared by its three
2
+ // parties so none of them spells a name or a limit on its own:
3
+ //
4
+ // - the capture bridge (bridge.ts) that the serve injects into the play
5
+ // frame's <head> when CASTLE_PLAY_COVER=on,
6
+ // - the shell's Play panel (shell/playCover.ts), which asks the frame for a
7
+ // capture and hands the PNG it approves to the host,
8
+ // - the serve (serve.ts), which only needs to know the gate.
9
+ //
10
+ // Shell -> deck, posted to the play frame at that frame's own origin:
11
+ // { type: 'castle-play-cover-capture', requestId }
12
+ // { type: 'castle-play-cover-cancel', requestId }
13
+ // Deck -> shell, posted back to the origin that asked:
14
+ // { type: 'castle-play-cover-result', requestId, ok: true, dataUrl, width, height }
15
+ // { type: 'castle-play-cover-result', requestId, ok: false, code, message }
16
+ //
17
+ // Deliberately NOT `castle-capture-cover`: that is the SDK's html2canvas
18
+ // handshake, a less faithful capture this path must never fall back to.
19
+ export const PLAY_COVER_CAPTURE = 'castle-play-cover-capture';
20
+ export const PLAY_COVER_CANCEL = 'castle-play-cover-cancel';
21
+ export const PLAY_COVER_RESULT = 'castle-play-cover-result';
22
+ // A request id is the shell's own token; anything longer is not one of ours.
23
+ export const MAX_REQUEST_ID_LENGTH = 64;
24
+ // The card the SDK mounts (`initCard`) or a deck marks itself -- the same
25
+ // selector the headless cover and the SDK's own screenshot use. A deck with
26
+ // neither is captured from <body>, which in Play IS the card.
27
+ export const COVER_TARGET_SELECTOR = '#castle-card, [data-castle-card]';
28
+ // Output resolution: twice the card's CSS size (a 500x700 card becomes a
29
+ // 1000x1400 PNG), with the long edge capped at 1400 so a large panel does not
30
+ // produce a bigger cover than a phone-sized one would.
31
+ export const COVER_SCALE = 2;
32
+ export const COVER_MAX_EDGE = 1400;
33
+ // The largest PNG the shell accepts from the deck, and so the largest it will
34
+ // ever hand the host to upload. A 1000x1400 PNG of a busy game measures 1-3 MB;
35
+ // 6 MiB leaves room for noisy WebGL art without letting a deck hand the host an
36
+ // arbitrary blob. Checked on the decoded bytes, in the bridge and again in the
37
+ // shell, which does not trust the deck to have checked.
38
+ export const MAX_COVER_PNG_BYTES = 6 * 1024 * 1024;
39
+ export const PNG_DATA_URL_PREFIX = 'data:image/png;base64,';
40
+ // How long the bridge waits for the deck's next animation frame once it is
41
+ // ready to capture, and how long the whole capture may take before it gives up
42
+ // on its own (resource fetches included). The shell waits a little longer than
43
+ // the bridge so the bridge's own, more specific, failure is what arrives.
44
+ export const FRAME_TIMEOUT_MS = 5_000;
45
+ export const BRIDGE_DEADLINE_MS = 25_000;
46
+ export const SHELL_CAPTURE_TIMEOUT_MS = 30_000;
47
+ // What a creator is told for each rejection. Short sentences a person can act
48
+ // on; the code travels next to it so a report can name the exact case. Any code
49
+ // not listed here falls back to the generic sentence.
50
+ const COVER_FAILURE_SENTENCES = {
51
+ UNSUPPORTED_ELEMENT: 'The card contains an element a cover cannot copy (an iframe, video, or script).',
52
+ UNSUPPORTED_SHADOW_ROOT: 'The card uses a shadow root, which a cover cannot copy.',
53
+ UNSUPPORTED_NAMESPACE: 'The card contains markup a cover cannot copy (such as MathML).',
54
+ UNSUPPORTED_SVG_ELEMENT: 'The card contains SVG a cover cannot copy.',
55
+ UNSUPPORTED_SVG_REFERENCE: 'The card contains SVG that references other content.',
56
+ UNSUPPORTED_EVENT_HANDLER: 'The card contains SVG with an event handler.',
57
+ UNSUPPORTED_RESOURCE: 'The card shows an image a cover cannot embed.',
58
+ UNSUPPORTED_RESOURCE_SCHEME: 'The card shows an image a cover cannot embed.',
59
+ UNSUPPORTED_RESOURCE_REFERENCE: 'The card shows an image a cover cannot embed.',
60
+ RESOURCE_ORIGIN_NOT_ALLOWED: 'The card uses an image or font from a site that does not allow copying it.',
61
+ RESOURCE_FETCH_FAILED: 'An image or font on the card could not be loaded for the cover.',
62
+ RESOURCE_TYPE_MISMATCH: 'The card shows an animated or unsupported image format (use PNG or JPEG).',
63
+ IMAGE_NOT_LOADED: "An image on the card hasn't finished loading. Try again once it shows.",
64
+ IMAGE_NOT_READABLE: 'The card shows an image from another site that the cover cannot check. Serve it from the deck itself, or allow it with CORS: an Access-Control-Allow-Origin header, plus crossorigin="anonymous" on an <img>.',
65
+ IMAGE_CHANGED: 'An image on the card loads differently each time, so the cover could not copy the one on screen.',
66
+ RESOURCE_BLOCKED_BY_PAGE: "The card uses an image the deck's own content security policy blocks.",
67
+ RESOURCE_TOO_LARGE: 'An image or font on the card is too large to embed.',
68
+ RESOURCE_BUDGET_EXCEEDED: 'The images and fonts on the card are too large to embed.',
69
+ TOO_MANY_RESOURCES: 'The card uses too many images and fonts to embed.',
70
+ UNSUPPORTED_FONT: 'Text on the card uses a web font the cover cannot embed.',
71
+ UNSUPPORTED_FONT_SOURCE: 'Text on the card uses a local font the cover cannot embed.',
72
+ UNSUPPORTED_FONT_STYLESHEET: 'A font stylesheet on the card could not be read.',
73
+ UNSUPPORTED_FONT_DESCRIPTOR: 'A font on the card uses a setting the cover cannot copy.',
74
+ TOO_MANY_FONT_FACES: "The card's fonts load more separate font files than the cover can check. Use fewer fonts, or fewer characters from large ones.",
75
+ TOO_MANY_FONT_STYLES: 'Text on the card uses more fonts, weights and styles than the cover can check. Use fewer on the card.',
76
+ UNSUPPORTED_FONT_DISPLAY: "Text on the card uses a web font with font-display: optional or fallback, so the cover can't tell whether the page is showing it. Use font-display: swap or block.",
77
+ FONTS_PENDING: 'Fonts were still loading. Try again in a moment.',
78
+ UNSUPPORTED_PSEUDO_RESOURCE: 'The card uses a CSS pseudo-element image, which a cover cannot copy.',
79
+ UNSUPPORTED_PSEUDO_STYLE: 'The card styles a first letter, first line or list marker on its own (a drop cap, say), which a cover cannot copy.',
80
+ CARD_TEXT_SELECTED: 'Text on the card is selected. Click elsewhere to clear it, then try again.',
81
+ UNSUPPORTED_HIGHLIGHT: 'The card highlights text with the CSS Highlight API, which a cover cannot copy.',
82
+ UNSUPPORTED_MARKER: 'A list marker on the card uses a web font in a style the cover cannot check.',
83
+ UNSUPPORTED_NATIVE_CONTROL: 'The card shows a native button, progress or meter bar, which a cover draws unstyled. Style it yourself (appearance: none and your own CSS).',
84
+ UNSUPPORTED_TOP_LAYER: 'The card has an open modal dialog or popover, which a cover cannot copy. Close it and try again.',
85
+ UNSUPPORTED_ANCESTOR_EFFECT: 'Something around the card fades, filters, blends or clips it, which a cover cannot copy.',
86
+ UNSUPPORTED_IMAGE_SET: 'The card uses image-set() for an image, which a cover cannot resolve the same way.',
87
+ UNSUPPORTED_FIXED_POSITION: 'The card has an element fixed to the page rather than the card, which a cover cannot place the same way.',
88
+ UNSUPPORTED_LINE_CLAMP: "The card has a line clamp the cover can't be sure is applied (its box is declared both as -webkit-box and as something else, or in a stylesheet it can't read).",
89
+ UNSUPPORTED_FORCED_COLORS: "The browser is in a forced-colors (high contrast) mode, which a cover can't copy. Turn it off to set a cover.",
90
+ UNSUPPORTED_PSEUDO_CONTENT: 'The card uses CSS generated content a cover cannot copy.',
91
+ UNSUPPORTED_SCROLL_LAYOUT: "A scrolled box on the card lays its content out in a way a cover can't copy (flex, grid, sticky or pinned items, or right-to-left). Scroll it back to the top and try again.",
92
+ UNSUPPORTED_SCROLLBARS: "The card shows scrollbars, which a cover can't copy. Hide them (scrollbar-width: none) and try again.",
93
+ SENSITIVE_FORM_CONTROL: 'The card shows a password field.',
94
+ UNSUPPORTED_FORM_VALUE: 'The card shows a text field or menu, whose contents a cover cannot copy.',
95
+ UNSUPPORTED_NODE: 'The card contains content a cover cannot copy.',
96
+ CANVAS_CONTEXT_UNKNOWN: 'A canvas on the card was drawn before the capture could observe it. Restart the deck and try again.',
97
+ UNSUPPORTED_CANVAS_CONTEXT: 'A canvas on the card uses a drawing mode a cover cannot read (such as WebGPU or bitmaprenderer).',
98
+ CANVAS_READBACK_FAILED: 'A canvas on the card shows an image from another site, so it cannot be read.',
99
+ WEBGL_CAPTURE_REQUIRED: 'The WebGL canvas was not drawn during an animation frame.',
100
+ WEBGL_NOT_RENDERED_THIS_FRAME: 'The WebGL canvas was not drawn during the captured animation frame.',
101
+ WEBGL_CAPTURE_STALE: 'The WebGL canvas changed while it was being copied. Try again.',
102
+ WEBGL_CONTEXT_LOST: 'The WebGL canvas lost its context.',
103
+ WEBGL_CONTEXT_NOT_TRACKED: 'A WebGL canvas on the card was created before the capture could observe it.',
104
+ WEBGL_NONDEFAULT_FRAMEBUFFER: 'The WebGL canvas was bound to an offscreen framebuffer at the end of the frame.',
105
+ WEBGL_NONDEFAULT_READ_FRAMEBUFFER: 'The WebGL canvas was bound to an offscreen framebuffer at the end of the frame.',
106
+ WEBGL_EMPTY_BUFFER: 'The WebGL canvas has no pixels.',
107
+ WEBGL_READBACK_FAILED: 'The WebGL canvas could not be read.',
108
+ WEBGL_TRANSPARENCY_UNSUPPORTED: 'The WebGL canvas is transparent; covers need an opaque WebGL canvas.',
109
+ APPLICATION_FRAME_TIMEOUT: 'The deck did not draw a new frame in time. Is it paused?',
110
+ FRAME_NOT_VISIBLE: "The browser paused the deck because it isn't on screen. Bring the Play panel fully into view and try again.",
111
+ FRAME_CHANGED_AFTER_CAPTURE: 'The card changed while it was being copied. Try again.',
112
+ PACKAGE_TOO_COMPLEX: 'The card has too many elements to copy.',
113
+ PACKAGE_TOO_LARGE: 'The card is too large to copy.',
114
+ EMPTY_TARGET: 'The card has no visible size.',
115
+ TARGET_NOT_FOUND: 'No card was found to capture.',
116
+ UNSUPPORTED_ROOT_TRANSFORM: 'The card is rotated or skewed, which a cover cannot copy.',
117
+ QUIRKS_MODE_DOCUMENT: "The deck's index.html has no <!doctype html>, so its layout cannot be copied exactly.",
118
+ RASTERIZE_BLOCKED: 'This browser would not turn the capture into an image. Try Chrome.',
119
+ RASTERIZE_FAILED: 'The capture could not be turned into an image.',
120
+ EFFECT_NOT_REPRODUCIBLE: "The card uses a shadow or blur this browser can't copy into a cover exactly (a backdrop-filter, or a shadow cut off at an edge).",
121
+ CAPTURE_UNVERIFIABLE: "This browser can't be checked copying an image or canvas on this card. Set this cover from Chrome or Edge on a computer instead.",
122
+ BUILTINS_MODIFIED: 'The deck replaces built-in browser functions the cover relies on, so its capture cannot be trusted.',
123
+ BROWSER_UNSUPPORTED: "Safari and other WebKit browsers can't make a cover exactly yet. Set this cover from Chrome or Edge on a computer instead.",
124
+ RASTERIZE_MISMATCH: "This browser drew the capture differently from the page, so it wasn't used. Try Chrome.",
125
+ COVER_TOO_LARGE: 'The captured image is too large to use as a cover.',
126
+ CAPTURE_BUSY: 'A capture is already in progress.',
127
+ CAPTURE_TIMEOUT: 'The capture took too long.',
128
+ CAPTURE_CANCELED: 'The capture was canceled.',
129
+ };
130
+ const GENERIC_FAILURE = 'The deck could not be captured.';
131
+ // In WebKit a card with any shadow or blur is refused outright (engine.ts),
132
+ // and the creator should know it is the browser, not the card.
133
+ const WEBKIT_EFFECT_SENTENCE = "Safari and other WebKit browsers can't copy shadows or blur into a cover exactly. Set this cover from Chrome or Edge on a computer instead.";
134
+ /** The sentence a creator sees for a rejection code (`webkit`: the browser showing it is WebKit). */
135
+ export function coverFailureSentence(code, webkit = false) {
136
+ if (webkit && code === 'EFFECT_NOT_REPRODUCIBLE')
137
+ return WEBKIT_EFFECT_SENTENCE;
138
+ return COVER_FAILURE_SENTENCES[code] ?? GENERIC_FAILURE;
139
+ }
@@ -0,0 +1,21 @@
1
+ import type { CoverPacket } from './clone.js';
2
+ export interface CoverImage {
3
+ dataUrl: string;
4
+ width: number;
5
+ height: number;
6
+ /** How it was drawn: the geometry that passed and how many draws it took. */
7
+ diagnostics: {
8
+ geometry: Geometry;
9
+ attempts: number;
10
+ bitmapsChecked: number;
11
+ /** Loaded web-font faces the check's rows drew (every face the card uses). */
12
+ fontFacesChecked: number;
13
+ unverifiedBitmaps: number;
14
+ strippedMarks: number;
15
+ };
16
+ }
17
+ export type Geometry = 'viewbox' | 'transform' | 'transform-padded' | 'zoom';
18
+ /** The output scale for a card: 2x, with the long edge held to COVER_MAX_EDGE. */
19
+ export declare function coverScale(width: number, height: number): number;
20
+ /** Rasterizes a packet to a PNG data URL at cover resolution, verified against the page. */
21
+ export declare function rasterizePacket(packet: CoverPacket, signal?: AbortSignal): Promise<CoverImage>;