makethisbetter 1.28.2 → 1.28.3

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.
@@ -5,7 +5,7 @@
5
5
  <button class="mtb-frustration-tell">${d(e.frustration.action)}</button>
6
6
  <button class="mtb-frustration-dismiss">${d(e.frustration.dismiss)}</button>
7
7
  </div>
8
- `,this.el.querySelector(".mtb-frustration-tell").addEventListener("click",r.onTell),this.el.querySelector(".mtb-frustration-dismiss").addEventListener("click",r.onDismiss),t.append(this.el),this.autoHideTimer=setTimeout(r.onAutoHide,He)}destroy(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.el.remove()}}const Fe=400;class Lt{constructor(t,e,r=()=>Date.now()){this.bornAt=Date.now(),this.bornAt=r(),this.onClick=()=>{r()-this.bornAt<Fe||e()},this.el=t.el("div","mtb-dim mtb-dim-clickable"),this.el.addEventListener("click",this.onClick),t.append(this.el)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}function S(){return window.matchMedia?.("(pointer: coarse)").matches??!1}class Be{constructor(){this.applied=!1,this.previousPadding="",this.previousTransition=""}reserve(t){if(this.applied||t<=0)return;this.applied=!0;const e=document.body.style;this.previousPadding=e.paddingTop,this.previousTransition=e.transition;const r=parseFloat(getComputedStyle(document.body).paddingTop)||0;e.transition="none",e.paddingTop=`${r+t}px`}release(){if(!this.applied)return;this.applied=!1;const t=document.body.style;t.paddingTop=this.previousPadding,t.transition=this.previousTransition}isApplied(){return this.applied}}const Pt=["wheel","touchmove"],ze=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," "]);function Oe(i){for(const t of i.composedPath()){if(!(t instanceof Element))continue;const e=getComputedStyle(t);if(/auto|scroll/.test(`${e.overflowY} ${e.overflowX}`)&&(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth))return!0}return!1}function Ue(i,t){const e=i.tagName;return!!(e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||i instanceof HTMLElement&&i.isContentEditable||t===" "&&(e==="BUTTON"||e==="SUMMARY"))}function $e(){const i=e=>{Oe(e)||e.cancelable&&e.preventDefault()},t=e=>{if(!(e instanceof KeyboardEvent)||!ze.has(e.key))return;const r=e.composedPath()[0];r instanceof Element&&Ue(r,e.key)||e.cancelable&&e.preventDefault()};for(const e of Pt)window.addEventListener(e,i,{capture:!0,passive:!1});return window.addEventListener("keydown",t,{capture:!0}),{release(){for(const e of Pt)window.removeEventListener(e,i,{capture:!0});window.removeEventListener("keydown",t,{capture:!0})}}}const je=44;class qe{constructor(t,e,r,n,s="right",o=!0){this.currentMode="markup",this.handlePointerMove=a=>{if(a.pointerType!=="mouse")return;const l=this.hintBarEl.getBoundingClientRect(),c=a.clientX>=l.left&&a.clientX<=l.right&&a.clientY>=l.top&&a.clientY<=l.bottom;this.hintBarEl.classList.toggle("mtb-hint-bar--under-pointer",c)},this.touchHintDismissListening=!1,this.dismissTouchHint=()=>{this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.stopTouchHintDismissListening()},this.messages=e,this.touch=S(),this.hintBarEl=t.el("div","mtb-hint-bar"),this.hintBarEl.innerHTML=`<span class="mtb-toolbar-hint">${d(this.idleHint())}</span>`,this.touch&&!o&&this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.el=t.el("div","mtb-toolbar"),s==="left"&&this.el.classList.add("left"),this.el.innerHTML=this.buildHTML(e),t.append(this.hintBarEl,this.el),this.host=t.host,this.host.setAttribute("data-mtb-toolbar",""),this.hintTextEl=this.hintBarEl.querySelector(".mtb-toolbar-hint"),this.markupBtn=this.el.querySelector(".mtb-toolbar-mode-markup"),this.recordBtn=this.el.querySelector(".mtb-toolbar-mode-record"),this.markupBtn.addEventListener("click",()=>{this.setMode("markup"),n?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),n?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",r),document.addEventListener("pointermove",this.handlePointerMove),this.touch&&o&&(document.addEventListener("pointerdown",this.dismissTouchHint,!0),this.touchHintDismissListening=!0)}stopTouchHintDismissListening(){this.touchHintDismissListening&&(this.touchHintDismissListening=!1,document.removeEventListener("pointerdown",this.dismissTouchHint,!0))}buildHTML(t){return`
8
+ `,this.el.querySelector(".mtb-frustration-tell").addEventListener("click",r.onTell),this.el.querySelector(".mtb-frustration-dismiss").addEventListener("click",r.onDismiss),t.append(this.el),this.autoHideTimer=setTimeout(r.onAutoHide,He)}destroy(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.el.remove()}}const Fe=400;class Lt{constructor(t,e,r=()=>Date.now()){this.bornAt=Date.now(),this.bornAt=r(),this.onClick=()=>{r()-this.bornAt<Fe||e()},this.el=t.el("div","mtb-dim mtb-dim-clickable"),this.el.addEventListener("click",this.onClick),t.append(this.el)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}function S(){return window.matchMedia?.("(pointer: coarse)").matches??!1}class Be{constructor(){this.applied=!1,this.previousPadding="",this.previousTransition=""}reserve(t){if(this.applied||t<=0)return;this.applied=!0;const e=document.body.style;this.previousPadding=e.paddingTop,this.previousTransition=e.transition;const r=parseFloat(getComputedStyle(document.body).paddingTop)||0;e.transition="none",e.paddingTop=`${r+t}px`}release(){if(!this.applied)return;this.applied=!1;const t=document.body.style;t.paddingTop=this.previousPadding,t.transition=this.previousTransition}isApplied(){return this.applied}}const Pt=["wheel","touchmove"],ze=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," "]);function Oe(i){for(const t of i.composedPath()){if(!(t instanceof Element))continue;const e=getComputedStyle(t);if(/auto|scroll/.test(`${e.overflowY} ${e.overflowX}`)&&(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth))return!0}return!1}function Ue(i,t){const e=i.tagName;return!!(e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||i instanceof HTMLElement&&i.isContentEditable||t===" "&&(e==="BUTTON"||e==="SUMMARY"))}function $e(){const i=e=>{Oe(e)||e.cancelable&&e.preventDefault()},t=e=>{if(!(e instanceof KeyboardEvent)||!ze.has(e.key))return;const r=e.composedPath()[0];r instanceof Element&&Ue(r,e.key)||e.cancelable&&e.preventDefault()};for(const e of Pt)window.addEventListener(e,i,{capture:!0,passive:!1});return window.addEventListener("keydown",t,{capture:!0}),{release(){for(const e of Pt)window.removeEventListener(e,i,{capture:!0});window.removeEventListener("keydown",t,{capture:!0})}}}const je=44;class qe{constructor(t,e,r,n,s="right",o=!0){this.currentMode="markup",this.handlePointerMove=a=>{if(a.pointerType!=="mouse")return;const c=this.hintBarEl.getBoundingClientRect(),l=a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom;this.hintBarEl.classList.toggle("mtb-hint-bar--under-pointer",l)},this.touchHintDismissListening=!1,this.dismissTouchHint=()=>{this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.stopTouchHintDismissListening()},this.messages=e,this.touch=S(),this.hintBarEl=t.el("div","mtb-hint-bar"),this.hintBarEl.innerHTML=`<span class="mtb-toolbar-hint">${d(this.idleHint())}</span>`,this.touch&&!o&&this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.el=t.el("div","mtb-toolbar"),s==="left"&&this.el.classList.add("left"),this.el.innerHTML=this.buildHTML(e),t.append(this.hintBarEl,this.el),this.host=t.host,this.host.setAttribute("data-mtb-toolbar",""),this.hintTextEl=this.hintBarEl.querySelector(".mtb-toolbar-hint"),this.markupBtn=this.el.querySelector(".mtb-toolbar-mode-markup"),this.recordBtn=this.el.querySelector(".mtb-toolbar-mode-record"),this.markupBtn.addEventListener("click",()=>{this.setMode("markup"),n?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),n?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",r),document.addEventListener("pointermove",this.handlePointerMove),this.touch&&o&&(document.addEventListener("pointerdown",this.dismissTouchHint,!0),this.touchHintDismissListening=!0)}stopTouchHintDismissListening(){this.touchHintDismissListening&&(this.touchHintDismissListening=!1,document.removeEventListener("pointerdown",this.dismissTouchHint,!0))}buildHTML(t){return`
9
9
  <div class="mtb-toolbar-modes">
10
10
  <button class="mtb-toolbar-mode-btn mtb-toolbar-mode-markup active" aria-label="${d(t.toolbar.markup)}" title="${d(t.toolbar.markup)}">
11
11
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><line x1="12" y1="3" x2="12" y2="7"/><line x1="12" y1="17" x2="12" y2="21"/><line x1="3" y1="12" x2="7" y2="12"/><line x1="17" y1="12" x2="21" y2="12"/></svg><span class="mtb-toolbar-label">${d(t.toolbar.markup)}</span>
@@ -20,7 +20,7 @@
20
20
  <path d="M18 6L6 18M6 6l12 12"/>
21
21
  </svg><span class="mtb-toolbar-label">${d(t.toolbar.exit)}</span>
22
22
  </button>
