@mushi-mushi/web 1.28.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,179 @@
2
2
 
3
3
  require('@mushi-mushi/core');
4
4
 
5
- // src/capture/compress-screenshot.ts
5
+ var __defProp = Object.defineProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/capture/display-capture.ts
12
+ var display_capture_exports = {};
13
+ __export(display_capture_exports, {
14
+ grabMaskedTabFrame: () => grabMaskedTabFrame
15
+ });
16
+ async function grabMaskedTabFrame(pendingStream, maskSelectors) {
17
+ const stream = await pendingStream;
18
+ const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;
19
+ if (surface && surface !== "browser") {
20
+ stream.getTracks().forEach((track) => track.stop());
21
+ throw Object.assign(new Error("Only this tab can be captured"), { name: "NotAllowedError" });
22
+ }
23
+ const selectors = maskSelectors.join(",");
24
+ const mask = document.createElement("style");
25
+ mask.setAttribute("data-mushi-capture-mask", "");
26
+ mask.textContent = `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}:is(${selectors}) *{visibility:hidden!important}`;
27
+ document.head.appendChild(mask);
28
+ const video = document.createElement("video");
29
+ try {
30
+ video.muted = true;
31
+ video.srcObject = stream;
32
+ await video.play();
33
+ await new Promise((resolve) => setTimeout(resolve, 150));
34
+ const canvas = document.createElement("canvas");
35
+ canvas.width = video.videoWidth;
36
+ canvas.height = video.videoHeight;
37
+ canvas.getContext("2d")?.drawImage(video, 0, 0);
38
+ return canvas.toDataURL("image/jpeg", 0.7);
39
+ } finally {
40
+ stream.getTracks().forEach((track) => track.stop());
41
+ video.srcObject = null;
42
+ mask.remove();
43
+ }
44
+ }
45
+
46
+ // src/capture/screenshot-annotation.ts
47
+ var screenshot_annotation_exports = {};
48
+ __export(screenshot_annotation_exports, {
49
+ createScreenshotAnnotation: () => createScreenshotAnnotation
50
+ });
51
+ function createScreenshotAnnotation(imageDataUrl, container) {
52
+ return new Promise((resolve, reject) => {
53
+ const img = new Image();
54
+ img.onload = () => {
55
+ const wrap = document.createElement("div");
56
+ wrap.style.position = "relative";
57
+ wrap.style.display = "inline-block";
58
+ wrap.style.maxWidth = "100%";
59
+ const base = document.createElement("canvas");
60
+ const overlay = document.createElement("canvas");
61
+ const scale = Math.min(1, 720 / img.width);
62
+ const w = Math.round(img.width * scale);
63
+ const h = Math.round(img.height * scale);
64
+ for (const c of [base, overlay]) {
65
+ c.width = w;
66
+ c.height = h;
67
+ c.style.width = "100%";
68
+ c.style.height = "auto";
69
+ c.style.display = "block";
70
+ }
71
+ overlay.style.position = "absolute";
72
+ overlay.style.left = "0";
73
+ overlay.style.top = "0";
74
+ overlay.style.cursor = "crosshair";
75
+ const bctx = base.getContext("2d");
76
+ const octx = overlay.getContext("2d");
77
+ if (!bctx || !octx) {
78
+ reject(new Error("Canvas not supported"));
79
+ return;
80
+ }
81
+ bctx.drawImage(img, 0, 0, w, h);
82
+ wrap.appendChild(base);
83
+ wrap.appendChild(overlay);
84
+ container.appendChild(wrap);
85
+ let tool = "highlight";
86
+ let drawing = false;
87
+ let start = null;
88
+ const strokes = [];
89
+ const toLocal = (ev) => {
90
+ const rect = overlay.getBoundingClientRect();
91
+ const touch = "touches" in ev ? ev.touches[0] ?? ev.changedTouches[0] : null;
92
+ const clientX = touch ? touch.clientX : ev.clientX;
93
+ const clientY = touch ? touch.clientY : ev.clientY;
94
+ return {
95
+ x: (clientX - rect.left) / rect.width * w,
96
+ y: (clientY - rect.top) / rect.height * h
97
+ };
98
+ };
99
+ const redraw = () => {
100
+ octx.clearRect(0, 0, w, h);
101
+ for (const s of strokes) {
102
+ if (s.tool === "highlight" && s.points.length >= 2) {
103
+ const [a, b] = s.points;
104
+ octx.fillStyle = "rgba(255, 230, 0, 0.35)";
105
+ octx.fillRect(
106
+ Math.min(a.x, b.x),
107
+ Math.min(a.y, b.y),
108
+ Math.abs(b.x - a.x),
109
+ Math.abs(b.y - a.y)
110
+ );
111
+ } else if (s.tool === "arrow" && s.points.length >= 2) {
112
+ const [a, b] = s.points;
113
+ octx.strokeStyle = "#ef4444";
114
+ octx.lineWidth = 3;
115
+ octx.beginPath();
116
+ octx.moveTo(a.x, a.y);
117
+ octx.lineTo(b.x, b.y);
118
+ octx.stroke();
119
+ }
120
+ }
121
+ };
122
+ const onDown = (ev) => {
123
+ drawing = true;
124
+ start = toLocal(ev);
125
+ };
126
+ const onUp = (ev) => {
127
+ if (!drawing || !start) return;
128
+ drawing = false;
129
+ const end = toLocal(ev);
130
+ if (tool === "blur") {
131
+ const x = Math.min(start.x, end.x);
132
+ const y = Math.min(start.y, end.y);
133
+ const bw = Math.abs(end.x - start.x);
134
+ const bh = Math.abs(end.y - start.y);
135
+ if (bw >= 1 && bh >= 1) {
136
+ bctx.filter = "blur(8px)";
137
+ bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh);
138
+ bctx.filter = "none";
139
+ }
140
+ } else {
141
+ strokes.push({ tool, points: [start, end] });
142
+ }
143
+ start = null;
144
+ redraw();
145
+ };
146
+ overlay.addEventListener("mousedown", onDown);
147
+ overlay.addEventListener("mouseup", onUp);
148
+ overlay.addEventListener("touchstart", onDown, { passive: true });
149
+ overlay.addEventListener("touchend", onUp);
150
+ resolve({
151
+ canvas: base,
152
+ setTool(t) {
153
+ tool = t;
154
+ },
155
+ getDataUrl() {
156
+ const out = document.createElement("canvas");
157
+ out.width = w;
158
+ out.height = h;
159
+ const ctx = out.getContext("2d");
160
+ if (!ctx) return imageDataUrl;
161
+ ctx.drawImage(base, 0, 0);
162
+ ctx.drawImage(overlay, 0, 0);
163
+ return out.toDataURL("image/jpeg", 0.85);
164
+ },
165
+ destroy() {
166
+ overlay.removeEventListener("mousedown", onDown);
167
+ overlay.removeEventListener("mouseup", onUp);
168
+ overlay.removeEventListener("touchstart", onDown);
169
+ overlay.removeEventListener("touchend", onUp);
170
+ wrap.remove();
171
+ }
172
+ });
173
+ };
174
+ img.onerror = () => reject(new Error("Failed to load screenshot"));
175
+ img.src = imageDataUrl;
176
+ });
177
+ }
6
178
 
