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,71 @@
1
+ /** An embedded bitmap whose painted pixels can be predicted exactly. */
2
+ export interface EmbeddedBitmap {
3
+ id: number;
4
+ dataUrl: string;
5
+ /** Content box in the copy's CSS pixels, relative to the card's origin. */
6
+ x: number;
7
+ y: number;
8
+ width: number;
9
+ height: number;
10
+ }
11
+ export { collectTextSamples, type TextSample } from './textSamples.js';
12
+ export interface RecordContext {
13
+ originX: number;
14
+ originY: number;
15
+ scaleX: number;
16
+ scaleY: number;
17
+ root: Element;
18
+ bitmaps: EmbeddedBitmap[];
19
+ /** Bitmaps painted in a way the check cannot predict (filters, blending, cropping). */
20
+ unverified: number;
21
+ /** Each source element's clone, so boxes found later can be tagged in the copy. */
22
+ clones: Map<Element, Element>;
23
+ /** This capture's attribute prefix for its own marks in the copy. */
24
+ marker: string;
25
+ /** The deck's own data-cover-* attributes left out of the copy. */
26
+ strippedMarks: number;
27
+ }
28
+ /**
29
+ * Notes a cloned bitmap for the check, tagging the clone so the check can find
30
+ * it again in the packet. Bitmaps that are hidden, tiny, transformed away from
31
+ * their box, or filtered are counted but not tagged.
32
+ */
33
+ export declare function recordBitmap(source: HTMLElement, clone: Element, dataUrl: string, context: RecordContext): void;
34
+ /** Paint effects the rasterizer must prove it draws right before it is trusted with them. */
35
+ export type Effect = 'box-shadow' | 'text-shadow' | 'filter-blur' | 'drop-shadow' | 'backdrop-blur';
36
+ /**
37
+ * The blur-type effects the card paints anywhere (elements and their
38
+ * ::before/::after). A browser has been seen to draw a blurred box-shadow
39
+ * unscaled and offset inside the copy, so each kind the card uses gets a
40
+ * probe in the check strip (verify.ts).
41
+ */
42
+ export declare function collectEffects(root: Element): Effect[];
43
+ /** A box whose overflow clips an effect, in the copy's CSS pixels. */
44
+ export interface ClipBox {
45
+ x: number;
46
+ y: number;
47
+ width: number;
48
+ height: number;
49
+ /** Its largest corner radius, so the check can stay clear of the curve. */
50
+ radius: number;
51
+ /** The other recorded boxes it sits inside: unclipped with it in its redraw. */
52
+ ancestors: number[];
53
+ }
54
+ export interface EffectClips {
55
+ /** Inner (non-root) boxes that clip a blur effect somewhere inside them. */
56
+ clips: ClipBox[];
57
+ /** The card root's largest corner radius. */
58
+ rootRadius: number;
59
+ /** Why the clipping around an effect cannot be checked, if it cannot. */
60
+ unverifiable: string | null;
61
+ }
62
+ /**
63
+ * The boxes that clip a blur effect: every ancestor of an element with one
64
+ * (below the card root) whose overflow is not visible. A browser has been seen
65
+ * to draw a shadow cut by such a clip as a hard rectangle in the wrong place,
66
+ * so the rasterizer draws the card again with those clips removed and checks
67
+ * nothing inside them changed (verify.ts, checkUnclipped).
68
+ */
69
+ export declare function collectEffectClips(root: Element, context: RecordContext): EffectClips;
70
+ /** Everything in the card WebKit may not be trusted to draw (engine.ts's rule). */
71
+ export declare function collectWebKitRefusedEffects(root: Element): string[];
@@ -0,0 +1,243 @@
1
+ // What the rasterizer's check needs to know about the card, recorded while the
2
+ // card is frozen at the capture boundary: where each embedded bitmap (a canvas
3
+ // snapshot or an <img>) sits and what its pixels are, and a sample of the text
4
+ // drawn in each embedded web font. The check itself is in verify.ts.
5
+ //
6
+ // This exists because a browser can lay the copy out and still not paint all of
7
+ // it: WebKit drew the whole card at 1x into a corner of the output, with every
8
+ // data: image and web font missing, and reported success. The check turns that
9
+ // class of failure into RASTERIZE_MISMATCH instead of a wrong cover.
10
+ import { visibleSnapshotElements } from './validate.js';
11
+ import { MAX_CHECKED_BITMAPS } from './verify.js';
12
+ export { collectTextSamples } from './textSamples.js';
13
+ function px(value) {
14
+ const parsed = Number.parseFloat(value);
15
+ return Number.isFinite(parsed) ? parsed : 0;
16
+ }
17
+ // A filter or blend mode between the bitmap and the page changes its pixels in
18
+ // a way the check's compositing model does not follow.
19
+ function predictable(source, root) {
20
+ for (let element = source; element; element = element.parentElement) {
21
+ const style = getComputedStyle(element);
22
+ if (style.filter !== 'none' || style.mixBlendMode !== 'normal')
23
+ return false;
24
+ if (element === root)
25
+ break;
26
+ }
27
+ const style = getComputedStyle(source);
28
+ return style.objectFit === 'fill' || style.objectFit === '';
29
+ }
30
+ /**
31
+ * Notes a cloned bitmap for the check, tagging the clone so the check can find
32
+ * it again in the packet. Bitmaps that are hidden, tiny, transformed away from
33
+ * their box, or filtered are counted but not tagged.
34
+ */
35
+ export function recordBitmap(source, clone, dataUrl, context) {
36
+ const style = getComputedStyle(source);
37
+ if (style.visibility !== 'visible')
38
+ return;
39
+ const rect = source.getBoundingClientRect();
40
+ const sx = context.scaleX;
41
+ const sy = context.scaleY;
42
+ // A rotated or skewed ancestor makes the bounding box bigger than the box.
43
+ const untransformed = Math.abs(rect.width - source.offsetWidth * sx) <= 1 &&
44
+ Math.abs(rect.height - source.offsetHeight * sy) <= 1;
45
+ if (!untransformed ||
46
+ !predictable(source, context.root) ||
47
+ context.bitmaps.length >= MAX_CHECKED_BITMAPS) {
48
+ context.unverified++;
49
+ return;
50
+ }
51
+ const left = (px(style.borderLeftWidth) + px(style.paddingLeft)) * sx;
52
+ const right = (px(style.borderRightWidth) + px(style.paddingRight)) * sx;
53
+ const top = (px(style.borderTopWidth) + px(style.paddingTop)) * sy;
54
+ const bottom = (px(style.borderBottomWidth) + px(style.paddingBottom)) * sy;
55
+ const width = rect.width - left - right;
56
+ const height = rect.height - top - bottom;
57
+ if (width < 4 || height < 4)
58
+ return;
59
+ const id = context.bitmaps.length;
60
+ clone.setAttribute(`${context.marker}-bitmap`, String(id));
61
+ context.bitmaps.push({
62
+ id,
63
+ dataUrl,
64
+ x: rect.left - context.originX + left,
65
+ y: rect.top - context.originY + top,
66
+ width,
67
+ height,
68
+ });
69
+ }
70
+ const EFFECT_ORDER = [
71
+ 'box-shadow',
72
+ 'text-shadow',
73
+ 'filter-blur',
74
+ 'drop-shadow',
75
+ 'backdrop-blur',
76
+ ];
77
+ function effectsOf(style, found) {
78
+ if (style.boxShadow && style.boxShadow !== 'none')
79
+ found.add('box-shadow');
80
+ if (style.textShadow && style.textShadow !== 'none')
81
+ found.add('text-shadow');
82
+ if (/\bblur\(/.test(style.filter))
83
+ found.add('filter-blur');
84
+ if (/\bdrop-shadow\(/.test(style.filter))
85
+ found.add('drop-shadow');
86
+ const backdrop = style.backdropFilter || style.getPropertyValue('-webkit-backdrop-filter');
87
+ if (backdrop && backdrop !== 'none')
88
+ found.add('backdrop-blur');
89
+ }
90
+ /**
91
+ * The blur-type effects the card paints anywhere (elements and their
92
+ * ::before/::after). A browser has been seen to draw a blurred box-shadow
93
+ * unscaled and offset inside the copy, so each kind the card uses gets a
94
+ * probe in the check strip (verify.ts).
95
+ */
96
+ export function collectEffects(root) {
97
+ const found = new Set();
98
+ for (const element of visibleSnapshotElements(root)) {
99
+ for (const pseudo of [null, '::before', '::after'])
100
+ effectsOf(getComputedStyle(element, pseudo), found);
101
+ }
102
+ return EFFECT_ORDER.filter((effect) => found.has(effect));
103
+ }
104
+ const MAX_EFFECT_CLIPS = 8;
105
+ function largestRadius(style, width, height) {
106
+ let largest = 0;
107
+ for (const corner of [
108
+ style.borderTopLeftRadius,
109
+ style.borderTopRightRadius,
110
+ style.borderBottomRightRadius,
111
+ style.borderBottomLeftRadius,
112
+ ]) {
113
+ for (const part of corner.split(/\s+/)) {
114
+ const value = Number.parseFloat(part);
115
+ if (!Number.isFinite(value))
116
+ continue;
117
+ largest = Math.max(largest, part.endsWith('%') ? (value / 100) * Math.max(width, height) : value);
118
+ }
119
+ }
120
+ return largest;
121
+ }
122
+ function clipsOverflow(style) {
123
+ return style.overflowX !== 'visible' || style.overflowY !== 'visible';
124
+ }
125
+ function hasEffect(element) {
126
+ const found = new Set();
127
+ for (const pseudo of [null, '::before', '::after'])
128
+ effectsOf(getComputedStyle(element, pseudo), found);
129
+ return found.size > 0;
130
+ }
131
+ // A box the check can unclip without moving anything, or why it cannot.
132
+ function clipBox(element, context) {
133
+ const style = getComputedStyle(element);
134
+ const rect = element.getBoundingClientRect();
135
+ const untransformed = Math.abs(rect.width - element.offsetWidth * context.scaleX) <= 1 &&
136
+ Math.abs(rect.height - element.offsetHeight * context.scaleY) <= 1;
137
+ if (!untransformed || style.clipPath !== 'none')
138
+ return 'an effect is clipped by a transformed or clip-path box';
139
+ // Unclipping a scroll container drops its scrollbars; where they take up
140
+ // room, that moves its content, and the comparison would mean nothing.
141
+ const borders = (a, b) => px(style.getPropertyValue(a)) + px(style.getPropertyValue(b));
142
+ if (element.offsetWidth - element.clientWidth - borders('border-left-width', 'border-right-width') >
143
+ 0.5 ||
144
+ element.offsetHeight -
145
+ element.clientHeight -
146
+ borders('border-top-width', 'border-bottom-width') >
147
+ 0.5) {
148
+ return 'an effect is clipped by a box with scrollbars that take up room';
149
+ }
150
+ const left = px(style.borderLeftWidth) * context.scaleX;
151
+ const top = px(style.borderTopWidth) * context.scaleY;
152
+ const width = rect.width - left - px(style.borderRightWidth) * context.scaleX;
153
+ const height = rect.height - top - px(style.borderBottomWidth) * context.scaleY;
154
+ return {
155
+ x: rect.left - context.originX + left,
156
+ y: rect.top - context.originY + top,
157
+ width,
158
+ height,
159
+ radius: largestRadius(style, width, height) * Math.max(context.scaleX, context.scaleY),
160
+ ancestors: [],
161
+ };
162
+ }
163
+ /**
164
+ * The boxes that clip a blur effect: every ancestor of an element with one
165
+ * (below the card root) whose overflow is not visible. A browser has been seen
166
+ * to draw a shadow cut by such a clip as a hard rectangle in the wrong place,
167
+ * so the rasterizer draws the card again with those clips removed and checks
168
+ * nothing inside them changed (verify.ts, checkUnclipped).
169
+ */
170
+ export function collectEffectClips(root, context) {
171
+ const rootStyle = getComputedStyle(root);
172
+ const rootRect = root.getBoundingClientRect();
173
+ const result = {
174
+ clips: [],
175
+ rootRadius: largestRadius(rootStyle, rootRect.width, rootRect.height) *
176
+ Math.max(context.scaleX, context.scaleY),
177
+ unverifiable: null,
178
+ };
179
+ const seen = new Set();
180
+ const tagged = new Map();
181
+ for (const element of visibleSnapshotElements(root)) {
182
+ if (!hasEffect(element))
183
+ continue;
184
+ for (let ancestor = element.parentElement; ancestor && ancestor !== root; ancestor = ancestor.parentElement) {
185
+ if (seen.has(ancestor) || !clipsOverflow(getComputedStyle(ancestor)))
186
+ continue;
187
+ seen.add(ancestor);
188
+ const box = ancestor instanceof HTMLElement
189
+ ? clipBox(ancestor, context)
190
+ : 'an effect is clipped by a non-HTML box';
191
+ const clone = context.clones.get(ancestor);
192
+ if (typeof box === 'string' || !clone)
193
+ result.unverifiable = typeof box === 'string' ? box : 'an effect clip was not copied';
194
+ else if (result.clips.length >= MAX_EFFECT_CLIPS)
195
+ result.unverifiable = 'too many boxes clip effects';
196
+ else {
197
+ // Tagged in the copy: these, and only these, are unclipped to check.
198
+ clone.setAttribute(`${context.marker}-effect-clip`, String(result.clips.length));
199
+ tagged.set(ancestor, result.clips.length);
200
+ result.clips.push(box);
201
+ }
202
+ }
203
+ }
204
+ // A clip bug can come from any box around the effect, so each box's redraw
205
+ // also unclips the recorded boxes it sits inside (and the card itself).
206
+ for (const [element, index] of tagged) {
207
+ for (let parent = element.parentElement; parent && parent !== root; parent = parent.parentElement) {
208
+ const outer = tagged.get(parent);
209
+ if (outer !== undefined)
210
+ result.clips[index].ancestors.push(outer);
211
+ }
212
+ }
213
+ return result;
214
+ }
215
+ // What WebKit is refused: every blur-type effect the probes cover, and paints
216
+ // WebKit was not shown to draw right and that nothing here checks -- shadows
217
+ // on ::first-letter/::first-line/::marker, -webkit-box-reflect, mask-image.
218
+ function webkitEffectsOf(element, found) {
219
+ const probed = new Set();
220
+ for (const pseudo of [null, '::before', '::after'])
221
+ effectsOf(getComputedStyle(element, pseudo), probed);
222
+ for (const effect of probed)
223
+ found.add(effect);
224
+ for (const pseudo of ['::first-letter', '::first-line', '::marker']) {
225
+ const shadow = getComputedStyle(element, pseudo).textShadow;
226
+ if (shadow && shadow !== 'none')
227
+ found.add(`text-shadow on ${pseudo}`);
228
+ }
229
+ const style = getComputedStyle(element);
230
+ const reflect = style.getPropertyValue('-webkit-box-reflect');
231
+ if (reflect && reflect !== 'none')
232
+ found.add('-webkit-box-reflect');
233
+ const mask = style.maskImage || style.getPropertyValue('-webkit-mask-image');
234
+ if (mask && mask !== 'none')
235
+ found.add('mask-image');
236
+ }
237
+ /** Everything in the card WebKit may not be trusted to draw (engine.ts's rule). */
238
+ export function collectWebKitRefusedEffects(root) {
239
+ const found = new Set();
240
+ for (const element of visibleSnapshotElements(root))
241
+ webkitEffectsOf(element, found);
242
+ return [...found].sort();
243
+ }
@@ -0,0 +1,4 @@
1
+ export declare function playCoverEnabled(): boolean;
2
+ export declare function playCoverBridgeTag(bridgePath?: string): string;
3
+ export declare function playCoverHeadInjection(bridgePath?: string): string;
4
+ export declare function playCoverOffered(bridgePath?: string): boolean;
@@ -0,0 +1,57 @@
1
+ // The serve's half of the Play panel's "Use as cover": the gate, and the
2
+ // capture bridge it injects into deck pages while the gate is open.
3
+ //
4
+ // Off for everyone until the serve is told otherwise, the same rollout shape as
5
+ // the Snap button's CASTLE_PLAY_SNAP (ide.ts): castle-www sets
6
+ // CASTLE_PLAY_COVER=on on the serve spawn for the users a server-side gate has
7
+ // opened it for, and only that exact string opens it. Closed, nothing about a
8
+ // deck page changes -- no script, no instrumentation -- and the editor info
9
+ // endpoint says `playCover: false`, so the shell shows no button.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ const BRIDGE_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'cover-bridge', 'play-cover-bridge.js');
14
+ export function playCoverEnabled() {
15
+ return process.env.CASTLE_PLAY_COVER === 'on';
16
+ }
17
+ const bridgeTags = new Map();
18
+ const bridgeErrors = new Set();
19
+ // The bundled bridge (vite.cover-bridge.config.ts) as an inline classic
20
+ // <script>. Read once: it is part of this CLI's build, not the deck's. The path
21
+ // is a parameter only so a test can name a bundle that is not there.
22
+ export function playCoverBridgeTag(bridgePath = BRIDGE_PATH) {
23
+ const cached = bridgeTags.get(bridgePath);
24
+ if (cached !== undefined)
25
+ return cached;
26
+ const code = fs.readFileSync(bridgePath, 'utf8');
27
+ // An inline script ends at the first `</script`, whatever the JS around it
28
+ // meant; a bundle that contains one would be cut short, so refuse it.
29
+ if (/<\/script/i.test(code))
30
+ throw new Error('play cover bridge bundle contains </script');
31
+ const tag = `<script data-castle-play-cover>${code}</script>`;
32
+ bridgeTags.set(bridgePath, tag);
33
+ return tag;
34
+ }
35
+ // What a deck page's <head> gains: the bridge while the gate is open, nothing
36
+ // otherwise. A build without the bundle is logged once and injects nothing --
37
+ // a deck page that fails to load over a cover button would be the worse bug.
38
+ export function playCoverHeadInjection(bridgePath = BRIDGE_PATH) {
39
+ if (!playCoverEnabled())
40
+ return '';
41
+ try {
42
+ return playCoverBridgeTag(bridgePath);
43
+ }
44
+ catch (error) {
45
+ if (!bridgeErrors.has(bridgePath)) {
46
+ bridgeErrors.add(bridgePath);
47
+ console.error(`[castle] Use as cover is unavailable: ${error instanceof Error ? error.message : String(error)}`);
48
+ }
49
+ return '';
50
+ }
51
+ }
52
+ // What the editor info endpoint reports as `playCover`: the gate is open AND
53
+ // deck pages actually carry the bridge. A build missing the bundle hides the
54
+ // button instead of offering one whose every press times out.
55
+ export function playCoverOffered(bridgePath = BRIDGE_PATH) {
56
+ return playCoverHeadInjection(bridgePath) !== '';
57
+ }
@@ -0,0 +1,11 @@
1
+ /** Where the comment starting at `at` ends, by the tokenizer's rules. */
2
+ export declare function commentEnd(html: string, at: number): number | null;
3
+ export interface BridgeSpot {
4
+ /** Where the bridge goes. */
5
+ at: number;
6
+ /** True when it leads <head>; false when it goes at the document's start. */
7
+ inHead: boolean;
8
+ }
9
+ export declare function coverBridgeSpot(html: string): BridgeSpot;
10
+ /** The page with the bridge placed (see coverBridgeSpot). */
11
+ export declare function placeCoverBridge(html: string, cover: string): string;
@@ -0,0 +1,110 @@
1
+ // Where the Play cover bridge goes in a deck page, so that it is the first
2
+ // script the browser runs -- ahead of anything the deck could use to hide
3
+ // from it -- without changing how the page parses.
4
+ //
5
+ // The page's start is read the way the HTML tokenizer reads it, not with a
6
+ // loose pattern: comments end where the tokenizer ends them (`<!-->`,
7
+ // `<!--->`, `-->`, `--!>`), a doctype or `<?...>` ends at its first `>`, and
8
+ // a tag's quoted attribute value may hold a `>`. What may come before
9
+ // `<head>` without running anything is a byte-order mark, whitespace,
10
+ // comments, `<?...>`, the doctype and the `<html>` tag. When only that comes
11
+ // first, the bridge leads <head>; otherwise it goes right after the doctype
12
+ // when one was read before anything else (before it, the page would be in
13
+ // quirks mode), else at byte 0.
14
+ // A tag's attributes as the tokenizer reads them: a name, then optionally
15
+ // `=` and a double-, single- or un-quoted value; quoted values may hold `>`.
16
+ const ATTRIBUTES = String.raw `(?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>\x60]+))?|\s*/)*\s*>`;
17
+ const HTML_TAG = new RegExp(String.raw `<html(?=[\s/>])${ATTRIBUTES}`, 'iy');
18
+ const HEAD_TAG = new RegExp(String.raw `<head(?=[\s/>])${ATTRIBUTES}`, 'iy');
19
+ const DOCTYPE_START = /<!doctype/iy;
20
+ const SPACE = /[\t\n\f\r ]+/y;
21
+ function startsBogusComment(html, at) {
22
+ if (html.startsWith('<?', at))
23
+ return true;
24
+ if (html.startsWith('<!', at)) {
25
+ return !html.startsWith('<!--', at) && !/^<!doctype/i.test(html.slice(at, at + 9));
26
+ }
27
+ return /^<\/(?![A-Za-z])/.test(html.slice(at, at + 3));
28
+ }
29
+ function stickyMatch(pattern, html, at) {
30
+ pattern.lastIndex = at;
31
+ return pattern.exec(html) ? pattern.lastIndex : null;
32
+ }
33
+ /** Where the comment starting at `at` ends, by the tokenizer's rules. */
34
+ export function commentEnd(html, at) {
35
+ const body = at + 4;
36
+ if (html[body] === '>')
37
+ return body + 1; // <!-->
38
+ if (html.startsWith('->', body))
39
+ return body + 2; // <!--->
40
+ const plain = html.indexOf('-->', body);
41
+ const bang = html.indexOf('--!>', body);
42
+ if (plain < 0 && bang < 0)
43
+ return null;
44
+ if (bang < 0 || (plain >= 0 && plain < bang))
45
+ return plain + 3;
46
+ return bang + 4;
47
+ }
48
+ export function coverBridgeSpot(html) {
49
+ let at = html.startsWith('') ? 1 : 0;
50
+ let doctypeEnd = null;
51
+ let sawOther = false;
52
+ let sawHtml = false;
53
+ const early = () => ({ at: doctypeEnd ?? 0, inHead: false });
54
+ while (at < html.length) {
55
+ const space = stickyMatch(SPACE, html, at);
56
+ if (space !== null) {
57
+ at = space;
58
+ continue;
59
+ }
60
+ if (html.startsWith('<!--', at)) {
61
+ const end = commentEnd(html, at);
62
+ if (end === null)
63
+ return early();
64
+ at = end;
65
+ continue;
66
+ }
67
+ if (!sawOther && !sawHtml && stickyMatch(DOCTYPE_START, html, at) !== null) {
68
+ const end = html.indexOf('>', at);
69
+ if (end < 0)
70
+ return early();
71
+ at = end + 1;
72
+ doctypeEnd = at;
73
+ sawOther = true;
74
+ continue;
75
+ }
76
+ // NULs are dropped where the page starts.
77
+ if (html[at] === '\0') {
78
+ at++;
79
+ continue;
80
+ }
81
+ // Bogus comments, which end at the first ">": <?...>, <! not starting a
82
+ // comment or doctype (<![CDATA[...]]>, <!x>), and </ not followed by a
83
+ // letter.
84
+ if (startsBogusComment(html, at)) {
85
+ const end = html.indexOf('>', at);
86
+ if (end < 0)
87
+ return early();
88
+ at = end + 1;
89
+ continue;
90
+ }
91
+ const htmlEnd = sawHtml ? null : stickyMatch(HTML_TAG, html, at);
92
+ if (htmlEnd !== null) {
93
+ at = htmlEnd;
94
+ sawHtml = true;
95
+ sawOther = true;
96
+ continue;
97
+ }
98
+ const headEnd = stickyMatch(HEAD_TAG, html, at);
99
+ if (headEnd !== null)
100
+ return { at: headEnd, inHead: true };
101
+ return early();
102
+ }
103
+ return early();
104
+ }
105
+ /** The page with the bridge placed (see coverBridgeSpot). */
106
+ export function placeCoverBridge(html, cover) {
107
+ const spot = coverBridgeSpot(html);
108
+ const insert = spot.inHead ? `\n ${cover}` : spot.at === 0 ? `${cover}\n` : `\n${cover}`;
109
+ return `${html.slice(0, spot.at)}${insert}${html.slice(spot.at)}`;
110
+ }
package/dist/serve.d.ts CHANGED
@@ -3,6 +3,7 @@ export declare function appendCapped(file: string, line: string): void;
3
3
  export declare function isViteClientUpgrade(req: http.IncomingMessage): boolean;
4
4
  export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
5
5
  export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
6
+ export declare function injectDeckHead(html: string): string;
6
7
  export declare function serve(dir: string, options?: {
7
8
  port?: string;
8
9
  host?: string;
package/dist/serve.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { placeCoverBridge } from './playCoverPlacement.js';
1
2
  import * as fs from 'fs';
2
3
  import * as http from 'http';
3
4
  import * as net from 'net';
@@ -12,6 +13,8 @@ import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugi
12
13
  import { viteClientStubPlugin } from './viteClientStub.js';
13
14
  import { paramsRegisterPlugin } from './paramsRegisterPlugin.js';
14
15
  import { modulePreloadPlugin } from './modulePreload.js';
16
+ import { externalSourcemapsPlugin } from './externalSourcemaps.js';
17
+ import { fontFaceImportsPlugin } from './fontFaceImports.js';
15
18
  import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
16
19
  import { installFilesChangedWatcher } from './filesChanged.js';
17
20
  import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
@@ -26,6 +29,7 @@ import { ServeSecurity } from './serveSecurity.js';
26
29
  import { atomicWriteFileSync } from './atomicFile.js';
27
30
  import { isSameOriginUpgrade } from './wsOrigin.js';
28
31
  import { createAssetCompression } from './assetCompression.js';
32
+ import { playCoverHeadInjection } from './playCoverGate.js';
29
33
  import { resolveServerConfig } from './castleJson.js';
30
34
  import { startDevSessionServer, } from './devSessionServer.js';
31
35
  // The log is a tail, not an archive: append, and once it passes the cap drop
@@ -508,6 +512,9 @@ export function isAllowedContentFilesRequest(role, method, reqPath) {
508
512
  // the redbox. Replacer functions throughout, so `$&` in the injected script
509
513
  // stays literal.
510
514
  function injectIntoHead(html, injected) {
515
+ // Unchanged by the Play cover on purpose: with its gate off a deck page is
516
+ // byte-for-byte what it was before the feature. Only the bridge itself is
517
+ // placed by the HTML-aware reader (placeCoverBridge).
511
518
  const head = /<head(\s[^>]*)?>/i;
512
519
  if (head.test(html))
513
520
  return html.replace(head, (match) => `${match}${injected}`);
@@ -519,21 +526,27 @@ function injectIntoHead(html, injected) {
519
526
  return html.replace(body, (match) => `${injected}${match}`);
520
527
  return `${injected}${html}`;
521
528
  }
522
- function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
523
- return {
524
- name: 'castle-dev',
525
- transformIndexHtml: {
526
- order: 'pre',
527
- handler(html) {
528
- // Give the deck page Castle's favicon too -- it's a real page when
529
- // opened directly (play surface / `?edit=0`), not just the editor's
530
- // iframe. Injected here rather than in the kit templates so bare
531
- // `--kit none` decks and already-scaffolded decks get it as well; a
532
- // deck that declares its own icon keeps it.
533
- const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
534
- ? ''
535
- : `\n ${FAVICON_LINK_TAGS}`;
536
- const injected = `${favicon}\n <script>
529
+ // Everything the serve adds to a deck page's <head>: Castle's favicon, the
530
+ // shell-origin and readiness script, the redbox, the console forward, and --
531
+ // behind CASTLE_PLAY_COVER -- the Play cover capture bridge. Exported for the
532
+ // tests that pin what a deck page receives.
533
+ export function injectDeckHead(html) {
534
+ // Give the deck page Castle's favicon too -- it's a real page when
535
+ // opened directly (play surface / `?edit=0`), not just the editor's
536
+ // iframe. Injected here rather than in the kit templates so bare
537
+ // `--kit none` decks and already-scaffolded decks get it as well; a
538
+ // deck that declares its own icon keeps it.
539
+ const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
540
+ ? ''
541
+ : `\n ${FAVICON_LINK_TAGS}`;
542
+ // The Play cover bridge goes first so it installs its hooks before anything
543
+ // else on the page runs. Empty unless CASTLE_PLAY_COVER=on, which leaves
544
+ // every byte of the page exactly as it is without the feature.
545
+ const cover = playCoverHeadInjection();
546
+ // The bridge is placed last, by playCoverPlacement.ts: it leads <head> when
547
+ // nothing that could run comes before it, else it goes at the very start
548
+ // of the document -- and nothing the serve adds lands ahead of it.
549
+ const injected = `${favicon}\n <script>
537
550
  window.CastleEmbed={edit:true,host:'dev'};
538
551
  window.__castleShellOrigin=(function(){
539
552
  var h=location.hostname.toLowerCase();
@@ -585,8 +598,15 @@ window.__castleShellOrigin=(function(){
585
598
  window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
586
599
  })();
587
600
  </script>\n ${FRAME_ERROR_CAPTURE}\n ${CONSOLE_CAPTURE}`;
588
- return injectIntoHead(html, injected);
589
- },
601
+ const page = injectIntoHead(html, injected);
602
+ return cover ? placeCoverBridge(page, cover) : page;
603
+ }
604
+ function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
605
+ return {
606
+ name: 'castle-dev',
607
+ transformIndexHtml: {
608
+ order: 'pre',
609
+ handler: injectDeckHead,
590
610
  },
591
611
  configureServer(server) {
592
612
  server.middlewares.use(createAssetCompression());
@@ -1228,6 +1248,11 @@ export async function serve(dir, options = {}) {
1228
1248
  sceneFilesPlugin(),
1229
1249
  scriptErrorsPlugin(scriptErrors),
1230
1250
  modulePreloadPlugin({ enabled: process.env.CASTLE_MODULE_PRELOAD === '1' }),
1251
+ externalSourcemapsPlugin({ enabled: process.env.CASTLE_EXTERNAL_SOURCEMAPS === '1' }),
1252
+ fontFaceImportsPlugin({
1253
+ enabled: process.env.CASTLE_FONT_FACE_IMPORTS === '1',
1254
+ projectDir,
1255
+ }),
1231
1256
  ],
1232
1257
  server: {
1233
1258
  port,