makethisbetter 1.21.1 → 1.21.2
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.
- package/dist/makethisbetter.cjs +17 -15
- package/dist/makethisbetter.cjs.map +1 -1
- package/dist/makethisbetter.esm.js +285 -285
- package/dist/makethisbetter.esm.js.map +1 -1
- package/dist/makethisbetter.js +17 -15
- package/dist/makethisbetter.js.map +1 -1
- package/dist/popup/clarify.d.ts.map +1 -1
- package/dist/screenshot/capture.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/popup/clarify.ts +7 -4
- package/src/screenshot/capture.ts +1 -10
package/dist/makethisbetter.cjs
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
<path d="M18 6L6 18M6 6l12 12"/>
|
|
21
21
|
</svg><span class="mtb-toolbar-label">${c(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||Ve}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),document.removeEventListener("pointerdown",this.dismissTouchHint,!0),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class Xe{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 Ke{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=bt(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()}}const Ge=/^(script|style|noscript|template)$/i;function te(i,t=80){let e="";for(const r of Array.from(i.childNodes)){if(e.length>=t)break;r.nodeType===3?e+=r.nodeValue??"":r instanceof Element&&!Ge.test(r.tagName)&&(e+=te(r,t-e.length))}return e}function bt(i){if(i instanceof HTMLElement){const t=i.getAttribute("aria-label");if(t)return t;const e=i.getAttribute("title");if(e)return e;const r=te(i).trim().slice(0,40);if(r)return r;const n=i.placeholder;if(n)return n;const s=i.alt;if(s)return s;const o=i.getAttribute("data-mark");if(o)return o}return i.tagName.toLowerCase()}function ee(i){const t=[];let e=i;for(;e&&e!==document.body&&t.length<5;){let r=e.tagName.toLowerCase();if(e.id){r=`#${e.id}`,t.unshift(r);break}const n=Array.from(e.classList).filter(o=>!o.startsWith("mtb-")).slice(0,2).join(".");n&&(r+=`.${n}`);const s=e.parentElement;if(s){const o=Array.from(s.children).filter(a=>a.tagName===e.tagName);if(o.length>1){const a=o.indexOf(e)+1;r+=`:nth-of-type(${a})`}}t.unshift(r),e=e.parentElement}return t.join(" > ")}class Je{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 pt="#059669",Ze='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',P={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 Qe{constructor(t){this.currentPath=null,this.currentPoints=[],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.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,e){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,e]),this.currentPath.setAttribute("d",kt(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:kt(this.currentPoints),points:this.currentPoints}),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}),!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}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){if(this.committed.length===0)return null;const t=this.committed.flatMap(n=>n.points),[e,r]=ti(t);return{type:"draw",x:e,y:r,drawPath:this.committed.map(n=>n.d).join(" ")}}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",P.color),t.setAttribute("stroke-width",P.width),t.setAttribute("stroke-linecap",P.linecap),t.setAttribute("stroke-linejoin",P.linejoin),t.setAttribute("style",`filter:${P.filter}`),t}}function kt(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 ti(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 f="[Filtered]",ei=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,ii=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,ri=[/\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],ni=/\b(?:\d[ -]?){12,18}\d\b/g,si=/\bhttps?:\/\/[^\s<>"']+/gi,oi=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),ai=new Set(["value","content"]),li=new Set(["password","hidden","file"]),ci=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),di=/(?:^|_)(?: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 A(i){let t=i.replace(ei,f).replace(ii,f);for(const e of ri)t=t.replace(e,f);return t=t.replace(ni,e=>hi(e)?f:e),t.replace(si,e=>O(e)||f)}function O(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function V(i,t){if(t&&ie(t)&&i!=null)return f;if(typeof i=="string")return A(i);if(Array.isArray(i))return i.map(e=>V(e));if(i&&typeof i=="object"){const e=re(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&ai.has(I(n))&&s!=null?f:V(s,n);return[A(n),o]}))}return i}function ie(i){return di.test(I(i))}function re(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return oi.has(r)?r==="type"?li.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>ci.has(I(n))):ie(e):!1})}function I(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 hi(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 ne(i){return re({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 Y(i,t){return i&&(ne(t)?f:A(i))}const ui=512;function se(){return new WeakMap}function oe(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ae(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ae(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>ui?n="too-large":A(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ae(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}const mi=60,St=["value","content"],bi=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])),Q="rr-block",U="rr-mask",pi="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",fi="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let N=null;function gi(){return N||(N=vi().catch(()=>wi()),N)}function yi(i,t){const e=V(i);return dt(e,t,se()),e}function dt(i,t,e){if(Array.isArray(i)){i.forEach(a=>dt(a,t,e));return}if(!Et(i))return;const r=Et(i.attributes)?i.attributes:null,n=r&&St.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=Y(i.text,o)),r)for(const a of St){const l=r[a];typeof l=="string"&&(r[a]=Y(l,o))}}else o?.nodeType===Node.TEXT_NODE&&oe(o,e)&&(typeof i.textContent=="string"&&(i.textContent=f),typeof i.value=="string"&&(i.value=f));Object.values(i).forEach(a=>dt(a,t,e))}function Et(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function vi(){return(await import("@rrweb/record")).record}function Tt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function wi(){return new Promise((i,t)=>{const e=Tt();if(e){i(e);return}const r=document.createElement("script");r.src=pi,r.integrity=fi,r.crossOrigin="anonymous",r.onload=()=>{const n=Tt();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 xi{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 gi();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(yi(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:bi,maskInputFn:(e,r)=>r.closest(`.${U}`)?f:Y(e,r),maskTextFn:()=>f,blockClass:Q,maskTextClass:U}),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?.()},mi*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())}}const ki=`.${Q}, .${U}`;function tt(i){return i.closest(ki)!==null}function ft(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 le(i){return i.tagName.toLowerCase()}const Si=10;function Ct(i){return tt(i)?{name:ft(i),text:"",selector:le(i)}:{name:bt(i),text:i.textContent?.trim().slice(0,200)??"",selector:ee(i)}}class Ei{constructor(t,e,r){this.messages=e,this.handlers=r,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.touch=w(),this.highlighter=new Ke(t),this.pinMarker=new Je(t),this.drawLayer=new Qe(t),this.overlay=new Xe(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=it(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()>=Si){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const e=it(t.clientX,t.clientY),r=e?Ct(e):null,n=r?.name??this.messages.annotation.element,s=e?.getBoundingClientRect(),o={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};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(o,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=it(t.x,t.y);if(!e)return t;const r=e.getBoundingClientRect(),n=Ct(e);return{...t,targetSelector:n.selector,targetText:n.text,targetName:n.name,targetRect:{top:r.top,left:r.left,width:r.width,height:r.height,bottom:r.bottom}}}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()}}function it(i,t){return document.elementsFromPoint(i,t).find(e=>e.id!=="mtb-widget-host")??null}const Ti=140;class Ci{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()},Ti)}}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 _i=480;function Li(){return window.innerWidth<=_i}class gt{constructor(t){this.el=t,this.inset=new Ci}apply(){return Li()?(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 Ai{constructor(t,e){this.onSubmit=e.onSubmit,this.submitLabel=e.messages.draw.submit,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(e.messages),t.append(this.el),this.sheet=new gt(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()),this.input.addEventListener("keydown",r=>{r.isComposing||r.keyCode===229||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||Ve}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),document.removeEventListener("pointerdown",this.dismissTouchHint,!0),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class Xe{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 Ke{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=bt(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()}}const Ge=/^(script|style|noscript|template)$/i;function te(i,t=80){let e="";for(const r of Array.from(i.childNodes)){if(e.length>=t)break;r.nodeType===3?e+=r.nodeValue??"":r instanceof Element&&!Ge.test(r.tagName)&&(e+=te(r,t-e.length))}return e}function bt(i){if(i instanceof HTMLElement){const t=i.getAttribute("aria-label");if(t)return t;const e=i.getAttribute("title");if(e)return e;const r=te(i).trim().slice(0,40);if(r)return r;const n=i.placeholder;if(n)return n;const s=i.alt;if(s)return s;const o=i.getAttribute("data-mark");if(o)return o}return i.tagName.toLowerCase()}function ee(i){const t=[];let e=i;for(;e&&e!==document.body&&t.length<5;){let r=e.tagName.toLowerCase();if(e.id){r=`#${e.id}`,t.unshift(r);break}const n=Array.from(e.classList).filter(o=>!o.startsWith("mtb-")).slice(0,2).join(".");n&&(r+=`.${n}`);const s=e.parentElement;if(s){const o=Array.from(s.children).filter(a=>a.tagName===e.tagName);if(o.length>1){const a=o.indexOf(e)+1;r+=`:nth-of-type(${a})`}}t.unshift(r),e=e.parentElement}return t.join(" > ")}class Je{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 pt="#059669",P={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 Ze{constructor(t){this.currentPath=null,this.currentPoints=[],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.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,e){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,e]),this.currentPath.setAttribute("d",kt(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:kt(this.currentPoints),points:this.currentPoints}),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}),!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}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){if(this.committed.length===0)return null;const t=this.committed.flatMap(n=>n.points),[e,r]=Qe(t);return{type:"draw",x:e,y:r,drawPath:this.committed.map(n=>n.d).join(" ")}}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",P.color),t.setAttribute("stroke-width",P.width),t.setAttribute("stroke-linecap",P.linecap),t.setAttribute("stroke-linejoin",P.linejoin),t.setAttribute("style",`filter:${P.filter}`),t}}function kt(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(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 f="[Filtered]",ti=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,ei=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,ii=[/\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],ri=/\b(?:\d[ -]?){12,18}\d\b/g,ni=/\bhttps?:\/\/[^\s<>"']+/gi,si=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),oi=new Set(["value","content"]),ai=new Set(["password","hidden","file"]),li=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),ci=/(?:^|_)(?: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 A(i){let t=i.replace(ti,f).replace(ei,f);for(const e of ii)t=t.replace(e,f);return t=t.replace(ri,e=>di(e)?f:e),t.replace(ni,e=>O(e)||f)}function O(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function V(i,t){if(t&&ie(t)&&i!=null)return f;if(typeof i=="string")return A(i);if(Array.isArray(i))return i.map(e=>V(e));if(i&&typeof i=="object"){const e=re(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&oi.has(I(n))&&s!=null?f:V(s,n);return[A(n),o]}))}return i}function ie(i){return ci.test(I(i))}function re(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return si.has(r)?r==="type"?ai.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>li.has(I(n))):ie(e):!1})}function I(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 di(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 ne(i){return re({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 Y(i,t){return i&&(ne(t)?f:A(i))}const hi=512;function se(){return new WeakMap}function oe(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ae(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ae(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>hi?n="too-large":A(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ae(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}const ui=60,St=["value","content"],mi=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])),Q="rr-block",U="rr-mask",bi="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",pi="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let N=null;function fi(){return N||(N=yi().catch(()=>vi()),N)}function gi(i,t){const e=V(i);return dt(e,t,se()),e}function dt(i,t,e){if(Array.isArray(i)){i.forEach(a=>dt(a,t,e));return}if(!Et(i))return;const r=Et(i.attributes)?i.attributes:null,n=r&&St.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=Y(i.text,o)),r)for(const a of St){const l=r[a];typeof l=="string"&&(r[a]=Y(l,o))}}else o?.nodeType===Node.TEXT_NODE&&oe(o,e)&&(typeof i.textContent=="string"&&(i.textContent=f),typeof i.value=="string"&&(i.value=f));Object.values(i).forEach(a=>dt(a,t,e))}function Et(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}async function yi(){return(await import("@rrweb/record")).record}function Tt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function vi(){return new Promise((i,t)=>{const e=Tt();if(e){i(e);return}const r=document.createElement("script");r.src=bi,r.integrity=pi,r.crossOrigin="anonymous",r.onload=()=>{const n=Tt();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 wi{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 fi();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{if(!this.stopped)try{this.events.push(gi(e,t))}catch{}},maskAllInputs:!1,maskInputOptions:mi,maskInputFn:(e,r)=>r.closest(`.${U}`)?f:Y(e,r),maskTextFn:()=>f,blockClass:Q,maskTextClass:U}),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?.()},ui*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())}}const xi=`.${Q}, .${U}`;function tt(i){return i.closest(xi)!==null}function ft(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 le(i){return i.tagName.toLowerCase()}const ki=10;function Ct(i){return tt(i)?{name:ft(i),text:"",selector:le(i)}:{name:bt(i),text:i.textContent?.trim().slice(0,200)??"",selector:ee(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=w(),this.highlighter=new Ke(t),this.pinMarker=new Je(t),this.drawLayer=new Ze(t),this.overlay=new Xe(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=it(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()>=ki){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const e=it(t.clientX,t.clientY),r=e?Ct(e):null,n=r?.name??this.messages.annotation.element,s=e?.getBoundingClientRect(),o={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};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(o,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=it(t.x,t.y);if(!e)return t;const r=e.getBoundingClientRect(),n=Ct(e);return{...t,targetSelector:n.selector,targetText:n.text,targetName:n.name,targetRect:{top:r.top,left:r.left,width:r.width,height:r.height,bottom:r.bottom}}}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()}}function it(i,t){return document.elementsFromPoint(i,t).find(e=>e.id!=="mtb-widget-host")??null}const Ei=140;class Ti{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()},Ei)}}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 Ci=480;function _i(){return window.innerWidth<=Ci}class gt{constructor(t){this.el=t,this.inset=new Ti}apply(){return _i()?(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 Li{constructor(t,e){this.onSubmit=e.onSubmit,this.submitLabel=e.messages.draw.submit,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(e.messages),t.append(this.el),this.sheet=new gt(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()),this.input.addEventListener("keydown",r=>{r.isComposing||r.keyCode===229||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="${c(t.draw.note_placeholder)}" />
|
|
25
25
|
<button class="mtb-draw-icon-btn mtb-draw-undo" type="button" title="${c(t.draw.undo)}" aria-label="${c(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>
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
<span class="mtb-draw-sep"></span>
|
|
32
32
|
<button class="mtb-draw-cancel" type="button">${c(t.draw.cancel)}</button>
|
|
33
33
|
<button class="mtb-draw-submit" type="button">${c(t.draw.submit)}</button>
|
|
34
|
-
`}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()}}function
|
|
34
|
+
`}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()}}function Ai(i){let t=!1;const e=()=>{t=!0},r=n=>{n.detail>0&&!t&&(n.stopPropagation(),n.preventDefault()),t=!1};return i.addEventListener("pointerdown",e,!0),i.addEventListener("click",r,!0),()=>{i.removeEventListener("pointerdown",e,!0),i.removeEventListener("click",r,!0)}}class _t{constructor(t,e){this.releaseGuard=null,this.selectedQuickOption=null,this.onSubmit=e.onSubmit,this.onClose=e.onClose,this.submitLabel=e.messages.popup.submit,this.messages=e.messages,this.el=t.el("div","mtb-popup"),this.el.innerHTML=this.buildHTML(e),t.append(this.el),this.sheet=new gt(this.el),w()&&(this.releaseGuard=Ai(this.el)),this.textarea=this.el.querySelector(".mtb-textarea"),this.submitBtn=this.el.querySelector(".mtb-submit-btn"),this.positionPopup(e.x,e.y,e.targetRect,e.position??"right"),this.bindEvents(e.messages),e.onMyFeedback&&this.el.querySelector(".mtb-my-feedback").addEventListener("click",e.onMyFeedback),w()||this.textarea.focus({preventScroll:!0})}buildHTML(t){const e=t.messages,r=e.popup.quickOptions.map(n=>`
|
|
35
35
|
<button class="mtb-quick-option" data-quick="${c(n.label)}">
|
|
36
36
|
<span class="mtb-quick-option-emoji">${c(n.emoji)}</span>
|
|
37
37
|
<span>${c(n.label)}</span>
|
|
@@ -62,15 +62,17 @@
|
|
|
62
62
|
</div>
|
|
63
63
|
${t.onMyFeedback?`<button class="mtb-my-feedback" type="button">${c(e.popup.my_feedback)}</button>`:""}
|
|
64
64
|
</div>
|
|
65
|
-
`}positionPopup(t,e,r,n){if(this.sheet.apply())return;const s=window.innerWidth,o=window.innerHeight,a=12,l=8,d=32,u=Math.min(320,s-2*a-d),
|
|
66
|
-
`).find(
|
|
67
|
-
`).find(
|
|
65
|
+
`}positionPopup(t,e,r,n){if(this.sheet.apply())return;const s=window.innerWidth,o=window.innerHeight,a=12,l=8,d=32,u=Math.min(320,s-2*a-d),h=this.el.offsetHeight||260,m=a+(n==="left"?d:0),y=s-a-(n==="right"?d:0);let v,g;const Pe=r&&r.width<s*.6&&r.height<o*.6;r&&Pe?(v=r.left,g=r.bottom+l,g+h>o-a&&(g=r.top-h-l),g<a&&(g=Math.min(r.bottom+l,o-h-a))):(v=t+12,g=e+12),v+u>y&&(v=y-u),v<m&&(v=m),g<a&&(g=a),this.el.style.left=`${v}px`,this.el.style.top=`${g}px`,this.el.style.maxHeight=`${o-g-a}px`}bindEvents(t){this.el.querySelector(".mtb-popup-close").addEventListener("click",()=>this.onClose()),this.el.querySelector(".mtb-cancel-btn").addEventListener("click",()=>this.onClose()),this.el.querySelectorAll(".mtb-quick-option").forEach(e=>{e.addEventListener("click",()=>{const r=e.dataset.quick??"";if(this.textarea.value.trim().length===0){this.textarea.value=r,this.updateSubmitState(),this.submit();return}this.selectedQuickOption=r,this.el.querySelectorAll(".mtb-quick-option").forEach(n=>{n.classList.toggle("selected",n===e)})})}),this.textarea.addEventListener("input",()=>this.updateSubmitState()),this.textarea.addEventListener("keydown",e=>{e.isComposing||e.keyCode===229||e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.submit())}),this.submitBtn.addEventListener("click",()=>this.submit())}updateSubmitState(){const t=this.textarea.value.trim().length>0;this.submitBtn.classList.toggle("ready",t),this.submitBtn.disabled=!t}submit(){const t=this.textarea.value.trim();if(!t)return;const e=this.selectedQuickOption?`[${this.selectedQuickOption}] ${t}`:t;this.onSubmit(e)}releaseElement(){return this.releaseGuard?.(),this.releaseGuard=null,this.sheet.release(),this.el}destroy(){this.releaseGuard?.(),this.releaseGuard=null,this.sheet.release(),this.el.remove()}}class ce extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}function Pi(i){return i instanceof ce&&i.status===409}const Mi="https://makethisbetter.dev/api/v1",Ri="sensitive-data-v1";class Ii{constructor(t,e,r=1e3,n,s){this.projectKey=t,this.apiUrl=(e??Mi).replace(/\/$/,""),this.retryDelayMs=r,this.userToken=n,this.userTokenFn=s}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}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=Fi(),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),d=new Blob([l],{type:"application/json"});n.append("feedback[recording]",d,"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"]=Ri,s["X-Idempotency-Key"]=Hi(),{...(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 startClarification(t,e,r){const n={};return r&&(n.message=A(r)),this.requestClarification(t,e,n)}async retryClarification(t,e){return this.requestClarification(t,e,{retry:!0})}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 getClarification(t,e){const r=await this.submissionHeaders(e);return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"GET",headers: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 Di(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e);return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r})).json()).feedback}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)return await Lt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await Lt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new ce(n.status)}}function Lt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Di(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
|
|
66
|
+
`).find(m=>m.startsWith("event:")),d=a.split(`
|
|
67
|
+
`).find(m=>m.startsWith("data:"));if(!d)return;const u=l?.slice(6).trim(),h=JSON.parse(d.slice(5).trim());u==="delta"&&typeof h.text=="string"?t(h.text):u==="done"&&(s={messages:Array.isArray(h.messages)?h.messages:[],done:h.done!==!1,failed:h.error===!0})};for(;;){const{done:a,value:l}=await e.read();if(a)break;n+=r.decode(l,{stream:!0});let d;for(;(d=n.indexOf(`
|
|
68
68
|
|
|
69
|
-
`))!==-1;){const u=n.slice(0,d);n=n.slice(d+2);try{o(u)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function
|
|
69
|
+
`))!==-1;){const u=n.slice(0,d);n=n.slice(d+2);try{o(u)}catch{}}}if(n+=r.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Hi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Fi(){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 $i=2e3,Bi=45e3,At=12e3,Oi=346,Ui=270;class Ni{constructor(t,e){this.pollTimer=null,this.pollDeadline=0,this.streamingBubble=null,this.lastMessages=[],this.done=!1,this.sending=!1,this.finalSubmissionStarted=!1,this.finalizing=!1,this.destroyed=!1,this.keyboardListenerTimer=null,this.streamAbort=null,this.unrecoverable=!1,this.submissionFailed=!1,this.handleKeydown=n=>{n.isComposing||n.keyCode===229||n.key!=="Enter"||n.shiftKey||n.composedPath().includes(this.inputEl)||(n.preventDefault(),this.skipAndFinalize())},this.submissionSessionId=e.submissionSessionId??"",this.submissionToken=e.submissionToken??"",this.apiClient=e.apiClient,this.onFinalize=e.onFinalize,this.onCancel=e.onCancel,this.i18n=e.messages,this.pendingSession=e.pendingSession,this.onRetrySubmission=e.onRetrySubmission;const r=e.element;this.el=r??t.el("div","mtb-clarify"),this.el.className=r?"mtb-clarify mtb-clarify-continuation":"mtb-clarify",this.el.innerHTML=this.buildHTML(e.messages),this.sheet=new gt(this.el),r?this.sheet.apply():(t.append(this.el),this.positionCard(e.x,e.y,e.position??"right")),this.messagesEl=this.el.querySelector(".mtb-clarify-messages"),this.bindEvents(),this.keyboardListenerTimer=setTimeout(()=>{this.keyboardListenerTimer=null,this.destroyed||window.addEventListener("keydown",this.handleKeydown)},0),this.startConversation()}positionCard(t,e,r){if(this.sheet.apply())return;const n=window.innerWidth,s=window.innerHeight,o=12,a=32,l=Math.min(Oi,n-2*o-a),d=this.el.offsetHeight||Ui,u=o+(r==="left"?a:0),h=n-o-(r==="right"?a:0);if(t===void 0||e===void 0){const v=Math.max(u,(n-l)/2);this.el.style.left=`${Math.min(v,h-l)}px`,this.el.style.top=`${Math.max(o,(s-d)/2)}px`,this.el.style.maxHeight=`${s-2*o}px`;return}let m=t+12,y=e+12;m+l>h&&(m=t-l-12),m+l>h&&(m=h-l),m<u&&(m=u),y+d>s-o&&(y=s-d-o),y<o&&(y=o),this.el.style.left=`${m}px`,this.el.style.top=`${y}px`,this.el.style.maxHeight=`${s-y-o}px`}buildHTML(t){return`
|
|
70
70
|
<div class="mtb-clarify-header">
|
|
71
71
|
<span class="mtb-clarify-icon">
|
|
72
|
-
<svg width="
|
|
73
|
-
<path d="
|
|
72
|
+
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--mtb-brand-on-primary)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
|
|
73
|
+
<path d="M21 2v6h-6"/>
|
|
74
|
+
<path d="M21 13a9 9 0 1 1-3-7.7L21 8"/>
|
|
75
|
+
<circle cx="12" cy="12" r="2.2" fill="var(--mtb-brand-on-primary)" stroke="none"/>
|
|
74
76
|
</svg>
|
|
75
77
|
</span>
|
|
76
78
|
<div class="mtb-clarify-titles">
|
|
@@ -98,10 +100,10 @@
|
|
|
98
100
|
<span class="mtb-clarify-send-spinner" aria-hidden="true"></span>
|
|
99
101
|
</button>
|
|
100
102
|
</div>
|
|
101
|
-
`}bindEvents(){this.el.querySelector(".mtb-clarify-close").addEventListener("click",()=>this.skipAndFinalize()),this.bindConversationControls()}bindConversationControls(){this.inputEl=this.el.querySelector(".mtb-clarify-input"),this.sendBtn=this.el.querySelector(".mtb-clarify-send"),this.el.querySelector(".mtb-clarify-skip").addEventListener("click",()=>this.skipAndFinalize()),this.inputEl.addEventListener("input",()=>{this.sendBtn.disabled=!this.inputEl.value.trim()}),this.inputEl.addEventListener("keydown",t=>{t.isComposing||t.keyCode===229||t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.sendMessage())}),this.sendBtn.addEventListener("click",()=>this.sendMessage())}skipAndFinalize(){if(this.submissionFailed){this.onCancel?.();return}this.
|
|
103
|
+
`}bindEvents(){this.el.querySelector(".mtb-clarify-close").addEventListener("click",()=>this.skipAndFinalize()),this.bindConversationControls()}bindConversationControls(){this.inputEl=this.el.querySelector(".mtb-clarify-input"),this.sendBtn=this.el.querySelector(".mtb-clarify-send"),this.el.querySelector(".mtb-clarify-skip").addEventListener("click",()=>this.skipAndFinalize()),this.inputEl.addEventListener("input",()=>{this.sendBtn.disabled=!this.inputEl.value.trim()}),this.inputEl.addEventListener("keydown",t=>{t.isComposing||t.keyCode===229||t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.sendMessage())}),this.sendBtn.addEventListener("click",()=>this.sendMessage())}skipAndFinalize(){if(this.submissionFailed){this.onCancel?.();return}this.finalize(),this.destroy()}async startConversation(){if(this.showThinking(),this.pendingSession){this.inputEl.disabled=!0,await this.adoptSession(this.pendingSession);return}await this.runInitialTurn()}async adoptSession(t){let e;try{e=await t}catch{e=null}if(!this.destroyed){if(!e){this.showSubmissionFailure();return}if(this.submissionSessionId=e.id,this.submissionToken=e.token,!this.finalizing){if(this.inputEl.disabled=!1,!e.ai_clarify_available){this.applyResult({messages:[],done:!0});return}await this.runInitialTurn()}}}showSubmissionFailure(){this.submissionFailed=!0,this.stopPolling(),this.removeThinking();const t=this.el.querySelector(".mtb-clarify-footer");t.innerHTML=`
|
|
102
104
|
<div class="mtb-clarify-error">${c(this.i18n.error.submit)}</div>
|
|
103
105
|
<button class="mtb-clarify-send-feedback mtb-clarify-retry" type="button">${c(this.i18n.clarify.retry)}</button>
|
|
104
|
-
`,t.querySelector(".mtb-clarify-retry").addEventListener("click",()=>{this.destroyed||this.retrySubmission()})}async retrySubmission(){!this.onRetrySubmission||this.sending||(this.submissionFailed=!1,this.showConversationControls(),this.inputEl.disabled=!0,this.showThinking(),await this.adoptSession(this.onRetrySubmission()))}async sendMessage(){const t=this.inputEl.value.trim();if(!(!t||this.sending||!this.submissionSessionId)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-busy","true"),this.stopPolling(),this.finalSubmissionStarted=!0,this.appendMessage({role:"user",content:t}),this.inputEl.value="",this.clearError();try{await this.runAnswerTurn(t)}catch{if(this.destroyed)return;this.finalSubmissionStarted=!1,this.sending=!1,this.renderConversation(this.lastMessages,!1),this.inputEl.value=t,this.showError(),this.sendBtn.removeAttribute("aria-busy"),this.inputEl.disabled=!1,this.sendBtn.disabled=!this.inputEl.value.trim(),this.inputEl.focus({preventScroll:!0})}}}async runInitialTurn(){const t=new AbortController;this.streamAbort=t;let e=setTimeout(()=>t.abort(),At);try{const r=await this.apiClient.streamClarification(this.submissionSessionId,this.submissionToken,n=>{clearTimeout(e),e=setTimeout(()=>t.abort(),At),this.appendStreamDelta(n)},t.signal);if(this.destroyed)return;this.endStreamingBubble(),this.applyResult(r)||this.startPolling()}catch{if(this.destroyed||this.finalizing)return;this.endStreamingBubble(),await this.runInitialTurnViaPolling()}finally{clearTimeout(e),this.streamAbort===t&&(this.streamAbort=null)}}async runInitialTurnViaPolling(){try{const t=await this.apiClient.startClarification(this.submissionSessionId,this.submissionToken);if(this.destroyed||this.finalizing)return;this.applyResult(t)||this.startPolling()}catch{if(this.destroyed||this.finalizing)return;this.handleFailure()}}async runAnswerTurn(t){const e=await this.apiClient.startClarification(this.submissionSessionId,this.submissionToken,t);this.destroyed||this.applyFinalSubmissionResult(e)||this.startPolling()}showError(){const t=this.el.querySelector(".mtb-clarify-footer"),e=document.createElement("div");e.className="mtb-clarify-error",e.textContent=this.i18n.error.submit,t.prepend(e)}clearError(){this.el.querySelector(".mtb-clarify-error")?.remove()}appendStreamDelta(t){this.streamingBubble||(this.removeThinking(),this.streamingBubble=document.createElement("div"),this.streamingBubble.className="mtb-clarify-bubble mtb-clarify-ai",this.messagesEl.appendChild(this.streamingBubble)),this.streamingBubble.textContent=(this.streamingBubble.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight}endStreamingBubble(){this.streamingBubble=null}startPolling(){this.stopPolling(),this.pollDeadline=Date.now()+
|
|
106
|
+
`,t.querySelector(".mtb-clarify-retry").addEventListener("click",()=>{this.destroyed||this.retrySubmission()})}async retrySubmission(){!this.onRetrySubmission||this.sending||(this.submissionFailed=!1,this.showConversationControls(),this.inputEl.disabled=!0,this.showThinking(),await this.adoptSession(this.onRetrySubmission()))}async sendMessage(){const t=this.inputEl.value.trim();if(!(!t||this.sending||!this.submissionSessionId)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-busy","true"),this.stopPolling(),this.finalSubmissionStarted=!0,this.appendMessage({role:"user",content:t}),this.inputEl.value="",this.clearError();try{await this.runAnswerTurn(t)}catch{if(this.destroyed)return;this.finalSubmissionStarted=!1,this.sending=!1,this.renderConversation(this.lastMessages,!1),this.inputEl.value=t,this.showError(),this.sendBtn.removeAttribute("aria-busy"),this.inputEl.disabled=!1,this.sendBtn.disabled=!this.inputEl.value.trim(),this.inputEl.focus({preventScroll:!0})}}}async runInitialTurn(){const t=new AbortController;this.streamAbort=t;let e=setTimeout(()=>t.abort(),At);try{const r=await this.apiClient.streamClarification(this.submissionSessionId,this.submissionToken,n=>{clearTimeout(e),e=setTimeout(()=>t.abort(),At),this.appendStreamDelta(n)},t.signal);if(this.destroyed)return;this.endStreamingBubble(),this.applyResult(r)||this.startPolling()}catch{if(this.destroyed||this.finalizing)return;this.endStreamingBubble(),await this.runInitialTurnViaPolling()}finally{clearTimeout(e),this.streamAbort===t&&(this.streamAbort=null)}}async runInitialTurnViaPolling(){try{const t=await this.apiClient.startClarification(this.submissionSessionId,this.submissionToken);if(this.destroyed||this.finalizing)return;this.applyResult(t)||this.startPolling()}catch{if(this.destroyed||this.finalizing)return;this.handleFailure()}}async runAnswerTurn(t){const e=await this.apiClient.startClarification(this.submissionSessionId,this.submissionToken,t);this.destroyed||this.applyFinalSubmissionResult(e)||this.startPolling()}showError(){const t=this.el.querySelector(".mtb-clarify-footer"),e=document.createElement("div");e.className="mtb-clarify-error",e.textContent=this.i18n.error.submit,t.prepend(e)}clearError(){this.el.querySelector(".mtb-clarify-error")?.remove()}appendStreamDelta(t){this.streamingBubble||(this.removeThinking(),this.streamingBubble=document.createElement("div"),this.streamingBubble.className="mtb-clarify-bubble mtb-clarify-ai",this.messagesEl.appendChild(this.streamingBubble)),this.streamingBubble.textContent=(this.streamingBubble.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight}endStreamingBubble(){this.streamingBubble=null}startPolling(){this.stopPolling(),this.pollDeadline=Date.now()+Bi,this.pollTimer=setInterval(()=>this.poll(),$i)}stopPolling(){this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null)}async poll(){if(Date.now()>this.pollDeadline){this.stopPolling(),this.handleFailure();return}try{const t=await this.apiClient.getClarification(this.submissionSessionId,this.submissionToken);if(this.destroyed)return;(this.finalSubmissionStarted?this.applyFinalSubmissionResult(t):this.applyResult(t))&&this.stopPolling()}catch{if(this.destroyed)return;this.stopPolling(),this.handleFailure()}}handleDone(t){if(!this.done){if(this.done=!0,this.stopPolling(),this.removeThinking(),t){this.finalize();return}this.showFinalizeButton()}}handleFailure(){this.done||(this.done=!0,this.sending=!1,this.finalSubmissionStarted=!1,this.stopPolling(),this.removeThinking(),this.showClarificationFailureActions())}showClarificationFailureActions(){const t=this.el.querySelector(".mtb-clarify-footer");t.innerHTML=`
|
|
105
107
|
<div class="mtb-clarify-error">${c(this.i18n.clarify.error)}</div>
|
|
106
108
|
<div class="mtb-clarify-actions">
|
|
107
109
|
<button class="mtb-clarify-fallback" type="button">${c(this.i18n.clarify.send_feedback)}</button>
|
|
@@ -115,10 +117,10 @@
|
|
|
115
117
|
</svg>
|
|
116
118
|
<span>${c(this.i18n.clarify.send_feedback)}</span>
|
|
117
119
|
</button>
|
|
118
|
-
`,t.querySelector(".mtb-clarify-send-feedback").addEventListener("click",()=>{this.destroyed||this.finalize()})}async finalize(){if(!(this.finalizing||this.destroyed||this.unrecoverable)){this.finalizing=!0,this.el.querySelector(".mtb-clarify-send")?.setAttribute("aria-busy","true"),this.el.querySelectorAll("button").forEach(t=>{t.disabled=!0});try{await this.onFinalize()}catch(t){if(this.destroyed)return;if(this.finalizing=!1,this.clearError(),
|
|
120
|
+
`,t.querySelector(".mtb-clarify-send-feedback").addEventListener("click",()=>{this.destroyed||this.finalize()})}async finalize(){if(!(this.finalizing||this.destroyed||this.unrecoverable)){this.finalizing=!0,this.el.querySelector(".mtb-clarify-send")?.setAttribute("aria-busy","true"),this.el.querySelectorAll("button").forEach(t=>{t.disabled=!0});try{await this.onFinalize()}catch(t){if(this.destroyed)return;if(this.finalizing=!1,this.clearError(),Pi(t)){this.showUnrecoverable();return}this.showFinalizeRetry()}}}showUnrecoverable(){this.unrecoverable=!0,this.stopPolling();const t=this.el.querySelector(".mtb-clarify-footer");t.innerHTML=`<div class="mtb-clarify-error">${c(this.i18n.clarify.expired)}</div>`}showFinalizeRetry(){const t=this.el.querySelector(".mtb-clarify-footer");t.innerHTML=`
|
|
119
121
|
<div class="mtb-clarify-error">${c(this.i18n.error.submit)}</div>
|
|
120
122
|
<button class="mtb-clarify-send-feedback mtb-clarify-retry" type="button">${c(this.i18n.clarify.retry)}</button>
|
|
121
|
-
`,t.querySelector(".mtb-clarify-retry").addEventListener("click",()=>{this.destroyed||this.finalize()})}renderConversation(t,e){this.lastMessages=t,this.renderMessages(t);const r=t[t.length-1];!e&&(!r||r.role==="user")&&this.showThinking()}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){if(this.messagesEl.querySelector(".mtb-clarify-thinking"))return;const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-clarify-thinking")?.remove()}destroy(){this.destroyed=!0,this.keyboardListenerTimer!==null&&(clearTimeout(this.keyboardListenerTimer),this.keyboardListenerTimer=null),window.removeEventListener("keydown",this.handleKeydown),this.streamAbort?.abort(),this.streamAbort=null,this.stopPolling(),this.sheet.release(),this.el.remove()}}const
|
|
123
|
+
`,t.querySelector(".mtb-clarify-retry").addEventListener("click",()=>{this.destroyed||this.finalize()})}renderConversation(t,e){this.lastMessages=t,this.renderMessages(t);const r=t[t.length-1];!e&&(!r||r.role==="user")&&this.showThinking()}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){if(this.messagesEl.querySelector(".mtb-clarify-thinking"))return;const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-clarify-thinking")?.remove()}destroy(){this.destroyed=!0,this.keyboardListenerTimer!==null&&(clearTimeout(this.keyboardListenerTimer),this.keyboardListenerTimer=null),window.removeEventListener("keydown",this.handleKeydown),this.streamAbort?.abort(),this.streamAbort=null,this.stopPolling(),this.sheet.release(),this.el.remove()}}const zi=5e3,qi=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;class ji{constructor(t,e,r,n,s){this.messages=e,this.el=t.el("div","mtb-success"),this.el.style.right="20px",this.el.style.bottom="20px";const o=s?.skipFollowup?e.success.title_no_ai:e.success.title,a=s?.skipFollowup?e.success.message_no_ai:e.success.message,l=n?`<button class="mtb-view-feedback-link">${c(e.success.view_feedback)} <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg></button>`:"",d=s?.emailCapture?`
|
|
122
124
|
<div class="mtb-email-capture">
|
|
123
125
|
<div class="mtb-email-prompt">${c(e.success.email_prompt)}</div>
|
|
124
126
|
<div class="mtb-email-row">
|
|
@@ -137,10 +139,10 @@
|
|
|
137
139
|
${d}
|
|
138
140
|
${l}
|
|
139
141
|
<button class="mtb-close-link">${c(e.success.close)}</button>
|
|
140
|
-
`,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",r),n&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",n),s?.emailCapture?this.bindEmailCapture(s.emailCapture.onSubmit):setTimeout(()=>r(),qi)}bindEmailCapture(t){const e=this.el.querySelector(".mtb-email-input"),r=this.el.querySelector(".mtb-email-submit"),n=this.el.querySelector(".mtb-email-error"),s=async()=>{const o=e.value.trim();if(!ji.test(o)){e.classList.add("mtb-email-invalid");return}e.classList.remove("mtb-email-invalid"),n.hidden=!0,r.disabled=!0,await t(o)?this.el.querySelector(".mtb-email-capture").innerHTML=`<div class="mtb-email-saved">${c(this.messages.success.email_saved)}</div>`:(n.hidden=!1,r.disabled=!1)};r.addEventListener("click",s),e.addEventListener("keydown",o=>{o.key==="Enter"&&s()})}destroy(){this.el.remove()}}function Vi(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),r=e.createElement("base"),n=e.createElement("a");return e.head.appendChild(r),e.body.appendChild(n),t&&(r.href=t),n.href=i,n.href}const Yi=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function x(i){const t=[];for(let e=0,r=i.length;e<r;e++)t.push(i[e]);return t}let E=null;function de(i={}){return E||(i.includeStyleProperties?(E=i.includeStyleProperties,E):(E=x(window.getComputedStyle(document.documentElement)),E))}function X(i,t){const r=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function Xi(i){const t=X(i,"border-left-width"),e=X(i,"border-right-width");return i.clientWidth+t+e}function Ki(i){const t=X(i,"border-top-width"),e=X(i,"border-bottom-width");return i.clientHeight+t+e}function he(i,t={}){const e=t.width||Xi(i),r=t.height||Ki(i);return{width:e,height:r}}function Gi(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const p=16384;function Ji(i){(i.width>p||i.height>p)&&(i.width>p&&i.height>p?i.width>i.height?(i.height*=p/i.width,i.width=p):(i.width*=p/i.height,i.height=p):i.width>p?(i.height*=p/i.width,i.width=p):(i.width*=p/i.height,i.height=p))}function K(i){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=e,r.crossOrigin="anonymous",r.decoding="async",r.src=i})}async function Zi(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Qi(i,t,e){const r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),s=document.createElementNS(r,"foreignObject");return n.setAttribute("width",`${t}`),n.setAttribute("height",`${e}`),n.setAttribute("viewBox",`0 0 ${t} ${e}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),n.appendChild(s),s.appendChild(i),Zi(n)}const b=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||b(e,t)};function tr(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function er(i,t){return de(t).map(e=>{const r=i.getPropertyValue(e),n=i.getPropertyPriority(e);return`${e}: ${r}${n?" !important":""};`}).join(" ")}function ir(i,t,e,r){const n=`.${i}:${t}`,s=e.cssText?tr(e):er(e,r);return document.createTextNode(`${n}{${s}}`)}function Pt(i,t,e,r){const n=window.getComputedStyle(i,e),s=n.getPropertyValue("content");if(s===""||s==="none")return;const o=Yi();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(ir(o,e,n,r)),t.appendChild(a)}function rr(i,t,e){Pt(i,t,":before",e),Pt(i,t,":after",e)}const Mt="application/font-woff",Rt="image/jpeg",nr={woff:Mt,woff2:Mt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Rt,jpeg:Rt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function sr(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function yt(i){const t=sr(i).toLowerCase();return nr[t]||""}function or(i){return i.split(/,/)[1]}function ht(i){return i.search(/^(data:)/)!==-1}function ar(i,t){return`data:${t};base64,${i}`}async function ue(i,t,e){const r=await fetch(i,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const n=await r.blob();return new Promise((s,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{s(e({res:r,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(n)})}const rt={};function lr(i,t,e){let r=i.replace(/\?.*/,"");return e&&(r=i),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function vt(i,t,e){const r=lr(i,t,e.includeQueryParams);if(rt[r]!=null)return rt[r];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let n;try{const s=await ue(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),or(a)));n=ar(s,t)}catch(s){n=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;s&&(o=typeof s=="string"?s:s.message),o&&console.warn(o)}return rt[r]=n,n}async function cr(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):K(t)}async function dr(i,t){if(i.currentSrc){const s=document.createElement("canvas"),o=s.getContext("2d");s.width=i.clientWidth,s.height=i.clientHeight,o?.drawImage(i,0,0,s.width,s.height);const a=s.toDataURL();return K(a)}const e=i.poster,r=yt(e),n=await vt(e,r,t);return K(n)}async function hr(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await et(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function ur(i,t){return b(i,HTMLCanvasElement)?cr(i):b(i,HTMLVideoElement)?dr(i,t):b(i,HTMLIFrameElement)?hr(i,t):i.cloneNode(me(i))}const mr=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",me=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function br(i,t,e){var r,n;if(me(t))return t;let s=[];return mr(i)&&i.assignedNodes?s=x(i.assignedNodes()):b(i,HTMLIFrameElement)&&(!((r=i.contentDocument)===null||r===void 0)&&r.body)?s=x(i.contentDocument.body.childNodes):s=x(((n=i.shadowRoot)!==null&&n!==void 0?n:i).childNodes),s.length===0||b(i,HTMLVideoElement)||await s.reduce((o,a)=>o.then(()=>et(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function pr(i,t,e){const r=t.style;if(!r)return;const n=window.getComputedStyle(i);n.cssText?(r.cssText=n.cssText,r.transformOrigin=n.transformOrigin):de(e).forEach(s=>{let o=n.getPropertyValue(s);s==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),b(i,HTMLIFrameElement)&&s==="display"&&o==="inline"&&(o="block"),s==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),r.setProperty(s,o,n.getPropertyPriority(s))})}function fr(i,t){b(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),b(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function gr(i,t){if(b(i,HTMLSelectElement)){const e=t,r=Array.from(e.children).find(n=>i.value===n.getAttribute("value"));r&&r.setAttribute("selected","")}}function yr(i,t,e){return b(t,Element)&&(pr(i,t,e),rr(i,t,e),fr(i,t),gr(i,t)),t}async function vr(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const r={};for(let s=0;s<e.length;s++){const a=e[s].getAttribute("xlink:href");if(a){const l=i.querySelector(a),d=document.querySelector(a);!l&&d&&!r[a]&&(r[a]=await et(d,t,!0))}}const n=Object.values(r);if(n.length){const s="http://www.w3.org/1999/xhtml",o=document.createElementNS(s,"svg");o.setAttribute("xmlns",s),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(s,"defs");o.appendChild(a);for(let l=0;l<n.length;l++)a.appendChild(n[l]);i.appendChild(o)}return i}async function et(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(r=>ur(r,t)).then(r=>br(i,r,t)).then(r=>yr(i,r,t)).then(r=>vr(r,t))}const be=/url\((['"]?)([^'"]+?)\1\)/g,wr=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,xr=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function kr(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Sr(i){const t=[];return i.replace(be,(e,r,n)=>(t.push(n),e)),t.filter(e=>!ht(e))}async function Er(i,t,e,r,n){try{const s=e?Vi(t,e):t,o=yt(t);let a;return n||(a=await vt(s,o,r)),i.replace(kr(t),`$1${a}$3`)}catch{}return i}function Tr(i,{preferredFontFormat:t}){return t?i.replace(xr,e=>{for(;;){const[r,,n]=wr.exec(e)||[];if(!n)return"";if(n===t)return`src: ${r};`}}):i}function pe(i){return i.search(be)!==-1}async function fe(i,t,e){if(!pe(i))return i;const r=Tr(i,e);return Sr(r).reduce((s,o)=>s.then(a=>Er(a,o,t,e)),Promise.resolve(r))}async function T(i,t,e){var r;const n=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(i);if(n){const s=await fe(n,null,e);return t.style.setProperty(i,s,t.style.getPropertyPriority(i)),!0}return!1}async function Cr(i,t){await T("background",i,t)||await T("background-image",i,t),await T("mask",i,t)||await T("-webkit-mask",i,t)||await T("mask-image",i,t)||await T("-webkit-mask-image",i,t)}async function _r(i,t){const e=b(i,HTMLImageElement);if(!(e&&!ht(i.src))&&!(b(i,SVGImageElement)&&!ht(i.href.baseVal)))return;const r=e?i.src:i.href.baseVal,n=await vt(r,yt(r),t);await new Promise((s,o)=>{i.onload=s,i.onerror=t.onImageErrorHandler?(...l)=>{try{s(t.onImageErrorHandler(...l))}catch(d){o(d)}}:o;const a=i;a.decode&&(a.decode=s),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=n):i.href.baseVal=n})}async function Lr(i,t){const r=x(i.childNodes).map(n=>ge(n,t));await Promise.all(r).then(()=>i)}async function ge(i,t){b(i,Element)&&(await Cr(i,t),await _r(i,t),await Lr(i,t))}function Ar(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(n=>{e[n]=r[n]}),i}const It={};async function Dt(i){let t=It[i];if(t!=null)return t;const r=await(await fetch(i)).text();return t={url:i,cssText:r},It[i]=t,t}async function Ht(i,t){let e=i.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,s=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(r,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),ue(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(s).then(()=>e)}function Ft(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let r=i.replace(e,"");const n=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=n.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(n,"");const s=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=s.exec(r);if(l===null){if(l=a.exec(r),l===null)break;s.lastIndex=a.lastIndex}else a.lastIndex=s.lastIndex;t.push(l[0])}return t}async function Pr(i,t){const e=[],r=[];return i.forEach(n=>{if("cssRules"in n)try{x(n.cssRules||[]).forEach((s,o)=>{if(s.type===CSSRule.IMPORT_RULE){let a=o+1;const l=s.href,d=Dt(l).then(u=>Ht(u,t)).then(u=>Ft(u).forEach(m=>{try{n.insertRule(m,m.startsWith("@import")?a+=1:n.cssRules.length)}catch(h){console.error("Error inserting rule from remote css",{rule:m,error:h})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(s){const o=i.find(a=>a.href==null)||document.styleSheets[0];n.href!=null&&r.push(Dt(n.href).then(a=>Ht(a,t)).then(a=>Ft(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",s)}}),Promise.all(r).then(()=>(i.forEach(n=>{if("cssRules"in n)try{x(n.cssRules||[]).forEach(s=>{e.push(s)})}catch(s){console.error(`Error while reading CSS rules from ${n.href}`,s)}}),e))}function Mr(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>pe(t.style.getPropertyValue("src")))}async function Rr(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=x(i.ownerDocument.styleSheets),r=await Pr(e,t);return Mr(r)}function ye(i){return i.trim().replace(/["']/g,"")}function Ir(i){const t=new Set;function e(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(s=>{t.add(ye(s))}),Array.from(r.children).forEach(s=>{s instanceof HTMLElement&&e(s)})}return e(i),t}async function Dr(i,t){const e=await Rr(i,t),r=Ir(i);return(await Promise.all(e.filter(s=>r.has(ye(s.style.fontFamily))).map(s=>{const o=s.parentStyleSheet?s.parentStyleSheet.href:null;return fe(s.cssText,o,t)}))).join(`
|
|
141
|
-
`)}async function Hr(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Dr(i,t);if(e){const r=document.createElement("style"),n=document.createTextNode(e);r.appendChild(n),i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r)}}async function Fr(i,t={}){const{width:e,height:r}=he(i,t),n=await et(i,t,!0);return await Hr(n,t),await ge(n,t),Ar(n,t),await Qi(n,e,r)}async function $r(i,t={}){const{width:e,height:r}=he(i,t),n=await Fr(i,t),s=await K(n),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||Gi(),d=t.canvasWidth||e,u=t.canvasHeight||r;return o.width=d*l,o.height=u*l,t.skipAutoScale||Ji(o),o.style.width=`${d}`,o.style.height=`${u}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(s,0,0,o.width,o.height),o}async function Br(i,t={}){return(await $r(i,t)).toDataURL("image/jpeg",t.quality||1)}const nt=400,st=300,$t=150,Bt=.3,Ot=.85;function ve(i){let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const s of i)if(s.type==="pin"){if(t=Math.min(t,s.x),e=Math.min(e,s.y),r=Math.max(r,s.x),n=Math.max(n,s.y),s.targetRect){const o=s.targetRect;t=Math.min(t,o.left),e=Math.min(e,o.top),r=Math.max(r,o.left+o.width),n=Math.max(n,o.bottom)}}else if(s.type==="draw"&&s.drawPath)for(const o of we(s.drawPath))for(const[a,l]of o)t=Math.min(t,a),e=Math.min(e,l),r=Math.max(r,a),n=Math.max(n,l);return!isFinite(t)||!isFinite(e)?null:{minX:t,minY:e,maxX:r,maxY:n}}function Or(i,t,e){const r=ve(i);if(!r)return null;const n=Math.max($t,t*Bt),s=Math.max($t,e*Bt);let o=r.minX-n,a=r.minY-s,l=r.maxX-r.minX+n*2,d=r.maxY-r.minY+s*2;return l<nt&&(o-=(nt-l)/2,l=nt),d<st&&(a-=(st-d)/2,d=st),l=Math.min(l,t),d=Math.min(d,e),o=Math.min(Math.max(0,o),t-l),a=Math.min(Math.max(0,a),e-d),l>=t*Ot&&d>=e*Ot?null:{x:Math.round(o),y:Math.round(a),width:Math.round(l),height:Math.round(d)}}function Ur(i,t){const e=document.createElement("canvas");e.width=t.width,e.height=t.height;const r=e.getContext("2d");return r&&r.drawImage(i,t.x,t.y,t.width,t.height,0,0,t.width,t.height),e}async function Nr(i=[],t){try{const e=tn(document.body),r=i.map(zr),n=Gr(document.body),s=await Br(document.body,{quality:.85,width:e.width,height:e.height,pixelRatio:Qr(e),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,filter:o=>!(o instanceof HTMLElement&&o.id==="mtb-widget-host")});return await Yr(s,r,e,n,t)}catch{return null}}function zr(i){const t=jr(qr(i));return t.x===0&&t.y===0?i:{...i,x:i.x+t.x,y:i.y+t.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+t.y,left:i.targetRect.left+t.x,bottom:i.targetRect.bottom+t.y},drawPath:i.drawPath&&Vr(i.drawPath,t)}}function qr(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}function jr(i){let t=0,e=0,r=i;for(;r&&r!==document.body;)r instanceof HTMLElement&&(t+=r.scrollLeft,e+=r.scrollTop),r=Wr(r);return{x:t,y:e}}function Wr(i){if(i.parentElement)return i.parentElement;const t=i.getRootNode();return t instanceof ShadowRoot?t.host:null}function Vr(i,t){return i.replace(/([ML])\s*(-?(?:\d+\.?\d*|\.\d+))\s+(-?(?:\d+\.?\d*|\.\d+))/g,(e,r,n,s)=>`${r} ${Number(n)+t.x} ${Number(s)+t.y}`)}async function Yr(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await rn(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=s.width/e.width,d=s.height/e.height;o.fillStyle="#e5e7eb";for(const h of r)o.fillRect((h.left-e.left)*l,(h.top-e.top)*d,h.width*l,h.height*d);let u=0;for(const h of t)h.type==="draw"&&h.drawPath?Zr(o,h.drawPath,e,l,d,n?.primary):h.type==="pin"&&en(o,(h.x-e.left)*l,(h.y-e.top)*d,++u,n);if(!Xr(t,e,l,d,s))return z(s);const m=Or(t,window.innerWidth,window.innerHeight);if(m){const h=Kr(m,e,l,d,s);return z(h?Ur(s,h):s)}return z(s)}function Xr(i,t,e,r,n){const s=ve(i);if(!s)return!0;const o=(s.minX-t.left)*e,a=(s.minY-t.top)*r,l=(s.maxX-t.left)*e,d=(s.maxY-t.top)*r;return o>=0&&a>=0&&l<=n.width&&d<=n.height}function Kr(i,t,e,r,n){const s=Math.min(n.width,Math.round(i.width*e)),o=Math.min(n.height,Math.round(i.height*r));if(s<=0||o<=0)return null;const a=Math.round((i.x-t.left)*e),l=Math.round((i.y-t.top)*r);return{x:Math.min(Math.max(0,a),n.width-s),y:Math.min(Math.max(0,l),n.height-o),width:s,height:o}}function Gr(i){const t=[];for(const s of Jr(i,`.${Q}`))ot(t,s.getBoundingClientRect());for(const s of i.querySelectorAll("input, textarea, select")){if(Ut(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=ne(s)||Y(o,s)!==o;!a&&!l||ot(t,s.getBoundingClientRect(),zt)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=se();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=A(o)!==o||oe(n,r);if(s&&!Ut(s)&&(a||l)){const d=document.createRange();d.selectNodeContents(n);for(const u of Array.from(d.getClientRects()))ot(t,u,zt)}n=e.nextNode()}return t}function Jr(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ut(i){return i.closest("#mtb-widget-host")!==null||i.closest(`.${Q}`)!==null}function ot(i,t,e=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,top:t.top-e,width:t.width+e*2,height:t.height+e*2})}function Zr(i,t,e,r,n,s=pt){i.save(),i.lineCap="round",i.lineJoin="round";for(const o of we(t))if(o.length!==0){i.beginPath(),i.moveTo((o[0][0]-e.left)*r,(o[0][1]-e.top)*n);for(let a=1;a<o.length;a++)i.lineTo((o[a][0]-e.left)*r,(o[a][1]-e.top)*n);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=s,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,zt=2;function Qr(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function tn(i){const t=i.getBoundingClientRect(),e=window.getComputedStyle(i),r=parseFloat(e.borderLeftWidth)+parseFloat(e.borderRightWidth),n=parseFloat(e.borderTopWidth)+parseFloat(e.borderBottomWidth),s=document.documentElement,o=Math.max(i.clientWidth,i.scrollWidth,s.clientWidth,s.scrollWidth),a=Math.max(i.clientHeight,i.scrollHeight,s.clientHeight,s.scrollHeight);return{left:t.left,top:t.top,width:o+(Number.isFinite(r)?r:0)||window.innerWidth,height:a+(Number.isFinite(n)?n:0)||window.innerHeight}}function en(i,t,e,r,n){const s=n?.primary??pt,o=n?.onPrimary??"#ffffff";i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=s,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.fillStyle=o,i.font=`700 10px ${Ze}`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(r),t,e),i.restore()}function we(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 rn(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function z(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class nn{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:sn(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 wt=new nn;function sn(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function xe(i){const t=on(i.name)||an(i.message),e=ln(i);return e?`${t} (${e})`:t}function on(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function an(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function ln(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 cn=20;class dn{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=wt.subscribe(t=>this.record(t)))}record(t){this.addError(xe(t))}addError(t){this.errors.length>=cn||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const j=new Set;let D=null,H=null,F=null,G=null,$=null,J=null;function ke(i){j.add(i),hn();let t=!1;return()=>{t||(t=!0,j.delete(i),j.size===0&&un())}}function at(i,t){const e={type:i,fromUrl:t,toUrl:location.href};J=e.toUrl;for(const r of[...j])try{r(e)}catch{}}function hn(){if(F)return;J=location.href,$=()=>at("pop",J??location.href),window.addEventListener("popstate",$),D=history.pushState,H=history.replaceState;const i=D,t=H;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),at("push",s)},G=function(e,r,n){const s=location.href;t.call(history,e,r,n),at("replace",s)},history.pushState=F,history.replaceState=G}function un(){$&&(window.removeEventListener("popstate",$),$=null),D&&history.pushState===F&&(history.pushState=D),H&&history.replaceState===G&&(history.replaceState=H),D=null,H=null,F=null,G=null,J=null}const mn=20;function bn(i){return tt(i)?ft(i):bt(i)}function pn(i){return tt(i)?le(i):ee(i)}class fn{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=wt.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=ke(()=>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>mn&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!C(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:bn(e),data:{selector:pn(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!C(e))try{const r=e,n=tt(e)?ft(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=xe(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=O(t),n=O(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const Se="mtb_frustration_state";let ut=null;function Z(){try{const i=window.sessionStorage.getItem(Se);return W(i?JSON.parse(i):ut)}catch{return W(ut)}}function Ee(i){const t=W(i);ut=t;try{window.sessionStorage.setItem(Se,JSON.stringify(t))}catch{}}function gn(){return Z().dismissedByUser}function yn(){Ee({...Z(),dismissedByUser:!0})}function W(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 vn=4,wn=1500,xn=3,kn=5e3,lt=500,Sn=2,En=3e4,Tn=2e3,Cn=1e3,_n=300,Ln=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),An=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),Pn=new Set(["A","BUTTON","SUMMARY"]),Mn=new Set(["button","link","tab","menuitem"]),qt=[/\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/],B=class B{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.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=wt.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>Tn)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.disconnectDomObserver())}startNavigationTracking(){this.unsubscribeNavigation=ke(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=Z();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=Z();Ee({...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)}handleClick(t){const e=t.target;if(!e||C(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-wn;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=vn){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-kn;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=xn&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),setTimeout(()=>{this.active&&this.checkErrorPage()},_n)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(C(e)||(this.rememberSubmitAttempt(e),setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},lt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||C(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),setTimeout(()=>{this.recentSubmitForms.delete(t)},lt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),setTimeout(()=>this.recentFailedForms.delete(t),lt);const e=Date.now(),r=e-En,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<Sn)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:q(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||C(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(qt.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&&qt.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(),setTimeout(()=>{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})},Cn))}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(Pn.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Mn.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(Ln.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&An.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+B.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+B.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};B.COOLDOWN_MS=6e4;let mt=B;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}"`:""}`}function Rn(){return{page_url:O(window.location.href),user_agent:navigator.userAgent,browser:In(),os:Dn(),screen_width:window.screen.width,screen_height:window.screen.height}}function In(){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 Dn(){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 Hn(i,t,e,r,n,s,o,a,l){return{...V({description:i,...t,page_url:O(t.page_url),console_errors:e,annotations:r?[r]:[],target_element:r?.targetSelector?{selector:r.targetSelector,text:r.targetText??"",name:r.targetName??""}:void 0,recording_events:s?.events,recording_duration:s?.duration,breadcrumbs:l}),user_id:n?.id,user_email:n?.email,user_name:n?.name,reporter_external_id:n?void 0:o,reporter_email:n?void 0:a}}const jt="mtb_anon_id",Te="mtb_reporter_email",Ce="mtb_board_url";let Wt=null,_e=null,Le=null;function Vt(){try{const i=window.localStorage.getItem(jt);if(i?.startsWith("anon_"))return i;const t=Kt();return window.localStorage.setItem(jt,t),t}catch{return Wt??(Wt=Kt()),Wt}}function Yt(){try{return window.localStorage.getItem(Te)??void 0}catch{return _e??void 0}}function Fn(i){_e=i;try{window.localStorage.setItem(Te,i)}catch{}}function $n(){try{return window.localStorage.getItem(Ce)??void 0}catch{return Le??void 0}}function Xt(i){Le=i;try{window.localStorage.setItem(Ce,i)}catch{}}function Kt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const Bn={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",cancel:"Cancel",my_feedback:"My feedback",quickOptions:[{emoji:"🐛",label:"Something's broken"},{emoji:"💡",label:"I have a suggestion"},{emoji:"🤔",label:"I'm confused"}]},success:{title:"Sent — thanks!",message:"Your note and captured technical context are on their way to the team. You’ll hear back when it’s resolved.",title_no_ai:"Thanks! We've received your feedback.",message_no_ai:"The team will take it from here. You'll hear back when it's resolved.",view_feedback:"View my feedback",close:"Close",email_prompt:"Want updates? Leave your email and we'll let you know when it's resolved.",email_placeholder:"you@example.com",email_submit:"Notify me",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again."},error:{submit:"Failed to submit. 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:"Type your answer — or skip the question",send:"Send",send_feedback:"Send feedback",skip:"Skip & send",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."}},On={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",my_feedback:"我的反馈",quickOptions:[{emoji:"🐛",label:"出问题了"},{emoji:"💡",label:"我有一个建议"},{emoji:"🤔",label:"我有点疑问"}]},success:{title:"已发送,感谢!",message:"您的反馈和采集到的技术上下文正在发送给团队。问题解决后,您会收到通知。",title_no_ai:"感谢!我们已收到您的反馈。",message_no_ai:"接下来由团队处理。问题解决后,您会收到通知。",view_feedback:"查看我的反馈",close:"关闭",email_prompt:"想了解进展?留下邮箱,问题解决后我们会通知您。",email_placeholder:"you@example.com",email_submit:"通知我",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。"},error:{submit:"提交失败,请重试。"},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:"发送",send_feedback:"发送反馈",skip:"跳过并发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},Un={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",my_feedback:"自分のフィードバック",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"提案があります"},{emoji:"🤔",label:"わかりにくいです"}]},success:{title:"送信しました。ありがとうございます!",message:"ご意見と取得した技術情報をチームに送信しました。解決次第お知らせします。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",message_no_ai:"チームが対応します。解決次第お知らせします。",view_feedback:"フィードバックを確認",close:"閉じる",email_prompt:"進捗を知りたい場合は、メールアドレスをご記入ください。解決次第お知らせします。",email_placeholder:"you@example.com",email_submit:"通知を受け取る",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。"},error:{submit:"送信に失敗しました。もう一度お試しください。"},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:"送信",send_feedback:"フィードバックを送信",skip:"スキップして送信",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Nn={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",my_feedback:"내 피드백",quickOptions:[{emoji:"🐛",label:"문제가 있어요"},{emoji:"💡",label:"제안이 있어요"},{emoji:"🤔",label:"헷갈려요"}]},success:{title:"전송되었습니다. 감사합니다!",message:"피드백과 수집된 기술 정보가 팀에 전달되었습니다. 해결되면 알려드리겠습니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",message_no_ai:"팀에서 처리합니다. 해결되면 알려드리겠습니다.",view_feedback:"내 피드백 보기",close:"닫기",email_prompt:"진행 상황이 궁금하신가요? 이메일을 남겨주시면 해결 시 알려드립니다.",email_placeholder:"you@example.com",email_submit:"알림 받기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요."},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},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:"보내기",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},zn={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",cancel:"Cancelar",my_feedback:"Mis comentarios",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Tengo una sugerencia"},{emoji:"🤔",label:"Estoy confundido"}]},success:{title:"Enviado, ¡gracias!",message:"Tu nota y el contexto técnico capturado se han enviado al equipo. Te avisaremos cuando se resuelva.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",message_no_ai:"El equipo se encargará a partir de aquí. Te avisaremos cuando se resuelva.",view_feedback:"Ver mis comentarios",close:"Cerrar",email_prompt:"¿Quieres novedades? Deja tu correo y te avisaremos cuando se resuelva.",email_placeholder:"tu@ejemplo.com",email_submit:"Avisarme",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo."},error:{submit:"Error al enviar. Por favor, 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:"Escribe tu respuesta — u omite la pregunta",send:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y 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."}},qn={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",cancel:"Annuler",my_feedback:"Mes avis",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'ai une suggestion"},{emoji:"🤔",label:"Je suis perplexe"}]},success:{title:"Envoyé, merci !",message:"Votre message et le contexte technique collecté ont été transmis à l’équipe. Vous serez informé(e) dès que ce sera résolu.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",message_no_ai:"L’équipe prend le relais. Vous serez informé(e) dès que ce sera résolu.",view_feedback:"Voir mes avis",close:"Fermer",email_prompt:"Envie de suivre l'avancement ? Laissez votre e-mail et nous vous préviendrons une fois résolu.",email_placeholder:"vous@exemple.com",email_submit:"Me prévenir",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer."},error:{submit:"Échec de l'envoi. 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:"Saisissez votre réponse — ou ignorez la question",send:"Envoyer",send_feedback:"Envoyer le retour",skip:"Ignorer et 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."}},jn={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",cancel:"Abbrechen",my_feedback:"Mein Feedback",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Ich bin verwirrt"}]},success:{title:"Gesendet, vielen Dank!",message:"Ihre Nachricht und der erfasste technische Kontext wurden an das Team gesendet. Sie werden benachrichtigt, sobald das Problem gelöst ist.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",message_no_ai:"Das Team übernimmt ab hier. Sie werden benachrichtigt, sobald das Problem gelöst ist.",view_feedback:"Mein Feedback ansehen",close:"Schließen",email_prompt:"Updates gewünscht? Hinterlassen Sie Ihre E-Mail und wir melden uns, sobald es gelöst ist.",email_placeholder:"sie@beispiel.de",email_submit:"Benachrichtigen",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."},error:{submit:"Senden fehlgeschlagen. 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:"Antwort eingeben — oder Frage überspringen",send:"Senden",send_feedback:"Feedback senden",skip:"Überspringen & 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."}},M={en:Bn,"zh-CN":On,ja:Un,ko:Nn,es:zn,fr:qn,de:jn};function Gt(i){if(M[i])return M[i];const t=i.split("-")[0];return M[t]?M[t]:M.en}class Wn{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
|
|
142
|
+
`,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",r),n&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",n),s?.emailCapture?this.bindEmailCapture(s.emailCapture.onSubmit):setTimeout(()=>r(),zi)}bindEmailCapture(t){const e=this.el.querySelector(".mtb-email-input"),r=this.el.querySelector(".mtb-email-submit"),n=this.el.querySelector(".mtb-email-error"),s=async()=>{const o=e.value.trim();if(!qi.test(o)){e.classList.add("mtb-email-invalid");return}e.classList.remove("mtb-email-invalid"),n.hidden=!0,r.disabled=!0,await t(o)?this.el.querySelector(".mtb-email-capture").innerHTML=`<div class="mtb-email-saved">${c(this.messages.success.email_saved)}</div>`:(n.hidden=!1,r.disabled=!1)};r.addEventListener("click",s),e.addEventListener("keydown",o=>{o.key==="Enter"&&s()})}destroy(){this.el.remove()}}function Wi(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),r=e.createElement("base"),n=e.createElement("a");return e.head.appendChild(r),e.body.appendChild(n),t&&(r.href=t),n.href=i,n.href}const Vi=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function x(i){const t=[];for(let e=0,r=i.length;e<r;e++)t.push(i[e]);return t}let E=null;function de(i={}){return E||(i.includeStyleProperties?(E=i.includeStyleProperties,E):(E=x(window.getComputedStyle(document.documentElement)),E))}function X(i,t){const r=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function Yi(i){const t=X(i,"border-left-width"),e=X(i,"border-right-width");return i.clientWidth+t+e}function Xi(i){const t=X(i,"border-top-width"),e=X(i,"border-bottom-width");return i.clientHeight+t+e}function he(i,t={}){const e=t.width||Yi(i),r=t.height||Xi(i);return{width:e,height:r}}function Ki(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const p=16384;function Gi(i){(i.width>p||i.height>p)&&(i.width>p&&i.height>p?i.width>i.height?(i.height*=p/i.width,i.width=p):(i.width*=p/i.height,i.height=p):i.width>p?(i.height*=p/i.width,i.width=p):(i.width*=p/i.height,i.height=p))}function K(i){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=e,r.crossOrigin="anonymous",r.decoding="async",r.src=i})}async function Ji(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Zi(i,t,e){const r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),s=document.createElementNS(r,"foreignObject");return n.setAttribute("width",`${t}`),n.setAttribute("height",`${e}`),n.setAttribute("viewBox",`0 0 ${t} ${e}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),n.appendChild(s),s.appendChild(i),Ji(n)}const b=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||b(e,t)};function Qi(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function tr(i,t){return de(t).map(e=>{const r=i.getPropertyValue(e),n=i.getPropertyPriority(e);return`${e}: ${r}${n?" !important":""};`}).join(" ")}function er(i,t,e,r){const n=`.${i}:${t}`,s=e.cssText?Qi(e):tr(e,r);return document.createTextNode(`${n}{${s}}`)}function Pt(i,t,e,r){const n=window.getComputedStyle(i,e),s=n.getPropertyValue("content");if(s===""||s==="none")return;const o=Vi();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(er(o,e,n,r)),t.appendChild(a)}function ir(i,t,e){Pt(i,t,":before",e),Pt(i,t,":after",e)}const Mt="application/font-woff",Rt="image/jpeg",rr={woff:Mt,woff2:Mt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Rt,jpeg:Rt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function nr(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function yt(i){const t=nr(i).toLowerCase();return rr[t]||""}function sr(i){return i.split(/,/)[1]}function ht(i){return i.search(/^(data:)/)!==-1}function or(i,t){return`data:${t};base64,${i}`}async function ue(i,t,e){const r=await fetch(i,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const n=await r.blob();return new Promise((s,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{s(e({res:r,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(n)})}const rt={};function ar(i,t,e){let r=i.replace(/\?.*/,"");return e&&(r=i),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function vt(i,t,e){const r=ar(i,t,e.includeQueryParams);if(rt[r]!=null)return rt[r];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let n;try{const s=await ue(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),sr(a)));n=or(s,t)}catch(s){n=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;s&&(o=typeof s=="string"?s:s.message),o&&console.warn(o)}return rt[r]=n,n}async function lr(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):K(t)}async function cr(i,t){if(i.currentSrc){const s=document.createElement("canvas"),o=s.getContext("2d");s.width=i.clientWidth,s.height=i.clientHeight,o?.drawImage(i,0,0,s.width,s.height);const a=s.toDataURL();return K(a)}const e=i.poster,r=yt(e),n=await vt(e,r,t);return K(n)}async function dr(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await et(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function hr(i,t){return b(i,HTMLCanvasElement)?lr(i):b(i,HTMLVideoElement)?cr(i,t):b(i,HTMLIFrameElement)?dr(i,t):i.cloneNode(me(i))}const ur=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",me=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function mr(i,t,e){var r,n;if(me(t))return t;let s=[];return ur(i)&&i.assignedNodes?s=x(i.assignedNodes()):b(i,HTMLIFrameElement)&&(!((r=i.contentDocument)===null||r===void 0)&&r.body)?s=x(i.contentDocument.body.childNodes):s=x(((n=i.shadowRoot)!==null&&n!==void 0?n:i).childNodes),s.length===0||b(i,HTMLVideoElement)||await s.reduce((o,a)=>o.then(()=>et(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function br(i,t,e){const r=t.style;if(!r)return;const n=window.getComputedStyle(i);n.cssText?(r.cssText=n.cssText,r.transformOrigin=n.transformOrigin):de(e).forEach(s=>{let o=n.getPropertyValue(s);s==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),b(i,HTMLIFrameElement)&&s==="display"&&o==="inline"&&(o="block"),s==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),r.setProperty(s,o,n.getPropertyPriority(s))})}function pr(i,t){b(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),b(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function fr(i,t){if(b(i,HTMLSelectElement)){const e=t,r=Array.from(e.children).find(n=>i.value===n.getAttribute("value"));r&&r.setAttribute("selected","")}}function gr(i,t,e){return b(t,Element)&&(br(i,t,e),ir(i,t,e),pr(i,t),fr(i,t)),t}async function yr(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const r={};for(let s=0;s<e.length;s++){const a=e[s].getAttribute("xlink:href");if(a){const l=i.querySelector(a),d=document.querySelector(a);!l&&d&&!r[a]&&(r[a]=await et(d,t,!0))}}const n=Object.values(r);if(n.length){const s="http://www.w3.org/1999/xhtml",o=document.createElementNS(s,"svg");o.setAttribute("xmlns",s),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(s,"defs");o.appendChild(a);for(let l=0;l<n.length;l++)a.appendChild(n[l]);i.appendChild(o)}return i}async function et(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(r=>hr(r,t)).then(r=>mr(i,r,t)).then(r=>gr(i,r,t)).then(r=>yr(r,t))}const be=/url\((['"]?)([^'"]+?)\1\)/g,vr=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,wr=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function xr(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function kr(i){const t=[];return i.replace(be,(e,r,n)=>(t.push(n),e)),t.filter(e=>!ht(e))}async function Sr(i,t,e,r,n){try{const s=e?Wi(t,e):t,o=yt(t);let a;return n||(a=await vt(s,o,r)),i.replace(xr(t),`$1${a}$3`)}catch{}return i}function Er(i,{preferredFontFormat:t}){return t?i.replace(wr,e=>{for(;;){const[r,,n]=vr.exec(e)||[];if(!n)return"";if(n===t)return`src: ${r};`}}):i}function pe(i){return i.search(be)!==-1}async function fe(i,t,e){if(!pe(i))return i;const r=Er(i,e);return kr(r).reduce((s,o)=>s.then(a=>Sr(a,o,t,e)),Promise.resolve(r))}async function T(i,t,e){var r;const n=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(i);if(n){const s=await fe(n,null,e);return t.style.setProperty(i,s,t.style.getPropertyPriority(i)),!0}return!1}async function Tr(i,t){await T("background",i,t)||await T("background-image",i,t),await T("mask",i,t)||await T("-webkit-mask",i,t)||await T("mask-image",i,t)||await T("-webkit-mask-image",i,t)}async function Cr(i,t){const e=b(i,HTMLImageElement);if(!(e&&!ht(i.src))&&!(b(i,SVGImageElement)&&!ht(i.href.baseVal)))return;const r=e?i.src:i.href.baseVal,n=await vt(r,yt(r),t);await new Promise((s,o)=>{i.onload=s,i.onerror=t.onImageErrorHandler?(...l)=>{try{s(t.onImageErrorHandler(...l))}catch(d){o(d)}}:o;const a=i;a.decode&&(a.decode=s),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=n):i.href.baseVal=n})}async function _r(i,t){const r=x(i.childNodes).map(n=>ge(n,t));await Promise.all(r).then(()=>i)}async function ge(i,t){b(i,Element)&&(await Tr(i,t),await Cr(i,t),await _r(i,t))}function Lr(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(n=>{e[n]=r[n]}),i}const It={};async function Dt(i){let t=It[i];if(t!=null)return t;const r=await(await fetch(i)).text();return t={url:i,cssText:r},It[i]=t,t}async function Ht(i,t){let e=i.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,s=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(r,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),ue(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(s).then(()=>e)}function Ft(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let r=i.replace(e,"");const n=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=n.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(n,"");const s=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=s.exec(r);if(l===null){if(l=a.exec(r),l===null)break;s.lastIndex=a.lastIndex}else a.lastIndex=s.lastIndex;t.push(l[0])}return t}async function Ar(i,t){const e=[],r=[];return i.forEach(n=>{if("cssRules"in n)try{x(n.cssRules||[]).forEach((s,o)=>{if(s.type===CSSRule.IMPORT_RULE){let a=o+1;const l=s.href,d=Dt(l).then(u=>Ht(u,t)).then(u=>Ft(u).forEach(h=>{try{n.insertRule(h,h.startsWith("@import")?a+=1:n.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:h,error:m})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(s){const o=i.find(a=>a.href==null)||document.styleSheets[0];n.href!=null&&r.push(Dt(n.href).then(a=>Ht(a,t)).then(a=>Ft(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",s)}}),Promise.all(r).then(()=>(i.forEach(n=>{if("cssRules"in n)try{x(n.cssRules||[]).forEach(s=>{e.push(s)})}catch(s){console.error(`Error while reading CSS rules from ${n.href}`,s)}}),e))}function Pr(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>pe(t.style.getPropertyValue("src")))}async function Mr(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=x(i.ownerDocument.styleSheets),r=await Ar(e,t);return Pr(r)}function ye(i){return i.trim().replace(/["']/g,"")}function Rr(i){const t=new Set;function e(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(s=>{t.add(ye(s))}),Array.from(r.children).forEach(s=>{s instanceof HTMLElement&&e(s)})}return e(i),t}async function Ir(i,t){const e=await Mr(i,t),r=Rr(i);return(await Promise.all(e.filter(s=>r.has(ye(s.style.fontFamily))).map(s=>{const o=s.parentStyleSheet?s.parentStyleSheet.href:null;return fe(s.cssText,o,t)}))).join(`
|
|
143
|
+
`)}async function Dr(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Ir(i,t);if(e){const r=document.createElement("style"),n=document.createTextNode(e);r.appendChild(n),i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r)}}async function Hr(i,t={}){const{width:e,height:r}=he(i,t),n=await et(i,t,!0);return await Dr(n,t),await ge(n,t),Lr(n,t),await Zi(n,e,r)}async function Fr(i,t={}){const{width:e,height:r}=he(i,t),n=await Hr(i,t),s=await K(n),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||Ki(),d=t.canvasWidth||e,u=t.canvasHeight||r;return o.width=d*l,o.height=u*l,t.skipAutoScale||Gi(o),o.style.width=`${d}`,o.style.height=`${u}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(s,0,0,o.width,o.height),o}async function $r(i,t={}){return(await Fr(i,t)).toDataURL("image/jpeg",t.quality||1)}const nt=400,st=300,$t=150,Bt=.3,Ot=.85;function ve(i){let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const s of i)if(s.type==="pin"){if(t=Math.min(t,s.x),e=Math.min(e,s.y),r=Math.max(r,s.x),n=Math.max(n,s.y),s.targetRect){const o=s.targetRect;t=Math.min(t,o.left),e=Math.min(e,o.top),r=Math.max(r,o.left+o.width),n=Math.max(n,o.bottom)}}else if(s.type==="draw"&&s.drawPath)for(const o of we(s.drawPath))for(const[a,l]of o)t=Math.min(t,a),e=Math.min(e,l),r=Math.max(r,a),n=Math.max(n,l);return!isFinite(t)||!isFinite(e)?null:{minX:t,minY:e,maxX:r,maxY:n}}function Br(i,t,e){const r=ve(i);if(!r)return null;const n=Math.max($t,t*Bt),s=Math.max($t,e*Bt);let o=r.minX-n,a=r.minY-s,l=r.maxX-r.minX+n*2,d=r.maxY-r.minY+s*2;return l<nt&&(o-=(nt-l)/2,l=nt),d<st&&(a-=(st-d)/2,d=st),l=Math.min(l,t),d=Math.min(d,e),o=Math.min(Math.max(0,o),t-l),a=Math.min(Math.max(0,a),e-d),l>=t*Ot&&d>=e*Ot?null:{x:Math.round(o),y:Math.round(a),width:Math.round(l),height:Math.round(d)}}function Or(i,t){const e=document.createElement("canvas");e.width=t.width,e.height=t.height;const r=e.getContext("2d");return r&&r.drawImage(i,t.x,t.y,t.width,t.height,0,0,t.width,t.height),e}async function Ur(i=[],t){try{const e=Qr(document.body),r=i.map(Nr),n=Kr(document.body),s=await $r(document.body,{quality:.85,width:e.width,height:e.height,pixelRatio:Zr(e),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,filter:o=>!(o instanceof HTMLElement&&o.id==="mtb-widget-host")});return await Vr(s,r,e,n,t)}catch{return null}}function Nr(i){const t=qr(zr(i));return t.x===0&&t.y===0?i:{...i,x:i.x+t.x,y:i.y+t.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+t.y,left:i.targetRect.left+t.x,bottom:i.targetRect.bottom+t.y},drawPath:i.drawPath&&Wr(i.drawPath,t)}}function zr(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}function qr(i){let t=0,e=0,r=i;for(;r&&r!==document.body;)r instanceof HTMLElement&&(t+=r.scrollLeft,e+=r.scrollTop),r=jr(r);return{x:t,y:e}}function jr(i){if(i.parentElement)return i.parentElement;const t=i.getRootNode();return t instanceof ShadowRoot?t.host:null}function Wr(i,t){return i.replace(/([ML])\s*(-?(?:\d+\.?\d*|\.\d+))\s+(-?(?:\d+\.?\d*|\.\d+))/g,(e,r,n,s)=>`${r} ${Number(n)+t.x} ${Number(s)+t.y}`)}async function Vr(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await en(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=s.width/e.width,d=s.height/e.height;o.fillStyle="#e5e7eb";for(const h of r)o.fillRect((h.left-e.left)*l,(h.top-e.top)*d,h.width*l,h.height*d);for(const h of t)h.type==="draw"&&h.drawPath?Jr(o,h.drawPath,e,l,d,n?.primary):h.type==="pin"&&tn(o,(h.x-e.left)*l,(h.y-e.top)*d,n);if(!Yr(t,e,l,d,s))return z(s);const u=Br(t,window.innerWidth,window.innerHeight);if(u){const h=Xr(u,e,l,d,s);return z(h?Or(s,h):s)}return z(s)}function Yr(i,t,e,r,n){const s=ve(i);if(!s)return!0;const o=(s.minX-t.left)*e,a=(s.minY-t.top)*r,l=(s.maxX-t.left)*e,d=(s.maxY-t.top)*r;return o>=0&&a>=0&&l<=n.width&&d<=n.height}function Xr(i,t,e,r,n){const s=Math.min(n.width,Math.round(i.width*e)),o=Math.min(n.height,Math.round(i.height*r));if(s<=0||o<=0)return null;const a=Math.round((i.x-t.left)*e),l=Math.round((i.y-t.top)*r);return{x:Math.min(Math.max(0,a),n.width-s),y:Math.min(Math.max(0,l),n.height-o),width:s,height:o}}function Kr(i){const t=[];for(const s of Gr(i,`.${Q}`))ot(t,s.getBoundingClientRect());for(const s of i.querySelectorAll("input, textarea, select")){if(Ut(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=ne(s)||Y(o,s)!==o;!a&&!l||ot(t,s.getBoundingClientRect(),zt)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=se();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=A(o)!==o||oe(n,r);if(s&&!Ut(s)&&(a||l)){const d=document.createRange();d.selectNodeContents(n);for(const u of Array.from(d.getClientRects()))ot(t,u,zt)}n=e.nextNode()}return t}function Gr(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ut(i){return i.closest("#mtb-widget-host")!==null||i.closest(`.${Q}`)!==null}function ot(i,t,e=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,top:t.top-e,width:t.width+e*2,height:t.height+e*2})}function Jr(i,t,e,r,n,s=pt){i.save(),i.lineCap="round",i.lineJoin="round";for(const o of we(t))if(o.length!==0){i.beginPath(),i.moveTo((o[0][0]-e.left)*r,(o[0][1]-e.top)*n);for(let a=1;a<o.length;a++)i.lineTo((o[a][0]-e.left)*r,(o[a][1]-e.top)*n);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=s,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,zt=2;function Zr(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Qr(i){const t=i.getBoundingClientRect(),e=window.getComputedStyle(i),r=parseFloat(e.borderLeftWidth)+parseFloat(e.borderRightWidth),n=parseFloat(e.borderTopWidth)+parseFloat(e.borderBottomWidth),s=document.documentElement,o=Math.max(i.clientWidth,i.scrollWidth,s.clientWidth,s.scrollWidth),a=Math.max(i.clientHeight,i.scrollHeight,s.clientHeight,s.scrollHeight);return{left:t.left,top:t.top,width:o+(Number.isFinite(r)?r:0)||window.innerWidth,height:a+(Number.isFinite(n)?n:0)||window.innerHeight}}function tn(i,t,e,r){const n=r?.primary??pt;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 we(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 en(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function z(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class rn{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:nn(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 wt=new rn;function nn(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function xe(i){const t=sn(i.name)||on(i.message),e=an(i);return e?`${t} (${e})`:t}function sn(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function on(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function an(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 ln=20;class cn{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=wt.subscribe(t=>this.record(t)))}record(t){this.addError(xe(t))}addError(t){this.errors.length>=ln||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const j=new Set;let D=null,H=null,F=null,G=null,$=null,J=null;function ke(i){j.add(i),dn();let t=!1;return()=>{t||(t=!0,j.delete(i),j.size===0&&hn())}}function at(i,t){const e={type:i,fromUrl:t,toUrl:location.href};J=e.toUrl;for(const r of[...j])try{r(e)}catch{}}function dn(){if(F)return;J=location.href,$=()=>at("pop",J??location.href),window.addEventListener("popstate",$),D=history.pushState,H=history.replaceState;const i=D,t=H;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),at("push",s)},G=function(e,r,n){const s=location.href;t.call(history,e,r,n),at("replace",s)},history.pushState=F,history.replaceState=G}function hn(){$&&(window.removeEventListener("popstate",$),$=null),D&&history.pushState===F&&(history.pushState=D),H&&history.replaceState===G&&(history.replaceState=H),D=null,H=null,F=null,G=null,J=null}const un=20;function mn(i){return tt(i)?ft(i):bt(i)}function bn(i){return tt(i)?le(i):ee(i)}class pn{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=wt.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=ke(()=>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>un&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!C(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:mn(e),data:{selector:bn(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!C(e))try{const r=e,n=tt(e)?ft(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=xe(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=O(t),n=O(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const Se="mtb_frustration_state";let ut=null;function Z(){try{const i=window.sessionStorage.getItem(Se);return W(i?JSON.parse(i):ut)}catch{return W(ut)}}function Ee(i){const t=W(i);ut=t;try{window.sessionStorage.setItem(Se,JSON.stringify(t))}catch{}}function fn(){return Z().dismissedByUser}function gn(){Ee({...Z(),dismissedByUser:!0})}function W(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 yn=4,vn=1500,wn=3,xn=5e3,lt=500,kn=2,Sn=3e4,En=2e3,Tn=1e3,Cn=300,_n=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),Ln=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),An=new Set(["A","BUTTON","SUMMARY"]),Pn=new Set(["button","link","tab","menuitem"]),qt=[/\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/],B=class B{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.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=wt.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>En)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.disconnectDomObserver())}startNavigationTracking(){this.unsubscribeNavigation=ke(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=Z();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=Z();Ee({...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)}handleClick(t){const e=t.target;if(!e||C(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-vn;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=yn){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-xn;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=wn&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),setTimeout(()=>{this.active&&this.checkErrorPage()},Cn)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(C(e)||(this.rememberSubmitAttempt(e),setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},lt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||C(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),setTimeout(()=>{this.recentSubmitForms.delete(t)},lt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),setTimeout(()=>this.recentFailedForms.delete(t),lt);const e=Date.now(),r=e-Sn,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<kn)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:q(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||C(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(qt.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&&qt.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(),setTimeout(()=>{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})},Tn))}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(An.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Pn.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(_n.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&Ln.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+B.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+B.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};B.COOLDOWN_MS=6e4;let mt=B;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}"`:""}`}function Mn(){return{page_url:O(window.location.href),user_agent:navigator.userAgent,browser:Rn(),os:In(),screen_width:window.screen.width,screen_height:window.screen.height}}function Rn(){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 In(){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 Dn(i,t,e,r,n,s,o,a,l){return{...V({description:i,...t,page_url:O(t.page_url),console_errors:e,annotations:r?[r]:[],target_element:r?.targetSelector?{selector:r.targetSelector,text:r.targetText??"",name:r.targetName??""}:void 0,recording_events:s?.events,recording_duration:s?.duration,breadcrumbs:l}),user_id:n?.id,user_email:n?.email,user_name:n?.name,reporter_external_id:n?void 0:o,reporter_email:n?void 0:a}}const jt="mtb_anon_id",Te="mtb_reporter_email",Ce="mtb_board_url";let Wt=null,_e=null,Le=null;function Vt(){try{const i=window.localStorage.getItem(jt);if(i?.startsWith("anon_"))return i;const t=Kt();return window.localStorage.setItem(jt,t),t}catch{return Wt??(Wt=Kt()),Wt}}function Yt(){try{return window.localStorage.getItem(Te)??void 0}catch{return _e??void 0}}function Hn(i){_e=i;try{window.localStorage.setItem(Te,i)}catch{}}function Fn(){try{return window.localStorage.getItem(Ce)??void 0}catch{return Le??void 0}}function Xt(i){Le=i;try{window.localStorage.setItem(Ce,i)}catch{}}function Kt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const $n={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",cancel:"Cancel",my_feedback:"My feedback",quickOptions:[{emoji:"🐛",label:"Something's broken"},{emoji:"💡",label:"I have a suggestion"},{emoji:"🤔",label:"I'm confused"}]},success:{title:"Sent — thanks!",message:"Your note and captured technical context are on their way to the team. You’ll hear back when it’s resolved.",title_no_ai:"Thanks! We've received your feedback.",message_no_ai:"The team will take it from here. You'll hear back when it's resolved.",view_feedback:"View my feedback",close:"Close",email_prompt:"Want updates? Leave your email and we'll let you know when it's resolved.",email_placeholder:"you@example.com",email_submit:"Notify me",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again."},error:{submit:"Failed to submit. 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:"Type your answer — or skip the question",send:"Send",send_feedback:"Send feedback",skip:"Skip & send",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."}},Bn={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",my_feedback:"我的反馈",quickOptions:[{emoji:"🐛",label:"出问题了"},{emoji:"💡",label:"我有一个建议"},{emoji:"🤔",label:"我有点疑问"}]},success:{title:"已发送,感谢!",message:"您的反馈和采集到的技术上下文正在发送给团队。问题解决后,您会收到通知。",title_no_ai:"感谢!我们已收到您的反馈。",message_no_ai:"接下来由团队处理。问题解决后,您会收到通知。",view_feedback:"查看我的反馈",close:"关闭",email_prompt:"想了解进展?留下邮箱,问题解决后我们会通知您。",email_placeholder:"you@example.com",email_submit:"通知我",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。"},error:{submit:"提交失败,请重试。"},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:"发送",send_feedback:"发送反馈",skip:"跳过并发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},On={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",my_feedback:"自分のフィードバック",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"提案があります"},{emoji:"🤔",label:"わかりにくいです"}]},success:{title:"送信しました。ありがとうございます!",message:"ご意見と取得した技術情報をチームに送信しました。解決次第お知らせします。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",message_no_ai:"チームが対応します。解決次第お知らせします。",view_feedback:"フィードバックを確認",close:"閉じる",email_prompt:"進捗を知りたい場合は、メールアドレスをご記入ください。解決次第お知らせします。",email_placeholder:"you@example.com",email_submit:"通知を受け取る",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。"},error:{submit:"送信に失敗しました。もう一度お試しください。"},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:"送信",send_feedback:"フィードバックを送信",skip:"スキップして送信",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},Un={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",my_feedback:"내 피드백",quickOptions:[{emoji:"🐛",label:"문제가 있어요"},{emoji:"💡",label:"제안이 있어요"},{emoji:"🤔",label:"헷갈려요"}]},success:{title:"전송되었습니다. 감사합니다!",message:"피드백과 수집된 기술 정보가 팀에 전달되었습니다. 해결되면 알려드리겠습니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",message_no_ai:"팀에서 처리합니다. 해결되면 알려드리겠습니다.",view_feedback:"내 피드백 보기",close:"닫기",email_prompt:"진행 상황이 궁금하신가요? 이메일을 남겨주시면 해결 시 알려드립니다.",email_placeholder:"you@example.com",email_submit:"알림 받기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요."},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},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:"보내기",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},Nn={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",cancel:"Cancelar",my_feedback:"Mis comentarios",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Tengo una sugerencia"},{emoji:"🤔",label:"Estoy confundido"}]},success:{title:"Enviado, ¡gracias!",message:"Tu nota y el contexto técnico capturado se han enviado al equipo. Te avisaremos cuando se resuelva.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",message_no_ai:"El equipo se encargará a partir de aquí. Te avisaremos cuando se resuelva.",view_feedback:"Ver mis comentarios",close:"Cerrar",email_prompt:"¿Quieres novedades? Deja tu correo y te avisaremos cuando se resuelva.",email_placeholder:"tu@ejemplo.com",email_submit:"Avisarme",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo."},error:{submit:"Error al enviar. Por favor, 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:"Escribe tu respuesta — u omite la pregunta",send:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y 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."}},zn={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",cancel:"Annuler",my_feedback:"Mes avis",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'ai une suggestion"},{emoji:"🤔",label:"Je suis perplexe"}]},success:{title:"Envoyé, merci !",message:"Votre message et le contexte technique collecté ont été transmis à l’équipe. Vous serez informé(e) dès que ce sera résolu.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",message_no_ai:"L’équipe prend le relais. Vous serez informé(e) dès que ce sera résolu.",view_feedback:"Voir mes avis",close:"Fermer",email_prompt:"Envie de suivre l'avancement ? Laissez votre e-mail et nous vous préviendrons une fois résolu.",email_placeholder:"vous@exemple.com",email_submit:"Me prévenir",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer."},error:{submit:"Échec de l'envoi. 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:"Saisissez votre réponse — ou ignorez la question",send:"Envoyer",send_feedback:"Envoyer le retour",skip:"Ignorer et 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."}},qn={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",cancel:"Abbrechen",my_feedback:"Mein Feedback",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Ich bin verwirrt"}]},success:{title:"Gesendet, vielen Dank!",message:"Ihre Nachricht und der erfasste technische Kontext wurden an das Team gesendet. Sie werden benachrichtigt, sobald das Problem gelöst ist.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",message_no_ai:"Das Team übernimmt ab hier. Sie werden benachrichtigt, sobald das Problem gelöst ist.",view_feedback:"Mein Feedback ansehen",close:"Schließen",email_prompt:"Updates gewünscht? Hinterlassen Sie Ihre E-Mail und wir melden uns, sobald es gelöst ist.",email_placeholder:"sie@beispiel.de",email_submit:"Benachrichtigen",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."},error:{submit:"Senden fehlgeschlagen. 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:"Antwort eingeben — oder Frage überspringen",send:"Senden",send_feedback:"Feedback senden",skip:"Überspringen & 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."}},M={en:$n,"zh-CN":Bn,ja:On,ko:Un,es:Nn,fr:zn,de:qn};function Gt(i){if(M[i])return M[i];const t=i.split("-")[0];return M[t]?M[t]:M.en}class jn{constructor(t,e,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
|
|
142
144
|
<span class="mtb-record-dot"></span>
|
|
143
145
|
<span class="mtb-record-timer">00:00</span>
|
|
144
146
|
<button class="mtb-record-stop" type="button">${c(e.record.stop)}</button>
|
|
145
|
-
`,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 Vn{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new xi(t,r),this.bar=new Wn(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}}const Yn=/^#[0-9a-f]{6}$/i;function Xn(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"&&Yn.test(e))?Jt():{primary:i.primary.toLowerCase(),hover:i.hover.toLowerCase(),active:i.active.toLowerCase(),onPrimary:i.onPrimary.toLowerCase()}}function Jt(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}const Kn=300;function Zt(){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 Gn{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new We,this.popup=null,this.clarify=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.mode="idle",this.via="pin",this.currentAnnotation=null,this.submittingUi=null,this.lastPopupPos=null,this.recordingManager=null,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=e=>{if(e.key==="Escape"&&!(e.isComposing||e.keyCode===229))switch(this.mode){case"annotating":case"popup":e.preventDefault(),e.stopPropagation(),this.exitAll();break;case"drawing":e.preventDefault(),e.stopPropagation(),this.cancelDraw();break;case"recording":e.preventDefault(),e.stopPropagation(),this.handleRecordStop();break}},this.handleRecordStop=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.showPopup(window.innerWidth/2,window.innerHeight/2,this.messages.record.timer_label))},this.config=t,this.brandColors=Xn(t.brandColors),this.messages=Gt(t.locale??document.documentElement.lang??"en"),this.apiClient=new Di(t.projectKey,t.apiUrl,void 0,t.userToken,t.userTokenFn),this.consoleCollector=new dn,this.consoleCollector.start(),this.breadcrumbCollector=new fn,this.breadcrumbCollector.start(),this.buildUI(),t.frustrationDetection!==!1&&(this.frustrationDetector=new mt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}buildUI(){if(this.shadow=new ct(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Zt()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(w()){Zt()&&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.tab=new Oe(this.shadow,this.messages,this.config.position??"right",()=>this.handleTabClick(),this.config.tabText,this.brandColors?void 0:this.config.tabColor))}open(){this.mode==="idle"&&(this.dismissFrustrationPrompt(),this.enterAnnotationMode())}close(){this.mode!=="idle"&&this.exitAll()}showLauncher(){w()||(this.mountTab(),this.tab?.setActive(this.mode!=="idle"))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=Gt(t),this.tab?.setMessages(this.messages)}handleTabClick(){this.mode==="idle"?(this.dismissFrustrationPrompt(),this.enterAnnotationMode()):this.exitAll()}handleFrustration(){this.mode!=="idle"||this.frustrationPrompt||gn()||(this.frustrationPrompt=new ze(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.enterAnnotationMode()},onDismiss:()=>{yn(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}enterAnnotationMode(){this.mode="annotating",this.tab?.setActive(!0);const t=w();this.toolbar=new Ye(this.shadow,this.messages,()=>this.exitAll(),e=>this.handleToolbarModeChange(e),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.session=this.createSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}createSession(){return new Ei(this.shadow,this.messages,{onPin:(t,e)=>{this.currentAnnotation=t,this.via="pin",this.showPopup(t.x,t.y,e,t.targetRect)},onDrawStroke:()=>this.handleDrawStroke()})}handleToolbarModeChange(t){if(this.mode==="clarifying"){this.toolbar?.setMode(this.via==="record"?"record":"markup");return}if(t==="record"){if(this.mode==="recording")return;this.mode="recording",this.currentAnnotation=null,this.teardownDraw(),this.session?.destroy(),this.session=null,this.recordingManager=new Vn,this.recordingManager.start(this.shadow,this.messages,this.handleRecordStop).catch(e=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",e),this.mode==="recording"&&(this.toolbar?.setMode("markup"),this.handleToolbarModeChange("markup"))})}else this.recordingManager?.destroy(),this.recordingManager=null,this.teardownDraw(),this.session||(this.session=this.createSession()),this.mode="annotating"}handleDrawStroke(){if(w()){this.showDrawSheet();return}this.mode!=="drawing"&&(this.mode="drawing",this.drawBar=new Ai(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t)})),this.refreshDrawBar()}showDrawSheet(){this.mode!=="drawing"&&(this.mode="drawing",this.popup=new _t(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,onSubmit:t=>this.handleDrawSubmit(t),onClose:()=>this.cancelDraw(),position:this.config.position??"right"}),this.submittingUi=this.popup)}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.teardownDraw(),this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.submittingUi=null,this.mode="annotating"}teardownDraw(){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(),this.submittingUi=this.drawBar??this.popup,this.handleSubmit(t||this.messages.annotation.drawing)}showPopup(t,e,r,n){this.mode="popup",this.lastPopupPos={x:t,y:e},this.teardownDraw(),this.session?.dismissInteraction(),this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.dim=new je(this.shadow,()=>this.exitAll()),this.popup=new _t(this.shadow,{targetName:r,x:t,y:e,targetRect:n,messages:this.messages,onSubmit:s=>this.handleSubmit(s),onClose:()=>this.exitAll(),onMyFeedback:this.buildMyFeedbackHandler(),position:this.config.position??"right"}),this.submittingUi=this.popup}buildMyFeedbackHandler(){if(!this.config.user&&$n())return async()=>{const t=await this.apiClient.createIdentityToken(Vt());!t?.identity_token||!t.board_url||(Xt(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}handleSubmit(t){if(!this.submittingUi)return;const e=this.currentAnnotation,r=this.recordingManager?.getRecording()??void 0,n=this.teardownSubmittingUi(!0),s=()=>this.startSubmissionRequest(t,e,r);this.showClarify(this.lastPopupPos,{element:n,pendingSession:s(),onRetrySubmission:s})}startSubmissionRequest(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){await Qt();const[s,o]=await Promise.all([Nr(e?[e]:[],this.brandColors),Promise.resolve(Rn())]),a=Hn(t,o,this.consoleCollector.getErrors(),e,this.config.user,r,this.config.user?void 0:Vt(),this.config.user?void 0:Yt(),this.breadcrumbCollector.getBreadcrumbs());try{const l=await this.apiClient.createSubmissionSession(a,s);return n!==this.submissionAttempt?(await this.apiClient.abandonSubmissionSession(l.id,l.token).catch(()=>{}),null):(this.activeSubmission=l,l)}catch{return null}}teardownSubmittingUi(t=!1){const e=t?this.popup?.releaseElement():void 0;return this.teardownDraw(),e||this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null,this.submittingUi=null,e}showClarify(t,e){this.mode="clarifying",this.tab?.setActive(!0),this.clarify=new zi(this.shadow,{apiClient:this.apiClient,messages:this.messages,element:e.element,position:this.config.position??"right",x:t?.x,y:t?.y,onFinalize:()=>this.finalizeSubmission(),onCancel:()=>this.exitAll(),pendingSession:e.pendingSession,onRetrySubmission:e.onRetrySubmission})}async finalizeSubmission(){const t=this.submissionAttempt,e=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!e)throw new Error("No active submission session");const r=new Promise(s=>setTimeout(s,Kn)),n=await this.apiClient.finalizeSubmissionSession(e.id,e.token);await Promise.all([r,Qt()]),!(t!==this.submissionAttempt||this.activeSubmission!==e)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.lastHandoff={feedbackId:n.id,boardUrl:n.board_url,identityToken:n.identity_token},n.board_url&&Xt(n.board_url),this.clarify?.destroy(),this.clarify=null,this.teardownToolbar(),this.showSuccess({skipFollowup:e.ai_clarify_available===!1}))}showSuccess(t){this.mode="idle",this.tab?.setActive(!1),this.success=new Wi(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},this.buildViewFeedbackHandler(),{...t,emailCapture:this.buildEmailCapture()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!Yt())return{onSubmit:async r=>{const n=await this.apiClient.updateReporter(t,r,e);return n&&Fn(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()=>{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.submissionAttempt+=1;const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{}),this.mode="idle",this.via="pin",this.tab?.setActive(!1),this.teardownToolbar(),this.teardownDraw(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.popup?.destroy(),this.popup=null,this.clarify?.destroy(),this.clarify=null,this.currentAnnotation=null,this.submittingUi=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.clarify?.destroy(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow.destroy()}}function Qt(){return new Promise(i=>requestAnimationFrame(()=>setTimeout(i,0)))}let k=null,_=null,L=null;function Jn(){L&&(document.removeEventListener("DOMContentLoaded",L),L=null)}function R(i){Jn(),k?.destroy(),k=i?new Gn(i):null}const Ae={init(i){R(),_=i,document.readyState==="loading"?(L=()=>{L=null,R(i)},document.addEventListener("DOMContentLoaded",L,{once:!0})):R(i)},destroy(){R(),_=null},setLocale(i){_&&(_.locale=i),k?.setLocale(i)},open(){k?.open()},close(){k?.close()},showLauncher(){k?.showLauncher()},hideLauncher(){k?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=Ae,document.addEventListener("turbo:load",()=>{const i=document.getElementById("mtb-widget-host");_&&(!i||!i.shadowRoot)&&(i?.remove(),R(_))}));exports.MakeThisBetter=Ae;
|
|
147
|
+
`,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 Wn{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new wi(t,r),this.bar=new jn(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}}const Vn=/^#[0-9a-f]{6}$/i;function Yn(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"&&Vn.test(e))?Jt():{primary:i.primary.toLowerCase(),hover:i.hover.toLowerCase(),active:i.active.toLowerCase(),onPrimary:i.onPrimary.toLowerCase()}}function Jt(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}const Xn=300;function Zt(){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 Kn{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new We,this.popup=null,this.clarify=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.mode="idle",this.via="pin",this.currentAnnotation=null,this.submittingUi=null,this.lastPopupPos=null,this.recordingManager=null,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=e=>{if(e.key==="Escape"&&!(e.isComposing||e.keyCode===229))switch(this.mode){case"annotating":case"popup":e.preventDefault(),e.stopPropagation(),this.exitAll();break;case"drawing":e.preventDefault(),e.stopPropagation(),this.cancelDraw();break;case"recording":e.preventDefault(),e.stopPropagation(),this.handleRecordStop();break}},this.handleRecordStop=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.showPopup(window.innerWidth/2,window.innerHeight/2,this.messages.record.timer_label))},this.config=t,this.brandColors=Yn(t.brandColors),this.messages=Gt(t.locale??document.documentElement.lang??"en"),this.apiClient=new Ii(t.projectKey,t.apiUrl,void 0,t.userToken,t.userTokenFn),this.consoleCollector=new cn,this.consoleCollector.start(),this.breadcrumbCollector=new pn,this.breadcrumbCollector.start(),this.buildUI(),t.frustrationDetection!==!1&&(this.frustrationDetector=new mt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}buildUI(){if(this.shadow=new ct(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Zt()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(w()){Zt()&&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.tab=new Oe(this.shadow,this.messages,this.config.position??"right",()=>this.handleTabClick(),this.config.tabText,this.brandColors?void 0:this.config.tabColor))}open(){this.mode==="idle"&&(this.dismissFrustrationPrompt(),this.enterAnnotationMode())}close(){this.mode!=="idle"&&this.exitAll()}showLauncher(){w()||(this.mountTab(),this.tab?.setActive(this.mode!=="idle"))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=Gt(t),this.tab?.setMessages(this.messages)}handleTabClick(){this.mode==="idle"?(this.dismissFrustrationPrompt(),this.enterAnnotationMode()):this.exitAll()}handleFrustration(){this.mode!=="idle"||this.frustrationPrompt||fn()||(this.frustrationPrompt=new ze(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.enterAnnotationMode()},onDismiss:()=>{gn(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}enterAnnotationMode(){this.mode="annotating",this.tab?.setActive(!0);const t=w();this.toolbar=new Ye(this.shadow,this.messages,()=>this.exitAll(),e=>this.handleToolbarModeChange(e),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.session=this.createSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}createSession(){return new Si(this.shadow,this.messages,{onPin:(t,e)=>{this.currentAnnotation=t,this.via="pin",this.showPopup(t.x,t.y,e,t.targetRect)},onDrawStroke:()=>this.handleDrawStroke()})}handleToolbarModeChange(t){if(this.mode==="clarifying"){this.toolbar?.setMode(this.via==="record"?"record":"markup");return}if(t==="record"){if(this.mode==="recording")return;this.mode="recording",this.currentAnnotation=null,this.teardownDraw(),this.session?.destroy(),this.session=null,this.recordingManager=new Wn,this.recordingManager.start(this.shadow,this.messages,this.handleRecordStop).catch(e=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",e),this.mode==="recording"&&(this.toolbar?.setMode("markup"),this.handleToolbarModeChange("markup"))})}else this.recordingManager?.destroy(),this.recordingManager=null,this.teardownDraw(),this.session||(this.session=this.createSession()),this.mode="annotating"}handleDrawStroke(){if(w()){this.showDrawSheet();return}this.mode!=="drawing"&&(this.mode="drawing",this.drawBar=new Li(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t)})),this.refreshDrawBar()}showDrawSheet(){this.mode!=="drawing"&&(this.mode="drawing",this.popup=new _t(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,onSubmit:t=>this.handleDrawSubmit(t),onClose:()=>this.cancelDraw(),position:this.config.position??"right"}),this.submittingUi=this.popup)}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.teardownDraw(),this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.submittingUi=null,this.mode="annotating"}teardownDraw(){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(),this.submittingUi=this.drawBar??this.popup,this.handleSubmit(t||this.messages.annotation.drawing)}showPopup(t,e,r,n){this.mode="popup",this.lastPopupPos={x:t,y:e},this.teardownDraw(),this.session?.dismissInteraction(),this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.dim=new je(this.shadow,()=>this.exitAll()),this.popup=new _t(this.shadow,{targetName:r,x:t,y:e,targetRect:n,messages:this.messages,onSubmit:s=>this.handleSubmit(s),onClose:()=>this.exitAll(),onMyFeedback:this.buildMyFeedbackHandler(),position:this.config.position??"right"}),this.submittingUi=this.popup}buildMyFeedbackHandler(){if(!this.config.user&&Fn())return async()=>{const t=await this.apiClient.createIdentityToken(Vt());!t?.identity_token||!t.board_url||(Xt(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}handleSubmit(t){if(!this.submittingUi)return;const e=this.currentAnnotation,r=this.recordingManager?.getRecording()??void 0,n=this.teardownSubmittingUi(!0),s=()=>this.startSubmissionRequest(t,e,r);this.showClarify(this.lastPopupPos,{element:n,pendingSession:s(),onRetrySubmission:s})}startSubmissionRequest(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){await Qt();const[s,o]=await Promise.all([Ur(e?[e]:[],this.brandColors),Promise.resolve(Mn())]),a=Dn(t,o,this.consoleCollector.getErrors(),e,this.config.user,r,this.config.user?void 0:Vt(),this.config.user?void 0:Yt(),this.breadcrumbCollector.getBreadcrumbs());try{const l=await this.apiClient.createSubmissionSession(a,s);return n!==this.submissionAttempt?(await this.apiClient.abandonSubmissionSession(l.id,l.token).catch(()=>{}),null):(this.activeSubmission=l,l)}catch{return null}}teardownSubmittingUi(t=!1){const e=t?this.popup?.releaseElement():void 0;return this.teardownDraw(),e||this.popup?.destroy(),this.popup=null,this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null,this.submittingUi=null,e}showClarify(t,e){this.mode="clarifying",this.tab?.setActive(!0),this.clarify=new Ni(this.shadow,{apiClient:this.apiClient,messages:this.messages,element:e.element,position:this.config.position??"right",x:t?.x,y:t?.y,onFinalize:()=>this.finalizeSubmission(),onCancel:()=>this.exitAll(),pendingSession:e.pendingSession,onRetrySubmission:e.onRetrySubmission})}async finalizeSubmission(){const t=this.submissionAttempt,e=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!e)throw new Error("No active submission session");const r=new Promise(s=>setTimeout(s,Xn)),n=await this.apiClient.finalizeSubmissionSession(e.id,e.token);await Promise.all([r,Qt()]),!(t!==this.submissionAttempt||this.activeSubmission!==e)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.lastHandoff={feedbackId:n.id,boardUrl:n.board_url,identityToken:n.identity_token},n.board_url&&Xt(n.board_url),this.clarify?.destroy(),this.clarify=null,this.teardownToolbar(),this.showSuccess({skipFollowup:e.ai_clarify_available===!1}))}showSuccess(t){this.mode="idle",this.tab?.setActive(!1),this.success=new ji(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},this.buildViewFeedbackHandler(),{...t,emailCapture:this.buildEmailCapture()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!Yt())return{onSubmit:async r=>{const n=await this.apiClient.updateReporter(t,r,e);return n&&Hn(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()=>{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.submissionAttempt+=1;const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{}),this.mode="idle",this.via="pin",this.tab?.setActive(!1),this.teardownToolbar(),this.teardownDraw(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.popup?.destroy(),this.popup=null,this.clarify?.destroy(),this.clarify=null,this.currentAnnotation=null,this.submittingUi=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.clarify?.destroy(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow.destroy()}}function Qt(){return new Promise(i=>requestAnimationFrame(()=>setTimeout(i,0)))}let k=null,_=null,L=null;function Gn(){L&&(document.removeEventListener("DOMContentLoaded",L),L=null)}function R(i){Gn(),k?.destroy(),k=i?new Kn(i):null}const Ae={init(i){R(),_=i,document.readyState==="loading"?(L=()=>{L=null,R(i)},document.addEventListener("DOMContentLoaded",L,{once:!0})):R(i)},destroy(){R(),_=null},setLocale(i){_&&(_.locale=i),k?.setLocale(i)},open(){k?.open()},close(){k?.close()},showLauncher(){k?.showLauncher()},hideLauncher(){k?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=Ae,document.addEventListener("turbo:load",()=>{const i=document.getElementById("mtb-widget-host");_&&(!i||!i.shadowRoot)&&(i?.remove(),R(_))}));exports.MakeThisBetter=Ae;
|
|
146
148
|
//# sourceMappingURL=makethisbetter.cjs.map
|