7
179
  // src/test-utils.ts
8
180
  async function triggerBug(opts = {}) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/test-utils.ts"],"names":[],"mappings":";;;;;;;AAuDA,eAAsB,UAAA,CAAW,IAAA,GAA0B,EAAC,EAA2B;AAErF,EAAU,OAAO,IAAA;AAqBnB;AAOO,SAAS,WAAW,QAAA,EAAsC;AAE/D,EAAU;AAEZ;AAGO,SAAS,gBAAgB,QAAA,EAAsC;AAEtE;AAOA,eAAsB,gBAAA,CAAiB,OAAA,GAAkC,EAAC,EAAoC;AAC5G,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,IAAa,GAAA;AACvC,EAAA,MAAM,OAAA,GAAU,KAAK,GAAA,EAAI;AACzB,EAAA,IAAI,eAAA,GAAiD,IAAA;AAErD,EAAA,OAAO,IAAA,CAAK,GAAA,EAAI,GAAI,OAAA,GAAU,SAAA,EAAW;AAQvC,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,MAAM,UAAA,CAAW,CAAA,EAAG,GAAG,CAAC,CAAA;AAAA,EAC7C;AAEA,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,KAAK,SAAA,CAAU,eAAe,CAAC,CAAA,CAAE,CAAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.cjs","sourcesContent":["/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
