mockforme 6.0.0 → 7.0.0

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.
@@ -1 +1 @@
1
- const e=()=>"undefined"!=typeof process&&null!=process.versions?.node,t=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},n=(e,t)=>{const n=e.split("/"),o=t.split("/");if(n.length!==o.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let o=[];function r(e){o=e}function s(){return o}function i(e,r="get"){const s=e=>e.startsWith("/")?e:`/${e}`,i=s(e);for(const a of o)if(t(a.apiMethod)===t(r)){const t=s(a.apiEndpoint);if(t===i||n(t,i)){console.log(`[MockForMe] Match Found: ${r} ${e} -> ${a.apiEndpoint}`);const t={url:e,method:a.apiMethod,_ack:a._ack||null};return a._ri_&&(t._ri_=a._ri_),t}}return null}const a="JAVASCRIPT",d="CHROME_EXTENSION",c="mfmver",l="mockforme",m="4.2.7",u="https://api.mockforme.com",p=`${u}/mockforme`,h=`${u}/gateway/3f4eae522b`;let f=null,g=null,y=null,b=[];function x({_o:e,mk:t,_mck:n,_rules:o}){f=e,g=t,y=n,b=o}function w(){return b}function v(){return`${p}/${f}/${g}`}function k(){return y}const q=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}},E=function(t,n,o){const r=e();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var n=e.split(";");try{return"application/json"===n[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();n.call(this,e,s)}else o.call(this,s.responseText,s)}function a(e,t){var n=[];for(var o in e)if(e.hasOwnProperty(o)){var r=t?t+"["+o+"]":o,s=e[o];n.push("object"==typeof s?a(s,r):encodeURIComponent(r)+"="+encodeURIComponent(s))}return n.join("&")}return r||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!r){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var e=a(t.params);if("get"==t.method.toLowerCase()&&"object"==typeof t.params){if(-1==t.url.indexOf("?"))t.url+="?";else{var n=t.url.split("?");n[1]&&n[1].split("=")[1]&&(t.url+="&")}t.url+=e}t.hasOwnProperty("async")||(t.async=!0),s.open(t.method,t.url,t.async),t.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(t.headers),s.send(e)}}}};function R({di:e,iv:t},n){var o;const r=function(e,t){const n=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%n)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),n+t);return JSON.parse(r)}function S(e,t,n,o){fetch(h,{method:"GET",headers:{[l]:e,[c]:m,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:s,_mck:i,mk:a,r:d}=e,c=R({di:t,iv:o},s);x({_o:s,mk:a,_mck:i,_rules:d}),c&&(r(c),n(c,{_o:s,mk:a,_mck:i,_rules:d}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}const _='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path><polyline points="21 3 21 8 16 8"></polyline></svg>',T='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><circle cx="12" cy="12" r="1.5"></circle><circle cx="12" cy="5" r="1.5"></circle><circle cx="12" cy="19" r="1.5"></circle></svg>',M='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',L=new class{constructor(t={}){e()||(this.token=t.token||("undefined"!=typeof localStorage?localStorage.getItem("mockforme-token"):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=t.onAuthSuccess||(()=>{}),this.mappings=t.mappings||[],this.rules=t.rules||[],this.widgetKey=t.widgetKey||null,this.mockedRequests=[],this.otherRequests=[],this.state={isOpen:"undefined"!=typeof localStorage&&"true"===localStorage.getItem("mockforme-widget-open"),activeTab:"mappings",selectedRequest:null,activeRequestTab:"response",lastError:null,searchQuery:""},"undefined"!=typeof document&&(window.addEventListener("resize",(()=>{this.bubble&&this.keepInBounds(this.bubble)})),document.addEventListener("click",(e=>{this.sharedDropdown&&this.sharedDropdown.classList.remove("show")}))))}init(){if("undefined"!=typeof document&&document.getElementById)if(this.checkVisibility())if(document.body)this.initWidget();else{const e=()=>{document.body&&this.initWidget()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e,{once:!0}):"interactive"===document.readyState||"complete"===document.readyState?setTimeout(e,0):window.addEventListener("load",e,{once:!0})}else{const e=document.getElementById("mockforme-root");e&&e.remove()}}initWidget(){document.getElementById("mockforme-root")||(this.createStyles(),this.render())}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}createStyles(){if(document.getElementById("mockforme-styles"))return;const e=document.createElement("style");e.id="mockforme-styles",e.innerHTML="\n #mockforme-root {\n font-family: 'Inter', system-ui, -apple-system, sans-serif;\n z-index: 999999;\n position: fixed;\n }\n .mfm-bubble {\n position: fixed;\n bottom: 20px;\n right: 20px;\n height: 42px;\n padding: 0px 12px;\n border-radius: 24px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n cursor: pointer;\n z-index: 999999;\n background: white;\n display: flex;\n align-items: center;\n gap: 8px;\n transition: transform 0.2s;\n border: 1px solid #eee;\n }\n .mfm-bubble:hover { transform: scale(1.05); }\n .mfm-bubble img { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; }\n \n .mfm-refresh-icon {\n width: 28px;\n height: 28px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #2563eb;\n transition: background 0.2s;\n margin-right: 10px;\n background: #f3f4f6;\n padding: 0;\n }\n .mfm-refresh-icon svg { width: 16px; height: 16px; }\n .mfm-refresh-icon:hover { }\n .mfm-refresh-icon.loading { animation: mfm-spin 1s linear infinite; }\n @keyframes mfm-spin { 100% { transform: rotate(360deg); } }\n\n .mfm-bottomsheet {\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0;\n background: white;\n border-top-left-radius: 16px;\n border-top-right-radius: 16px;\n box-shadow: 0 -4px 20px rgba(0,0,0,0.15);\n padding: 20px;\n z-index: 999999;\n height: 80vh;\n max-width: 500px;\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n transition: transform 0.3s ease-out;\n transform: translateY(100%);\n visibility: hidden;\n overflow-y: auto;\n }\n @media (max-width: 480px) {\n .mfm-bottomsheet { padding: 16px; }\n }\n .mfm-bottomsheet.open { transform: translateY(0); visibility: visible; }\n \n .mfm-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 15px;\n padding-bottom: 10px;\n border-bottom: 1px solid #eee;\n flex-shrink: 0;\n }\n .mfm-title-group { display: flex; align-items: center; gap: 10px; }\n .mfm-title { font-size: 18px; font-weight: 600; color: #111; }\n .mfm-title img { height: 30px; }\n .mfm-delete-token-btn { \n background: #fee2e2; \n color: #dc2626; \n font-size: 13px; \n padding: 4px 12px; \n border-radius: 20px; \n cursor: pointer; \n display: flex;\n align-items: center;\n gap: 6px;\n border: none;\n font-weight: 500;\n transition: background 0.2s;\n }\n .mfm-delete-token-btn:hover { background: #fecaca; }\n .mfm-header-actions { display: flex; align-items: center; gap: 10px; }\n .mfm-close { background: none; border: none; padding: 4px; cursor: pointer; color: #666; display: flex; align-items: center; justify-content: center; }\n .mfm-close:hover { color: #111; background: #f3f4f6; border-radius: 4px; }\n /* Login Form */\n .mfm-logo-container { text-align: center; padding: 20px 0; width: 100%; display: flex; justify-content: center; flex-shrink: 0; }\n .mfm-logo { width: 120px; height: auto; }\n .mfm-link { color: #2563eb; text-decoration: none; font-size: 14px; margin-top: 5px; cursor: pointer; display: inline-block; }\n .mfm-link:hover { text-decoration: underline; }\n .mfm-form { display: flex; flex-direction: column; gap: 10px; }\n .mfm-input {\n padding: 12px;\n border: 1px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n outline: none;\n transition: border-color 0.2s;\n }\n .mfm-input:focus { border-color: #2563eb; }\n .mfm-error { color: #dc2626; font-size: 13px; margin-top: -5px; }\n .mfm-btn {\n padding: 12px;\n background: #2563eb;\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.2s;\n }\n .mfm-btn:hover { background: #1d4ed8; }\n .mfm-btn:disabled { background: #9ca3af; cursor: not-allowed; }\n\n .mfm-tabs { \n display: flex; \n border-bottom: 1px solid #dee2e6; \n margin-bottom: 10px; \n flex-shrink: 0; \n gap: 2px;\n }\n .mfm-tab {\n padding: 8px 16px;\n cursor: pointer;\n color: #666;\n border: 1px solid transparent;\n border-bottom: none;\n border-top-left-radius: 6px;\n border-top-right-radius: 6px;\n font-weight: 300;\n font-size: 14px;\n margin-bottom: -1px;\n transition: all 0.2s;\n }\n .mfm-tab:hover {\n background-color: #f8f9fa;\n border-color: #e9ecef #e9ecef transparent;\n }\n .mfm-tab.active { \n color: #2563eb; \n background-color: white;\n border: 1px solid #dee2e6;\n border-bottom: 1px solid white;\n font-weight: 500;\n }\n \n .mfm-list {\n flex: 1;\n overflow-y: auto;\n min-height: 200px;\n max-height: 60vh;\n }\n .mfm-list-item {\n padding: 10px;\n border-bottom: 1px solid #f3f4f6;\n cursor: pointer;\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n justify-content: space-between;\n font-size: 14px;\n min-height: 52px;\n box-sizing: border-box;\n }\n .mfm-list-item:hover { background: #f9fafb; }\n .mfm-method { \n font-weight: bold; \n padding: 4px 8px; \n border-radius: 4px; \n margin-right: 10px;\n font-size: 12px;\n }\n .GET { background: #dbfcfe; color: #006064; }\n .POST { background: #dcfce7; color: #14532d; }\n .PUT { background: #fef9c3; color: #713f12; }\n .DELETE { background: #fee2e2; color: #7f1d1d; }\n .PATCH { background: #f3e8ff; color: #581c87; }\n .RULE { background: #f3f4f6; color: #374151; }\n\n /* Search & Actions */\n .mfm-actions-bar { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; flex-shrink: 0; }\n .mfm-search-input { flex: 1; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; outline: none; }\n .mfm-search-input:focus { border-color: #2563eb; }\n .mfm-icon-btn { background: none; border: none; cursor: pointer; color: #666; display: flex; align-items: center; justify-content: center; padding: 4px; border-radius: 4px; }\n .mfm-icon-btn:hover { color: #333; background: #f3f4f6; }\n .mfm-icon-btn.refresh { color: #2563eb; padding: 0; height: 24px; width:24px; border-radius: 50%; }\n .mfm-icon-btn.refresh.loading { animation: mfm-spin 1s linear infinite; }\n .mfm-icon-btn.delete { color: #dc2626; }\n\n .mfm-url { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .mfm-status { font-weight: bold; margin-left: 10px; }\n .status-2xx { color: #16a34a; }\n .status-non-2xx { color: #dc2626; }\n .status-aborted, .status-timeout, .status-error { color: #dc2626; font-size: 11px; font-weight: 500; }\n\n .mfm-rule-tag {\n font-size: 9px;\n padding: 2px 4px;\n border-radius: 4px;\n background: #fef3c7;\n color: #92400e;\n border: 1px solid #fde68a;\n margin-right: 6px;\n text-transform: uppercase;\n font-weight: bold;\n }\n\n .mfm-redirect-badge {\n font-size: 10px;\n color: #166534;\n background: #dcfce7;\n padding: 2px 6px;\n border-radius: 10px;\n margin-top: 2px;\n display: inline-block;\n font-weight: 500;\n border: 1px solid #bbf7d0;\n }\n\n /* Mapping UI Enhanced */\n .mfm-mapping-info { display: flex; flex-direction: column; flex: 1; overflow: hidden; }\n .mfm-rule-name { font-weight: 600; color: #1f2937; margin-bottom: 2px; display: block; overflow: hidden; text-overflow: ellipsis; }\n .mfm-condition-brief { font-size: 11px; color: #6b7280; font-family: monospace; cursor: pointer; }\n .mfm-condition-brief:hover { color: #2563eb; text-decoration: underline; }\n .mfm-mod-actions-count { \n font-size: 10px; \n background: #eff6ff; \n color: #1d4ed8; \n padding: 2px 6px; \n border-radius: 12px; \n cursor: pointer; \n font-weight: 600;\n margin-top: 4px;\n display: inline-block;\n width: fit-content;\n }\n .mfm-mod-actions-count:hover { background: #dbeafe; }\n\n /* Modals */\n .mfm-modal-overlay {\n position: fixed;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 1000001;\n opacity: 0;\n transition: opacity 0.2s;\n pointer-events: none;\n }\n .mfm-modal-overlay.show { opacity: 1; pointer-events: auto; }\n .mfm-modal {\n background: white;\n padding: 20px;\n border-radius: 12px;\n width: 90%;\n max-width: 400px;\n max-height: 80vh;\n overflow-y: auto;\n box-shadow: 0 10px 25px rgba(0,0,0,0.2);\n transform: scale(0.9);\n transition: transform 0.2s;\n }\n .mfm-modal-overlay.show .mfm-modal { transform: scale(1); }\n .mfm-modal-title { font-size: 16px; font-weight: 600; margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center; }\n .mfm-modal-body { font-size: 14px; color: #4b5563; }\n .mfm-modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; }\n .mfm-btn-alt { background: #f3f4f6; color: #333; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 14px; }\n .mfm-btn-danger { background: #dc2626; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 14px; }\n .mfm-mod-item { border-bottom: 1px solid #eee; padding-bottom: 8px; margin-bottom: 8px; }\n .mfm-mod-item:last-child { border-bottom: none; margin-bottom: 0; }\n .mfm-mod-type { font-weight: 600; font-size: 12px; color: #2563eb; text-transform: uppercase; margin-bottom: 4px; }\n .mfm-mod-detail { font-size: 11px; font-family: monospace; word-break: break-all; }\n\n .mfm-spinner {\n width: 12px;\n height: 12px;\n border: 2px solid #f3f3f3;\n border-top: 2px solid #2563eb;\n border-radius: 50%;\n animation: mfm-spin 1s linear infinite;\n margin-right: 8px;\n display: inline-block;\n }\n .mfm-duration { color: #666; font-size: 11px; margin-left: 8px; font-weight: normal; }\n\n .mfm-detail-view { display: flex; flex-direction: column; height: 100%; }\n .mfm-detail-actions { margin-bottom: 10px; }\n .mfm-back-btn { background: none; border: none; color: #2563eb; cursor: pointer; font-size: 14px; display: flex; align-items: center; gap: 4px; padding: 0;}\n \n .mfm-code-block {\n background: #f8fafc;\n padding: 10px;\n border-radius: 8px;\n overflow-x: auto;\n font-family: monospace;\n font-size: 12px;\n white-space: pre-wrap;\n word-break: break-all;\n max-height: 300px;\n border: 1px solid #e2e8f0;\n }\n .section-title { font-size: 14px; font-weight: 600; margin: 10px 0 5px; color: #333; }\n .section-header { display: flex; align-items: center; justify-content: space-between; margin: 10px 0 5px; }\n .mfm-copy-btn {\n background: #f1f5f9;\n color: #64748b;\n padding: 2px 8px;\n border-radius: 4px;\n font-size: 10px;\n cursor: pointer;\n border: 1px solid #e2e8f0;\n transition: all 0.2s;\n font-weight: 600;\n text-transform: uppercase;\n }\n .mfm-copy-btn:hover { background: #e2e8f0; color: #334155; }\n \n .mfm-copy-group {\n display: flex;\n gap: 6px;\n flex-wrap: wrap;\n margin-top: 4px;\n }\n .mfm-copy-group .mfm-copy-btn {\n font-size: 9px;\n padding: 2px 6px;\n }\n\n /* Dropdown Menu */\n .mfm-menu-dots {\n cursor: pointer;\n padding: 4px;\n color: #666;\n border-radius: 4px;\n transition: background 0.2s;\n line-height: 1;\n margin-left: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .mfm-menu-dots:hover { background: #f3f4f6; color: #333; }\n \n .mfm-dropdown-shared {\n position: fixed;\n background: white;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n z-index: 1000005;\n display: none;\n flex-direction: column;\n width: 160px;\n overflow: hidden;\n }\n .mfm-dropdown-shared.show { display: flex; }\n .mfm-dropdown-item {\n padding: 10px 14px;\n font-size: 13px;\n color: #334155;\n cursor: pointer;\n transition: background 0.2s;\n text-align: left;\n border-bottom: 1px solid #f1f5f9;\n white-space: nowrap;\n }\n .mfm-dropdown-item:last-child { border-bottom: none; }\n .mfm-dropdown-item:hover { background: #f8fafc; color: #2563eb; }\n\n /* Snackbar */\n .mfm-snackbar {\n position: fixed;\n bottom: 80px;\n left: 50%;\n transform: translateX(-50%) translateY(20px);\n background: #333;\n color: white;\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 14px;\n z-index: 1000000;\n opacity: 0;\n transition: opacity 0.3s, transform 0.3s;\n pointer-events: none;\n }\n .mfm-snackbar.show { opacity: 1; transform: translateX(-50%) translateY(0); }\n ",document.head.appendChild(e)}render(){const e=document.createElement("div");e.id="mockforme-root",document.body.appendChild(e),this.root=e,this.bubble=this.renderBubble(),this.root.appendChild(this.bubble),this.sheet=document.createElement("div"),this.sheet.className="mfm-bottomsheet",this.root.appendChild(this.sheet),this.snackbar=document.createElement("div"),this.snackbar.className="mfm-snackbar",this.root.appendChild(this.snackbar),this.modalOverlay=document.createElement("div"),this.modalOverlay.className="mfm-modal-overlay",this.root.appendChild(this.modalOverlay),this.sharedDropdown=document.createElement("div"),this.sharedDropdown.className="mfm-dropdown-shared",this.sharedDropdown.innerHTML='\n <div class="mfm-dropdown-item" data-format="curl">Copy as cURL</div>\n <div class="mfm-dropdown-item" data-format="fetch">Copy as Fetch</div>\n <div class="mfm-dropdown-item" data-format="xhr">Copy as XHR</div>\n ',this.root.appendChild(this.sharedDropdown),this.updateUI()}updateUI(){this.sheet&&(this.state.isOpen?(this.renderBottomSheetContent(),this.sheet.classList.add("open")):this.sheet.classList.remove("open"))}renderBubble(){const e=document.createElement("div");e.className="mfm-bubble";const t="undefined"!=typeof localStorage?JSON.parse(localStorage.getItem("mockforme-dot-pos")||"{}"):{};return t.bottom&&(e.style.bottom=t.bottom+"px"),t.right&&(e.style.right=t.right+"px"),e.innerHTML=`\n <div class="mfm-refresh-icon" title="Reload Mappings">${_}</div>\n <img src="https://ik.imagekit.io/mfm/static-collection/mfm-48x48.png" alt="MFM" />\n `,this.addDragLogic(e),this.keepInBounds(e),e.querySelector("img").onclick=e=>{this.isDragging||this.toggleSheet()},e.querySelector(".mfm-refresh-icon").onclick=e=>{e.stopPropagation(),this.refreshMappings()},e}keepInBounds(e){const t=e.getBoundingClientRect(),n=10;let o=parseInt(e.style.right)||20,r=parseInt(e.style.bottom)||20;const s=window.innerWidth-t.width-n,i=window.innerHeight-t.height-n;o<n&&(o=n),r<n&&(r=n),o>s&&(o=s),r>i&&(r=i),e.style.right=o+"px",e.style.bottom=r+"px"}addDragLogic(e){let t,n,o,r,s=!1;const i=(i,a)=>{s=!1,this.isDragging=!1,t=i,n=a;const d=e.getBoundingClientRect();o=window.innerWidth-d.right,r=window.innerHeight-d.bottom},a=(i,a)=>{const d=t-i,c=n-a;(Math.abs(d)>3||Math.abs(c)>3)&&(s=!0,this.isDragging=!0),s&&(e.style.right=o+d+"px",e.style.bottom=r+c+"px")},d=()=>{s&&(this.keepInBounds(e),"undefined"!=typeof localStorage&&localStorage.setItem("mockforme-dot-pos",JSON.stringify({bottom:parseInt(e.style.bottom),right:parseInt(e.style.right)})))},c=e=>{a(e.clientX,e.clientY)},l=()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",l),d()},m=e=>{const t=e.touches[0];a(t.clientX,t.clientY),s&&e.cancelable&&e.preventDefault()},u=()=>{document.removeEventListener("touchmove",m),document.removeEventListener("touchend",u),d()};e.addEventListener("mousedown",(e=>{i(e.clientX,e.clientY),document.addEventListener("mousemove",c),document.addEventListener("mouseup",l)})),e.addEventListener("touchstart",(e=>{const t=e.touches[0];i(t.clientX,t.clientY),document.addEventListener("touchmove",m,{passive:!1}),document.addEventListener("touchend",u)}),{passive:!0})}toggleSheet(){this.state.isOpen=!this.state.isOpen,"undefined"!=typeof localStorage&&localStorage.setItem("mockforme-widget-open",this.state.isOpen),this.updateUI()}showSnackbar(e){this.snackbar&&(this.snackbar.textContent=e,this.snackbar.classList.add("show"),setTimeout((()=>this.snackbar.classList.remove("show")),3e3))}showConfirm(e,t,n){this.showModal(e,t,[{label:"Cancel",className:"mfm-btn-alt",onClick:e=>e.classList.remove("show")},{label:"Delete",className:"mfm-btn-danger",onClick:e=>{e.classList.remove("show"),n()}}])}showModal(e,t,n=[]){if(!this.modalOverlay)return;this.modalOverlay.innerHTML=`\n <div class="mfm-modal">\n <div class="mfm-modal-title">\n <span>${e}</span>\n <span style="cursor:pointer;" id="mfm-modal-close">${M}</span>\n </div>\n <div class="mfm-modal-body">${t}</div>\n <div class="mfm-modal-actions" id="mfm-modal-actions"></div>\n </div>\n `;const o=this.modalOverlay.querySelector("#mfm-modal-actions");if(n.forEach((e=>{const t=document.createElement("button");t.className=e.className||"mfm-btn-alt",t.textContent=e.label,t.onclick=()=>e.onClick(this.modalOverlay),o.appendChild(t)})),0===n.length){const e=document.createElement("button");e.className="mfm-btn",e.textContent="OK",e.onclick=()=>this.modalOverlay.classList.remove("show"),o.appendChild(e)}this.modalOverlay.querySelector("#mfm-modal-close").onclick=()=>{this.modalOverlay.classList.remove("show")},this.modalOverlay.classList.add("show")}refreshMappings(){if(!this.token)return void this.toggleSheet();const e=document.querySelectorAll(".mfm-refresh-icon, #mfm-refresh-mappings-btn");e.forEach((e=>e.classList.add("loading"))),S(this.token,"JAVASCRIPT",((t,n)=>{console.log("[MockForMe] Mappings reloaded",{mappings:t?.length,rules:n?._rules?.length}),e.forEach((e=>e.classList.remove("loading"))),this.mappings=t||[],this.rules=n?._rules||[],this.onAuthSuccess(this.token,this.mappings,n),this.updateUI(),this.showSnackbar("Mappings reloaded!")}),(t=>{e.forEach((e=>e.classList.remove("loading"))),this.showSnackbar("Failed to reload mappings")}))}renderBottomSheetContent(){this.sheet.innerHTML="",this.isAuthenticated?this.state.selectedRequest?this.sheet.appendChild(this.renderRequestDetail(this.state.selectedRequest)):this.sheet.appendChild(this.renderDashboard()):this.sheet.appendChild(this.renderTokenForm())}renderTokenForm(){const e=document.createElement("div");e.innerHTML=`\n <div class="mfm-header">\n <span class="mfm-title">Save Token</span>\n <button class="mfm-close">${M}</button>\n </div>\n <div class="mfm-logo-container">\n <img src="https://dashboard.mockforme.com/public/assets/images/logo.png" class="mfm-logo" alt="MockForMe Logo" />\n </div>\n <div class="mfm-form">\n <input type="text" class="mfm-input" placeholder="Enter MockForMe Access Token" id="mfm-token-input">\n <div class="mfm-error" id="mfm-error-msg" style="display: ${this.state.lastError?"block":"none"}">${this.state.lastError||""}</div>\n <a href="https://dashboard.mockforme.com/user/token" target="_blank" class="mfm-link">Get Access Token?</a>\n <button class="mfm-btn" id="mfm-save-token-btn">Save</button>\n </div>\n `,e.querySelector(".mfm-close").onclick=()=>{this.state.lastError=null,this.toggleSheet()};const t=e.querySelector("#mfm-save-token-btn"),n=e.querySelector("#mfm-token-input");return t.onclick=()=>{const o=n.value.trim();o&&(t.textContent="Validating...",t.disabled=!0,this.state.lastError=null,e.querySelector("#mfm-error-msg").style.display="none",S(o,a,((e,t)=>{"undefined"!=typeof localStorage&&localStorage.setItem("mockforme-token",o),this.token=o,this.isAuthenticated=!0,this.mappings=e,this.rules=t?._rules||[],this.onAuthSuccess(o,e,t),this.updateUI()}),(e=>{t.textContent="Save",t.disabled=!1;let n="Invalid Token or Network Error";e&&"function"==typeof e.json?e.json().then((e=>{this.state.lastError=e.message||n,this.updateUI()})).catch((()=>{this.state.lastError=n,this.updateUI()})):(this.state.lastError=e.message||n,this.updateUI())})))},e}updateMappings(e,t){this.mappings=e||[],this.rules=t?._rules||[],this.root&&this.updateUI()}deleteToken(){"undefined"!=typeof localStorage&&localStorage.removeItem("mockforme-token"),this.token=null,this.isAuthenticated=!1,this.mappings=[],this.rules=[],this.state.lastError=null,this.updateUI()}renderDashboard(){const e=document.createElement("div");e.innerHTML=`\n <div class="mfm-header">\n <span class="mfm-title"><img src="https://www.mockforme.com/assets/images/logo.png" /></span>\n <div class="mfm-header-actions">\n <button class="mfm-close">${M}</button>\n </div>\n </div>\n `;const t=document.createElement("div");t.className="mfm-tabs",["mappings","mocked","other","settings"].forEach((e=>{const n=document.createElement("div");n.className="mfm-tab "+(this.state.activeTab===e?"active":""),n.textContent="mappings"===e?"Api Mappings":"mocked"===e?"Mocked Apis":"other"===e?"Other Apis":"Settings",n.onclick=()=>{this.state.activeTab=e,this.updateUI()},t.appendChild(n)})),e.querySelector(".mfm-header").after(t);const n=document.createElement("div");n.className="mfm-actions-bar","mappings"===this.state.activeTab?(n.innerHTML=`\n <div style="flex: 1; font-size: 13px; color: #666;">Total: ${this.mappings.length+this.rules.length}</div>\n <div class="mfm-icon-btn refresh" id="mfm-refresh-mappings-btn" title="Refresh Mappings">${_}</div>\n `,n.querySelector("#mfm-refresh-mappings-btn").onclick=()=>this.refreshMappings()):"settings"!==this.state.activeTab?(n.innerHTML=`\n <input type="text" class="mfm-search-input" placeholder="Search requests..." id="mfm-search-input" value="${this.state.searchQuery}">\n <button class="mfm-icon-btn delete" id="mfm-clear-requests-btn" title="Clear List"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg></button>\n `,n.querySelector("#mfm-search-input").oninput=e=>{this.state.searchQuery=e.target.value,this.updateRequestList(o)},n.querySelector("#mfm-clear-requests-btn").onclick=()=>{"mocked"===this.state.activeTab?this.mockedRequests=[]:this.otherRequests=[],this.updateUI()}):n.style.display="none",t.after(n);const o=document.createElement("div");return o.className="mfm-list",this.updateRequestList(o),e.appendChild(o),e.querySelector(".mfm-close").onclick=()=>this.toggleSheet(),e}updateRequestList(e){if(e.innerHTML="","mappings"===this.state.activeTab){const t=[...this.mappings.map((e=>({...e,type:"mapping"}))),...this.rules.map((e=>({...e,type:"rule"})))];0===t.length?e.innerHTML='<div style="padding: 20px; text-align: center; color: #999;">No items found</div>':t.forEach((t=>{const n=document.createElement("div");if(n.className="mfm-list-item","mapping"===t.type){const e=(t.apiMethod||"GET").toUpperCase();n.innerHTML=`<div style="display:flex; align-items:center; width:100%"><span class="mfm-method ${e}">${e}</span><span class="mfm-url">${t.apiEndpoint}</span></div>`}else{const e=t.rule||t,o=e.timingAction||{},r=o.activeAction||"none",s=o.actions?.[r]?.value,i=`Rule (${r}${void 0!==s?` ${s}s`:""})`;let a="{}";e.conditions&&Array.isArray(e.conditions)&&(a=e.conditions.map((e=>`${e.type}:${e.operator}:${e.value}`)).join(" AND "));const d=a.length>40?a.substring(0,40)+"...":a;let c=0;const l=e.modificationActions||{};Object.values(l).forEach((e=>{e.enabled&&(e.add&&(c+=e.add.length),e.remove&&(c+=e.remove.length),e.update&&(c+=e.update.length))})),n.innerHTML=`\n <div class="mfm-mapping-info">\n <span class="mfm-rule-name" style="cursor:pointer; color:#2563eb; text-decoration:underline;" id="mfm-view-full-rule" title="View full rule details">${i}</span>\n <span class="mfm-condition-brief" title="View condition">\n ${d} <span style="font-weight:bold; color:#2563eb; margin-left:4px; cursor:pointer;" id="mfm-view-cond-dots">${T}</span>\n </span>\n ${c>0?`<div class="mfm-mod-actions-count" id="mfm-view-mods">${c} Modification Actions</div>`:""}\n </div>\n <span class="mfm-method RULE">RULE</span>\n `,n.querySelector("#mfm-view-full-rule").onclick=t=>{t.stopPropagation();const n=JSON.stringify(e,null,2);this.showModal("Full Rule Information",`<pre class="mfm-code-block">${n}</pre>`)},n.querySelector("#mfm-view-cond-dots").onclick=t=>{t.stopPropagation();const n=e.conditions.map((e=>`\n <div class="mfm-mod-item">\n <div class="mfm-mod-type">${e.type} (${e.operator})</div>\n <div class="mfm-mod-detail"><b>Key:</b> ${e.key||"N/A"}<br><b>Value:</b> ${e.value}</div>\n </div>\n `)).join("");this.showModal("Rule Conditions",n)},c>0&&(n.querySelector("#mfm-view-mods").onclick=e=>{e.stopPropagation();let t="";Object.entries(l).forEach((([e,n])=>{n.enabled&&(t+=`<div class="mfm-mod-item"><div class="mfm-mod-type">${e.replace("modify","")}</div>`,n.add?.length&&(t+=`<div class="mfm-mod-detail"><b>Add:</b> ${JSON.stringify(n.add)}</div>`),n.update?.length&&(t+=`<div class="mfm-mod-detail"><b>Update:</b> ${JSON.stringify(n.update)}</div>`),n.remove?.length&&(t+=`<div class="mfm-mod-detail"><b>Remove:</b> ${JSON.stringify(n.remove)}</div>`),t+="</div>")})),this.showModal("Modification Actions",t)})}e.appendChild(n)}))}else if("settings"===this.state.activeTab)e.innerHTML='\n <div style="padding: 16px;">\n <div class="section-title" style="margin-top: 0; margin-bottom: 12px; font-size: 15px; border-bottom: 1px solid #eee; padding-bottom: 8px;">Token Management</div>\n <p style="font-size: 13px; color: #666; margin-bottom: 16px;">Removing your token will clear all saved mappings and rules from this browser instance.</p>\n <button class="mfm-delete-token-btn" id="mfm-settings-delete-token" style="padding: 8px 16px; font-size: 14px; width: fit-content;">\n <span><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></span>\n <span>Delete Token</span>\n </button>\n </div>\n ',e.querySelector("#mfm-settings-delete-token").onclick=()=>{this.showConfirm("Delete Token","Are you sure you want to Delete Token? This will clear your saved token.",(()=>{this.deleteToken()}))};else{let t="mocked"===this.state.activeTab?this.mockedRequests:this.otherRequests;if(this.state.searchQuery){const e=this.state.searchQuery.toLowerCase();t=t.filter((t=>(t.url||"").toLowerCase().includes(e)||(t.method||"").toLowerCase().includes(e)||String(t.status).includes(e)))}0===t.length?e.innerHTML='<div style="padding: 20px; text-align: center; color: #999;">No items found</div>':t.forEach((t=>{const n=document.createElement("div");n.className="mfm-list-item";const o=(t.method||"").toUpperCase(),r=`<span class="mfm-duration" style="color:#2563eb; font-size:11px; font-weight:500; display:block; height:14px; line-height:14px;">${void 0!==t.duration?t.duration+"ms":""}</span>`;let s="",i="";if(t.rule){const e=t.rule.action||"";let n="delay_and_timeout"===e?"Delay and Timout":e.split("_")[0];const o=t.rule.config?.value;void 0!==o&&(e.includes("delay")||e.includes("timeout"))&&(n+=` (${o}s)`),s=`<span class="mfm-rule-tag" title="${e}">${n}</span>`,"delay_and_redirect"===e&&t.rule.config?.redirectUrl&&(i=`<div class="mfm-redirect-badge">Redirected to: ${t.rule.config.redirectUrl}</div>`)}let a=t.status,d="mfm-status";t.pending?a='<span class="mfm-spinner"></span>':t.aborted?(a="Aborted",d+=" status-aborted"):t.timeout?(a="Timeout",d+=" status-timeout"):t.error?(a="Error/CORS",d+=" status-error"):(a=t.status,d+=t.status>=200&&t.status<300?" status-2xx":" status-non-2xx"),n.innerHTML=`\n <div style="display:flex; align-items:center; width:100%; gap:8px;">\n <span class="mfm-method ${o}">${o}</span>\n <div style="flex:1; min-width:0; display:flex; flex-direction:column; gap:2px; justify-content:center;">\n <span class="mfm-url">${s}${t.url}</span>\n ${i}\n ${r}\n </div>\n <span class="${d}">${a}</span>\n <span class="mfm-menu-dots" title="Copy As...">${T}</span>\n </div>\n `;const c=n.querySelector(".mfm-menu-dots");c.onclick=e=>{e.stopPropagation();const n=c.getBoundingClientRect();this.sharedDropdown.style.top=n.bottom+5+"px",this.sharedDropdown.style.left=n.right-160+"px",this.sharedDropdown.classList.toggle("show"),this.sharedDropdown.onclick=e=>{e.stopPropagation();const n=e.target.getAttribute("data-format");if(!n)return;let o="";"curl"===n?o=this.generateCurl(t):"fetch"===n?o=this.generateFetch(t):"xhr"===n&&(o=this.generateXHR(t)),o&&navigator.clipboard.writeText(o).then((()=>{this.showSnackbar(`${n.toUpperCase()} copied!`),this.sharedDropdown.classList.remove("show")}))}},n.onclick=()=>{this.state.selectedRequest=t,this.updateUI()},e.appendChild(n)}))}}renderRequestDetail(e){const t=document.createElement("div");t.className="mfm-detail-view",t.innerHTML=`\n <div class="mfm-header">\n <span class="mfm-title">Details</span>\n <button class="mfm-close">${M}</button>\n </div>\n <div class="mfm-detail-actions">\n <button class="mfm-back-btn"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block; vertical-align:middle; margin-right:4px;"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>Back</button>\n </div>\n `;const n=document.createElement("div");n.className="mfm-tabs",["request","response"].forEach((e=>{const t=document.createElement("div");t.className="mfm-tab "+(this.state.activeRequestTab===e?"active":""),t.textContent=e.charAt(0).toUpperCase()+e.slice(1),t.onclick=()=>{this.state.activeRequestTab=e,this.updateUI()},n.appendChild(t)}));const o=document.createElement("div");o.style.overflowY="auto",o.style.flex="1";const r=(e.method||"").toUpperCase(),s=this.formatBody(e.requestBody),i=this.formatBody(e.responseBody);o.innerHTML="request"===this.state.activeRequestTab?`\n <div class="section-title">URL</div><div class="mfm-code-block">${r} ${e.url}</div>\n ${e.rule?`<div class="section-title">Matched Rule</div><div class="mfm-code-block">${e.rule.action} (value: ${e.rule.config?.value})</div>`:""}\n <div class="section-title">Headers</div><div class="mfm-code-block">${JSON.stringify(e.requestHeaders||{},null,2)}</div>\n <div class="section-title">Query Params</div><div class="mfm-code-block">${JSON.stringify(e.queryParams||{},null,2)}</div>\n <div class="section-header">\n <div class="section-title" style="margin: 0;">Payload</div>\n <div class="mfm-copy-btn" id="mfm-copy-payload">Copy</div>\n </div>\n <div class="mfm-code-block">${s}</div>\n `:`\n <div class="section-title">Status</div><div class="mfm-code-block">${e.status}</div>\n <div class="section-title">Response Headers</div><div class="mfm-code-block">${JSON.stringify(e.responseHeaders||{},null,2)}</div>\n <div class="section-header">\n <div class="section-title" style="margin: 0;">Response Body</div>\n <div class="mfm-copy-btn" id="mfm-copy-response">Copy</div>\n </div>\n <div class="mfm-code-block">${i}</div>\n `,t.appendChild(n),t.appendChild(o);const a=o.querySelector("#mfm-copy-payload");a&&(a.onclick=()=>{navigator.clipboard.writeText(s).then((()=>{this.showSnackbar("Payload copied!")}))});const d=o.querySelector("#mfm-copy-response");return d&&(d.onclick=()=>{navigator.clipboard.writeText(i).then((()=>{this.showSnackbar("Response copied!")}))}),t.querySelector(".mfm-close").onclick=()=>this.toggleSheet(),t.querySelector(".mfm-back-btn").onclick=()=>{this.state.selectedRequest=null,this.updateUI()},t}formatBody(e){if(!e)return"";if("undefined"!=typeof FormData&&e instanceof FormData){const t={};return e.forEach(((e,n)=>{"undefined"!=typeof File&&e instanceof File?t[n]=`[File: ${e.name} (${e.size} bytes)]`:"undefined"!=typeof Blob&&e instanceof Blob?t[n]=`[Blob: ${e.type} (${e.size} bytes)]`:t[n]=e})),JSON.stringify(t,null,2)}if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return JSON.stringify(Object.fromEntries(e.entries()),null,2);if("undefined"!=typeof Blob&&e instanceof Blob)return`[${"undefined"!=typeof File&&e instanceof File?"File":"Blob"}: ${e.type||"binary"} (${e.size} bytes)]`;if(e instanceof ArrayBuffer||"undefined"!=typeof Uint8Array&&e instanceof Uint8Array)return`[Binary Data: ${e.byteLength||e.length} bytes]`;if("object"==typeof e)try{return JSON.stringify(e,null,2)}catch{return String(e)}try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}generateCurl(e){const t=(e.method||"GET").toUpperCase();let n=`curl -X ${t} "${e.url}"`;if(e.requestHeaders&&Object.entries(e.requestHeaders).forEach((([e,t])=>{n+=` \\\n -H "${e}: ${t}"`})),e.requestBody&&"GET"!==t){const t=("string"==typeof e.requestBody?e.requestBody:JSON.stringify(e.requestBody)).replace(/'/g,"'\\''");n+=` \\\n --data-raw '${t}'`}return n}generateFetch(e){const t=(e.method||"GET").toUpperCase();let n=`{\n method: "${t}",\n headers: ${(e.requestHeaders?JSON.stringify(e.requestHeaders,null,2):"{}").replace(/\n/g,"\n ")}`;if(e.requestBody&&"GET"!==t){const t="string"==typeof e.requestBody?e.requestBody:JSON.stringify(e.requestBody,null,2);n+=`,\n body: ${"string"==typeof e.requestBody?"`"+t+"`":JSON.stringify(e.requestBody,null,2).replace(/\n/g,"\n ")}`}return n+="\n}",`fetch("${e.url}", ${n})\n .then(response => response.json())\n .then(data => console.log(data))\n .catch(error => console.error(error));`}generateXHR(e){const t=(e.method||"GET").toUpperCase();let n=`var xhr = new XMLHttpRequest();\nxhr.open("${t}", "${e.url}");\n`;if(e.requestHeaders&&Object.entries(e.requestHeaders).forEach((([e,t])=>{n+=`xhr.setRequestHeader("${e}", "${t}");\n`})),n+="\nxhr.onload = function() {\n console.log(xhr.responseText);\n};\n",e.requestBody&&"GET"!==t){const t="string"==typeof e.requestBody?e.requestBody:JSON.stringify(e.requestBody);n+=`\nxhr.send(${"string"==typeof e.requestBody?"`"+t+"`":JSON.stringify(e.requestBody)});`}else n+="\nxhr.send();";return n}addRequest(e,t){const n=String(t.method||"").toUpperCase().trim(),o=String(t.url||"");console.log(`[MockForMe] addRequest type=${e} method=${n} url=${o} requestId=${t.requestId} pending=${t.pending}`);const r=o.includes("api.mockforme.com")||o.includes("mockforme.com/proxy")||o.includes("mockforme.com/gateway")||o.includes("/3f4eae522b")||p&&o.includes(String(p));if("OPTIONS"===n||r)return;const s="mocked"===e?this.mockedRequests:this.otherRequests,i="mocked"===e?this.otherRequests:this.mockedRequests;if(t.requestId){const e=s.findIndex((e=>e.requestId===t.requestId));if(-1!==e)return s[e]={...s[e],...t},void this.updateUI();const n=i.findIndex((e=>e.requestId===t.requestId));if(-1!==n){const e={...i[n],...t};return i.splice(n,1),s.unshift(e),s.length>100&&s.pop(),void this.updateUI()}}s.unshift(t),s.length>100&&s.pop(),this.updateUI()}};class ${static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:r,body:s}=e,i="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:d,operator:c,value:l}=e;switch(a){case"URL":try{t=new URL(n,i).pathname}catch{t=n}break;case"QUERY_PARAM":if(r&&void 0!==r[d])t=String(r[d]);else try{t=new URL(n,i).searchParams.get(d)||""}catch{t=""}break;case"REQUEST_BODY":if(d){if("object"==typeof s&&null!==s)t=void 0!==s[d]?String(s[d]):"";else if("string"==typeof s)try{const e=JSON.parse(s);t=void 0!==e[d]?String(e[d]):""}catch{t=""}}else t="object"==typeof s?JSON.stringify(s):String(s||"");break;case"REQUEST_HEADER":if(d){const e=d?.toLowerCase();if(t="",o){const n=Object.keys(o).find((t=>t.toLowerCase()===e));t=n?String(o[n]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,c,l))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),r=String(e),s=String(n);switch(o){case"contains":return r.includes(s);case"equal":case"equals":return r===s;case"regexp":try{let e=s;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),o=e.slice(t+1);return new RegExp(n,o).test(r)}return new RegExp(e).test(r)}catch{return!1}default:return!1}}}class I{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,o=n?.[t];if(!o)return{type:"passThrough",delay:0};const r={type:"passThrough",delay:0},s=Number(o.value||0);switch(t){case"delay":r.delay=s,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)));break;case"delay_and_redirect":r.type="redirect",r.delay=s,r.redirectUrl=o.redirectUrl,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)));break;case"delay_and_timeout":r.type="timeout",r.delay=s,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)))}return r}}class A{static applyRequestModifications(e,t){if(!t)return e;let{url:n,headers:o,queryParams:r,body:s}={...e};o&&(o={...o}),r&&(r={...r});const{modifyQueryParams:i,modifyRequestBody:a,modifyRequestHeaders:d}=t;if(i?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(i.remove)&&i.remove.forEach((t=>{e.searchParams.delete(t),r&&delete r[t]})),Array.isArray(i.add)&&i.add.forEach((({key:t,value:n})=>{e.searchParams.set(t,n),r&&(r[t]=n)})),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}if(d?.enabled&&(o={...o},Array.isArray(d.remove)&&d.remove.forEach((e=>{const t=e.toLowerCase(),n=Object.keys(o).find((e=>e.toLowerCase()===t));n&&delete o[n]})),Array.isArray(d.add)&&d.add.forEach((({key:e,value:t})=>{o[e]=t}))),a?.enabled)try{let t=null;if("string"==typeof s)try{t=JSON.parse(s)}catch{}else if("object"==typeof s&&null!==s)try{t=JSON.parse(JSON.stringify(s))}catch{t={...s}}t&&(Array.isArray(a.remove)&&a.remove.forEach((e=>delete t[e])),Array.isArray(a.add)&&a.add.forEach((({key:e,value:n})=>t[e]=n)),Array.isArray(a.update)&&a.update.forEach((({key:e,value:n})=>t[e]=n)),s="string"==typeof e.body?JSON.stringify(t):t)}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:r,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,o={...e};return Array.isArray(n.remove)&&n.remove.forEach((e=>{const t=e.toLowerCase(),n=Object.keys(o).find((e=>e.toLowerCase()===t));n&&delete o[n]})),Array.isArray(n.add)&&n.add.forEach((({key:e,value:t})=>{o[e]=t})),o}}class O{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&$.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,o=A.applyRequestModifications(t,n.modificationActions);return{...await I.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return A.applyResponseModifications(e,t)}}class C{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:s=async(e,t,n,o,r)=>null,onMockMatch:i=async(e,t,n,o,r)=>null,onOtherRequest:a=async(e,t,n,o)=>null}){t&&(e.fetch=async function(e,d={}){let c;try{const t="string"==typeof e?e:e.url,n=String(d.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),o=Math.random().toString(36).substring(7);c={url:t,method:n,headers:d.headers||(e instanceof Request?e.headers:{}),body:d.body||(e instanceof Request?"{binary/stream}":null),requestId:o,queryParams:C.getQueryParams(t)},r(c)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,d)}try{const r=n(),l=O.match(c,r);if(l){const n=await s(l,c,e,d,t);if(n)return n}const m=o(c);if(m){const n=await i(m,c,e,d,t);if(n)return n}const u=await a(c,e,d,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;console.warn("[MockForMe] Interceptor Hook Error:",e)}return t(e,d)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class H{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:s=(e,t,n,o)=>{o.call(n.proxy,t.body)},onMockMatch:i=(e,t,n,o)=>{o.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)}}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,o={}){if(this._captured)return;this._captured=!0;const r=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),r("readystatechange"),"Aborted"===e||o.aborted?r("abort"):0===e||"Error"===e||o.error?r("error"):"Timeout"===e||o.timeout?r("timeout"):r("load")}open(e,t,n=!0,o=null,r=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,o,r)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:H.getQueryParams(this._url)};r(t);const d=n(),c=O.match(t,d),l=e=>this._xhr.send(e);if(c)return this._isMocked=!0,s(c,t,this,l);const m=o(t);return m?(this._isMocked=!0,i(m,t,this,l)):(this._isMocked=!1,a(t,this,l))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const U=(t,n=null,o=a)=>{if(e())return;let u="string"==typeof t?t:t?.token,p="object"==typeof t?t?.widgetKey:null;if(p?L.setWidgetKey(p):L.init(),o===a)try{u&&("undefined"!=typeof localStorage&&localStorage.removeItem("mockforme-token"),L.token=u,L.isAuthenticated=!0),!u&&L.token&&(u=L.token),L.onAuthSuccess=(e,t,n)=>{r(t),x(n),L.updateMappings(t,n)}}catch(e){console.log("Error in showing mockforme widget",e)}n||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:f=[],_o:g,mk:y,_mck:b,_rules:_=[]}=n;return r(f),x({_o:g,mk:y,_mck:b,_rules:_}),{run:(e,t=()=>{})=>{!function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>L.token||e;C.apply({ruleProvider:()=>w(),mappingProvider:e=>{try{return i(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o,r)=>{const s=t.requestId||Math.random().toString(36).substring(7),i=Date.now();L.addRequest("mocked",{...t,requestId:s,pending:!0,startTime:i,rule:e});const a=await O.apply(e,t),{modifiedRequest:d,type:c,delay:l,redirectUrl:m}=a;if("timeout"!==c&&L.addRequest("mocked",{...d,requestId:s,pending:!0,startTime:i,rule:e}),"timeout"===c){const e=Date.now()-i;throw L.addRequest("mocked",{...d,requestId:s,status:"Aborted",pending:!1,duration:e,aborted:!0}),new Error("Fetch timed out by rules")}let u="redirect"===c?m:d.url,p={...o};d.headers&&(p.headers=d.headers),d.body&&(p.body=d.body);let h=null;if("redirect"===c){h=Math.random().toString(36).substring(7);const e={url:m,method:d.method,headers:p.headers||{},body:p.body,requestId:h,queryParams:C.getQueryParams(m),requestHeaders:p.headers||{},requestBody:p.body,pending:!0,startTime:Date.now()};L.addRequest("mocked",e)}return r(u,p).then((async e=>{const t=Date.now()-i;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=O.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===c&&h){const t=e.clone(),o=t.headers.get("content-type")||"",r=Date.now()-i;try{let s;s=o.includes("application/json")?await t.json():await t.text(),L.addRequest("mocked",{url:m,method:d.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,responseBody:s,requestHeaders:p.headers||{},requestBody:p.body})}catch(t){L.addRequest("mocked",{url:m,method:d.method,requestId:h,status:e.status,pending:!1,duration:r,responseHeaders:n,requestHeaders:p.headers||{},requestBody:p.body})}}return L.addRequest("mocked",{...d,requestId:s,status:e.status,pending:!1,duration:t,responseHeaders:n}),e})).catch((e=>{const t=Date.now()-i,n="AbortError"===e.name||e.message.includes("aborted");throw L.addRequest("mocked",{...d,requestId:s,status:n?"Aborted":0,pending:!1,duration:t}),"redirect"===c&&h&&L.addRequest("mocked",{url:m,method:d.method,requestId:h,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),e}))},onMockMatch:async(e,o,r,s,i)=>{const a=o.requestId||Math.random().toString(36).substring(7),u=Date.now();L.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:u});const p=n(),h=new URL(o.url,window.location.origin).search;let f=`${v()}${e.url}${h}`,g={[l]:p,[c]:m,"x-mfm-adaptor":t};const y=k();y&&e._ack&&(g["x-mfm-key"]=`${y}-${e._ack}`),e?._ri_&&(g._ri_=e._ri_);const b=r instanceof Request?r.headers:s.headers,x=new Headers(b||{});Object.entries(g).forEach((([e,t])=>x.set(e,t)));let w=s.body;if(!w&&r instanceof Request){const e=r.clone();"GET"!==e.method&&"HEAD"!==e.method&&(w=await e.text())}const E={method:o.method,headers:x,credentials:r instanceof Request&&r.credentials||s.credentials||"include",mode:r instanceof Request&&r.mode||s.mode||"cors"};return t===d?(({actualUrl:e,url:t,method:n,headers:o,body:r,credentials:s,mode:i,rule:a})=>{const d=`${Date.now()}-${Math.random()}`,c=q(t);return new Promise(((t,l)=>{window.addEventListener("message",(function e(n){if(n.source!==window)return;const o=n.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===d){if(window.removeEventListener("message",e),o?.response?.error)return l(new Error(o.response.message));const{status:n,headers:r,body:s}=o.response;t(new Response(s,{status:n,headers:r}))}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:d,payload:{actualUrl:e,url:c,method:n,headers:o,body:r,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:o.url,url:f,method:o.method,headers:Object.fromEntries(x.entries()),body:w,credentials:E.credentials,mode:E.mode}).then((e=>(e.clone().text().then((t=>{const n=Date.now()-u;L.addRequest("mocked",{...o,requestId:a,status:e.status,responseHeaders:Object.fromEntries(e.headers.entries()),responseBody:t,pending:!1,duration:n})})),e))):(w&&(E.body=w),i(f,E).then((async e=>{const t=e.clone(),n=t.headers.get("content-type")||"",r=Date.now()-u,s=n=>(L.addRequest("mocked",{...o,requestId:a,status:e.status,responseHeaders:Object.fromEntries(t.headers.entries()),responseBody:n,pending:!1,duration:r}),new Response("string"==typeof n?n:JSON.stringify(n),{status:e.status,headers:t.headers}));return n.includes("application/json")?t.json().then(s):t.text().then(s)})).catch((e=>{const t=Date.now()-u;return L.addRequest("mocked",{...o,requestId:a,status:0,pending:!1,duration:t}),i(r,s)})))},onOtherRequest:async(e,t,n,o)=>{if("OPTIONS"===e.method)return o(t,n);const r=e.requestId,s=Date.now();return L.addRequest("other",{...e,requestId:r,pending:!0,startTime:s}),o(t,n).then((async t=>{const n=t.clone(),o=Date.now()-s;try{const s=await n.text();L.addRequest("other",{...e,requestId:r,status:t.status,responseHeaders:Object.fromEntries(t.headers.entries()),responseBody:s,pending:!1,duration:o})}catch(e){}return t})).catch((t=>{const n=Date.now()-s,o="AbortError"===t.name||t.message.includes("aborted"),i="TimeoutError"===t.name||t.message.includes("timed out");throw L.addRequest("other",{...e,requestId:r,status:o?"Aborted":i?"Timeout":"Error",pending:!1,duration:n,aborted:o,timeout:i,error:!o&&!i}),t}))}}),H.apply({ruleProvider:()=>w(),mappingProvider:e=>{try{return i(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const r=t.requestId,s=Date.now();L.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:s,rule:e});const i=await O.apply(e,t),{modifiedRequest:a,type:d,redirectUrl:c}=i;"timeout"!==d&&L.addRequest("mocked",{...a,requestId:r,pending:!0,startTime:s,rule:e});let l=null;if("redirect"===d){l=Math.random().toString(36).substring(7);const e={url:c,method:a.method,headers:a.headers||{},body:a.body,requestId:l,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(c,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};L.addRequest("mocked",e)}const m=(e,t,o,m={})=>{const u=Date.now()-s;if(i.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof o?Object.fromEntries(o.split("\r\n").filter((e=>e)).map((e=>e.split(": ")))):o;e=O.applyResponseModifications(e,i.rule.modificationActions),o=e}L.addRequest("mocked",{...a,requestId:r,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,...m}),"redirect"===d&&l&&L.addRequest("mocked",{url:c,method:a.method,requestId:l,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...m}),n._capture(e,t,o,m)};if("timeout"===d)return m("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();"redirect"===d?n._xhr.open(a.method,c,!0):a.url!==t.url&&n._xhr.open(a.method,a.url,!0),a.headers&&Object.entries(a.headers).forEach((([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}})),n._xhr.addEventListener("abort",(()=>m("Aborted","Aborted",{},{aborted:!0})),{once:!0}),n._xhr.addEventListener("error",(()=>m(0,"Error",{},{error:!0})),{once:!0}),n._xhr.addEventListener("timeout",(()=>m("Timeout","Timeout",{},{timeout:!0})),{once:!0}),n._xhr.addEventListener("load",(()=>m(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders())),{once:!0}),o(a.body)},onMockMatch:(e,o,r,s)=>{const i=o.requestId,a=Date.now(),u=n(),p=new URL(o.url,window.location.origin);let h=`${v()}${e.url}${p.search}`,f={[l]:u,[c]:m,"x-mfm-adaptor":t};const g=k();g&&e._ack&&(f["x-mfm-key"]=`${g}-${e._ack}`),e?._ri_&&(f._ri_=e._ri_);const y={...o.headers,...f};L.addRequest("mocked",{...o,requestId:i,pending:!0,startTime:a});const b=(e,t,n,s={})=>{const d=Date.now()-a;L.addRequest("mocked",{...o,requestId:i,status:e,responseBody:t,responseHeaders:n,pending:!1,duration:d,...s}),r._capture(e,t,n,s)};if(r._xhr.addEventListener("abort",(()=>b("Aborted","Aborted",{},{aborted:!0})),{once:!0}),r._xhr.addEventListener("error",(()=>b(0,"Error",{},{error:!0})),{once:!0}),r._xhr.addEventListener("timeout",(()=>b("Timeout","Timeout",{},{timeout:!0})),{once:!0}),t===d)(({actualUrl:e,url:t,method:n,headers:o,body:r,onSuccess:s,onError:i,rule:a})=>{const d=`${Date.now()}-${Math.random()}`,c=q(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const n=t.data;if("INTERCEPTED_RESPONSE"===n.type&&n.requestId===d){if(window.removeEventListener("message",e),n.response?.error)return i?.(n.response.message);const{body:t,status:o,headers:r}=n.response;s?.({body:t,status:o,headers:r})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:d,payload:{actualUrl:e,url:c,method:n,headers:o,body:r,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:o.url,url:h,method:o.method,headers:y,body:o.body,onSuccess:({body:e,status:t,headers:n})=>b(t,e,n||{}),onError:e=>b(0,e.message||"XHR Error",{},{error:!0})});else{const e=new window.XMLHttpRequest;e.open(o.method,h,!0);for(const t in y)e.setRequestHeader(t,y[t]);e.withCredentials=r.proxy.withCredentials,e.onload=()=>b(e.status,e.responseText,e.getAllResponseHeaders()),e.onerror=()=>b(0,"Network Error",{},{error:!0}),e.ontimeout=()=>b("Timeout","Request timed out",{},{timeout:!0}),e.send(o.body)}},onOtherRequest:(e,t,n)=>{if("OPTIONS"===e.method)return n(e.body);const o=Date.now();L.addRequest("other",{...e,pending:!0,startTime:o});const r=(n,r,s,i={})=>{const a=Date.now()-o;L.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:s,pending:!1,duration:a,...i}),t._capture(n,r,s,i)};t._xhr.addEventListener("abort",(()=>r("Aborted","Aborted",{},{aborted:!0})),{once:!0}),t._xhr.addEventListener("error",(()=>r(0,"Error",{},{error:!0})),{once:!0}),t._xhr.addEventListener("timeout",(()=>r("Timeout","Timeout",{},{timeout:!0})),{once:!0}),t._xhr.addEventListener("load",(()=>r(t._xhr.status,t._xhr.responseText,t._xhr.getAllResponseHeaders())),{once:!0}),n(e.body)}})}(u,o),g&&y?(L.mappings=f,L.rules=_,e?.(f,{_o:g,mk:y,_mck:b,_rules:_})):u&&function(t,n,o,s){E({method:"get",url:h,async:!1,headers:{[l]:t,[c]:m,"x-mfm-adaptor":n}},(t=>{if(t)try{const{di:s,iv:i,_o:a,_mck:d,mk:c,r:l}=t,m=R({di:s,iv:i},a);x({_o:a,mk:c,_mck:d,_rules:l}),m&&(r(m),n=m,o={_o:a,mk:c,_mck:d,_rules:l},L.updateMappings(n,o),e?.(n,o))}catch(e){return void s(new Error("Unable to fetch mocked apis"))}var n,o}),(e=>{console.log("Error in loading mocked apis"),s(e)})).request()}(u,o,0,t)},checkIfApiToBeMocked:i,getMappings:s,doFetchMappings:(e,t)=>{S(u||L.token,o,((t,n)=>{L.updateMappings(t,n),e?.(t,n)}),t)},recheckWidgetVisibility:()=>{L.init()}}},B=e();B||(globalThis.mockforme=U);let N=U;B&&(N=e=>({run:()=>{}}));const P=N;export{P as mockforme};
1
+ var e={133:(e,t,n)=>{n.r(t),n.d(t,{default:()=>q}),function(){try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode('.json-viewer{font-family:Consolas,Monaco,monospace;font-size:13px;line-height:1.6;padding:12px;border-radius:6px;overflow:auto}.json-viewer-light{background:#fff;color:#1f1f1f}.json-viewer-dark{background:#1e1e1e;color:#d4d4d4}.json-node{position:relative;padding-left:18px;white-space:nowrap}.json-children{margin-left:18px;padding-left:8px;border-left:1px dotted rgba(128,128,128,.25)}.json-toggle{position:absolute;left:0;cursor:pointer;-webkit-user-select:none;user-select:none;width:14px;height:14px;display:flex;align-items:center;justify-content:center;color:#888;font-weight:700;font-size:14px;border:1px solid rgba(128,128,128,.3);border-radius:2px;line-height:1;background:#8080800d;top:4px}.json-toggle:hover{color:#007acc;border-color:#007acc;background:#007acc0d}.json-bracket,.json-closing-bracket{display:inline-block}.json-closing-bracket{margin-left:18px}.json-key{color:#922}.json-viewer-dark .json-key{color:#9cdcfe}.json-value.string{color:#0b7500}.json-value.number{color:#1a01cc}.json-value.boolean{color:#aa0d91}.json-value.null{color:#777}.json-viewer-dark .json-value.string{color:#ce9178}.json-viewer-dark .json-value.number{color:#b5cea8}.json-viewer-dark .json-value.boolean{color:#569cd6}.json-viewer-dark .json-value.null{color:gray}.json-node:hover{background:#0000000a;border-radius:4px}.json-viewer-dark .json-node:hover{background:#ffffff0f}.json-match{background-color:#ffff0059;border-radius:3px}.json-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid rgba(128,128,128,.15)}.json-toolbar-group,.json-search-group{display:flex;align-items:center;gap:4px}.json-toolbar button{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border-radius:4px;border:1px solid var(--mfm-primary);cursor:pointer;background:var(--mfm-bg);color:#555;transition:all .2s}.json-toolbar button:hover{background:#eee;border-color:#ccc;color:#000}.json-viewer-dark .json-toolbar button{background:#333;color:#bbb;border:1px solid #444}.json-viewer-dark .json-toolbar button:hover{background:#444;border-color:#555;color:#fff}.json-search-group{flex:1;max-width:200px}.json-toolbar input{flex:1;font-size:12px;height:28px;padding:0 8px;border-radius:4px;border:1px solid var(--mfm-primary);outline:none}.json-viewer-dark .json-toolbar input{background:#252525;color:#ddd;border:1px solid #444}.json-viewer::-webkit-scrollbar{width:8px;height:8px}.json-viewer::-webkit-scrollbar-thumb{background:#80808066;border-radius:4px}.json-viewer::-webkit-scrollbar-thumb:hover{background:#80808099}.mfm-status.rule{color:var(--mfm-info)}.mfm-mod-pill{font-size:.7rem;color:var(--mfm-primary);background:#3b82f61a;padding:2px 6px;border-radius:10px;font-weight:500}.mfm-mapping-list-activity{padding:0;max-height:468px;overflow-y:scroll}.mfm-mapping-list-activity .mfm-spinner{display:flex;justify-content:center;margin:10px auto}.mfm-empty{padding:32px;text-align:center;color:var(--mfm-text-dim);font-size:.9rem}.mfm-spinner{width:24px;height:24px;border:2px solid var(--mfm-border);border-top-color:var(--mfm-primary);border-radius:50%;animation:mfm-spin .8s linear infinite}@keyframes mfm-spin{to{transform:rotate(360deg)}}.mfm-rule-info{font-size:.7rem;color:var(--mfm-text-dim);margin-top:4px;padding-left:4px}.mfm-mocked-apis-activity{padding:0;height:468px;overflow-y:scroll}.mfm-other-apis-activity{padding:0;max-height:468px}.mfm-request-item{display:flex;flex-direction:column;padding:12px 16px;border-bottom:1px solid var(--mfm-border);cursor:pointer;background:var(--mfm-bg);transition:background-color .2s ease}.mfm-request-item:hover{background:var(--mfm-hover)}.mfm-request-item.active{background:var(--mfm-active-bg)}.mfm-request-header{display:flex;justify-content:space-between;align-items:center}.mfm-flex-row{display:flex;align-items:center;gap:8px}.mfm-method{font-size:.75rem;font-weight:700;min-width:40px}.mfm-status{font-size:.8rem;margin-left:8px}.mfm-status.success{color:var(--mfm-success)}.mfm-status.error{color:var(--mfm-error)}.mfm-status.pending{color:var(--mfm-text-dim)}.mfm-url{font-size:.85rem;color:var(--mfm-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.4}.mfm-dropdown{position:relative;display:inline-block}.mfm-dropdown-content{display:none;position:absolute;right:0;top:100%;background-color:var(--mfm-bg);min-width:160px;box-shadow:0 4px 12px #00000026;z-index:1000;border:1px solid var(--mfm-border);border-radius:6px;overflow:hidden;margin-top:4px}.mfm-dropdown-content button{color:var(--mfm-text);padding:10px 16px;text-decoration:none;display:block;width:100%;text-align:left;background:none;border:none;cursor:pointer;font-size:.85rem;transition:background .1s}.mfm-dropdown-content button:hover{background-color:var(--mfm-hover)}.mfm-btn-icon{background:none;border:none;padding:4px;cursor:pointer;color:var(--mfm-text-dim);border-radius:4px;display:flex;align-items:center;justify-content:center}.mfm-btn-icon:hover{background:var(--mfm-hover);color:var(--mfm-text)}.mfm-token-form{padding:24px;text-align:center;max-width:400px;margin:0 auto;width:100%;box-sizing:border-box}.mfm-token-container{display:flex;flex-direction:column;align-items:center;padding:16px}.mfm-token-header{position:absolute;right:0;top:0}.mfm-token-logo{margin-bottom:16px;height:25px}.mfm-token-title{margin:0 0 8px;font-size:1.25rem;font-weight:600;color:var(--mfm-text)}.mfm-token-desc{color:var(--mfm-text-dim);font-size:.9rem;margin-bottom:24px;line-height:1.5}.mfm-token-input{text-align:center;height:44px;font-size:1rem;width:100%;border:1px solid var(--mfm-border);border-radius:6px;background:var(--mfm-input-bg);color:var(--mfm-text);padding:0 12px;outline:none;transition:all .2s}.mfm-token-input:focus{border-color:var(--mfm-primary);box-shadow:0 0 0 2px #3b82f633}.mfm-token-error{color:var(--mfm-error);font-size:.8rem;margin-top:8px;display:none;min-height:20px}.mfm-token-submit{margin-top:16px;width:100%;height:44px;background:var(--mfm-primary);color:#fff;border:none;border-radius:6px;font-size:.95rem;font-weight:500;cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center}.mfm-token-submit:hover{background:var(--mfm-primary-hover)}.mfm-token-submit:disabled{opacity:.7;cursor:not-allowed}:root{--mfm-primary: #2563eb;--mfm-primary-hover: #1d4ed8;--mfm-bg: #ffffff;--mfm-surface: #f8fafc;--mfm-surface-bright: #f1f5f9;--mfm-text: #0f172a;--mfm-text-dim: #64748b;--mfm-border: #e2e8f0;--mfm-success: #10b981;--mfm-error: #ef4444;--mfm-warning: #f59e0b;--mfm-radius: 8px;--mfm-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--mfm-shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--mfm-transition: all .15s ease-in-out}#mfm-root{position:fixed;bottom:24px;right:24px;z-index:999999;font-family:Inter,-apple-system,system-ui,sans-serif;color:var(--mfm-text);-webkit-user-select:none;user-select:none;box-sizing:border-box}#mfm-root *{box-sizing:border-box}.mfm-widget-toggle{display:flex;align-items:center;background:#fff;padding:6px;border-radius:9999px;box-shadow:var(--mfm-shadow-lg);border:1px solid var(--mfm-border);gap:2px;cursor:pointer;transition:var(--mfm-transition)}.mfm-widget-toggle.hidden{display:none!important}.mfm-toggle-section{padding:6px;border-radius:50%;display:flex;align-items:center;justify-content:center;transition:var(--mfm-transition)}.mfm-toggle-section:hover{background:var(--mfm-surface-bright)}.mfm-toggle-logo img{width:32px;height:32px}.mfm-toggle-divider{width:1px;height:24px;background:var(--mfm-border);margin:0 4px}.mfm-main-container{position:fixed;bottom:24px;right:24px;width:370px;height:650px;background:var(--mfm-bg);border:1px solid var(--mfm-border);border-radius:var(--mfm-radius);box-shadow:var(--mfm-shadow-lg);display:flex;flex-direction:column;overflow:hidden;transition:var(--mfm-transition);transform-origin:bottom right}.mfm-main-container.hidden{opacity:0;transform:scale(.95) translateY(20px);pointer-events:none}.mfm-header{padding:12px 16px;margin-bottom:5px;background:#fff;display:flex;align-items:center;justify-content:space-between}.mfm-logo img{height:25px;width:auto}.mfm-tabs-container{flex:1;display:flex;flex-direction:column;overflow:hidden}.mfm-tabs-nav{display:flex;padding:0 16px;background:#fff;border-bottom:1px solid var(--mfm-border);gap:4px}.mfm-tab-btn{padding:10px 16px;background:transparent;border:1px solid transparent;border-bottom:none;color:var(--mfm-text-dim);cursor:pointer;font-size:.9rem;font-weight:500;margin-bottom:-1px;border-top-left-radius:4px;border-top-right-radius:4px;transition:var(--mfm-transition)}.mfm-tab-btn:hover{color:var(--mfm-text);background:var(--mfm-surface)}.mfm-tab-btn.active{color:var(--mfm-primary);background:#fff;border-color:var(--mfm-border);border-bottom:1px solid white;font-weight:700}.mfm-tab-toolbar{padding:12px 16px;border-bottom:1px solid var(--mfm-border);display:flex;flex-direction:column;gap:8px}.mfm-toolbar-row{display:flex;gap:8px;align-items:center}.mfm-input{height:36px;width:100%;padding:0 12px;border:1px solid var(--mfm-border);border-radius:6px;font-size:.875rem;outline:none}.mfm-input:focus{border-color:var(--mfm-primary);box-shadow:0 0 0 2px #2563eb1a}.mfm-btn-outline,.mfm-btn-icon{height:36px;padding:0 12px;background:transparent!important;border:none!important;border-radius:6px;font-size:.875rem;font-weight:500;cursor:pointer;color:var(--mfm-text-dim);transition:var(--mfm-transition);display:flex;align-items:center;justify-content:center}.back-btn{padding:0}.mfm-btn-outline:hover,.mfm-btn-icon:hover{background:var(--mfm-surface-bright)!important;color:var(--mfm-text)}.mfm-preserve-logs{display:flex;align-items:center;gap:1px;font-size:.75rem;color:var(--mfm-text-dim);cursor:pointer}.mfm-preserve-logs input{-webkit-appearance:auto;-moz-appearance:auto;appearance:auto}.mfm-tab-content{flex:1;background:#fff;height:468px;overflow-y:scroll}.mfm-list{display:flex;flex-direction:column;max-height:460px;overflow-y:scroll}.mfm-empty{padding:60px 20px;text-align:center;color:var(--mfm-text-dim);font-size:.875rem}.mfm-request-item{padding:6px 16px;border-bottom:1px solid var(--mfm-border);cursor:pointer;transition:var(--mfm-transition)}.mfm-request-item.active{background:#eff6ff;border-left:3px solid var(--mfm-primary)}.mfm-request-item:hover{background:var(--mfm-surface)}.mfm-request-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:4px}.mfm-method{font-size:.7rem;font-weight:700;padding:2px 6px;border-radius:4px;text-transform:uppercase}.mfm-method.get{color:#2563eb;background:#eff6ff}.mfm-method.post{color:#16a34a;background:#f0fdf4}.mfm-method.put{color:#d97706;background:#fffbeb}.mfm-method.delete{color:#dc2626;background:#fef2f2}.mfm-method.rule{color:#7c3aed;background:#f5f3ff}.mfm-status{font-size:.75rem;font-weight:600}.mfm-status.rule{color:#8b5cf6;background:#8b5cf61a}.mfm-status.success{color:#16a34a}.mfm-status.error{color:#dc2626}.mfm-status.pending{color:#64748b}.mfm-url{font-size:.8125rem;color:var(--mfm-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mfm-bottomsheet{position:absolute;top:60px;left:0;right:0;bottom:0;background:#fff;z-index:1100;display:flex;flex-direction:column;transform:translate(100%);transition:transform .25s ease-in-out}.mfm-bottomsheet.active{transform:translate(0)}.mfm-bottomsheet-header{padding:12px 16px;border-bottom:1px solid var(--mfm-border);display:flex;align-items:center;gap:5px}.mfm-bottomsheet-content{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column}.mfm-detail-tabs{display:flex;border-bottom:1px solid var(--mfm-border);margin:16px -16px;padding:0 16px;gap:8px}.mfm-detail-tab-btn{padding:8px 12px;background:transparent;border:none;border-bottom:2px solid transparent;color:var(--mfm-text-dim);font-size:.8rem;font-weight:600;cursor:pointer;transition:var(--mfm-transition)}.mfm-detail-tab-btn:hover{color:var(--mfm-text)}.mfm-detail-tab-btn.active{color:var(--mfm-primary);border-bottom-color:var(--mfm-primary)}.mfm-detail-body{flex:1}.mfm-tab-content::-webkit-scrollbar,.mfm-bottomsheet-content::-webkit-scrollbar{width:8px}.mfm-tab-content::-webkit-scrollbar-track,.mfm-bottomsheet-content::-webkit-scrollbar-track{background:transparent}.mfm-tab-content::-webkit-scrollbar-thumb,.mfm-bottomsheet-content::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:4px;border:2px solid white}.mfm-tab-content::-webkit-scrollbar-thumb:hover,.mfm-bottomsheet-content::-webkit-scrollbar-thumb:hover{background:#94a3b8}.mfm-detail-section{margin-bottom:24px}.mfm-detail-title{font-size:.75rem;font-weight:600;text-transform:uppercase;color:var(--mfm-text-dim);margin-bottom:8px;display:flex;justify-content:space-between}.mfm-detail-content{background:var(--mfm-bg);padding:12px;border-radius:6px;font-family:JetBrains Mono,Menlo,monospace;font-size:.8rem;border:1px solid var(--mfm-primary);word-break:break-all;max-height:370px;overflow-y:auto}.mfm-copy-btn{background:var(--mfm-primary);border:none;color:#fff;padding:4px 8px;border-radius:4px;font-size:.7rem;cursor:pointer;font-weight:600}.mfm-dropdown{position:relative}.mfm-dropdown-content{display:none;position:absolute;top:100%;right:0;background:#fff;min-width:140px;box-shadow:var(--mfm-shadow-lg);border:1px solid var(--mfm-border);border-radius:8px;z-index:1000;overflow:hidden}.mfm-dropdown-content.show{display:block}.mfm-dropdown-content button{width:100%;padding:10px 16px;text-align:left;background:transparent;border:none;font-size:.8125rem;color:var(--mfm-text);cursor:pointer}.mfm-dropdown-content button:hover{background:var(--mfm-surface)}.mfm-btn-primary{background:var(--mfm-primary);color:#fff;border:none;border-radius:8px;padding:12px 24px;font-weight:600;cursor:pointer;transition:var(--mfm-transition)}.mfm-btn-primary:hover{background:var(--mfm-primary-hover)}.mfm-header-actions{display:flex;align-items:center}.mfm-switch{position:relative;display:inline-block;width:32px;height:20px;margin-right:12px}.mfm-switch input{opacity:0;width:0;height:0}.mfm-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#cbd5e1;transition:.4s;border-radius:34px}.mfm-slider:before{position:absolute;content:"";height:16px;width:16px;left:2px;bottom:2px;background-color:#fff;transition:.4s;border-radius:50%}input:checked+.mfm-slider{background-color:var(--mfm-primary)}input:checked+.mfm-slider:before{transform:translate(12px)}.mfm-spinner{width:14px;height:14px;border:2px solid #cbd5e1;border-bottom-color:var(--mfm-primary);border-radius:50%;display:inline-block;box-sizing:border-box;animation:mfm-rotation 1s linear infinite}@keyframes mfm-rotation{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.mfm-request-item.pending-item{cursor:default;opacity:.8}.mfm-snackbar{visibility:hidden;min-width:250px;background-color:#333;color:#fff;text-align:center;border-radius:8px;padding:12px;position:fixed;z-index:2000;left:50%;bottom:30px;transform:translate(-50%);font-size:.9rem;box-shadow:0 4px 6px #0000001a;opacity:0;transition:opacity .3s,bottom .3s}.mfm-snackbar.show{visibility:visible;opacity:1;bottom:50px}.clear-btn svg{color:var(--mfm-text-dim)}')),document.head.appendChild(e)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}}();const o=JSON.parse(sessionStorage.getItem("MFM_SAVED_REQUESTS")||"[]").filter((e=>{var t;return!((null==(t=e.request)?void 0:t.url)||"").includes("/3f4eae522b")})),r=JSON.parse(localStorage.getItem("MFM_CONFIG")||"{}"),s={state:{enabled:!0,isInterceptEnabled:"false"!==sessionStorage.getItem("MFM_IS_INTERCEPT_ENABLED"),isOpen:r.isOpen||!1,token:localStorage.getItem("MFM_TOKEN")||null,isTokenValidating:!1,isTokenLoading:!1,mappings:{apis:[],rules:[]},isMappingsLoading:!1,requests:o,ui:{selectedTab:"MOCKED",isDetailOpen:r.isDetailOpen||!1,selectedRequestId:r.selectedRequestId||null,selectedRule:r.selectedRule||null,detailTab:r.detailTab||"HEADERS",tokenError:null,tabConfigs:{MAPPINGS:{searchText:""},MOCKED:{searchText:"",isPreserveLogs:"true"===localStorage.getItem("MFM_PRESERVE_LOGS_MOCKED")},OTHER:{searchText:"",isPreserveLogs:"true"===localStorage.getItem("MFM_PRESERVE_LOGS_OTHER")}}}},listeners:[],subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter((t=>t!==e))}},notify(){this.listeners.forEach((e=>e(this.state))),document.dispatchEvent(new CustomEvent("MFM_STATE_CHANGE",{detail:this.state})),localStorage.setItem("MFM_CONFIG",JSON.stringify({isOpen:this.state.isOpen,selectedRequestId:this.state.ui.selectedRequestId,isDetailOpen:this.state.ui.isDetailOpen,selectedRule:this.state.ui.selectedRule,detailTab:this.state.ui.detailTab}))},update(e,t){const n=e.split(".");let o=this.state;for(let e=0;e<n.length-1;e++)o=o[n[e]];o[n[n.length-1]]=t,this.notify()},set(e,t){this.state[e]=t,this.notify()}},i=new class{constructor(){this.level=3}setLevel(e){this.level=e}postLog(e,t){if(window&&window.postMessage){const n=t.map((e=>{try{return"object"==typeof e?e:String(e)}catch(e){return"[Unserializable]"}}));window.postMessage({source:"mfm-widget-logger",type:e,payload:n},"*")}}info(...e){this.level>=1&&(console.log("[MFM Info]",...e),this.postLog("MFM_LOG_INFO",e))}warn(...e){this.level>=2&&(console.warn("[MFM Warn]",...e),this.postLog("MFM_LOG_WARN",e))}error(...e){this.level>=3&&(console.error("[MFM Error]",...e),this.postLog("MFM_LOG_ERROR",e))}};let a=[];const d={toggleWidget(){s.update("isOpen",!s.state.isOpen)},setTab(e){s.update("ui.selectedTab",e)},deleteToken(){i.warn("Deleting Client Token"),s.update("token",null),s.update("isTokenValidating",!1),s.update("isTokenLoading",!1),s.update("ui.tokenError",null),d.closeDetails(),s.set("requests",[]),this.clearQueue(),sessionStorage.removeItem("MFM_SAVED_REQUESTS"),localStorage.removeItem("MFM_TOKEN"),window.postMessage({type:"MFM_DEL_CLIENT_TOKEN"},"*")},submitToken(e){e?(s.update("ui.tokenError",null),s.update("isTokenValidating",!0),s.update("isTokenLoading",!0),localStorage.setItem("MFM_TOKEN_TEMP",e),window.postMessage({type:"MFM_SUBMIT_TOKEN",payload:{token:e}},"*")):s.update("ui.tokenError","Token is required")},reloadMappings(){i.info("Reloading Mappings"),s.update("isMappingsLoading",!0),window.postMessage({type:"MFM_REQ_MAPPINGS"},"*")},toggleInterception(){const e=!s.state.isInterceptEnabled;i.info("Toggling Interception:",e),s.update("isInterceptEnabled",e),sessionStorage.setItem("MFM_IS_INTERCEPT_ENABLED",e),window.postMessage({type:"MFM_TOGGLE_INTERCEPTION",payload:{enabled:e}},"*")},addRequest(e){var t,n,o;if(((null==(t=e.request)?void 0:t.url)||"").includes("/3f4eae522b"))return;if(s.state.isTokenValidating)return i.info("Queuing request during token validation",e.requestId),void a.push(e);let r=[...s.state.requests];const d=r.findIndex((t=>t.requestId===e.requestId));if(d>-1){const t=r[d];r[d]={...t,...e,rule:e.rule||t.rule}}else r.push(e);r.length>100&&(r=r.slice(r.length-100)),s.set("requests",r);const l=null==(n=s.state.ui.tabConfigs.MOCKED)?void 0:n.isPreserveLogs,c=null==(o=s.state.ui.tabConfigs.OTHER)?void 0:o.isPreserveLogs,m=r.filter((e=>{const t="MOCKED"===e.interceptionType;return t&&l||!t&&c}));m.length>0?sessionStorage.setItem("MFM_SAVED_REQUESTS",JSON.stringify(m)):sessionStorage.removeItem("MFM_SAVED_REQUESTS")},clearRequests(){const e=s.state.ui.selectedTab,t=s.state.requests.filter((t=>("MOCKED"===t.interceptionType?"MOCKED":"OTHER")!==e));s.set("requests",t),sessionStorage.setItem("MFM_SAVED_REQUESTS",JSON.stringify(t))},setPreserveLogs(e){var t,n;const o=s.state.ui.selectedTab;if("MAPPINGS"===o)return;s.update(`ui.tabConfigs.${o}.isPreserveLogs`,e),localStorage.setItem(`MFM_PRESERVE_LOGS_${o}`,e);const r=null==(t=s.state.ui.tabConfigs.MOCKED)?void 0:t.isPreserveLogs,i=null==(n=s.state.ui.tabConfigs.OTHER)?void 0:n.isPreserveLogs,a=s.state.requests.filter((e=>{const t="MOCKED"===e.interceptionType;return t&&r||!t&&i}));a.length>0?sessionStorage.setItem("MFM_SAVED_REQUESTS",JSON.stringify(a)):sessionStorage.removeItem("MFM_SAVED_REQUESTS")},setSearchText(e){const t=s.state.ui.selectedTab;s.update(`ui.tabConfigs.${t}.searchText`,e)},selectRequest(e){s.state.ui.selectedRequestId=e,s.state.ui.selectedRule=null,s.state.ui.isDetailOpen=!0,s.state.ui.detailTab="HEADERS",s.notify()},selectRule(e){s.state.ui.selectedRule=e,s.state.ui.selectedRequestId=null,s.state.ui.isDetailOpen=!0,s.state.ui.detailTab="HEADERS",s.notify()},minimizeDetails(){s.state.ui.isDetailOpen=!1,s.notify()},closeDetails(){s.state.ui.isDetailOpen=!1,s.state.ui.selectedRequestId=null,s.state.ui.selectedRule=null,s.notify()},setDetailTab(e){s.update("ui.detailTab",e)},flushQueue(){i.info("Flushing request queue",a.length);const e=[...a];a=[],e.forEach((e=>this.addRequest(e)))},clearQueue(){i.warn("Clearing request queue"),a=[]}},l="https://www.mockforme.com/assets/images/logo.png",c='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg>',m='\n<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>\n';class u{constructor(e,t={}){if(!e)throw new Error("Container element required");this.container=e,this.options={expandLevel:t.expandLevel??1,theme:t.theme??"light",toolbar:t.toolbar??!0,searchable:t.searchable??!0},this.container.classList.add("json-viewer"),this.container.classList.add(`json-viewer-${this.options.theme}`),this.options.toolbar&&this._createToolbar(),this.treeContainer=document.createElement("div"),this.container.appendChild(this.treeContainer)}render(e){this.treeContainer.innerHTML="",this.root=this._createNode(e,null,0),this.treeContainer.appendChild(this.root)}_createNode(e,t=null,n=0){const o=document.createElement("div");if(o.className="json-node",null!==t){const e=document.createElement("span");e.className="json-key",e.textContent=`"${t}": `,o.appendChild(e)}if("object"==typeof e&&null!==e){const t=Array.isArray(e),r=n<this.options.expandLevel,s=document.createElement("span");s.className="json-toggle",s.textContent=r?"-":"+";const i=document.createElement("span");i.className="json-bracket",i.textContent=t?"[":"{";const a=document.createElement("div");a.className="json-children",a.style.display=r?"block":"none",s.addEventListener("click",(()=>{const e="none"===a.style.display;a.style.display=e?"block":"none",s.textContent=e?"-":"+"})),o.appendChild(s),o.appendChild(i),Object.entries(e).forEach((([e,t])=>{const o=this._createNode(t,e,n+1);a.appendChild(o)})),o.appendChild(a);const d=document.createElement("div");d.className="json-closing-bracket",d.textContent=t?"]":"}",o.appendChild(d)}else{const t=document.createElement("span");t.className="json-value "+typeof e,t.textContent="string"==typeof e?`"${e}"`:e,o.appendChild(t)}return o}_createToolbar(){this.toolbar=document.createElement("div"),this.toolbar.className="json-toolbar";const e=document.createElement("div");e.className="json-toolbar-group";const t=document.createElement("button");t.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>',t.title="Expand All",t.onclick=()=>this.expandAll();const n=document.createElement("button");if(n.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line></svg>',n.title="Collapse All",n.onclick=()=>this.collapseAll(),e.appendChild(t),e.appendChild(n),this.toolbar.appendChild(e),this.options.searchable){const e=document.createElement("div");e.className="json-search-group";const t=document.createElement("input");t.placeholder="Search...",t.oninput=e=>this.search(e.target.value);const n=document.createElement("button");n.innerHTML=c,n.title="Clear Search",n.onclick=()=>{t.value="",this.clearSearch()},e.appendChild(t),e.appendChild(n),this.toolbar.appendChild(e)}this.container.appendChild(this.toolbar)}expandAll(){this.treeContainer.querySelectorAll(".json-children").forEach((e=>e.style.display="block")),this.treeContainer.querySelectorAll(".json-toggle").forEach((e=>e.textContent="-"))}collapseAll(){this.treeContainer.querySelectorAll(".json-children").forEach((e=>e.style.display="none")),this.treeContainer.querySelectorAll(".json-toggle").forEach((e=>e.textContent="+"))}search(e){if(this.clearSearch(),!e)return;const t=new RegExp(e,"i");this.treeContainer.querySelectorAll(".json-node").forEach((e=>{if(t.test(e.textContent)){e.classList.add("json-match");let t=e.parentElement;for(;t&&t!==this.treeContainer;){if(t.classList.contains("json-children")){t.style.display="block";const e=t.parentElement.querySelector(":scope > .json-toggle");e&&(e.textContent="-")}t=t.parentElement}}}))}clearSearch(){this.treeContainer.querySelectorAll(".json-match").forEach((e=>e.classList.remove("json-match")))}}class p{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-rule-list",this.init()}init(){this.parent.appendChild(this.element),this.attachEvents()}attachEvents(){this.element.onclick=e=>{const t=e.target.closest(".mfm-dots-btn");if(t)return e.stopPropagation(),this.closeAllDropdowns(),void t.nextElementSibling.classList.toggle("show");const n=e.target.closest("[data-action]");if(n){e.stopPropagation();const t=n.dataset.action,o=n.closest(".mfm-request-item").dataset.id;return this.handleAction(t,o),void n.parentElement.classList.remove("show")}const o=e.target.closest(".mfm-request-item");if(o){e.stopPropagation();const t=o.dataset.id,{rules:n}=s.state.mappings,r=n.find((e=>e.ruleName===t||e.condition===t));r&&d.selectRule(r)}}}closeAllDropdowns(){document.querySelectorAll(".mfm-dropdown-content.show").forEach((e=>e.classList.remove("show")))}handleAction(e,t){if("view-rule-details"===e){const{rules:e}=s.state.mappings,n=e.find((e=>e.ruleName===t||e.condition===t));n&&d.selectRule(n)}}render(e){this.element.innerHTML=e?e.map((e=>{var t,n,o;const r=null==(t=e.timingAction)?void 0:t.activeAction,i=null==(o=null==(n=e.timingAction)?void 0:n.actions)?void 0:o[r],a=i?`${i.value}s (${r.replace(/_/g," ")})`:e.type;let d=0;return e.modificationActions&&Object.values(e.modificationActions).forEach((e=>{e.enabled&&d++})),`\n <div class="mfm-request-item ${!s.state.ui.selectedRule||s.state.ui.selectedRule.ruleName!==(e.ruleName||e.condition)&&s.state.ui.selectedRule.condition!==(e.condition||e.ruleName)?"":"active"}" data-id="${e.ruleName||e.condition}" data-type="rule">\n <div class="mfm-request-header">\n <div class="mfm-flex-row">\n <span class="mfm-method rule">RULE</span>\n <span class="mfm-status rule">${a}</span>\n </div>\n \n <div class="mfm-dropdown" style="display: flex; align-items: center; gap: 8px;">\n ${d>0?`\n <span class="mfm-mod-pill">${d} Actions</span>\n `:""}\n \n <button class="mfm-btn-icon mfm-dots-btn">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>\n </button>\n <div class="mfm-dropdown-content">\n <button data-action="view-rule-details">View Modifications</button>\n </div>\n </div>\n </div>\n <span class="mfm-url" title="${e.condition||e.ruleName}">${e.condition||e.ruleName}</span>\n </div>\n `})).join(""):""}}class f{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-apis-list",this.init()}init(){this.parent.appendChild(this.element)}render(e){e&&0!==e.length?this.element.innerHTML=e.map((e=>`\n <div class="mfm-request-item" data-id="${e.url}" data-type="api">\n <div class="mfm-request-header">\n <div class="mfm-flex-row">\n <span class="mfm-method ${(e.method||"").toLowerCase()}">${e.method||"REQ"}</span>\n <span class="mfm-status success">Active</span>\n </div>\n </div>\n <span class="mfm-url" title="${e.url}">${e.url}</span>\n </div>\n `)).join(""):this.element.innerHTML=""}}class h{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-mapping-list-activity",this.ruleListView=new p(this.element),this.apisListView=new f(this.element),this.unsubscribe=null,this.init()}init(){this.parent.appendChild(this.element),this.unsubscribe=s.subscribe((()=>{"MAPPINGS"===s.state.ui.selectedTab&&this.render()})),this.render()}render(){if(s.state.isMappingsLoading)return this.element.innerHTML='<div class="mfm-spinner"></div>',this.ruleListView.element.style.display="none",void(this.apisListView.element.style.display="none");const{apis:e,rules:t}=function(){const{apis:e,rules:t}=s.state.mappings,n=(s.state.ui.tabConfigs.MAPPINGS.searchText||"").toLowerCase();return{apis:e.filter((e=>(e.url||"").toLowerCase().includes(n))),rules:t.filter((e=>(e.ruleName||"").toLowerCase().includes(n)||(e.condition||"").toLowerCase().includes(n)))}}();if(0===e.length&&0===t.length)return this.element.innerHTML='<div class="mfm-empty">No mappings found</div>',this.ruleListView.element.style.display="none",void(this.apisListView.element.style.display="none");!s.state.isMappingsLoading&&(e.length>0||t.length>0)?(this.element.contains(this.ruleListView.element)||(this.element.innerHTML="",this.element.appendChild(this.ruleListView.element),this.element.appendChild(this.apisListView.element)),this.ruleListView.element.style.display="block",this.apisListView.element.style.display="block",this.ruleListView.render(t),this.apisListView.render(e)):s.state.isMappingsLoading?this.element.innerHTML='<div class="mfm-spinner"></div>':this.element.innerHTML='<div class="mfm-empty">No mappings found</div>'}destroy(){this.unsubscribe&&this.unsubscribe(),this.element.remove()}}class g{static render(e){var t,n,o,r,i,a;const d=e.rule?{action:e.rule.action||(null==(t=e.rule.timingAction)?void 0:t.activeAction),config:e.rule.config||(null==(r=null==(n=e.rule.timingAction)?void 0:n.actions)?void 0:r[null==(o=e.rule.timingAction)?void 0:o.activeAction])}:null,l=void 0===(null==(i=e.response)?void 0:i.statusCode),c=l?"Pending":e.response.statusCode,m=0===c?"Error":c,u=l?"pending":!l&&c>=200&&c<300?"success":!l&&(0===c||c>=400)?"error":"";return`\n <div class="mfm-request-item ${s.state.ui.selectedRequestId===e.requestId?"active":""} ${l?"pending-item":""}" data-id="${e.requestId}" data-type="request">\n <div class="mfm-request-header">\n <div class="mfm-flex-row">\n <span class="mfm-method ${(e.request.method||"").toLowerCase()}">${e.request.method}</span>\n <span class="mfm-status ${u}">\n ${l?'<span class="mfm-spinner"></span>':m}\n </span>\n </div>\n \n <div class="mfm-dropdown" style="display: flex; align-items: center; gap: 8px;">\n <button class="mfm-btn-icon mfm-dots-btn">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>\n </button>\n <div class="mfm-dropdown-content">\n <button data-action="copy-curl">Copy as cURL</button>\n <button data-action="copy-fetch">Copy as Fetch</button>\n <button data-action="copy-xhr">Copy as XHR</button>\n </div>\n </div>\n </div>\n <span class="mfm-url" title="${e.request.url}">${e.request.url}</span>\n ${d&&d.action?`\n <div class="mfm-rule-info">\n ${(null==(a=d.config)?void 0:a.value)||0}s (${d.action.replace(/_/g," ")})\n </div>\n `:""}\n </div>\n `}}let b=class{static render(e){var t;const n=void 0===(null==(t=e.response)?void 0:t.statusCode),o=n?"Pending":e.response.statusCode,r=0===o?"Error":o,i=n?"pending":!n&&o>=200&&o<300?"success":!n&&(0===o||o>=400)?"error":"";return`\n <div class="mfm-request-item ${s.state.ui.selectedRequestId===e.requestId?"active":""} ${n?"pending-item":""}" data-id="${e.requestId}" data-type="request">\n <div class="mfm-request-header">\n <div class="mfm-flex-row">\n <span class="mfm-method ${(e.request.method||"").toLowerCase()}">${e.request.method}</span>\n <span class="mfm-status ${i}">\n ${n?'<span class="mfm-spinner"></span>':r}\n </span>\n </div>\n <div class="mfm-dropdown" style="display: flex; align-items: center; gap: 8px;">\n <button class="mfm-btn-icon mfm-dots-btn">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>\n </button>\n <div class="mfm-dropdown-content">\n <button data-action="copy-curl">Copy as cURL</button>\n <button data-action="copy-fetch">Copy as Fetch</button>\n <button data-action="copy-xhr">Copy as XHR</button>\n </div>\n </div>\n </div>\n <span class="mfm-url" title="${e.request.url}">${e.request.url}</span>\n </div>\n `}};class y{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-mocked-apis-activity",this.unsubscribe=null,this.init()}init(){this.parent.appendChild(this.element),this.attachEvents(),this.unsubscribe=s.subscribe((()=>{"MOCKED"===s.state.ui.selectedTab&&this.render()})),this.render()}attachEvents(){this.element.onclick=e=>{const t=e.target.closest(".mfm-dots-btn");if(t)return e.stopPropagation(),document.querySelectorAll(".mfm-dropdown-content.show").forEach((e=>e.classList.remove("show"))),void t.nextElementSibling.classList.toggle("show");const n=e.target.closest("[data-action]");if(n){e.stopPropagation();const t=n.dataset.action,o=n.closest(".mfm-request-item").dataset.id;return this.handleAction(t,o),void n.parentElement.classList.remove("show")}const o=e.target.closest(".mfm-request-item");if(o){if(o.classList.contains("pending-item"))return;e.stopPropagation();const t=o.dataset.id;d.selectRequest(t)}}}handleAction(e,t){const n=s.state.requests.find((e=>e.requestId===t));if(!n)return;let o="";"copy-curl"===e?o=`curl '${n.request.url}' -X ${n.request.method}`:"copy-fetch"===e?o=`fetch('${n.request.url}', { method: '${n.request.method}' })`:"copy-xhr"===e&&(o=`const xhr = new XMLHttpRequest(); xhr.open('${n.request.method}', '${n.request.url}'); xhr.send();`),o&&navigator.clipboard.writeText(o)}render(){const e=function(){const e=(s.state.ui.tabConfigs.MOCKED.searchText||"").toLowerCase();return s.state.requests.filter((t=>{var n,o;return"MOCKED"===t.interceptionType&&(((null==(n=t.request)?void 0:n.url)||"").toLowerCase().includes(e)||((null==(o=t.rule)?void 0:o.ruleName)||"").toLowerCase().includes(e))}))}();e&&0!==e.length?this.element.innerHTML=e.map((e=>e.rule?g.render(e):b.render(e))).join(""):this.element.innerHTML='<div class="mfm-empty">No requests found</div>'}destroy(){this.unsubscribe&&this.unsubscribe(),this.element.remove()}}class v{static render(e){var t;const n=void 0===(null==(t=e.response)?void 0:t.statusCode),o=n?"Pending":e.response.statusCode,r=0===o?"Error":o,i=n?"pending":!n&&o>=200&&o<300?"success":!n&&(0===o||o>=400)?"error":"";return`\n <div class="mfm-request-item ${s.state.ui.selectedRequestId===e.requestId?"active":""} ${n?"pending-item":""}" data-id="${e.requestId}" data-type="request">\n <div class="mfm-request-header">\n <div class="mfm-flex-row">\n <span class="mfm-method ${(e.request.method||"").toLowerCase()}">${e.request.method}</span>\n <span class="mfm-status ${i}">\n ${n?'<span class="mfm-spinner"></span>':r}\n </span>\n </div>\n <div class="mfm-dropdown" style="display: flex; align-items: center; gap: 8px;">\n <button class="mfm-btn-icon mfm-dots-btn">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>\n </button>\n <div class="mfm-dropdown-content">\n <button data-action="copy-curl">Copy as cURL</button>\n <button data-action="copy-fetch">Copy as Fetch</button>\n <button data-action="copy-xhr">Copy as XHR</button>\n </div>\n </div>\n </div>\n <span class="mfm-url" title="${e.request.url}">${e.request.url}</span>\n </div>\n `}}class x{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-other-apis-activity",this.unsubscribe=null,this.init()}init(){this.parent.appendChild(this.element),this.attachEvents(),this.unsubscribe=s.subscribe((()=>{"OTHER"===s.state.ui.selectedTab&&this.render()})),this.render()}attachEvents(){this.element.onclick=e=>{const t=e.target.closest(".mfm-dots-btn");if(t)return e.stopPropagation(),document.querySelectorAll(".mfm-dropdown-content.show").forEach((e=>e.classList.remove("show"))),void t.nextElementSibling.classList.toggle("show");const n=e.target.closest("[data-action]");if(n){e.stopPropagation();const t=n.dataset.action,o=n.closest(".mfm-request-item").dataset.id;return this.handleAction(t,o),void n.parentElement.classList.remove("show")}const o=e.target.closest(".mfm-request-item");if(o){if(o.classList.contains("pending-item"))return;e.stopPropagation();const t=o.dataset.id;d.selectRequest(t)}}}handleAction(e,t){const n=s.state.requests.find((e=>e.requestId===t));if(!n)return;let o="";"copy-curl"===e?o=`curl '${n.request.url}' -X ${n.request.method}`:"copy-fetch"===e?o=`fetch('${n.request.url}', { method: '${n.request.method}' })`:"copy-xhr"===e&&(o=`const xhr = new XMLHttpRequest(); xhr.open('${n.request.method}', '${n.request.url}'); xhr.send();`),o&&navigator.clipboard.writeText(o)}render(){const e=function(){const e=(s.state.ui.tabConfigs.OTHER.searchText||"").toLowerCase();return s.state.requests.filter((t=>{var n;return"MOCKED"!==t.interceptionType&&((null==(n=t.request)?void 0:n.url)||"").toLowerCase().includes(e)}))}();e&&0!==e.length?this.element.innerHTML=e.map((e=>v.render(e))).join(""):this.element.innerHTML='<div class="mfm-empty">No requests found</div>'}destroy(){this.unsubscribe&&this.unsubscribe(),this.element.remove()}}class w{constructor(e){this.parent=e,this.element=document.createElement("div"),this.element.className="mfm-token-form",this.input=null,this.submitBtn=null,this.errorDisplay=null,this.unsubscribe=s.subscribe(this.render.bind(this)),this.init()}init(){this.renderStructure(),this.bindEvents(),this.render(s.state),this.parent.appendChild(this.element)}closeTokenForm(){d.toggleWidget()}renderStructure(){this.element.innerHTML=`\n <div class="mfm-token-header">\n <button class="mfm-btn-icon" id="mfm-close-token-form" title="Close Widget">\n ${m}\n </button>\n </div>\n <div class="mfm-token-container">\n <img src="${l}" alt="MockForMe Logo" class="mfm-token-logo">\n <h3 class="mfm-token-title">Welcome to MockForMe</h3>\n <p class="mfm-token-desc">\n Paste your token below to start mocking and intercepting API requests.\n </p>\n <input type="text" class="mfm-input mfm-token-input" placeholder="Enter Client Token...">\n <div class="mfm-token-error"></div>\n <button class="mfm-token-submit">\n Continue\n </button>\n </div>\n `,this.input=this.element.querySelector(".mfm-token-input"),this.submitBtn=this.element.querySelector(".mfm-token-submit"),this.errorDisplay=this.element.querySelector(".mfm-token-error"),this.closeBtn=this.element.querySelector("#mfm-close-token-form")}bindEvents(){this.input.oninput=()=>{s.state.ui.tokenError&&s.update("ui.tokenError",null)},this.submitBtn.onclick=()=>{const e=this.input.value.trim();e&&d.submitToken(e)},this.closeBtn.onclick=()=>{this.closeTokenForm()}}render(e){const{tokenError:t}=e.ui,{isTokenLoading:n}=e;t?(this.errorDisplay.textContent=t,this.errorDisplay.style.display="block",this.input.style.borderColor="var(--mfm-error)"):(this.errorDisplay.style.display="none",this.input.style.borderColor=""),n?(this.input.disabled=!0,this.submitBtn.disabled=!0,this.submitBtn.innerHTML='<div class="mfm-spinner"></div>'):(this.input.disabled=!1,this.submitBtn.disabled=!1,this.submitBtn.innerHTML="Continue")}destroy(){this.unsubscribe&&this.unsubscribe(),this.element.remove()}}function k(e,t=3e3){if(!document.body)return;let n=document.getElementById("mfm-snackbar");n||(n=document.createElement("div"),n.id="mfm-snackbar",n.className="mfm-snackbar",document.body.appendChild(n)),n.textContent=e,n.className="mfm-snackbar show",setTimeout((()=>{n.className=n.className.replace("show","")}),t)}const E='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path><polyline points="21 3 21 8 16 8"></polyline></svg>';function M(e){i.info("Initializing MockForMe Widget");let t=null;const n=e=>{if(!e)return;t=document.createElement("div"),t.id="mfm-root";const n=document.createElement("div");n.className="mfm-widget-toggle",n.innerHTML=`\n <div class="mfm-toggle-section mfm-toggle-reload" title="Reload Mappings">\n ${E}\n </div>\n <div class="mfm-toggle-divider"></div>\n <div class="mfm-toggle-section mfm-toggle-logo" title="MockForMe">\n <img src="https://ik.imagekit.io/mfm/static-collection/mfm-48x48.png" alt="Logo">\n </div>\n `;const o=document.createElement("div");o.className="mfm-main-container hidden",t.appendChild(n),t.appendChild(o),e.appendChild(t);const r=(e,n)=>{const o=t.getBoundingClientRect(),r=window.innerWidth,s=window.innerHeight,i=r-(o.width||60),a=s-(o.height||60),d=Math.max(0,Math.min(e,i)),l=Math.max(0,Math.min(n,a));return t.style.left=`${d}px`,t.style.top=`${l}px`,t.style.bottom="auto",t.style.right="auto",{x:d,y:l}},i=()=>{const e=JSON.parse(localStorage.getItem("MFM_POSITION")||"null");if(e&&void 0!==e.xPercent){const t=e.xPercent*window.innerWidth,n=e.yPercent*window.innerHeight;r(t,n)}};i();let a,p,f,g,b=!1;const v=e=>{const o="touchstart"===e.type?e.touches[0].clientX:e.clientX,r="touchstart"===e.type?e.touches[0].clientY:e.clientY;b=!0,a=o,p=r;const s=t.getBoundingClientRect();f=s.left,g=s.top,n.dataset.moved="false",document.addEventListener("mousemove",k),document.addEventListener("mouseup",M),document.addEventListener("touchmove",k,{passive:!1}),document.addEventListener("touchend",M),t.style.transition="none"},k=e=>{if(!b)return;"touchmove"===e.type&&e.cancelable&&e.preventDefault();const t="touchmove"===e.type?e.touches[0].clientX:e.clientX,o="touchmove"===e.type?e.touches[0].clientY:e.clientY,s=t-a,i=o-p;(Math.abs(s)>5||Math.abs(i)>5)&&(n.dataset.moved="true"),r(f+s,g+i)},M=()=>{if(!b)return;b=!1,document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",M),document.removeEventListener("touchmove",k),document.removeEventListener("touchend",M),t.style.transition="";const e=t.getBoundingClientRect();((e,t)=>{const n=e/window.innerWidth,o=t/window.innerHeight;localStorage.setItem("MFM_POSITION",JSON.stringify({xPercent:n,yPercent:o}))})(e.left,e.top)};n.addEventListener("mousedown",v),n.addEventListener("touchstart",v,{passive:!1}),window.addEventListener("resize",i),window.addEventListener("orientationchange",i),function(e){const t=document.createElement("div");t.className="mfm-header",t.innerHTML=`\n <div class="mfm-logo">\n <img src="${l}" height="32" alt="MockForMe Logo">\n </div>\n <div class="mfm-header-actions">\n <label class="mfm-switch" title="Toggle Mock Interception">\n <input type="checkbox" id="mfm-intercept-toggle" ${s.state.isInterceptEnabled?"checked":""}>\n <span class="mfm-slider"></span>\n </label>\n <button class="mfm-btn-icon" id="mfm-reload-header" title="Reload Mappings">\n \n<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-rotate-cw"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path><polyline points="21 3 21 8 16 8"></polyline></svg>\n\n </button>\n <button class="mfm-btn-icon" id="mfm-delete-token" title="Delete Token">\n \n<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>\n\n </button>\n <button class="mfm-btn-icon" id="mfm-close-widget" title="Close Widget">\n ${m}\n </button>\n </div>\n `,e.appendChild(t);const n=t.querySelector("#mfm-intercept-toggle");n.onchange=()=>{d.toggleInterception()};const o=t.querySelector("#mfm-reload-header");o.onclick=()=>{o.innerHTML='<div class="mfm-spinner"></div>',o.style.pointerEvents="none",d.reloadMappings()},t.querySelector("#mfm-delete-token").onclick=()=>{d.deleteToken()},t.querySelector("#mfm-close-widget").onclick=()=>{d.toggleWidget()},s.subscribe((e=>{n.checked=e.isInterceptEnabled}))}(o),new w(o),function(e){const t=document.createElement("div");t.className="mfm-tabs-container";const n=document.createElement("div");n.className="mfm-tabs-nav",[{id:"MAPPINGS",label:"Mappings"},{id:"MOCKED",label:"Mocked"},{id:"OTHER",label:"Others"}].forEach((e=>{const t=document.createElement("button");t.className="mfm-tab-btn "+(s.state.ui.selectedTab===e.id?"active":""),t.innerText=e.label,t.onclick=()=>{d.setTab(e.id)},t.dataset.tabId=e.id,n.appendChild(t)}));const o=document.createElement("div");o.className="mfm-tab-toolbar",o.innerHTML=`\n <div class="mfm-toolbar-row">\n <input type="text" class="mfm-input" id="mfm-search" placeholder="Search requests..." value="${s.state.ui.searchText}">\n <label class="mfm-preserve-logs">\n <input type="checkbox" id="mfm-preserve-check" ${s.state.ui.isPreserveLogs?"checked":""}>\n Preserve\n </label>\n <button class="mfm-btn-outline clear-btn" id="mfm-clear-btn" title="Clear requests">\n ${c}\n </button>\n </div>\n `;const r=document.createElement("div");r.className="mfm-tab-content",t.appendChild(n),t.appendChild(o),t.appendChild(r),e.appendChild(t);const i=new h(r),a=new y(r),l=new x(r),m=o.querySelector("#mfm-search"),u=o.querySelector("#mfm-clear-btn"),p=o.querySelector("#mfm-preserve-check");function f(){const e=s.state.ui.selectedTab,t=s.state.ui.tabConfigs[e];n.querySelectorAll(".mfm-tab-btn").forEach((t=>{t.classList.toggle("active",t.dataset.tabId===e)}));const r=(null==t?void 0:t.searchText)||"";m.value!==r&&(m.value=r);const d="MAPPINGS"===e;u.style.display=d?"none":"block",o.querySelector(".mfm-preserve-logs").style.display=d?"none":"flex",d||(p.checked=!!(null==t?void 0:t.isPreserveLogs)),i.element&&(i.element.style.display="MAPPINGS"===e?"block":"none"),a.element&&(a.element.style.display="MOCKED"===e?"block":"none"),l.element&&(l.element.style.display="OTHER"===e?"block":"none")}m.oninput=e=>{d.setSearchText(e.target.value)},u.onclick=()=>{d.clearRequests()},p.onchange=e=>{d.setPreserveLogs(e.target.checked)},f(),s.subscribe((e=>{f()}))}(o),function(e){const t=document.createElement("div");t.className="mfm-bottomsheet",t.id="mfm-details-sheet",t.innerHTML='\n <div class="mfm-bottomsheet-header" style="justify-content: flex-start; gap: 8px; padding-right: 12px;">\n <button class="mfm-btn-icon back-btn" id="mfm-close-sheet" title="Back">\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>\n </button>\n <div id="mfm-header-info" style="display: flex; align-items: baseline; gap: 6px; overflow: hidden; flex: 1; cursor: pointer;"></div>\n </div>\n <div class="mfm-bottomsheet-content"></div>\n ',e.appendChild(t);const n=t.querySelector("#mfm-close-sheet"),o=t.querySelector("#mfm-header-info");n.onclick=e=>{e.stopPropagation(),d.closeDetails()};let r=!1;function i(){var e,n,i,a,l,c;const{isDetailOpen:m,selectedRequestId:p,selectedRule:f,detailTab:h}=s.state.ui;if(!m||!p&&!f)return t.classList.remove("active"),void(r=!1);let g,b=!1;if(f){b=!0;const e=f,t={};e.modificationActions&&Object.entries(e.modificationActions).forEach((([e,n])=>{n.enabled&&(t[e]=n)})),g={requestId:`rule_${e.ruleName}`,interceptionType:"RULE",request:{method:"RULE",url:e.condition||e.ruleName,headers:e.modificationActions||{},body:t},response:{statusCode:e.type,body:e}}}else g=s.state.requests.find((e=>String(e.requestId)===String(p)));if(!g)return void d.closeDetails();const y=g.request.method||"REQ",v=b?(null==(e=g.response)?void 0:e.statusCode)||"RULE":void 0!==(null==(n=g.response)?void 0:n.statusCode)?g.response.statusCode:"Pending",x="Pending"===v,w="number"==typeof v,k=x?"pending":!x&&!b&&w&&v>=200&&v<300?"success":x||b||!(w&&(0===v||v>=400)||!w&&"Pending"!==v)?b?"rule":"":"error",E=g.request.url||"";let M=v;0===v&&(M="Error"),o.innerHTML=`\n <span class="mfm-method ${y.toLowerCase()}" style="flex-shrink: 0;">${y}</span>\n <span class="mfm-status ${k}" style="font-size: 0.8rem; flex-shrink: 0;">${M}</span>\n <span class="mfm-url-small" title="Click to toggle full URL" style="\n font-family: monospace; \n font-size: 0.75rem; \n color: var(--mfm-text-dim); \n overflow: hidden; \n text-overflow: ellipsis; \n white-space: ${r?"normal":"nowrap"};\n word-break: ${r?"break-all":"normal"};\n max-height: ${r?"60px":"2em"};\n overflow-y: ${r?"auto":"hidden"};\n flex: 1;\n ">${E}</span>\n `;const q=b?"Configs":"Headers",_=b?"Modifications":"Request",R=b?"Full Rule":"Response";if(t.querySelector(".mfm-bottomsheet-content").innerHTML=`\n <div class="mfm-detail-tabs" style="margin-top: 0;">\n <button class="mfm-detail-tab-btn ${"HEADERS"===h?"active":""}" data-tab="HEADERS">${q}</button>\n <button class="mfm-detail-tab-btn ${"REQ_BODY"===h?"active":""}" data-tab="REQ_BODY">${_}</button>\n <button class="mfm-detail-tab-btn ${"RES_BODY"===h?"active":""}" data-tab="RES_BODY">${R}</button>\n </div>\n\n <div class="mfm-detail-body">\n ${"HEADERS"===h?`\n <div class="mfm-detail-section">\n <div class="mfm-detail-title">${b?"Rule Configuration":"Request Headers"}</div>\n <div class="mfm-detail-content">\n <pre style="margin:0">${JSON.stringify(g.request.headers||{},null,2)}</pre>\n </div>\n </div>\n ${b?"":`\n <div class="mfm-detail-section" style="margin-top:16px">\n <div class="mfm-detail-title">Response Headers</div>\n <div class="mfm-detail-content">\n <pre style="margin:0">${JSON.stringify((null==(i=g.response)?void 0:i.headers)||{},null,2)}</pre>\n </div>\n </div>`}\n `:""}\n\n ${"REQ_BODY"===h?`\n <div class="mfm-detail-section">\n <div class="mfm-detail-title">${b?"Enabled Modifications":"Request Body"}</div>\n <div class="mfm-detail-content">\n <pre style="margin:0">${"string"==typeof g.request.body?g.request.body:JSON.stringify(g.request.body,null,2)}</pre>\n </div>\n </div>\n `:""}\n\n ${"RES_BODY"===h?`\n <div class="mfm-detail-section">\n <div class="mfm-detail-title">\n ${b?"Complete Rule Object":"Response Body"}\n <button class="mfm-copy-btn" id="mfm-copy-res">Copy</button>\n </div>\n <div class="mfm-detail-content" id="mfm-res-viewer">\n <pre style="margin:0">${"string"==typeof(null==(a=g.response)?void 0:a.body)?g.response.body:JSON.stringify((null==(l=g.response)?void 0:l.body)||{},null,2)}</pre>\n </div>\n </div>\n `:""}\n </div>\n `,"RES_BODY"===h&&(null==(c=g.response)?void 0:c.body))try{let e=g.response.body;if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}if("object"==typeof e&&null!==e){const n=t.querySelector("#mfm-res-viewer");n&&(n.innerHTML="",new u(n,{expandLevel:1,theme:"light",toolbar:!0,searchable:!0}).render(e))}}catch(e){console.error("Error rendering JSON viewer:",e)}t.querySelectorAll(".mfm-detail-tab-btn").forEach((e=>{e.onclick=()=>d.setDetailTab(e.dataset.tab)}));const T=t.querySelector("#mfm-copy-res");T&&(T.onclick=()=>{let e="";try{e="object"==typeof g.response.body?JSON.stringify(g.response.body,null,2):g.response.body}catch(t){e=String(g.response.body)}navigator.clipboard.writeText(e)}),t.classList.add("active")}o.onclick=()=>{r=!r,i()},s.subscribe(i),i()}(o);const q=e=>{const t=!!e.token,r=o.querySelector(".mfm-header"),s=o.querySelector(".mfm-tabs-container"),i=o.querySelector(".mfm-token-form");r&&(r.style.display=t?"flex":"none"),s&&(s.style.display=t?"block":"none"),i&&(i.style.display=t?"none":"block"),o.classList.toggle("hidden",!e.isOpen),n.classList.toggle("hidden",e.isOpen)};n.querySelector(".mfm-toggle-reload").onclick=e=>{e.stopPropagation(),"true"!==n.dataset.moved&&(s.state.token?d.reloadMappings():s.update("isOpen",!0))},n.querySelector(".mfm-toggle-logo").onclick=e=>{e.stopPropagation(),"true"!==n.dataset.moved&&(s.state.token?d.toggleWidget():s.update("isOpen",!0))},window.addEventListener("click",(e=>{e.target.closest(".mfm-dropdown")||document.querySelectorAll(".mfm-dropdown-content.show").forEach((e=>e.classList.remove("show")))})),s.subscribe(q),q(s.state)},o=()=>e||document.body;return o()?n(o()):"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>n(o()))):document.body&&n(document.body),window.addEventListener("message",(e=>{const{type:t,payload:n}=e.data;if(t&&t.startsWith("MFM_"))switch(t.startsWith("MFM_LOG_")||i.info(`Incoming PostMessage: ${t}`,n),t){case"MFM_RES_MAPPINGS":if(n.token&&!s.state.token&&(i.info("Setting token from incoming MFM_RES_MAPPINGS"),s.update("token",n.token),localStorage.setItem("MFM_TOKEN",n.token)),s.set("mappings",n),s.update("isMappingsLoading",!1),s.state.isTokenValidating){const e=localStorage.getItem("MFM_TOKEN_TEMP")||s.state.token;e&&(s.update("token",e),localStorage.setItem("MFM_TOKEN",e),localStorage.removeItem("MFM_TOKEN_TEMP")),s.update("isTokenValidating",!1),s.update("isTokenLoading",!1),d.flushQueue()}const e=document.querySelector("#mfm-reload-header");e&&(e.innerHTML=E,e.style.pointerEvents="auto"),k("Mappings reloaded successfully");break;case"MFM_REQ":i.info("Captured Request",n),d.addRequest(n);break;case"MFM_RES":i.info("Captured Response",n),d.addRequest(n);break;case"MFM_TOKEN_ERROR":case"MFM_TOKEN_API_FAILED":i.error(`Token Error (${t})`,n),s.update("ui.tokenError",(null==n?void 0:n.message)||"Something went wrong"),s.update("isTokenLoading",!1),s.update("isMappingsLoading",!1),s.update("isTokenValidating",!1),"MFM_TOKEN_ERROR"===t&&(s.update("token",null),d.clearQueue(),localStorage.removeItem("MFM_TOKEN"),localStorage.removeItem("MFM_TOKEN_TEMP"));const o=document.querySelector("#mfm-reload-header");o&&(o.innerHTML=E,o.style.pointerEvents="auto"),k((null==n?void 0:n.message)||"Request failed","error")}})),{destroy(){t&&t.remove()},actions:d}}const q={run:M,initMFM:M,actions:d};window.MFM=q}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,r=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),o=t.split("/");if(n.length!==o.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==o[e]&&":any"!==t)return!1}return!0};let i=[];function a(e){i=e}function d(){return i}function l(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,o=n(e);for(const a of i)if(r(a.apiMethod)===r(t)){const r=n(a.apiEndpoint);if(r===o||s(r,o)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${a.apiEndpoint}`);const n={url:e,method:a.apiMethod,_ack:a._ack||null};return a._ri_&&(n._ri_=a._ri_),n}}return null}const c="JAVASCRIPT",m="CHROME_EXTENSION",u="mfmver",p="mockforme",f="7.0.0",h="https://api.mockforme.com",g=`${h}/mockforme`,b=`${h}/gateway/3f4eae522b`;let y=null,v=null,x=null,w=[];function k({_o:e,mk:t,_mck:n,_rules:o}){y=e,v=t,x=n,w=o}function E(){return w}function M(){return`${g}/${y}/${v}`}function q(){return x}const _=e=>{try{return new URL(e,window.location.origin).toString()}catch{return e}},R=function(e,t,n){const r=o();var s;function i(){if(4==s.readyState)if(s.status.toString().match(/^20[0-9]$/)){var e=function(){var e=s.getResponseHeader("Content-Type"),t=s.responseText;if(e){var n=e.split(";");try{return"application/json"===n[0]?JSON.parse(t):t}catch(e){throw"Unable to convert response header"}}}();t.call(this,e,s)}else n.call(this,s.responseText,s)}function a(e,t){var n=[];for(var o in e)if(e.hasOwnProperty(o)){var r=t?t+"["+o+"]":o,s=e[o];n.push("object"==typeof s?a(s,r):encodeURIComponent(r)+"="+encodeURIComponent(s))}return n.join("&")}return r||(window.XMLHttpRequest?s=new XMLHttpRequest:window.ActiveXObject&&(s=new ActiveXObject("Microsoft.XMLHTTP"))),{request:function(){if(!r){if(window.XMLHttpRequest)s.onload=i;else{if(!window.ActiveXObject)throw"unable to process ajax";s.onreadystatechange=i}var t=a(e.params);if("get"==e.method.toLowerCase()&&"object"==typeof e.params){if(-1==e.url.indexOf("?"))e.url+="?";else{var n=e.url.split("?");n[1]&&n[1].split("=")[1]&&(e.url+="&")}e.url+=t}e.hasOwnProperty("async")||(e.async=!0),s.open(e.method,e.url,e.async),e.headers&&function(e){for(let t in e)s.setRequestHeader(t,e[t])}(e.headers),s.send(t)}}}};function T({di:e,iv:t},n){var o;const r=function(e,t){const n=t.length;return e.split("").map(((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%n)))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),n+t);return JSON.parse(r)}function S(e,t,n,o){fetch(b,{method:"GET",headers:{[p]:e,[u]:f,"x-mfm-adaptor":t}}).then((e=>{if(!e.ok)throw e;return e.json()})).then((e=>{if(e){const{di:t,iv:o,_o:r,_mck:s,mk:i,r:d}=e,l=T({di:t,iv:o},r);k({_o:r,mk:i,_mck:s,_rules:d}),l&&(a(l),n(l,{_o:r,mk:i,_mck:s,_rules:d}))}})).catch((e=>{console.error("Error in loading mocked APIs:",e),o(e)}))}const L="MFM_TOKEN_ERROR",C=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem("MFM_TOKEN"):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.interceptionEnabled="undefined"==typeof localStorage||"false"!==localStorage.getItem("MFM_INTERCEPTION_ENABLED"),this.setupMessageListeners())}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",(e=>{const{type:t,payload:n}=e.data||{};if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case"MFM_REQ_MAPPINGS":this.refreshMappings();break;case"MFM_SUBMIT_TOKEN":this.handleTokenSubmission(n?.token);break;case"MFM_DEL_CLIENT_TOKEN":this.handleTokenDeletion();break;case"MFM_TOGGLE_INTERCEPTION":this.interceptionEnabled=!!n?.enabled,"undefined"!=typeof localStorage&&localStorage.setItem("MFM_INTERCEPTION_ENABLED",this.interceptionEnabled)}}))}init(){"undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,133)).then((()=>{window.MFM&&"function"==typeof window.MFM.run&&window.MFM.run()})).catch((e=>{console.error("[MockForMe] Failed to load mfm-widget",e)})),console.log("[MockForMe] Widget initialized"),this.token&&this.refreshMappings())}setWidgetKey(e){this.widgetKey=e,this.init()}checkVisibility(){return!this.widgetKey||"undefined"!=typeof localStorage&&localStorage.getItem("widgetKey")===this.widgetKey}handleTokenSubmission(e){e&&(this.token=e,this.isAuthenticated=!0,"undefined"!=typeof localStorage&&localStorage.setItem("MFM_TOKEN",e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&localStorage.removeItem("MFM_TOKEN"),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}refreshMappings(){this.token&&S(this.token,"JAVASCRIPT",((e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.onAuthSuccess(this.token,this.mappings,t),this.updateMappings(this.mappings,t)}),(e=>{console.error("[MockForMe] Failed to fetch mappings",e),e instanceof Response&&e.headers&&"true"===e.headers.get("mfm-invalid-token")&&this.sendMessage(L,{message:"Unauthorized: Invalid token"}),this.updateMappings([],{_rules:[]})}))}updateMappings(e,t){this.sendMessage("MFM_RES_MAPPINGS",{apis:e.map((e=>({method:e.apiMethod,url:e.apiEndpoint}))),rules:(t?._rules||[]).map((e=>{const t=e.rule||e,n=t.timingAction?.activeAction||"MODIFY";let o="";if(t.conditions&&t.conditions.length>0){const e=t.conditions[0];o=`${e.type} ${e.operator} ${e.value}`,t.conditions.length>1&&(o+=` (+${t.conditions.length-1} more)`)}return{ruleName:t.ruleName||e.ruleName||e._id||"Unnamed Rule",type:n,condition:o,timingAction:t.timingAction,modificationActions:t.modificationActions}}))})}addRequest(e,t){if(!this.interceptionEnabled)return;const n=e=>{if(!e)return{};let t={};return"string"==typeof e?e.split("\r\n").forEach((e=>{const n=e.split(": "),o=n.shift();o&&(t[o]=n.join(": "))})):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce(((e,n)=>(e[n.toLowerCase()]=t[n],e)),{})},o={requestId:t.requestId||Math.random().toString(36).substring(7),interceptionType:"mocked"===e?"MOCKED":"OTHER",request:{method:t.method,url:t.url,headers:n(t.requestHeaders||t.headers),body:t.requestBody||t.body},response:t.pending?null:{statusCode:t.status,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString()},rule:t.rule};if(t.pending)this.sendMessage("MFM_REQ",o);else if(this.sendMessage("MFM_RES",o),o.response&&o.response.headers){const e=o.response.headers["mfm-invalid-token"];if("true"===e||!0===e){const{message:e}=t.responseBody;console.warn("[MockForMe] Invalid token detected from response headers"),this.sendMessage(L,{message:e||"Unauthorized: Invalid token detected from response headers"}),this.handleTokenDeletion()}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};class O{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:o,queryParams:r,body:s}=e,i="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:d,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,i).pathname}catch{t=n}break;case"QUERY_PARAM":if(r&&void 0!==r[d])t=String(r[d]);else try{t=new URL(n,i).searchParams.get(d)||""}catch{t=""}break;case"REQUEST_BODY":if(d){if("object"==typeof s&&null!==s)t=void 0!==s[d]?String(s[d]):"";else if("string"==typeof s)try{const e=JSON.parse(s);t=void 0!==e[d]?String(e[d]):""}catch{t=""}}else t="object"==typeof s?JSON.stringify(s):String(s||"");break;case"REQUEST_HEADER":if(d){const e=d?.toLowerCase();if(t="",o){const n=Object.keys(o).find((t=>t.toLowerCase()===e));t=n?String(o[n]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const o=t?.toLowerCase(),r=String(e),s=String(n);switch(o){case"contains":return r.includes(s);case"equal":case"equals":return r===s;case"regexp":try{let e=s;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),o=e.slice(t+1);return new RegExp(n,o).test(r)}return new RegExp(e).test(r)}catch{return!1}default:return!1}}}class I{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,o=n?.[t];if(!o)return{type:"passThrough",delay:0};const r={type:"passThrough",delay:0},s=Number(o.value||0);switch(t){case"delay":r.delay=s,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)));break;case"redirect":case"delay_and_redirect":r.type="redirect",r.delay=s,r.redirectUrl=o.redirectUrl,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)));break;case"delay_and_timeout":r.type="timeout",r.delay=s,r.delay>0&&await new Promise((e=>setTimeout(e,1e3*r.delay)))}return r}}class A{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:o,headers:r,queryParams:s,body:i}={...e};r&&(r={...r}),s&&(s={...s});const{modifyQueryParams:a,modifyRequestBody:d,modifyRequestHeaders:l}=t;if(a?.enabled)try{const e=new URL(n,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(a.remove)&&a.remove.forEach((t=>{e.searchParams.delete(t),s&&delete s[t]})),Array.isArray(a.add)&&a.add.forEach((({key:t,value:n})=>{e.searchParams.set(t,n),s&&(s[t]=n)})),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(r={...r},Array.isArray(l.remove)&&l.remove.forEach((e=>{const t=e.toLowerCase(),n=Object.keys(r).find((e=>e.toLowerCase()===t));n&&delete r[n]})),Array.isArray(l.add)&&l.add.forEach((({key:e,value:t})=>{r[e]=t})));const c=String(o||"GET").toUpperCase(),m="GET"===c||"HEAD"===c;if(d?.enabled&&!m)try{let e=null;if("string"==typeof i)try{e=JSON.parse(i)}catch{e={}}else if("object"==typeof i&&null!==i)try{e=JSON.parse(JSON.stringify(i))}catch{e={...i}}else(Array.isArray(d.add)&&d.add.length>0||Array.isArray(d.update)&&d.update.length>0)&&(e={});e&&(Array.isArray(d.remove)&&d.remove.forEach((t=>delete e[t])),Array.isArray(d.add)&&d.add.forEach((({key:t,value:n})=>e[t]=n)),Array.isArray(d.update)&&d.update.forEach((({key:t,value:n})=>e[t]=n)),i=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:r,queryParams:s,body:i}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,o={...e};return Array.isArray(n.remove)&&n.remove.forEach((e=>{const t=e.toLowerCase(),n=Object.keys(o).find((e=>e.toLowerCase()===t));n&&delete o[n]})),Array.isArray(n.add)&&n.add.forEach((({key:e,value:t})=>{o[e]=t})),o}}class j{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const n of t){const t=n.rule||n;if(t.conditions&&Array.isArray(t.conditions)&&O.match(e,t.conditions)){const e=t.timingAction?.activeAction||"";return{action:e,config:t.timingAction?.actions?.[e]||{},rule:t}}}return null}static async apply(e,t){if(!e)return null;const n=e.rule||e,o=A.applyRequestModifications(t,n.modificationActions);return{...await I.apply(n.timingAction),modifiedRequest:o,rule:n}}static applyResponseModifications(e,t){return A.applyResponseModifications(e,t)}}class N{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:s=async(e,t,n,o,r)=>null,onMockMatch:i=async(e,t,n,o,r)=>null,onOtherRequest:a=async(e,t,n,o)=>null,isEnabled:d=()=>!0}){t&&(e.fetch=async function(e,l={}){if(!d())return t(e,l);let c;try{const t="string"==typeof e?e:e.url,n=String(l.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),o=Math.random().toString(36).substring(7);c={url:t,method:n,headers:l.headers||(e instanceof Request?e.headers:{}),body:l.body||(e instanceof Request?"{binary/stream}":null),requestId:o,queryParams:N.getQueryParams(t)},r(c)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,l)}try{const r=n(),d=j.match(c,r);if(d){const n=await s(d,c,e,l,t);if(n)return n}const m=o(c);if(m){const n=await i(m,c,e,l,t);if(n)return n}const u=await a(c,e,l,t);if(u)return u}catch(e){if(e.message.includes("timed out")||"AbortError"===e.name||e.message.includes("rules"))throw e;throw console.warn("[MockForMe] Interceptor Hook Error:",e),e}return t(e,l)})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}class P{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:o=e=>null,onBeforeRequest:r=e=>{},onRuleMatch:s=(e,t,n,o)=>{o.call(n.proxy,t.body)},onMockMatch:i=(e,t,n,o)=>{o.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:d=()=>!0}){t&&(e.XMLHttpRequest=class{constructor(){return this._xhr=new t,this._headers={},this._method=null,this._url=null,this._body=null,this._requestId=null,this._startTime=null,this._captured=!1,this._isMocked=!1,this.proxy=new Proxy(this,{get:(e,t)=>{if(t in e)return e[t];const n=e._xhr[t];return"function"==typeof n?n.bind(e._xhr):n},set:(e,t,n)=>t in e?(e[t]=n,!0):(e._xhr[t]=n,!0)}),this.proxy}_capture(e,t,n,o={}){if(this._captured)return;this._captured=!0;const r=e=>{const t=`on${e}`;(this[t]||this._xhr[t])?.(),this._xhr.dispatchEvent(new Event(e))};if("Aborted"!==e)try{Object.defineProperty(this.proxy,"responseText",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"response",{value:t,configurable:!0}),Object.defineProperty(this.proxy,"status",{value:Number(e)||0,configurable:!0}),Object.defineProperty(this.proxy,"statusText",{value:200==e?"OK":"",configurable:!0})}catch(e){console.warn("[MockForMe] Error setting XHR props",e)}Object.defineProperty(this.proxy,"readyState",{value:4,configurable:!0}),r("readystatechange"),"Aborted"===e||o.aborted?r("abort"):0===e||"Error"===e||o.error?r("error"):"Timeout"===e||o.timeout?r("timeout"):r("load")}open(e,t,n=!0,o=null,r=null){this._method=(e||"").toUpperCase().trim();try{this._url=new URL(t,"undefined"!=typeof window?window.location.href:"http://localhost").toString()}catch(e){this._url=t}return this._xhr.open(e,t,n,o,r)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!d())return this._xhr.send(e);this._body=e,this._requestId=Math.random().toString(36).substring(7),this._startTime=Date.now();const t={url:this._url,method:this._method,headers:this._headers,body:this._body,requestId:this._requestId,startTime:this._startTime,queryParams:P.getQueryParams(this._url)};r(t);const l=n(),c=j.match(t,l),m=e=>this._xhr.send(e);if(c)return this._isMocked=!0,s(c,t,this,m);const u=o(t);return u?(this._isMocked=!0,i(u,t,this,m)):(this._isMocked=!1,a(t,this,m))}})}static getQueryParams(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e,t).searchParams;return Object.fromEntries(n.entries())}catch{return{}}}}const $=(e,t=null,n=c)=>{if(o())return;let r="string"==typeof e?e:e?.token,s="object"==typeof e?e?.widgetKey:null;if(s?C.setWidgetKey(s):C.init(),n===c)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),C.token=r,C.isAuthenticated=!0),!r&&C.token&&(r=C.token),C.onAuthSuccess=(e,t,n)=>{a(t),k(n),C.updateMappings(t,n)}}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:i=[],_o:h,mk:g,_mck:y,_rules:v=[]}=t;return a(i),k({_o:h,mk:g,_mck:y,_rules:v}),{run:(e,t=()=>{})=>{!function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>C.token||e;N.apply({isEnabled:()=>C.interceptionEnabled,ruleProvider:()=>E(),mappingProvider:e=>{try{return l(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o,r)=>{const s=t.requestId||Math.random().toString(36).substring(7),i=Date.now();C.addRequest("mocked",{...t,requestId:s,pending:!0,startTime:i,rule:e});const a=await j.apply(e,t),{modifiedRequest:d,type:l,delay:c,redirectUrl:m}=a;if("timeout"!==l&&C.addRequest("mocked",{...d,requestId:s,pending:!0,startTime:i,rule:e}),"timeout"===l){const t=Date.now()-i;throw C.addRequest("mocked",{...d,requestId:s,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!m)throw new Error("rules: Redirect missing URL");let u="redirect"===l?m:d.url,p={...o};d.headers&&(p.headers=d.headers),d.body&&(p.body=d.body);let f=null;if("redirect"===l){f=Math.random().toString(36).substring(7);const e={url:m,method:d.method,headers:p.headers||{},body:p.body,requestId:f,queryParams:N.getQueryParams(m),requestHeaders:p.headers||{},requestBody:p.body,pending:!0,startTime:Date.now()};C.addRequest("mocked",e)}return r(u,p).then((async e=>{const t=Date.now()-i;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=j.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&f){const t=e.clone(),o=t.headers.get("content-type")||"",r=Date.now()-i;try{let s;s=o.includes("application/json")?await t.json():await t.text(),C.addRequest("mocked",{url:m,method:d.method,requestId:f,status:e.status,pending:!1,duration:r,responseHeaders:n,responseBody:s,requestHeaders:p.headers||{},requestBody:p.body})}catch(t){C.addRequest("mocked",{url:m,method:d.method,requestId:f,status:e.status,pending:!1,duration:r,responseHeaders:n,requestHeaders:p.headers||{},requestBody:p.body})}}return C.addRequest("mocked",{...d,requestId:s,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e})).catch((e=>{const t=Date.now()-i,n="AbortError"===e.name||e.message.includes("aborted");if(C.addRequest("mocked",{...d,requestId:s,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&f&&C.addRequest("mocked",{url:m,method:d.method,requestId:f,status:n?"Aborted":0,pending:!1,duration:t,error:!n}),"redirect"===l){const t=e.message||"Redirect failed";if(!t.includes("rules"))throw new Error(`rules: Redirect failed - ${t}`)}throw e}))},onMockMatch:async(e,o,r,s,i)=>{const a=o.requestId||Math.random().toString(36).substring(7),d=Date.now();C.addRequest("mocked",{...o,requestId:a,pending:!0,startTime:d});const l=n(),c=new URL(o.url,window.location.origin).search;let h=`${M()}${e.url}${c}`,g={[p]:l,[u]:f,"x-mfm-adaptor":t};const b=q();b&&e._ack&&(g["x-mfm-key"]=`${b}-${e._ack}`),e?._ri_&&(g._ri_=e._ri_);const y=r instanceof Request?r.headers:s.headers,v=new Headers(y||{});Object.entries(g).forEach((([e,t])=>v.set(e,t))),v.set("x-mfm-internal","true");let x=s.body;if(!x&&r instanceof Request){const e=r.clone();"GET"!==e.method&&"HEAD"!==e.method&&(x=await e.text())}const w={method:o.method,headers:v,credentials:r instanceof Request&&r.credentials||s.credentials||"include",mode:r instanceof Request&&r.mode||s.mode||"cors"};return t===m?(({actualUrl:e,url:t,method:n,headers:o,body:r,credentials:s,mode:i,rule:a})=>{const d=`${Date.now()}-${Math.random()}`,l=_(t);return new Promise(((t,c)=>{window.addEventListener("message",(function e(n){if(n.source!==window)return;const o=n.data;if("INTERCEPTED_RESPONSE"===o?.type&&o?.requestId===d){if(window.removeEventListener("message",e),o?.response?.error)return c(new Error(o.response.message));const{status:n,headers:r,body:s}=o.response,i=new Response(s,{status:n,headers:r});i._rawHeaders=r,t(i)}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:d,payload:{actualUrl:e,url:l,method:n,headers:o,body:r,credentials:s,mode:i,rule:a}},"*")}))})({actualUrl:o.url,url:h,method:o.method,headers:Object.fromEntries(v.entries()),body:x,credentials:w.credentials,mode:w.mode}).then((e=>(e.clone().text().then((t=>{const n=Date.now()-d,r=e._rawHeaders||Object.fromEntries(e.headers.entries());C.addRequest("mocked",{...o,requestId:a,status:e.status,responseHeaders:r,responseBody:t,pending:!1,duration:n})})),e))):(x&&(w.body=x),i(h,w).then((async e=>{const t=e.clone(),n=t.headers.get("content-type")||"",r=Date.now()-d,s=n=>(C.addRequest("mocked",{...o,requestId:a,status:e.status,responseHeaders:Object.fromEntries(t.headers.entries()),responseBody:n,pending:!1,duration:r}),new Response("string"==typeof n?n:JSON.stringify(n),{status:e.status,headers:t.headers}));return n.includes("application/json")?t.json().then(s):t.text().then(s)})).catch((e=>{const t=Date.now()-d;return C.addRequest("mocked",{...o,requestId:a,status:0,pending:!1,duration:t}),i(r,s)})))},onOtherRequest:async(e,t,n,o)=>{const r=n?.headers||(t instanceof Request?t.headers:{});let s=!1;r instanceof Headers?s="true"===r.get("x-mfm-internal"):"object"==typeof r&&(s="true"===r["x-mfm-internal"]);const i=M();if(e.url.startsWith(i)&&(s=!0),"OPTIONS"===e.method||s)return o(t,n);const a=e.requestId,d=Date.now();return C.addRequest("other",{...e,requestId:a,pending:!0,startTime:d}),o(t,n).then((async t=>{const n=t.clone(),o=Date.now()-d;try{const r=await n.text();C.addRequest("other",{...e,requestId:a,status:t.status,responseHeaders:Object.fromEntries(t.headers.entries()),responseBody:r,pending:!1,duration:o})}catch(e){}return t})).catch((t=>{const n=Date.now()-d,o="AbortError"===t.name||t.message.includes("aborted"),r="TimeoutError"===t.name||t.message.includes("timed out");throw C.addRequest("other",{...e,requestId:a,status:o?"Aborted":r?"Timeout":"Error",pending:!1,duration:n,aborted:o,timeout:r,error:!o&&!r}),t}))}}),P.apply({isEnabled:()=>C.interceptionEnabled,ruleProvider:()=>E(),mappingProvider:e=>{try{return l(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,o)=>{const r=t.requestId,s=Date.now();C.addRequest("mocked",{...t,requestId:r,pending:!0,startTime:s,rule:e});const i=await j.apply(e,t),{modifiedRequest:a,type:d,redirectUrl:l}=i;"timeout"!==d&&C.addRequest("mocked",{...a,requestId:r,pending:!0,startTime:s,rule:e});let c=null;if("redirect"===d){c=Math.random().toString(36).substring(7);const e={url:l,method:a.method,headers:a.headers||{},body:a.body,requestId:c,queryParams:(()=>{try{const e="undefined"!=typeof window?window.location.origin:"http://localhost",t=new URL(l,e).searchParams;return Object.fromEntries(t.entries())}catch{return{}}})(),requestHeaders:a.headers||{},requestBody:a.body,pending:!0,startTime:Date.now()};C.addRequest("mocked",e)}const m=(e,t,o,m={})=>{const u=Date.now()-s;if(i.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof o?Object.fromEntries(o.split("\r\n").filter((e=>e)).map((e=>e.split(": ")))):o;e=j.applyResponseModifications(e,i.rule.modificationActions),o=e}C.addRequest("mocked",{...a,requestId:r,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,rule:i.rule,...m}),"redirect"===d&&c&&C.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:o,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...m}),n._capture(e,t,o,m)};if("timeout"===d)return m("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===d){if(!l)return void m(0,"Redirect missing URL",{},{error:!0});n._xhr.open(a.method,l,!0)}else a.url!==t.url&&n._xhr.open(a.method,a.url,!0);a.headers&&Object.entries(a.headers).forEach((([e,t])=>{try{n._xhr.setRequestHeader(e,t)}catch(e){}})),n._xhr.addEventListener("abort",(()=>m("Aborted","Aborted",{},{aborted:!0})),{once:!0}),n._xhr.addEventListener("error",(()=>m(0,"Error",{},{error:!0})),{once:!0}),n._xhr.addEventListener("timeout",(()=>m("Timeout","Timeout",{},{timeout:!0})),{once:!0}),n._xhr.addEventListener("load",(()=>m(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders())),{once:!0}),o(a.body)},onMockMatch:(e,o,r,s)=>{const i=o.requestId,a=Date.now(),d=n(),l=new URL(o.url,window.location.origin);let c=`${M()}${e.url}${l.search}`,h={[p]:d,[u]:f,"x-mfm-adaptor":t};const g=q();g&&e._ack&&(h["x-mfm-key"]=`${g}-${e._ack}`),e?._ri_&&(h._ri_=e._ri_),h["x-mfm-internal"]="true";const b={...o.headers,...h};C.addRequest("mocked",{...o,requestId:i,pending:!0,startTime:a});const y=(e,t,n,s={})=>{const d=Date.now()-a;C.addRequest("mocked",{...o,requestId:i,status:e,responseBody:t,responseHeaders:n,pending:!1,duration:d,...s}),r._capture(e,t,n,s)};if(r._xhr.addEventListener("abort",(()=>y("Aborted","Aborted",{},{aborted:!0})),{once:!0}),r._xhr.addEventListener("error",(()=>y(0,"Error",{},{error:!0})),{once:!0}),r._xhr.addEventListener("timeout",(()=>y("Timeout","Timeout",{},{timeout:!0})),{once:!0}),t===m)(({actualUrl:e,url:t,method:n,headers:o,body:r,onSuccess:s,onError:i,rule:a})=>{const d=`${Date.now()}-${Math.random()}`,l=_(t);window.addEventListener("message",(function e(t){if(t.source!==window)return;const n=t.data;if("INTERCEPTED_RESPONSE"===n.type&&n.requestId===d){if(window.removeEventListener("message",e),n.response?.error)return i?.(n.response.message);const{body:t,status:o,headers:r}=n.response;s?.({body:t,status:o,headers:r})}})),window.postMessage({type:"REQUEST_INTERCEPTED",requestId:d,payload:{actualUrl:e,url:l,method:n,headers:o,body:r,credentials:"same-origin",mode:"cors",rule:a}},"*")})({actualUrl:o.url,url:c,method:o.method,headers:b,body:o.body,onSuccess:({body:e,status:t,headers:n})=>y(t,e,n||{}),onError:e=>y(0,e.message||"XHR Error",{},{error:!0})});else{const e=new window.XMLHttpRequest;e.open(o.method,c,!0);for(const t in b)e.setRequestHeader(t,b[t]);e.withCredentials=r.proxy.withCredentials,e.onload=()=>y(e.status,e.responseText,e.getAllResponseHeaders()),e.onerror=()=>y(0,"Network Error",{},{error:!0}),e.ontimeout=()=>y("Timeout","Request timed out",{},{timeout:!0}),e.send(o.body)}},onOtherRequest:(e,t,n)=>{const o="true"===e.headers?.["x-mfm-internal"],r=M(),s=e.url.startsWith(r);if("OPTIONS"===e.method||o||s)return n(e.body);const i=Date.now();C.addRequest("other",{...e,pending:!0,startTime:i});const a=(n,o,r,s={})=>{const a=Date.now()-i;C.addRequest("other",{...e,status:n,responseBody:o,responseHeaders:r,pending:!1,duration:a,...s}),t._capture(n,o,r,s)};t._xhr.addEventListener("abort",(()=>a("Aborted","Aborted",{},{aborted:!0})),{once:!0}),t._xhr.addEventListener("error",(()=>a(0,"Error",{},{error:!0})),{once:!0}),t._xhr.addEventListener("timeout",(()=>a("Timeout","Timeout",{},{timeout:!0})),{once:!0}),t._xhr.addEventListener("load",(()=>a(t._xhr.status,t._xhr.responseText,t._xhr.getAllResponseHeaders())),{once:!0}),n(e.body)}})}(r,n),h&&g?(C.mappings=i,C.rules=v,e?.(i,{_o:h,mk:g,_mck:y,_rules:v})):r&&function(t,n,o,r){R({method:"get",url:b,async:!1,headers:{[p]:t,[u]:f,"x-mfm-adaptor":n}},(t=>{if(t)try{const{di:r,iv:s,_o:i,_mck:d,mk:l,r:c}=t,m=T({di:r,iv:s},i);k({_o:i,mk:l,_mck:d,_rules:c}),m&&(a(m),n=m,o={_o:i,mk:l,_mck:d,_rules:c},C.updateMappings(n,o),e?.(n,o))}catch(e){return void r(new Error("Unable to fetch mocked apis"))}var n,o}),(e=>{console.log("Error in loading mocked apis"),r(e)})).request()}(r,n,0,t)},checkIfApiToBeMocked:l,getMappings:d,doFetchMappings:(e,t)=>{S(r||C.token,n,((t,n)=>{C.updateMappings(t,n),e?.(t,n)}),t)},recheckWidgetVisibility:()=>{C.init()}}},H=o();H||(globalThis.mockforme=$);let D=$;H&&(D=e=>({run:()=>{}}));const F=D;export{F as mockforme};