makethisbetter 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/api/client.d.ts.map +1 -1
- package/dist/context/frustration.d.ts +5 -1
- package/dist/context/frustration.d.ts.map +1 -1
- package/dist/makethisbetter.cjs.js +4 -4
- package/dist/makethisbetter.cjs.js.map +1 -1
- package/dist/makethisbetter.esm.js +94 -87
- package/dist/makethisbetter.esm.js.map +1 -1
- package/dist/makethisbetter.js +3 -3
- package/dist/makethisbetter.js.map +1 -1
- package/dist/record/session.d.ts.map +1 -1
- package/dist/widget/controller.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/api/client.test.ts +33 -0
- package/src/api/client.ts +11 -0
- package/src/context/frustration.test.ts +24 -0
- package/src/context/frustration.ts +31 -19
- package/src/record/session.ts +8 -1
- package/src/widget/controller.ts +5 -0
package/README.md
CHANGED
|
@@ -338,8 +338,8 @@ Shadow DOM Host (#mtb-widget-host)
|
|
|
338
338
|
|
|
339
339
|
| Format | Size | gzip |
|
|
340
340
|
|--------|------|------|
|
|
341
|
-
| IIFE | ~
|
|
342
|
-
| ESM | ~
|
|
341
|
+
| IIFE | ~80 KB | ~23 KB |
|
|
342
|
+
| ESM | ~94 KB | ~25 KB |
|
|
343
343
|
|
|
344
344
|
rrweb is loaded on demand and not included in these numbers.
|
|
345
345
|
|
package/dist/api/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAIlF,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,UAAU,CAAQ;IAC1B,OAAO,CAAC,YAAY,CAAQ;IAC5B,OAAO,CAAC,SAAS,CAAC,CAAQ;IAC1B,OAAO,CAAC,WAAW,CAAC,CAAuB;gBAE/B,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,YAAY,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC;IAQvH,gBAAgB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;YAKvC,WAAW;IAQnB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAIlF,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,UAAU,CAAQ;IAC1B,OAAO,CAAC,YAAY,CAAQ;IAC5B,OAAO,CAAC,SAAS,CAAC,CAAQ;IAC1B,OAAO,CAAC,WAAW,CAAC,CAAuB;gBAE/B,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,YAAY,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC;IAQvH,gBAAgB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;YAKvC,WAAW;IAQnB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA2C5F,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IAYlF,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;YAStD,cAAc;CAmB7B"}
|
|
@@ -24,7 +24,9 @@ export declare class FrustrationDetector {
|
|
|
24
24
|
private boundSubmitHandler;
|
|
25
25
|
private boundInvalidHandler;
|
|
26
26
|
private errorPageUrls;
|
|
27
|
-
private
|
|
27
|
+
private domObserver;
|
|
28
|
+
private pendingDomChecks;
|
|
29
|
+
private lastMutationAt;
|
|
28
30
|
constructor(onFrustration: (event: FrustrationEvent) => void);
|
|
29
31
|
start(): void;
|
|
30
32
|
stop(): void;
|
|
@@ -38,6 +40,8 @@ export declare class FrustrationDetector {
|
|
|
38
40
|
private handleFormInvalid;
|
|
39
41
|
private checkErrorPage;
|
|
40
42
|
private checkDeadClickDom;
|
|
43
|
+
private ensureDomObserver;
|
|
44
|
+
private disconnectDomObserver;
|
|
41
45
|
private looksInteractive;
|
|
42
46
|
private isInteractive;
|
|
43
47
|
private isWidgetElement;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"frustration.d.ts","sourceRoot":"","sources":["../../src/context/frustration.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,iBAAiB,GACzB,YAAY,GACZ,YAAY,GACZ,eAAe,GACf,kBAAkB,GAClB,cAAc,GACd,YAAY,GACZ,gBAAgB,CAAA;AAEpB,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,iBAAiB,CAAA;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB;AA6BD,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,YAAY,CAAoB;IACxC,OAAO,CAAC,aAAa,CAAmC;IACxD,OAAO,CAAC,iBAAiB,CAAyB;IAClD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,UAAU,CAAI;IACtB,OAAO,CAAC,cAAc,CAAI;IAC1B,OAAO,CAAC,aAAa,CAAI;IACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAS;IAE5C,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,oBAAoB,CAA4B;IACxD,OAAO,CAAC,iBAAiB,CAAoC;IAC7D,OAAO,CAAC,oBAAoB,CAAuC;IACnE,OAAO,CAAC,kBAAkB,CAAoC;IAC9D,OAAO,CAAC,qBAAqB,CAAuC;IACpE,OAAO,CAAC,kBAAkB,CAAoC;IAC9D,OAAO,CAAC,mBAAmB,CAAoC;IAC/D,OAAO,CAAC,aAAa,CAAoB;IACzC,OAAO,CAAC,gBAAgB,
|
|
1
|
+
{"version":3,"file":"frustration.d.ts","sourceRoot":"","sources":["../../src/context/frustration.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,iBAAiB,GACzB,YAAY,GACZ,YAAY,GACZ,eAAe,GACf,kBAAkB,GAClB,cAAc,GACd,YAAY,GACZ,gBAAgB,CAAA;AAEpB,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,iBAAiB,CAAA;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB;AA6BD,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,YAAY,CAAoB;IACxC,OAAO,CAAC,aAAa,CAAmC;IACxD,OAAO,CAAC,iBAAiB,CAAyB;IAClD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,UAAU,CAAI;IACtB,OAAO,CAAC,cAAc,CAAI;IAC1B,OAAO,CAAC,aAAa,CAAI;IACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAS;IAE5C,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,oBAAoB,CAA4B;IACxD,OAAO,CAAC,iBAAiB,CAAoC;IAC7D,OAAO,CAAC,oBAAoB,CAAuC;IACnE,OAAO,CAAC,kBAAkB,CAAoC;IAC9D,OAAO,CAAC,qBAAqB,CAAuC;IACpE,OAAO,CAAC,kBAAkB,CAAoC;IAC9D,OAAO,CAAC,mBAAmB,CAAoC;IAC/D,OAAO,CAAC,aAAa,CAAoB;IACzC,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,gBAAgB,CAAI;IAC5B,OAAO,CAAC,cAAc,CAAK;gBAEf,aAAa,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI;IAK5D,KAAK,IAAI,IAAI;IAab,IAAI,IAAI,IAAI;IAeZ,OAAO,CAAC,uBAAuB;IAsB/B,OAAO,CAAC,sBAAsB;IAoB9B,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,gBAAgB;IAWxB,OAAO,CAAC,WAAW;IAuCnB,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,cAAc;IAmCtB,OAAO,CAAC,iBAAiB;IAqBzB,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,gBAAgB;IAcxB,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,WAAW;IAOnB,OAAO,CAAC,gBAAgB;CAIzB"}
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
<input class="mtb-clarify-input" type="text" placeholder="${L(t.clarify.placeholder)}" />
|
|
81
81
|
<button class="mtb-clarify-send" disabled>${L(t.clarify.send)}</button>
|
|
82
82
|
</div>
|
|
83
|
-
`}bindEvents(t){this.el.querySelector(".mtb-clarify-skip").addEventListener("click",()=>{this.stopPolling(),this.onDone()}),this.inputEl.addEventListener("input",()=>{const e=this.inputEl.value.trim().length>0;this.sendBtn.disabled=!e||this.sending}),this.inputEl.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),this.sendMessage(t))}),this.sendBtn.addEventListener("click",()=>this.sendMessage(t))}async startConversation(){this.showThinking();try{const t=await this.apiClient.startClarification(this.feedbackId);if(this.destroyed)return;this.renderMessages(t.messages),t.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}}async sendMessage(t){const e=this.inputEl.value.trim();if(!(!e||this.sending)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.stopPolling(),this.appendMessage({role:"user",content:e}),this.inputEl.value="",this.showThinking();try{const s=await this.apiClient.startClarification(this.feedbackId,e);if(this.destroyed)return;this.renderMessages(s.messages),s.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}finally{this.sending=!1,this.inputEl.disabled=!1,this.sendBtn.disabled=this.inputEl.value.trim().length===0,this.inputEl.focus()}}}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>this.poll(),Tt)}stopPolling(){this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null)}async poll(){try{const t=await this.apiClient.getClarification(this.feedbackId);if(this.destroyed)return;this.renderMessages(t.messages),t.done&&(this.stopPolling(),this.handleDone())}catch{if(this.destroyed)return;this.stopPolling()}}handleDone(){this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.doneTimer=setTimeout(()=>{this.destroyed||this.onDone()},Lt)}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}destroy(){this.destroyed=!0,this.stopPolling(),this.doneTimer!==null&&(clearTimeout(this.doneTimer),this.doneTimer=null),this.el.remove()}}function L(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const Pt=5e3;class
|
|
83
|
+
`}bindEvents(t){this.el.querySelector(".mtb-clarify-skip").addEventListener("click",()=>{this.stopPolling(),this.onDone()}),this.inputEl.addEventListener("input",()=>{const e=this.inputEl.value.trim().length>0;this.sendBtn.disabled=!e||this.sending}),this.inputEl.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),this.sendMessage(t))}),this.sendBtn.addEventListener("click",()=>this.sendMessage(t))}async startConversation(){this.showThinking();try{const t=await this.apiClient.startClarification(this.feedbackId);if(this.destroyed)return;this.renderMessages(t.messages),t.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}}async sendMessage(t){const e=this.inputEl.value.trim();if(!(!e||this.sending)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.stopPolling(),this.appendMessage({role:"user",content:e}),this.inputEl.value="",this.showThinking();try{const s=await this.apiClient.startClarification(this.feedbackId,e);if(this.destroyed)return;this.renderMessages(s.messages),s.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}finally{this.sending=!1,this.inputEl.disabled=!1,this.sendBtn.disabled=this.inputEl.value.trim().length===0,this.inputEl.focus()}}}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>this.poll(),Tt)}stopPolling(){this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null)}async poll(){try{const t=await this.apiClient.getClarification(this.feedbackId);if(this.destroyed)return;this.renderMessages(t.messages),t.done&&(this.stopPolling(),this.handleDone())}catch{if(this.destroyed)return;this.stopPolling()}}handleDone(){this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.doneTimer=setTimeout(()=>{this.destroyed||this.onDone()},Lt)}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}destroy(){this.destroyed=!0,this.stopPolling(),this.doneTimer!==null&&(clearTimeout(this.doneTimer),this.doneTimer=null),this.el.remove()}}function L(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const Pt=5e3;class Dt{constructor(t,e,s,r){this.el=t.el("div","mtb-success"),this.el.style.right="20px",this.el.style.bottom="20px";const n=r?`<button class="mtb-view-feedback-link">${e.success.view_feedback}</button>`:"";this.el.innerHTML=`
|
|
84
84
|
<div class="mtb-success-icon">
|
|
85
85
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="${x}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
86
86
|
<polyline points="20 6 9 17 4 12"/>
|
|
@@ -90,10 +90,10 @@
|
|
|
90
90
|
<div class="mtb-success-msg">${e.success.message}</div>
|
|
91
91
|
${n}
|
|
92
92
|
<button class="mtb-close-link">${e.success.close}</button>
|
|
93
|
-
`,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",s),r&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",r),setTimeout(()=>s(),Pt)}destroy(){this.el.remove()}}function Dt(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),s=e.createElement("base"),r=e.createElement("a");return e.head.appendChild(s),e.body.appendChild(r),t&&(s.href=t),r.href=i,r.href}const _t=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function p(i){const t=[];for(let e=0,s=i.length;e<s;e++)t.push(i[e]);return t}let b=null;function Y(i={}){return b||(i.includeStyleProperties?(b=i.includeStyleProperties,b):(b=p(window.getComputedStyle(document.documentElement)),b))}function S(i,t){const s=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return s?parseFloat(s.replace("px","")):0}function Ht(i){const t=S(i,"border-left-width"),e=S(i,"border-right-width");return i.clientWidth+t+e}function $t(i){const t=S(i,"border-top-width"),e=S(i,"border-bottom-width");return i.clientHeight+t+e}function X(i,t={}){const e=t.width||Ht(i),s=t.height||$t(i);return{width:e,height:s}}function It(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const d=16384;function Ot(i){(i.width>d||i.height>d)&&(i.width>d&&i.height>d?i.width>i.height?(i.height*=d/i.width,i.width=d):(i.width*=d/i.height,i.height=d):i.width>d?(i.height*=d/i.width,i.width=d):(i.width*=d/i.height,i.height=d))}function C(i){return new Promise((t,e)=>{const s=new Image;s.onload=()=>{s.decode().then(()=>{requestAnimationFrame(()=>t(s))})},s.onerror=e,s.crossOrigin="anonymous",s.decoding="async",s.src=i})}async function Ft(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function jt(i,t,e){const s="http://www.w3.org/2000/svg",r=document.createElementNS(s,"svg"),n=document.createElementNS(s,"foreignObject");return r.setAttribute("width",`${t}`),r.setAttribute("height",`${e}`),r.setAttribute("viewBox",`0 0 ${t} ${e}`),n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("x","0"),n.setAttribute("y","0"),n.setAttribute("externalResourcesRequired","true"),r.appendChild(n),n.appendChild(i),Ft(r)}const h=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||h(e,t)};function Ut(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function zt(i,t){return Y(t).map(e=>{const s=i.getPropertyValue(e),r=i.getPropertyPriority(e);return`${e}: ${s}${r?" !important":""};`}).join(" ")}function Bt(i,t,e,s){const r=`.${i}:${t}`,n=e.cssText?Ut(e):zt(e,s);return document.createTextNode(`${r}{${n}}`)}function O(i,t,e,s){const r=window.getComputedStyle(i,e),n=r.getPropertyValue("content");if(n===""||n==="none")return;const o=_t();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(Bt(o,e,r,s)),t.appendChild(a)}function qt(i,t,e){O(i,t,":before",e),O(i,t,":after",e)}const F="application/font-woff",j="image/jpeg",Wt={woff:F,woff2:F,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:j,jpeg:j,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Nt(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function D(i){const t=Nt(i).toLowerCase();return Wt[t]||""}function Vt(i){return i.split(/,/)[1]}function P(i){return i.search(/^(data:)/)!==-1}function Yt(i,t){return`data:${t};base64,${i}`}async function G(i,t,e){const s=await fetch(i,t);if(s.status===404)throw new Error(`Resource "${s.url}" not found`);const r=await s.blob();return new Promise((n,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{n(e({res:s,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(r)})}const A={};function Xt(i,t,e){let s=i.replace(/\?.*/,"");return e&&(s=i),/ttf|otf|eot|woff2?/i.test(s)&&(s=s.replace(/.*\//,"")),t?`[${t}]${s}`:s}async function _(i,t,e){const s=Xt(i,t,e.includeQueryParams);if(A[s]!=null)return A[s];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let r;try{const n=await G(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),Vt(a)));r=Yt(n,t)}catch(n){r=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;n&&(o=typeof n=="string"?n:n.message),o&&console.warn(o)}return A[s]=r,r}async function Gt(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):C(t)}async function Kt(i,t){if(i.currentSrc){const n=document.createElement("canvas"),o=n.getContext("2d");n.width=i.clientWidth,n.height=i.clientHeight,o?.drawImage(i,0,0,n.width,n.height);const a=n.toDataURL();return C(a)}const e=i.poster,s=D(e),r=await _(e,s,t);return C(r)}async function Jt(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await M(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function Qt(i,t){return h(i,HTMLCanvasElement)?Gt(i):h(i,HTMLVideoElement)?Kt(i,t):h(i,HTMLIFrameElement)?Jt(i,t):i.cloneNode(K(i))}const Zt=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",K=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function te(i,t,e){var s,r;if(K(t))return t;let n=[];return Zt(i)&&i.assignedNodes?n=p(i.assignedNodes()):h(i,HTMLIFrameElement)&&(!((s=i.contentDocument)===null||s===void 0)&&s.body)?n=p(i.contentDocument.body.childNodes):n=p(((r=i.shadowRoot)!==null&&r!==void 0?r:i).childNodes),n.length===0||h(i,HTMLVideoElement)||await n.reduce((o,a)=>o.then(()=>M(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function ee(i,t,e){const s=t.style;if(!s)return;const r=window.getComputedStyle(i);r.cssText?(s.cssText=r.cssText,s.transformOrigin=r.transformOrigin):Y(e).forEach(n=>{let o=r.getPropertyValue(n);n==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),h(i,HTMLIFrameElement)&&n==="display"&&o==="inline"&&(o="block"),n==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),s.setProperty(n,o,r.getPropertyPriority(n))})}function ie(i,t){h(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),h(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function se(i,t){if(h(i,HTMLSelectElement)){const e=t,s=Array.from(e.children).find(r=>i.value===r.getAttribute("value"));s&&s.setAttribute("selected","")}}function re(i,t,e){return h(t,Element)&&(ee(i,t,e),qt(i,t,e),ie(i,t),se(i,t)),t}async function ne(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const s={};for(let n=0;n<e.length;n++){const a=e[n].getAttribute("xlink:href");if(a){const l=i.querySelector(a),c=document.querySelector(a);!l&&c&&!s[a]&&(s[a]=await M(c,t,!0))}}const r=Object.values(s);if(r.length){const n="http://www.w3.org/1999/xhtml",o=document.createElementNS(n,"svg");o.setAttribute("xmlns",n),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(n,"defs");o.appendChild(a);for(let l=0;l<r.length;l++)a.appendChild(r[l]);i.appendChild(o)}return i}async function M(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(s=>Qt(s,t)).then(s=>te(i,s,t)).then(s=>re(i,s,t)).then(s=>ne(s,t))}const J=/url\((['"]?)([^'"]+?)\1\)/g,oe=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ae=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function le(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function ce(i){const t=[];return i.replace(J,(e,s,r)=>(t.push(r),e)),t.filter(e=>!P(e))}async function he(i,t,e,s,r){try{const n=e?Dt(t,e):t,o=D(t);let a;return r||(a=await _(n,o,s)),i.replace(le(t),`$1${a}$3`)}catch{}return i}function de(i,{preferredFontFormat:t}){return t?i.replace(ae,e=>{for(;;){const[s,,r]=oe.exec(e)||[];if(!r)return"";if(r===t)return`src: ${s};`}}):i}function Q(i){return i.search(J)!==-1}async function Z(i,t,e){if(!Q(i))return i;const s=de(i,e);return ce(s).reduce((n,o)=>n.then(a=>he(a,o,t,e)),Promise.resolve(s))}async function g(i,t,e){var s;const r=(s=t.style)===null||s===void 0?void 0:s.getPropertyValue(i);if(r){const n=await Z(r,null,e);return t.style.setProperty(i,n,t.style.getPropertyPriority(i)),!0}return!1}async function ue(i,t){await g("background",i,t)||await g("background-image",i,t),await g("mask",i,t)||await g("-webkit-mask",i,t)||await g("mask-image",i,t)||await g("-webkit-mask-image",i,t)}async function pe(i,t){const e=h(i,HTMLImageElement);if(!(e&&!P(i.src))&&!(h(i,SVGImageElement)&&!P(i.href.baseVal)))return;const s=e?i.src:i.href.baseVal,r=await _(s,D(s),t);await new Promise((n,o)=>{i.onload=n,i.onerror=t.onImageErrorHandler?(...l)=>{try{n(t.onImageErrorHandler(...l))}catch(c){o(c)}}:o;const a=i;a.decode&&(a.decode=n),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=r):i.href.baseVal=r})}async function fe(i,t){const s=p(i.childNodes).map(r=>tt(r,t));await Promise.all(s).then(()=>i)}async function tt(i,t){h(i,Element)&&(await ue(i,t),await pe(i,t),await fe(i,t))}function me(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const s=t.style;return s!=null&&Object.keys(s).forEach(r=>{e[r]=s[r]}),i}const U={};async function z(i){let t=U[i];if(t!=null)return t;const s=await(await fetch(i)).text();return t={url:i,cssText:s},U[i]=t,t}async function B(i,t){let e=i.cssText;const s=/url\(["']?([^"')]+)["']?\)/g,n=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(s,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),G(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(n).then(()=>e)}function q(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let s=i.replace(e,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=r.exec(s);if(l===null)break;t.push(l[0])}s=s.replace(r,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=n.exec(s);if(l===null){if(l=a.exec(s),l===null)break;n.lastIndex=a.lastIndex}else a.lastIndex=n.lastIndex;t.push(l[0])}return t}async function be(i,t){const e=[],s=[];return i.forEach(r=>{if("cssRules"in r)try{p(r.cssRules||[]).forEach((n,o)=>{if(n.type===CSSRule.IMPORT_RULE){let a=o+1;const l=n.href,c=z(l).then(u=>B(u,t)).then(u=>q(u).forEach(T=>{try{r.insertRule(T,T.startsWith("@import")?a+=1:r.cssRules.length)}catch(rt){console.error("Error inserting rule from remote css",{rule:T,error:rt})}})).catch(u=>{console.error("Error loading remote css",u.toString())});s.push(c)}})}catch(n){const o=i.find(a=>a.href==null)||document.styleSheets[0];r.href!=null&&s.push(z(r.href).then(a=>B(a,t)).then(a=>q(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",n)}}),Promise.all(s).then(()=>(i.forEach(r=>{if("cssRules"in r)try{p(r.cssRules||[]).forEach(n=>{e.push(n)})}catch(n){console.error(`Error while reading CSS rules from ${r.href}`,n)}}),e))}function ge(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>Q(t.style.getPropertyValue("src")))}async function ye(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=p(i.ownerDocument.styleSheets),s=await be(e,t);return ge(s)}function et(i){return i.trim().replace(/["']/g,"")}function xe(i){const t=new Set;function e(s){(s.style.fontFamily||getComputedStyle(s).fontFamily).split(",").forEach(n=>{t.add(et(n))}),Array.from(s.children).forEach(n=>{n instanceof HTMLElement&&e(n)})}return e(i),t}async function we(i,t){const e=await ye(i,t),s=xe(i);return(await Promise.all(e.filter(n=>s.has(et(n.style.fontFamily))).map(n=>{const o=n.parentStyleSheet?n.parentStyleSheet.href:null;return Z(n.cssText,o,t)}))).join(`
|
|
94
|
-
`)}async function ke(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await we(i,t);if(e){const s=document.createElement("style"),r=document.createTextNode(e);s.appendChild(r),i.firstChild?i.insertBefore(s,i.firstChild):i.appendChild(s)}}async function ve(i,t={}){const{width:e,height:s}=X(i,t),r=await M(i,t,!0);return await ke(r,t),await tt(r,t),me(r,t),await jt(r,e,s)}async function Ee(i,t={}){const{width:e,height:s}=X(i,t),r=await ve(i,t),n=await C(r),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||It(),c=t.canvasWidth||e,u=t.canvasHeight||s;return o.width=c*l,o.height=u*l,t.skipAutoScale||Ot(o),o.style.width=`${c}`,o.style.height=`${u}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(n,0,0,o.width,o.height),o}async function Se(i,t={}){return(await Ee(i,t)).toDataURL()}async function Ce(i=[]){const t=Me(i);try{const e=await Se(document.body,{cacheBust:!0,skipAutoScale:!1,filter:s=>!(s instanceof HTMLElement&&s.id==="mtb-widget-host")});return Ae(e)}catch{return null}finally{t?.remove()}}function Me(i){if(i.length===0)return null;const t=document.createElement("div");t.setAttribute("data-mtb-capture-annotations","true"),t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;inset:0;pointer-events:none;z-index:2147483645;";for(const[e,s]of i.entries())s.type==="pin"?t.appendChild(Te(s,e+1)):s.type==="draw"&&s.drawPath&&t.appendChild(Le(s.drawPath));return document.body.appendChild(t),t}function Te(i,t){const e=document.createElement("div");return e.textContent=String(t),e.style.cssText=["position:fixed",`left:${i.x}px`,`top:${i.y}px`,"width:22px","height:22px","border-radius:50% 50% 50% 2px","background:#059669","border:2px solid #fff","display:flex","align-items:center","justify-content:center",'font:700 10px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"color:#fff","box-shadow:0 2px 8px rgba(5,150,105,0.45)","transform:translate(-50%,-50%)"].join(";"),e}function Le(i){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","100%"),t.setAttribute("height","100%"),t.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),t.style.cssText="position:fixed;inset:0;width:100%;height:100%;overflow:visible;";const e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d",i),e.setAttribute("fill","none"),e.setAttribute("stroke","#059669"),e.setAttribute("stroke-width","3.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("filter","drop-shadow(0 1px 2px rgba(5,150,105,0.35))"),t.appendChild(e),t}function Ae(i){const[t,e]=i.split(","),s=t.match(/:(.*?);/)?.[1]??"image/png",r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return new Blob([n],{type:s})}class Pe{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,s,r,n)=>(this.emit({message:String(t),source:e,line:s,col:r,error:n}),this.originalOnError?this.originalOnError.call(window,t,e,s,r,n):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason);this.emit({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 it=new Pe,Re=20;class De{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=it.subscribe(t=>this.record(t)))}record(t){const e=t.line!=null?` (${t.line}:${t.col??0})`:"";this.addError(`${t.message}${e}`)}addError(t){this.errors.length>=Re||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const _e=3,He=1e3,$e=3,Ie=5e3,Oe=500,Fe=500,je=300,Ue=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),ze=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),W=["404","500","not found","page not found","server error","internal server error"],v=class v{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.errorCount=0,this.deadClickCount=0,this.cooldownUntil=0,this.navTimestamps=[],this.boundPopstateHandler=null,this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.errorPageUrls=new Set,this.pendingObservers=[],this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=it.subscribe(t=>{this.errorCount++}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){if(this.active){this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear();for(const t of this.pendingObservers)t.disconnect();this.pendingObservers=[]}}startNavigationTracking(){this.boundPopstateHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.boundPopstateHandler),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history);const t=this.originalPushState,e=this.originalReplaceState,s=()=>this.handleNavigation();this.installedPushState=function(r,n,o){t(r,n,o),s()},this.installedReplaceState=function(r,n,o){e(r,n,o),s()},history.pushState=this.installedPushState,history.replaceState=this.installedReplaceState}stopNavigationTracking(){this.boundPopstateHandler&&(window.removeEventListener("popstate",this.boundPopstateHandler),this.boundPopstateHandler=null),this.originalPushState&&history.pushState===this.installedPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&history.replaceState===this.installedReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.navTimestamps=[]}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null)}handleClick(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const s=Date.now();this.clickHistory.push({target:e,time:s});const r=s-He;if(this.clickHistory=this.clickHistory.filter(o=>o.time>r),this.clickHistory.filter(o=>o.target===e).length>=_e){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:y(e),timestamp:s});return}this.isInteractive(e)||(this.deadClickCount++,this.deadClickCount>=3&&this.errorCount>0&&(this.deadClickCount=0,this.errorCount=0,this.emitIfReady({signal:"dead_click",target:y(e),timestamp:s}))),this.checkDeadClickDom(e,s)}handleNavigation(){const t=Date.now();this.navTimestamps.push(t);const e=t-Ie;this.navTimestamps=this.navTimestamps.filter(s=>s>e),this.navTimestamps.length>=$e&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:t})),setTimeout(()=>{this.active&&this.checkErrorPage()},je)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(this.isWidgetElement(e)||setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.emitIfReady({signal:"form_failure",target:y(e),timestamp:Date.now()})},Oe))}handleFormInvalid(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const s=e.closest("form");this.emitIfReady({signal:"form_failure",target:y(s||e),timestamp:Date.now()})}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(W.some(r=>e.includes(r))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const s=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const r of s){const n=r.textContent??"";if(n.length<200&&W.some(o=>n.toLowerCase().includes(o))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:n.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){if(!this.looksInteractive(t))return;let s=!1;const r=new MutationObserver(()=>{s=!0});r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.pendingObservers.push(r),setTimeout(()=>{r.disconnect();const n=this.pendingObservers.indexOf(r);n>=0&&this.pendingObservers.splice(n,1),!s&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:y(t),timestamp:e})},Fe)}looksInteractive(t){if(window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const s of t.classList){const r=s.toLowerCase();if(r.includes("btn")||r.includes("button"))return!0}return!1}isInteractive(t){if(Ue.has(t.tagName))return!0;const e=t.getAttribute("role");return!!(e&&ze.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.contentEditable==="true"||window.getComputedStyle(t).cursor==="pointer"||t.closest('a, button, [role="button"], [role="link"], label'))}isWidgetElement(t){const e=document.getElementById("mtb-widget-host");return e?e===t||e.contains(t):!1}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+v.COOLDOWN_MS,this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+v.COOLDOWN_MS,this.onFrustration(t)}};v.COOLDOWN_MS=6e4;let R=v;function y(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",s=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",r=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${s}>${r?` "${r}"`:""}`}function Be(){return{page_url:window.location.href,user_agent:navigator.userAgent,browser:qe(),os:We(),screen_width:window.screen.width,screen_height:window.screen.height}}function qe(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function We(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}const Ne="https://makethisbetter.dev/api/v1";class Ve{constructor(t,e,s=1e3,r,n){this.projectKey=t,this.apiUrl=(e??Ne).replace(/\/$/,""),this.retryDelayMs=s,this.userToken=r,this.userTokenFn=n}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async authHeaders(t){const e={"X-Project-Key":this.projectKey},s=await this.resolveUserToken();return s&&(e["X-User-Token"]=s),t&&(e["Content-Type"]=t),e}async submitFeedback(t,e){const s=new FormData;if(s.append("feedback[description]",t.description),s.append("feedback[page_url]",t.page_url),s.append("feedback[user_agent]",t.user_agent),s.append("feedback[browser]",t.browser),s.append("feedback[os]",t.os),s.append("feedback[screen_width]",String(t.screen_width)),s.append("feedback[screen_height]",String(t.screen_height)),s.append("feedback[console_errors]",JSON.stringify(t.console_errors)),s.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&s.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&s.append("feedback[user_id]",t.user_id),t.user_email&&s.append("feedback[user_email]",t.user_email),t.user_name&&s.append("feedback[user_name]",t.user_name),t.recording_events&&t.recording_events.length>0){const o=JSON.stringify(t.recording_events),a=new Blob([o],{type:"application/json"});s.append("feedback[recording]",a,"recording.json"),s.append("feedback[recording_duration]",String(t.recording_duration??0))}e&&s.append("feedback[screenshot]",e,"screenshot.png");const r=await this.authHeaders();return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks`,{method:"POST",headers:r,body:s})).json()}async startClarification(t,e){const s={};e&&(s.message=e);const r=await this.authHeaders("application/json");return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:r,body:JSON.stringify(s)})).json()}async getClarification(t){const e=await this.authHeaders();return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"GET",headers:e})).json()}async fetchWithRetry(t,e,s=1){let r;try{r=await fetch(t,e)}catch(n){if(s>0)return await N(this.retryDelayMs),this.fetchWithRetry(t,e,s-1);throw n}if(r.ok)return r;if(r.status>=500&&s>0)return await N(this.retryDelayMs),this.fetchWithRetry(t,e,s-1);throw new Error(`HTTP ${r.status}`)}}function N(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}function Ye(i,t,e,s,r,n){return{description:i,...t,console_errors:e,annotations:s?[s]:[],target_element:s?.targetSelector?{selector:s.targetSelector,text:s.targetText??"",name:s.targetName??""}:void 0,user_id:r?.id,user_email:r?.email,user_name:r?.name,recording_events:n?.events,recording_duration:n?.duration}}const Xe={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click any element to annotate · drag to draw",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",cancel:"Cancel",quickOptions:[{emoji:"🐛",label:"Something is broken"},{emoji:"💡",label:"I wish this worked differently"},{emoji:"🤔",label:"I don't understand this"},{emoji:"✨",label:"I have an idea"}]},success:{title:"Thanks!",message:"Your feedback has been received.",view_feedback:"View my feedback",close:"Close"},error:{submit:"Failed to submit. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached"},clarify:{thinking:"Thinking...",placeholder:"Type your response...",send:"Send",skip:"Skip"}},Ge={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击任意元素进行标注 · 拖拽可自由绘制",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",quickOptions:[{emoji:"🐛",label:"这里有问题"},{emoji:"💡",label:"我希望它能更好用"},{emoji:"🤔",label:"我看不懂这里"},{emoji:"✨",label:"我有个想法"}]},success:{title:"感谢!",message:"您的反馈已收到。",view_feedback:"查看我的反馈",close:"关闭"},error:{submit:"提交失败,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最大录制时长"},clarify:{thinking:"思考中...",placeholder:"输入你的回复...",send:"发送",skip:"跳过"}},Ke={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"要素をクリックして注釈 · ドラッグで描画",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"もっと使いやすくしてほしい"},{emoji:"🤔",label:"ここがわかりにくい"},{emoji:"✨",label:"アイデアがあります"}]},success:{title:"ありがとうございます!",message:"フィードバックを受け付けました。",view_feedback:"フィードバックを確認",close:"閉じる"},error:{submit:"送信に失敗しました。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大録画時間に達しました"},clarify:{thinking:"考え中...",placeholder:"回答を入力...",send:"送信",skip:"スキップ"}},Je={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"요소를 클릭하여 주석 · 드래그하여 그리기",hintRecord:"화면을 녹화 중입니다",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",quickOptions:[{emoji:"🐛",label:"오류가 있어요"},{emoji:"💡",label:"이 기능을 개선해 주세요"},{emoji:"🤔",label:"이 부분을 모르겠어요"},{emoji:"✨",label:"아이디어가 있어요"}]},success:{title:"감사합니다!",message:"피드백이 접수되었습니다.",view_feedback:"내 피드백 보기",close:"닫기"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다"},clarify:{thinking:"생각 중...",placeholder:"답변을 입력하세요...",send:"보내기",skip:"건너뛰기"}},Qe={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Haz clic en cualquier elemento para anotar · arrastra para dibujar",hintRecord:"Grabando tu pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",cancel:"Cancelar",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Me gustaría que funcionara diferente"},{emoji:"🤔",label:"No entiendo esto"},{emoji:"✨",label:"Tengo una idea"}]},success:{title:"¡Gracias!",message:"Tu comentario ha sido recibido.",view_feedback:"Ver mis comentarios",close:"Cerrar"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Se alcanzó el tiempo máximo de grabación"},clarify:{thinking:"Pensando...",placeholder:"Escribe tu respuesta...",send:"Enviar",skip:"Omitir"}},Ze={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquez sur un élément pour l'annoter · glissez pour dessiner",hintRecord:"Enregistrement de l'écran en cours",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",cancel:"Annuler",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'aimerais que cela fonctionne autrement"},{emoji:"🤔",label:"Je ne comprends pas ceci"},{emoji:"✨",label:"J'ai une idée"}]},success:{title:"Merci !",message:"Votre avis a bien été reçu.",view_feedback:"Voir mes avis",close:"Fermer"},error:{submit:"Échec de l'envoi. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte"},clarify:{thinking:"Réflexion...",placeholder:"Tapez votre réponse...",send:"Envoyer",skip:"Passer"}},ti={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken Sie auf ein Element zum Kommentieren · ziehen Sie zum Zeichnen",hintRecord:"Bildschirmaufnahme läuft",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",cancel:"Abbrechen",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich wünsche mir das anders"},{emoji:"🤔",label:"Das verstehe ich nicht"},{emoji:"✨",label:"Ich habe eine Idee"}]},success:{title:"Vielen Dank!",message:"Ihr Feedback wurde empfangen.",view_feedback:"Mein Feedback ansehen",close:"Schließen"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmezeit erreicht"},clarify:{thinking:"Einen Moment...",placeholder:"Antwort eingeben...",send:"Senden",skip:"Überspringen"}},k={en:Xe,"zh-CN":Ge,ja:Ke,ko:Je,es:Qe,fr:Ze,de:ti};function ei(i){if(k[i])return k[i];const t=i.split("-")[0];return k[t]?k[t]:k.en}const ii=60,si="https://cdn.jsdelivr.net/npm/rrweb@2/dist/rrweb.min.js";let E=null;function ri(){return E||(E=ni().catch(()=>oi()),E)}async function ni(){return(await import("rrweb")).record}function oi(){return new Promise((i,t)=>{const e=globalThis;if(e.rrweb?.record){i(e.rrweb.record);return}const s=document.createElement("script");s.src=si,s.onload=()=>{const r=globalThis;r.rrweb?.record?i(r.rrweb.record):t(new Error("rrweb global not found after script load"))},s.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(s)})}class ai{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await ri();this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{this.stopped||this.events.push(e)}}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},ii*1e3)}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.round((Date.now()-this.startedAt)/1e3)}destroy(){this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const s=this.shadow.el("div","mtb-click-ripple");s.style.left=`${t}px`,s.style.top=`${e}px`,this.shadow.append(s),s.addEventListener("animationend",()=>s.remove())}}class li{constructor(t,e,s,r){this.intervalId=null,this.getDuration=s,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
|
|
93
|
+
`,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",s),r&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",r),setTimeout(()=>s(),Pt)}destroy(){this.el.remove()}}function Rt(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),s=e.createElement("base"),r=e.createElement("a");return e.head.appendChild(s),e.body.appendChild(r),t&&(s.href=t),r.href=i,r.href}const _t=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function p(i){const t=[];for(let e=0,s=i.length;e<s;e++)t.push(i[e]);return t}let b=null;function Y(i={}){return b||(i.includeStyleProperties?(b=i.includeStyleProperties,b):(b=p(window.getComputedStyle(document.documentElement)),b))}function S(i,t){const s=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return s?parseFloat(s.replace("px","")):0}function Ht(i){const t=S(i,"border-left-width"),e=S(i,"border-right-width");return i.clientWidth+t+e}function $t(i){const t=S(i,"border-top-width"),e=S(i,"border-bottom-width");return i.clientHeight+t+e}function X(i,t={}){const e=t.width||Ht(i),s=t.height||$t(i);return{width:e,height:s}}function It(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const d=16384;function Ot(i){(i.width>d||i.height>d)&&(i.width>d&&i.height>d?i.width>i.height?(i.height*=d/i.width,i.width=d):(i.width*=d/i.height,i.height=d):i.width>d?(i.height*=d/i.width,i.width=d):(i.width*=d/i.height,i.height=d))}function C(i){return new Promise((t,e)=>{const s=new Image;s.onload=()=>{s.decode().then(()=>{requestAnimationFrame(()=>t(s))})},s.onerror=e,s.crossOrigin="anonymous",s.decoding="async",s.src=i})}async function Ft(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function jt(i,t,e){const s="http://www.w3.org/2000/svg",r=document.createElementNS(s,"svg"),n=document.createElementNS(s,"foreignObject");return r.setAttribute("width",`${t}`),r.setAttribute("height",`${e}`),r.setAttribute("viewBox",`0 0 ${t} ${e}`),n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("x","0"),n.setAttribute("y","0"),n.setAttribute("externalResourcesRequired","true"),r.appendChild(n),n.appendChild(i),Ft(r)}const h=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||h(e,t)};function Ut(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function zt(i,t){return Y(t).map(e=>{const s=i.getPropertyValue(e),r=i.getPropertyPriority(e);return`${e}: ${s}${r?" !important":""};`}).join(" ")}function Bt(i,t,e,s){const r=`.${i}:${t}`,n=e.cssText?Ut(e):zt(e,s);return document.createTextNode(`${r}{${n}}`)}function O(i,t,e,s){const r=window.getComputedStyle(i,e),n=r.getPropertyValue("content");if(n===""||n==="none")return;const o=_t();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(Bt(o,e,r,s)),t.appendChild(a)}function qt(i,t,e){O(i,t,":before",e),O(i,t,":after",e)}const F="application/font-woff",j="image/jpeg",Wt={woff:F,woff2:F,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:j,jpeg:j,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Nt(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function R(i){const t=Nt(i).toLowerCase();return Wt[t]||""}function Vt(i){return i.split(/,/)[1]}function P(i){return i.search(/^(data:)/)!==-1}function Yt(i,t){return`data:${t};base64,${i}`}async function G(i,t,e){const s=await fetch(i,t);if(s.status===404)throw new Error(`Resource "${s.url}" not found`);const r=await s.blob();return new Promise((n,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{n(e({res:s,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(r)})}const A={};function Xt(i,t,e){let s=i.replace(/\?.*/,"");return e&&(s=i),/ttf|otf|eot|woff2?/i.test(s)&&(s=s.replace(/.*\//,"")),t?`[${t}]${s}`:s}async function _(i,t,e){const s=Xt(i,t,e.includeQueryParams);if(A[s]!=null)return A[s];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let r;try{const n=await G(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),Vt(a)));r=Yt(n,t)}catch(n){r=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;n&&(o=typeof n=="string"?n:n.message),o&&console.warn(o)}return A[s]=r,r}async function Gt(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):C(t)}async function Kt(i,t){if(i.currentSrc){const n=document.createElement("canvas"),o=n.getContext("2d");n.width=i.clientWidth,n.height=i.clientHeight,o?.drawImage(i,0,0,n.width,n.height);const a=n.toDataURL();return C(a)}const e=i.poster,s=R(e),r=await _(e,s,t);return C(r)}async function Jt(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await M(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function Qt(i,t){return h(i,HTMLCanvasElement)?Gt(i):h(i,HTMLVideoElement)?Kt(i,t):h(i,HTMLIFrameElement)?Jt(i,t):i.cloneNode(K(i))}const Zt=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",K=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function te(i,t,e){var s,r;if(K(t))return t;let n=[];return Zt(i)&&i.assignedNodes?n=p(i.assignedNodes()):h(i,HTMLIFrameElement)&&(!((s=i.contentDocument)===null||s===void 0)&&s.body)?n=p(i.contentDocument.body.childNodes):n=p(((r=i.shadowRoot)!==null&&r!==void 0?r:i).childNodes),n.length===0||h(i,HTMLVideoElement)||await n.reduce((o,a)=>o.then(()=>M(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function ee(i,t,e){const s=t.style;if(!s)return;const r=window.getComputedStyle(i);r.cssText?(s.cssText=r.cssText,s.transformOrigin=r.transformOrigin):Y(e).forEach(n=>{let o=r.getPropertyValue(n);n==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),h(i,HTMLIFrameElement)&&n==="display"&&o==="inline"&&(o="block"),n==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),s.setProperty(n,o,r.getPropertyPriority(n))})}function ie(i,t){h(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),h(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function se(i,t){if(h(i,HTMLSelectElement)){const e=t,s=Array.from(e.children).find(r=>i.value===r.getAttribute("value"));s&&s.setAttribute("selected","")}}function re(i,t,e){return h(t,Element)&&(ee(i,t,e),qt(i,t,e),ie(i,t),se(i,t)),t}async function ne(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const s={};for(let n=0;n<e.length;n++){const a=e[n].getAttribute("xlink:href");if(a){const l=i.querySelector(a),c=document.querySelector(a);!l&&c&&!s[a]&&(s[a]=await M(c,t,!0))}}const r=Object.values(s);if(r.length){const n="http://www.w3.org/1999/xhtml",o=document.createElementNS(n,"svg");o.setAttribute("xmlns",n),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(n,"defs");o.appendChild(a);for(let l=0;l<r.length;l++)a.appendChild(r[l]);i.appendChild(o)}return i}async function M(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(s=>Qt(s,t)).then(s=>te(i,s,t)).then(s=>re(i,s,t)).then(s=>ne(s,t))}const J=/url\((['"]?)([^'"]+?)\1\)/g,oe=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ae=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function le(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function ce(i){const t=[];return i.replace(J,(e,s,r)=>(t.push(r),e)),t.filter(e=>!P(e))}async function he(i,t,e,s,r){try{const n=e?Rt(t,e):t,o=R(t);let a;return r||(a=await _(n,o,s)),i.replace(le(t),`$1${a}$3`)}catch{}return i}function de(i,{preferredFontFormat:t}){return t?i.replace(ae,e=>{for(;;){const[s,,r]=oe.exec(e)||[];if(!r)return"";if(r===t)return`src: ${s};`}}):i}function Q(i){return i.search(J)!==-1}async function Z(i,t,e){if(!Q(i))return i;const s=de(i,e);return ce(s).reduce((n,o)=>n.then(a=>he(a,o,t,e)),Promise.resolve(s))}async function g(i,t,e){var s;const r=(s=t.style)===null||s===void 0?void 0:s.getPropertyValue(i);if(r){const n=await Z(r,null,e);return t.style.setProperty(i,n,t.style.getPropertyPriority(i)),!0}return!1}async function ue(i,t){await g("background",i,t)||await g("background-image",i,t),await g("mask",i,t)||await g("-webkit-mask",i,t)||await g("mask-image",i,t)||await g("-webkit-mask-image",i,t)}async function pe(i,t){const e=h(i,HTMLImageElement);if(!(e&&!P(i.src))&&!(h(i,SVGImageElement)&&!P(i.href.baseVal)))return;const s=e?i.src:i.href.baseVal,r=await _(s,R(s),t);await new Promise((n,o)=>{i.onload=n,i.onerror=t.onImageErrorHandler?(...l)=>{try{n(t.onImageErrorHandler(...l))}catch(c){o(c)}}:o;const a=i;a.decode&&(a.decode=n),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=r):i.href.baseVal=r})}async function fe(i,t){const s=p(i.childNodes).map(r=>tt(r,t));await Promise.all(s).then(()=>i)}async function tt(i,t){h(i,Element)&&(await ue(i,t),await pe(i,t),await fe(i,t))}function me(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const s=t.style;return s!=null&&Object.keys(s).forEach(r=>{e[r]=s[r]}),i}const U={};async function z(i){let t=U[i];if(t!=null)return t;const s=await(await fetch(i)).text();return t={url:i,cssText:s},U[i]=t,t}async function B(i,t){let e=i.cssText;const s=/url\(["']?([^"')]+)["']?\)/g,n=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(s,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),G(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(n).then(()=>e)}function q(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let s=i.replace(e,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=r.exec(s);if(l===null)break;t.push(l[0])}s=s.replace(r,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=n.exec(s);if(l===null){if(l=a.exec(s),l===null)break;n.lastIndex=a.lastIndex}else a.lastIndex=n.lastIndex;t.push(l[0])}return t}async function be(i,t){const e=[],s=[];return i.forEach(r=>{if("cssRules"in r)try{p(r.cssRules||[]).forEach((n,o)=>{if(n.type===CSSRule.IMPORT_RULE){let a=o+1;const l=n.href,c=z(l).then(u=>B(u,t)).then(u=>q(u).forEach(T=>{try{r.insertRule(T,T.startsWith("@import")?a+=1:r.cssRules.length)}catch(rt){console.error("Error inserting rule from remote css",{rule:T,error:rt})}})).catch(u=>{console.error("Error loading remote css",u.toString())});s.push(c)}})}catch(n){const o=i.find(a=>a.href==null)||document.styleSheets[0];r.href!=null&&s.push(z(r.href).then(a=>B(a,t)).then(a=>q(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",n)}}),Promise.all(s).then(()=>(i.forEach(r=>{if("cssRules"in r)try{p(r.cssRules||[]).forEach(n=>{e.push(n)})}catch(n){console.error(`Error while reading CSS rules from ${r.href}`,n)}}),e))}function ge(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>Q(t.style.getPropertyValue("src")))}async function ye(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=p(i.ownerDocument.styleSheets),s=await be(e,t);return ge(s)}function et(i){return i.trim().replace(/["']/g,"")}function xe(i){const t=new Set;function e(s){(s.style.fontFamily||getComputedStyle(s).fontFamily).split(",").forEach(n=>{t.add(et(n))}),Array.from(s.children).forEach(n=>{n instanceof HTMLElement&&e(n)})}return e(i),t}async function we(i,t){const e=await ye(i,t),s=xe(i);return(await Promise.all(e.filter(n=>s.has(et(n.style.fontFamily))).map(n=>{const o=n.parentStyleSheet?n.parentStyleSheet.href:null;return Z(n.cssText,o,t)}))).join(`
|
|
94
|
+
`)}async function ke(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await we(i,t);if(e){const s=document.createElement("style"),r=document.createTextNode(e);s.appendChild(r),i.firstChild?i.insertBefore(s,i.firstChild):i.appendChild(s)}}async function ve(i,t={}){const{width:e,height:s}=X(i,t),r=await M(i,t,!0);return await ke(r,t),await tt(r,t),me(r,t),await jt(r,e,s)}async function Ee(i,t={}){const{width:e,height:s}=X(i,t),r=await ve(i,t),n=await C(r),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||It(),c=t.canvasWidth||e,u=t.canvasHeight||s;return o.width=c*l,o.height=u*l,t.skipAutoScale||Ot(o),o.style.width=`${c}`,o.style.height=`${u}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(n,0,0,o.width,o.height),o}async function Se(i,t={}){return(await Ee(i,t)).toDataURL()}async function Ce(i=[]){const t=Me(i);try{const e=await Se(document.body,{cacheBust:!0,skipAutoScale:!1,filter:s=>!(s instanceof HTMLElement&&s.id==="mtb-widget-host")});return Ae(e)}catch{return null}finally{t?.remove()}}function Me(i){if(i.length===0)return null;const t=document.createElement("div");t.setAttribute("data-mtb-capture-annotations","true"),t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;inset:0;pointer-events:none;z-index:2147483645;";for(const[e,s]of i.entries())s.type==="pin"?t.appendChild(Te(s,e+1)):s.type==="draw"&&s.drawPath&&t.appendChild(Le(s.drawPath));return document.body.appendChild(t),t}function Te(i,t){const e=document.createElement("div");return e.textContent=String(t),e.style.cssText=["position:fixed",`left:${i.x}px`,`top:${i.y}px`,"width:22px","height:22px","border-radius:50% 50% 50% 2px","background:#059669","border:2px solid #fff","display:flex","align-items:center","justify-content:center",'font:700 10px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"color:#fff","box-shadow:0 2px 8px rgba(5,150,105,0.45)","transform:translate(-50%,-50%)"].join(";"),e}function Le(i){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","100%"),t.setAttribute("height","100%"),t.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),t.style.cssText="position:fixed;inset:0;width:100%;height:100%;overflow:visible;";const e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d",i),e.setAttribute("fill","none"),e.setAttribute("stroke","#059669"),e.setAttribute("stroke-width","3.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("filter","drop-shadow(0 1px 2px rgba(5,150,105,0.35))"),t.appendChild(e),t}function Ae(i){const[t,e]=i.split(","),s=t.match(/:(.*?);/)?.[1]??"image/png",r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return new Blob([n],{type:s})}class Pe{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,s,r,n)=>(this.emit({message:String(t),source:e,line:s,col:r,error:n}),this.originalOnError?this.originalOnError.call(window,t,e,s,r,n):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason);this.emit({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 it=new Pe,De=20;class Re{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=it.subscribe(t=>this.record(t)))}record(t){const e=t.line!=null?` (${t.line}:${t.col??0})`:"";this.addError(`${t.message}${e}`)}addError(t){this.errors.length>=De||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const _e=3,He=1e3,$e=3,Ie=5e3,Oe=500,Fe=500,je=300,Ue=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),ze=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),W=["404","500","not found","page not found","server error","internal server error"],v=class v{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.errorCount=0,this.deadClickCount=0,this.cooldownUntil=0,this.navTimestamps=[],this.boundPopstateHandler=null,this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=it.subscribe(t=>{this.errorCount++}),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.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.disconnectDomObserver())}startNavigationTracking(){this.boundPopstateHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.boundPopstateHandler),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history);const t=this.originalPushState,e=this.originalReplaceState,s=()=>this.handleNavigation();this.installedPushState=function(r,n,o){t(r,n,o),s()},this.installedReplaceState=function(r,n,o){e(r,n,o),s()},history.pushState=this.installedPushState,history.replaceState=this.installedReplaceState}stopNavigationTracking(){this.boundPopstateHandler&&(window.removeEventListener("popstate",this.boundPopstateHandler),this.boundPopstateHandler=null),this.originalPushState&&history.pushState===this.installedPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&history.replaceState===this.installedReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.navTimestamps=[]}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null)}handleClick(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const s=Date.now();this.clickHistory.push({target:e,time:s});const r=s-He;if(this.clickHistory=this.clickHistory.filter(o=>o.time>r),this.clickHistory.filter(o=>o.target===e).length>=_e){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:y(e),timestamp:s});return}this.isInteractive(e)||(this.deadClickCount++,this.deadClickCount>=3&&this.errorCount>0&&(this.deadClickCount=0,this.errorCount=0,this.emitIfReady({signal:"dead_click",target:y(e),timestamp:s}))),this.checkDeadClickDom(e,s)}handleNavigation(){const t=Date.now();this.navTimestamps.push(t);const e=t-Ie;this.navTimestamps=this.navTimestamps.filter(s=>s>e),this.navTimestamps.length>=$e&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:t})),setTimeout(()=>{this.active&&this.checkErrorPage()},je)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(this.isWidgetElement(e)||setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.emitIfReady({signal:"form_failure",target:y(e),timestamp:Date.now()})},Oe))}handleFormInvalid(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const s=e.closest("form");this.emitIfReady({signal:"form_failure",target:y(s||e),timestamp:Date.now()})}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(W.some(r=>e.includes(r))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const s=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const r of s){const n=r.textContent??"";if(n.length<200&&W.some(o=>n.toLowerCase().includes(o))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:n.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),setTimeout(()=>{this.pendingDomChecks--;const s=this.lastMutationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!s&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:y(t),timestamp:e})},Fe))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const s of t.classList){const r=s.toLowerCase();if(r.includes("btn")||r.includes("button"))return!0}return!1}isInteractive(t){if(Ue.has(t.tagName))return!0;const e=t.getAttribute("role");return!!(e&&ze.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.contentEditable==="true"||window.getComputedStyle(t).cursor==="pointer"||t.closest('a, button, [role="button"], [role="link"], label'))}isWidgetElement(t){const e=document.getElementById("mtb-widget-host");return e?e===t||e.contains(t):!1}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+v.COOLDOWN_MS,this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+v.COOLDOWN_MS,this.onFrustration(t)}};v.COOLDOWN_MS=6e4;let D=v;function y(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",s=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",r=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${s}>${r?` "${r}"`:""}`}function Be(){return{page_url:window.location.href,user_agent:navigator.userAgent,browser:qe(),os:We(),screen_width:window.screen.width,screen_height:window.screen.height}}function qe(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function We(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}const Ne="https://makethisbetter.dev/api/v1";class Ve{constructor(t,e,s=1e3,r,n){this.projectKey=t,this.apiUrl=(e??Ne).replace(/\/$/,""),this.retryDelayMs=s,this.userToken=r,this.userTokenFn=n}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async authHeaders(t){const e={"X-Project-Key":this.projectKey},s=await this.resolveUserToken();return s&&(e["X-User-Token"]=s),t&&(e["Content-Type"]=t),e}async submitFeedback(t,e){const s=new FormData;if(s.append("feedback[description]",t.description),s.append("feedback[page_url]",t.page_url),s.append("feedback[user_agent]",t.user_agent),s.append("feedback[browser]",t.browser),s.append("feedback[os]",t.os),s.append("feedback[screen_width]",String(t.screen_width)),s.append("feedback[screen_height]",String(t.screen_height)),s.append("feedback[console_errors]",JSON.stringify(t.console_errors)),s.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&s.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&s.append("feedback[user_id]",t.user_id),t.user_email&&s.append("feedback[user_email]",t.user_email),t.user_name&&s.append("feedback[user_name]",t.user_name),t.recording_events&&t.recording_events.length>0){const o=JSON.stringify(t.recording_events),a=new Blob([o],{type:"application/json"});s.append("feedback[recording]",a,"recording.json"),s.append("feedback[recording_duration]",String(t.recording_duration??0))}e&&s.append("feedback[screenshot]",e,"screenshot.png");const r=await this.authHeaders();return r["X-Idempotency-Key"]=Ye(),(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks`,{method:"POST",headers:r,body:s})).json()}async startClarification(t,e){const s={};e&&(s.message=e);const r=await this.authHeaders("application/json");return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:r,body:JSON.stringify(s)})).json()}async getClarification(t){const e=await this.authHeaders();return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"GET",headers:e})).json()}async fetchWithRetry(t,e,s=1){let r;try{r=await fetch(t,e)}catch(n){if(s>0)return await N(this.retryDelayMs),this.fetchWithRetry(t,e,s-1);throw n}if(r.ok)return r;if(r.status>=500&&s>0)return await N(this.retryDelayMs),this.fetchWithRetry(t,e,s-1);throw new Error(`HTTP ${r.status}`)}}function N(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}function Ye(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Xe(i,t,e,s,r,n){return{description:i,...t,console_errors:e,annotations:s?[s]:[],target_element:s?.targetSelector?{selector:s.targetSelector,text:s.targetText??"",name:s.targetName??""}:void 0,user_id:r?.id,user_email:r?.email,user_name:r?.name,recording_events:n?.events,recording_duration:n?.duration}}const Ge={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click any element to annotate · drag to draw",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",cancel:"Cancel",quickOptions:[{emoji:"🐛",label:"Something is broken"},{emoji:"💡",label:"I wish this worked differently"},{emoji:"🤔",label:"I don't understand this"},{emoji:"✨",label:"I have an idea"}]},success:{title:"Thanks!",message:"Your feedback has been received.",view_feedback:"View my feedback",close:"Close"},error:{submit:"Failed to submit. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached"},clarify:{thinking:"Thinking...",placeholder:"Type your response...",send:"Send",skip:"Skip"}},Ke={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击任意元素进行标注 · 拖拽可自由绘制",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",quickOptions:[{emoji:"🐛",label:"这里有问题"},{emoji:"💡",label:"我希望它能更好用"},{emoji:"🤔",label:"我看不懂这里"},{emoji:"✨",label:"我有个想法"}]},success:{title:"感谢!",message:"您的反馈已收到。",view_feedback:"查看我的反馈",close:"关闭"},error:{submit:"提交失败,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最大录制时长"},clarify:{thinking:"思考中...",placeholder:"输入你的回复...",send:"发送",skip:"跳过"}},Je={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"要素をクリックして注釈 · ドラッグで描画",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"もっと使いやすくしてほしい"},{emoji:"🤔",label:"ここがわかりにくい"},{emoji:"✨",label:"アイデアがあります"}]},success:{title:"ありがとうございます!",message:"フィードバックを受け付けました。",view_feedback:"フィードバックを確認",close:"閉じる"},error:{submit:"送信に失敗しました。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大録画時間に達しました"},clarify:{thinking:"考え中...",placeholder:"回答を入力...",send:"送信",skip:"スキップ"}},Qe={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"요소를 클릭하여 주석 · 드래그하여 그리기",hintRecord:"화면을 녹화 중입니다",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",quickOptions:[{emoji:"🐛",label:"오류가 있어요"},{emoji:"💡",label:"이 기능을 개선해 주세요"},{emoji:"🤔",label:"이 부분을 모르겠어요"},{emoji:"✨",label:"아이디어가 있어요"}]},success:{title:"감사합니다!",message:"피드백이 접수되었습니다.",view_feedback:"내 피드백 보기",close:"닫기"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다"},clarify:{thinking:"생각 중...",placeholder:"답변을 입력하세요...",send:"보내기",skip:"건너뛰기"}},Ze={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Haz clic en cualquier elemento para anotar · arrastra para dibujar",hintRecord:"Grabando tu pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",cancel:"Cancelar",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Me gustaría que funcionara diferente"},{emoji:"🤔",label:"No entiendo esto"},{emoji:"✨",label:"Tengo una idea"}]},success:{title:"¡Gracias!",message:"Tu comentario ha sido recibido.",view_feedback:"Ver mis comentarios",close:"Cerrar"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Se alcanzó el tiempo máximo de grabación"},clarify:{thinking:"Pensando...",placeholder:"Escribe tu respuesta...",send:"Enviar",skip:"Omitir"}},ti={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquez sur un élément pour l'annoter · glissez pour dessiner",hintRecord:"Enregistrement de l'écran en cours",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",cancel:"Annuler",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'aimerais que cela fonctionne autrement"},{emoji:"🤔",label:"Je ne comprends pas ceci"},{emoji:"✨",label:"J'ai une idée"}]},success:{title:"Merci !",message:"Votre avis a bien été reçu.",view_feedback:"Voir mes avis",close:"Fermer"},error:{submit:"Échec de l'envoi. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte"},clarify:{thinking:"Réflexion...",placeholder:"Tapez votre réponse...",send:"Envoyer",skip:"Passer"}},ei={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken Sie auf ein Element zum Kommentieren · ziehen Sie zum Zeichnen",hintRecord:"Bildschirmaufnahme läuft",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",cancel:"Abbrechen",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich wünsche mir das anders"},{emoji:"🤔",label:"Das verstehe ich nicht"},{emoji:"✨",label:"Ich habe eine Idee"}]},success:{title:"Vielen Dank!",message:"Ihr Feedback wurde empfangen.",view_feedback:"Mein Feedback ansehen",close:"Schließen"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmezeit erreicht"},clarify:{thinking:"Einen Moment...",placeholder:"Antwort eingeben...",send:"Senden",skip:"Überspringen"}},k={en:Ge,"zh-CN":Ke,ja:Je,ko:Qe,es:Ze,fr:ti,de:ei};function ii(i){if(k[i])return k[i];const t=i.split("-")[0];return k[t]?k[t]:k.en}const si=60,ri="https://cdn.jsdelivr.net/npm/rrweb@2.1.0/dist/rrweb.min.js",ni="sha384-6qZKf9GE/E2uhA8IdLwXsQiLN/jVx8mhA0i04rQ1aHLrs2URo3ivHlSbaccG59zt";let E=null;function oi(){return E||(E=ai().catch(()=>li()),E)}async function ai(){return(await import("rrweb")).record}function li(){return new Promise((i,t)=>{const e=globalThis;if(e.rrweb?.record){i(e.rrweb.record);return}const s=document.createElement("script");s.src=ri,s.integrity=ni,s.crossOrigin="anonymous",s.onload=()=>{const r=globalThis;r.rrweb?.record?i(r.rrweb.record):t(new Error("rrweb global not found after script load"))},s.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(s)})}class ci{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await oi();this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{this.stopped||this.events.push(e)}}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},si*1e3)}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.round((Date.now()-this.startedAt)/1e3)}destroy(){this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const s=this.shadow.el("div","mtb-click-ripple");s.style.left=`${t}px`,s.style.top=`${e}px`,this.shadow.append(s),s.addEventListener("animationend",()=>s.remove())}}class hi{constructor(t,e,s,r){this.intervalId=null,this.getDuration=s,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
|
|
95
95
|
<span class="mtb-record-dot"></span>
|
|
96
96
|
<span class="mtb-record-timer">00:00</span>
|
|
97
97
|
<button class="mtb-record-stop" type="button">${e.record.stop}</button>
|
|
98
|
-
`,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",r),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),s=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${s}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class
|
|
98
|
+
`,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",r),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),s=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${s}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class di{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,s){this.session=new ci(t,s),this.bar=new hi(t,e,()=>this.session?.getDuration()??0,s),await this.session.start()}stop(){return this.session?(this.result=this.session.stop(),this.teardownUI(),this.result):null}getRecording(){return this.result}destroy(){this.teardownUI(),this.result=null}teardownUI(){this.session?.destroy(),this.session=null,this.bar?.destroy(),this.bar=null}}class V{constructor(t){this.tab=null,this.pet=null,this.toolbar=null,this.session=null,this.popup=null,this.clarify=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.mode="idle",this.currentAnnotation=null,this.recordingManager=null,this.config=t,this.messages=ii(t.locale??"en"),this.apiClient=new Ve(t.projectKey,t.apiUrl,void 0,t.userToken,t.userTokenFn),this.consoleCollector=new Re,this.consoleCollector.start(),this.buildUI(),t.frustrationDetection!==!1&&(this.frustrationDetector=new D(()=>this.handleFrustration()),this.frustrationDetector.start())}buildUI(){this.shadow=new pt(this.config.theme??"auto"),(this.config.entryMode??"button")==="pet"?this.pet=new mt(this.shadow,this.messages,()=>this.handleTabClick()):this.tab=new ft(this.shadow,this.messages,this.config.position??"right",()=>this.handleTabClick(),this.config.tabText)}handleTabClick(){this.mode==="idle"?(this.dismissFrustrationPrompt(),this.enterAnnotationMode()):this.exitAll()}handleFrustration(){this.mode!=="idle"||this.frustrationPrompt||(this.frustrationPrompt=new gt(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.enterAnnotationMode()},onDismiss:()=>this.dismissFrustrationPrompt()}))}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}enterAnnotationMode(){this.mode="annotating",this.tab?.setActive(!0),this.pet?.setActive(!0),this.toolbar=new yt(this.shadow,this.messages,()=>this.exitAll(),t=>this.handleToolbarModeChange(t)),this.session=new $(this.shadow,this.messages,(t,e)=>{this.currentAnnotation=t,this.showPopup(t.x,t.y,e)})}handleToolbarModeChange(t){t==="record"?(this.mode="recording",this.session?.destroy(),this.session=null,this.recordingManager=new di,this.recordingManager.start(this.shadow,this.messages,()=>{this.recordingManager&&(this.recordingManager.stop(),this.showPopup(window.innerWidth/2,window.innerHeight/2,this.messages.record.timer_label))}).catch(()=>{this.mode==="recording"&&(this.toolbar?.setMode("markup"),this.handleToolbarModeChange("markup"))})):(this.recordingManager?.destroy(),this.recordingManager=null,this.session||(this.session=new $(this.shadow,this.messages,(e,s)=>{this.currentAnnotation=e,this.showPopup(e.x,e.y,s)})),this.mode="annotating")}showPopup(t,e,s){this.mode="popup",this.session?.dismissInteraction(),this.popup=new Mt(this.shadow,{targetName:s,x:t,y:e,messages:this.messages,onSubmit:r=>this.handleSubmit(r),onClose:()=>this.exitAll()})}async handleSubmit(t){if(!this.popup)return;this.popup.setLoading(!0);const e=this.currentAnnotation,s=this.recordingManager?.getRecording()??void 0,[r,n]=await Promise.all([Ce(e?[e]:[]),Promise.resolve(Be())]),o=Xe(t,n,this.consoleCollector.getErrors(),e,this.config.user,s);try{const a=await this.apiClient.submitFeedback(o,r);this.popup?.destroy(),this.popup=null,this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null,this.showClarify(a.id,a.project_id)}catch{this.popup?.setLoading(!1),this.popup?.setError(this.messages.error.submit)}}showClarify(t,e){this.mode="idle",this.tab?.setActive(!1),this.pet?.setActive(!1),this.clarify=new At(this.shadow,{feedbackId:t,apiClient:this.apiClient,messages:this.messages,onDone:()=>{this.clarify?.destroy(),this.clarify=null,this.showSuccess(e)}})}showSuccess(t){this.mode="idle",this.tab?.setActive(!1),this.pet?.setActive(!1);const s=`${this.config.apiUrl?this.config.apiUrl.replace(/\/api\/v1\/?$/,""):"https://makethisbetter.dev"}/board/projects/${t}/feedbacks`,r=!!(this.config.userToken||this.config.userTokenFn);this.success=new Dt(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},r?async()=>{const n=await this.apiClient.resolveUserToken();n&&window.open(`${s}?identity=${encodeURIComponent(n)}`,"_blank")}:void 0)}exitAll(){this.mode="idle",this.tab?.setActive(!1),this.pet?.setActive(!1),this.toolbar?.destroy(),this.toolbar=null,this.session?.destroy(),this.session=null,this.popup?.destroy(),this.popup=null,this.clarify?.destroy(),this.clarify=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){this.exitAll(),this.consoleCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.clarify?.destroy(),this.success?.destroy(),this.tab?.destroy(),this.pet?.destroy(),this.recordingManager?.destroy(),this.shadow.destroy()}}let f=null;const st={init(i){f&&(f.destroy(),f=null),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{f=new V(i)}):f=new V(i)},destroy(){f?.destroy(),f=null}};typeof window<"u"&&(window.MakeThisBetter=st);exports.MakeThisBetter=st;
|
|
99
99
|
//# sourceMappingURL=makethisbetter.cjs.js.map
|