23
- `}idleHint(){return this.touch?this.messages.toolbar.hintTouch:this.messages.toolbar.hint}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintTextEl.textContent=this.idleHint()):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintTextEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}height(){return this.el.getBoundingClientRect().height||je}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),this.stopTouchHintDismissListening(),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class We{constructor(t,e){this.handlers=e,this.overlayEl=t.el("div","mtb-overlay"),this.onPointerDown=r=>{const n=r;if(n.isPrimary){try{this.overlayEl.setPointerCapture(n.pointerId)}catch{}this.handlers.onPointerDown(n)}},this.onPointerMove=r=>{const n=r;n.isPrimary&&this.handlers.onPointerMove(n)},this.onPointerUp=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerUp(n))},this.onPointerCancel=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerCancel(n))},this.overlayEl.addEventListener("pointerdown",this.onPointerDown),this.overlayEl.addEventListener("pointermove",this.onPointerMove),this.overlayEl.addEventListener("pointerup",this.onPointerUp),this.overlayEl.addEventListener("pointercancel",this.onPointerCancel),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}releaseCapture(t){try{this.overlayEl.releasePointerCapture(t)}catch{}}destroy(){this.overlayEl.removeEventListener("pointerdown",this.onPointerDown),this.overlayEl.removeEventListener("pointermove",this.onPointerMove),this.overlayEl.removeEventListener("pointerup",this.onPointerUp),this.overlayEl.removeEventListener("pointercancel",this.onPointerCancel),this.overlayEl.remove(),this.dimEl.remove()}}class Ye{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.tooltipEl=t.el("div","mtb-highlight-tooltip"),this.hide(),t.append(this.highlightEl,this.tooltipEl)}highlight(t){const e=t.getBoundingClientRect();this.highlightEl.style.top=`${e.top-2}px`,this.highlightEl.style.left=`${e.left-2}px`,this.highlightEl.style.width=`${e.width+4}px`,this.highlightEl.style.height=`${e.height+4}px`,this.highlightEl.style.display="block",this.showTooltip(t,e)}showTooltip(t,e){this.tooltipEl.textContent=kt(t);const r=e.top<30;this.tooltipEl.classList.toggle("below",r),this.tooltipEl.style.left=`${e.left+e.width/2}px`,this.tooltipEl.style.top=r?`${e.bottom+8}px`:`${e.top-8}px`,this.tooltipEl.style.display="block"}select(){this.highlightEl.classList.add("selected"),this.tooltipEl.style.display="none"}hide(){this.highlightEl.style.display="none",this.highlightEl.classList.remove("selected"),this.tooltipEl.style.display="none"}destroy(){this.highlightEl.remove(),this.tooltipEl.remove()}}function Ve(i,t,e){return{left:i.left,top:i.top,scaleX:t/i.width,scaleY:e/i.height}}function G(i,t){return(t-i.left)*i.scaleX}function Z(i,t){return(t-i.top)*i.scaleY}function Xe(i,t){return{left:G(i,t.left),top:Z(i,t.top),width:t.width*i.scaleX,height:t.height*i.scaleY}}function Ke(){return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function Ge(i,t){return{x:i.x-t.x,y:i.y-t.y}}function $(i){let t=0,e=0,r=i;for(;r&&r!==document.body;)r instanceof HTMLElement&&(t+=r.scrollLeft,e+=r.scrollTop),r=Qt(r);return{x:t,y:e}}function Qt(i){if(i.parentElement)return i.parentElement;const t=i.getRootNode();return t instanceof ShadowRoot?t.host:null}function Dt(i){const t=$(i);return{x:t.x+window.scrollX,y:t.y+window.scrollY}}class Ze{constructor(t){this.pins=[],this.shadow=t}addPin(t,e){const r=this.shadow.el("div","mtb-pin");r.style.top=`${e}px`,r.style.left=`${t}px`,this.shadow.append(r),this.pins.push(r)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const te="#059669",T={color:"var(--mtb-brand-primary)",width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 0 1px rgba(255, 255, 255, 0.95)) drop-shadow(0 1px 2px rgba(15, 23, 42, 0.72))"};class Je{constructor(t){this.currentPath=null,this.currentPoints=[],this.currentAnchor=Qe(),this.isDrawing=!1,this.committed=[],this.redoStack=[],this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,e){this.isDrawing=!0,this.currentPoints=[[t,e]],this.currentAnchor=ti(t,e),this.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,e){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,e]),this.currentPath.setAttribute("d",lt(this.currentPoints)))}getCurrentSpan(){const[t]=this.currentPoints;if(!t)return 0;let e=0;for(const[r,n]of this.currentPoints)e=Math.max(e,Math.hypot(r-t[0],n-t[1]));return e}commitStroke(){return!this.isDrawing||!this.currentPath?!1:(this.isDrawing=!1,this.committed.push({path:this.currentPath,d:lt(this.currentPoints),points:this.currentPoints,anchor:this.currentAnchor}),this.redoStack=[],this.currentPath=null,this.currentPoints=[],!0)}cancelCurrentDraw(){this.currentPath?.remove(),this.currentPath=null,this.isDrawing=!1,this.currentPoints=[]}undo(){const t=this.committed.pop();return t?(t.path.remove(),this.redoStack.push({d:t.d,points:t.points,anchor:t.anchor}),!0):!1}redo(){const t=this.redoStack.pop();if(!t)return!1;const e=this.createPath();return e.setAttribute("d",t.d),this.svg.appendChild(e),this.committed.push({path:e,d:t.d,points:t.points,anchor:t.anchor}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){const[t]=this.committed;if(!t)return null;const e=this.committed.map(s=>ei(s.points,{x:s.anchor.offset.x-t.anchor.offset.x,y:s.anchor.offset.y-t.anchor.offset.y})),[r,n]=ii(e.flat());return{type:"draw",x:r,y:n,drawPath:e.map(lt).join(" "),captureOffsetX:t.anchor.offset.x,captureOffsetY:t.anchor.offset.y}}viewportDrift(){const[t]=this.committed;return t?{x:window.scrollX-t.anchor.pageScroll.x,y:window.scrollY-t.anchor.pageScroll.y}:{x:0,y:0}}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.currentPath=null,this.isDrawing=!1,this.currentPoints=[],this.committed=[],this.redoStack=[]}isCurrentlyDrawing(){return this.isDrawing}destroy(){this.svg.remove()}createPath(){const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("fill","none"),t.setAttribute("stroke",T.color),t.setAttribute("stroke-width",T.width),t.setAttribute("stroke-linecap",T.linecap),t.setAttribute("stroke-linejoin",T.linejoin),t.setAttribute("style",`filter:${T.filter}`),t}}function lt(i){if(i.length===0)return"";const[t,e]=i[0];let r=`M ${t} ${e}`;for(let n=1;n<i.length;n++){const[s,o]=i[n];r+=` L ${s} ${o}`}return r}function Qe(){return{offset:{x:0,y:0},pageScroll:{x:0,y:0}}}function ti(i,t){const e={x:window.scrollX,y:window.scrollY},r=$(V(i,t));return{offset:{x:r.x+e.x,y:r.y+e.y},pageScroll:e}}function ei(i,t){return t.x===0&&t.y===0?i:i.map(([e,r])=>[e+t.x,r+t.y])}function ii(i){const t=i.map(s=>s[0]),e=i.map(s=>s[1]),r=(Math.min(...t)+Math.max(...t))/2,n=(Math.min(...e)+Math.max(...e))/2;return[r,n]}const nt="rr-block",O="rr-mask",ri=`.${nt}, .${O}`;function st(i){return i.closest(ri)!==null}function Et(i){const t=i.getAttribute("role")?.trim().split(/\s+/)[0];return t&&/^[a-z][a-z0-9-]*$/i.test(t)?t:i.tagName.toLowerCase()}function ee(i){return i.tagName.toLowerCase()}const ni=10;function Mt(i){return st(i)?{name:Et(i),text:"",selector:ee(i)}:{name:kt(i),text:i.textContent?.trim().slice(0,200)??"",selector:Jt(i)}}class si{constructor(t,e,r){this.messages=e,this.handlers=r,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.touch=S(),this.highlighter=new Ye(t),this.pinMarker=new Ze(t),this.drawLayer=new Je(t),this.overlay=new We(t,{onPointerDown:n=>this.handlePointerDown(n),onPointerMove:n=>this.handlePointerMove(n),onPointerUp:n=>this.handlePointerUp(n),onPointerCancel:()=>{this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handlePointerDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handlePointerMove(t){if(this.drawLayer.isCurrentlyDrawing()){this.cancelPendingHighlight(),this.drawLayer.continueDraw(t.clientX,t.clientY),this.highlighter.hide();return}this.lastMoveX=t.clientX,this.lastMoveY=t.clientY,this.pendingHighlightFrame===null&&(this.pendingHighlightFrame=requestAnimationFrame(()=>{this.pendingHighlightFrame=null,this.updateHighlight()}))}updateHighlight(){if(!this.interactionActive||this.drawLayer.isCurrentlyDrawing()||this.drawSessionActive())return;const t=V(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handlePointerUp(t){this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(t)}finishStroke(t){if(this.drawLayer.getCurrentSpan()>=ni){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const e=V(t.clientX,t.clientY),r=e?Mt(e):null,n=r?.name??this.messages.annotation.element,s=e?.getBoundingClientRect(),o=Dt(e),a={type:"pin",x:t.clientX,y:t.clientY,targetSelector:r?.selector,targetText:r?.text??"",targetName:n,targetRect:s?{top:s.top,left:s.left,width:s.width,height:s.height,bottom:s.bottom}:void 0,captureOffsetX:o.x,captureOffsetY:o.y};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(a,n)}undoDraw(){this.drawLayer.undo()}redoDraw(){this.drawLayer.redo()}canUndoDraw(){return this.drawLayer.canUndo()}canRedoDraw(){return this.drawLayer.canRedo()}hasDrawStrokes(){return this.drawLayer.hasStrokes()}drawSessionActive(){return this.drawLayer.hasStrokes()||this.drawLayer.canRedo()}getDrawAnnotation(){const t=this.drawLayer.getAnnotation();if(!t)return null;const e=this.drawLayer.viewportDrift(),r=V(t.x-e.x,t.y-e.y);if(!r)return t;const n=r.getBoundingClientRect(),s=Dt(r),o=s.x-(t.captureOffsetX??0),a=s.y-(t.captureOffsetY??0),l=Mt(r);return{...t,targetSelector:l.selector,targetText:l.text,targetName:l.name,targetRect:{top:n.top+a,left:n.left+o,width:n.width,height:n.height,bottom:n.bottom+a}}}clearDraw(){this.drawLayer.clearAll()}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy())}hideHighlight(){this.highlighter.hide()}destroy(){this.dismissInteraction(),this.highlighter.destroy(),this.pinMarker.destroy(),this.drawLayer.destroy()}}const oi=140;class ai{constructor(){this.onChange=null,this.timer=null,this.lastReading=null,this.handler=()=>{this.timer!==null&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null;const t=this.current();if(t===this.lastReading){this.lastReading=null,this.onChange?.(t);return}this.lastReading=t,this.handler()},oi)}}current(){const t=window.visualViewport;if(!t||t.height<=0)return 0;const e=Math.round(window.innerHeight-(t.height+t.offsetTop));return Math.min(Math.max(0,e),window.innerHeight)}observe(t){const e=window.visualViewport;e&&(this.onChange=t,e.addEventListener("resize",this.handler),e.addEventListener("scroll",this.handler))}stop(){const t=window.visualViewport;this.onChange=null,this.lastReading=null,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),t&&(t.removeEventListener("resize",this.handler),t.removeEventListener("scroll",this.handler))}}const li=480;function ci(){return window.innerWidth<=li}class ie{constructor(t){this.el=t,this.inset=new ai}apply(){return ci()?(this.el.style.left="",this.el.style.top="",this.el.style.maxHeight="",this.lift(this.inset.current()),this.inset.observe(t=>this.lift(t)),!0):!1}release(){this.inset.stop()}lift(t){const e=Math.max(0,window.innerHeight-this.el.offsetHeight),r=Math.min(t,e);this.el.style.bottom=r>0?`${r}px`:""}}class hi{constructor(t,e){this.onSubmit=e.onSubmit,this.submitLabel=e.messages.draw.submit,this.messages=e.messages,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(e.messages),t.append(this.el),this.sheet=new ie(this.el),this.sheet.apply(),this.input=this.el.querySelector(".mtb-draw-input"),this.undoBtn=this.el.querySelector(".mtb-draw-undo"),this.redoBtn=this.el.querySelector(".mtb-draw-redo"),this.submitBtn=this.el.querySelector(".mtb-draw-submit"),this.undoBtn.addEventListener("click",e.onUndo),this.redoBtn.addEventListener("click",e.onRedo),this.el.querySelector(".mtb-draw-cancel").addEventListener("click",e.onCancel),this.submitBtn.addEventListener("click",()=>this.submit()),e.onActivity&&this.input.addEventListener("input",e.onActivity),this.input.addEventListener("keydown",r=>{xt(r)||r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),this.submit())}),this.input.focus({preventScroll:!0})}buildHTML(t){return`
23
+ `}idleHint(){return this.touch?this.messages.toolbar.hintTouch:this.messages.toolbar.hint}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintTextEl.textContent=this.idleHint()):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintTextEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}height(){return this.el.getBoundingClientRect().height||je}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),this.stopTouchHintDismissListening(),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class We{constructor(t,e){this.handlers=e,this.overlayEl=t.el("div","mtb-overlay"),this.onPointerDown=r=>{const n=r;if(n.isPrimary){try{this.overlayEl.setPointerCapture(n.pointerId)}catch{}this.handlers.onPointerDown(n)}},this.onPointerMove=r=>{const n=r;n.isPrimary&&this.handlers.onPointerMove(n)},this.onPointerUp=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerUp(n))},this.onPointerCancel=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerCancel(n))},this.overlayEl.addEventListener("pointerdown",this.onPointerDown),this.overlayEl.addEventListener("pointermove",this.onPointerMove),this.overlayEl.addEventListener("pointerup",this.onPointerUp),this.overlayEl.addEventListener("pointercancel",this.onPointerCancel),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}releaseCapture(t){try{this.overlayEl.releasePointerCapture(t)}catch{}}destroy(){this.overlayEl.removeEventListener("pointerdown",this.onPointerDown),this.overlayEl.removeEventListener("pointermove",this.onPointerMove),this.overlayEl.removeEventListener("pointerup",this.onPointerUp),this.overlayEl.removeEventListener("pointercancel",this.onPointerCancel),this.overlayEl.remove(),this.dimEl.remove()}}class Ye{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.tooltipEl=t.el("div","mtb-highlight-tooltip"),this.hide(),t.append(this.highlightEl,this.tooltipEl)}highlight(t){const e=t.getBoundingClientRect();this.highlightEl.style.top=`${e.top-2}px`,this.highlightEl.style.left=`${e.left-2}px`,this.highlightEl.style.width=`${e.width+4}px`,this.highlightEl.style.height=`${e.height+4}px`,this.highlightEl.style.display="block",this.showTooltip(t,e)}showTooltip(t,e){this.tooltipEl.textContent=kt(t);const r=e.top<30;this.tooltipEl.classList.toggle("below",r),this.tooltipEl.style.left=`${e.left+e.width/2}px`,this.tooltipEl.style.top=r?`${e.bottom+8}px`:`${e.top-8}px`,this.tooltipEl.style.display="block"}select(){this.highlightEl.classList.add("selected"),this.tooltipEl.style.display="none"}hide(){this.highlightEl.style.display="none",this.highlightEl.classList.remove("selected"),this.tooltipEl.style.display="none"}destroy(){this.highlightEl.remove(),this.tooltipEl.remove()}}function Ve(i,t,e){return{left:i.left,top:i.top,scaleX:t/i.width,scaleY:e/i.height}}function G(i,t){return(t-i.left)*i.scaleX}function Z(i,t){return(t-i.top)*i.scaleY}function Xe(i,t){return{left:G(i,t.left),top:Z(i,t.top),width:t.width*i.scaleX,height:t.height*i.scaleY}}function Ke(){return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function Ge(i,t){return{x:i.x-t.x,y:i.y-t.y}}function $(i){let t=0,e=0,r=i;for(;r&&r!==document.body;)r instanceof HTMLElement&&(t+=r.scrollLeft,e+=r.scrollTop),r=Qt(r);return{x:t,y:e}}function Qt(i){if(i.parentElement)return i.parentElement;const t=i.getRootNode();return t instanceof ShadowRoot?t.host:null}function Dt(i){const t=$(i);return{x:t.x+window.scrollX,y:t.y+window.scrollY}}class Ze{constructor(t){this.pins=[],this.shadow=t}addPin(t,e){const r=this.shadow.el("div","mtb-pin");r.style.top=`${e}px`,r.style.left=`${t}px`,this.shadow.append(r),this.pins.push(r)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const te="#059669",T={color:"var(--mtb-brand-primary)",width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 0 1px rgba(255, 255, 255, 0.95)) drop-shadow(0 1px 2px rgba(15, 23, 42, 0.72))"};class Je{constructor(t){this.currentPath=null,this.currentPoints=[],this.currentAnchor=Qe(),this.isDrawing=!1,this.committed=[],this.redoStack=[],this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,e){this.isDrawing=!0,this.currentPoints=[[t,e]],this.currentAnchor=ti(t,e),this.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,e){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,e]),this.currentPath.setAttribute("d",lt(this.currentPoints)))}getCurrentSpan(){const[t]=this.currentPoints;if(!t)return 0;let e=0;for(const[r,n]of this.currentPoints)e=Math.max(e,Math.hypot(r-t[0],n-t[1]));return e}commitStroke(){return!this.isDrawing||!this.currentPath?!1:(this.isDrawing=!1,this.committed.push({path:this.currentPath,d:lt(this.currentPoints),points:this.currentPoints,anchor:this.currentAnchor}),this.redoStack=[],this.currentPath=null,this.currentPoints=[],!0)}cancelCurrentDraw(){this.currentPath?.remove(),this.currentPath=null,this.isDrawing=!1,this.currentPoints=[]}undo(){const t=this.committed.pop();return t?(t.path.remove(),this.redoStack.push({d:t.d,points:t.points,anchor:t.anchor}),!0):!1}redo(){const t=this.redoStack.pop();if(!t)return!1;const e=this.createPath();return e.setAttribute("d",t.d),this.svg.appendChild(e),this.committed.push({path:e,d:t.d,points:t.points,anchor:t.anchor}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){const[t]=this.committed;if(!t)return null;const e=this.committed.map(s=>ei(s.points,{x:s.anchor.offset.x-t.anchor.offset.x,y:s.anchor.offset.y-t.anchor.offset.y})),[r,n]=ii(e.flat());return{type:"draw",x:r,y:n,drawPath:e.map(lt).join(" "),captureOffsetX:t.anchor.offset.x,captureOffsetY:t.anchor.offset.y}}viewportDrift(){const[t]=this.committed;return t?{x:window.scrollX-t.anchor.pageScroll.x,y:window.scrollY-t.anchor.pageScroll.y}:{x:0,y:0}}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.currentPath=null,this.isDrawing=!1,this.currentPoints=[],this.committed=[],this.redoStack=[]}isCurrentlyDrawing(){return this.isDrawing}destroy(){this.svg.remove()}createPath(){const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("fill","none"),t.setAttribute("stroke",T.color),t.setAttribute("stroke-width",T.width),t.setAttribute("stroke-linecap",T.linecap),t.setAttribute("stroke-linejoin",T.linejoin),t.setAttribute("style",`filter:${T.filter}`),t}}function lt(i){if(i.length===0)return"";const[t,e]=i[0];let r=`M ${t} ${e}`;for(let n=1;n<i.length;n++){const[s,o]=i[n];r+=` L ${s} ${o}`}return r}function Qe(){return{offset:{x:0,y:0},pageScroll:{x:0,y:0}}}function ti(i,t){const e={x:window.scrollX,y:window.scrollY},r=$(V(i,t));return{offset:{x:r.x+e.x,y:r.y+e.y},pageScroll:e}}function ei(i,t){return t.x===0&&t.y===0?i:i.map(([e,r])=>[e+t.x,r+t.y])}function ii(i){const t=i.map(s=>s[0]),e=i.map(s=>s[1]),r=(Math.min(...t)+Math.max(...t))/2,n=(Math.min(...e)+Math.max(...e))/2;return[r,n]}const nt="rr-block",O="rr-mask",ri=`.${nt}, .${O}`;function st(i){return i.closest(ri)!==null}function Et(i){const t=i.getAttribute("role")?.trim().split(/\s+/)[0];return t&&/^[a-z][a-z0-9-]*$/i.test(t)?t:i.tagName.toLowerCase()}function ee(i){return i.tagName.toLowerCase()}const ni=10;function Mt(i){return st(i)?{name:Et(i),text:"",selector:ee(i)}:{name:kt(i),text:i.textContent?.trim().slice(0,200)??"",selector:Jt(i)}}class si{constructor(t,e,r){this.messages=e,this.handlers=r,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.touch=S(),this.highlighter=new Ye(t),this.pinMarker=new Ze(t),this.drawLayer=new Je(t),this.overlay=new We(t,{onPointerDown:n=>this.handlePointerDown(n),onPointerMove:n=>this.handlePointerMove(n),onPointerUp:n=>this.handlePointerUp(n),onPointerCancel:()=>{this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handlePointerDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handlePointerMove(t){if(this.drawLayer.isCurrentlyDrawing()){this.cancelPendingHighlight(),this.drawLayer.continueDraw(t.clientX,t.clientY),this.highlighter.hide();return}this.lastMoveX=t.clientX,this.lastMoveY=t.clientY,this.pendingHighlightFrame===null&&(this.pendingHighlightFrame=requestAnimationFrame(()=>{this.pendingHighlightFrame=null,this.updateHighlight()}))}updateHighlight(){if(!this.interactionActive||this.drawLayer.isCurrentlyDrawing()||this.drawSessionActive())return;const t=V(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handlePointerUp(t){this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(t)}finishStroke(t){if(this.drawLayer.getCurrentSpan()>=ni){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const e=V(t.clientX,t.clientY),r=e?Mt(e):null,n=r?.name??this.messages.annotation.element,s=e?.getBoundingClientRect(),o=Dt(e),a={type:"pin",x:t.clientX,y:t.clientY,targetSelector:r?.selector,targetText:r?.text??"",targetName:n,targetRect:s?{top:s.top,left:s.left,width:s.width,height:s.height,bottom:s.bottom}:void 0,captureOffsetX:o.x,captureOffsetY:o.y};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(a,n)}undoDraw(){this.drawLayer.undo()}redoDraw(){this.drawLayer.redo()}canUndoDraw(){return this.drawLayer.canUndo()}canRedoDraw(){return this.drawLayer.canRedo()}hasDrawStrokes(){return this.drawLayer.hasStrokes()}drawSessionActive(){return this.drawLayer.hasStrokes()||this.drawLayer.canRedo()}getDrawAnnotation(){const t=this.drawLayer.getAnnotation();if(!t)return null;const e=this.drawLayer.viewportDrift(),r=V(t.x-e.x,t.y-e.y);if(!r)return t;const n=r.getBoundingClientRect(),s=Dt(r),o=s.x-(t.captureOffsetX??0),a=s.y-(t.captureOffsetY??0),c=Mt(r);return{...t,targetSelector:c.selector,targetText:c.text,targetName:c.name,targetRect:{top:n.top+a,left:n.left+o,width:n.width,height:n.height,bottom:n.bottom+a}}}clearDraw(){this.drawLayer.clearAll()}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy())}hideHighlight(){this.highlighter.hide()}destroy(){this.dismissInteraction(),this.highlighter.destroy(),this.pinMarker.destroy(),this.drawLayer.destroy()}}const oi=140;class ai{constructor(){this.onChange=null,this.timer=null,this.lastReading=null,this.handler=()=>{this.timer!==null&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null;const t=this.current();if(t===this.lastReading){this.lastReading=null,this.onChange?.(t);return}this.lastReading=t,this.handler()},oi)}}current(){const t=window.visualViewport;if(!t||t.height<=0)return 0;const e=Math.round(window.innerHeight-(t.height+t.offsetTop));return Math.min(Math.max(0,e),window.innerHeight)}observe(t){const e=window.visualViewport;e&&(this.onChange=t,e.addEventListener("resize",this.handler),e.addEventListener("scroll",this.handler))}stop(){const t=window.visualViewport;this.onChange=null,this.lastReading=null,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),t&&(t.removeEventListener("resize",this.handler),t.removeEventListener("scroll",this.handler))}}const li=480;function ci(){return window.innerWidth<=li}class ie{constructor(t){this.el=t,this.inset=new ai}apply(){return ci()?(this.el.style.left="",this.el.style.top="",this.el.style.maxHeight="",this.lift(this.inset.current()),this.inset.observe(t=>this.lift(t)),!0):!1}release(){this.inset.stop()}lift(t){const e=Math.max(0,window.innerHeight-this.el.offsetHeight),r=Math.min(t,e);this.el.style.bottom=r>0?`${r}px`:""}}class hi{constructor(t,e){this.onSubmit=e.onSubmit,this.submitLabel=e.messages.draw.submit,this.messages=e.messages,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(e.messages),t.append(this.el),this.sheet=new ie(this.el),this.sheet.apply(),this.input=this.el.querySelector(".mtb-draw-input"),this.undoBtn=this.el.querySelector(".mtb-draw-undo"),this.redoBtn=this.el.querySelector(".mtb-draw-redo"),this.submitBtn=this.el.querySelector(".mtb-draw-submit"),this.undoBtn.addEventListener("click",e.onUndo),this.redoBtn.addEventListener("click",e.onRedo),this.el.querySelector(".mtb-draw-cancel").addEventListener("click",e.onCancel),this.submitBtn.addEventListener("click",()=>this.submit()),e.onActivity&&this.input.addEventListener("input",e.onActivity),this.input.addEventListener("keydown",r=>{xt(r)||r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),this.submit())}),this.input.focus({preventScroll:!0})}buildHTML(t){return`
24
24
  <input class="mtb-draw-input" type="text" placeholder="${d(t.draw.note_placeholder)}" />