1
+ {"version":3,"sources":["../src/capture/display-capture.ts","../src/capture/screenshot-annotation.ts","../src/test-utils.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA;AAAA,EAAA,kBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAiBA,eAAsB,kBAAA,CACpB,eACA,aAAA,EACiB;AACjB,EAAA,MAAM,SAAS,MAAM,aAAA;AAKrB,EAAA,MAAM,UAAU,MAAA,CAAO,cAAA,KAAmB,CAAC,CAAA,EAAG,eAAc,CAAE,cAAA;AAC9D,EAAA,IAAI,OAAA,IAAW,YAAY,SAAA,EAAW;AACpC,IAAA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AAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.cjs","sourcesContent":["/**\n * Explicit, user-consented fallback for when the DOM capturer can't produce an\n * image: the browser's own picker asks the reporter to share this tab, one\n * frame is grabbed, and every track stops immediately. Loaded lazily — only a\n * reporter who clicks \"Share this tab instead\" pays for it.\n *\n * The caller requests the stream itself, synchronously inside the click\n * (getDisplayMedia needs the transient user activation, which an awaited\n * dynamic import would lose), and passes the pending stream in.\n *\n * A tab share is real pixels, so DOM-level redaction can't reach it. While the\n * frame is taken, a temporary stylesheet blacks out the same sensitive\n * selectors on the live page; the caller passes them (the always-on baseline\n * plus the host's lists) so this chunk imports nothing from the main bundle.\n * The reporter still reviews the preview before anything is sent.\n * Rejects with the browser's error (NotAllowedError when the reporter cancels).\n */\nexport async function grabMaskedTabFrame(\n pendingStream: Promise<MediaStream>,\n maskSelectors: readonly string[],\n): Promise<string> {\n const stream = await pendingStream;\n // Masking only reaches this page: refuse a window or the whole screen rather\n // than capture it unmasked. (A different browser tab also reports 'browser'\n // and can't be told apart here; preferCurrentTab makes this tab the default\n // choice, and the reporter reviews the preview before sending.)\n const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;\n if (surface && surface !== 'browser') {\n stream.getTracks().forEach((track) => track.stop());\n throw Object.assign(new Error('Only this tab can be captured'), { name: 'NotAllowedError' });\n }\n const selectors = maskSelectors.join(',');\n const mask = document.createElement('style');\n mask.setAttribute('data-mushi-capture-mask', '');\n mask.textContent =\n `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}` +\n `:is(${selectors}) *{visibility:hidden!important}`;\n document.head.appendChild(mask);\n const video = document.createElement('video');\n try {\n video.muted = true;\n video.srcObject = stream;\n await video.play();\n // Let the masked page reach the stream before grabbing a frame.\n await new Promise((resolve) => setTimeout(resolve, 150));\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d')?.drawImage(video, 0, 0);\n return canvas.toDataURL('image/jpeg', 0.7);\n } finally {\n stream.getTracks().forEach((track) => track.stop());\n video.srcObject = null;\n mask.remove();\n }\n}\n","/**\n * Lightweight canvas overlay for screenshot markup (highlight / blur / arrow).\n * Blur doubles as client-side PII redaction before upload.\n */\n\nexport type AnnotationTool = 'highlight' | 'blur' | 'arrow'\n\nexport interface AnnotationStroke {\n tool: AnnotationTool\n points: Array<{ x: number; y: number }>\n color?: string\n}\n\nexport interface AnnotationSession {\n canvas: HTMLCanvasElement\n getDataUrl(): string\n setTool(tool: AnnotationTool): void\n destroy(): void\n}\n\nexport function createScreenshotAnnotation(\n imageDataUrl: string,\n container: HTMLElement,\n): Promise<AnnotationSession> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => {\n const wrap = document.createElement('div')\n wrap.style.position = 'relative'\n wrap.style.display = 'inline-block'\n wrap.style.maxWidth = '100%'\n\n const base = document.createElement('canvas')\n const overlay = document.createElement('canvas')\n const scale = Math.min(1, 720 / img.width)\n const w = Math.round(img.width * scale)\n const h = Math.round(img.height * scale)\n for (const c of [base, overlay]) {\n c.width = w\n c.height = h\n c.style.width = '100%'\n c.style.height = 'auto'\n c.style.display = 'block'\n }\n overlay.style.position = 'absolute'\n overlay.style.left = '0'\n overlay.style.top = '0'\n overlay.style.cursor = 'crosshair'\n\n const bctx = base.getContext('2d')\n const octx = overlay.getContext('2d')\n if (!bctx || !octx) {\n reject(new Error('Canvas not supported'))\n return\n }\n bctx.drawImage(img, 0, 0, w, h)\n\n wrap.appendChild(base)\n wrap.appendChild(overlay)\n container.appendChild(wrap)\n\n let tool: AnnotationTool = 'highlight'\n let drawing = false\n let start: { x: number; y: number } | null = null\n const strokes: AnnotationStroke[] = []\n\n const toLocal = (ev: MouseEvent | TouchEvent): { x: number; y: number } => {\n const rect = overlay.getBoundingClientRect()\n // On `touchend`, `ev.touches` is empty (the finger lifted) — the final\n // coordinates live in `changedTouches`. Reading `touches[0]` there\n // would land every stroke at (0,0) on touch devices.\n const touch = 'touches' in ev ? (ev.touches[0] ?? ev.changedTouches[0]) : null\n const clientX = touch ? touch.clientX : (ev as MouseEvent).clientX\n const clientY = touch ? touch.clientY : (ev as MouseEvent).clientY\n return {\n x: ((clientX - rect.left) / rect.width) * w,\n y: ((clientY - rect.top) / rect.height) * h,\n }\n }\n\n // Blur is baked destructively into `base` (see onUp) so the exported\n // pixels contain no original PII — keep only highlight/arrow on the\n // re-drawable overlay here.\n const redraw = () => {\n octx.clearRect(0, 0, w, h)\n for (const s of strokes) {\n if (s.tool === 'highlight' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.fillStyle = 'rgba(255, 230, 0, 0.35)'\n octx.fillRect(\n Math.min(a.x, b.x),\n Math.min(a.y, b.y),\n Math.abs(b.x - a.x),\n Math.abs(b.y - a.y),\n )\n } else if (s.tool === 'arrow' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.strokeStyle = '#ef4444'\n octx.lineWidth = 3\n octx.beginPath()\n octx.moveTo(a.x, a.y)\n octx.lineTo(b.x, b.y)\n octx.stroke()\n }\n }\n }\n\n const onDown = (ev: MouseEvent | TouchEvent) => {\n drawing = true\n start = toLocal(ev)\n }\n const onUp = (ev: MouseEvent | TouchEvent) => {\n if (!drawing || !start) return\n drawing = false\n const end = toLocal(ev)\n if (tool === 'blur') {\n // Redaction must be irreversible in the exported image: bake an\n // opaque blurred patch into the base canvas, overwriting the\n // original pixels (the overlay's feathered alpha would otherwise\n // leak the source pixels around the region's edge).\n const x = Math.min(start.x, end.x)\n const y = Math.min(start.y, end.y)\n const bw = Math.abs(end.x - start.x)\n const bh = Math.abs(end.y - start.y)\n if (bw >= 1 && bh >= 1) {\n bctx.filter = 'blur(8px)'\n bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh)\n bctx.filter = 'none'\n }\n } else {\n strokes.push({ tool, points: [start, end] })\n }\n start = null\n redraw()\n }\n\n overlay.addEventListener('mousedown', onDown)\n overlay.addEventListener('mouseup', onUp)\n overlay.addEventListener('touchstart', onDown, { passive: true })\n overlay.addEventListener('touchend', onUp)\n\n resolve({\n canvas: base,\n setTool(t: AnnotationTool) {\n tool = t\n },\n getDataUrl() {\n const out = document.createElement('canvas')\n out.width = w\n out.height = h\n const ctx = out.getContext('2d')\n if (!ctx) return imageDataUrl\n ctx.drawImage(base, 0, 0)\n ctx.drawImage(overlay, 0, 0)\n return out.toDataURL('image/jpeg', 0.85)\n },\n destroy() {\n overlay.removeEventListener('mousedown', onDown)\n overlay.removeEventListener('mouseup', onUp)\n overlay.removeEventListener('touchstart', onDown)\n overlay.removeEventListener('touchend', onUp)\n wrap.remove()\n },\n })\n }\n img.onerror = () => reject(new Error('Failed to load screenshot'))\n img.src = imageDataUrl\n })\n}\n","// SPDX-License-Identifier: MIT\n// Copyright (c) 2024–2026 Kenji Sakuramoto (kensaurus) — Mushi Mushi\n/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
@@ -1,6 +1,178 @@
1
1
  import '@mushi-mushi/core';
2
2
 
3
- // src/capture/compress-screenshot.ts
3
+ var __defProp = Object.defineProperty;
4
+ var __export = (target, all) => {
5
+ for (var name in all)
6
+ __defProp(target, name, { get: all[name], enumerable: true });
7
+ };
8
+
9
+ // src/capture/display-capture.ts
10
+ var display_capture_exports = {};
11
+ __export(display_capture_exports, {
12
+ grabMaskedTabFrame: () => grabMaskedTabFrame
13
+ });
14
+ async function grabMaskedTabFrame(pendingStream, maskSelectors) {
15
+ const stream = await pendingStream;
16
+ const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;
17
+ if (surface && surface !== "browser") {
18
+ stream.getTracks().forEach((track) => track.stop());
19
+ throw Object.assign(new Error("Only this tab can be captured"), { name: "NotAllowedError" });
20
+ }
21
+ const selectors = maskSelectors.join(",");
22
+ const mask = document.createElement("style");
23
+ mask.setAttribute("data-mushi-capture-mask", "");
24
+ mask.textContent = `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}:is(${selectors}) *{visibility:hidden!important}`;
25
+ document.head.appendChild(mask);
26
+ const video = document.createElement("video");
27
+ try {
28
+ video.muted = true;
29
+ video.srcObject = stream;
30
+ await video.play();
31
+ await new Promise((resolve) => setTimeout(resolve, 150));
32
+ const canvas = document.createElement("canvas");
33
+ canvas.width = video.videoWidth;
34
+ canvas.height = video.videoHeight;
35
+ canvas.getContext("2d")?.drawImage(video, 0, 0);
36
+ return canvas.toDataURL("image/jpeg", 0.7);
37
+ } finally {
38
+ stream.getTracks().forEach((track) => track.stop());
39
+ video.srcObject = null;
40
+ mask.remove();
41
+ }
42
+ }
43
+
44
+ // src/capture/screenshot-annotation.ts
45
+ var screenshot_annotation_exports = {};
46
+ __export(screenshot_annotation_exports, {
47
+ createScreenshotAnnotation: () => createScreenshotAnnotation
48
+ });
49
+ function createScreenshotAnnotation(imageDataUrl, container) {
50
+ return new Promise((resolve, reject) => {
51
+ const img = new Image();
52
+ img.onload = () => {
53
+ const wrap = document.createElement("div");
54
+ wrap.style.position = "relative";
55
+ wrap.style.display = "inline-block";
56
+ wrap.style.maxWidth = "100%";
57
+ const base = document.createElement("canvas");
58
+ const overlay = document.createElement("canvas");
59
+ const scale = Math.min(1, 720 / img.width);
60
+ const w = Math.round(img.width * scale);
61
+ const h = Math.round(img.height * scale);
62
+ for (const c of [base, overlay]) {
63
+ c.width = w;
64
+ c.height = h;
65
+ c.style.width = "100%";
66
+ c.style.height = "auto";
67
+ c.style.display = "block";
68
+ }
69
+ overlay.style.position = "absolute";
70
+ overlay.style.left = "0";
71
+ overlay.style.top = "0";
72
+ overlay.style.cursor = "crosshair";
73
+ const bctx = base.getContext("2d");
74
+ const octx = overlay.getContext("2d");
75
+ if (!bctx || !octx) {
76
+ reject(new Error("Canvas not supported"));
77
+ return;
78
+ }
79
+ bctx.drawImage(img, 0, 0, w, h);
80
+ wrap.appendChild(base);
81
+ wrap.appendChild(overlay);
82
+ container.appendChild(wrap);
83
+ let tool = "highlight";
84
+ let drawing = false;
85
+ let start = null;
86
+ const strokes = [];
87
+ const toLocal = (ev) => {
88
+ const rect = overlay.getBoundingClientRect();
89
+ const touch = "touches" in ev ? ev.touches[0] ?? ev.changedTouches[0] : null;
90
+ const clientX = touch ? touch.clientX : ev.clientX;
91
+ const clientY = touch ? touch.clientY : ev.clientY;
92
+ return {
93
+ x: (clientX - rect.left) / rect.width * w,
94
+ y: (clientY - rect.top) / rect.height * h
95
+ };
96
+ };
97
+ const redraw = () => {
98
+ octx.clearRect(0, 0, w, h);
99
+ for (const s of strokes) {
100
+ if (s.tool === "highlight" && s.points.length >= 2) {
101
+ const [a, b] = s.points;
102
+ octx.fillStyle = "rgba(255, 230, 0, 0.35)";
103
+ octx.fillRect(
104
+ Math.min(a.x, b.x),
105
+ Math.min(a.y, b.y),
106
+ Math.abs(b.x - a.x),
107
+ Math.abs(b.y - a.y)
108
+ );
109
+ } else if (s.tool === "arrow" && s.points.length >= 2) {
110
+ const [a, b] = s.points;
111
+ octx.strokeStyle = "#ef4444";
112
+ octx.lineWidth = 3;
113
+ octx.beginPath();
114
+ octx.moveTo(a.x, a.y);
115
+ octx.lineTo(b.x, b.y);
116
+ octx.stroke();
117
+ }
118
+ }
119
+ };
120
+ const onDown = (ev) => {
121
+ drawing = true;
122
+ start = toLocal(ev);
123
+ };
124
+ const onUp = (ev) => {
125
+ if (!drawing || !start) return;
126
+ drawing = false;
127
+ const end = toLocal(ev);
128
+ if (tool === "blur") {
129
+ const x = Math.min(start.x, end.x);
130
+ const y = Math.min(start.y, end.y);
131
+ const bw = Math.abs(end.x - start.x);
132
+ const bh = Math.abs(end.y - start.y);
133
+ if (bw >= 1 && bh >= 1) {
134
+ bctx.filter = "blur(8px)";
135
+ bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh);
136
+ bctx.filter = "none";
137
+ }
138
+ } else {
139
+ strokes.push({ tool, points: [start, end] });
140
+ }
141
+ start = null;
142
+ redraw();
143
+ };
144
+ overlay.addEventListener("mousedown", onDown);
145
+ overlay.addEventListener("mouseup", onUp);
146
+ overlay.addEventListener("touchstart", onDown, { passive: true });
147
+ overlay.addEventListener("touchend", onUp);
148
+ resolve({
149
+ canvas: base,
150
+ setTool(t) {
151
+ tool = t;
152
+ },
153
+ getDataUrl() {
154
+ const out = document.createElement("canvas");
155
+ out.width = w;
156
+ out.height = h;
157
+ const ctx = out.getContext("2d");
158
+ if (!ctx) return imageDataUrl;
159
+ ctx.drawImage(base, 0, 0);
160
+ ctx.drawImage(overlay, 0, 0);
161
+ return out.toDataURL("image/jpeg", 0.85);
162
+ },
163
+ destroy() {
164
+ overlay.removeEventListener("mousedown", onDown);
165
+ overlay.removeEventListener("mouseup", onUp);
166
+ overlay.removeEventListener("touchstart", onDown);
167
+ overlay.removeEventListener("touchend", onUp);
168
+ wrap.remove();
169
+ }
170
+ });
171
+ };
172
+ img.onerror = () => reject(new Error("Failed to load screenshot"));
173
+ img.src = imageDataUrl;
174
+ });
175
+ }
4
176
 
5
177
  // src/test-utils.ts
6
178
  async function triggerBug(opts = {}) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/test-utils.ts"],"names":[],"mappings":";;;;;AAuDA,eAAsB,UAAA,CAAW,IAAA,GAA0B,EAAC,EAA2B;AAErF,EAAU,OAAO,IAAA;AAqBnB;AAOO,SAAS,WAAW,QAAA,EAAsC;AAE/D,EAAU;AAEZ;AAGO,SAAS,gBAAgB,QAAA,EAAsC;AAEtE;AAOA,eAAsB,gBAAA,CAAiB,OAAA,GAAkC,EAAC,EAAoC;AAC5G,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,IAAa,GAAA;AACvC,EAAA,MAAM,OAAA,GAAU,KAAK,GAAA,EAAI;AACzB,EAAA,IAAI,eAAA,GAAiD,IAAA;AAErD,EAAA,OAAO,IAAA,CAAK,GAAA,EAAI,GAAI,OAAA,GAAU,SAAA,EAAW;AAQvC,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,MAAM,UAAA,CAAW,CAAA,EAAG,GAAG,CAAC,CAAA;AAAA,EAC7C;AAEA,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,KAAK,SAAA,CAAU,eAAe,CAAC,CAAA,CAAE,CAAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.js","sourcesContent":["/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
1
+ {"version":3,"sources":["../src/capture/display-capture.ts","../src/capture/screenshot-annotation.ts","../src/test-utils.ts"],"names":[],"mappings":";;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA;AAAA,EAAA,kBAAA,EAAA,MAA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GAAA,EAAI,GAAI,OAAA,GAAU,SAAA,EAAW;AAQvC,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,MAAM,UAAA,CAAW,CAAA,EAAG,GAAG,CAAC,CAAA;AAAA,EAC7C;AAEA,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,KAAK,SAAA,CAAU,eAAe,CAAC,CAAA,CAAE,CAAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.js","sourcesContent":["/**\n * Explicit, user-consented fallback for when the DOM capturer can't produce an\n * image: the browser's own picker asks the reporter to share this tab, one\n * frame is grabbed, and every track stops immediately. Loaded lazily — only a\n * reporter who clicks \"Share this tab instead\" pays for it.\n *\n * The caller requests the stream itself, synchronously inside the click\n * (getDisplayMedia needs the transient user activation, which an awaited\n * dynamic import would lose), and passes the pending stream in.\n *\n * A tab share is real pixels, so DOM-level redaction can't reach it. While the\n * frame is taken, a temporary stylesheet blacks out the same sensitive\n * selectors on the live page; the caller passes them (the always-on baseline\n * plus the host's lists) so this chunk imports nothing from the main bundle.\n * The reporter still reviews the preview before anything is sent.\n * Rejects with the browser's error (NotAllowedError when the reporter cancels).\n */\nexport async function grabMaskedTabFrame(\n pendingStream: Promise<MediaStream>,\n maskSelectors: readonly string[],\n): Promise<string> {\n const stream = await pendingStream;\n // Masking only reaches this page: refuse a window or the whole screen rather\n // than capture it unmasked. (A different browser tab also reports 'browser'\n // and can't be told apart here; preferCurrentTab makes this tab the default\n // choice, and the reporter reviews the preview before sending.)\n const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;\n if (surface && surface !== 'browser') {\n stream.getTracks().forEach((track) => track.stop());\n throw Object.assign(new Error('Only this tab can be captured'), { name: 'NotAllowedError' });\n }\n const selectors = maskSelectors.join(',');\n const mask = document.createElement('style');\n mask.setAttribute('data-mushi-capture-mask', '');\n mask.textContent =\n `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}` +\n `:is(${selectors}) *{visibility:hidden!important}`;\n document.head.appendChild(mask);\n const video = document.createElement('video');\n try {\n video.muted = true;\n video.srcObject = stream;\n await video.play();\n // Let the masked page reach the stream before grabbing a frame.\n await new Promise((resolve) => setTimeout(resolve, 150));\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d')?.drawImage(video, 0, 0);\n return canvas.toDataURL('image/jpeg', 0.7);\n } finally {\n stream.getTracks().forEach((track) => track.stop());\n video.srcObject = null;\n mask.remove();\n }\n}\n","/**\n * Lightweight canvas overlay for screenshot markup (highlight / blur / arrow).\n * Blur doubles as client-side PII redaction before upload.\n */\n\nexport type AnnotationTool = 'highlight' | 'blur' | 'arrow'\n\nexport interface AnnotationStroke {\n tool: AnnotationTool\n points: Array<{ x: number; y: number }>\n color?: string\n}\n\nexport interface AnnotationSession {\n canvas: HTMLCanvasElement\n getDataUrl(): string\n setTool(tool: AnnotationTool): void\n destroy(): void\n}\n\nexport function createScreenshotAnnotation(\n imageDataUrl: string,\n container: HTMLElement,\n): Promise<AnnotationSession> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => {\n const wrap = document.createElement('div')\n wrap.style.position = 'relative'\n wrap.style.display = 'inline-block'\n wrap.style.maxWidth = '100%'\n\n const base = document.createElement('canvas')\n const overlay = document.createElement('canvas')\n const scale = Math.min(1, 720 / img.width)\n const w = Math.round(img.width * scale)\n const h = Math.round(img.height * scale)\n for (const c of [base, overlay]) {\n c.width = w\n c.height = h\n c.style.width = '100%'\n c.style.height = 'auto'\n c.style.display = 'block'\n }\n overlay.style.position = 'absolute'\n overlay.style.left = '0'\n overlay.style.top = '0'\n overlay.style.cursor = 'crosshair'\n\n const bctx = base.getContext('2d')\n const octx = overlay.getContext('2d')\n if (!bctx || !octx) {\n reject(new Error('Canvas not supported'))\n return\n }\n bctx.drawImage(img, 0, 0, w, h)\n\n wrap.appendChild(base)\n wrap.appendChild(overlay)\n container.appendChild(wrap)\n\n let tool: AnnotationTool = 'highlight'\n let drawing = false\n let start: { x: number; y: number } | null = null\n const strokes: AnnotationStroke[] = []\n\n const toLocal = (ev: MouseEvent | TouchEvent): { x: number; y: number } => {\n const rect = overlay.getBoundingClientRect()\n // On `touchend`, `ev.touches` is empty (the finger lifted) — the final\n // coordinates live in `changedTouches`. Reading `touches[0]` there\n // would land every stroke at (0,0) on touch devices.\n const touch = 'touches' in ev ? (ev.touches[0] ?? ev.changedTouches[0]) : null\n const clientX = touch ? touch.clientX : (ev as MouseEvent).clientX\n const clientY = touch ? touch.clientY : (ev as MouseEvent).clientY\n return {\n x: ((clientX - rect.left) / rect.width) * w,\n y: ((clientY - rect.top) / rect.height) * h,\n }\n }\n\n // Blur is baked destructively into `base` (see onUp) so the exported\n // pixels contain no original PII — keep only highlight/arrow on the\n // re-drawable overlay here.\n const redraw = () => {\n octx.clearRect(0, 0, w, h)\n for (const s of strokes) {\n if (s.tool === 'highlight' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.fillStyle = 'rgba(255, 230, 0, 0.35)'\n octx.fillRect(\n Math.min(a.x, b.x),\n Math.min(a.y, b.y),\n Math.abs(b.x - a.x),\n Math.abs(b.y - a.y),\n )\n } else if (s.tool === 'arrow' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.strokeStyle = '#ef4444'\n octx.lineWidth = 3\n octx.beginPath()\n octx.moveTo(a.x, a.y)\n octx.lineTo(b.x, b.y)\n octx.stroke()\n }\n }\n }\n\n const onDown = (ev: MouseEvent | TouchEvent) => {\n drawing = true\n start = toLocal(ev)\n }\n const onUp = (ev: MouseEvent | TouchEvent) => {\n if (!drawing || !start) return\n drawing = false\n const end = toLocal(ev)\n if (tool === 'blur') {\n // Redaction must be irreversible in the exported image: bake an\n // opaque blurred patch into the base canvas, overwriting the\n // original pixels (the overlay's feathered alpha would otherwise\n // leak the source pixels around the region's edge).\n const x = Math.min(start.x, end.x)\n const y = Math.min(start.y, end.y)\n const bw = Math.abs(end.x - start.x)\n const bh = Math.abs(end.y - start.y)\n if (bw >= 1 && bh >= 1) {\n bctx.filter = 'blur(8px)'\n bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh)\n bctx.filter = 'none'\n }\n } else {\n strokes.push({ tool, points: [start, end] })\n }\n start = null\n redraw()\n }\n\n overlay.addEventListener('mousedown', onDown)\n overlay.addEventListener('mouseup', onUp)\n overlay.addEventListener('touchstart', onDown, { passive: true })\n overlay.addEventListener('touchend', onUp)\n\n resolve({\n canvas: base,\n setTool(t: AnnotationTool) {\n tool = t\n },\n getDataUrl() {\n const out = document.createElement('canvas')\n out.width = w\n out.height = h\n const ctx = out.getContext('2d')\n if (!ctx) return imageDataUrl\n ctx.drawImage(base, 0, 0)\n ctx.drawImage(overlay, 0, 0)\n return out.toDataURL('image/jpeg', 0.85)\n },\n destroy() {\n overlay.removeEventListener('mousedown', onDown)\n overlay.removeEventListener('mouseup', onUp)\n overlay.removeEventListener('touchstart', onDown)\n overlay.removeEventListener('touchend', onUp)\n wrap.remove()\n },\n })\n }\n img.onerror = () => reject(new Error('Failed to load screenshot'))\n img.src = imageDataUrl\n })\n}\n","// SPDX-License-Identifier: MIT\n// Copyright (c) 2024–2026 Kenji Sakuramoto (kensaurus) — Mushi Mushi\n/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
@@ -28,8 +28,18 @@ interface ScreenshotCapture {
28
28
  interface ScreenshotCaptureOptions {
29
29
  privacy?: MushiPrivacyConfig;
30
30
  /** Callback invoked when capture fails (taint, security policy, etc.). */
31
- onFailed?: (reason: 'taint' | 'error') => void;
31
+ onFailed?: (reason: ScreenshotFailureReason) => void;
32
32
  }
33
+ /**
34
+ * Why a capture produced no image. Also the `detail.reason` of the
35
+ * `mushi:screenshot_failed` document event.
36
+ * - taint: cross-origin content made the canvas unreadable
37
+ * - timeout: the SVG never loaded or errored within 5 s
38
+ * - unsupported: no 2D canvas, or the engine rasterised nothing (WebKit)
39
+ * - csp: the host's Content-Security-Policy img-src blocks data: images
40
+ * - error: anything else
41
+ */
42
+ type ScreenshotFailureReason = 'taint' | 'timeout' | 'unsupported' | 'csp' | 'error';
33
43
  declare function createScreenshotCapture(options?: ScreenshotCaptureOptions): ScreenshotCapture;
34
44
 
35
45
  interface PerformanceCapture {
@@ -60,4 +70,4 @@ interface TimelineCapture {
60
70
  }
61
71
  declare function createTimelineCapture(): TimelineCapture;
62
72
 
63
- export { type ConsoleCapture as C, type ElementSelector as E, type NetworkCapture as N, type PerformanceCapture as P, type ScreenshotCapture as S, type TimelineCapture as T, createElementSelector as a, createNetworkCapture as b, createConsoleCapture as c, createPerformanceCapture as d, createScreenshotCapture as e, createTimelineCapture as f };
73
+ export { type ConsoleCapture as C, type ElementSelector as E, type NetworkCapture as N, type PerformanceCapture as P, type ScreenshotCapture as S, type TimelineCapture as T, createElementSelector as a, createNetworkCapture as b, createConsoleCapture as c, createPerformanceCapture as d, createScreenshotCapture as e, createTimelineCapture as f, type ScreenshotFailureReason as g };