makethisbetter 1.28.2 → 1.28.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,7 +62,7 @@ var MakeThisBetter=function(){"use strict";const Qe=`*,*:before,*:after{box-sizi
62
62
  <div class="mtb-chat-finalize-message">${d(this.i18n.error.finalize_message)}</div>
63
63
  ${t?`<button class="mtb-chat-finalize-retry" type="button">${d(this.i18n.clarify.retry)}</button>`:""}
64
64
  <button class="mtb-chat-finalize-close" type="button">${d(this.i18n.success.close)}</button>
65
- `,t&&i.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=i.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),i.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const i=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");i&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),i()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const i=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const a=document.createElement("input");a.className="mtb-chat-email-input",a.type="email",a.placeholder=i.email_cta,s.appendChild(a);const o=document.createElement("button");o.className="mtb-chat-email-submit",o.type="button",o.textContent=i.notify,o.disabled=!0;const l=async()=>{const c=a.value.trim();if(!c)return;if(o.disabled=!0,a.disabled=!0,await t.onSubmit(c)){const m=document.createElement("div");m.className="mtb-chat-email-note",m.textContent=i.email_saved,r.replaceChildren(m),this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt);return}a.disabled=!1,o.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=i.email_error,r.appendChild(u)};return a.addEventListener("input",()=>{o.disabled=!a.value.trim()}),a.addEventListener("keydown",c=>{c.key==="Enter"&&a.value.trim()&&l()}),o.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(o),r.appendChild(n),r}appendUserBubble(t){const i=document.createElement("div");i.className="mtb-chat-bubble mtb-chat-bubble-user",i.textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const i=document.createElement("div");i.className="mtb-chat-ai-row",i.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,i.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const i=document.createElement("div");i.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),i.appendChild(n)}this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,i){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",i),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,i,r,n){const s=Di(n),{vw:a,vh:o,minLeft:l,maxRight:c}=s,h=tt,u=8,m=Mi(Fi,s),v=(this.el.offsetHeight||280)+80;let w,b;const zt=r&&r.width<a*.6&&r.height<o*.6;r&&zt?(w=r.left,b=r.bottom+u,b+v>o-h&&(b=r.top-v-u),b<h&&(b=Math.min(r.bottom+u,o-v-h))):(w=t+12,b=i+12),w+m>c&&(w=c-m),w<l&&(w=l),b<h&&(b=h),b+v>o-h&&(b=o-v-h),b<h&&(b=h),this.el.style.left=`${w}px`,this.el.style.top=`${b}px`,this.el.style.maxHeight=`${o-b-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const $i=5e3,Ui='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ji{constructor(t,i,r,n){const s=i.success,a=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",a);const o=document.createElement("div");o.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=Ui,o.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=a,o.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),o.appendChild(h)}this.el.appendChild(o),t.append(this.el),this.focusTrap=Jt(this.el),this.autoCloseTimer=setTimeout(r,$i)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const g="[Filtered]",qi=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Wi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Vi=[/\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],Yi=/\b(?:\d[ -]?){12,18}\d\b/g,Xi=/\bhttps?:\/\/[^\s<>"']+/gi,Ki=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Gi=new Set(["value","content"]),Ji=new Set(["password","hidden","file"]),Zi=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Qi=/(?:^|_)(?: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 _(e){let t=e.replace(qi,g).replace(Wi,g);for(const i of Vi)t=t.replace(i,g);return t=t.replace(Yi,i=>tr(i)?g:i),t.replace(Xi,i=>F(i)||g)}function F(e){try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}function it(e,t){if(t&&Qt(t)&&e!=null)return g;if(typeof e=="string")return _(e);if(Array.isArray(e))return e.map(i=>it(i));if(e&&typeof e=="object"){const i=te(e);return Object.fromEntries(Object.entries(e).map(([n,s])=>{const a=i&&Gi.has(H(n))&&s!=null?g:it(s,n);return[_(n),a]}))}return e}function Qt(e){return Qi.test(H(e))}function te(e){return Object.entries(e).some(([t,i])=>{if(typeof i!="string")return!1;const r=H(t);return Ki.has(r)?r==="type"?Ji.has(H(i)):r==="autocomplete"?i.split(/\s+/).some(n=>Zi.has(H(n))):Qt(i):!1})}function H(e){return e.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 tr(e){const t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let i=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)),i+=s,r=!r}return i%10===0}function ee(e){return te({type:e.getAttribute("type"),autocomplete:e.getAttribute("autocomplete"),name:e.getAttribute("name"),id:e.id,"aria-label":e.getAttribute("aria-label"),placeholder:e.getAttribute("placeholder")})}function rt(e,t){return e&&(ee(t)?g:_(e))}const er=512;function ie(){return new WeakMap}function re(e,t){let i=e.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const r=ne(i,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;i=i.parentElement}return!1}function ne(e,t){const i=t.get(e);if(i)return i;const r=e.textContent??"";let n="none";return r.length>er?n="too-large":_(r)!==r&&(n=Array.from(e.children).some(a=>{const o=ne(a,t);return o==="sensitive"||o==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(e,n),n}function ir(e){return new Promise(t=>{const i=new Image;i.onload=()=>t(i),i.onerror=()=>t(null),i.src=e})}function se(e){const t=[];let i=null;const r=e.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,a]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(a)||(n[0]==="M"?(i=[[s,a]],t.push(i)):i&&i.push([s,a]))}return t}function rr(e,t,i){return se(e).map(r=>r.map(([n,s],a)=>`${a===0?"M":"L"} ${n+t} ${s+i}`).join(" ")).join(" ")}let B=null;function ae(){return B||(B=Promise.resolve().then(()=>vs).catch(e=>{throw B=null,e}),B)}let Et,St=null;function Ct(){return Et!==void 0?Promise.resolve(Et):(St??(St=ae().then(({getFontEmbedCSS:e})=>e(document.body)).then(e=>(Et=e,e)).catch(()=>{St=null})),St)}const nr=200,sr="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function ar(e,t){try{if(t?.aborted)return null;const[{toJpeg:i},r]=await Promise.all([ae(),Ct()]),n=document.body.getBoundingClientRect(),s=fi(),a={x:window.scrollX,y:window.scrollY},o=ur(document.body),l=await i(document.body,{quality:.85,imagePlaceholder:sr,resourceUrlResolver:e,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:pr(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===x)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-a.y<=s.height+nr}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:o,pageScroll:a}}catch{return null}}async function or(e,t=[],i){try{const r=t.map(n=>lr(n,e.pageScroll));return await dr(e.dataUrl,r,e.metrics,e.redactions,i)}catch{return null}}function lr(e,t){const i=cr(e,t);return i.x===0&&i.y===0?e:{...e,x:e.x+i.x,y:e.y+i.y,targetRect:e.targetRect&&{...e.targetRect,top:e.targetRect.top+i.y,left:e.targetRect.left+i.x,bottom:e.targetRect.bottom+i.y},drawPath:e.drawPath&&rr(e.drawPath,i.x,i.y)}}function cr(e,t){return e.captureOffsetX!==void 0&&e.captureOffsetY!==void 0?gi({x:e.captureOffsetX,y:e.captureOffsetY},t):D(hr(e))}function hr(e){if(e.targetSelector)try{const t=document.querySelector(e.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(e.x,e.y)[0]??null}async function dr(e,t,i,r,n){const s=document.createElement("canvas"),a=s.getContext("2d");if(!a)return null;const o=await ir(e);if(!o)return null;s.width=o.naturalWidth||window.innerWidth,s.height=o.naturalHeight||window.innerHeight,a.drawImage(o,0,0);const l=bi(i,s.width,s.height);a.fillStyle="#e5e7eb";for(const c of r){const h=pi(l,c);a.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?br(a,c.drawPath,l,n?.primary):c.type==="pin"&&fr(a,G(l,c.x),J(l,c.y),n);return gr(s)}function ur(e){const t=[];for(const s of mr(e,`.${Z}`))Tt(t,s.getBoundingClientRect(),oe(s));for(const s of e.querySelectorAll("input, textarea, select")){if(le(s))continue;const a=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",o=s.closest(`.${I}`)!==null,l=ee(s)||rt(a,s)!==a;!o&&!l||Tt(t,s.getBoundingClientRect(),oe(s),he)}const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=ie();let n=i.nextNode();for(;n;){const s=n.parentElement,a=n.textContent??"",o=s?.closest(`.${I}`)!==null,l=_(a)!==a||re(n,r);if(s&&!le(s)&&(o||l)){const c=D(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))Tt(t,u,c,he)}n=i.nextNode()}return t}function oe(e){return D(Wt(e))}function mr(e,t){const i=Array.from(e.querySelectorAll(t));return e.matches(t)?[e,...i]:i}function le(e){return e.closest(`#${x}`)!==null||e.closest(`.${Z}`)!==null}function Tt(e,t,i,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||e.push({left:t.left+i.x-r,top:t.top+i.y-r,width:t.width+r*2,height:t.height+r*2})}function br(e,t,i,r=Yt){e.save(),e.lineCap="round",e.lineJoin="round";for(const n of se(t))if(n.length!==0){e.beginPath(),e.moveTo(G(i,n[0][0]),J(i,n[0][1]));for(let s=1;s<n.length;s++)e.lineTo(G(i,n[s][0]),J(i,n[s][1]));e.shadowColor="transparent",e.strokeStyle="rgba(15, 23, 42, 0.72)",e.lineWidth=7,e.stroke(),e.strokeStyle="#ffffff",e.lineWidth=5.5,e.stroke(),e.strokeStyle=r,e.lineWidth=3.5,e.stroke()}e.restore()}const ce=16e6,he=2;function pr(e){const t=e.width*e.height;return!Number.isFinite(t)||t<=ce?1:Math.sqrt(ce/t)}function fr(e,t,i,r){const n=r?.primary??Yt;e.save(),e.shadowColor="rgba(15, 23, 42, 0.68)",e.shadowOffsetY=2,e.shadowBlur=8,e.fillStyle=n,e.beginPath(),e.arc(t,i,11,0,Math.PI*2),e.fill(),e.shadowColor="transparent",e.lineWidth=2,e.strokeStyle="#ffffff",e.stroke(),e.restore()}function gr(e){return new Promise(t=>{try{e.toBlob(i=>t(i),"image/jpeg",.85)}catch{t(null)}})}class wr{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,i,r,n,s)=>(this.emit({name:yr(s),message:String(t),source:i,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,i,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const i=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: ${i}`})},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 i of this.listeners)i(t)}}const _t=new wr;function yr(e){return!e||typeof e!="object"||!("name"in e)?void 0:String(e.name)||void 0}function de(e){const t=vr(e.name)||xr(e.message),i=kr(e);return i?`${t} (${i})`:t}function vr(e){return e&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(e)?e:""}function xr(e){return e.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function kr(e){if(!e.source)return"";try{const t=new URL(e.source,window.location.href).pathname;return e.line==null?t:`${t}:${e.line}:${e.col??0}`}catch{return""}}const Er=20;class Sr{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=_t.subscribe(t=>this.record(t)))}record(t){this.addError(de(t))}addError(t){this.errors.length>=Er||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const nt=new Set;let N=null,O=null,z=null,st=null,$=null,at=null;function ue(e){nt.add(e),Cr();let t=!1;return()=>{t||(t=!0,nt.delete(e),nt.size===0&&Tr())}}function At(e,t){const i={type:e,fromUrl:t,toUrl:location.href};at=i.toUrl;for(const r of[...nt])try{r(i)}catch{}}function Cr(){if(z)return;at=location.href,$=()=>At("pop",at??location.href),window.addEventListener("popstate",$),N=history.pushState,O=history.replaceState;const e=N,t=O;z=function(i,r,n){const s=location.href;e.call(history,i,r,n),At("push",s)},st=function(i,r,n){const s=location.href;t.call(history,i,r,n),At("replace",s)},history.pushState=z,history.replaceState=st}function Tr(){$&&(window.removeEventListener("popstate",$),$=null),N&&history.pushState===z&&(history.pushState=N),O&&history.replaceState===st&&(history.replaceState=O),N=null,O=null,z=null,st=null,at=null}const _r=20;function Ar(e){return Q(e)?vt(e):gt(e)}function Lr(e){return Q(e)?Xt(e):Ut(e)}class Pr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=_t.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=ue(()=>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>_r&&this.breadcrumbs.shift()}handleClick(t){const i=t.target;if(i&&!C(i))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:Ar(i),data:{selector:Lr(i)}})}catch{}}handleChange(t){const i=t.target;if(i&&!C(i))try{const r=i,n=Q(i)?vt(i):r.name||r.placeholder||i.getAttribute("aria-label")||i.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const i=de(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:i,data:{message:i}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,i=location.href;if(t===i)return;this.lastUrl=i;const r=F(t),n=F(i);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const me="mtb_frustration_state";let Lt=null;function ot(){try{const e=window.sessionStorage.getItem(me);return lt(e?JSON.parse(e):Lt)}catch{return lt(Lt)}}function be(e){const t=lt(e);Lt=t;try{window.sessionStorage.setItem(me,JSON.stringify(t))}catch{}}function Rr(){return ot().dismissedByUser}function Dr(){be({...ot(),dismissedByUser:!0})}function lt(e){const t=e??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(i=>typeof i=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(i=>typeof i=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const Mr=4,Ir=1500,Fr=3,Hr=5e3,Pt=500,Br=2,Nr=3e4,Or=2e3,zr=1e3,$r=300,Ur=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),jr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),qr=new Set(["A","BUTTON","SUMMARY"]),Wr=new Set(["button","link","tab","menuitem"]),pe=[/\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/],X=class X{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=i=>this.handleClick(i)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=_t.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>Or)return;const i=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:ct(i.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,i){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},i);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=ue(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=ot();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=ot();be({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const i=t.target;if(!i||C(i))return;this.trackFormSubmitIntent(i),this.trackNativeNavigationIntent(t,i);const r=this.interactionTarget(i),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-Ir;if(this.clickHistory=this.clickHistory.filter(o=>o.time>s),this.clickHistory.filter(o=>o.target===r).length>=Mr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:ct(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const i=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(i);const n=i-Hr;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=Fr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:i}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},$r)}handleFormSubmit(t){const i=t.target;i instanceof HTMLFormElement&&(C(i)||(this.rememberSubmitAttempt(i),this.schedule(()=>{this.active&&i.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(i)},Pt)))}trackFormSubmitIntent(t){const i=t.closest("button, input");(i instanceof HTMLButtonElement||i instanceof HTMLInputElement)&&(i.type!=="submit"&&i.type!=="image"||!i.form||C(i.form)||this.rememberSubmitAttempt(i.form))}trackNativeNavigationIntent(t,i){i.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},Pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),Pt);const i=Date.now(),r=i-Nr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(i),this.formFailureTimestamps.set(t,n),!(n.length<Br)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:ct(t),timestamp:i}))}handleFormInvalid(t){const i=t.target;if(!i||C(i))return;const r=i.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const i=document.title.toLowerCase();if(pe.some(n=>n.test(i))){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&&pe.some(a=>a.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,i){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=i,n=this.lastNavigationAt>=i;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:ct(t),timestamp:i})},zr))}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(qr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const i=t.getAttribute("role");if(i&&Wr.has(i)||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 i=t;for(;i&&i!==document.body;){if(this.isIntrinsicInteractive(i))return i;i=i.parentElement}let r=t;for(i=t.parentElement;i&&i!==document.body&&this.looksInteractive(i);)r=i,i=i.parentElement;return r}isIntrinsicInteractive(t){if(Ur.has(t.tagName))return!0;const i=t.getAttribute("role");return i&&jr.has(i)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const i=Date.now();i<this.cooldownUntil||(this.cooldownUntil=i+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};X.COOLDOWN_MS=6e4;let Rt=X;function ct(e){const t=e.tagName.toLowerCase(),i=e.id?`#${e.id}`:"",r=e.className&&typeof e.className=="string"?"."+e.className.trim().split(/\s+/).slice(0,2).join("."):"",n=e.textContent?.trim().slice(0,30)??"";return`<${t}${i}${r}>${n?` "${n}"`:""}`}class Vr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Yr=25e3,Xr="https://makethisbetter.dev/api/v1",Kr="sensitive-data-v1";class Gr{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Xr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,i,r,n,s){if(!(n&&!n.startsWith("image/")))try{const a=new URL(r,window.location.href);if(!["http:","https:"].includes(a.protocol)||a.origin===window.location.origin)return;const o=await this.submissionHeaders(i,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:o,body:JSON.stringify({image_proxy_url:{source:a.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const i={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(i["X-User-Token"]=r),t&&(i["Content-Type"]=t),i}async submissionHeaders(t,i){const r=await this.authHeaders(i);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,i){const r=Qr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(i){const l=i.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",i,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Kr,s["X-Idempotency-Key"]=Zr(),{...(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 i=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:i,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,i,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:i}})}),!0}catch{return!1}}async answerClarification(t,i,r){return this.requestClarification(t,i,{message:_(r)})}async requestClarification(t,i,r){const n=await this.submissionHeaders(i,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,i,r,n){const s=await this.submissionHeaders(i,"application/json");s.Accept="text/event-stream";const a=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),o=a.headers.get("Content-Type")??"";if(!a.ok||!a.body||!o.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Jr(a.body,r)}async finalizeSubmissionSession(t,i){const r=await this.submissionHeaders(i),n=new AbortController,s=setTimeout(()=>n.abort(),Yr);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,i,r,n){const s=await this.submissionHeaders(i);delete s["Content-Type"];const a=new FormData;a.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:a,signal:n})}async abandonSubmissionSession(t,i){const r=await this.submissionHeaders(i);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,i,r=1){let n;try{n=await fetch(t,i)}catch(s){if(r>0&&!i.signal?.aborted)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw new Vr(n.status)}}function fe(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async function Jr(e,t){const i=e.getReader(),r=new TextDecoder;let n="",s=null;const a=o=>{const l=o.split(`
65
+ `,t&&i.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=i.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),i.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const i=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");i&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),i()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const i=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const a=document.createElement("input");a.className="mtb-chat-email-input",a.type="email",a.placeholder=i.email_cta,s.appendChild(a);const o=document.createElement("button");o.className="mtb-chat-email-submit",o.type="button",o.textContent=i.notify,o.disabled=!0;const l=async()=>{const c=a.value.trim();if(!c)return;if(o.disabled=!0,a.disabled=!0,await t.onSubmit(c)){const m=document.createElement("div");m.className="mtb-chat-email-note",m.textContent=i.email_saved,r.replaceChildren(m),this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt);return}a.disabled=!1,o.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=i.email_error,r.appendChild(u)};return a.addEventListener("input",()=>{o.disabled=!a.value.trim()}),a.addEventListener("keydown",c=>{c.key==="Enter"&&a.value.trim()&&l()}),o.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(o),r.appendChild(n),r}appendUserBubble(t){const i=document.createElement("div");i.className="mtb-chat-bubble mtb-chat-bubble-user",i.textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const i=document.createElement("div");i.className="mtb-chat-ai-row",i.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,i.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const i=document.createElement("div");i.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),i.appendChild(n)}this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,i){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",i),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,i,r,n){const s=Di(n),{vw:a,vh:o,minLeft:l,maxRight:c}=s,h=tt,u=8,m=Mi(Fi,s),v=(this.el.offsetHeight||280)+80;let w,b;const zt=r&&r.width<a*.6&&r.height<o*.6;r&&zt?(w=r.left,b=r.bottom+u,b+v>o-h&&(b=r.top-v-u),b<h&&(b=Math.min(r.bottom+u,o-v-h))):(w=t+12,b=i+12),w+m>c&&(w=c-m),w<l&&(w=l),b<h&&(b=h),b+v>o-h&&(b=o-v-h),b<h&&(b=h),this.el.style.left=`${w}px`,this.el.style.top=`${b}px`,this.el.style.maxHeight=`${o-b-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const $i=5e3,Ui='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ji{constructor(t,i,r,n){const s=i.success,a=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",a);const o=document.createElement("div");o.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=Ui,o.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=a,o.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),o.appendChild(h)}this.el.appendChild(o),t.append(this.el),this.focusTrap=Jt(this.el),this.autoCloseTimer=setTimeout(r,$i)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const g="[Filtered]",qi=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Wi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Vi=[/\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],Yi=/\b(?:\d[ -]?){12,18}\d\b/g,Xi=/\bhttps?:\/\/[^\s<>"']+/gi,Ki=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Gi=new Set(["value","content"]),Ji=new Set(["password","hidden","file"]),Zi=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Qi=/(?:^|_)(?: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 _(e){let t=e.replace(qi,g).replace(Wi,g);for(const i of Vi)t=t.replace(i,g);return t=t.replace(Yi,i=>tr(i)?g:i),t.replace(Xi,i=>F(i)||g)}function F(e){try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}function it(e,t){if(t&&Qt(t)&&e!=null)return g;if(typeof e=="string")return _(e);if(Array.isArray(e))return e.map(i=>it(i));if(e&&typeof e=="object"){const i=te(e);return Object.fromEntries(Object.entries(e).map(([n,s])=>{const a=i&&Gi.has(H(n))&&s!=null?g:it(s,n);return[_(n),a]}))}return e}function Qt(e){return Qi.test(H(e))}function te(e){return Object.entries(e).some(([t,i])=>{if(typeof i!="string")return!1;const r=H(t);return Ki.has(r)?r==="type"?Ji.has(H(i)):r==="autocomplete"?i.split(/\s+/).some(n=>Zi.has(H(n))):Qt(i):!1})}function H(e){return e.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 tr(e){const t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let i=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)),i+=s,r=!r}return i%10===0}function ee(e){return te({type:e.getAttribute("type"),autocomplete:e.getAttribute("autocomplete"),name:e.getAttribute("name"),id:e.id,"aria-label":e.getAttribute("aria-label"),placeholder:e.getAttribute("placeholder")})}function rt(e,t){return e&&(ee(t)?g:_(e))}const er=512;function ie(){return new WeakMap}function re(e,t){let i=e.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const r=ne(i,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;i=i.parentElement}return!1}function ne(e,t){const i=t.get(e);if(i)return i;const r=e.textContent??"";let n="none";return r.length>er?n="too-large":_(r)!==r&&(n=Array.from(e.children).some(a=>{const o=ne(a,t);return o==="sensitive"||o==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(e,n),n}function ir(e){return new Promise(t=>{const i=new Image;i.onload=()=>t(i),i.onerror=()=>t(null),i.src=e})}function se(e){const t=[];let i=null;const r=e.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,a]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(a)||(n[0]==="M"?(i=[[s,a]],t.push(i)):i&&i.push([s,a]))}return t}function rr(e,t,i){return se(e).map(r=>r.map(([n,s],a)=>`${a===0?"M":"L"} ${n+t} ${s+i}`).join(" ")).join(" ")}let B=null;function ae(){return B||(B=Promise.resolve().then(()=>vs).catch(e=>{throw B=null,e}),B)}let Et,St=null;function Ct(){return Et!==void 0?Promise.resolve(Et):(St??(St=ae().then(({getFontEmbedCSS:e})=>e(document.body)).then(e=>(Et=e,e)).catch(()=>{St=null})),St)}const nr=200,sr="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function ar(e,t){try{if(t?.aborted)return null;const[{toJpeg:i},r]=await Promise.all([ae(),Ct()]);if(await new Promise(c=>setTimeout(c,0)),t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=fi(),a={x:window.scrollX,y:window.scrollY},o=ur(document.body),l=await i(document.body,{quality:.85,imagePlaceholder:sr,resourceUrlResolver:e,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:pr(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===x)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-a.y<=s.height+nr}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:o,pageScroll:a}}catch{return null}}async function or(e,t=[],i){try{const r=t.map(n=>lr(n,e.pageScroll));return await dr(e.dataUrl,r,e.metrics,e.redactions,i)}catch{return null}}function lr(e,t){const i=cr(e,t);return i.x===0&&i.y===0?e:{...e,x:e.x+i.x,y:e.y+i.y,targetRect:e.targetRect&&{...e.targetRect,top:e.targetRect.top+i.y,left:e.targetRect.left+i.x,bottom:e.targetRect.bottom+i.y},drawPath:e.drawPath&&rr(e.drawPath,i.x,i.y)}}function cr(e,t){return e.captureOffsetX!==void 0&&e.captureOffsetY!==void 0?gi({x:e.captureOffsetX,y:e.captureOffsetY},t):D(hr(e))}function hr(e){if(e.targetSelector)try{const t=document.querySelector(e.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(e.x,e.y)[0]??null}async function dr(e,t,i,r,n){const s=document.createElement("canvas"),a=s.getContext("2d");if(!a)return null;const o=await ir(e);if(!o)return null;s.width=o.naturalWidth||window.innerWidth,s.height=o.naturalHeight||window.innerHeight,a.drawImage(o,0,0);const l=bi(i,s.width,s.height);a.fillStyle="#e5e7eb";for(const c of r){const h=pi(l,c);a.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?br(a,c.drawPath,l,n?.primary):c.type==="pin"&&fr(a,G(l,c.x),J(l,c.y),n);return gr(s)}function ur(e){const t=[];for(const s of mr(e,`.${Z}`))Tt(t,s.getBoundingClientRect(),oe(s));for(const s of e.querySelectorAll("input, textarea, select")){if(le(s))continue;const a=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",o=s.closest(`.${I}`)!==null,l=ee(s)||rt(a,s)!==a;!o&&!l||Tt(t,s.getBoundingClientRect(),oe(s),he)}const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=ie();let n=i.nextNode();for(;n;){const s=n.parentElement,a=n.textContent??"",o=s?.closest(`.${I}`)!==null,l=_(a)!==a||re(n,r);if(s&&!le(s)&&(o||l)){const c=D(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))Tt(t,u,c,he)}n=i.nextNode()}return t}function oe(e){return D(Wt(e))}function mr(e,t){const i=Array.from(e.querySelectorAll(t));return e.matches(t)?[e,...i]:i}function le(e){return e.closest(`#${x}`)!==null||e.closest(`.${Z}`)!==null}function Tt(e,t,i,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||e.push({left:t.left+i.x-r,top:t.top+i.y-r,width:t.width+r*2,height:t.height+r*2})}function br(e,t,i,r=Yt){e.save(),e.lineCap="round",e.lineJoin="round";for(const n of se(t))if(n.length!==0){e.beginPath(),e.moveTo(G(i,n[0][0]),J(i,n[0][1]));for(let s=1;s<n.length;s++)e.lineTo(G(i,n[s][0]),J(i,n[s][1]));e.shadowColor="transparent",e.strokeStyle="rgba(15, 23, 42, 0.72)",e.lineWidth=7,e.stroke(),e.strokeStyle="#ffffff",e.lineWidth=5.5,e.stroke(),e.strokeStyle=r,e.lineWidth=3.5,e.stroke()}e.restore()}const ce=16e6,he=2;function pr(e){const t=e.width*e.height;return!Number.isFinite(t)||t<=ce?1:Math.sqrt(ce/t)}function fr(e,t,i,r){const n=r?.primary??Yt;e.save(),e.shadowColor="rgba(15, 23, 42, 0.68)",e.shadowOffsetY=2,e.shadowBlur=8,e.fillStyle=n,e.beginPath(),e.arc(t,i,11,0,Math.PI*2),e.fill(),e.shadowColor="transparent",e.lineWidth=2,e.strokeStyle="#ffffff",e.stroke(),e.restore()}function gr(e){return new Promise(t=>{try{e.toBlob(i=>t(i),"image/jpeg",.85)}catch{t(null)}})}class wr{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,i,r,n,s)=>(this.emit({name:yr(s),message:String(t),source:i,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,i,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const i=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: ${i}`})},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 i of this.listeners)i(t)}}const _t=new wr;function yr(e){return!e||typeof e!="object"||!("name"in e)?void 0:String(e.name)||void 0}function de(e){const t=vr(e.name)||xr(e.message),i=kr(e);return i?`${t} (${i})`:t}function vr(e){return e&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(e)?e:""}function xr(e){return e.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function kr(e){if(!e.source)return"";try{const t=new URL(e.source,window.location.href).pathname;return e.line==null?t:`${t}:${e.line}:${e.col??0}`}catch{return""}}const Er=20;class Sr{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=_t.subscribe(t=>this.record(t)))}record(t){this.addError(de(t))}addError(t){this.errors.length>=Er||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const nt=new Set;let N=null,O=null,z=null,st=null,$=null,at=null;function ue(e){nt.add(e),Cr();let t=!1;return()=>{t||(t=!0,nt.delete(e),nt.size===0&&Tr())}}function At(e,t){const i={type:e,fromUrl:t,toUrl:location.href};at=i.toUrl;for(const r of[...nt])try{r(i)}catch{}}function Cr(){if(z)return;at=location.href,$=()=>At("pop",at??location.href),window.addEventListener("popstate",$),N=history.pushState,O=history.replaceState;const e=N,t=O;z=function(i,r,n){const s=location.href;e.call(history,i,r,n),At("push",s)},st=function(i,r,n){const s=location.href;t.call(history,i,r,n),At("replace",s)},history.pushState=z,history.replaceState=st}function Tr(){$&&(window.removeEventListener("popstate",$),$=null),N&&history.pushState===z&&(history.pushState=N),O&&history.replaceState===st&&(history.replaceState=O),N=null,O=null,z=null,st=null,at=null}const _r=20;function Ar(e){return Q(e)?vt(e):gt(e)}function Lr(e){return Q(e)?Xt(e):Ut(e)}class Pr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=_t.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=ue(()=>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>_r&&this.breadcrumbs.shift()}handleClick(t){const i=t.target;if(i&&!C(i))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:Ar(i),data:{selector:Lr(i)}})}catch{}}handleChange(t){const i=t.target;if(i&&!C(i))try{const r=i,n=Q(i)?vt(i):r.name||r.placeholder||i.getAttribute("aria-label")||i.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const i=de(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:i,data:{message:i}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,i=location.href;if(t===i)return;this.lastUrl=i;const r=F(t),n=F(i);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const me="mtb_frustration_state";let Lt=null;function ot(){try{const e=window.sessionStorage.getItem(me);return lt(e?JSON.parse(e):Lt)}catch{return lt(Lt)}}function be(e){const t=lt(e);Lt=t;try{window.sessionStorage.setItem(me,JSON.stringify(t))}catch{}}function Rr(){return ot().dismissedByUser}function Dr(){be({...ot(),dismissedByUser:!0})}function lt(e){const t=e??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(i=>typeof i=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(i=>typeof i=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const Mr=4,Ir=1500,Fr=3,Hr=5e3,Pt=500,Br=2,Nr=3e4,Or=2e3,zr=1e3,$r=300,Ur=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),jr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),qr=new Set(["A","BUTTON","SUMMARY"]),Wr=new Set(["button","link","tab","menuitem"]),pe=[/\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/],X=class X{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=i=>this.handleClick(i)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=_t.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>Or)return;const i=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:ct(i.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,i){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},i);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=ue(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=ot();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=ot();be({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const i=t.target;if(!i||C(i))return;this.trackFormSubmitIntent(i),this.trackNativeNavigationIntent(t,i);const r=this.interactionTarget(i),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-Ir;if(this.clickHistory=this.clickHistory.filter(o=>o.time>s),this.clickHistory.filter(o=>o.target===r).length>=Mr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:ct(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const i=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(i);const n=i-Hr;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=Fr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:i}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},$r)}handleFormSubmit(t){const i=t.target;i instanceof HTMLFormElement&&(C(i)||(this.rememberSubmitAttempt(i),this.schedule(()=>{this.active&&i.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(i)},Pt)))}trackFormSubmitIntent(t){const i=t.closest("button, input");(i instanceof HTMLButtonElement||i instanceof HTMLInputElement)&&(i.type!=="submit"&&i.type!=="image"||!i.form||C(i.form)||this.rememberSubmitAttempt(i.form))}trackNativeNavigationIntent(t,i){i.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},Pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),Pt);const i=Date.now(),r=i-Nr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(i),this.formFailureTimestamps.set(t,n),!(n.length<Br)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:ct(t),timestamp:i}))}handleFormInvalid(t){const i=t.target;if(!i||C(i))return;const r=i.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const i=document.title.toLowerCase();if(pe.some(n=>n.test(i))){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&&pe.some(a=>a.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,i){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=i,n=this.lastNavigationAt>=i;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:ct(t),timestamp:i})},zr))}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(qr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const i=t.getAttribute("role");if(i&&Wr.has(i)||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 i=t;for(;i&&i!==document.body;){if(this.isIntrinsicInteractive(i))return i;i=i.parentElement}let r=t;for(i=t.parentElement;i&&i!==document.body&&this.looksInteractive(i);)r=i,i=i.parentElement;return r}isIntrinsicInteractive(t){if(Ur.has(t.tagName))return!0;const i=t.getAttribute("role");return i&&jr.has(i)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const i=Date.now();i<this.cooldownUntil||(this.cooldownUntil=i+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};X.COOLDOWN_MS=6e4;let Rt=X;function ct(e){const t=e.tagName.toLowerCase(),i=e.id?`#${e.id}`:"",r=e.className&&typeof e.className=="string"?"."+e.className.trim().split(/\s+/).slice(0,2).join("."):"",n=e.textContent?.trim().slice(0,30)??"";return`<${t}${i}${r}>${n?` "${n}"`:""}`}class Vr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Yr=25e3,Xr="https://makethisbetter.dev/api/v1",Kr="sensitive-data-v1";class Gr{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Xr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,i,r,n,s){if(!(n&&!n.startsWith("image/")))try{const a=new URL(r,window.location.href);if(!["http:","https:"].includes(a.protocol)||a.origin===window.location.origin)return;const o=await this.submissionHeaders(i,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:o,body:JSON.stringify({image_proxy_url:{source:a.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const i={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(i["X-User-Token"]=r),t&&(i["Content-Type"]=t),i}async submissionHeaders(t,i){const r=await this.authHeaders(i);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,i){const r=Qr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(i){const l=i.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",i,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Kr,s["X-Idempotency-Key"]=Zr(),{...(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 i=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:i,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,i,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:i}})}),!0}catch{return!1}}async answerClarification(t,i,r){return this.requestClarification(t,i,{message:_(r)})}async requestClarification(t,i,r){const n=await this.submissionHeaders(i,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,i,r,n){const s=await this.submissionHeaders(i,"application/json");s.Accept="text/event-stream";const a=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),o=a.headers.get("Content-Type")??"";if(!a.ok||!a.body||!o.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Jr(a.body,r)}async finalizeSubmissionSession(t,i){const r=await this.submissionHeaders(i),n=new AbortController,s=setTimeout(()=>n.abort(),Yr);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,i,r,n){const s=await this.submissionHeaders(i);delete s["Content-Type"];const a=new FormData;a.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:a,signal:n})}async abandonSubmissionSession(t,i){const r=await this.submissionHeaders(i);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,i,r=1){let n;try{n=await fetch(t,i)}catch(s){if(r>0&&!i.signal?.aborted)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw new Vr(n.status)}}function fe(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async function Jr(e,t){const i=e.getReader(),r=new TextDecoder;let n="",s=null;const a=o=>{const l=o.split(`
66
66
  `).find(m=>m.startsWith("event:")),c=o.split(`
67
67
  `).find(m=>m.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(m=>typeof m=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:o,value:l}=await i.read();if(o)break;n+=r.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
68
68