25
25
  <button class="mtb-draw-icon-btn mtb-draw-undo" type="button" title="${d(t.draw.undo)}" aria-label="${d(t.draw.undo)}" disabled>
26
26
  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14L4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-1"/></svg>
@@ -34,7 +34,7 @@
34
34
  <span class="mtb-draw-sep"></span>
35
35
  <button class="mtb-draw-cancel" type="button">${d(t.draw.cancel)}</button>
36
36
  <button class="mtb-draw-submit" type="button">${d(t.draw.submit)}</button>
37
- `}setLoading(t){t?(this.submitBtn.disabled=!0,this.submitBtn.classList.add("mtb-btn-loading"),this.submitBtn.textContent=this.messages.popup.sending,this.input.disabled=!0):(this.submitBtn.disabled=!1,this.submitBtn.classList.remove("mtb-btn-loading"),this.submitBtn.textContent=this.submitLabel,this.input.disabled=!1)}setUndoRedo(t,e){this.undoBtn.disabled=!t,this.redoBtn.disabled=!e}submit(){this.onSubmit(this.input.value.trim())}destroy(){this.sheet.release(),this.el.remove()}}const J=12,gt=32;function di(i){const t=window.innerWidth,e=window.innerHeight;return{vw:t,vh:e,minLeft:J+(i==="left"?gt:0),maxRight:t-J-(i==="right"?gt:0)}}function ui(i,t){return Math.min(i,t.vw-2*J-gt)}const mi=["button:not([disabled])","input:not([disabled])","textarea:not([disabled])","select:not([disabled])","a[href]",'[tabindex]:not([tabindex="-1"])'].join(", ");function re(i){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,e=r=>{if(r.key!=="Tab")return;const n=Array.from(i.querySelectorAll(mi)).filter(c=>!c.hidden);if(n.length===0)return;const s=n[0],o=n[n.length-1],l=i.getRootNode().activeElement??document.activeElement;r.shiftKey?(l===s||!i.contains(l))&&(r.preventDefault(),o.focus({preventScroll:!0})):(l===o||!i.contains(l))&&(r.preventDefault(),s.focus({preventScroll:!0}))};return i.addEventListener("keydown",e),{release(){i.removeEventListener("keydown",e)},restoreFocus(){t?.isConnected&&t.focus({preventScroll:!0})}}}const bi=320,Rt=5e3,pi="https://makethisbetter.dev",j='<svg viewBox="0 0 512 512" fill="none"><defs><linearGradient id="mtb-bg" x1=".3" y1="0" x2=".7" y2="1"><stop offset="0%" stop-color="var(--mtb-chat-logo-start, #10b981)"/><stop offset="100%" stop-color="var(--mtb-chat-logo-end, #059669)"/></linearGradient></defs><rect width="512" height="512" rx="96" fill="url(#mtb-bg)"/><g transform="translate(89,89) scale(13.9)" stroke="var(--mtb-chat-logo-fg, #fff)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M21 13a9 9 0 1 1-3-7.7L21 8"/><circle cx="12" cy="12" r="2.2" fill="var(--mtb-chat-logo-fg, #fff)" stroke="none"/></g></svg>',fi='<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8.9 8l3.3-3.3-.9-.9L8 7.1 4.7 3.8l-.9.9L7.1 8l-3.3 3.3.9.9L8 8.9l3.3 3.3.9-.9z"/></svg>',gi='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6.2 2.6h3.6l.9 1.4H14a1 1 0 011 1v7.4a1 1 0 01-1 1H2a1 1 0 01-1-1V5a1 1 0 011-1h3.3l.9-1.4z"/><circle cx="8" cy="9" r="2.5" class="mtb-chat-icon-lens"/></svg>',vi='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><circle cx="8" cy="8" r="6.6"/><polygon points="6.4,5.2 11,8 6.4,10.8" class="mtb-chat-icon-lens"/></svg>',wi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ct{constructor(t,e){this.state="idle",this.autoCloseTimer=null,this.session=null,this.clarifyAbort=null,this.streamingBubbleEl=null,this.opts=e,this.i18n=e.messages,this.el=t.el("div","mtb-chat"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",e.targetName),this.el.innerHTML=this.buildHTML(),t.append(this.el),this.focusTrap=re(this.el),this.sheet=new ie(this.el),this.sheet.apply()||this.positionCard(e.x,e.y,e.targetRect,e.position??"right"),this.messagesEl=this.el.querySelector(".mtb-chat-messages"),this.composerEl=this.el.querySelector(".mtb-chat-composer"),this.actionsEl=this.el.querySelector(".mtb-chat-actions"),this.inputEl=this.el.querySelector(".mtb-chat-input"),this.sendBtn=this.el.querySelector(".mtb-chat-send"),this.quickRepliesEl=this.el.querySelector(".mtb-chat-quick-replies"),this.bindEvents(),this.handleEscape=this.handleEscape.bind(this),window.addEventListener("keydown",this.handleEscape),this.inputEl.focus({preventScroll:!0})}handleEscape(t){if(t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),this.state!=="sending")){if(this.state==="done"){this.destroy();return}this.opts.onCancel()}}buildHTML(){const t=this.i18n,e=this.opts,r=t.popup.quickOptions.map(s=>`<button class="mtb-chat-qr" type="button" data-quick="${d(s.label)}" data-value="${d(s.value??s.label)}">${d(s.emoji)} ${d(s.label)}</button>`).join(""),n=e.recordingSeconds!=null?`<span class="mtb-chat-attachment" title="${d(t.popup.recording_locked_hint)}">${vi}<span class="mtb-chat-capture-label">${Math.round(e.recordingSeconds)}s</span></span>`:e.onScreenshotToggle?`<button class="mtb-chat-screenshot" type="button" title="${d(t.popup.screenshot_hint)}" aria-pressed="${e.screenshotEnabled!==!1}">${gi}<span class="mtb-chat-capture-label">${d(t.popup.screenshot_short)}</span></button>`:"";return`
37
+ `}setLoading(t){t?(this.submitBtn.disabled=!0,this.submitBtn.classList.add("mtb-btn-loading"),this.submitBtn.textContent=this.messages.popup.sending,this.input.disabled=!0):(this.submitBtn.disabled=!1,this.submitBtn.classList.remove("mtb-btn-loading"),this.submitBtn.textContent=this.submitLabel,this.input.disabled=!1)}setUndoRedo(t,e){this.undoBtn.disabled=!t,this.redoBtn.disabled=!e}submit(){this.onSubmit(this.input.value.trim())}destroy(){this.sheet.release(),this.el.remove()}}const J=12,gt=32;function di(i){const t=window.innerWidth,e=window.innerHeight;return{vw:t,vh:e,minLeft:J+(i==="left"?gt:0),maxRight:t-J-(i==="right"?gt:0)}}function ui(i,t){return Math.min(i,t.vw-2*J-gt)}const mi=["button:not([disabled])","input:not([disabled])","textarea:not([disabled])","select:not([disabled])","a[href]",'[tabindex]:not([tabindex="-1"])'].join(", ");function re(i){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,e=r=>{if(r.key!=="Tab")return;const n=Array.from(i.querySelectorAll(mi)).filter(l=>!l.hidden);if(n.length===0)return;const s=n[0],o=n[n.length-1],c=i.getRootNode().activeElement??document.activeElement;r.shiftKey?(c===s||!i.contains(c))&&(r.preventDefault(),o.focus({preventScroll:!0})):(c===o||!i.contains(c))&&(r.preventDefault(),s.focus({preventScroll:!0}))};return i.addEventListener("keydown",e),{release(){i.removeEventListener("keydown",e)},restoreFocus(){t?.isConnected&&t.focus({preventScroll:!0})}}}const bi=320,Rt=5e3,pi="https://makethisbetter.dev",j='<svg viewBox="0 0 512 512" fill="none"><defs><linearGradient id="mtb-bg" x1=".3" y1="0" x2=".7" y2="1"><stop offset="0%" stop-color="var(--mtb-chat-logo-start, #10b981)"/><stop offset="100%" stop-color="var(--mtb-chat-logo-end, #059669)"/></linearGradient></defs><rect width="512" height="512" rx="96" fill="url(#mtb-bg)"/><g transform="translate(89,89) scale(13.9)" stroke="var(--mtb-chat-logo-fg, #fff)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M21 13a9 9 0 1 1-3-7.7L21 8"/><circle cx="12" cy="12" r="2.2" fill="var(--mtb-chat-logo-fg, #fff)" stroke="none"/></g></svg>',fi='<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8.9 8l3.3-3.3-.9-.9L8 7.1 4.7 3.8l-.9.9L7.1 8l-3.3 3.3.9.9L8 8.9l3.3 3.3.9-.9z"/></svg>',gi='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6.2 2.6h3.6l.9 1.4H14a1 1 0 011 1v7.4a1 1 0 01-1 1H2a1 1 0 01-1-1V5a1 1 0 011-1h3.3l.9-1.4z"/><circle cx="8" cy="9" r="2.5" class="mtb-chat-icon-lens"/></svg>',vi='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><circle cx="8" cy="8" r="6.6"/><polygon points="6.4,5.2 11,8 6.4,10.8" class="mtb-chat-icon-lens"/></svg>',wi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ct{constructor(t,e){this.state="idle",this.autoCloseTimer=null,this.session=null,this.clarifyAbort=null,this.streamingBubbleEl=null,this.opts=e,this.i18n=e.messages,this.el=t.el("div","mtb-chat"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",e.targetName),this.el.innerHTML=this.buildHTML(),t.append(this.el),this.focusTrap=re(this.el),this.sheet=new ie(this.el),this.sheet.apply()||this.positionCard(e.x,e.y,e.targetRect,e.position??"right"),this.messagesEl=this.el.querySelector(".mtb-chat-messages"),this.composerEl=this.el.querySelector(".mtb-chat-composer"),this.actionsEl=this.el.querySelector(".mtb-chat-actions"),this.inputEl=this.el.querySelector(".mtb-chat-input"),this.sendBtn=this.el.querySelector(".mtb-chat-send"),this.quickRepliesEl=this.el.querySelector(".mtb-chat-quick-replies"),this.bindEvents(),this.handleEscape=this.handleEscape.bind(this),window.addEventListener("keydown",this.handleEscape),this.inputEl.focus({preventScroll:!0})}handleEscape(t){if(t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),this.state!=="sending")){if(this.state==="done"){this.destroy();return}this.opts.onCancel()}}buildHTML(){const t=this.i18n,e=this.opts,r=t.popup.quickOptions.map(s=>`<button class="mtb-chat-qr" type="button" data-quick="${d(s.label)}" data-value="${d(s.value??s.label)}">${d(s.emoji)} ${d(s.label)}</button>`).join(""),n=e.recordingSeconds!=null?`<span class="mtb-chat-attachment" title="${d(t.popup.recording_locked_hint)}">${vi}<span class="mtb-chat-capture-label">${Math.round(e.recordingSeconds)}s</span></span>`:e.onScreenshotToggle?`<button class="mtb-chat-screenshot" type="button" title="${d(t.popup.screenshot_hint)}" aria-pressed="${e.screenshotEnabled!==!1}">${gi}<span class="mtb-chat-capture-label">${d(t.popup.screenshot_short)}</span></button>`:"";return`
38
38
  <div class="mtb-chat-header">
