makethisbetter 1.28.6 → 1.28.7

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 @@
62
62
  <div class="mtb-chat-finalize-message">${d(this.i18n.error.finalize_message)}</div>
63
63
  ${t?`<button class="mtb-chat-finalize-retry" type="button">${d(this.i18n.clarify.retry)}</button>`:""}
64
64
  <button class="mtb-chat-finalize-close" type="button">${d(this.i18n.success.close)}</button>
65
- `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):this.finalized&&!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>{this.finalized=!0,this.attachHandoff()}).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=hi(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=Q,u=8,b=di(mi,s),k=(this.el.offsetHeight||280)+80;let f,m;const lt=r&&r.width<o*.6&&r.height<a*.6;r&&lt?(f=r.left,m=r.bottom+u,m+k>a-h&&(m=r.top-k-u),m<h&&(m=Math.min(r.bottom+u,a-k-h))):(f=t+12,m=e+12),f+b>c&&(f=c-b),f<l&&(f=l),m<h&&(m=h),m+k>a-h&&(m=a-k-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const wi=5e3,yi='<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 xi{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=yi,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,wi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",ki=/-----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,Si=[/\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],_i=/\b(?:\d[ -]?){12,18}\d\b/g,Ci=/\bhttps?:\/\/[^\s<>"']+/gi,Ti=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Ai=new Set(["value","content"]),Li=new Set(["password","hidden","file"]),Pi=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 T(i){let t=i.replace(ki,p).replace(Ei,p);for(const e of Si)t=t.replace(e,p);return t=t.replace(_i,e=>Mi(e)?p:e),t.replace(Ci,e=>$(e)||p)}function $(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function tt(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return T(i);if(Array.isArray(i))return i.map(e=>tt(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Ai.has(I(n))&&s!=null?p:tt(s,n);return[T(n),o]}))}return i}function ne(i){return Di.test(I(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return Ti.has(r)?r==="type"?Li.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Pi.has(I(n))):ne(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 Mi(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function et(i,t){return i&&(oe(t)?p:T(i))}const Ri=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ri?n="too-large":T(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Ii(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Hi(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let L=null;function de(){return L||(L=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw L=null,i}),L)}let dt,ut=null;function _t(){return dt!==void 0?Promise.resolve(dt):(ut??(ut=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(dt=i,i)).catch(()=>{ut=null})),ut)}const Ni=200,Fi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function Bi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),_t()]);if(t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=Xe(),o={x:window.scrollX,y:window.scrollY},a=qi(document.body),l=await e(document.body,{quality:.85,imagePlaceholder:Fi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Vi(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===v)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Ni}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function zi(i,t=[],e){try{const r=t.map(n=>Oi(n,i.pageScroll));return await ji(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Oi(i,t){const e=Ui(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Hi(i.drawPath,e.x,e.y)}}function Ui(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ke({x:i.captureOffsetX,y:i.captureOffsetY},t):j($i(i))}function $i(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function ji(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Ii(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=Ye(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of r){const h=Ve(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?Yi(o,c.drawPath,l,n?.primary):c.type==="pin"&&Xi(o,Z(l,c.x),J(l,c.y),n);return Ki(s)}function qi(i){const t=[];for(const s of Wi(i,`.${st}`))mt(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=oe(s)||et(o,s)!==o;!a&&!l||mt(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=T(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||l)){const c=j(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))mt(t,u,c,Ft)}n=e.nextNode()}return t}function It(i){return j(Qt(i))}function Wi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${v}`)!==null||i.closest(`.${st}`)!==null}function mt(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Yi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(Z(e,n[0][0]),J(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(Z(e,n[s][0]),J(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Vi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Xi(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Ki(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Gi{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:Zi(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 Ct=new Gi;function Zi(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Ji(i.name)||Qi(i.message),e=tr(i);return e?`${t} (${e})`:t}function Ji(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function Qi(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function tr(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 er=20;class ir{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=Ct.subscribe(t=>this.record(t)))}record(t){this.addError(ue(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 K=new Set;let H=null,N=null,F=null,it=null,B=null,rt=null;function me(i){K.add(i),rr();let t=!1;return()=>{t||(t=!0,K.delete(i),K.size===0&&nr())}}function bt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};rt=e.toUrl;for(const r of[...K])try{r(e)}catch{}}function rr(){if(F)return;rt=location.href,B=()=>bt("pop",rt??location.href),window.addEventListener("popstate",B),H=history.pushState,N=history.replaceState;const i=H,t=N;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),bt("push",s)},it=function(e,r,n){const s=location.href;t.call(history,e,r,n),bt("replace",s)},history.pushState=F,history.replaceState=it}function nr(){B&&(window.removeEventListener("popstate",B),B=null),H&&history.pushState===F&&(history.pushState=H),N&&history.replaceState===it&&(history.replaceState=N),H=null,N=null,F=null,it=null,rt=null}const sr=20;function or(i){return ot(i)?St(i):Et(i)}function ar(i){return ot(i)?ee(i):Jt(i)}class lr{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=Ct.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>sr&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!E(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:or(e),data:{selector:ar(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!E(e))try{const r=e,n=ot(e)?St(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=$(t),n=$(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let wt=null;function nt(){try{const i=window.sessionStorage.getItem(be);return G(i?JSON.parse(i):wt)}catch{return G(wt)}}function pe(i){const t=G(i);wt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function cr(){return nt().dismissedByUser}function hr(){pe({...nt(),dismissedByUser:!0})}function G(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 dr=4,ur=1500,mr=3,br=5e3,pt=500,pr=2,fr=3e4,gr=2e3,vr=1e3,wr=300,yr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),xr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),kr=new Set(["A","BUTTON","SUMMARY"]),Er=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],O=class O{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=Ct.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>gr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:W(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=nt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=nt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||E(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-ur;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=dr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:W(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-br;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=mr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},wr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(E(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},pt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||E(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),pt);const e=Date.now(),r=e-fr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<pr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:W(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||E(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:W(t),timestamp:e})},vr))}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(kr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Er.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(yr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&xr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};O.COOLDOWN_MS=6e4;let yt=O;function W(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class Sr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const _r=25e3,Cr="https://makethisbetter.dev/api/v1",Tr="sensitive-data-v1";class Ar{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Cr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Dr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const l=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Tr,s["X-Idempotency-Key"]=Pr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:T(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Lr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),_r);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Sr(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Lr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
65
+ `,t&&e.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=e.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),e.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.finalized=!0,this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const e=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");e&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),e()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):this.finalized&&!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const e=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=e.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=e.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const b=document.createElement("div");b.className="mtb-chat-email-note",b.textContent=e.email_saved,r.replaceChildren(b),this.autoCloseTimer=setTimeout(()=>this.destroy(),Rt);return}o.disabled=!1,a.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=e.email_error,r.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),r.appendChild(n),r}appendUserBubble(t){const e=document.createElement("div");e.className="mtb-chat-bubble mtb-chat-bubble-user",e.textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const e=document.createElement("div");e.className="mtb-chat-ai-row",e.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,e.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const e=document.createElement("div");e.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),e.appendChild(n)}this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${q}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,e){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",e),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,e,r,n){const s=hi(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=Q,u=8,b=di(mi,s),k=(this.el.offsetHeight||280)+80;let f,m;const lt=r&&r.width<o*.6&&r.height<a*.6;r&&lt?(f=r.left,m=r.bottom+u,m+k>a-h&&(m=r.top-k-u),m<h&&(m=Math.min(r.bottom+u,a-k-h))):(f=t+12,m=e+12),f+b>c&&(f=c-b),f<l&&(f=l),m<h&&(m=h),m+k>a-h&&(m=a-k-h),m<h&&(m=h),this.el.style.left=`${f}px`,this.el.style.top=`${m}px`,this.el.style.maxHeight=`${a-m-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const wi=5e3,yi='<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 xi{constructor(t,e,r,n){const s=e.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=yi,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=re(this.el),this.autoCloseTimer=setTimeout(r,wi)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const p="[Filtered]",ki=/-----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,Si=[/\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],_i=/\b(?:\d[ -]?){12,18}\d\b/g,Ci=/\bhttps?:\/\/[^\s<>"']+/gi,Ti=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Ai=new Set(["value","content"]),Li=new Set(["password","hidden","file"]),Pi=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 T(i){let t=i.replace(ki,p).replace(Ei,p);for(const e of Si)t=t.replace(e,p);return t=t.replace(_i,e=>Mi(e)?p:e),t.replace(Ci,e=>$(e)||p)}function $(i){try{const t=new URL(i);return`${t.origin}${t.pathname}`}catch{return""}}function tt(i,t){if(t&&ne(t)&&i!=null)return p;if(typeof i=="string")return T(i);if(Array.isArray(i))return i.map(e=>tt(e));if(i&&typeof i=="object"){const e=se(i);return Object.fromEntries(Object.entries(i).map(([n,s])=>{const o=e&&Ai.has(I(n))&&s!=null?p:tt(s,n);return[T(n),o]}))}return i}function ne(i){return Di.test(I(i))}function se(i){return Object.entries(i).some(([t,e])=>{if(typeof e!="string")return!1;const r=I(t);return Ti.has(r)?r==="type"?Li.has(I(e)):r==="autocomplete"?e.split(/\s+/).some(n=>Pi.has(I(n))):ne(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 Mi(i){const t=i.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let e=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),e+=s,r=!r}return e%10===0}function oe(i){return se({type:i.getAttribute("type"),autocomplete:i.getAttribute("autocomplete"),name:i.getAttribute("name"),id:i.id,"aria-label":i.getAttribute("aria-label"),placeholder:i.getAttribute("placeholder")})}function et(i,t){return i&&(oe(t)?p:T(i))}const Ri=512;function ae(){return new WeakMap}function le(i,t){let e=i.parentElement;for(;e&&e!==document.body&&e!==document.documentElement;){const r=ce(e,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;e=e.parentElement}return!1}function ce(i,t){const e=t.get(i);if(e)return e;const r=i.textContent??"";let n="none";return r.length>Ri?n="too-large":T(r)!==r&&(n=Array.from(i.children).some(o=>{const a=ce(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(i,n),n}function Ii(i){return new Promise(t=>{const e=new Image;e.onload=()=>t(e),e.onerror=()=>t(null),e.src=i})}function he(i){const t=[];let e=null;const r=i.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(e=[[s,o]],t.push(e)):e&&e.push([s,o]))}return t}function Hi(i,t,e){return he(i).map(r=>r.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+e}`).join(" ")).join(" ")}let L=null;function de(){return L||(L=Promise.resolve().then(()=>require("./html-to-image.cjs")).catch(i=>{throw L=null,i}),L)}let dt,ut=null;function _t(){return dt!==void 0?Promise.resolve(dt):(ut??(ut=de().then(({getFontEmbedCSS:i})=>i(document.body)).then(i=>(dt=i,i)).catch(()=>{ut=null})),ut)}const Ni=200,Fi="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function Bi(i,t){try{if(t?.aborted)return null;const[{toJpeg:e},r]=await Promise.all([de(),_t()]);if(t?.aborted)return null;const n=document.body.getBoundingClientRect(),s=Xe(),o={x:window.scrollX,y:window.scrollY},a=qi(document.body),l=await e(document.body,{quality:.85,imagePlaceholder:Fi,resourceUrlResolver:i,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:Vi(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===v)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+Ni}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function zi(i,t=[],e){try{const r=t.map(n=>Oi(n,i.pageScroll));return await ji(i.dataUrl,r,i.metrics,i.redactions,e)}catch{return null}}function Oi(i,t){const e=Ui(i,t);return e.x===0&&e.y===0?i:{...i,x:i.x+e.x,y:i.y+e.y,targetRect:i.targetRect&&{...i.targetRect,top:i.targetRect.top+e.y,left:i.targetRect.left+e.x,bottom:i.targetRect.bottom+e.y},drawPath:i.drawPath&&Hi(i.drawPath,e.x,e.y)}}function Ui(i,t){return i.captureOffsetX!==void 0&&i.captureOffsetY!==void 0?Ke({x:i.captureOffsetX,y:i.captureOffsetY},t):j($i(i))}function $i(i){if(i.targetSelector)try{const t=document.querySelector(i.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(i.x,i.y)[0]??null}async function ji(i,t,e,r,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await Ii(i);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=Ye(e,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of r){const h=Ve(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?Yi(o,c.drawPath,l,n?.primary):c.type==="pin"&&Xi(o,Z(l,c.x),J(l,c.y),n);return Ki(s)}function qi(i){const t=[];for(const s of Wi(i,`.${st}`))mt(t,s.getBoundingClientRect(),It(s));for(const s of i.querySelectorAll("input, textarea, select")){if(Ht(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${U}`)!==null,l=oe(s)||et(o,s)!==o;!a&&!l||mt(t,s.getBoundingClientRect(),It(s),Ft)}const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),r=ae();let n=e.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${U}`)!==null,l=T(o)!==o||le(n,r);if(s&&!Ht(s)&&(a||l)){const c=j(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))mt(t,u,c,Ft)}n=e.nextNode()}return t}function It(i){return j(Qt(i))}function Wi(i,t){const e=Array.from(i.querySelectorAll(t));return i.matches(t)?[i,...e]:e}function Ht(i){return i.closest(`#${v}`)!==null||i.closest(`.${st}`)!==null}function mt(i,t,e,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||i.push({left:t.left+e.x-r,top:t.top+e.y-r,width:t.width+r*2,height:t.height+r*2})}function Yi(i,t,e,r=te){i.save(),i.lineCap="round",i.lineJoin="round";for(const n of he(t))if(n.length!==0){i.beginPath(),i.moveTo(Z(e,n[0][0]),J(e,n[0][1]));for(let s=1;s<n.length;s++)i.lineTo(Z(e,n[s][0]),J(e,n[s][1]));i.shadowColor="transparent",i.strokeStyle="rgba(15, 23, 42, 0.72)",i.lineWidth=7,i.stroke(),i.strokeStyle="#ffffff",i.lineWidth=5.5,i.stroke(),i.strokeStyle=r,i.lineWidth=3.5,i.stroke()}i.restore()}const Nt=16e6,Ft=2;function Vi(i){const t=i.width*i.height;return!Number.isFinite(t)||t<=Nt?1:Math.sqrt(Nt/t)}function Xi(i,t,e,r){const n=r?.primary??te;i.save(),i.shadowColor="rgba(15, 23, 42, 0.68)",i.shadowOffsetY=2,i.shadowBlur=8,i.fillStyle=n,i.beginPath(),i.arc(t,e,11,0,Math.PI*2),i.fill(),i.shadowColor="transparent",i.lineWidth=2,i.strokeStyle="#ffffff",i.stroke(),i.restore()}function Ki(i){return new Promise(t=>{try{i.toBlob(e=>t(e),"image/jpeg",.85)}catch{t(null)}})}class Gi{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:Zi(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 Ct=new Gi;function Zi(i){return!i||typeof i!="object"||!("name"in i)?void 0:String(i.name)||void 0}function ue(i){const t=Ji(i.name)||Qi(i.message),e=tr(i);return e?`${t} (${e})`:t}function Ji(i){return i&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(i)?i:""}function Qi(i){return i.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function tr(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 er=20;class ir{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=Ct.subscribe(t=>this.record(t)))}record(t){this.addError(ue(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 K=new Set;let H=null,N=null,F=null,it=null,B=null,rt=null;function me(i){K.add(i),rr();let t=!1;return()=>{t||(t=!0,K.delete(i),K.size===0&&nr())}}function bt(i,t){const e={type:i,fromUrl:t,toUrl:location.href};rt=e.toUrl;for(const r of[...K])try{r(e)}catch{}}function rr(){if(F)return;rt=location.href,B=()=>bt("pop",rt??location.href),window.addEventListener("popstate",B),H=history.pushState,N=history.replaceState;const i=H,t=N;F=function(e,r,n){const s=location.href;i.call(history,e,r,n),bt("push",s)},it=function(e,r,n){const s=location.href;t.call(history,e,r,n),bt("replace",s)},history.pushState=F,history.replaceState=it}function nr(){B&&(window.removeEventListener("popstate",B),B=null),H&&history.pushState===F&&(history.pushState=H),N&&history.replaceState===it&&(history.replaceState=N),H=null,N=null,F=null,it=null,rt=null}const sr=20;function or(i){return ot(i)?St(i):Et(i)}function ar(i){return ot(i)?ee(i):Jt(i)}class lr{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=Ct.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=me(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>sr&&this.breadcrumbs.shift()}handleClick(t){const e=t.target;if(e&&!E(e))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:or(e),data:{selector:ar(e)}})}catch{}}handleChange(t){const e=t.target;if(e&&!E(e))try{const r=e,n=ot(e)?St(e):r.name||r.placeholder||e.getAttribute("aria-label")||e.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const e=ue(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:e,data:{message:e}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,e=location.href;if(t===e)return;this.lastUrl=e;const r=$(t),n=$(e);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const be="mtb_frustration_state";let wt=null;function nt(){try{const i=window.sessionStorage.getItem(be);return G(i?JSON.parse(i):wt)}catch{return G(wt)}}function pe(i){const t=G(i);wt=t;try{window.sessionStorage.setItem(be,JSON.stringify(t))}catch{}}function cr(){return nt().dismissedByUser}function hr(){pe({...nt(),dismissedByUser:!0})}function G(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 dr=4,ur=1500,mr=3,br=5e3,pt=500,pr=2,fr=3e4,gr=2e3,vr=1e3,wr=300,yr=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),xr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),kr=new Set(["A","BUTTON","SUMMARY"]),Er=new Set(["button","link","tab","menuitem"]),Bt=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],O=class O{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=Ct.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>gr)return;const e=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:W(e.target),detail:"Uncaught error after interaction",timestamp:t})}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,e){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},e);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=me(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=nt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=nt();pe({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const e=t.target;if(!e||E(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-ur;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===r).length>=dr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:W(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-br;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=mr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:e}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},wr)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(E(e)||(this.rememberSubmitAttempt(e),this.schedule(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(e)},pt)))}trackFormSubmitIntent(t){const e=t.closest("button, input");(e instanceof HTMLButtonElement||e instanceof HTMLInputElement)&&(e.type!=="submit"&&e.type!=="image"||!e.form||E(e.form)||this.rememberSubmitAttempt(e.form))}trackNativeNavigationIntent(t,e){e.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),pt);const e=Date.now(),r=e-fr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(e),this.formFailureTimestamps.set(t,n),!(n.length<pr)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:W(t),timestamp:e}))}handleFormInvalid(t){const e=t.target;if(!e||E(e))return;const r=e.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(Bt.some(n=>n.test(e))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of r){const s=n.textContent??"";if(s.length<200&&Bt.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e,n=this.lastNavigationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:W(t),timestamp:e})},vr))}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(kr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const e=t.getAttribute("role");if(e&&Er.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(yr.has(t.tagName))return!0;const e=t.getAttribute("role");return e&&xr.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+O.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};O.COOLDOWN_MS=6e4;let yt=O;function W(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",n=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${n?` "${n}"`:""}`}class Sr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const _r=25e3,Cr="https://makethisbetter.dev/api/v1",Tr="sensitive-data-v1";class Ar{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Cr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,e,r,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(r,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(e,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submissionHeaders(t,e){const r=await this.authHeaders(e);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,e){const r=Dr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const l=e.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",e,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Tr,s["X-Idempotency-Key"]=Pr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async answerClarification(t,e,r){return this.requestClarification(t,e,{message:T(r)})}async requestClarification(t,e,r){const n=await this.submissionHeaders(e,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,e,r,n){const s=await this.submissionHeaders(e,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Lr(o.body,r)}async finalizeSubmissionSession(t,e){const r=await this.submissionHeaders(e),n=new AbortController,s=setTimeout(()=>n.abort(),_r);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,e,r,n){const s=await this.submissionHeaders(e);delete s["Content-Type"];const o=new FormData;o.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,e){const r=await this.submissionHeaders(e);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,e,r=1){let n;try{n=await fetch(t,e)}catch(s){if(r>0&&!e.signal?.aborted)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await zt(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Sr(n.status)}}function zt(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function Lr(i,t){const e=i.getReader(),r=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
66
66
  `).find(b=>b.startsWith("event:")),c=a.split(`
67
67
  `).find(b=>b.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(b=>typeof b=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:a,value:l}=await e.read();if(a)break;n+=r.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
68
68