39
39
  <div class="mtb-chat-handle"></div>
40
40
  <div class="mtb-chat-header-row">
@@ -62,13 +62,13 @@
62
62
  <div class="mtb-chat-finalize-message">${d(this.i18n.error.finalize_message)}</div>
63
63
  ${t?`<button class="mtb-chat-finalize-retry" type="button">${d(this.i18n.clarify.retry)}</button>`:""}
64
64
  <button class="mtb-chat-finalize-close" type="button">${d(this.i18n.success.close)}</button>
65
- `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=di(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=J,u=8,b=ui(bi,s),g=(this.el.offsetHeight||280)+80;let f,m;const at=r&&r.width<o*.6&&r.height<a*.6;r&&at?(f=r.left,m=r.bottom+u,m+g>a-h&&(m=r.top-g-u),m<h&&(m=Math.min(r.bottom+u,a-g-h))):(f=t+12,m=e+12),f+b>c&&(f=c-b),f<l&&(f=l),m<h&&(m=h),m+g>a-h&&(m=a-g-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const yi=5e3,xi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ki{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=xi,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,yi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",Ei=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Si=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,_i=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],Ci=/\b(?:\d[ -]?){12,18}\d\b/g,Ti=/\bhttps?:\/\/[^\s<>"']+/gi,Ai=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Li=new Set(["value","content"]),Pi=new Set(["password","hidden","file"]),Di=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Mi=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function C(i){let t=i.replace(Ei,p).replace(Si,p);for(const e of _i)t=t.replace(e,p);return t=t.replace(Ci,e=>Ri(e)?p:e),t.replace(Ti,e=>U(e)||p)}function U(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function Q(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return C(i);if(Array.isArray(i))return i.map(e=>Q(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Li.has(R(n))&&s!=null?p:Q(s,n);return[C(n),o]}))}return i}function ne(i){return Mi.test(R(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=R(t);return Ai.has(r)?r==="type"?Pi.has(R(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Di.has(R(n))):ne(e):!1})}function R(i){return i.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Ri(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function tt(i,t){return i&&(oe(t)?p:C(i))}const Ii=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ii?n="too-large":C(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Hi(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Ni(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let A=null;function de(){return A||(A=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw A=null,i}),A)}let ht,dt=null;function St(){return ht!==void 0?Promise.resolve(ht):(dt??(dt=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(ht=i,i)).catch(()=>{dt=null})),dt)}const Fi=200,Bi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function zi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),St()]),n=document.body.getBoundingClientRect(),s=Ke(),o={x:window.scrollX,y:window.scrollY},a=Wi(document.body),l=await e(document.body,{quality:.85,imagePlaceholder:Bi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Xi(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===w)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Fi}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function Oi(i,t=[],e){try{const r=t.map(n=>Ui(n,i.pageScroll));return await qi(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Ui(i,t){const e=$i(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Ni(i.drawPath,e.x,e.y)}}function $i(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ge({x:i.captureOffsetX,y:i.captureOffsetY},t):$(ji(i))}function ji(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function qi(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Hi(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=Ve(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of r){const h=Xe(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?Vi(o,c.drawPath,l,n?.primary):c.type==="pin"&&Ki(o,G(l,c.x),Z(l,c.y),n);return Gi(s)}function Wi(i){const t=[];for(const s of Yi(i,`.${nt}`))ut(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${O}`)!==null,l=oe(s)||tt(o,s)!==o;!a&&!l||ut(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${O}`)!==null,l=C(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||l)){const c=$(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))ut(t,u,c,Ft)}n=e.nextNode()}return t}function It(i){return $(Qt(i))}function Yi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${w}`)!==null||i.closest(`.${nt}`)!==null}function ut(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Vi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(G(e,n[0][0]),Z(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(G(e,n[s][0]),Z(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Xi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Ki(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Gi(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Zi{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,n,s)=>(this.emit({name:Ji(s),message:String(t),source:e,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,e,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),r=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:r,message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const _t=new Zi;function Ji(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Qi(i.name)||tr(i.message),e=er(i);return e?`${t} (${e})`:t}function Qi(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function tr(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function er(i){if(!i.source)return"";try{const t=new URL(i.source,window.location.href).pathname;return i.line==null?t:`${t}:${i.line}:${i.col??0}`}catch{return""}}const ir=20;class rr{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=_t.subscribe(t=>this.record(t)))}record(t){this.addError(ue(t))}addError(t){this.errors.length>=ir||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const X=new Set;let I=null,H=null,N=null,et=null,F=null,it=null;function me(i){X.add(i),nr();let t=!1;return()=>{t||(t=!0,X.delete(i),X.size===0&&sr())}}function mt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};it=e.toUrl;for(const r of[...X])try{r(e)}catch{}}function nr(){if(N)return;it=location.href,F=()=>mt("pop",it??location.href),window.addEventListener("popstate",F),I=history.pushState,H=history.replaceState;const i=I,t=H;N=function(e,r,n){const s=location.href;i.call(history,e,r,n),mt("push",s)},et=function(e,r,n){const s=location.href;t.call(history,e,r,n),mt("replace",s)},history.pushState=N,history.replaceState=et}function sr(){F&&(window.removeEventListener("popstate",F),F=null),I&&history.pushState===N&&(history.pushState=I),H&&history.replaceState===et&&(history.replaceState=H),I=null,H=null,N=null,et=null,it=null}const or=20;function ar(i){return st(i)?Et(i):kt(i)}function lr(i){return st(i)?ee(i):Jt(i)}class cr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=_t.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>or&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!k(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:ar(e),data:{selector:lr(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!k(e))try{const r=e,n=st(e)?Et(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=U(t),n=U(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let vt=null;function rt(){try{const i=window.sessionStorage.getItem(be);return K(i?JSON.parse(i):vt)}catch{return K(vt)}}function pe(i){const t=K(i);vt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function hr(){return rt().dismissedByUser}function dr(){pe({...rt(),dismissedByUser:!0})}function K(i){const t=i??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(e=>typeof e=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(e=>typeof e=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const ur=4,mr=1500,br=3,pr=5e3,bt=500,fr=2,gr=3e4,vr=2e3,wr=1e3,yr=300,xr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),kr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),Er=new Set(["A","BUTTON","SUMMARY"]),Sr=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],z=class z{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=_t.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>vr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:q(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=rt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=rt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||k(e))return;this.trackFormSubmitIntent(e),this.trackNativeNavigationIntent(t,e);const r=this.interactionTarget(e),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-mr;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=ur){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:q(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const e=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(e);const n=e-pr;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=br&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},yr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(k(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},bt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||k(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},bt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),bt);const e=Date.now(),r=e-gr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<fr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:q(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||k(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:q(t),timestamp:e})},wr))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(Er.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Sr.has(e)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let e=t;for(;e&&e!==document.body;){if(this.isIntrinsicInteractive(e))return e;e=e.parentElement}let r=t;for(e=t.parentElement;e&&e!==document.body&&this.looksInteractive(e);)r=e,e=e.parentElement;return r}isIntrinsicInteractive(t){if(xr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&kr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+z.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+z.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};z.COOLDOWN_MS=6e4;let wt=z;function q(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class _r extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Cr=25e3,Tr="https://makethisbetter.dev/api/v1",Ar="sensitive-data-v1";class Lr{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Tr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Mr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const l=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Ar,s["X-Idempotency-Key"]=Dr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:C(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Pr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),Cr);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new _r(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Pr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
66
- `).find(b=>b.startsWith("event:")),c=a.split(`
67
- `).find(b=>b.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(b=>typeof b=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:a,value:l}=await e.read();if(a)break;n+=r.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
65
+ `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const c=async()=>{const l=o.value.trim();if(!l)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(l)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",l=>{l.key==="Enter"&&o.value.trim()&&c()}),a.addEventListener("click",()=>void c()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${j}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=di(n),{vw:o,vh:a,minLeft:c,maxRight:l}=s,h=J,u=8,b=ui(bi,s),g=(this.el.offsetHeight||280)+80;let f,m;const at=r&&r.width<o*.6&&r.height<a*.6;r&&at?(f=r.left,m=r.bottom+u,m+g>a-h&&(m=r.top-g-u),m<h&&(m=Math.min(r.bottom+u,a-g-h))):(f=t+12,m=e+12),f+b>l&&(f=l-b),f<c&&(f=c),m<h&&(m=h),m+g>a-h&&(m=a-g-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const yi=5e3,xi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ki{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const c=document.createElement("div");c.className="mtb-chat-success-icon",c.innerHTML=xi,a.appendChild(c);const l=document.createElement("div");if(l.className="mtb-chat-success-title",l.textContent=o,a.appendChild(l),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,yi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",Ei=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Si=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,_i=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],Ci=/\b(?:\d[ -]?){12,18}\d\b/g,Ti=/\bhttps?:\/\/[^\s<>"']+/gi,Ai=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Li=new Set(["value","content"]),Pi=new Set(["password","hidden","file"]),Di=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Mi=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function C(i){let t=i.replace(Ei,p).replace(Si,p);for(const e of _i)t=t.replace(e,p);return t=t.replace(Ci,e=>Ri(e)?p:e),t.replace(Ti,e=>U(e)||p)}function U(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function Q(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return C(i);if(Array.isArray(i))return i.map(e=>Q(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Li.has(R(n))&&s!=null?p:Q(s,n);return[C(n),o]}))}return i}function ne(i){return Mi.test(R(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=R(t);return Ai.has(r)?r==="type"?Pi.has(R(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Di.has(R(n))):ne(e):!1})}function R(i){return i.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Ri(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function tt(i,t){return i&&(oe(t)?p:C(i))}const Ii=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ii?n="too-large":C(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Hi(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Ni(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let A=null;function de(){return A||(A=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw A=null,i}),A)}let ht,dt=null;function St(){return ht!==void 0?Promise.resolve(ht):(dt??(dt=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(ht=i,i)).catch(()=>{dt=null})),dt)}const Fi=200,Bi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function zi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),St()]);if(await new Promise(l=>setTimeout(l,0)),t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=Ke(),o={x:window.scrollX,y:window.scrollY},a=Wi(document.body),c=await e(document.body,{quality:.85,imagePlaceholder:Bi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Xi(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:l=>{if(l instanceof HTMLElement&&l.id===w)return!1;if(!(l instanceof Element))return!0;const h=l.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Fi}});return t?.aborted?null:{dataUrl:c,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function Oi(i,t=[],e){try{const r=t.map(n=>Ui(n,i.pageScroll));return await qi(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Ui(i,t){const e=$i(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Ni(i.drawPath,e.x,e.y)}}function $i(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ge({x:i.captureOffsetX,y:i.captureOffsetY},t):$(ji(i))}function ji(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function qi(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Hi(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const c=Ve(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const l of r){const h=Xe(c,l);o.fillRect(h.left,h.top,h.width,h.height)}for(const l of t)l.type==="draw"&&l.drawPath?Vi(o,l.drawPath,c,n?.primary):l.type==="pin"&&Ki(o,G(c,l.x),Z(c,l.y),n);return Gi(s)}function Wi(i){const t=[];for(const s of Yi(i,`.${nt}`))ut(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${O}`)!==null,c=oe(s)||tt(o,s)!==o;!a&&!c||ut(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${O}`)!==null,c=C(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||c)){const l=$(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))ut(t,u,l,Ft)}n=e.nextNode()}return t}function It(i){return $(Qt(i))}function Yi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${w}`)!==null||i.closest(`.${nt}`)!==null}function ut(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Vi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(G(e,n[0][0]),Z(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(G(e,n[s][0]),Z(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Xi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Ki(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Gi(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Zi{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,n,s)=>(this.emit({name:Ji(s),message:String(t),source:e,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,e,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason),r=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:r,message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const _t=new Zi;function Ji(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Qi(i.name)||tr(i.message),e=er(i);return e?`${t} (${e})`:t}function Qi(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function tr(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function er(i){if(!i.source)return"";try{const t=new URL(i.source,window.location.href).pathname;return i.line==null?t:`${t}:${i.line}:${i.col??0}`}catch{return""}}const ir=20;class rr{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=_t.subscribe(t=>this.record(t)))}record(t){this.addError(ue(t))}addError(t){this.errors.length>=ir||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const X=new Set;let I=null,H=null,N=null,et=null,F=null,it=null;function me(i){X.add(i),nr();let t=!1;return()=>{t||(t=!0,X.delete(i),X.size===0&&sr())}}function mt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};it=e.toUrl;for(const r of[...X])try{r(e)}catch{}}function nr(){if(N)return;it=location.href,F=()=>mt("pop",it??location.href),window.addEventListener("popstate",F),I=history.pushState,H=history.replaceState;const i=I,t=H;N=function(e,r,n){const s=location.href;i.call(history,e,r,n),mt("push",s)},et=function(e,r,n){const s=location.href;t.call(history,e,r,n),mt("replace",s)},history.pushState=N,history.replaceState=et}function sr(){F&&(window.removeEventListener("popstate",F),F=null),I&&history.pushState===N&&(history.pushState=I),H&&history.replaceState===et&&(history.replaceState=H),I=null,H=null,N=null,et=null,it=null}const or=20;function ar(i){return st(i)?Et(i):kt(i)}function lr(i){return st(i)?ee(i):Jt(i)}class cr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=_t.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>or&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!k(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:ar(e),data:{selector:lr(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!k(e))try{const r=e,n=st(e)?Et(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=U(t),n=U(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let vt=null;function rt(){try{const i=window.sessionStorage.getItem(be);return K(i?JSON.parse(i):vt)}catch{return K(vt)}}function pe(i){const t=K(i);vt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function hr(){return rt().dismissedByUser}function dr(){pe({...rt(),dismissedByUser:!0})}function K(i){const t=i??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(e=>typeof e=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(e=>typeof e=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const ur=4,mr=1500,br=3,pr=5e3,bt=500,fr=2,gr=3e4,vr=2e3,wr=1e3,yr=300,xr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),kr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),Er=new Set(["A","BUTTON","SUMMARY"]),Sr=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],z=class z{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=_t.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>vr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:q(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=rt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=rt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||k(e))return;this.trackFormSubmitIntent(e),this.trackNativeNavigationIntent(t,e);const r=this.interactionTarget(e),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-mr;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=ur){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:q(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const e=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(e);const n=e-pr;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=br&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},yr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(k(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},bt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||k(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},bt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),bt);const e=Date.now(),r=e-gr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<fr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:q(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||k(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:q(t),timestamp:e})},wr))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(Er.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Sr.has(e)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let e=t;for(;e&&e!==document.body;){if(this.isIntrinsicInteractive(e))return e;e=e.parentElement}let r=t;for(e=t.parentElement;e&&e!==document.body&&this.looksInteractive(e);)r=e,e=e.parentElement;return r}isIntrinsicInteractive(t){if(xr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&kr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+z.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+z.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};z.COOLDOWN_MS=6e4;let wt=z;function q(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class _r extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Cr=25e3,Tr="https://makethisbetter.dev/api/v1",Ar="sensitive-data-v1";class Lr{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Tr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),l=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof l.url=="string"?l.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Mr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const c=JSON.stringify(t.recording_events),l=new Blob([c],{type:"application/json"});n.append("feedback[recording]",l,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const c=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${c}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Ar,s["X-Idempotency-Key"]=Dr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:C(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Pr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),Cr);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new _r(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Pr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const c=a.split(`
66
+ `).find(b=>b.startsWith("event:")),l=a.split(`
67
+ `).find(b=>b.startsWith("data:"));if(!l)return;const h=c?.slice(6).trim(),u=JSON.parse(l.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(b=>typeof b=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:a,value:c}=await e.read();if(a)break;n+=r.decode(c,{stream:!0});let l;for(;(l=n.indexOf(`
68
68
 
69
- `))!==-1;){const h=n.slice(0,c);n=n.slice(c+2);try{o(h)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Dr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Mr(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const i=crypto.getRandomValues(new Uint8Array(32));return Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}const Ot="mtb_anon_id",fe="mtb_reporter_email",ge="mtb_board_url";let Ut=null,ve=null,we=null;function ye(){try{const i=window.localStorage.getItem(Ot);if(i?.startsWith("anon_"))return i;const t=$t();return window.localStorage.setItem(Ot,t),t}catch{return Ut??(Ut=$t()),Ut}}function xe(){try{return window.localStorage.getItem(fe)??void 0}catch{return ve??void 0}}function Rr(i){ve=i;try{window.localStorage.setItem(fe,i)}catch{}}function Ir(){try{return window.localStorage.getItem(ge)??void 0}catch{return we??void 0}}function L(i){we=i;try{window.localStorage.setItem(ge,i)}catch{}}function $t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const Hr={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},error:{submit:"Failed to submit. Please try again.",finalize_title:"We couldn't send this yet.",finalize_message:"Your feedback is still saved. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},Nr={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"有问题",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。",finalize_title:"暂时无法发送。",finalize_message:"你的反馈仍已保存,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},Fr={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。",finalize_title:"まだ送信できませんでした。",finalize_message:"フィードバックは保存されています。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Br={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요.",finalize_title:"아직 전송하지 못했습니다.",finalize_message:"피드백은 저장되어 있습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},zr={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo.",finalize_title:"Aún no pudimos enviarlo.",finalize_message:"Tu comentario sigue guardado. Inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},Or={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},error:{submit:"Échec de l'envoi. Veuillez réessayer.",finalize_title:"Nous n'avons pas encore pu l'envoyer.",finalize_message:"Votre retour est toujours enregistré. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},Ur={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut.",finalize_title:"Wir konnten dies noch nicht senden.",finalize_message:"Ihr Feedback ist weiterhin gespeichert. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}},P={en:Hr,"zh-CN":Nr,ja:Fr,ko:Br,es:zr,fr:Or,de:Ur};function jt(i){if(P[i])return P[i];const t=i.split("-")[0];return P[t]?P[t]:P.en}const $r=60,qt=["value","content"],jr=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(i=>[i,!0])),qr="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",Wr="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let D=null;function Yr(){return D||(D=Xr().catch(()=>Kr()).catch(t=>{throw D=null,t}),D)}function Vr(i,t){const e=Q(i);return yt(e,t,ae()),e}function yt(i,t,e){if(Array.isArray(i)){i.forEach(a=>yt(a,t,e));return}if(!Wt(i))return;const r=Wt(i.attributes)?i.attributes:null,n=r&&qt.some(a=>typeof r[a]=="string"),o=(typeof i.text=="string"||typeof i.textContent=="string"||typeof i.value=="string"||n)&&typeof i.id=="number"?t.mirror.getNode(i.id):null;if(o instanceof Element){if(typeof i.text=="string"&&(i.text=tt(i.text,o)),r)for(const a of qt){const l=r[a];typeof l=="string"&&(r[a]=tt(l,o))}}else o?.nodeType===Node.TEXT_NODE&&le(o,e)&&(typeof i.textContent=="string"&&(i.textContent=p),typeof i.value=="string"&&(i.value=p));Object.values(i).forEach(a=>yt(a,t,e))}function Wt(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function Xr(){return(await import("@rrweb/record")).record}function Yt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Kr(){return new Promise((i,t)=>{const e=Yt();if(e){i(e);return}const r=document.createElement("script");r.src=qr,r.integrity=Wr,r.crossOrigin="anonymous",r.onload=()=>{const n=Yt();n?i(n):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class Gr{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Yr();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(Vr(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:jr,maskInputFn:(e,r)=>r.closest(`.${O}`)?p:tt(e,r),maskTextFn:()=>p,blockClass:nt,maskTextClass:O}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},$r*1e3))}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Zr{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
69
+ `))!==-1;){const h=n.slice(0,l);n=n.slice(l+2);try{o(h)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Dr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Mr(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const i=crypto.getRandomValues(new Uint8Array(32));return Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}const Ot="mtb_anon_id",fe="mtb_reporter_email",ge="mtb_board_url";let Ut=null,ve=null,we=null;function ye(){try{const i=window.localStorage.getItem(Ot);if(i?.startsWith("anon_"))return i;const t=$t();return window.localStorage.setItem(Ot,t),t}catch{return Ut??(Ut=$t()),Ut}}function xe(){try{return window.localStorage.getItem(fe)??void 0}catch{return ve??void 0}}function Rr(i){ve=i;try{window.localStorage.setItem(fe,i)}catch{}}function Ir(){try{return window.localStorage.getItem(ge)??void 0}catch{return we??void 0}}function L(i){we=i;try{window.localStorage.setItem(ge,i)}catch{}}function $t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const Hr={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},error:{submit:"Failed to submit. Please try again.",finalize_title:"We couldn't send this yet.",finalize_message:"Your feedback is still saved. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},Nr={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"有问题",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。",finalize_title:"暂时无法发送。",finalize_message:"你的反馈仍已保存,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},Fr={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。",finalize_title:"まだ送信できませんでした。",finalize_message:"フィードバックは保存されています。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Br={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요.",finalize_title:"아직 전송하지 못했습니다.",finalize_message:"피드백은 저장되어 있습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},zr={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo.",finalize_title:"Aún no pudimos enviarlo.",finalize_message:"Tu comentario sigue guardado. Inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},Or={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},error:{submit:"Échec de l'envoi. Veuillez réessayer.",finalize_title:"Nous n'avons pas encore pu l'envoyer.",finalize_message:"Votre retour est toujours enregistré. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},Ur={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut.",finalize_title:"Wir konnten dies noch nicht senden.",finalize_message:"Ihr Feedback ist weiterhin gespeichert. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}},P={en:Hr,"zh-CN":Nr,ja:Fr,ko:Br,es:zr,fr:Or,de:Ur};function jt(i){if(P[i])return P[i];const t=i.split("-")[0];return P[t]?P[t]:P.en}const $r=60,qt=["value","content"],jr=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(i=>[i,!0])),qr="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",Wr="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let D=null;function Yr(){return D||(D=Xr().catch(()=>Kr()).catch(t=>{throw D=null,t}),D)}function Vr(i,t){const e=Q(i);return yt(e,t,ae()),e}function yt(i,t,e){if(Array.isArray(i)){i.forEach(a=>yt(a,t,e));return}if(!Wt(i))return;const r=Wt(i.attributes)?i.attributes:null,n=r&&qt.some(a=>typeof r[a]=="string"),o=(typeof i.text=="string"||typeof i.textContent=="string"||typeof i.value=="string"||n)&&typeof i.id=="number"?t.mirror.getNode(i.id):null;if(o instanceof Element){if(typeof i.text=="string"&&(i.text=tt(i.text,o)),r)for(const a of qt){const c=r[a];typeof c=="string"&&(r[a]=tt(c,o))}}else o?.nodeType===Node.TEXT_NODE&&le(o,e)&&(typeof i.textContent=="string"&&(i.textContent=p),typeof i.value=="string"&&(i.value=p));Object.values(i).forEach(a=>yt(a,t,e))}function Wt(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function Xr(){return(await import("@rrweb/record")).record}function Yt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Kr(){return new Promise((i,t)=>{const e=Yt();if(e){i(e);return}const r=document.createElement("script");r.src=qr,r.integrity=Wr,r.crossOrigin="anonymous",r.onload=()=>{const n=Yt();n?i(n):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class Gr{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Yr();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(Vr(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:jr,maskInputFn:(e,r)=>r.closest(`.${O}`)?p:tt(e,r),maskTextFn:()=>p,blockClass:nt,maskTextClass:O}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},$r*1e3))}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Zr{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
70
70
  <span class="mtb-record-dot"></span>
71
71
  <span class="mtb-record-timer">00:00</span>
72
72
  <button class="mtb-record-stop" type="button">${d(e.record.stop)}</button>
73
- `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",n),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),r=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${r}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class Jr{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new Gr(t,r),this.bar=new Zr(t,e,()=>this.session?.getDuration()??0,r),await this.session.start()}stop(){return this.session?(this.result=this.session.stop(),this.teardownUI(),this.result):null}getRecording(){return this.result}destroy(){this.teardownUI(),this.result=null}teardownUI(){this.session?.destroy(),this.session=null,this.bar?.destroy(),this.bar=null}}function Qr(){return{page_url:U(window.location.href),user_agent:navigator.userAgent,browser:tn(),os:en(),screen_width:window.screen.width,screen_height:window.screen.height}}function tn(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function en(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}function rn(i){const{description:t,pageContext:e,consoleErrors:r,annotation:n,user:s,recording:o,anonId:a,anonEmail:l,breadcrumbs:c}=i;return{...Q({description:t,...e,page_url:U(e.page_url),console_errors:r,annotations:n?[n]:[],target_element:n?.targetSelector?{selector:n.targetSelector,text:n.targetText??"",name:n.targetName??""}:void 0,recording_events:o?.events,recording_duration:o?.duration,breadcrumbs:c}),user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:a,reporter_email:s?void 0:l}}const nn=300,sn=5e3;class on{constructor(t,e){this.deps=t,this.host=e,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.pendingScreenshotTask=null,this.screenshotAbortController=null,this.screenshotEnabled=!0}isScreenshotEnabled(){return this.screenshotEnabled}resetScreenshotConsent(){this.screenshotEnabled=!0}setScreenshotEnabled(t){if(this.screenshotEnabled=t,t){this.warmScreenshotDeps();return}this.screenshotAbortController?.abort()}warmScreenshotDeps(){this.screenshotEnabled&&St()}start(t,e,r){const n=++this.submissionAttempt,s=this.createSubmission(t,e,r,n);return this.pendingSubmissionRequest=s,s}async createSubmission(t,e,r,n){if(await Vt(),n!==this.submissionAttempt)return null;const s=Qr(),o=rn({description:t,pageContext:s,consoleErrors:this.deps.consoleCollector.getErrors(),annotation:e,user:this.deps.user(),recording:r,anonId:ye(),anonEmail:xe(),breadcrumbs:this.deps.breadcrumbCollector.getBreadcrumbs()});let a;try{a=this.deps.apiClient.createSubmissionSession(o,null)}catch{return null}let l=null;if(this.screenshotEnabled){const h=new AbortController;l=h,this.screenshotAbortController?.abort(),this.screenshotAbortController=h;const b=(async()=>{try{const g=await zi(async(at,Se)=>{const Tt=await a;if(!(h.signal.aborted||n!==this.submissionAttempt))return this.deps.apiClient.resolveScreenshotResourceUrl(Tt.id,Tt.token,at,Se,h.signal)},h.signal);if(h.signal.aborted||n!==this.submissionAttempt||!g)return;const f=await Oi(g,e?[e]:[],this.deps.brandColors);if(h.signal.aborted||n!==this.submissionAttempt||!f)return;const m=await a;if(h.signal.aborted||n!==this.submissionAttempt)return;await this.deps.apiClient.uploadScreenshot(m.id,m.token,f,h.signal)}catch{}})().finally(()=>{this.pendingScreenshotTask===b&&(this.pendingScreenshotTask=null),this.screenshotAbortController===h&&(this.screenshotAbortController=null)});this.pendingScreenshotTask=b}let c;try{if(c=await a,n!==this.submissionAttempt)return l?.abort(),await this.deps.apiClient.abandonSubmissionSession(c.id,c.token).catch(()=>{}),null;this.activeSubmission=c}catch{return l?.abort(),null}return c}async finalize(){const t=this.submissionAttempt;this.resetScreenshotConsent();const e=this.host.isBackground(),r=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!r){if(e)return this.showFinalizeFailure({canRetry:!1});throw new Error("No active submission session")}if(await this.waitForScreenshot(),t!==this.submissionAttempt)return;const n=e?Promise.resolve():new Promise(o=>setTimeout(o,nn));let s;try{s=await this.deps.apiClient.finalizeSubmissionSession(r.id,r.token)}catch(o){if(e)return this.showFinalizeFailure({canRetry:!0});throw o}await Promise.all([n,Vt()]),!(t!==this.submissionAttempt||this.activeSubmission!==r)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.host.onFinalized(s,r))}async waitForScreenshot(){const t=this.pendingScreenshotTask;if(!t)return;let e;const r=await Promise.race([t.then(()=>!0),new Promise(n=>{e=setTimeout(()=>n(!1),sn)})]);e!==void 0&&clearTimeout(e),r||(this.screenshotAbortController?.abort(),this.pendingScreenshotTask===t&&(this.pendingScreenshotTask=null))}showFinalizeFailure(t){this.host.onFinalizeFailure(t.canRetry?()=>this.retryBackgroundFinalization():void 0)}retryBackgroundFinalization(){this.host.onReenterBackground(),this.finalize().catch(()=>this.showFinalizeFailure({canRetry:!0}))}abandon(){this.submissionAttempt+=1,this.screenshotAbortController?.abort(),this.screenshotAbortController=null,this.pendingScreenshotTask=null,this.resetScreenshotConsent();const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.deps.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{})}}function Vt(){return new Promise(i=>requestAnimationFrame(()=>setTimeout(i,0)))}function ot(i){i.preventDefault(),i.stopPropagation()}class y{constructor(t){this.host=t,this.launcherLit=!0,this.acceptsFrustrationPrompt=!1}enter(){}exit(){}handleOpen(){}handleClose(){this.host.exitAll()}handleEscape(t){}handleTabClick(){this.host.exitAll()}handleToolbarModeChange(t){}handleDrawStroke(){}}class W extends y{constructor(){super(...arguments),this.kind="idle",this.launcherLit=!1,this.acceptsFrustrationPrompt=!0}handleOpen(){this.host.dismissFrustrationPrompt(),this.host.dismissSuccess(),this.host.transitionTo(new x(this.host))}handleClose(){}handleTabClick(){this.handleOpen()}}class x extends y{constructor(){super(...arguments),this.kind="annotating"}enter(){if(!this.host.hasAnnotationChrome()){this.host.mountAnnotationChrome();return}this.host.destroyRecordingManager(),this.host.teardownDrawBar(),this.host.ensureSession()}handleEscape(t){ot(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):this.host.transitionTo(new x(this.host))}handleDrawStroke(){this.host.transitionTo(new an(this.host,S()?"sheet":"bar"))}}class Ct extends y{constructor(){super(...arguments),this.kind="recording"}enter(){this.host.clearCurrentAnnotation(),this.host.teardownDrawBar(),this.host.destroySession(),this.host.startRecorder()}handleEscape(t){ot(t),this.host.stopRecordingIntoNote()}handleToolbarModeChange(t){t!=="record"&&this.host.transitionTo(new x(this.host))}}class an extends y{constructor(t,e){super(t),this.surface=e,this.kind="drawing"}enter(){this.surface==="sheet"?this.host.mountDrawSheet():(this.host.mountDrawBar(),this.host.refreshDrawBar())}handleEscape(t){ot(t),this.host.cancelDraw()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):this.host.transitionTo(new x(this.host))}handleDrawStroke(){this.surface==="bar"&&this.host.refreshDrawBar()}}class Xt extends y{constructor(t,e){super(t),this.opts=e,this.kind="popup"}enter(){this.host.mountNotePopup(this.opts)}handleEscape(t){ot(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):(this.host.dismissNotePopup(),this.host.transitionTo(new x(this.host)))}}class pt extends y{constructor(){super(...arguments),this.kind="clarifying"}handleToolbarModeChange(t){this.host.revertToolbarDuringClarify()}}class Y extends y{constructor(){super(...arguments),this.kind="submitting",this.launcherLit=!1}enter(){this.host.releaseClarifyUi()}handleTabClick(){}}const ln=/^#[0-9a-f]{6}$/i;function cn(i){return i===void 0?void 0:typeof i!="object"||i===null||![i.primary,i.hover,i.active,i.onPrimary].every(e=>typeof e=="string"&&ln.test(e))?Kt():{primary:i.primary.toLowerCase(),hover:i.hover.toLowerCase(),active:i.active.toLowerCase(),onPrimary:i.onPrimary.toLowerCase()}}function Kt(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}function Gt(){const{hostname:i}=window.location;return i==="localhost"||i==="127.0.0.1"||i==="[::1]"||i.endsWith(".localhost")||i.endsWith(".local")||i.endsWith(".test")}class hn{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new Be,this.chatPopup=null,this.scrollLock=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.state=new W(this),this.via="pin",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=e=>{e.key==="Escape"&&(xt(e)||this.state.handleEscape(e))},this.stopRecordingIntoNote=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.transitionTo(new Xt(this,{x:window.innerWidth/2,y:window.innerHeight/2,targetName:this.messages.record.timer_label})))},this.config=t,t.projectKey||console.warn("[MakeThisBetter] projectKey is missing. Feedback submission will be rejected."),this.brandColors=cn(t.brandColors),this.messages=jt(t.locale??document.documentElement.lang??"en"),this.apiClient=new Lr({projectKey:t.projectKey,apiUrl:t.apiUrl,userToken:t.userToken,userTokenFn:t.userTokenFn}),this.consoleCollector=new rr,this.consoleCollector.start(),this.breadcrumbCollector=new cr,this.breadcrumbCollector.start(),this.lifecycle=new on({apiClient:this.apiClient,consoleCollector:this.consoleCollector,breadcrumbCollector:this.breadcrumbCollector,brandColors:this.brandColors,shadow:()=>this.shadow,messages:()=>this.messages,user:()=>this.config.user},{isBackground:()=>this.state.kind==="submitting",onFinalizeFailure:e=>this.chatPopup?.showFinalizeFailure(e),onReenterBackground:()=>this.transitionTo(new Y(this)),onFinalized:(e,r)=>this.handleFinalized(e,r)});try{this.buildUI()}catch(e){this.consoleCollector.stop(),this.breadcrumbCollector.stop(),console.warn("[MakeThisBetter] Widget failed to start:",e);return}t.frustrationDetection!==!1&&(this.frustrationDetector=new wt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}transitionTo(t){const e=this.state;this.state=t,e.exit(),t.enter(),this.tab?.setActive(t.launcherLit)}buildUI(){if(this.shadow=new ft(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Gt()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(S()){Gt()&&console.warn("[MakeThisBetter] No launcher is rendered on touch devices. Call MakeThisBetter.open() from your own mobile UI.");return}this.mountTab()}mountTab(){this.tab||!this.shadow||(this.tab=new Ie(this.shadow,this.messages,this.config.position??"right",()=>this.state.handleTabClick(),this.config.tabText))}open(){this.shadow&&this.state.handleOpen()}close(){this.state.handleClose()}showLauncher(){S()||(this.mountTab(),this.tab?.setActive(this.state.launcherLit))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=jt(t),this.tab?.setMessages(this.messages)}handleFrustration(){!this.state.acceptsFrustrationPrompt||this.frustrationPrompt||hr()||(this.frustrationPrompt=new Ne(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.state.handleOpen()},onDismiss:()=>{dr(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissSuccess(){this.success?.destroy(),this.success=null,this.chatPopup?.destroy(),this.chatPopup=null}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}hasAnnotationChrome(){return this.toolbar!==null}mountAnnotationChrome(){St();const t=S();this.toolbar=new qe(this.shadow,this.messages,()=>this.exitAll(),e=>this.state.handleToolbarModeChange(e),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.ensureSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}ensureSession(){this.session||(this.session=new si(this.shadow,this.messages,{onPin:(t,e)=>{this.currentAnnotation=t,this.via="pin",this.transitionTo(new Xt(this,{x:t.x,y:t.y,targetName:e,targetRect:t.targetRect}))},onDrawStroke:()=>this.state.handleDrawStroke()}))}destroySession(){this.session?.destroy(),this.session=null}clearCurrentAnnotation(){this.currentAnnotation=null}startRecorder(){this.recordingManager=new Jr,this.recordingManager.start(this.shadow,this.messages,this.stopRecordingIntoNote).catch(t=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",t),this.state.kind==="recording"&&(this.toolbar?.setMode("markup"),this.state.handleToolbarModeChange("markup"))})}destroyRecordingManager(){this.recordingManager?.destroy(),this.recordingManager=null}mountDrawBar(){this.engageScrollLock(),this.drawBar=new hi(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t),onActivity:()=>this.lifecycle.warmScreenshotDeps()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}mountDrawSheet(){this.engageScrollLock();let t=!1;this.chatPopup=new ct(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async e=>{const r=this.session?.getDrawAnnotation();if(!r)return this.cancelDraw(),null;t=!0,this.currentAnnotation=r,this.via="draw",this.session?.dismissInteraction(),this.teardownDrawBar();const n=this.recordingManager?.getRecording()??void 0,s=await this.lifecycle.start(e||this.messages.annotation.drawing,r,n);return s?.board_url&&L(s.board_url),s},onClarify:async(e,r,n,s)=>this.apiClient.streamClarification(e,r,n,s),onAnswer:(e,r,n)=>this.apiClient.answerClarification(e,r,n),onFinalize:()=>(this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>t?this.exitAll():this.cancelDraw(),onConversationOpen:()=>this.transitionTo(new pt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}handleDrawUndoRedo(t){t==="undo"?this.session?.undoDraw():this.session?.redoDraw(),this.refreshDrawBar()}refreshDrawBar(){this.session&&this.drawBar?.setUndoRedo(this.session.canUndoDraw(),this.session.canRedoDraw())}cancelDraw(){this.session?.clearDraw(),this.releaseScrollLock(),this.teardownDrawBar(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.transitionTo(new x(this))}teardownDrawBar(){this.drawBar?.destroy(),this.drawBar=null}handleDrawSubmit(t){const e=this.session?.getDrawAnnotation();if(!e){this.cancelDraw();return}this.currentAnnotation=e,this.via="draw",this.session?.dismissInteraction();const r=t||this.messages.annotation.drawing,n=this.recordingManager?.getRecording()??void 0;this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.mountChatAfterSubmit(r,e,n)}mountChatAfterSubmit(t,e,r){this.dim=new Lt(this.shadow,()=>this.exitAll()),this.engageScrollLock(),this.chatPopup=new ct(this.shadow,{targetName:e?.targetName??this.messages.annotation.drawing,x:this.lastPopupPos?.x??window.innerWidth/2,y:this.lastPopupPos?.y??window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async()=>{const n=await this.lifecycle.start(t,e,r);return n?.board_url&&L(n.board_url),n},onClarify:async(n,s,o,a)=>this.apiClient.streamClarification(n,s,o,a),onAnswer:(n,s,o)=>this.apiClient.answerClarification(n,s,o),onFinalize:()=>(this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new pt(this)),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.chatPopup.submit(t)}mountNotePopup({x:t,y:e,targetName:r,targetRect:n}){this.lastPopupPos={x:t,y:e},this.teardownDrawBar(),this.session?.dismissInteraction(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.dim=new Lt(this.shadow,()=>this.exitAll());const s=this.recordingManager?.getRecording();s&&this.lifecycle.setScreenshotEnabled(!0);const o=this.currentAnnotation,a=this.recordingManager?.getRecording()??void 0;this.chatPopup=new ct(this.shadow,{targetName:r,x:t,y:e,targetRect:n,messages:this.messages,position:this.config.position??"right",onSubmit:async l=>{this.currentAnnotation=o??this.currentAnnotation;const c=await this.lifecycle.start(l,this.currentAnnotation,a);return c?.board_url&&L(c.board_url),c},onClarify:async(l,c,h,u)=>this.apiClient.streamClarification(l,c,h,u),onAnswer:(l,c,h)=>this.apiClient.answerClarification(l,c,h),onFinalize:()=>(this.teardownSubmittingUi(),this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new pt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture(),...s?{recordingSeconds:s.duration}:{onScreenshotToggle:l=>this.lifecycle.setScreenshotEnabled(l),screenshotEnabled:this.lifecycle.isScreenshotEnabled()}}),this.engageScrollLock(),this.lifecycle.warmScreenshotDeps()}dismissNotePopup(){this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.releaseScrollLock(),this.clearCurrentAnnotation(),this.destroySession()}engageScrollLock(){this.scrollLock||(this.scrollLock=$e())}releaseScrollLock(){this.scrollLock?.release(),this.scrollLock=null}buildMyFeedbackHandler(){if(!this.config.user&&Ir())return async()=>{const t=await this.apiClient.createIdentityToken(ye());!t?.identity_token||!t.board_url||(L(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}teardownSubmittingUi(){this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null}revertToolbarDuringClarify(){this.toolbar?.setMode(this.via==="record"?"record":"markup")}releaseClarifyUi(){this.teardownToolbar(),this.currentAnnotation=null}handleFinalized(t,e){if(this.lastHandoff={feedbackId:t.id,boardUrl:t.board_url,identityToken:t.identity_token},t.board_url&&L(t.board_url),!(this.chatPopup&&this.chatPopup.sessionId()!==e.id)&&!(!this.chatPopup&&this.state.kind!=="submitting"&&this.state.kind!=="clarifying")){if(this.chatPopup){this.chatPopup.showFinalizeSuccess(),this.teardownSubmittingUi(),this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.transitionTo(new W(this));return}this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.showSuccess({skipFollowup:e.ai_clarify_available===!1})}}showSuccess(t){this.transitionTo(new W(this)),this.success=new ki(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},{...t,onViewFeedback:this.buildViewFeedbackHandler()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!xe())return{onSubmit:async r=>{const n=await this.apiClient.updateReporter(t,r,e);return n&&Rr(r),n}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:e}=this.lastHandoff;if(t){if(e)return()=>{window.open(`${t}?identity=${encodeURIComponent(e)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{try{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}catch{}}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.lifecycle.abandon(),this.via="pin",this.transitionTo(new W(this)),this.teardownToolbar(),this.teardownDrawBar(),this.releaseScrollLock(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.chatPopup?.destroy(),this.chatPopup=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){document.removeEventListener("keydown",this.handleKeydown,!0),this.exitAll(),this.consoleCollector.stop(),this.breadcrumbCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow?.destroy()}}let v=null,E=null,_=null;function dn(){_&&(document.removeEventListener("DOMContentLoaded",_),_=null)}function M(i){dn(),v?.destroy(),v=i?new hn(i):null}const ke={init(i){typeof document>"u"||(M(),E=i,document.readyState==="loading"?(_=()=>{_=null,M(i)},document.addEventListener("DOMContentLoaded",_,{once:!0})):M(i))},destroy(){M(),E=null},setLocale(i){E&&(E.locale=i),v?.setLocale(i)},open(){v?.open()},close(){v?.close()},showLauncher(){v?.showLauncher()},hideLauncher(){v?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=ke,document.addEventListener("turbo:load",()=>{const i=document.getElementById(w);E&&(!i||!i.shadowRoot)&&(i?.remove(),M(E))}));exports.MakeThisBetter=ke;
73
+ `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",n),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),r=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${r}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class Jr{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new Gr(t,r),this.bar=new Zr(t,e,()=>this.session?.getDuration()??0,r),await this.session.start()}stop(){return this.session?(this.result=this.session.stop(),this.teardownUI(),this.result):null}getRecording(){return this.result}destroy(){this.teardownUI(),this.result=null}teardownUI(){this.session?.destroy(),this.session=null,this.bar?.destroy(),this.bar=null}}function Qr(){return{page_url:U(window.location.href),user_agent:navigator.userAgent,browser:tn(),os:en(),screen_width:window.screen.width,screen_height:window.screen.height}}function tn(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function en(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}function rn(i){const{description:t,pageContext:e,consoleErrors:r,annotation:n,user:s,recording:o,anonId:a,anonEmail:c,breadcrumbs:l}=i;return{...Q({description:t,...e,page_url:U(e.page_url),console_errors:r,annotations:n?[n]:[],target_element:n?.targetSelector?{selector:n.targetSelector,text:n.targetText??"",name:n.targetName??""}:void 0,recording_events:o?.events,recording_duration:o?.duration,breadcrumbs:l}),user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:a,reporter_email:s?void 0:c}}const nn=300,sn=5e3;class on{constructor(t,e){this.deps=t,this.host=e,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.pendingScreenshotTask=null,this.screenshotAbortController=null,this.screenshotEnabled=!0}isScreenshotEnabled(){return this.screenshotEnabled}resetScreenshotConsent(){this.screenshotEnabled=!0}setScreenshotEnabled(t){if(this.screenshotEnabled=t,t){this.warmScreenshotDeps();return}this.screenshotAbortController?.abort()}warmScreenshotDeps(){this.screenshotEnabled&&St()}start(t,e,r){const n=++this.submissionAttempt,s=this.createSubmission(t,e,r,n);return this.pendingSubmissionRequest=s,s}async createSubmission(t,e,r,n){if(await Vt(),n!==this.submissionAttempt)return null;const s=Qr(),o=rn({description:t,pageContext:s,consoleErrors:this.deps.consoleCollector.getErrors(),annotation:e,user:this.deps.user(),recording:r,anonId:ye(),anonEmail:xe(),breadcrumbs:this.deps.breadcrumbCollector.getBreadcrumbs()});let a;try{a=this.deps.apiClient.createSubmissionSession(o,null)}catch{return null}let c=null;if(this.screenshotEnabled){const h=new AbortController;c=h,this.screenshotAbortController?.abort(),this.screenshotAbortController=h;const b=(async()=>{try{const g=await zi(async(at,Se)=>{const Tt=await a;if(!(h.signal.aborted||n!==this.submissionAttempt))return this.deps.apiClient.resolveScreenshotResourceUrl(Tt.id,Tt.token,at,Se,h.signal)},h.signal);if(h.signal.aborted||n!==this.submissionAttempt||!g)return;const f=await Oi(g,e?[e]:[],this.deps.brandColors);if(h.signal.aborted||n!==this.submissionAttempt||!f)return;const m=await a;if(h.signal.aborted||n!==this.submissionAttempt)return;await this.deps.apiClient.uploadScreenshot(m.id,m.token,f,h.signal)}catch{}})().finally(()=>{this.pendingScreenshotTask===b&&(this.pendingScreenshotTask=null),this.screenshotAbortController===h&&(this.screenshotAbortController=null)});this.pendingScreenshotTask=b}let l;try{if(l=await a,n!==this.submissionAttempt)return c?.abort(),await this.deps.apiClient.abandonSubmissionSession(l.id,l.token).catch(()=>{}),null;this.activeSubmission=l}catch{return c?.abort(),null}return l}async finalize(){const t=this.submissionAttempt;this.resetScreenshotConsent();const e=this.host.isBackground(),r=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!r){if(e)return this.showFinalizeFailure({canRetry:!1});throw new Error("No active submission session")}if(await this.waitForScreenshot(),t!==this.submissionAttempt)return;const n=e?Promise.resolve():new Promise(o=>setTimeout(o,nn));let s;try{s=await this.deps.apiClient.finalizeSubmissionSession(r.id,r.token)}catch(o){if(e)return this.showFinalizeFailure({canRetry:!0});throw o}await Promise.all([n,Vt()]),!(t!==this.submissionAttempt||this.activeSubmission!==r)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.host.onFinalized(s,r))}async waitForScreenshot(){const t=this.pendingScreenshotTask;if(!t)return;let e;const r=await Promise.race([t.then(()=>!0),new Promise(n=>{e=setTimeout(()=>n(!1),sn)})]);e!==void 0&&clearTimeout(e),r||(this.screenshotAbortController?.abort(),this.pendingScreenshotTask===t&&(this.pendingScreenshotTask=null))}showFinalizeFailure(t){this.host.onFinalizeFailure(t.canRetry?()=>this.retryBackgroundFinalization():void 0)}retryBackgroundFinalization(){this.host.onReenterBackground(),this.finalize().catch(()=>this.showFinalizeFailure({canRetry:!0}))}abandon(){this.submissionAttempt+=1,this.screenshotAbortController?.abort(),this.screenshotAbortController=null,this.pendingScreenshotTask=null,this.resetScreenshotConsent();const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.deps.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{})}}function Vt(){return new Promise(i=>requestAnimationFrame(()=>setTimeout(i,0)))}function ot(i){i.preventDefault(),i.stopPropagation()}class y{constructor(t){this.host=t,this.launcherLit=!0,this.acceptsFrustrationPrompt=!1}enter(){}exit(){}handleOpen(){}handleClose(){this.host.exitAll()}handleEscape(t){}handleTabClick(){this.host.exitAll()}handleToolbarModeChange(t){}handleDrawStroke(){}}class W extends y{constructor(){super(...arguments),this.kind="idle",this.launcherLit=!1,this.acceptsFrustrationPrompt=!0}handleOpen(){this.host.dismissFrustrationPrompt(),this.host.dismissSuccess(),this.host.transitionTo(new x(this.host))}handleClose(){}handleTabClick(){this.handleOpen()}}class x extends y{constructor(){super(...arguments),this.kind="annotating"}enter(){if(!this.host.hasAnnotationChrome()){this.host.mountAnnotationChrome();return}this.host.destroyRecordingManager(),this.host.teardownDrawBar(),this.host.ensureSession()}handleEscape(t){ot(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):this.host.transitionTo(new x(this.host))}handleDrawStroke(){this.host.transitionTo(new an(this.host,S()?"sheet":"bar"))}}class Ct extends y{constructor(){super(...arguments),this.kind="recording"}enter(){this.host.clearCurrentAnnotation(),this.host.teardownDrawBar(),this.host.destroySession(),this.host.startRecorder()}handleEscape(t){ot(t),this.host.stopRecordingIntoNote()}handleToolbarModeChange(t){t!=="record"&&this.host.transitionTo(new x(this.host))}}class an extends y{constructor(t,e){super(t),this.surface=e,this.kind="drawing"}enter(){this.surface==="sheet"?this.host.mountDrawSheet():(this.host.mountDrawBar(),this.host.refreshDrawBar())}handleEscape(t){ot(t),this.host.cancelDraw()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):this.host.transitionTo(new x(this.host))}handleDrawStroke(){this.surface==="bar"&&this.host.refreshDrawBar()}}class Xt extends y{constructor(t,e){super(t),this.opts=e,this.kind="popup"}enter(){this.host.mountNotePopup(this.opts)}handleEscape(t){ot(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Ct(this.host)):(this.host.dismissNotePopup(),this.host.transitionTo(new x(this.host)))}}class pt extends y{constructor(){super(...arguments),this.kind="clarifying"}handleToolbarModeChange(t){this.host.revertToolbarDuringClarify()}}class Y extends y{constructor(){super(...arguments),this.kind="submitting",this.launcherLit=!1}enter(){this.host.releaseClarifyUi()}handleTabClick(){}}const ln=/^#[0-9a-f]{6}$/i;function cn(i){return i===void 0?void 0:typeof i!="object"||i===null||![i.primary,i.hover,i.active,i.onPrimary].every(e=>typeof e=="string"&&ln.test(e))?Kt():{primary:i.primary.toLowerCase(),hover:i.hover.toLowerCase(),active:i.active.toLowerCase(),onPrimary:i.onPrimary.toLowerCase()}}function Kt(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}function Gt(){const{hostname:i}=window.location;return i==="localhost"||i==="127.0.0.1"||i==="[::1]"||i.endsWith(".localhost")||i.endsWith(".local")||i.endsWith(".test")}class hn{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new Be,this.chatPopup=null,this.scrollLock=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.state=new W(this),this.via="pin",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=e=>{e.key==="Escape"&&(xt(e)||this.state.handleEscape(e))},this.stopRecordingIntoNote=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.transitionTo(new Xt(this,{x:window.innerWidth/2,y:window.innerHeight/2,targetName:this.messages.record.timer_label})))},this.config=t,t.projectKey||console.warn("[MakeThisBetter] projectKey is missing. Feedback submission will be rejected."),this.brandColors=cn(t.brandColors),this.messages=jt(t.locale??document.documentElement.lang??"en"),this.apiClient=new Lr({projectKey:t.projectKey,apiUrl:t.apiUrl,userToken:t.userToken,userTokenFn:t.userTokenFn}),this.consoleCollector=new rr,this.consoleCollector.start(),this.breadcrumbCollector=new cr,this.breadcrumbCollector.start(),this.lifecycle=new on({apiClient:this.apiClient,consoleCollector:this.consoleCollector,breadcrumbCollector:this.breadcrumbCollector,brandColors:this.brandColors,shadow:()=>this.shadow,messages:()=>this.messages,user:()=>this.config.user},{isBackground:()=>this.state.kind==="submitting",onFinalizeFailure:e=>this.chatPopup?.showFinalizeFailure(e),onReenterBackground:()=>this.transitionTo(new Y(this)),onFinalized:(e,r)=>this.handleFinalized(e,r)});try{this.buildUI()}catch(e){this.consoleCollector.stop(),this.breadcrumbCollector.stop(),console.warn("[MakeThisBetter] Widget failed to start:",e);return}t.frustrationDetection!==!1&&(this.frustrationDetector=new wt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}transitionTo(t){const e=this.state;this.state=t,e.exit(),t.enter(),this.tab?.setActive(t.launcherLit)}buildUI(){if(this.shadow=new ft(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Gt()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(S()){Gt()&&console.warn("[MakeThisBetter] No launcher is rendered on touch devices. Call MakeThisBetter.open() from your own mobile UI.");return}this.mountTab()}mountTab(){this.tab||!this.shadow||(this.tab=new Ie(this.shadow,this.messages,this.config.position??"right",()=>this.state.handleTabClick(),this.config.tabText))}open(){this.shadow&&this.state.handleOpen()}close(){this.state.handleClose()}showLauncher(){S()||(this.mountTab(),this.tab?.setActive(this.state.launcherLit))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=jt(t),this.tab?.setMessages(this.messages)}handleFrustration(){!this.state.acceptsFrustrationPrompt||this.frustrationPrompt||hr()||(this.frustrationPrompt=new Ne(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.state.handleOpen()},onDismiss:()=>{dr(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissSuccess(){this.success?.destroy(),this.success=null,this.chatPopup?.destroy(),this.chatPopup=null}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}hasAnnotationChrome(){return this.toolbar!==null}mountAnnotationChrome(){St();const t=S();this.toolbar=new qe(this.shadow,this.messages,()=>this.exitAll(),e=>this.state.handleToolbarModeChange(e),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.ensureSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}ensureSession(){this.session||(this.session=new si(this.shadow,this.messages,{onPin:(t,e)=>{this.currentAnnotation=t,this.via="pin",this.transitionTo(new Xt(this,{x:t.x,y:t.y,targetName:e,targetRect:t.targetRect}))},onDrawStroke:()=>this.state.handleDrawStroke()}))}destroySession(){this.session?.destroy(),this.session=null}clearCurrentAnnotation(){this.currentAnnotation=null}startRecorder(){this.recordingManager=new Jr,this.recordingManager.start(this.shadow,this.messages,this.stopRecordingIntoNote).catch(t=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",t),this.state.kind==="recording"&&(this.toolbar?.setMode("markup"),this.state.handleToolbarModeChange("markup"))})}destroyRecordingManager(){this.recordingManager?.destroy(),this.recordingManager=null}mountDrawBar(){this.engageScrollLock(),this.drawBar=new hi(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t),onActivity:()=>this.lifecycle.warmScreenshotDeps()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}mountDrawSheet(){this.engageScrollLock();let t=!1;this.chatPopup=new ct(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async e=>{const r=this.session?.getDrawAnnotation();if(!r)return this.cancelDraw(),null;t=!0,this.currentAnnotation=r,this.via="draw",this.session?.dismissInteraction(),this.teardownDrawBar();const n=this.recordingManager?.getRecording()??void 0,s=await this.lifecycle.start(e||this.messages.annotation.drawing,r,n);return s?.board_url&&L(s.board_url),s},onClarify:async(e,r,n,s)=>this.apiClient.streamClarification(e,r,n,s),onAnswer:(e,r,n)=>this.apiClient.answerClarification(e,r,n),onFinalize:()=>(this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>t?this.exitAll():this.cancelDraw(),onConversationOpen:()=>this.transitionTo(new pt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}handleDrawUndoRedo(t){t==="undo"?this.session?.undoDraw():this.session?.redoDraw(),this.refreshDrawBar()}refreshDrawBar(){this.session&&this.drawBar?.setUndoRedo(this.session.canUndoDraw(),this.session.canRedoDraw())}cancelDraw(){this.session?.clearDraw(),this.releaseScrollLock(),this.teardownDrawBar(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.transitionTo(new x(this))}teardownDrawBar(){this.drawBar?.destroy(),this.drawBar=null}handleDrawSubmit(t){const e=this.session?.getDrawAnnotation();if(!e){this.cancelDraw();return}this.currentAnnotation=e,this.via="draw",this.session?.dismissInteraction();const r=t||this.messages.annotation.drawing,n=this.recordingManager?.getRecording()??void 0;this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.mountChatAfterSubmit(r,e,n)}mountChatAfterSubmit(t,e,r){this.dim=new Lt(this.shadow,()=>this.exitAll()),this.engageScrollLock(),this.chatPopup=new ct(this.shadow,{targetName:e?.targetName??this.messages.annotation.drawing,x:this.lastPopupPos?.x??window.innerWidth/2,y:this.lastPopupPos?.y??window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async()=>{const n=await this.lifecycle.start(t,e,r);return n?.board_url&&L(n.board_url),n},onClarify:async(n,s,o,a)=>this.apiClient.streamClarification(n,s,o,a),onAnswer:(n,s,o)=>this.apiClient.answerClarification(n,s,o),onFinalize:()=>(this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new pt(this)),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.chatPopup.submit(t)}mountNotePopup({x:t,y:e,targetName:r,targetRect:n}){this.lastPopupPos={x:t,y:e},this.teardownDrawBar(),this.session?.dismissInteraction(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.dim=new Lt(this.shadow,()=>this.exitAll());const s=this.recordingManager?.getRecording();s&&this.lifecycle.setScreenshotEnabled(!0);const o=this.currentAnnotation,a=this.recordingManager?.getRecording()??void 0;this.chatPopup=new ct(this.shadow,{targetName:r,x:t,y:e,targetRect:n,messages:this.messages,position:this.config.position??"right",onSubmit:async c=>{this.currentAnnotation=o??this.currentAnnotation;const l=await this.lifecycle.start(c,this.currentAnnotation,a);return l?.board_url&&L(l.board_url),l},onClarify:async(c,l,h,u)=>this.apiClient.streamClarification(c,l,h,u),onAnswer:(c,l,h)=>this.apiClient.answerClarification(c,l,h),onFinalize:()=>(this.teardownSubmittingUi(),this.transitionTo(new Y(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new pt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture(),...s?{recordingSeconds:s.duration}:{onScreenshotToggle:c=>this.lifecycle.setScreenshotEnabled(c),screenshotEnabled:this.lifecycle.isScreenshotEnabled()}}),this.engageScrollLock(),this.lifecycle.warmScreenshotDeps()}dismissNotePopup(){this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.releaseScrollLock(),this.clearCurrentAnnotation(),this.destroySession()}engageScrollLock(){this.scrollLock||(this.scrollLock=$e())}releaseScrollLock(){this.scrollLock?.release(),this.scrollLock=null}buildMyFeedbackHandler(){if(!this.config.user&&Ir())return async()=>{const t=await this.apiClient.createIdentityToken(ye());!t?.identity_token||!t.board_url||(L(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}teardownSubmittingUi(){this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null}revertToolbarDuringClarify(){this.toolbar?.setMode(this.via==="record"?"record":"markup")}releaseClarifyUi(){this.teardownToolbar(),this.currentAnnotation=null}handleFinalized(t,e){if(this.lastHandoff={feedbackId:t.id,boardUrl:t.board_url,identityToken:t.identity_token},t.board_url&&L(t.board_url),!(this.chatPopup&&this.chatPopup.sessionId()!==e.id)&&!(!this.chatPopup&&this.state.kind!=="submitting"&&this.state.kind!=="clarifying")){if(this.chatPopup){this.chatPopup.showFinalizeSuccess(),this.teardownSubmittingUi(),this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.transitionTo(new W(this));return}this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.showSuccess({skipFollowup:e.ai_clarify_available===!1})}}showSuccess(t){this.transitionTo(new W(this)),this.success=new ki(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},{...t,onViewFeedback:this.buildViewFeedbackHandler()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!xe())return{onSubmit:async r=>{const n=await this.apiClient.updateReporter(t,r,e);return n&&Rr(r),n}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:e}=this.lastHandoff;if(t){if(e)return()=>{window.open(`${t}?identity=${encodeURIComponent(e)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{try{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}catch{}}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.lifecycle.abandon(),this.via="pin",this.transitionTo(new W(this)),this.teardownToolbar(),this.teardownDrawBar(),this.releaseScrollLock(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.chatPopup?.destroy(),this.chatPopup=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){document.removeEventListener("keydown",this.handleKeydown,!0),this.exitAll(),this.consoleCollector.stop(),this.breadcrumbCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow?.destroy()}}let v=null,E=null,_=null;function dn(){_&&(document.removeEventListener("DOMContentLoaded",_),_=null)}function M(i){dn(),v?.destroy(),v=i?new hn(i):null}const ke={init(i){typeof document>"u"||(M(),E=i,document.readyState==="loading"?(_=()=>{_=null,M(i)},document.addEventListener("DOMContentLoaded",_,{once:!0})):M(i))},destroy(){M(),E=null},setLocale(i){E&&(E.locale=i),v?.setLocale(i)},open(){v?.open()},close(){v?.close()},showLauncher(){v?.showLauncher()},hideLauncher(){v?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=ke,document.addEventListener("turbo:load",()=>{const i=document.getElementById(w);E&&(!i||!i.shadowRoot)&&(i?.remove(),M(E))}));exports.MakeThisBetter=ke;
74
74
  //# sourceMappingURL=makethisbetter.cjs.map